content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def language_is_allowed(code): """ Check a language code is valid """ return code in get_language_dict()
fc9fc5f890d56a61b5a7389dc507c256e675f9fd
3,613,469
def calculate_distance(vector1, vector2): """ Calculates Euclidean distance between two vectors. :param vector1:vector presents a face feature :param vector2:vector presents a face feature :return:disance:the Euclidean distance between vector1 and vector2. """ temp = vector1 - vector2 di...
9f3d296486a8291a35becb01fcd8d8fb6f86979c
3,613,470
import torch def classify(img, is_url=False): """ Runs the given image through the model and returns the results. """ data = ImageData([[True], [img]]) if not is_url else ImageData([[True], [img]], is_url=True) # pass image to be "tensorized" tensor_image, _, img_path = data[0] # get image tensor etc ...
8c29952940921354bce0da83a925d9b44ffecc5f
3,613,471
def rb_interleaved_execution(rb_opts: dict, shots: int): """ Create interleaved rb circuits with depolarizing error and simulate them Args: rb_opts: the options for the rb circuits shots: number of shots for each circuit simulation Returns: list: list of ...
ac80fa28dd0d0f704c20c40c77c69bfccd75ae7f
3,613,472
def nd_to_columns(data, layers, rows, columns): """ Reshapes an array from nd layout to [samples (rows*columns) x dimensions] """ if layers == 1: return np.ascontiguousarray(data.flatten()[:, np.newaxis]) else: return np.ascontiguousarray(data.transpose(1, 2, 0).reshape(rows*column...
accc6c2492a3fb4c047da6c0331137829c669b61
3,613,473
def server_error(exception): """Return True if we should retry (in this case when it's an ServerError, False otherwise""" return isinstance(exception, ServerError) or isinstance(exception, ConnectionError)
4c70e2c12a455e947e23e027d639af518b289d4a
3,613,474
def lat_weights_regular_grid(lat): """ Generate latitude weights for equally spaced (regular) global grids. Weights are computed as sin(lat+dlat/2)-sin(lat-dlat/2) and sum to 2.0. """ dlat = np.abs(np.diff(lat)) np.testing.assert_almost_equal(dlat, dlat[0]) w = np.abs(np.sin(np.radians(lat +...
97bba018efefca2a05466ff633de187c085a6bc7
3,613,475
def get_universe(name, cache=False, environ=None): """ Parameters ---------- name: str cache: Returns ------- AbstractUniverse """ # cache universe in case we use it in-memory... if name == 'test': return TestUniverse(cache) elif name == 'quandl': retu...
23c231b0de267dba320b81477c1dc71a8c78b490
3,613,476
def explore_CordAttractor(N=10, angle=0.0, max_time=4.0, a=0.25, b=4.0, F=8.0, G=1.0, Plot=False): """ You can use it with animated widgets: from IPython.html.widgets import interact, interactive w = interactive(solve_lorenz, angle=(0.,360.), N=(0,50), sigma=(0.0,50.0), rho=(0.0,5...
22c26a1512b424edf15ab258d723ae460c74a4d7
3,613,478
def get_current_user(sql: Session = Depends(db_session), token: str = Depends(oauth2_scheme)): """get authenticated user""" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ...
55d327e234def0acfcd8bd7bdbcc30867e5c6bb7
3,613,479
def long_from_bytes(data): """ Return an integer from base64-encoded string. :param data: UTF-8 string containing base64-encoded data. :returns: Corresponding decoded integer. """ return int.from_bytes(decode_base64(data.encode("ascii")), 'big')
08d5d378c1c14684b8321be8a123897a3ddfa368
3,613,480
from lingcod.common import uaparser def valid_browser(ua): """ Returns boolean depending on whether we support their browser based on their HTTP_USER_AGENT Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_...
dc8bdf87633caf8547d1f6962718ded748c78510
3,613,482
def openREADME(): """ This is only needed because README.rst is UTF-8 encoded and that won't work under python3 iff sys.getfilesystemencoding() returns 'ascii' Since open() doesn't accept an encoding in python2... """ try: f = open("README.rst", encoding="utf-8") except: f =...
d42e07721f40d7681a9a8a22787a4ba9ac78ec8d
3,613,483
def set_host_enabled(self, arg_dict): """Sets this host's ability to accept new instances. It will otherwise continue to operate normally. """ enabled = arg_dict.get("enabled") if enabled is None: raise pluginlib.PluginError( "Missing 'enabled' argument to set_host_enabled") ...
2db8f0c8c9a97edab4042df6cc6773fb2e007b4a
3,613,485
from datetime import datetime def to_local_js_timestamp(utc_datetime): """Convert a UTC datetime into a local time timestamp suitable for the JavaScript date object""" return int(datetime.timestamp(utc_datetime.replace(tzinfo=timezone.utc).astimezone(tz=None)) * 1000)
c44a2482d2990ff297bce9ad16a77adb51e7030f
3,613,486
def userfcn_dcline_formulation(om, args): """This is the 'formulation' stage userfcn callback that defines the user constraints for the dummy generators representing DC lines. It expects to find a 'dcline' field in the ppc stored in om, as described above. By the time it is passed to this callback, ...
05db608241bfb3108c235ccec8339781c727c325
3,613,487
def read_raw(path): """Return the contents of `path`. Parameters ========== path : string Input data file (may be compressed) Returns ======= data : pandas DataFrame Contents of `path` """ # Set compression type if path.endswith('.gz'): compression = 'g...
bdceb6d53efee02d6944ac8e4249534d1db6784f
3,613,488
def _assign_interval_base(x, boundaries): """Assign each value in x an interval from boundaries. Parameters ---------- x: numpy.array, shape (number of examples,) The column of data that need to be discretized. boundaries: numpy.array, shape (number of interval boundaries,) ...
5d407ce565b188eff9248041b01796e289f2231c
3,613,491
def angle_between_vectors(v1, v2, v3): """ Compute the angle between the vector (v2, v3) and (v1, v2) The angle is constrained to lie in [-np.pi, np.pi] No turn will result in an angle of 0. A left turn will produce a positive angle. A right turn will produce a negative angle. The function...
a23042e6ac0a99a9065ac6c897abaad632b99ef6
3,613,492
def ts(nodes, topo_order): # topo must be a list of names """ Orders nodes by their topological order :param nodes: Nodes to be ordered :param topo_order: Order to arrange nodes :return: Ordered nodes (indices) """ node_set = set(nodes) return [n for n in topo_order if n in node_set]
741c7b3ac34c9f5beb6dc57ebf1539a27cc2b91b
3,613,494
def energy_loss(ef_energy='x', gv_energy='x', n='x'): """ Calculate and return the value of energy loss using given values of the params How to Use: Give arguments for ef_energy and gv_energy parameters or,give arguments for efficiency and gv_energy parameters *USE KEYWORD ARGUMENTS FOR...
868a5fa02beeda29fd053973c7cf999a1ed3ed22
3,613,495
def normalize_min_max(x, axis=None): """ Parameters: ---------- x: np.array() target array axis: int target axis Returns: ---------- np.array() normalized array so that the maximum value is 1 and the minimum value is 0 """ min = x.min(axis=axis, keepdims...
fddc3886f12d312994165641704207d97fcc1331
3,613,496
def get_2nd_or_3rd(): """ Returns all 2nd or 3rd degree connections for a user http://127.0.0.1:5000/2nd3rd/?ourid=3 """ args = request.args ourid = args['ourid'] return jsonify({'result' : n4jinstance.get_2nd_or_3rd(ourid) })
c5a36d5d7785a7ec304f42b5552b9777c2a57c68
3,613,497
def get_features_route(model_name: str, file_hash: str) -> str: """Gets the features of a file from the dataset. Args: model_name (str): Name of the model file_hash (str): Hash of the file Raises: PredictionNotCalledFirstError: The prediction route was not called before...
65238f3e031df5c0a432b6f9675ead9348a2e868
3,613,498
def fitted_predicted_OK3(X, y, Tree): """Function running OK3 and returning Y_train, Y_test, and Y_preds, for readability purposes Parameters ---------- X : np.ndarray features of the dataset y : np.ndarray labels of the dataset Tree : estimator estimator to fit and pred...
7507deb4f6ad3091eff837e397c5c4b95150ae18
3,613,499
def About(parent): """Display the about SPPAS dialog. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi :param parent: (wx.Window) ...
9ffb3c7adcd237a9efec4a748a59352d25105386
3,613,500
from typing import List from typing import Tuple from typing import Optional from typing import Dict from typing import Any import platform def _map_remote_share(share_system_name: str = None, share_user: str = None, share_pass: str = None, share_location_format_str: str = None, ...
194d88089bc5a846abdd6ad70ed1d2a13d07842d
3,613,502
from typing import Callable from typing import Iterable def values_reducer(values_fn: Callable) -> Reducer: """Return a reducer that just applies values_fn to its values""" def reduce(key, values: Iterable) -> KV: return (key, values_fn(values)) return reduce
ae61633fa7221fd71be93d117cc41ab699b3492c
3,613,504
def background_subtraction_quant_function(im, spool, t, frames, quant_radius=3, quant_z_radius=1, quant_voxels=20, background_radius=30, other_pos_radius=None, threads_to_quantify=None, quantified_voxels=None): """ Takes the mean of the 20 brightest pixels in a 3x7x7 square around the specified position minus t...
7420951a0791be9bf59ab8493696e06048edeaaa
3,613,505
import requests import json def _get_topics_by_token(push_token): """ :param push_token: required :return: topics, to which this token is subscribed (tags) """ firebase_server_key = "SERVER_KEY" firebase_info_url = "FIREBASE_INFO_URL" # "https://iid.googleapis.com/iid/info/" auth_key = "k...
a1265c6ab177caec92c3c550eebae3ecd35887c6
3,613,506
def set_product_options(name, version): """Set the options needed by the product template""" data = request.get_data().decode('utf-8') product = registry.get_product(name, version) product.options = data return '', 204
7dddd862a6077ad1ae40105d7d9a5e34374ccc47
3,613,507
def compute_and_update_frame_translations_dt(imp, channel, dt, process, shifts = None): """ imp contains a hyper virtual stack, and we want to compute the X,Y,Z translation between every t and t+dt time points in it using the given preferred channel. if shifts were already determined at other (lower) dt the...
b56d719c80ca8109ed51b3de21c915981c335696
3,613,508
import numpy def sigmoid_activation(aggregate: numpy.ndarray) -> float: """ :param aggregate: an array whose elements are the aggregate of all the inputs from the previous layer. For instance, the first element of the array is the aggregate of all input coming into the first node, the second element ...
d86c98e2edcd9b92efbbd244f68539f87ada9b62
3,613,510
def remove_dev(id): """Apagar parametro filtrando pela id""" index = id del devs[index] return jsonify({'message': 'Dev is no longer alive'}), 200
02f20695e043582f9616a6f1422ce22d623691af
3,613,511
def _get_configuration(resource_root, cluster_name, type, tag="version1"): """ Get configuration of a cluster @param resource_root: The root Resource . @param cluster_name: cluster_name @param type: type of config @return: A ConfigModel object """ dic = resource_root.get( paths.C...
d3dcfc309fce62a7d0b1591a94fbba54b40e5352
3,613,512
def create_job(): """Create a job.""" blob = request.get_json(force=True) payload = blob["payload"] state = blob.get("state", None) job = request.q.create(payload, state) return jsonify(job_as_json(job)), 200
73ed457478556123443ad08d3600435ae47f48fe
3,613,513
def import_model(sklearn_model): """ Load a tree ensemble model from a scikit-learn model object Parameters ---------- sklearn_model : object of type \ :py:class:`~sklearn.ensemble.RandomForestRegressor` / \ :py:class:`~sklearn.ensemble.RandomForestClassifier...
b807bac59de36589b672a7fadd2be9d6e63d0e63
3,613,514
def cir_Randles_simplified_Fit(params, w): """ Fit Function: Randles simplified -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit. See more under cir_Randles_simplified() NOTE: This Randles circuit is only meant for semi-infinate linear diffusion Kristian B. Knudsen (kknu@berkeley.edu || kr...
b87924de478402a9597b4686f6bef0afda4745c1
3,613,515
import collections def read_pubmed_to_genes(): """NCBI provides a list of articles (PMIDs) that discuss a particular gene (Entrez IDs). These provide a nice positive distant supervision set, as mentions of a gene name in an article about that gene are likely to be true mentions. This returns a dictionary t...
5e5d151e33aab538841a1db504cc18bc884ce33f
3,613,516
def MTFL(args): """ The protected feature is faces with or without glasses. Clusters are tested in binary gender classification. Pictures are 224x224 with 2 labels. """ transform = transforms.Compose([ # suggested transform for resnet50 encoder transforms.Resize(256), transforms...
479eb18f3da0d2dd43897f51b65f3e22e0866283
3,613,517
def return_slice(axis, index): """Prepares a slice tuple to use for extracting a slice for rendering Args: axis (str): One of "x", "y" or "z" index (int): The index of the slice to fetch Returns: tuple: can be used to extract a slice """ if axis == "x": return (sli...
ac6db30fc12509062efa4481d1f7b2fdaff8149b
3,613,518
def load_data(pickle_file): """Loads a data from a pickle file.""" print("Loading data...") dict_dataset = load_pickle(pickle_file) train_dataset = dict_dataset['train_dataset'] val_dataset = dict_dataset['val_dataset'] test_dataset = dict_dataset['test_dataset'] train_labels = dict_dataset[...
d88570826d0b3b7a42ed9ea41274e4cc8944dfc0
3,613,520
def unfold(data, prefix='', delimeter='__'): """ >>> _dd(unfold({'a': 4, 'b': 5})) "{'a': 4, 'b': 5}" >>> _dd(unfold({'a': [1, 2, 3]})) "{'a__0': 1, 'a__1': 2, 'a__2': 3}" >>> _dd(unfold({'a': {'a': 4, 'b': 5}})) "{'a__a': 4, 'a__b': 5}" >>> _dd(unfold({'a': {'a': 4, 'b': 5}}, 'form')) ...
26414f86499ff2302be6f56bb686bfbc23641e65
3,613,521
def get(*args, **kwargs): """Decorates a test to issue a GET request to the application. This is sugar for ``@open(method='GET')``. Arguments are the same as to :class:`~werkzeug.test.EnvironBuilder`. Typical usage:: @frontend.test @get('/') def index(response): ass...
c6322bd1340f5fe919ba25d70823be52ec368363
3,613,522
def photographer_required(func): """ if used to make sure the the current user is sa photographer :param func: :return: """ @wraps(func) def decorated_view(*args, **kwargs): if current_user.photographer is None: flash("You are not yet registered as a photographer") ...
eb7ccc85b4ad6d30e0b4a8b44fa3df2b98cb5417
3,613,523
import json def parse_arch_json_from_file(arch_json_path: str, photoroom_csv_path: str) -> House: """ Parses a house given the arch.json and the photoroom.csv :param arch_json_path: str: Path to arch.json :param photoroom_csv_path: str: Path to photoroom.csv :return: Parsed house """ with...
4dd40a80c4d7e7486cbaec71fd6401a9d3b7dc51
3,613,524
def Singleton_args(theClass): """ decorator for a class to make a singleton out of it """ classInstances = {} def getInstance(*args, **kwargs): """ creating or just return the one and only class instance. The singleton depends on the parameters used in __init__ """ key = (theCla...
0aea083099c9731134f093dc9f73ff411a4f35f2
3,613,525
def read_py_file(filename, skip_encoding_cookie=True): """Read a Python file, using the encoding declared inside the file. Parameters ---------- filename : str The path to the file to read. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in t...
c7c7c0ecb82f185452e126ee92e453c9119f60b1
3,613,526
def ts_min(x): """ [Definition] 对x中的每个时间序列在period范围内滚动求最小值 [Category] 统计 """ # 取前n天数据的最小值 return 'ts_min(%s,%s)' %(x, pe.gen_param('ts_min','period'))
27570afa1c9ab67618f254588dd57c2aa3acbccf
3,613,528
def rotation_matrix(angle, direction, point=None, dtype=np.float32): """Return matrix to rotate about axis defined by point and direction. http://www.lfd.uci.edu/~gohlke/code/transformations.py.html """ assert direction.dtype == dtype, "Wrong: %s" % direction.dtype sina = dtype(np.math.sin(angle)) ...
d4aaf7d18ea7e32be1707619d2caac51d773db5d
3,613,529
def good_partner_matrix(results, nplayers, repetitions): """ An n by n matrix of good partner ratings for n players Parameters ---------- results : list A cooperation results matrix of the form: [ [[a, j], [b, k], [c, l]], [[d, m], [e, n], [f, o]], ...
3b4f73f7b3a83e310618a3da5e50eb5d32ecc09c
3,613,530
def _date_keyboard(possible_dates): """Creates a keyboard of possible crab dates.""" date_keyboard = [ [InlineKeyboardButton(possible_dates["1"]["formatted"], callback_data=possible_dates["1"]["string"]), InlineKeyboardButton(possible_dates["2"]["formatted"], callback_data=possible_dates["2"]["...
072fe9fac119dd7d19748d3c5725bf08e8c7db78
3,613,531
def lite_plus_tot_functions(): """ Return the total number of lite_plus function extentions.""" return len(GLOBAL_REGISTER_LIST)
ac4e0a8b0a10ecb3493571c8c3a45aa2ccf89fff
3,613,533
def add(high, low): """Vector Arithmetic Add :param high: :param low: :return: :real: """ return ADD(high, low)
07376d4b7d91bfc6a1351ac0afde7afd147bec96
3,613,534
import numpy def features(im, max_features=6, min_pixels=50): """ Returns a list of features found in `im`. Args: im (Image): Source image. max_features (int): The maximum number of features to return. min_pixels (int): The minimum number of pixels a feature must conta...
2b7895391512ceb1554ba5b43f7918673cbeaf13
3,613,536
def _buffer_proxy(filename_or_buf, function, reset_fp=True, file_mode="rb", *args, **kwargs): """ Calls a function with an open file or file-like object as the first argument. If the file originally was a filename, the file will be opened, otherwise it will just be passed to the underl...
c5680ebb183559a00f1c635ec81d3cac135b7de5
3,613,538
def word_tokenize(text): """ convert a string to list of normal word tokens """ return filter_stopwords(tokenizer(text))
9b3778504945f43df699e9bc2e8d512d904c77b0
3,613,539
import re import ast def _parseSpec(values): """ Split the argument string. Example: --arg name:value0,value1,key2=value2,key3=value3 gets split into name, args, kwargs = ( "name", (value0, value1), {"key2":value2, "key3":value3}, ) """ split = values.split(":", 1) name = split[0].str...
2708b106bc83a82b44df71742fc7b689016921a1
3,613,540
def get_mask(mask_path): """Loads the data from a given mask. Parameters ---------- mask_path : str Path to the mask. Returns ------- numpy.ndarray Data of the given mask. """ return nibabel.load(mask_path).get_data()
d44e0cb9324ab31a192867dcef762ee392fe0560
3,613,541
def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula ...
94f918aa5b10057d34edc7c3606348cb75f60f1f
3,613,542
def PLUS_DI(df, time_period=14): """ +DI 最高价上涨的次数 + di是真实范围的百分比。di是真实范围下降的百分比。当+ di越过di时,生成一个买入信号。当di越过+ di时,产生一个卖出信号。你应该等到交易进入极限点为止。也就是说,你应该等待进入一个长期的交易,直到价格达到高的酒吧上di di越过di,并等待进入短期贸易,直到价格达到低的酒吧上的di越过+ di。 python API real=PLUS_DI(high, low, close, timeperiod=14) :return: """ high = df['h...
8e183cca7cff54ca3b9cf1048a7bb1222564a114
3,613,543
def map_records_nb(records, map_func_nb, *args): """Map each record to a scalar value. `map_func_nb` must accept a single record and `*args`, and return a scalar value.""" result = np.empty(records.shape[0], dtype=np.float_) for r in range(records.shape[0]): result[r] = map_func_nb(records[r], ...
ed4f693361abeaf1ee56ba1345caf2434fefe7e1
3,613,544
def schema(): """ Returns the basic schema of :class:`.Agent` .. http:get:: /api/v1/agents/schema HTTP/1.1 **Request** .. sourcecode:: http GET /api/v1/agents/schema HTTP/1.1 Accept: application/json **Response** .. sourcecode:: http ...
c42655d0afb00c1d1b7b763e64a5566d9300d220
3,613,545
def storage_root(state: State, address: Address) -> Root: """ Calculate the storage root of an account. Parameters ---------- state: The state address : Address of the account. Returns ------- root : `Root` Storage root of the account. """ assert sta...
ebebb135693ff1814b8a6e08bc5e0e6106971edd
3,613,546
def sort_out_edges(g, tag, tag_offset_name='_TAG_OFFSET'): """Return a new graph which sorts the out edges of each node. Sort the out edges according to the given destination node tags in integer. A typical use case is to sort the edges by the destination node types, where the tags represent destinatio...
78fda8d04aa49c95efec266da07dd523770426e0
3,613,547
def _count_dot_semicolumn(value): """Count the number of `.` and `:` in the given string.""" return sum([1 for c in value if c in [".", ":"]])
57ee0c88d31ed62168e562191bb1dd4ebb3de859
3,613,548
import re def FixIP(pattern): """If a stand alone IP, fix it so RE does not go off the rails""" if re.search(pattern,"^([0-9]{1,3}\.){3}[0-9]{1,3}$"): # If IP, make sure "." is not interpreted as a regexp "." instead of a period seperator pattern = pattern.replace(".",r"\.") return pattern
6cddfc3afda7f4c00ec7167a2a468791d8cc6632
3,613,549
def grant_staff_access(actor, user, is_staff): """ Grant staff access to a user via an actor. """ user.is_staff = is_staff user.save() return user
18624d0c9968e0e495235c4684d243650183dae0
3,613,550
from typing import Dict def _random_cropping_decoder( sequences: Dict[str, media_sequences.EncodedSequence], *, image_size: int, min_crop_window_area: float, max_crop_window_area: float, min_crop_window_aspect_ratio: float, max_crop_window_aspect_ratio: float, ) -> Dict[str, brave_datasets...
d57c58d25512c22532ea83dc0f7506d4df357c76
3,613,551
def generate_curve(A, B, C, D): """ if Seg(A1, B1) and Seg(A2, B2) intersects at P, then C is the closest point to A in the trajectory1 opposite to the direction of B, and D is the closest point to B opposite to the direction of A output: Bezier curve """ line_CA = Line(C, A) line_BD = ...
53c9d6b8146753858ef0f0dea527bdac6a1a2115
3,613,552
from typing import Dict from typing import List import copy def nutanix_hypervisor_task_results_get_command(client: Client, args: Dict): """ Poll tasks given by task_ids to check if they are ready. Returns all the tasks from 'task_ids' list that are ready at the moment Nutanix service was polled. ...
5a50a208f4eb2665783311e3faa5ebfbe038809f
3,613,553
def concatenate(adatas, merge_var_cols=None, **kwargs): """ Extension of scanpy's native `concatenate` funcion. Allows to merge columns in `var` of the same name with same contents into a single one instead of generating col-1, col-2, ... The columns to merge need to be specified explicitly. ...
e643a14fc3e6a0756dd0650b3209c5c788d75a2d
3,613,554
def downgrade_images(I_MS,I_PAN,ratio,sensor): """ downgrade MS and PAN by a ratio factor with given sensor's gains """ I_MS=np.double(I_MS) I_PAN=np.double(I_PAN) ratio=np.double(ratio) flag_PAN_MTF=0 if sensor=='QB': flag_resize_new = 2 GNyq = np.asarray([0.34, 0.3...
b356418b9b7e14af043345f58c68f8b7889fd896
3,613,556
def less_equal(evaluator, ast, state): """Evaluates "left <= right".""" res = UppaalBool(evaluator.eval_ast(ast["left"], state) <= evaluator.eval_ast(ast["right"], state)) return res
c7adef576ff63441c48a11e3e054dd891c126729
3,613,557
def get_vo_oasis_managers(global_data, vo): """return OASIS Managers list for given vo, if any, else an empty list""" vos_data = global_data.get_vos_data() return safe_dict_get(vos_data, vo, "OASIS", "Managers", default=[])
f649cab2ba24c43a222d45a1cc93904159620958
3,613,558
import re def normalize_string(string, able=None): """ Parameters ---------- string: str able: list[str] or None, default None Returns ------- str """ if able is None: return string if "space" in able: string = re.sub(r"[\t\u2028\u2029\u00a0\u1680\u180e\u20...
eb50298d476fba2b1a313afb3051233c1b16e4b5
3,613,559
def load_data(filename, smooth=False, filter_window=3, order=1): """ Reads the input datafile which is a multiindex pandas array generated by DeepLabCut as a result of analyzing a video. Parameters ---------- filename: string Full path of the multiindex pandas array(.h5) file as a string. ...
42e4f6940cfdb778a1bec7fec1da480720150060
3,613,560
from typing import get_args def create_function_dictionary(node): """Creates a dictionary from a node describing a FunctionDef Args: **node (:obj: `ast.FunctionDef`)**: The node to create the dictionary for Returns: A dictionary """ func_dict = { 'new_name': hex_name(node...
8a4e55cce2dea9a5da75831b5daeecee4c3527fb
3,613,561
import sqlite3 def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ try: conn = sqlite3.connect(db_file) return conn except Error as e: ...
9a2cde9bbd38571dea154f9a197bf82ee8a197aa
3,613,562
def get_p_Y_val_approx_mahalanobis(post_samples, y_mean, y_truth, cov): """Calculate the percentage of draws from the predicted distribution that encompasses the truth, for all of the examples in the validation set. Parameters ---------- post_samples : np.array of shape [n_samples, n_sightlines, Y_...
d38f217510befd24ad44b0b0b80707713da5578d
3,613,563
from typing import Dict from typing import Any import struct def parse_data_frame(data_bytes: bytearray, data_format_name: str) -> Dict[int, Any]: """Convert bytearray block from XEM buffer into formatted data. Args: data_bytes: a data block from the FIFO buffer data_format_name: a designatio...
5ed942e0cfed332a4df5ae569addd41e81b079da
3,613,564
def wavs_in_ranges(wavs, ranges): """Determine if wavelength is in one of the ranges given. wavs: wavelengths to check ranges: list of (lower limit, upper limit) pairs Returns ------- in_range: np.array containing True if the wavelength at the same index was in one of the ranges """ ...
3a6f974fc2012b6d1c8f6234d085bdf9e7327b3b
3,613,566
def node_compute_accuracy(l_inferred, l_targets) -> dict: """ - l_inferred : list of tensors of shape (N_nodes_i) - l_targets : list of tensors of shape (N_nodes_i) """ return edgefeat_compute_accuracy(l_inferred, l_targets)
bc189fa32172f17ee736d65366c92acc9e25c33c
3,613,567
import tqdm def _eval_knn(k,train_x,train_y,query_x,query_y,dist_metric,compute_loss=True): """ knn algorithm Inputs: k: (list) k[0]:lower bound of number of nearest neighbours; k[1]:upper bound of number of nearest neighbours train_x: (np.array) input training vector train_y: (np...
35dc3b362f3e6fec298e87af2b3252f5f438fa51
3,613,568
def spherical_uniform(size, dim=3, r=1.): """ Samples points from a uniform distribution on a spherical manifold. Uniform sampling on the sphere can be achieved by sampling from a Gaussian in the ambient space of the CCM, and then projecting the samples onto the sphere. :param size: number of po...
9d4cb35c43c232da4789e4e2221f1f60dddd311b
3,613,569
def la_roots(n, alpha, mu=False): """Gauss-generalized Laguerre quadrature Computes the sample points and weights for Gauss-generalized Laguerre quadrature. The sample points are the roots of the `n`th degree generalized Laguerre polynomial, :math:`L^{\\alpha}_n(x)`. These sample points and weight...
483876befb137b3f06aee7f2f2b140e925e4cda0
3,613,570
def modify_coco(coco): """ :param coco: json file containing coco ground truth, loaded with coco :return: json file containing coco ground truth where each object (all sailing ships) is segmented separately """ anns = coco['annotations'] L_im = [[] for i in range(16)] idx = 0 for i in r...
d800f261c44dd35f0a6b4c304f914b714c358c28
3,613,571
def average_above_zero(tab): """ Brief: computes of the avrage of the positive value sended Arg: a list of numeric values, except on positive value, else it will raise an Error Return: a list with the computed average as a float value and the max value Raise: Valu...
307846cdd75d8e415c6a7d819ffc0d5f7bc70da6
3,613,572
def _sample_discrete_actions(batch_probs): """Sample a batch of actions from a batch of action probabilities. Args: batch_probs (ndarray): batch of action probabilities BxA Returns: List consisting of sampled actions """ action_indices = [] # Subtract a tiny value from probabilitie...
3b897d8df682d8abe5f5d3887ac7a55421c3e58d
3,613,573
from pathlib import Path def get_data_dir() -> Path: """ * relative path: relative to package * Path with ~ is expanded * Absolute paths supported """ path = Path(config["global"]["datadir"].get()).expanduser() path = path if path.is_absolute() else DIR.parent / path if not path.exists...
8a449610cb9a3ae0ea7356eae8eb06b682db20a3
3,613,574
from re import T def first(seq: Seq[T], default=NOT_GIVEN) -> T: """ Return the first element of sequence. Raise ValueError or return the given default if sequence is empty. Examples: >>> sk.first("abcd") 'a' See Also: :func:`second` :func:`last` :func:`n...
ac1ca1cf1fb701310c19646d3dc0a6fae3728a6d
3,613,575
def se3ToVec(se3mat): """ Converts an se3 matrix into a spatial velocity vector :param se3mat: A 4x4 matrix in se3 :return: The spatial velocity 6-vector corresponding to se3mat Example Input: se3mat = np.array([[ 0, -3, 2, 4], [ 3, 0, -1, 5], ...
8a662704a0d2481352f63b2ede93c39523ab8cc8
3,613,576
def CommentPattern(lang_id=0): """Returns a list of characters used to comment a block of code @keyword lang_id: used to select a specific subset of comment pattern(s) """ if lang_id == synglob.ID_LANG_SQUIRREL: return ['//'] else: return list()
e79d46c3530343f1bc5732227c280d48f754c081
3,613,577
import click import traceback def handle_exception(e: Exception, verbose: bool) -> int: """ Handle exception from a scan command. """ if isinstance(e, click.exceptions.Abort): return 0 elif isinstance(e, click.ClickException): raise e else: if verbose: trace...
6f295f1c260d8ca92ac1e04ec504177a711c200e
3,613,578
from datetime import datetime def windrose( station, database="asos", months=np.arange(1, 13), hours=np.arange(0, 24), sts=datetime(1970, 1, 1), ets=datetime(2050, 1, 1), units="mph", nsector=36, justdata=False, rmax=None, sname=None, sknt=None, drct=None, valid...
39878da6f59660ec22af0448c09bdce51849b08e
3,613,579
def get_std(array, axis=None): """ Computes the standard deviation of an array, along a given axis. Parameters ---------- array: numpy array The array over which the operation will be done. axis : None, int Axis along which the operation will be done. Returns ---...
f71ac61e6419b7b6d2a28a853e2310b0789656b1
3,613,580
def calc_montage_horizontal(border_size, *frames): """Return total[], pos1[], pos2[], ... for a horizontal montage. Usage example: >>> calc_montage_horizontal(1, [2,1], [3,2]) ([8, 4], [1, 1], [4, 1]) """ num_frames = len(frames) total_width = sum(f[0] for f in frames) + (border_siz...
8fe5de84d9b1bff9950690ec99f63e174f2f0d22
3,613,581
def getArkoudaClientLogger(name : str) -> ArkoudaLogger: """ A convenience method for instantiating an ArkoudaLogger that retrieves the logging level from the ARKOUDA_LOG_LEVEL env variable and outputs log messages without any formatting to stdout. Parameters ---------- name : str ...
f5fe0abe2aefda7eac58c352ac79769bae20c2ba
3,613,582
def is_valid_file(ext, argument): """ Checks if file format is compatible """ formats = { 'input_dataset_path': ['csv'], 'output_results_path': ['csv'], 'output_plot_path': ['png'] } return ext in formats[argument]
85bd0ee9cb0eafc1244271d6b2b91b88fcbd3acc
3,613,583
def load_data(filename, kfold=3, seed=333, split='random'): """ Function to load the pressure data with stratified k fold Parameters ---------- filename : string Path to the data file. augment : bool, optional Whether or not to add random noise to the pressure data. The ...
597f70d2eb9fc2cde99f084873ea8fa023d964ff
3,613,584