content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def shell_Green_grid_Arnoldi_Mmn_step(n,k, invchi, rgrid,rsqrgrid,rdiffgrid, RgMgrid, ImMgrid, unitMvecs, Gmat, plotVectors=False): """ this method does one more Arnoldi step, given existing Arnoldi vectors in unitMvecs the last entry in unitMvecs is G*unitMvecs[-2] without orthogonalization and normalizati...
2c07c08a1ed60a001f7dde52dd9c2db4adb704af
3,606,631
def prepare_data(data, variables, bg_vars, nice_names, labels, nothing_string): """Create data for a distplot. Args: data (pd.DataFrame): The dataset that contains variable and background_variables. variables (list): List of variables whose distributions are visualized. Can be categ...
79ae6e8c08e59058063705ddea0d331ea2f1eb97
3,606,632
def run_rod(smooth = 0.001, dirname = 'task1/val/'): """ use_set: validation or test """ #if use_set == 'val': # dirname = 'task1/val/' #elif use_set == 'test': # dirname = 'task1/test/' #else: # dirname = '' # read ground truth all_sen, features, labels, docs = uti...
028248b84b5aaaebbd78d3c09023c4153281f387
3,606,633
def on_leafs(y_leafs, grouping_name: str, is_leaf_list: bool) -> list: """ Parse all the 'leaf' or 'leaf-list' elements Args: y_leafs: reference to all 'leaf' elements grouping_name: if YANG entity contain 'uses', this argument represent the...
cde3ee003c180370af0ea506c5dba05fe0e8e980
3,606,634
def preprocessor(accepts, exports, flag=None): """Decorator to add a new preprocessor""" def decorator(f): preprocessors.append((accepts, exports, flag, f)) return f return decorator
c579934724612c8788ad9e50acb529fae696977d
3,606,635
import uuid def build_request_body(method, params): """Build a JSON-RPC request body based on the parameters given.""" data = { "jsonrpc": "2.0", "method": method, "params": params, "id": str(uuid.uuid4()) } return data
372df70bd17e78f01de5f0e537988072ac9716cc
3,606,636
import wave import json def recognize(model, wav_file_path): """ Speech to text recognizer for russian speech using vosk models path to russian vosk model should be configured in config.py file """ with wave.open(wav_file_path, "rb") as wf: if wf.getnchannels() != 1 or wf.getsampwidth() !...
c51ab23bd3f170e4dd48c4f2b1b282b0320b14ba
3,606,637
def read_config(fname): """ Opens and reads in the config file in its most raw form. Creates a dictionary of dictionaries that contain the string result Args: fname: Real path to the config file to be opened Returns: config: dict of dicts containing the info in a config file """...
88248fc9b17f1d551bbfd0602757fddd85c3d67f
3,606,638
import hashlib def get_content_md5(fileobj): """Get Content-MD5 value All content will be read from the current position to the end of the file. The file will be left open with its seek position at the end of the file. :param fileobj: A file-like object. :returns: RFC-1864-compliant Content-...
f7612ad1302dc7c9ecac6deeac4dcb9acdc9d62c
3,606,639
def cosine_similarity_loss(x1, x2, labels): """ cosine 相似度损失 Examples: # >>> logits = torch.randn(5, 5).clamp(min=_EPSILON) # 负对数似然的输入需要值大于 0 # >>> labels = torch.arange(5) # >>> onehot_labels = F.one_hot(labels) # # # 与官方结果比较 # >>> my_ret = negative_log_likelih...
ad9e32d2496e77d42e87bafc3550f727a39edd51
3,606,640
def line_count(text_field: bytes, is_double_height: bool) -> int: """Returns the number of lines separated by one or more newline characters in the TF field `text_field` """ count = 0 was_eol = False for c in text_field: if _is_newline_code(c): if is_double_height: if was_eol: w...
4ebf186b08b1591e81a7d9493e50b071e7a9d1c9
3,606,641
def part1(input_data): """ >>> part1(["939","7,13,x,x,59,x,31,19"]) 295 """ timestamp = int(input_data[0]) bus_ids = input_data[1].split(',') # Ignore bus_ids with 'x' bus_ids = map(int, filter(lambda bus_id: bus_id != 'x', bus_ids)) # (id, time_to_wait) # last_busstop = timestam...
99c1928c5833f3c9773a28323f2bd2a903f626f3
3,606,643
from dronekit.mavlink import MAVConnection def connect(ip, _initialize=True, wait_ready=None, timeout=30, still_waiting_callback=default_still_waiting_callback, still_waiting_interval=1, status_printer=None, vehicle_class=None, ...
2ec36b5d7d2c766ebb1a3856ce8abc606432b3bf
3,606,644
def create(movie_id, country_id, **options): """ creates a new movie 2 country record. :param uuid.UUID movie_id: movie id. :param uuid.UUID country_id: country id. :keyword bool is_main: is main. :raises ValidationError: validation error. """ return get_component(RelatedCountriesPac...
fbe2795d0f239371a6d760a5c26778e170839eb4
3,606,645
import uuid def read_bootid(): """ Mocks read_bootid as this is a Linux-specific operation. """ return uuid.uuid4().hex
02ef132a4aa157a4c111bf8938a4a3716a9c2f29
3,606,646
def make_grid_point_weight(reference_point, MO, approach_code=1, table_code=13, title='', subtitle='', label='', superelement_adaptivity_index='') -> None: """creates a grid point weight table""" Mtt_ = MO[:3, :3] Mrr_ = MO[3:,...
20d8194c595ca51ddd1777b82c00c22c692a8df3
3,606,648
import torch def total_correlation(z, mu, logvar): """Estimate total correlation in a batch. Compute the expectation over a batch of: E_j [log(q(z(x_j))) - log(prod_l q(z(x_j)_l))] We ignore the constant as it does not matter for the minimization. The constant should be equal to (n_dims - 1) * ...
ffa518d09de672a894d088d8b9ac0a9689135bc8
3,606,649
def list_group(flatten_list, offset_list): """list_flatten的逆操作""" pos_lists = [] for offset in offset_list: pos_lists.append(flatten_list[offset[0] : offset[1]]) return pos_lists
6ae7f52d267ea682c704a4a494bdfb63f8ccf23a
3,606,650
async def get_balance(user: str) -> int: """ Returns the balance for a user. """ async with aiosqlite.connect("./balance.db") as db: db.row_factory = aiosqlite.Row await _create_if_not_exists(db, user) async with db.execute("SELECT * FROM balance WHERE username = ?", [user]) as cursor: ...
bdb48e2038be1aeb10c5f64d8fe5f60a8805eb8a
3,606,651
def get_auth0_user_key_info(is_authenticated): """Getting users permission on their first launch At the same time, also update the users_permissions table as we want to keep the users_permissions table up to date for the dashboards. """ if is_authenticated: app.logger.info( f...
b01c731bac3665636a6ce7af255bd5dc86584cf5
3,606,652
def main(*args): """Main function.""" BenchBuild.subcommand('bootstrap', BenchBuildBootstrap) BenchBuild.subcommand('config', BBConfig) BenchBuild.subcommand('container', cli.BenchBuildContainer) BenchBuild.subcommand('experiment', BBExperiment) BenchBuild.subcommand('log', BenchBuildLog) B...
0a97e7a2fda2370b2dccc03ebc6e8748cbcb6d51
3,606,653
def exporter(): """Create exporters.""" serving_input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn( features=dict( block_ids=tf.placeholder(tf.int32, [None, None]), block_mask=tf.placeholder(tf.int32, [None, None]), block_segment_ids=tf.placeholder(tf.int32, [None...
ca4effcb35d1d95d153c7a5fb8debeddd502e065
3,606,655
import numpy def normalized(vector): """ Get unit vector for a given one. :param vector: Numpy vector as coordinates in Cartesian space, or an array of such. :returns: Numpy array of the same shape and structure where all vectors are normalized. That is, each coordinate compon...
424595a59e52ed8b328a629b28dd0206c599484f
3,606,656
def getBoxesMidpoint(box): """ takes in normalized coordinates of the 800x600 screen. coordinates are xmin,ymin,xmax,ymax returns a tuple of the midpoint """ #denormalize them normalized_coord = np.array([box[0]*806,box[1]*629,box[2]*806,box[3]*629],dtype=np.float32) #offset from the origin ...
aaadb54af0a24ab52e977a8968e258c79c66e75a
3,606,657
def sample_conditional_random(generator, m, n, **kwargs): """ Sample `m * n` points from condition space completely randomly. """ return generator.condition_distribution.sample(m * n).eval()
bc50e32e47bffe10c11df02cf365c5396b722d4a
3,606,659
import pathlib def my_read_image(img_path): """ Return a loaded image according to the input path. Note that the color channels are sorted as RGB order. Args: img_path: pathlib.Path File path of an image you want to load. Returns: ndarray Loaded image sorted as RGB ord...
632f9d9954168588cb98757f7f3c0021ec538692
3,606,660
import asyncio def rpc(func): """ A decorator used to indicate an RPC. All @rpc methods if explicitly called via a request message must have node.identifier as the first argument. All @rpc methods return a 2-tuple: (node_identifier, response) The node_identifier is consumed by kademlia to u...
f54ee5897f73c6407c38716b1b15dbfa31ccbf6e
3,606,661
def low_cut_filter(x, fs, cutoff=70): """Low cut filter Parameters --------- x : array, shape(`samples`) Waveform sequence fs: array, int Sampling frequency cutoff : float, optional Cutoff frequency of low cut filter Default set to 70 [Hz] Returns ------...
2e936503e1a719575e11ec2a92147d2f85f366bc
3,606,662
import json import base64 def lambda_handler(event, context): """ Lambda Handler for Image Processing logic. """ #Load the event print("My event: {}\n".format(event)) try: event = json.loads(event['body']) except: event = event['body'] # Content image pre-pro...
7d25d12ac20fb1530423aced98c438166959a885
3,606,663
def empty_like(a, dtype=None): """ alias for empty(a.axes, dtype=a.dtype) See also -------- empty, ones_like, zeros_like, nans_like >>> a = empty([('time',[2000,2001]),('items',['a','b','c'])]) >>> b = empty_like(a) >>> b.fill(3) >>> b dimarray: 6 non-null elements (0 null) 0 /...
84fda4883556ddad085949bf145f2ee3c4ec7df2
3,606,664
import torch def fetch_optimizer(lr, wdecay, epsilon, num_steps, params): """ Create the optimizer and learning rate scheduler """ optimizer = torch.optim.AdamW(params, lr=lr, weight_decay=wdecay, eps=epsilon) scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, lr, num_steps+100, pct_start...
e6d028f4adf58c303e1e7f0cb0b5233cf4f6026c
3,606,665
import random def calc_rpn(C, img_data, width, height, resized_width, resized_height, img_length_calc_function): """(Important part!) Calculate the rpn for all anchors If feature map has shape 38x50=1900, there are 1900x9=17100 potential anchors Args: C: config img_data: augmented image data width: origi...
9510f1652342830515d8eafe7c4367e729d39c6e
3,606,667
def actionify(trip_message, vehicle_message, timestamp): """ Parses the trip update and vehicle update messages (if there is one; may be None) for a particular trip into an action log. """ # If a vehicle message is not None, the trip is already in progress. inp = vehicle_message is not None ...
591a239d2a732a5e40188324ff7b4e9986565aae
3,606,668
def closest_index(x, a): """ x: value a: array """ return np.argmin(np.abs(x - a))
0c06f75d1530f4b7f511209c4ee039f3e2ce51bb
3,606,669
def calc_darcy(pipe_diameter_m, reynolds, pipe_roughness_m): """ Calculates the Darcy friction factor [Oppelt et al., 2016]. :param pipe_diameter_m: vector containing the pipe diameter in m for each edge e in the network (e x 1) :param reynolds: vector containing the reynolds number of flows ...
b5e7b4123d1cb1b1c357ec40402ef59ddfd06740
3,606,670
def makeCube(): """ Create a Cube Credits: https://github.com/danginsburg/webgl-brain-viewer/blob/master/common/esShapes.js """ vertices = np.array( [ [-0.5, -0.5, -0.5],[-0.5, -0.5, 0.5],[0.5, -0.5, 0.5],[0.5, -0.5, -0.5], [-0.5, 0.5, -0.5],[-0.5, 0.5, 0.5],[0.5, 0.5, 0.5],[0.5, 0....
96d788d95ceba0bac1ce13677745610145aeae59
3,606,671
def try_create(model, where): """Try to create an object in the database and return it if successful. Args: model (Model): DB model class to instantiate. where (dict): Values for fields to be populated in the new instance. Returns: A new instance of the Model if creation was successf...
1044ae5b5fa23b3c1e860e75d7643565b1407e7a
3,606,673
def load_user_data(filename, **kwargs): """ Load `filename`, template in `kwargs` dynamically (kwarg values may be cloud formation json values). """ with open(filename) as fd: content = fd.read() lines = content.split("\n") # Template in parts matching {{foo}} with kwargs lines...
e40296a0fbeb4923f41a0c6883212060171c7386
3,606,674
from typing import Dict from typing import List from typing import Any def load_library_metadata() -> TypeRawLibraryCache: """ Loads the cached version of the music library. The cache is saved in the configurable cache directory. Recreates LibraryFile instances from the data. Returns: A "...
bf3c00858dc5d65c67f5399ed5388d99da9d611a
3,606,675
def get_b(i,j): """returns the in-tad coordinates""" i,j = np.sort([i,j]) bx,by=[],[] for y_ in range(i,j+1): for x_ in range(i,y_): bx.append(x_) by.append(y_) return bx,by
4e66bce44f00dd2642af460015db69ade4084ab0
3,606,676
def load_bmrbm(table_fname, resname_col, atom_col, shift_col): """Load a BMRBM table and return a dictionary.""" bmrb_dic = {} with open(table_fname, "r") as bmrb_file: for line in bmrb_file.readlines(): # Split so that the whitespaces don't matter c_shift = line.split() ...
85abb1fb714f407b91ecb9b3b04163b2badbec8f
3,606,677
def random_spd(p, eig_min, cond, rand_gen=None): """Generate a random symmetric positive definite matrix. Parameters ---------- p : int The first dimension of the array. eig_min : float Minimal eigenvalue. cond : float Condition number, defined as the ratio of the maxi...
4d4ae1bbb290e635cfbba2ab7ee824695aa07e30
3,606,678
def get_centroids(w2v_model, aspects_count): """ Clustering all word vectors with K-means and returning L2-normalizes cluster centroids; used for ABAE aspects matrix initialization """ km = MiniBatchKMeans(n_clusters=aspects_count, verbose=0, n_init=100) m = [] for k in w2v_model.w...
5a23b20e59fa6fdc993f8bc04128e5a5257172ca
3,606,680
def get_wikidata_sitelinks(source, target, titles): """ Returns a dictionary mapping from titles to wikidata ids for the articles in source missing in target """ endpoint = configuration.get_config_value('endpoints', 'wikidata') params = configuration.get_config_dict('wikidata_params') param...
c4f16eaad0c7f2bea46fa1af0ded355e56447b60
3,606,681
def stats_filter(session, datapath, threshold): """ Here we test for the first 4 critieria used in the publication, basically if a neurons passes these at a threshold of 0.05. Despite doing 4 tests a neurons transientyl firing would be excluded so this threshold was chosen inste...
29a93f938793543052d28cd588c9d3457f07a90d
3,606,682
def yp_raw_competitors(data_path): """ The file contains the list of business objects. File Type: JSON """ return f'{data_path}/yp_competitors.json'
7c33229d9cec5900a2e7b4fd868f91f576761c50
3,606,683
def compute_geodesic_from_start_to_target_vkeys(mesh, start_v_keys_list, target_v_keys_list): """ compute distances from one edges to another edge and get longest way and shortest way """ v, f = mesh.to_vertices_and_faces() v = np.array(v) f = np.array(f) vertices_start = np.array(start_v_ke...
99dc0a4206bfddc728970d92b4ff058c353d1d90
3,606,684
def typename(char): """ Return a description for the given data type code. Parameters ---------- char : str Data type code. Returns ------- out : str Description of the input data type code. See Also -------- typecodes dtype """ return _namefro...
87f31468176c715813c25877453d5c06d94c3bc9
3,606,685
def _load_pascal_annotation(filename, class2ind): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ tree = ET.parse(filename) objs = tree.findall('object') if not cfg.USE_DIFFICULT: # Exclude the samples labeled as difficult non_diff_objs...
490a1c3e0c553ce5f21f59835a07686591e9f132
3,606,686
def imitation_sonar(): """imitates a sonar object that sends either depth or temperature data""" return str(sonar_depth()) + "_" + str(sonar_temp())
2ab655b00a56167d823ef6ae52f004db0cc3b57e
3,606,687
from operator import gt def _evaluate_class(class_id, iou_threshold, recall_thresholds, class_counter, mpolicy="greedy"): """ Evaluate class. Arguments: class_id (int): index of evaluated class. iou_threshold (float): iou threshold. recall_thresholds (np.array or None): specific recal...
00033a24af59bd0f2582db3d3d5fdc46024760fd
3,606,688
def reciprocal_rank(rs): # iterator of relevance scores in rank order """ Compute reciprocal ranks for a bunch of queries: reciprocal of the rank of the first relevant item for each query (considering the first element being of 'rank 1'). Relevance is binary (nonzero is relevant). Args: rs: Iterat...
a7740625cd938983a71eab1697f0134ad9efae3a
3,606,689
def can_view_related_model(func): """ Decorator for view-methods to check permission to view the filtered items. """ def wrapper(self, request, **kwargs): permission = '{app_label}.view_{model}'.format(**kwargs) if not request.user.has_perm(permission): raise PermissionDenied...
6cb3b4fc054163b69d630f4928945cf4462b40d9
3,606,690
def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs): """Add a vertical color bar to an image plot.""" divider = axes_grid1.make_axes_locatable(im.axes) width = axes_grid1.axes_size.AxesY(im.axes, aspect=1 / aspect) pad = axes_grid1.axes_size.Fraction(pad_fraction, width) current_ax = plt.gca...
5939616ca7e1f873e7ac87d98ba3be73e830d915
3,606,691
import re def to_num(string): """Convert string to number (or None) if possible""" if type(string) != str: return string if string == "None": return None if re.match("\d+\.\d*$", string): return float(string) elif re.match("\d+$", string): return int(string) ...
79a0740e298e33198dca2d7b7fcd53700f121869
3,606,693
def button_action (date, action, value) : """ Create a button for time-tracking actions """ ''"approve", ''"deny", ''"edit again" if not date : return '' return \ '''<input type="button" value="%s" onClick=" if(submit_once()) { document.forms.edit_...
314f950d1601987d23490fc48c2f5365a39d4533
3,606,694
from typing import Callable import hmac def validate_hmac(header: str, secret: Callable): """ Validates that the HMAC signature in `header` is a valid signature for the request body """ def decorator(f): @wraps(f) def decorated_function(request: Request, *args, **kwargs): ...
bded33fefea4957dd09f0b0555a0ba1455789f54
3,606,695
def get_tidy_invocation(f, clang_tidy_binary, checks, build_path, quiet, config): """Gets a command line for clang-tidy.""" start = [clang_tidy_binary] # Show warnings in all in-project headers by default. start.append('-header-filter=src/') if checks: start.append('-...
50e95d612f08ec5762bd2d0689a4fcbe9c699a11
3,606,698
import sqlite3 def get_all_users(): """ Gets all fields from all users. """ conn = sqlite3.connect(DB_STRING) # Create a query cursor on the db connection queryCurs = conn.cursor() queryCurs.execute('SELECT * FROM Users') usersData = queryCurs.fetchall() conn.commit() conn.clos...
7d4849dafd67c8af162b06b2bf53a8c1369e56df
3,606,699
def success_checks(successf): """Return an action collection with a successing check""" au = ActionUnit("SuccessUnit", "this unit should always succeed", successf) return ActionCollection([au])
277a392c6d577965511b0c1da4230358ee418431
3,606,700
def _handle_split_region(split_roi, until_eof=False): """ Checks format against `until_eof` and creates the Roi object Args: split_roi (:py:obj:`list` or :py::obj:`tuple`): the contig, start, and stop information. until_eof (bool): whether or not to allow access to end of reference or file (whi...
61f516aebe7d92f55a3474756e644c0db29fc00b
3,606,701
def register(disp,host,info): """ Perform registration on remote server with provided info. disp must be connected dispatcher instance. Returns true or false depending on registration result. If registration fails you can get additional info from the dispatcher's owner attributes lastErrNode, lastErr and lastE...
fe7f157a61faf89e3519568b73c4f7ffd0decca5
3,606,702
from typing import Sequence import torch def reference_reduction_numpy(f, supports_keepdims=True): """Wraps a NumPy reduction operator. The wrapper function will forward dim, keepdim, mask, and identity kwargs to the wrapped function as the NumPy equivalent axis, keepdims, where, and initiak kwargs, ...
5e982f6763a72ee12885cd8c5f7a5c3cec5438ab
3,606,703
def get_tree_ctrl_image(file_path, file_type=wx.BITMAP_TYPE_PNG, width=16, height=16): """ Create an image top be used in the TreeCtrl from the provided file_path :param file_path: absolute file_path of image :type file_path: str :param file_type: specify the image format (PNG by default) :param...
a1c9b6146535e45cbfc61dc39bcbb242c485014d
3,606,704
def copy_seat_allocations(flight_id, allocations): """ Re-apply a set of seat allocations :param flight_id: ID for the flight to apply the allocations to :param allocations: A list of (seat number, passenger ID) tuples for the seat allocations to apply :return: A list of passenger IDs for passenge...
cc3a0dee1338dfc7ce91d8386e5cc31fbc18c034
3,606,705
from typing import Iterable def delete_states_rows(state_ids: Iterable[int]) -> StatementLambdaElement: """Delete states rows.""" return lambda_stmt( lambda: delete(States) .where(States.state_id.in_(state_ids)) .execution_options(synchronize_session=False) )
0538a67f78da9b624b9c0dc96b17b1c01431fcfa
3,606,706
def add_navnode(request, tree): """Add a new node""" response = {} # get the type of object object_type = request.POST['object_type'] if object_type: app_label, model_name = object_type.split('.') content_type = ContentType.objects.get(app_label=app_label, model=model_name) ...
c6da07c7762bd679d910e4002b8d782103ee45fe
3,606,707
def get_control_colors(): """ Returns control colors available in DCC :return: list(tuple(float, float, float)) """ return list()
3629fdd069353e4916ba23e172299e96e389b824
3,606,708
def parse_arg_type(arg, type): """Parses argument to corresponding type, if not already. Parameters ---------- arg: Argument type: Required type of the argument """ if arg is not None: if not isinstance(arg, type): if type == bool: arg = bool(strtobool(arg)) else: ...
ec604d47f5581fbd8a9407c349f5007bceb1eef3
3,606,709
import torch def _pre_conv(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1): """ This is a block of local computation done at the beginning of the convolution. It basically does the matrix unrolling to be able to do the convolution as a simple matrix multiplication. Because al...
be27cb73d5dd7480da477b46c3fa64a32feee744
3,606,710
def regionvit_small_224(pretrained=False, progress=True, **kwargs): """ Constructs the RegionViT-Small-224 model. .. note:: RegionViT-Small-224 model from `"RegionViT: Regional-to-Local Attention for Vision Transformers" <https://arxiv.org/pdf/2106.02689.pdf>`_. The required input size of t...
88e67bf0696ed9f93c8fb8acdea4539150ed86ae
3,606,712
def smallestPrimeFactorv2(num): """assumes num is an integer returns an int, representing the smallest prime factor of num""" for divisor in range(num): if checkPrime(divisor): if num % divisor == 0: return divisor
03be01271e97e42456a42959072cbe3f036a976c
3,606,713
def solve_milp_problem(problem, eng, path='./estimation/matlab/matfiles/'): """ call m-file with solver function of MIXED-INTEGER LINEAR PROGRAMMING PROBLEM :param problem: object of problem. It includes objective function, number of integer variables, inequality matrix, linear inequality constraint ...
50e61bba1a158d0b0a43819f83d5f3c625a53de5
3,606,714
def read_rms(filename): """Read back the RMS from one of IRAF's results files.""" with open(filename) as f: good = [] line = 'a' while line: line = f.readline() if line.startswith('# Xin and Yin fit rms:'): linesplit = line[:-1].split() ...
7d26d4aae90dbdaddc6248c5f538a57b89375fdd
3,606,715
def validateAccessList(expectedUserTypes): """ Validate that the user is logged in, use the information in the session data to determine if their username is valid and one of the expectedUserTypes, return boolean, True if valid, False if invalid """ if 'email' not in session or session['email'] ...
1f5dba60589ff7aca5f578c6e3f01837a6038d14
3,606,716
async def async_unload_entry(hass, entry): """Unload a config entry.""" LOGGER.error("async_unload_entry %s", entry.data) bridge = hass.data[DOMAIN].pop(entry.entry_id) return await bridge.async_reset()
4c5ddbaa98734317c90195254da81f5ec47cf95f
3,606,717
def get_version_info(): """Retrieve version details from current Git HEAD.""" repository = git.Repo(search_parent_directories=True) return {"author": repository.head.object.author.email, "hash": repository.head.object.hexsha}
88f6d5f9cc18386e1928c67a9a0d9b0d882af99a
3,606,718
def read_file(file_path, offset, numbytes): """reads from all chunk?""" master = f"localhost:{Config.master_loc}" with grpc.insecure_channel(master) as channel: stub = gfs_pb2_grpc.MasterServerToClientStub(channel) st = file_path + "|" + str(offset) + "|" + str(numbytes) req = gfs_pb...
6a3e1076f288daed65e3f1e6afe568356b8d24b9
3,606,719
def scoreMatrix(mms): """ Returns (rowNames, columnNames, S) where: - S is a matrix where S_{ij} represents the score delta of mutation j against read i - rowNames[i] is an identifier name for the the read i---presently we use the the row number within the cmp.h5, encoded as a s...
300786414006cb029c39b10411bb6ad3967f89a9
3,606,720
def generate_html_from_template(name, data=None): """Returns html using a template data Args:s name(str): The name of the template data(dict): Data contain Returns: (str): String containing the html """ template = get_template(name) return template.render(data)
17e3e062352d80fe613becb37c3da92e36ac7b24
3,606,721
def graph_with_labels() -> StructureGraph: """Create a Graph objects that represents the same graph as the previous fixture but with labels of different sizes """ graph = StructureGraph() # Create the nodes first in order to set their labels graph.add_node("1", width=3) graph.add_node("2", w...
61850d6249fed93fd2f4f85856e1f1caab07b1cf
3,606,722
def unique_permutations(elements): """ Get all unique permutations of a list of elements Parameters ---------- elements : list a list containing the elements """ n = len(elements) uniques = list(set(elements)) nu = len(uniques) if not elements: return [] eli...
181e454905cda19c2247a80513a0314297fa915f
3,606,723
def add_new_last_layer(base_model, nb_classes): """Add last layer to the convnet Args: base_model: keras model excluding top nb_classes: # of classes Returns: new keras model with last layer """ x = base_model.output x = GlobalAveragePooling2D()(x) x = Dense(128, acti...
bdabed131283e3f166e2d368191e4630d3717cb0
3,606,724
def SteadyBEM(Omega,pitch,V0,xdot,u_turb, nB, cone, r, chord, twist, polars, # Rotor rho=1.225,KinVisc=15.68*10**-6, # Environment nItMax=100, aTol=10**-6, bTipLoss=True, bHubLoss=False, bAIDrag=True, bTIDrag=True, bSwirl=True, relaxation=0.4, a_init=None, ap_init=None): """ Run the BEM m...
9d7270bbac166febd7602cc604b9168010f4aabf
3,606,725
from typing import List from typing import Tuple from typing import Union import logging import io def extract_answers_from_files(files: List[Tuple[bytes, str]]) -> List[Tuple[smart_forms_types.FormAnswer, List[List[Union[bytes, None]]]]]: """ Processes files, extracting their answers. The files have to b...
47caff89f13a51da0e7a5b6a2c50f3a13d3e870f
3,606,726
def dataset_pre_0_3(client): """Return paths of dataset metadata for pre 0.3.4.""" project_is_pre_0_3 = int(client.project.version) < 2 if project_is_pre_0_3: return (client.path / 'data').rglob(client.METADATA) return []
892732100f46c8ad727b91d63d8563181d7a9dbb
3,606,727
def before(min_dist=0, max_dist=INFTY): """Returns a function that computes whether a temporal interval is before another, optionally filtering the time difference to be between ``min_dist`` and ``max_dist`` (inclusive). The output function expects two temporal intervals (dicts with keys 't1' and '...
0e3d2594f5509006fd799cca81f23aee6fdf28b5
3,606,728
def calc_electronic_entropy(multiplicity): """ # Electronic entropy evaluation # Depends on multiplicity Calculates the electronic entropic contribution (J/(mol*K)) of the molecule S_elec = R(Ln(multiplicity) """ entropy = GAS_CONSTANT * (np.log(multiplicity)) return entropy
d584d318e65b41fee217f4b5883e7e02f0dbeb2a
3,606,729
import re def ExtractFromSeqWithAnno(seqWithAnno):#{{{ """ Extract information from the record seqWithAnno Return (seqID, anno, seq, seqIdentity, dgscore) ==updated 2013-03-20 """ posAnnoEnd = seqWithAnno.find('\n') anno = seqWithAnno[1:posAnnoEnd] anno = anno.lstrip('>') seqID = m...
7e88ebc27e5c69e9527154a341f9e61555df1982
3,606,730
import copy def sanitize_slicing(slice_across, slice_relative_position): """ Return standardized format for `slice_across` and `slice_relative_position`: - either `slice_across` and `slice_relative_position` are both `None` (no slicing) - or `slice_across` and `slice_relative_position` are both lists,...
1f7c3a0f70ecfc2bc66434d3acde684b499bb35c
3,606,731
def distribution( symbol="", refid="", token="", version="", filter="", **timeseries_kwargs ): """Distribution Obtain up-to-date and detailed information on all new announcements, as well as 12+ years of historical records. Updated at 5am, 10am, 8pm UTC daily https://iexcloud.io/docs/api/#distribution...
adefc3d85b687ac734c604a25a2f601a2555a322
3,606,732
def guinierplot(*args, **kwargs): """Make a Guinier plot. This is simply a wrapper around plotsascurve().""" ret=plotsascurve(*args, **kwargs) plt.xscale('power',exponent=2) plt.yscale('log') return ret
9e4ab481422a9a39d260d70cfe113adbb8124790
3,606,733
def get_rdtype(ipaddr): """ Get the record type 'A' or 'AAAA' for this ipaddr. :param ipaddr: ip address v4 or v6 (str) :return: 'A' or 'AAAA' """ af = dns.inet.af_for_address(ipaddr) return 'A' if af == dns.inet.AF_INET else 'AAAA'
b5f8ad8e34eecd97efc13638920e98b48d055a29
3,606,735
def _root_leastsq(fun, x0, args=(), jac=None, col_deriv=0, xtol=1.49012e-08, ftol=1.49012e-08, gtol=0.0, maxiter=0, eps=0.0, factor=100, diag=None, **unknown_options): """ Solve for least squares with Levenberg-Marquardt Options ------- col_deri...
5363788e4ef612797ee77fb02d73c8f94ee44e83
3,606,736
def is_dependency_valid(dep: dict, dep_dict: dict) -> bool: """ :param dep: a dependency that may or may not be valid or up-to-date :param dep_dict: a dictionary mapping dependency identifiers to their up-to-date dependency counterparts :return: a boolean indicating whether the dependency is out-of-date...
8a5a384ae94152921749d1d93cfe48ce6723e320
3,606,738
def equations(abs1, abs2, abs3, solvent): """Contains absorption constans (coef) and formulas.""" separator = "___________________________________________" coef = [[10.05, 0.97, 16.36, 2.43, 7.62, 15.39, 1.43, 35.87, 205], [9.93, 0.75, 16.23, 2.42, 7.51,15.48, 1.3, 33.12, 213], ...
126dc09f0823bf4ae1e881ef3b6284ca76e81fb3
3,606,740
def wcov(x: np.ndarray, y: np.ndarray, w: np.ndarray) -> float: """ Compute weighted covariance between two arrays. Parameters ---------- x : (N,) np.ndarray scalar array y : (N,) np.ndarray scalar array w : (N,) np.ndarray weights Returns ------- float ...
34f5393a3437240d68bbc1128f8789c4e1ad2919
3,606,741
def _url_prefix_to_short(url_pref): """Returns the commonly used short abbreviation for a few common URL prefixes.""" return _CONVENTIONAL_URL_SHORTENINGS.get(url_pref)
0c1c0a3728ad616c1eaaba2afe5b04770278aa2b
3,606,743
import threading def _open_session_with_timeout(transport): """ Helper function which encapsulates a difference between older and newer Paramiko versions. For a given paramiko.Transport object, returns a session opened from the tranport, with a timeout of OPEN_SESSION_TIMEOUT seconds. New ve...
04d66e200dfc1a3449ed38f5267e2b65f06cb4ae
3,606,744
def best_promo(order: Order) -> Decimal: """Compute the best discount available""" return max(promo(order) for promo in promos)
ad1284c18bf96a89d6e85d5877124be9ec151699
3,606,746