content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import colorsys def hsv_to_rgb(image): """ Convert HSV img to RGB img. Args: image (numpy.ndarray): NumPy HSV image array of shape (H, W, C) to be converted. Returns: numpy.ndarray, NumPy HSV image with same shape of image. """ h, s, v = image[:, :, 0], image[:, :, 1], image[...
4e356beb6e9579c96cea3b050d6cc9b863723554
3,657,900
def dom_to_tupletree(node): """Convert a DOM object to a pyRXP-style tuple tree. Each element is a 4-tuple of (NAME, ATTRS, CONTENTS, None). Very nice for processing complex nested trees. """ if node.nodeType == node.DOCUMENT_NODE: # boring; pop down one level return dom_to_tuplet...
a3df44ff17c1a36eb30a57bb1e327f8c633c51fc
3,657,901
def import_bom_rf3(filename, **kwargs): """Import a NetCDF radar rainfall product from the BoM Rainfields3. Parameters ---------- filename : str Name of the file to import. Returns ------- out : tuple A three-element tuple containing the rainfall field in mm/h imported ...
1763a35ba3d46f1c584c53b9bce8dd91f55cfd20
3,657,902
def pipe_collapse(fq, outdir, gzipped=True): """ Collapse, by sequence """ fname = filename(fq) check_path(outdir) fq_out = collapse_fx(fq, outdir, gzipped=True) stat_fq(fq_out) # 1U 10A fq_list = split_fq_1u10a(fq_out) for f in fq_list: stat_fq(f) # wrap stat ...
5f510894b0eecc5d0c7e35a0b5e4e3550cfc49f9
3,657,903
from tqdm.auto import tqdm #if they have it, let users have a progress bar def multi_bw(init, y, X, n, k, family, tol, max_iter, rss_score, gwr_func, bw_func, sel_func, multi_bw_min, multi_bw_max, bws_same_times, verbose=False): """ Multiscale GWR bandwidth search procedure using it...
f1631a7c9d511fa4d6e95002042f846c484f30f5
3,657,904
def _auth_url(url): """Returns the authentication URL based on the URL originally requested. Args: url: String, the original request.url Returns: String, the authentication URL. """ parsed_url = urlparse.urlparse(url) parsed_auth_url = urlparse.ParseResult(parsed_url.scheme, ...
ede4b75e10e605b1ae36970ffdf3f6f31d70b810
3,657,905
import os import errno import stat def ismount(path): """ Test whether a path is a mount point. This is code hijacked from C Python 2.6.8, adapted to remove the extra lstat() system call. """ try: s1 = os.lstat(path) except os.error as err: if err.errno == errno.ENOENT: ...
d1d18af449c720ed0b616436d905c28313ed88d1
3,657,906
def getSupportedPrintTypes(mainControl, guiParent=None): """ Returns dictionary {printTypeName: (printObject, printTypeName, humanReadableName, addOptPanel)} addOptPanel is the additional options GUI panel and is always None if guiParent is None """ return groupOptPanelPlugins(mainContro...
468eb8a0aa404ac701f574b7ae2af276e2fd6136
3,657,907
def read_image(file_name: str) -> np.array: """ pomocna funkce na nacteni obrazku :param file_name: cesta k souboru :return: numpy array, pripravene na upravy pomoci nasich funkcni """ return np.asarray(Image.open(file_name), dtype=np.int32)
1241049c6cb2dff2a467cadea15cc92f4f8be958
3,657,908
def weighted_img(img, initial_img, α=0.8, β=1.0, γ=0.0): """ `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: ...
635870b037dabaa02ea7d2acb8726d98b604c288
3,657,909
def md5SessionKey(params, password): """ If the "algorithm" directive's value is "MD5-sess", then A1 [the session key] is calculated only once - on the first request by the client following receipt of a WWW-Authenticate challenge from the server. This creates a 'session key' for the authentication ...
2df5a7ce449553b55155618e1c93621a306eb6c8
3,657,910
def all_state_action(buffer: RolloutBuffer, learner: BaseAlgorithm, state_only: bool = False): """ Equivalent of state_action on the whole RolloutBuffer.""" o_shape = get_obs_shape(learner.observation_space) t = lambda x, shape=[-1]: buffer.to_torch(x).view(buffer.buffer_size*buffer.n_envs, *shape) if i...
89c236ac32893b7bab41cb2a00e7484dd0f15b1f
3,657,911
def write_results(conn, cursor, mag_dict, position_dict): """ Write star truth results to the truth table Parameters ---------- conn is a sqlite3 connection to the database cursor is a sqlite3.conneciton.cursor() object mag_dict is a dict of mags. It is keyed on the pid of the Proces...
0b0c9234a32050277a7e70fee3ab7ba1be5931bb
3,657,912
def get_sparameters(sim: td.Simulation) -> np.ndarray: """Adapted from tidy3d examples. Returns full Smatrix for a component https://support.lumerical.com/hc/en-us/articles/360042095873-Metamaterial-S-parameter-extraction """ sim = run_simulation(sim).result() def get_amplitude(monitor): ...
6577fac645e195c4e30406c6252c9b55831343a0
3,657,913
def mapmri_STU_reg_matrices(radial_order): """ Generates the static portions of the Laplacian regularization matrix according to [1]_ eq. (11, 12, 13). Parameters ---------- radial_order : unsigned int, an even integer that represent the order of the basis Returns ------- S, T,...
40cb1159f04d1291e06146dabd89380936c407a0
3,657,914
def _checker(word: dict): """checks if the 'word' dictionary is fine :param word: the node in the list of the text :type word: dict :return: if "f", "ref" and "sig" in word, returns true, else, returns false :rtype: bool """ if "f" in word and "ref" in word and "sig" in word: return...
ee6ec5a7ee393ddcbc97b13f6c09cdd9019fb1a6
3,657,915
def construc_prob(history, window, note_set, model, datafilename): """ This function constructs the proabilities of seeing each next note Inputs: history, A list of strings, the note history in chronological order window, and integer how far back we are looking note_set, the set of n...
92e75d386c5fce984302ca60f80b2dc1891fc873
3,657,916
def renderPybullet(envs, config, tensor=True): """Provides as much images as envs""" if type(envs) is list: obs = [ env_.render( mode="rgb_array", image_size=config["image_size"], color=config["color"], fpv=config["fpv"], ...
fb04ecda7e0dbfbe7899d4684979828b3fcd83c6
3,657,917
def wifi(request): """Collect status information for wifi and return HTML response.""" context = { 'refresh': 5, 'item': '- Wifi', 'timestamp': timestamp(), 'wifi': sorted(Wifi().aps), } return render(request, 'ulm.html', context)
0a5412c2912eaeae192dd6d5fe85d336dec1b169
3,657,918
def genModel( nChars, nHidden, numLayers = 1, dropout = 0.5, recurrent_dropout = 0.5 ): """Generates the RNN model with nChars characters and numLayers hidden units with dimension nHidden.""" model = Sequential() model.add( LSTM( nHidden, input_shape = (None, nChars), return_sequences = True, ...
4aeef47b8a4948e37eaa2ea07ac22ecee167df51
3,657,919
def rotate_system(shape_list, angle, center_point = None): """Rotates a set of shapes around a given point If no center point is given, assume the center of mass of the shape Args: shape_list (list): A list of list of (x,y) vertices angle (float): Angle in radians to rotate counterclockwis...
64c4ff717fd432a187d2616263405ae89a0d89f8
3,657,920
def _large_compatible_negative(tensor_type): """Large negative number as Tensor. This function is necessary because the standard value for epsilon in this module (-1e9) cannot be represented using tf.float16 Args: tensor_type: a dtype to determine the type. Returns: a large negative number. """ ...
c73a9e2de341d771ec07ecf2b2a178911ecc27bd
3,657,921
def classified_unread_counts(): """ Unread counts return by helper.classify_unread_counts function. """ return { 'all_msg': 12, 'all_pms': 8, 'unread_topics': { (1000, 'Some general unread topic'): 3, (99, 'Some private unread topic'): 1 }, ...
4d5e984641de88fd497b6c78891b7e6478bb8385
3,657,922
def company_key(company_name=DEFAULT_COMPANY_NAME): """Constructs a Datastore key for a Company entity with company_name.""" return ndb.Key('Company', company_name)
f9387ef2ee33ea87a4a9fd721f14c35ca60ac482
3,657,923
def to_n_class(digit_lst, data, labels): """to make a subset of MNIST dataset, which has particular digits Parameters ---------- digit_lst : list for example, [0,1,2] or [1, 5, 8] data : numpy.array, shape (n_samples, n_features) labels : numpy.array or list of str Returns ------...
79652687ec0670ec00d67681711903ae01f4cc87
3,657,924
from re import T import numpy from operator import ne def acosh(x: T.Tensor) -> T.Tensor: """ Elementwise inverse hyperbolic cosine of a tensor. Args: x (greater than 1): A tensor. Returns: tensor: Elementwise inverse hyperbolic cosine. """ y = numpy.clip(x,1+T.EPSILON, nump...
c5566c9b67b8be57be47c96762ce7371e1d4d988
3,657,925
import argparse def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('replace', metavar='str', help='Th...
3b7211aea79cf67e4b4b4e8e6c29d37cbf65bac6
3,657,926
def run_unit_tests(): """ Run unit tests against installed tools rpms """ # At the time of this writing, no unit tests exist. # A unit tests script will be run so that unit tests can easily be modified print "Running unit tests..." success, output = run_cli_cmd(["/bin/sh", UNIT_TEST_SCRIPT], False) ...
fd2241bd471b7de61bac922f3da485cb954fbe06
3,657,927
def encode_input_descr(prm): """ Encode process description input.""" elem = NIL("Input", *_encode_param_common(prm)) elem.attrib["minOccurs"] = ("1", "0")[bool(prm.is_optional)] elem.attrib["maxOccurs"] = "1" if isinstance(prm, LiteralData): elem.append(_encode_literal(prm, True)) elif ...
9d5db979f5da325595501a50c2031f56fd438b47
3,657,928
def poly_quo(f, g, *symbols): """Returns polynomial quotient. """ return poly_div(f, g, *symbols)[0]
2a4b04b053189db9bd5cb946b6399257b49a8afb
3,657,929
import random from typing import OrderedDict def preprocess_data(dataset, encoder, config): """ Function to perform 4 preprocessing steps: 1. Exclude classes below minimum threshold defined in config.threshold 2. Exclude all classes that are not referenced in encoder.classes 3. Encode ...
ed7f7382c4d1c8bc6ce718605b9d64cc2cb6ff6e
3,657,930
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, ...
3cd30bcc35b308913a5f54f39f2e0fb7a5583032
3,657,931
import os import importlib import sys def load_test_environment(skill): """Load skill's test environment if present Arguments: skill (str): path to skill root folder Returns: Module if a valid test environment module was found else None """ test_env = None test_env_path = os....
333d769ea59455afe73e20df00eedd88dd0a3f88
3,657,932
import json from datetime import datetime async def ready(request): """ For Kubernetes readiness probe, """ try: # check redis valid. if app.redis_pool: await app.redis_pool.save('health', 'ok', 1) # check mysql valid. if app.mysql_pool: sql = "...
f776787f65609fa341eb360c801cf8ebdc16a2eb
3,657,933
def surface_area(polygon_mesh): """ Computes the surface area for a polygon mesh. Parameters ---------- polygon_mesh : ``PolygonMesh`` object Returns ------- result : surface area """ if isinstance(polygon_mesh, polygonmesh.FaceVertexMesh): print("A FaceVertex Mesh") ...
587740d493ef5762c85f75f81d98e141121b5d7d
3,657,934
from scipy.optimize import fsolve # non-linear solver import numpy as np def gas_zfactor(T_pr, P_pr): """ Calculate Gas Compressibility Factor For range: 0.2 < P_pr < 30; 1 < T_pr < 3 (error 0.486%) (Dranchuk and Aboukassem, 1975) """ # T_pr : calculated pseudoreduced temperature # P_pr : calculated pse...
b9b1d770483737da8277a89b3f1100ea0c49c1c0
3,657,935
def format_value_with_percentage(original_value): """ Return a value in percentage format from an input argument, the original value """ percentage_value = "{0:.2%}".format(original_value) return percentage_value
78bfb753b974bc7cbe3ac96f58ee49251063d2e7
3,657,936
import numpy def get_Z_and_extent(topofile): """Get data from an ESRI ASCII file.""" f = open(topofile, "r") ncols = int(f.readline().split()[1]) nrows = int(f.readline().split()[1]) xllcorner = float(f.readline().split()[1]) yllcorner = float(f.readline().split()[1]) cellsize = float(f....
e96db5c2ae4a0d6c94654d7ad29598c3231ec186
3,657,937
from typing import Sequence from typing import MutableMapping import copy def modified_config( file_config: submanager.models.config.ConfigPaths, request: pytest.FixtureRequest, ) -> submanager.models.config.ConfigPaths: """Modify an existing config file and return the path.""" # Get and check request...
8a453233b6340b50fdcbc4d3bf7b2f1f1e7e15ce
3,657,938
import torch def train_discrim(discrim, state_features, actions, optim, demostrations, settings): """demostractions: [state_features|actions] """ criterion = torch.nn.BCELoss() for _ in range(settings.VDB_UPDATE_NUM): learner = discrim(torch.cat([state_features, actions], di...
7e6c16fc396b371e92d3a04179eacb9cae63659c
3,657,939
import sys from pathlib import Path def task_install(): """install the packages into the sys.packages""" def install(pip): if pip: name = get_name() assert not doit.tools.CmdAction( f"python -m pip install --find-links=dist --no-index --ignore-installed --no-d...
48c413f3b478a9fdba22ba5780efa982158f0fc9
3,657,940
def filter_column(text, column, start=0, sep=None, **kwargs): """ Filters (like grep) lines of text according to a specified column and operator/value :param text: a string :param column: integer >=0 :param sep: optional separator between words (default is arbitrary number of blanks) :param kwargs:...
f7a788d2d79dba33961213c6bc469d41a0151812
3,657,941
def max_tb(collection): # pragma: no cover """Returns the maximum number of TB recorded in the collection""" max_TB = 0 for doc in collection.find({}).sort([('total_TB',-1)]).limit(1): max_TB = doc['total_TB'] return max_TB
bde417de0b38de7a7b5e4e3db8c05e87fa6c55ca
3,657,942
def prep_im_for_blob(im, pixel_means, target_size_1, target_size_2, max_size_1, max_size_2): """Mean subtract and scale an image for use in a blob.""" im = im.astype(np.float32, copy=False) im -= pixel_means im_shape = im.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) im_sca...
a1842d918149f5d1ccc52e04cc499005570b72ea
3,657,943
import os import logging def bandit_run_bandit_scan(attr_dict, path_package, package_name, path_sdk_settings=None, **__): """ Run Bandit Scan on whole package using the settings defined in ``constants.BANDIT_DEFAULT_ARGS``. Raises a SDKException if ``bandit`` isn't installed. In use with ``validate``...
0229a0ca9980232d5c9ff4b52f7ae4d4ec2c737c
3,657,944
def plotann(annotation, title = None, timeunits = 'samples', returnfig = False): """ Plot sample locations of an Annotation object. Usage: plotann(annotation, title = None, timeunits = 'samples', returnfig = False) Input arguments: - annotation (required): An Annotation object. The sample att...
2159c1ffed52ef6524990f861d7e986b7aa00c25
3,657,945
def match_assignments(nb_assignments, course_id): """ Check sqlalchemy table for match with nbgrader assignments from a specified course. Creates a dictionary with nbgrader assignments as the key If match is found, query the entry from the table and set as the value. Else, set the value to None ...
22158bc0d3655a78b8e5b6cb245b781e187f1481
3,657,946
def tan(input): """Computes tangent of values in ``input``. :rtype: TensorList of tan(input). If input is an integer, the result will be float, otherwise the type is preserved. """ return _arithm_op("tan", input)
27e6487591ff4d207baea094293be83ef22a4099
3,657,947
def recall_from_IoU(IoU, samples=500): """ plot recall_vs_IoU_threshold """ if not (isinstance(IoU, list) or IoU.ndim == 1): raise ValueError('IoU needs to be a list or 1-D') iou = np.float32(IoU) # Plot intersection over union IoU_thresholds = np.linspace(0.0, 1.0, samples) r...
9c24a4e546a76998339ce85e02fae6fec3adb00d
3,657,948
import math def _GetImage(options): """Returns the ndvi regression image for the given options. Args: options: a dict created by _ReadOptions() containing the request options Returns: An ee.Image with the coefficients of the regression and a band called "rmse" containing the Root...
00b4bd82e772a8afa8c4f92c3dd9afa880af79f2
3,657,949
def get_registered_plugins(registry, as_instances=False, sort_items=True): """Get registered plugins. Get a list of registered plugins in a form if tuple (plugin name, plugin description). If not yet auto-discovered, auto-discovers them. :param registry: :param bool as_instances: :param bool s...
68b695ebe3de95a86d37831fe38ce934bcced16c
3,657,950
import time def datetime_to_timestamp(d): """convert a datetime object to seconds since Epoch. Args: d: a naive datetime object in default timezone Return: int, timestamp in seconds """ return int(time.mktime(d.timetuple()))
356ac090b0827d49e9929a7ef26041b26c6cc690
3,657,951
import torch def gumbel_softmax(logits, temperature): """From https://gist.github.com/yzh119/fd2146d2aeb329d067568a493b20172f logits: a tensor of shape (*, n_class) returns an one-hot vector of shape (*, n_class) """ y = gumbel_softmax_sample(logits, temperature) shape = y.size() _, ind = ...
49a79bf5955cfc01fd27f0a56c23d001e3ef65cc
3,657,952
def in_whitelist(address): """ Test if the given email address is contained in the list of allowed addressees. """ if WHITELIST is None: return True else: return any(regex.search(address) for regex in WHITELIST)
ed552f16a2cd4b9d5e97033e47d5ec8950841164
3,657,953
def decomposePath(path): """ :example: >>> decomposePath(None) >>> decomposePath("") >>> decomposePath(1) >>> decomposePath("truc") ('', 'truc', '', 'truc') >>> decomposePath("truc.txt") ('', 'truc', 'txt', 'truc.txt') >>> decomposePath("/home/...
7b45cfe64f631912fc56246f404ddbea51b9f1ec
3,657,954
def BSCLLR(c,p): """ c: A list of ones and zeros representing a codeword received over a BSC. p: Flip probability of the BSC. Returns log-likelihood ratios for c. """ N = len(c) evidence = [0]*N for i in range(N): if (c[i]): evidence[i] = log(p/(1-p)) else: ...
2ee6f4a72a8c2aa3257ae00e8374511f74edcbdb
3,657,955
import torch def _res_dynamics_fwd( real_input, imag_input, sin_decay, cos_decay, real_state, imag_state, threshold, w_scale, dtype=torch.int32 ): """ """ dtype = torch.int64 device = real_state.device real_old = (real_state * w_scale).clone().detach().to(dtype).to(device) imag_ol...
259b520c9ba4491931726b02ff51bc1c69283cdd
3,657,956
def make_json_error(error): """ Handle errors by logging and """ message = extract_error_message(error) status_code = extract_status_code(error) context = extract_context(error) retryable = extract_retryable(error) headers = extract_headers(error) # Flask will not log user exception...
ea249272428cdab765ef21cc3cef8d899c9edb19
3,657,957
def tokenize_finding(finding): """Turn the finding into multiple findings split by whitespace.""" tokenized = set() tokens = finding.text.split() cursor = 0 # Note that finding.start and finding.end refer to the location in the overall # text, but finding.text is just the text for this finding. for token ...
28974a87bdb006bbdf37fff68345a9df81ea0962
3,657,958
import scipy def gaussian_filter_density(gt): """generate ground truth density map Args: gt: (height, width), object center is 1.0, otherwise 0.0 Returns: density map """ density = np.zeros(gt.shape, dtype=np.float32) gt_count = np.count_nonzero(gt) if gt_count == 0: ...
9a51de844a08af18e5d1f72d368dbd6b05d24d34
3,657,959
def RGBfactorstoBaseandRange( lumrange: list[int, int], rgbfactors: list[float, float, float]): """Get base color luminosity and luminosity range from color expressed as r, g, b float values and min and max byte lumin...
47fba5a98b324fc27869fee8b03903f844ef2c38
3,657,960
def mean_by_orbit(inst, data_label): """Mean of data_label by orbit over Instrument.bounds Parameters ---------- data_label : string string identifying data product to be averaged Returns ------- mean : pandas Series simple mean of data_label indexed by start of each orbit ...
55e3edac3231d4c42428cd87ee758f1b27d959b9
3,657,961
from typing import Callable from typing import Optional def quantile_constraint( column: str, quantile: float, assertion: Callable[[float], bool], where: Optional[str] = None, hint: Optional[str] = None, ) -> Constraint: """ Runs quantile analysis on the given column and executes the asser...
b3e3924a830ec7fd47de981e1ae9eb3f1810c2a1
3,657,962
from typing import Tuple import torch def _compute_rank( kg_embedding_model, pos_triple, corrupted_subject_based, corrupted_object_based, device, ) -> Tuple[int, int]: """ :param kg_embedding_model: :param pos_triple: :param corrupted_subject_based: :param c...
2b5043dfed43907563c473141257626bb93027b7
3,657,963
def _get_bool_argument(ctx: ClassDefContext, expr: CallExpr, name: str, default: bool) -> bool: """Return the boolean value for an argument to a call or the default if it's not found. """ attr_value = _get_argument(expr, name) if attr_value: ret = ctx.api.parse_bool(at...
7f903f884edcb4af328207a0b7d2569cefce0a93
3,657,964
import json def validate_filter_parameter(string): """ Extracts a single filter parameter in name[=value] format """ result = () if string: comps = string.split('=', 1) if comps[0]: if len(comps) > 1: # In the portal, if value textbox is blank we store the valu...
8258cff656889a57aaeb24644ea4efc9a60a6997
3,657,965
def ones(distribution, dtype=float): """Create a LocalArray filled with ones.""" la = LocalArray(distribution=distribution, dtype=dtype) la.fill(1) return la
d3caa46b76932a44d441574c78ebbd9c4e8d29f9
3,657,966
def update_podcast_url(video): """Query the DDB table for this video. If found, it means we have a podcast m4a stored in S3. Otherwise, return no podcast. """ try: response = PODCAST_TABLE_CLIENT.query( KeyConditionExpression=Key('session').eq(video.session_id) & Key('year').eq(v...
50a39aceaba7980dff90043bf444b01607b258ae
3,657,967
def translate(filename): """ File editing handler """ if request.method == 'POST': return save_translation(app, request, filename) else: return open_editor_form(app, request, filename)
5f9419db30ebd76e17f9f5c6efd746b3ddc1d8b0
3,657,968
def read_fileset(fileset): """ Extract required data from the sdoss fileset. """ feat_data = { 'DATE_OBS': [], 'FEAT_HG_LONG_DEG': [], 'FEAT_HG_LAT_DEG': [], 'FEAT_X_PIX': [], 'FEAT_Y_PIX': [], 'FEAT_AREA_DEG2': [], 'FEAT_FILENAME': []} for c...
3c1c9018444af04ca8cc7d95176032ad92c42928
3,657,969
def get_branch_index(edge_index, edge_degree, branch_cutting_frequency=1000): """Finds the branch indexes for each branch in the MST. Parameters ---------- edge_index : array The node index of the ends of each edge. edge_degree : array The degree for the ends of each edge. branc...
3ac24625f9c67cdb60759e840b06b21f260733c9
3,657,970
def update_coverage(coverage, path, func, line, status): """Add to coverage the coverage status of a single line""" coverage[path] = coverage.get(path, {}) coverage[path][func] = coverage[path].get(func, {}) coverage[path][func][line] = coverage[path][func].get(line, status) coverage[path][func][li...
46e5a1e5c4ebba3a9483f90ada96a0f7f94d8c1d
3,657,971
def cross_product(v1, v2): """Calculate the cross product of 2 vectors as (x1 * y2 - x2 * y1).""" return v1.x * v2.y - v2.x * v1.y
871d803ef687bf80facf036549b4b2062f713994
3,657,972
def loadData(fname='Unstra.out2.00008.athdf'): """load 3d bfield and calc the current density""" #data=ath.athdf(fname,quantities=['B1','B2','B3']) time,data=ath.athdf(fname,quantities=['vel1']) vx = data['vel1'] time,data=ath.athdf(fname,quantities=['vel2']) vy = data['vel2'] time,data=ath.athdf(fname,qu...
121768232fe71ce8ce3714aea70b5bf2c7493907
3,657,973
def text_iou(ground_truth: Text, prediction: Text) -> ScalarMetricValue: """ Calculates agreement between ground truth and predicted text """ return float(prediction.answer == ground_truth.answer)
5ea135b30ba93da45fb1ecd624fe7dc556f01cf5
3,657,974
def divisors(num): """ Takes a number and returns all divisors of the number, ordered least to greatest :param num: int :return: list (int) """ # Fill in the function and change the return statment. return 0
f15169b2672847294a219207f6022ad3e49338d2
3,657,975
def space_oem(*argv): """Handle oem files Usage: space-oem get <selector>... space-oem insert (- | <file>) space-oem compute (- | <selector>...) [options] space-oem list <selector>... [options] space-oem purge <selector>... [--until <until>] space-oem list-tags <...
54c479f7008f475f778f491c7b6c5574390fd38c
3,657,976
def compare_distance(tree,target): """ Checks tree edit distance. Since every node has a unique position, we know that the node is the same when the positions are the same. Hence, a simple method of counting the number of edits one needs to do to create the target tree out of a given tree is equal to the number of...
96b57e88b8e70dbb43231b56cbe7e9b7ebcfd10f
3,657,977
def header(name='peptide'): """ Parameters ---------- name Returns ------- """ with open('{}.pdb'.format(name), 'r') as f: file = f.read() model = file.find('\nMODEL') atom = file.find('\nATOM') if atom < 0: raise ValueError('no ATOM entries found in...
84e75e34771b7c395ee36611c8d055ca1fdf67dc
3,657,978
from datetime import datetime def isoUTC2datetime(iso): """Convert and ISO8601 (UTC only) like string date/time value to a :obj:`datetime.datetime` object. :param str iso: ISO8061 string :rtype: datetime.datetime """ formats = ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"] if 'T' in iso: ...
0dae4fb7828f7319afa7190deca6ae4fda5ffd1d
3,657,979
from typing import Optional from typing import Dict from typing import Union def groupstatus(aid: int, state: int = 0) -> EndpointResult: """Retrieve anime release status for different groups. :param aid: anidb anime id :type aid: int :param state: release state. int 1 to 6. Example: zenchi.mappings....
f81ab06c8d47b9660cac9bde76978a722a13f49f
3,657,980
def get_communities_codes(communities, fields=None, community_field='Community'): """From the postal code conversion file, select entries for the `communities`. This function is similar to get_community_codes, but works if `communities` and `fields` are strings or lists of strings. """ if not ...
552fef722cd138f1a935755349116c89e0df3e3b
3,657,981
from vba import VBA from dataFrame import DF def GLMFit_(file, designMatrix, mask, outputVBA, outputCon, fit="Kalman_AR1"): """ Call the GLM Fit function with apropriate arguments Parameters ---------- file designmatrix mask outputVBA outputCon fit='Kalman_AR1' ...
25ced91bc6c865faaffab30278d59aad6a475d4f
3,657,982
from typing import Iterable def get_stoch_rsi(quotes: Iterable[Quote], rsi_periods: int, stoch_periods: int, signal_periods: int, smooth_periods: int = 1): """Get Stochastic RSI calculated. Stochastic RSI is a Stochastic interpretation of the Relative Strength Index. Parameters: `quotes` : Itera...
b548a620ef3b3bc4cb37049d1dfb29aac442b394
3,657,983
def PUtilHann (inUV, outUV, err, scratch=False): """ Hanning smooth a UV data set returns smoothed UV data object inUV = Python UV object to smooth Any selection editing and calibration applied before average. outUV = Predefined UV data if scratch is False, ignored if scrat...
a53f8d442055b2d575b36f49a96b68f6c6eff7ed
3,657,984
def str2bytes(seq): """ Converts an string to a list of integers """ return map(ord,str(seq))
7afe8e40cd4133c59be673b537f2717591b093cf
3,657,985
def __downloadFilings(cik: str) -> list: """Function to download the XML text of listings pages for a given CIK from the EDGAR database. Arguments: cik {str} -- Target CIK. Returns: list -- List of page XML, comprising full listing metadata for CIK. """ idx = 0 # Curr...
c98996d3607076ed0328a5e0621ef015037ddc2e
3,657,986
def KK_RC43_fit(params, w, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params["Rs"] R1 = params["R1"] R2 = params["R2"] R3 = params["R3"] R4 = params["R4"] R5 = params["R5"] R6 = params["R6"] ...
9f88b73ac5da422069e67af28c15c2846178169b
3,657,987
from .column import ColumnVirtualConstant def vconstant(value, length, dtype=None, chunk_size=1024): """Creates a virtual column with constant values, which uses 0 memory. :param value: The value with which to fill the column :param length: The length of the column, i.e. the number of rows it should cont...
b712ec9f1aea2f65f1f992cd3b23ab671339f97a
3,657,988
import os def getsize(filename): """Return the size of a file, reported by os.stat().""" return os.stat(filename).st_size
f21bd048bf1fdbc80cdcbd4f14dba8f390439f74
3,657,989
def get_all_nsds_of_node(logger, instance): """ This function performs "mmlsnsd -X -Y". Args: instance (str): instance for which disks are use by filesystem. region (str): Region of operation Returns: all_disk_names (list): Disk names in list format. ...
648bb6706c2dd01d448044b98425642319a75eca
3,657,990
def gen_color_palette(n: int): """ Generates a hex color palette of size n, without repeats and only light colors (easily visible on dark background). Adapted from code by 3630 TAs Binit Shah and Jerred Chen Args: n (int): number of clouds, each cloud gets a unique color """ pal...
6b1004674d1448cdcca8c3500b149b1602e0045f
3,657,991
def absolute_vorticity(u, v, dx, dy, lats, dim_order='yx'): """Calculate the absolute vorticity of the horizontal wind. Parameters ---------- u : (M, N) ndarray x component of the wind v : (M, N) ndarray y component of the wind dx : float or ndarray The grid spacing(s) i...
9ae200b3a8b8415f67fc640b0702bc5272c77d3a
3,657,992
def drop_path(input, drop_prob=0.0, training=False, scale_by_keep=True): """ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ if drop_prob == 0.0 or not training: return input keep_prob = 1 - drop_prob shape = (input.shape[0],) + (1,) * (input....
289ae545fa184bb459275685d3a2894e5219db2e
3,657,993
from typing import Dict from typing import Any from typing import List import secrets def ask_user_config() -> Dict[str, Any]: """ Ask user a few questions to build the configuration. Interactive questions built using https://github.com/tmbo/questionary :returns: Dict with keys to put into template ...
7697ba65c7ba7f73b81af3ae3575beb0eb9b30b8
3,657,994
def generate_menusystem(): """ Generate Top-level Menu Structure (cached for specified timeout) """ return '[%s] Top-level Menu System' % timestamp()
eb3575835889af768887f3071816d0f22f867568
3,657,995
import time def main(): """ main loop """ #TODO: enable parallezation to use multiple cores N = int(1e18) def sum(N): start = time.time() result = 0 for i in range(N): if i % int(1e9) == 0: print("** step %i **" % int(i/1e9)) result += ...
1327fcff07e706624cfb5fa9f270bbac25f340bb
3,657,996
import json import aiohttp import asyncio from loguru import logger from typing import Optional async def simple_post(session, url: str, data: dict, timeout: int = 10) -> Optional[dict]: """ A simple post function with exception feedback Args: session (CommandSession): current session url ...
2a0b6a26154f322f42850106a21b167161fe7cc0
3,657,997
def gnomonic_proj(lon, lat, lon0=0, lat0=0): """ lon, lat : arrays of the same shape; longitude and latitude of points to be projected lon0, lat0: floats, longitude and latitude in radians for the tangency point --------------------------- Returns the gnomonic project...
61daaee7bc0ca5dd901582adc03ec6c36ddf2ef2
3,657,998
def local_pluggables(pluggable_type): """ Accesses pluggable names Args: pluggable_type (Union(PluggableType,str)): The pluggable type Returns: list[str]: pluggable names Raises: AquaError: if the type is not registered """ _discover_on_demand() if isinstance(plu...
8626e931da1fd33d76cef4ed85b6ea1a7d7e907d
3,657,999