content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def get_tiff_param(tiff_file): """Obtain relevant parameters of TiffFile object""" xy_dim, description = lookup_page(tiff_file.pages[0]) shape = tiff_file.asarray().shape if tiff_file.is_fluoview: return get_fluoview_param(description, xy_dim, shape) elif tiff_file.is_imagej...
d161f142780e86e19cb2a8e7e9440c4768509119
3,630,900
def get_number_of_classes(model_config): """Returns the number of classes for a detection model. Args: model_config: A model_pb2.DetectionModel. Returns: Number of classes. Raises: ValueError: If the model type is not recognized. """ meta_architecture = model_config.WhichOneof("model") meta...
d87605b6025e1bc78c7436affe740f7591a99f68
3,630,901
from typing import Optional def to_xy0( xyz: npt.ArrayLike, radius: Optional[float] = 1.0, stacked: Optional[bool] = True ) -> np.ndarray: """ Convert geocentric xyz coordinates to longitude (φ) and latitude (λ) xy0 (i.e., φλ0) coordinates. Parameters ---------- xyz : ArrayLike A ...
9f3e94def7f7fa5d34a791fcd054068874f5621b
3,630,902
def getDataset(filepath = ""): """ Reads a comma separated variables (csv) file and creates a dataset. A dataset has the following components: Variables, Data, Types, Groups, Sorts To call each componenet of a dataset, do the following. Say you have a dataset named: somedata somedata['VARIABLES'...
cb3ae7b9b392a702729078df009452cff0a965b6
3,630,903
def draw_matches(img0, img1, kpts0, kpts1, match_idx, downscale_ratio=1, color=(0, 255, 0), radius=4, thickness=2): """ Args: img: color image. kpts: Nx2 numpy array. match_idx: Mx2 numpy array indicating the matching index. Returns: display: image with drawn...
17b118bf175bef066292b370a7f0571425900fc3
3,630,904
def shorten_build_target(build_target: str) -> str: """Returns a shortened version of the build target.""" if build_target == '//chrome/android:chrome_java': return 'chrome_java' return build_target.replace('//chrome/browser/', '//c/b/')
03af53f1fcacae9a4e0309053075806d65275ce9
3,630,905
from datetime import datetime import copy def store_initial_role_data(dynamo_table, arn, create_date, role_id, role_name, account_number, current_policy, tags): """ Store the initial version of a role in Dynamo Args: role (Role) current_policy (dict) Returns: None """ ...
2c6a54a3b6fc414e638e3ba2870201c73b37a2b1
3,630,906
def apply_shift(x, shift, out): """ Translates elements of `x` along axis=0 by `shift`, using linear interpolation for non-integer shifts. Parameters ---------- x : ndarray Array with ndim >= 1, holding data. shift : float Shift magnitude. out : ndarray Array wit...
86e58c536cbc2fb43bb049aab6d0d4d733308bbd
3,630,907
import platform def get_socket(dname, protocol, host, dno): """socket = get_socket(dname, protocol, host, dno) Connect to the display specified by DNAME, PROTOCOL, HOST and DNO, which are the corresponding values from a previous call to get_display(). Return SOCKET, a new socket object connected to ...
d2703d7747ffac8d142f170dd153169f111f8b5d
3,630,908
def azureblobstorage_folder_list(node_addon, **kwargs): """ Returns all the subsequent folders under the folder id passed. """ return node_addon.get_folders()
d6934946a428e592ab2644ffbfb0a28ebb2ad9c8
3,630,909
def summary_statistics(is_significant, time_interp, n_records_at_t, n_window): """Compute summary statistics.""" # Initialize significant_number = np.zeros(len(time_interp)) significant_relative = np.zeros(len(time_interp)) max_records_around_t = np.zeros(len(time_interp)) for j in xrange(len(...
e970e78a1dfe96220f8ff49a85deccc5dc00f673
3,630,910
from typing import Tuple import random def draw_two(max_n: int) -> Tuple[int, int]: """Draw two different ints given max (mod max).""" i = random.randint(0, max_n) j = (i + random.randint(1, max_n - 1)) % max_n return i, j
9ebb09158c296998c39a2c4e8fc7a18456428fc6
3,630,911
def compareFloats(a, b, rtol=1.0e-5, atol=opscore.RO.SysConst.FAccuracy): """Compares values a and b Returns 0 if the values are approximately equals, i.e.: - |a - b| < atol + (rtol * |a + b|) Else 1 if a > b, -1 if a < b Inputs: - a, b: scalars to be compared (int or float) - atol: absolut...
6ff9e55040bfbefea11ef6f10cdc88b5e2fa7a77
3,630,912
def net_import_share_constraint_rule(backend_model, constraint_group, carrier, what): """ Enforces demand shares of net imports from transmission technologies for groups of locations, on average over the entire model period. Transmission within the group are ignored. The share is relative to ``demand`` ...
30add5ca89d2b995742e52eec759ca9504029e57
3,630,913
def loss_gaussian(X): """ encode X by CNML """ Xmat = np.matrix(X) n, m = Xmat.shape if n == 1: Xmat = Xmat.T n, m = Xmat.shape else: pass if n <= 0: return np.nan Xc = Xmat - np.mean(Xmat, 0) S = np.dot(Xc.T, Xc / n) detS = sl.det(S) l...
b9e7db0b25f8b9b6104d653561b3e13a154a742b
3,630,914
def integrand(x, n): """ Bessel function of first kind and order n. """ return jn(n, x)
6b5dce69f94285518cc6e23b4ae23f22e0e981fc
3,630,915
def get_forms_tuple(*args): """ Converts a string of grammemes to a tuple of two sets: - set of tags for declension - set of tags for refining the word form """ forms = list() specs = list() for arg in args: for key in force_str(arg).split(','): if key in INFL...
9f8264b29e0828ffa01af6da1704d7f9c889e167
3,630,916
def truncate(inputs, channels, data_format): """Slice the inputs to channels if necessary.""" if data_format == 'channels_last': input_channels = inputs.get_shape()[3].value else: assert data_format == 'channels_first' input_channels = inputs.get_shape()[1].value if input_channe...
965574da9af5e85c80ce66ed13b36d13b5cffbef
3,630,917
def do_rating_by_user(parser, token): """ Returns a User's Rating of a Snippet, if any. Example:: {% get_rating_by_user user.id object.id as rating %} """ bits = token.contents.split() if len(bits) != 5: raise template.TemplateSyntaxError("'%s' tag takes exactly four ar...
761e3414bc3c292e315c25d79e1c7417e6f894c7
3,630,918
import os def get_read_counts_total_table(path, pool): """ This table is used for "Fraction of Total Reads that Align to the Human Genome" plot """ full_path = os.path.join(path, AGBM_READ_COUNTS_FILENAME) read_counts_total = pd.read_csv(full_path, sep='\t') col_idx = ~read_counts_total.colum...
dae44903051eabbce1118363fc51c8566861484b
3,630,919
def get_label_funcs_threshold(bin_count=10, lower=1e-9, upper=1e-3, bin_func=bin_func_sum): """ :param bin_count: Number of different thresholds to encode the goes flux into. :param lower: Lower limit for valid goes flux values. :param upper: Upper limit for valid goes flux values. :param bin_func: ...
561dbc5b468b2b657908403ef39e630fe66649d9
3,630,920
def modify_layer(layer, name, norm = None, dropout = None): """Add BatchNorm and/or Dropout on top of `layer`""" if dropout is not None: name = "%s-dropout" % (name) layer = Dropout(dropout, name = name)(layer) if norm is not None: name = "%s-%snorm" % (name, norm) layer =...
169905b19fe29d1beee2b4a3b5a5e97cb9ca9e93
3,630,921
def create_access(terms_to_check, new_term): """ Breaks a new_term up into separate constituent parts so that they can be compared in a check_access test. Returns a list of terms that should be inserted. """ protos = new_term.match.get('protocol', ['any']) sources = new_term.m...
61a3a6b786f61b56698e360a6b6acaf393d0fa15
3,630,922
def versionPropertiesDictionary(sql_row_list): """ versionPropertiesDictionary(sql_row_list) transforms a row gotten via SQL request (list), to a dictionary """ properties_dictionary = \ { "id": sql_row_list[0], "model_id": sql_row_list[1], "version": sql_row_list[2]...
ab8cdd166bf8a187945c44fd416c3a4cf4634d02
3,630,923
def register(): """ Register a new user """ logger.debug('register()') return render_template('register.html', user=None)
9306168e54b6b2bdff532792d1ffa493608cc5b8
3,630,924
import logging def verify_received_aes_key(key: dict, rsa_public_key) -> bool: """ Verifies the AES key received as a dict and passed here is valid. :param dict key: An AES key, as a dictionary. :param rsa_public_key: The RSA public key of the author. :return bool: True if the information is a va...
53d0578d8761a06be260b7a63dff97e123a4e010
3,630,925
def remove_indices(dist_array, indices): """ Remove given indices from dist_array :param dist_array: a flattened version of the dist_matrix in the format of entries (node0/ window0, node1/ window1, distance), usually sorted :param indices: indices which should be removed :return: ""...
3b61645655a19c18889f7a02b8bfda0368091873
3,630,926
def bow_net(data, dict_dim, emb_dim=128, hid_dim=128, hid_dim2=96, class_dim=2): """ Bow net """ # embedding layer emb = fluid.layers.embedding( input=data, size=[dict_dim, emb_dim], param_attr=fluid.ParamAttr(name="@HUB_senta_bow@embedding_0.w_0")) # bow layer bow =...
94c7f0483c98644d943815ba92e00cbee0196e50
3,630,927
def close_story(request): """ Tags: logs+stories --- Closes an open story. --- story_id: in: path type: string required: true """ auth_context = auth_context_from_request(request) # Only available to Owners for now. if not auth_context.is_owner(): raise...
4b28978c99c26f76bbe04d62a55ca22ba9d40676
3,630,928
def convert_dates_to_ISO(date: str, date_2: str): """Assumes both dates are current system year. If the latter one occurs chronologically before the former (i.e given "december 4 2021" and "january 4 2021", january comes first in the year. This means that the second date is likely the next year, so we'll assume tha...
7fd68c06ad5abff67e5bd69c1a23530f985857e0
3,630,929
def findliteralblocks(blocks): """Finds literal blocks and adds a 'type' field to the blocks. Literal blocks are given the type 'literal', all other blocks are given type the 'paragraph'. """ i = 0 while i < len(blocks): # Searching for a block that looks like this: # # ...
43b2472784744e5d1c17b5b4e306b23c953223fa
3,630,930
import argparse def get_parser(): """ Return parser """ parser = argparse.ArgumentParser(description='BioWardrobe Migration', add_help=True) parser.add_argument("-c", "--config", help="Path to the BioWardrobe config file", default="/etc/wardrobe/wardrobe") logging_level = parser.add_mutually_exclusive...
6f72a0ea5891acaf895b0c190b6f1774e1290731
3,630,931
import requests def urlcheck(): """takes all devurls and checks their header return""" urlstatus = [] for elem in get_bundle_dev_url(): appads = "https://" + elem[1] + "/app-ads.txt" try: x = requests.head(appads, timeout=3.5, allow_redirects=True) except requests.excep...
b4f8aa5cdd8cc4aab9b2a4ddf204ab3dd43f0792
3,630,932
def get_vpc_dhcp_options(dhcp_options_id=None,filters=None,tags=None,opts=None): """ Retrieve information about an EC2 DHCP Options configuration. ## Example Usage ### Lookup by DHCP Options ID ```python import pulumi import pulumi_aws as aws example = aws.ec2.get_vpc_dhcp_options(dhc...
05d73c3d230c3e815e47aa8c6134c89efb814439
3,630,933
import os def moduleName(file): """Extract a module name from the python source file name, with appended ':'.""" return os.path.splitext(os.path.split(file)[1])[0] + ":"
4f5035e80ddd3df7a8a93585bebf25e2e3300b49
3,630,934
def ms2str(v): """ Convert a time in milliseconds to a time string. Arguments: v: a time in milliseconds. Returns: A string in the format HH:MM:SS,mmm. """ v, ms = divmod(v, 1000) v, s = divmod(v, 60) h, m = divmod(v, 60) return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
5d50aa072584e5ad17d8bd3d08b0b0813aced819
3,630,935
import operator def regroup(X, N): """ Regroup the rows and columns in X. Rows/Columns that are N apart in X are adjacent in Y. Parameters: X (np.ndarray): Image to be regrouped N (list): Size of 1D DCT performed (could give int) Returns: Y (np.ndarray): Regoruped image """ #...
d4492e71a42a69d86d0e2a1c21bf05d13dfe13d7
3,630,936
def uint_to_two_compl(value: int, length: int) -> int: """Convert int to two complement integer with binary operations.""" if value >> (length - 1) & 1 == 0: # check sign bit return value & (2 ** length - 1) else: return value | (~0 << length)
a0b7bd5192a3f12119ea7ec1a58ca785c37369bf
3,630,937
def synthetic_pattern_program(): """A program that tests pattern matching of `PrimOp` outputs. Returns: program: `instructions.Program`. """ block = instructions.Block( [ instructions.prim_op( [], ("one", ("five", "three")), lambda: (1, (2, 3))), instructions.prim_op...
c3f55b75301604a394d9f0ec01d4198a27f90c8e
3,630,938
def generator(z, out_channel_dim, is_train=True, alpha=0.2): """ Create the generator network :param z: Input z :param out_channel_dim: The number of channels in the output image :param is_train: Boolean if generator is being used for training :param alpha : leaky relu rate :return: The tens...
9bea06f8c78aadc2e9a4287ce44b12422cfead99
3,630,939
import re def manual_filtration(word, neg_list): """作用在 word 上, 若该词为负例则返回 True, 否则返回 False""" pattern_1 = r',|\.|:|;|"' pattern_2 = r'行|示|为|较|见|天|音' pattern_3 = r'切除|标本|摄取|存在|活检|穿刺|开口|引流|胸痛|患者|治疗|不适|受限|疼痛|基本|压缩' pattern_4 = r'^[A-Za-z0-9_]+$' remove_word_list = neg_list + ['病理', '癌', '炎', '占位'...
6957c8a3b86073060ffeded9c5a7c7badf1005cc
3,630,940
def two(f): """Church numeral 2: same as successor(successor(zero))""" "*** YOUR CODE HERE ***" return lambda x: f(f(x))
0ae1c89aca0a3fa85319882d49aea0cc05c12b7a
3,630,941
import warnings def _find_indexes(obj, var_name, min_limit, max_limit, use_dask): """ Function to find array indexes where failing limit tests Parameters ---------- obj : Xarray.Dataset Dataset containing data to use in test var_name : str Variable name to inspect min_limi...
ad59ce154bf056d0ede5b98250fc95265ec83c89
3,630,942
def asinh_grad(orig, grad): """Returns [grad * 1/((1 + (x ^ 2)) ^ (1/2))]""" x = orig.args[0] ones = ones_like(x) return [grad * ones / sqrt(ones + (x * x))]
6cdcc4b0271aa8173059fe165fc77a556da79834
3,630,943
def inject_test_seed(seed, signature, user_data_dir): """Injects the given test seed. Args: seed (str): A variations seed. signature (str): A seed signature. user_data_dir (str): Path to the user data directory used to launch Chrome. Returns: bool: Whether the injection succeeded. """ seed_d...
838c4f0a2bd969327f0733c270659243caa3a881
3,630,944
import math def _scale_stage_depth(stack_args, repeats, depth_multiplier=1.0, depth_trunc='ceil'): """ Per-stage depth scaling Scales the block repeats in each stage. This depth scaling impl maintains compatibility with the EfficientNet scaling method, while allowing sensible scaling for other models ...
e1411f4c62bf5834a994d6c0313ea77e7368ee2c
3,630,945
def tokenize(s): """ Ковертирует строку в питон список токенов """ return s.replace('(',' ( ').replace(')',' ) ').split()
639baad1a6ec7640abe6752ad44e1f8585a9aafe
3,630,946
def vote_entropy(votes, classes): """Calculates the vote entropy for measuring the level of disagreement in QBC. Parameters ---------- votes : array-like, shape (n_samples, n_estimators) The class predicted by the estimators for each sample. classes : array-like, shape (n_classes) ...
2f8232d85fae5511555eba469d7b7c33b375a8e0
3,630,947
def printModelDict(localsDict): """Convert serverConfig model configuration to a dictionary. This writes the dictionary as text. This does not create a usable modelDict, just one to use to print out the dictionary as python code.""" modelDict={} parmsDict={} tcDict={} dbs=DATABASES scTe...
af8450e0d2807198de5f09d3245ff8100f9e8cdf
3,630,948
import ctypes def ira_equinox(jd_tdb, equinox, accuracy=0): """ To compute the intermediate right ascension of the equinox at the input Julian date, using an analytical expression for the accumulated precession in right ascension. For the true equinox, the result is the equation of the origins. ...
ce145a20c623e444623c6ae3f5d7d59910520a82
3,630,949
import os def load_plugins(plugins_folder, verbose=True): """Import all plugins from target folder recursively.""" found_plugins = [] for pack in os.walk(plugins_folder): for filename in pack[2]: if "_" == filename[:1] or ".py" != filename[-3:]: continue ...
f33cb1f4b817136ba9320ceda8174e74d9b4ffcd
3,630,950
from typing import Sequence from typing import Any from typing import Callable from typing import Dict def _generate_steps( episode: Sequence[Any], step_fn: Callable[[Dict[str, Any]], Dict[str, Any]]) -> Dict[str, Any]: """Constructs a dictionary of steps for the given episode. Args: episode: Sequenc...
4ddafb41501a1ab6b61b325ebb8db0c2bd40bf85
3,630,951
def format_results_data(results_data, compute_rank=True): """Formats results_data as sorted list of rows so it can be easily displayed as results_table Appends user and ranks. Side effect: This function modifies objects (i.e. individual results) contained in results_data """ Result = namedtuple(...
6fdceb3a07ebcc23b245e43a2eb3770f67073cd0
3,630,952
def encode_triangle(X, centroids): """ Perform triangle k-means encoding """ X3 = X.reshape(X.shape[0], 1, X.shape[1]) centroids3 = centroids.reshape(1, centroids.shape[0], centroids.shape[1]) z = np.sqrt(((X3 - centroids3) ** 2).sum(2)) means = z.mean(1).reshape(-1, 1) return np.maximum...
98f11930892b61d8a7ee653a4dab677a6d0543d1
3,630,953
def get_user_and_check_password(username, password): """ Called by account controller and/or AuthKit valid_password to return a user from local db """ try: q = Session.query(User).select_from(join(User, UserLogin, User.login_details)) q = q.filter(User.id == make_username(usernam...
3def5ad6bba4486d235d58b4f8f50cf3ac27b734
3,630,954
import hashlib def get_db_for_id(id_value): """ Work out the database number containing a Review record with pk of "id_value". """ # XXX: If we were interested in being able to add databases and do minimal # data moving, it would be better to use a consistent hashing algorithm # here (dist...
7ece564172061e31c61168cba02b034ac2666533
3,630,955
def subclass(request): """Return a Object subclass""" try: params = request.param except AttributeError: params = {} class TestObject(Object): @property def fields(self): return params.get("fields", {}) TestObject.__name__ = params.get("name", "TestObjec...
376578606f20ae8899dba01590675847a2c8e11f
3,630,956
def is_index(file_name: str) -> bool: """Determines if a filename is a proper index name.""" return file_name == "index"
7beb5779b61e25b4467eb7964478c78d44f28931
3,630,957
from typing import List def _recv_n_get_rsp(event: "Event") -> List[str]: """Logging handler when an N-GET-RSP is received. Parameters ---------- event : events.Event The evt.EVT_DIMSE_RECV event that occurred. """ msg = event.message cs = msg.command_set dataset = "None" ...
1ccc8951e212ecbacdd7a9e48986a646c15e9da2
3,630,958
def GenerateShardedFilenames(spec): # pylint:disable=invalid-name """Generate the list of filenames corresponding to the sharding path. Args: spec: Sharding specification. Returns: List of filenames. Raises: ShardError: If spec is not a valid sharded file specification. """ basename, num_sha...
38fe085c7063c80d633221aab9c0159fc8bc68ac
3,630,959
def _tseries_from_nifti_helper(coords, data, TR, filter, normalize, average): """ Helper function for the function time_series_from_nifti, which does the core operations of pulling out data from a data array given coords and then normalizing and averaging if needed """ if coords is not None: ...
1e464b0f54536ab062ae32b49ed821f2d230f45f
3,630,960
import hashlib def hash_short(message, length=16): """ Given Hash Function""" return hashlib.sha1(message).hexdigest()[:length / 4]
bd071674ce5caf382dc73d27835f43409a6a49d2
3,630,961
def feincms_frontend_editing(cms_obj, request): """ {% feincms_frontend_editing feincms_page request %} """ if hasattr(request, 'session') and request.session.get('frontend_editing'): context = template.RequestContext(request, { "feincms_page": cms_obj, 'FEINCMS_ADMIN_ME...
6e1e1e0ee771d4260ffd310f970bf53a045a48ba
3,630,962
def _add_tensor_cores(tt_a, tt_b): """Internal function to be called from add for two TT-tensors. Does the actual assembling of the TT-cores to add two TT-tensors. """ ndims = tt_a.ndims() dtype = tt_a.dtype shape = shapes.lazy_raw_shape(tt_a) a_ranks = shapes.lazy_tt_ranks(tt_a) b_ranks = shapes.lazy_...
07c1c79fff1547afe6c69fc82fe584f418432d8a
3,630,963
from typing import OrderedDict def create_mosaic_iterative(dataset_in, clean_mask=None, no_data=-9999, intermediate_product=None): """ Description: Creates a most recent - oldest mosaic of the input dataset. If no clean mask is given, the 'cf_mask' variable must be included in the input dataset, a...
6ba190145b2b655decd7bdd770abd8a6390b09bc
3,630,964
from typing import Sequence from typing import cast import collections def dicom_file_loader( accept_multiple_files: bool, stop_before_pixels: bool ) -> Sequence["pydicom.Dataset"]: """A Streamlit component that provides DICOM upload functionality. Parameters ---------- accept_multiple_files : ``...
acaf9c54270a67f1893605a9a1d5b101dd02aba6
3,630,965
def get_substrings(source: str): """Get all substrings of a given string Args: string (str): the string to generate the substring from Returns: list: list of substrings """ # the number of substrings per length is the same as the length of the substring # if the characters are...
79f1db4184c51235a9d6beb8437f1647bc993958
3,630,966
import csv def _write_output_csv(reader: csv.DictReader, writer: csv.DictWriter, config: dict) -> list: """Reads each row of a CSV and creates statvars for counts of Incidents, Offenses, Victims and Known Offenders with different bias motivations. Args: reader: CSV dict ...
057820c97100b626171250d4d97f90b07f0c48a7
3,630,967
def get_vehicle_lay_off_engine_acceleration(carla_vehicle): """ Calculate the acceleration a carla vehicle faces by the engine on lay off This respects the following forces: - engine brake force :param carla_vehicle: the carla vehicle :type carla_vehicle: carla.Vehicle :return: acceleratio...
84ca84d75866840e88cc6afdb615cbc0529ea311
3,630,968
from typing import Dict from typing import Any import sys def create_data(name: str) -> Dict[str, Any]: """Arbitrary function that returns a dictionary. This demonstration uses pydantic, but any dictionary can be tested! """ return User(id=sys.maxsize, name=name).dict()
8d5e04da128e4ff55fcb3d2fc375f72ab876246b
3,630,969
def _run_docker_shell_script(script_name, docker_dir, trailing_args=None, env_variables=dict()): """ script_name (String) filename of a script in the nest/docker/ directory docker_dir (String) directory of docker scripts in the nest repo. expected to be /code_live/docker, but may be different is...
a68d85a6affd1905d312b91ccc85475c30809c22
3,630,970
def _create_functional_connect_edges_dynamic(n_node, is_edge_func): """Creates complete edges for a graph with `n_node`. Args: n_node: (integer scalar `Tensor`) The number of nodes. is_edge_func: (bool) callable(sender, receiver) that returns tf.bool if connected. Must broadcast. Returns: A di...
338b7a240f516703853af8f810f56e313fcb2b99
3,630,971
import os def _BreakoutFilesByLinter(files): """Maps a linter method to the list of files to lint.""" map_to_return = {} for f in files: extension = os.path.splitext(f)[1] if extension in PYTHON_EXTENSIONS: pylint_list = map_to_return.setdefault(_PylintFiles, []) pylint_list.append(f) el...
0f99bd166c9f1cfe73b10b745df3bca7ef4d3306
3,630,972
from operator import matmul def simulateBERParallel(codes, channelfun, params, printValue=True): """ Simulates BER values at multiple SNRs, where the massively parallel algorithm is used. This implementation is especially designed for cupy. Args: codes (ndarray): an input codebook, which is gener...
89df47bbe05b19f32276d608c260ae51ea9c7f28
3,630,973
from datetime import datetime import json def modify_app_description(s, base_url, app_id, description): """ Modifies the description of an app """ rjson = app_full(s, base_url, app_id)[1] rjson["modifiedDate"] = str( ((datetime.today()) + timedelta(days=1)).isoformat() + "Z" ) rjs...
e4f1529a31dd982b2ccf56d31542139f6cc564ef
3,630,974
def search_tag(resource_info, tag_key): """Search tag in tag list by given tag key.""" return next( (tag["Value"] for tag in resource_info.get("Tags", []) if tag["Key"] == tag_key), None, )
5945631a3de7032c62c493369e82dd330ef2bc47
3,630,975
def compute_GARCH_price(theta, num_periods, init_price, init_sigma, risk_free_rate, num_simulations=50000): """ Compute asset price at period t + s (s periods ahead) given estimated theta...
de6a6aca57bb6ea63cfa39221522798322bafdda
3,630,976
def create_order_nb(size: float, price: float, size_type: int = SizeType.Amount, direction: int = Direction.All, fees: float = 0., fixed_fees: float = 0., slippage: float = 0., min...
660940e9258f1b43352cf5e2b78e083b0c984bc7
3,630,977
def generate_noise_2d_fft_filter(F, randstate=None, seed=None, fft_method=None, domain="spatial"): """Produces a field of correlated noise using global Fourier filtering. Parameters ---------- F : dict A filter object returned by :py:func:`pysteps.noise...
4c4dbe8b22cf73730bff84affa5ff592e0484a1c
3,630,978
import os def _get_image_files_and_labels(name, csv_path, image_dir): """Process input and get the image file paths, image ids and the labels. Args: name: 'train' or 'test'. csv_path: path to the Google-landmark Dataset csv Data Sources files. image_dir: directory that stores downloaded images. Re...
fdde6e48c859579c41086e17c128e463145a430c
3,630,979
def get_spending_features(txn, windows_size=[1, 7, 30]): """ This function computes: - the cumulative number of transactions for a customer for 1, 7 and 30 days - the cumulative average transaction amount for a customer for 1, 7 and 30 days Args: txn: grouped transactions of custome...
b648df3d1217074edec455a416e0eb698d8069ee
3,630,980
def break_up(expr): """ breaks up an expression with nested parenthesis into sub expressions with no parenthesis, with the innermost expressions first, that needs to be calculated before doing the outer expression. also replaces the statement with a single symbol in the larger expression """ p=0 new_ex...
7f28290a3dadfec2bd42696bcf7be348288a7bca
3,630,981
def fft_operation(file_path): """ FFT operation :param file_path: Original wav file path :return: freqs, 20 * log10(fft/max_fft), name """ wave_data, nchannels, sample_width, framerate, numframes = read_file(file_path) abs_fft = np.abs(np.fft.fft(wave_data)) normalized_abs_fft = abs_fft...
75c672298e3d8650e79ee56ce540006102a1b375
3,630,982
import six def _expand_expected_codes(codes): """Expand the expected code string in set of codes. 200-204 -> 200, 201, 202, 204 200, 203 -> 200, 203 """ retval = set() for code in codes.replace(',', ' ').split(' '): code = code.strip() if not code: continue ...
52056db88bf14352d4cda2411f25855457defbd7
3,630,983
from typing import Optional from pathlib import Path import importlib def predict( seq: np.ndarray, aa_cut: Optional[np.ndarray] = None, percent_peptide: Optional[np.ndarray] = None, model: Optional[GradientBoostingRegressor] = None, model_file: Optional[Path] = None, pam_audit: bool = True, ...
50cb3adc03d017e7e94353dd9a9b15166e616d4a
3,630,984
import collections def _is_proper_sequence(seq): """Returns is seq is sequence and not string.""" return (isinstance(seq, collections.abc.Sequence) and not isinstance(seq, str))
d5f1f211330a9f4928b8cc8c7407adaf705fd4b2
3,630,985
def sigmoid(mat, target = None): """ Apply the logistic sigmoid to each element of the matrix mat. """ if not target: target = mat err_code = _cudamat.apply_sigmoid(mat.p_mat, target.p_mat) if err_code: raise generate_exception(err_code) return target
ba02fe038ce1d491b40b605baf43e4bf8afda057
3,630,986
def mutation_modify_controlaction(controlaction_id: str, actionstatus: ActionStatusType, error: str = None): """Returns a mutation for modifying the status and errors of the ControlAction Arguments: controlaction_id: The unique identifier of the ControlAction. actionstatus: the status to update ...
f7ef2c0174fe8c31505d2397df38602c9cee46ac
3,630,987
def get_colours(time, flux, data, nuv=[nuvwave, nuvtrans], u=[uwave, utrans], r=[rwave, rtrans], filter_pairs=None): """" Calculates the colours of a given sfh fluxes across time given the BC03 models from the magnitudes of the SED. :time: Array of times at which the colours should be calcu...
d03c33822918c50d30db06284fbe56571886228c
3,630,988
def loginpage(): """A route to login the user.""" year = date.today().year return render_template("website/login.html", base=get_base_data(year), route=Routes, year=year, github_enabled=is_github_supp...
282630fb7c4585cf0321c3fa3fc3ce55bfc33c8e
3,630,989
from hypothesis.internal.conjecture.shrinker import dfa_replacement, sort_key import math def learn_a_new_dfa(runner, u, v, predicate): """Given two buffers ``u`` and ``v```, learn a DFA that will allow the shrinker to normalise them better. ``u`` and ``v`` should not currently shrink to the same test cas...
ff0ba6d5831099d8d5f392b3cd7dec59ac3a3663
3,630,990
def generate_corrected_profiles (corr_factor, fwd_border_dicts, fwd_profile, plasmid_length, scale): """ Correct the edges of the transcription profiles """ # New profile to hold the normalised data Normalized_fwd_profile = np.ones(plasmid_length)*scale # Cycle through each transcript (no idea why this is a dict) ...
d7fbd70e7651b7467d7cc6e754bb4baad1e8d2ca
3,630,991
import json import sys import traceback def base_handler(event: Event, loader_cls: type) -> Response: """Handler which is called when accessing the endpoint.""" response: Response = {"statusCode": 200, "body": json.dumps("")} db_helper = DatabaseHelper() try: point = ( Point(event[...
b1336c6ae71724284d5221cce3858e31070b68d1
3,630,992
import os def publish_image_dir(): """ checks if publishing of images configured and if so it returns the directory to publish to (full path) or None """ root_dir = publish_root_dir() if root_dir != None: rel_dir = get_value_with_default(['publish', 'package_dir'], 'images') ...
19ac151adb31488b300e08db34fea617d0e9b2ff
3,630,993
def transforToManagerProxyObject(manager, data): """将不转换dict中的key 只支持基础数据,dict,list和tuple tuple将会转换成list result = data """ if isinstance(data, dict): result = manager.dict() for key in data: result[key] = transforToManagerProxyObject(manager, data[key]) elif isinstance(data, list) or isinstance(data, tupl...
d9b0c17b1e1eb50a9bede908130d8444422b8fd4
3,630,994
import json import time def get_new_account_id(event): """Return account id for new account events.""" create_account_status_id = ( event["detail"] .get("responseElements", {}) .get("createAccountStatus", {})["id"] # fmt: no ) LOG.info("createAccountStatus = %s", create_accoun...
e782e930d09b2f02b10547e5a39e14bba852d896
3,630,995
from tvrenamer.common import tools def list_opts(): """Returns a list of oslo_config options available in the library. The returned list includes all oslo_config options which may be registered at runtime by the library. Each element of the list is a tuple. The first element is the name of the gr...
a650cf9fb8d3bfd0ee60e6301463ff62d3842f8f
3,630,996
from datetime import datetime def tokenize_for_t5_advice_training(encoder, subreddit=None, date=None, title=None, selftext=None, body=None): """ Tokenizes the post title / post selftext / comment body. If it's too long we'll cut some paragraphs at random from the selfte...
5716eb12d2f1c7773fcb49abfe7c203375ef9c65
3,630,997
def hvdisp_plot_records_2d(records, to_pe, config, t_reference, time_stream=None, tools=(x_zoom_wheel(), 'xpan'), default_tools=('save', 'pan', 'box_zoom', 's...
0fa08d4f71ef08c35a2121e4716bce213e39d9d8
3,630,998
import re def join_url(url, *paths): """ :param url: api url :param paths: endpoint :return: full url """ for path in paths: url = re.sub(r"/?$", re.sub(r"^/?", "/", path), url) return url
32e085acc64590901afcf3d4ded47f8be7d40119
3,630,999