content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def detect_inner_pix(half_binary, outer_pix, side): """Relative (r, c) coordinates of the inner pixel (between wing and body) Arguments --------- half_binary : 2D array binary image of left/right wing outer_pix : 1D array (r, c) coordinates (relative) of the outer pixel side : s...
2ec6d52d1464a606165af93e655e47a2badea6f3
3,600,900
def decode_list(in_str: str): """ Decode a list of strings from 2-digit decimal encoding separated by 00's (Decoding function provided in Scratch Library) """ return [decode_str(i) for i in in_str.split('00')]
ba8a7cbb05d8b7cd6ea4e142f4dfb3e8e51b1f59
3,600,901
import math def hargreaves_equation(lat, doy, t_min, t_max): """ Calculate the reference evapotranspiration using the Hargreaves equation (Allen et al. 1998). This equation should be used when solar radiation data, relative humidity data, and/or wind speed data are missing. NOTE: This equati...
25ae68458e4a5fb1783e47f38615a662ced7aa2d
3,600,902
def justify_bytes(b: bytes, length: int) -> bytes: """ Same function than text_formatter.justify.justify(), but taking bytes instead of standard strings. """ checkBytes(b) # Just like justify(), this # function is not completed yet. return b
e56aa1ca6ef0786fb55463dd6bea622b0ad78557
3,600,903
def on_epoch_start(func): """A function decorator that wraps a Callable inside the NeMoCallback object and runs the function with the on_epoch_start callback event. """ class NeMoCallbackWrapper(NeMoCallback): def __init__(self, my_func): self._func = my_func def on_epoch_s...
ee7bbd81799dac57355a5946f025919a187bf64c
3,600,904
import os def plot_map(map_name="de_dust2", map_type="original", dark=False): """Plots the map""" if map_type == "original": map_bg = imageio.imread( os.path.join(os.path.dirname(__file__), "") + """../data/map/{0}.png""".format(map_name) ) else: col = "ligh...
184693bfc05edfd62e9345434150733f5885b167
3,600,905
import os def locate_blockmesh_template(): """the function uses the StoveOpt path and blockmesh template name to open the template version of the blockMeshDict file for editing in the system folder Args: None Returns: blockmesh_template (str): full file path where blockmesh template lives ...
d2fdbdf5890551f1e808217d70076654ce59e96a
3,600,906
def get_columns(invoice_list): """return columns based on filters""" columns = [ _("Item") + ":Data:350", _("Invoice") + ":Link/Purchase Invoice:120", _("Posting Date") + ":Date:80", _("Vendor") + ":Link/Supplier:120", _("Bill No") + "::120", _("Bill Date") + ":Date:80", _("Grand Total") + ":Currency/cu...
12675f8c8e5ae87333b962c05cb17662807c3f4d
3,600,907
def leaderboard_delete(request, pk=None): """Special view for deleting leaderboards from across the site kwargs: pk -- a leaderboard id (primary key) """ template = "pages/deleteLeaderboard.html" if pk is not None and request.user.is_authenticated: leaderboard = get_object_or_404(Le...
410e86a570fac52e7b5b4cbf74d5cfcc82b616c8
3,600,908
def bboxes_crop_or_pad(bboxes, xs, ys, height, width, offset_y, offset_x, target_height, target_width): """Adapt bounding boxes to crop or pad operations. Coordinates are always supposed to be relative to the image. Arguments: bboxe...
17e72d2c4c03065bafad918044163c63505de02b
3,600,909
def create_Adam_op(loss, alpha, beta1, beta2, epsilon): """ adam """ return tf.train.AdamOptimizer(alpha, beta1, beta2, epsilon).minimize(loss)
3299f4b931b505d501a77fd207d9e7f655ef462c
3,600,910
def run_operate(model_data, timings, backend, build_only): """ For use when mode is 'operate', to allow the model to be built, edited, and iteratively run within Pyomo. """ log_time(logger, timings, 'run_start', comment='Backend: starting model run in operational mode') defaults =...
60d25fbb9214d7498881ab55bdfdcaa8c7deaaa9
3,600,911
def count_query(query): """ The Google Cloud Datastore API doesn't expose a way to count a query the traditional method of doing a keys-only query is apparently actually slower than this method """ # Largest 32 bit number, fairly arbitrary but I've seen Java Cloud Datastore # co...
6ad65b75838048cac0a0360098972427034e6cca
3,600,912
from os.path import basename import ipdb def convert_to_example_wmosh(image_data, image_path, height, width, label, center, gt3d, pose, shape, scale_factors, start_pt, cam): """Build an Example proto for an image example. Args: image_data: string...
227d7996d4f570445abdd8b110903c5775da1c17
3,600,913
import argparse def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text', metavar='str', help='Input...
c65de376ca46b1c182243eaba3303816e9dd4ac2
3,600,914
import pandas as pd import os def prostitutes(path): """Parent-Duchatelet's time-series data on the number of prostitutes in Paris A table indicating month by month, for the years 1812-1854, the number of prostitutes on the registers of the administration of the city of Paris. A data frame with 516 observ...
c633b63324296c1b6b4c51789fceb6e0d4d7d44e
3,600,915
import os import sys def get_vmvalue_from_procfs(vmkey='VmSize', pid=None): """Return virtual memory value (in bytes) for the given pid using the /proc filesystem. If pid is not given, it default to the current process pid. Available keys are: VmSize, VmRSS (default), VmStk """ if pid is None: ...
3c90c49e1596c2ae9de4259d5b39adb8957cf11d
3,600,916
import torch def log_importance_weight_matrix(batch_size, dataset_size): """ Calculates a log importance weight matrix Parameters ---------- batch_size: int number of training images in the batch dataset_size: int number of training images in the dataset """ N = dataset_s...
78555bd2e35bae8587602e43698c98bb0f463b21
3,600,917
def fetch_items(parent_key, valid_flag=None): """ Fetch the items by parent_key :param parent_key|str: :rtype list of Registry: """ query = Registry.all() if parent_key is not None: query.filter("parent_key =", parent_key) if valid_flag is not None: qu...
89715533cb5edc28c6c15daaf9047772a4634456
3,600,918
import sys import glob def serial_ports(): """List serial port names. raises EnvironmentError: On unsupported or unknown platforms returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] ...
3ce89c4c5b7f38ece5065e396d82cdf662dda947
3,600,919
from typing import Sequence def shard_args(devices: Sequence[xb.xla_client.Device], indices: Sequence[Sequence[Index]], args) -> Sequence[Sequence[xb.xla_client.Buffer]]: """Shard each argument data array along its leading axis. Args: devices: sequence of Devices mapping replica...
a805a542d4b3e79997900b25dfcd40216ab57401
3,600,920
def blog_get_mkd_attachment(post): """ Attempts to find a vimpress tag containing a URL for a markdown attachment and parses it. @params post - the content of a post @returns a dictionary with the attachment's content and URL """ attach = dict() try: lead = post.rindex("<!-- ") ...
f005ec7b44a3beb0016ab37df457800f036326fe
3,600,921
def algo2(x,y): """ Trouve le nombre de carres dans deux listes pour chaque absisse Args: x (list): liste des cordonnees en x y (lsit): liste des coordonnees en y Returns: int: Nombre de carres """ liste_x = [] liste_y = [] resul = 0 '''Crée une liste qui co...
d2e1c47f98c912fff3f02f759176b81b479ca659
3,600,922
def setop2d_functor(op): """Return a binary function that will perform the passed 1-dimensional set operation on 2-dimensional array arguments. """ if op not in (np.intersect1d, np.union1d, np.setdiff1d): raise ValueError def setop2d(a, b): # inspired by https://stackoverflow.com/questi...
2f4da344f875df22b15b1a441b05ce60f946f339
3,600,923
import joblib from pathlib import Path def _test_clean(): """ Ordinal Encoding for Test Categorical Columns. Yields ------ test_clean: 'datasets/test_clean.csv' Returns ------- test_clean. """ test_set = pd.read_csv('datasets/test_set.csv') cat_data = test_set[CA...
76174aa63f9eb576008b97d74ba0e0cb19888fd0
3,600,924
def compose_tbl_filename_from_config(table_cfg, default=None): """compose a file name based on a table config. This function calls ``compose_tbl_filename()``. Parameters ---------- table_cfg : dict A table config default : dict, optional A default config Returns -----...
08865e36201b843c134a2bdb9cb1d01433cbb839
3,600,925
def abbreviate_agency(agency_name): """ Abbreviate the name of the agency for storage. """ return NAME_TO_ABBR[agency_name]
cdc1fd7be6417bf2a488e95b00477c0180bbec3a
3,600,926
def exp_decay_k(x, width=1., height=None, mode="causal"): """ Exponential decay kernel function Normalized by area if ``height=None`` (if possible), otherwise `height` is the value at 0. Mode determines value for ``x<0``: - ``'causal'`` - it's 0 for ``x<0``; - ``'step'`` - it's...
b624cf6951e1ceb3458cb4c857d284a084ff2aaa
3,600,927
def check_board(board): """ This function is to check if the board is in correct format The length of the board must be 9 (Rows) Each row must have 9 elements (Columns) Each element must be between 1 - 9 """ check_if_the_board_is_correct = True if len(board) == 9: ...
f5940470c6158bfd500aca40a9f89c715d8592ac
3,600,928
import re def remove_url(txt): """Replace URLs found in a text string with nothing (i.e. it will remove the URL from the string). Parameters ---------- txt : string A text string that you want to parse and remove urls. Returns ------- The same txt string with url's removed. ...
8d1b8b89cb65ca7761c093dc388d1f19729137e7
3,600,929
import time def findLoadOnBus(mirror, Busnum, Id=None): """Find first load on bus unless Id specified Note that Ids are typically a strings i.e. '2' """ tic = time.time() if not mirror.searchDict: for x in range(len(mirror.Load)): if mirror.Load[x].Busnum == Busnum: ...
1b81f7495b5ea5fe060d7eead92db10510b76c97
3,600,930
import os import sys def load(dir=FORMAT_DIRECTORY): """Load format processing modules.""" # Load everything matching the naming conventions. modules = [] for fn in (f for f in os.listdir(dir) if _is_format_module(f)): module = _load_format_module(dir, fn) if module is None: ...
9d3ad1b6910b10f8e7812fd4aa15e8492d11cd94
3,600,931
def get_timestamp_drop_sql(variant): """ Generate a list of statements to drop the timestamp update triggers """ sql = [] if "postgres" in variant: sql.append("DROP FUNCTION IF EXISTS update_history_update_time() CASCADE;") else: for operation in ["INSERT", "UPDATE", "DELETE"]:...
0d64fc2ae8b2678f87cc02d1448f11e824b79bd9
3,600,932
def _check_proper_permutation(a): """ Check to see if the matrix has been properly permuted. This should be redundent to what is already built into 'fix_top'. Parameters ---------- a : numpy.ndarray A matrix. Returns ------- bool """ t = len(a) for ind in range...
c715e41eb8ef68add832b7a9e7a082ceba25ad88
3,600,933
def get_package_format_names_with_distros(): """Get names for package formats that support distributions.""" return get_package_format_names(lambda k, v: "distribution" in v)
b9e3f03fa4ee9742b8c7bd81686727b5e687352e
3,600,934
def distance_PBC(a: np.ndarray, b: np.ndarray, lattice: np.ndarray) -> float: """Compute the distance between a and b on the lattice with periodic BCs. Parameters ---------- a, b : np.array points in cartesian coordinates lattice : np.array lattice to use to compute PBC Returns...
4bedf4690c0f975c71b85e86ae601b340baf3277
3,600,935
def release_gamepad_input() -> None: """release_gamepad_input() -> None (internal) Resumes normal gamepad event processing. """ return None
fe4ea812ba64d50dec7d67c85f93199af8a27b30
3,600,936
def pretty_print_fmt_containers(containers, args): """ Pretty print container data in regular long form, displaying all data. :param containers: The containers found from docker ps. :type containers: list :param args: Parsed arguments from cli. :type args: <Namespace> obj """ selected_i...
1c75181ac4fb6e833b790ba0bf6dc1cdaec42e58
3,600,937
def StyleGAN(const_shape, resolution, n_dense=2, n_styles=5, middle_input_synth=None, microstyle_layer=6): """ :param const_shape: :param middle_input_synth: None - full network; 8, 16, ... - input resolution :return: """ def G_mapping(input_, truncation_psi, mapping_layers, dlatent_broadcast, ...
54ebe63adff29c791655866619b4d0d4cea37734
3,600,938
def _FetchMapTile(url): """Fetches and returns a tile, given an url. Args: url: the exact url of the tile to fetch. Returns: The tile bitmap. """ try: fp = urllib.urlopen(url) f = StringIO.StringIO(fp.read()) im_tile = Image.open(f) im_tile.load() except IOError, e: im_tile...
a2053be7c91b1581315cef744348e9e499388fdb
3,600,939
def _bin_str_to_int(bin_str): """ This function returns integere value extracted from binary string of length 16. :param bin_str: :return: """ if len(bin_str) <= 16: return int(bin_str, 2) else: None
42ea2d6858d9e41f0dcffb9711ea287c8d051f07
3,600,940
def get_FN026_cache(lake=None): """Return a dictionary of dictionaries that reference the spaces available for each creel. useage: fn026 = FN026_cache[prj_cd][space_code] """ FN026_cache = {} if lake: spaces = FN026.objects.filter(creel__lake__abbrev=lake).select_related("creel")...
8bbb6ad1a9fdc244658ee21b7ddb35b7cdefa4b0
3,600,941
from datagears.core.stores import FeatureStore def feature_store() -> FeatureStoreAPI: """Default feature store fixture.""" return FeatureStore()
2611e0fdac74c722d7b0690416dd8c2f63fe5281
3,600,942
def str_to_bytes(s): """convert string to byte unit. Case insensitive. >>> str_to_bytes('2GB') 2147483648 >>> str_to_bytes('1kb') 1024 """ s = s.replace(' ', '') if s[-1].isalpha() and s[-2].isalpha(): _unit = s[-2:].upper() _num = s[:-2] elif s[-1].isalpha(): _unit = s[-1].upper() ...
71bef1d7a81fad44a00deb268fba83dac1ed633e
3,600,943
import sympy def guard(clusters): """ Return a ClusterGroup containing a new PartialCluster for each conditional expression encountered in ``clusters``. """ processed = ClusterGroup() for c in clusters: free = [] for e in c.exprs: if e.conditionals: ...
1dc3f1f922b65b493a426f9424dd441044a921c5
3,600,944
def select_first_node(g): """ :param g: the graph :return: the first node of the node sequence based on which the graph will be partitioned. We select the first node as the node which has the lowest degree """ all_degrees = [] node_list = list(range(0, len(g))) for node in node_list: ...
769a36437e38b19984f88f510b544c22df984106
3,600,945
import os def get_metadata_id(platform_code: str, format: str='json'): """ Get the metadata values from the input platform_code (the ID). Parameters ---------- platform_code: str Platform code Returns ------- (response, status_code): (dict, int) Th...
6440509e519e3f5a05003bbee7b84c05e13e5a39
3,600,946
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ Same as `django.core.urlresolvers.reverse`, but optionally takes a request and returns a fully qualified URL, using the request to get the base URL. """ if format is not None: kwargs = kwargs or {} ...
d1048fe8f08a6a23b8ed00fed47b4d10012a670b
3,600,947
def get_subsequences(sequence): """ Get length k-1 subsequences of length k sequence >>> get_subsequences((('A', 'B'), ('C',))) [(('A', 'B'),), (('A',), ('C',)), (('B',), ('C',))] >>> get_subsequences((('A', 'B'), ('C',), ('D', 'E'))) [(('A', 'B'), ('C',), ('D',)), (('A', 'B'), ('C',), ('E',)),...
7f25a3339d7b73eda1d56b7c4cb7941adc17adad
3,600,948
import scipy import numpy def deleterowcol(A: scipy.sparse.csc_matrix, delrow: numpy.ndarray, delcol: numpy.ndarray) -> scipy.sparse.csc_matrix: """ Delete the specified rows and columns from csc sparse matrix A. Assumes that matrix is in symmetric csc form! Parameters ---------...
0d62c07226eb7cf10a0ff0635d3c80be4850d23c
3,600,949
import math def determine_camera_orientation(obj_pos, gantry_pos): """ Calculates the orientation of the camera for a given object position and gantry position. obj_pos: object position in world frame. numpy array of size (3,), in cm gantry_pos: gantry position in world frame. numpy array of size ...
97fc80c1a1fdeea22e62709557eaee460dbac0a7
3,600,950
import typing import os def find(root_dir: str, name: str) -> typing.Optional[str]: """ recurse through the desired directory, and return a py.path.local object that matches that name. """ for root, _, file_names in os.walk(root_dir): if name in file_names: return os.path.join(...
08657d7a0a20137a283d20af73f39697f0cbdf86
3,600,951
from typing import List def get_all_duplicates(df: pd.DataFrame) -> List: """Find the subject ids of all subjects where the `iauname` metadata field is the same as one or more other subjects Note: classifications.csv only lists subjects with at least one classification, so run this often. Args: ...
700d0088ff11fc631b65a07e711411b375245b2b
3,600,952
def expand_line(line, var_dict): """ Expand one line of text by substituting environment and user variables, as well as variables in 'var_dict'. """ line = expandvars(expanduser(line)) if "$" not in line: return line for key, val in var_dict.items(): line = line.replace(var_r...
e48f73c9641789f690c385d3e61e166d6c64a33e
3,600,953
def publicKeyEncrypt(recipientKeyfile, message): """ Applies public key (hybrid) encryption to a given message when supplied with a path to a public key (RSA in PEM format). """ # Load the recipients pubkey from a PEM file with open(recipientKeyfile, 'rb') as f: recipientKey = RSA.impor...
6cdc0a4b39a7a1ce418dc5973fff748fbac6bf33
3,600,954
import sys def get_keyword_list(file_name): """获取文件中的关键词列表""" with open(file_name, 'rb') as f: try: lines = f.read().splitlines() lines = [line.decode('utf-8-sig') for line in lines] except UnicodeDecodeError: print(u'%s文件应为utf-8编码,请先将文件编码转为utf-8再运行程序', file...
2d3b2c0feb0fb43dd52cba83ce45ffb6722ad6c4
3,600,955
def chroma_to_tonnetz( C ): """Transforms chromagram to Tonnetz (Harte, Sandler, 2006).""" N = C.shape[0] T = np.zeros((N,6)) r1 = 1 # Fifths r2 = 1 # Minor r3 = 0.5 # Major # Generate Transformation matrix phi = np.zeros((6,12)) for i in range(6): for j in ran...
92b461b1d5cecd77296afcb5580ad31a77ef509d
3,600,956
def generate_aliases(aliases, cfg): """Generate aliases according to command line and level generation.""" def process(aliased, what, method): checking = {k: method(f) for k, f in what.items()} if all_unique_values(aliased, checking): return checking return what def remo...
3e954c78bc12ec42e7e013a1c917bc14a578c007
3,600,957
def init_grid_hdf(init_region, h5file, overlap_thresh, crd_sys, intr_prms=None, base_grp="rapidpe_grids"): """ Set up a new HDF5 file (h5file), truncating any existing file with this name. A new 'folder' called 'base_grp' is set up and the initial region with attribute 'overlap_thresh' is set up under it. "...
a700ad338d5469cd5c44704f14ed14dbe5d76908
3,600,958
def integrated_time(sampler,w, low=10, high=None, step=1, c=2, full_output=False, axis=0, fast=False): """Estimate the integrated autocorrelation time of a time series. This estimate uses the iterative procedure described on page 16 of `Sokal's notes <http://www.stat.unc.edu/faculty...
10ae57c452ce0ce94be9cc17456e30a52fa508b3
3,600,959
def grasp_dataset_rotation_to_xyz_theta(rotation, verbose=0): """Convert a rotation to an angle axis theta specifically for brainrobotdata From above, a rotation to the right should be a positive theta, and a rotation to the left negative theta. The initial pose is with the z axis pointing down, the y ...
a8ebc763d700f24ba958c3f8878f03363d4ee147
3,600,960
def _get_three_wdr_with_flag_group_and_shift(asm_str): """decode the full BN standard format with wd, ws1 and optional flag group and possibly shifted rs2 (e.g.: "w21, w5, w7 >> 128")""" substr = asm_str.split(',') if not (len(substr) == 3 or len(substr) == 4): raise SyntaxError('Syntax error in...
19f206d83ce25e3b4ee1208e45aec7c9da3c8f54
3,600,961
def _logsumexp_and_conditionalprobs(array): """return logsumexp and conditional probabilities from array a that has the same shape as the discrete data in dummy-representation""" exp_shifted, a_max = _exp_shiftedmax(array, axis=1) summed = np.sum(exp_shifted, axis=1, keepdims=True) # entries always > ...
5c6a56bf927089d423244a91966db82d53939e25
3,600,962
def _flatten(coll): """ Flatten list and convert elements to int """ if isinstance(coll, list): return [int(a) for i in coll for a in _flatten(i)] else: return [coll]
a6f1dee42a5c881e4cf4496283f248a230f38465
3,600,963
def random_rotation(patch, low_bound=5, high_bound=89, verbose=0): """ Rotates randomly the input, angle between low_bound and high_bound. :param patch: List of 2 or 3 inputs (ndarrays) [image, mask, (weights)] :param low_bound: Int, lower bound of the randomly selected rotation angle. :param high_b...
b4bc8fa109e2832e67ae0ab4f56069a81ad473b1
3,600,964
def augment_parser(parser): """Augment parser from sequential wrapper with parallel wrapper""" group = parser.add_argument_group("Parallel Options", "Configuration of parallel execution") group.add_argument( "--threads", type=int, default=1, help="Number of threads to use fo...
481e0edc9e8d90ccbc5f0d71ef201ccd9ac23a01
3,600,965
from typing import Iterable from typing import Dict def vlad_histograms(images: Iterable[str], data: DataSetBase) -> Dict[str, np.ndarray]: """Construct VLAD histograms from the image features. Returns a dictionary of VLAD vectors for the images. """ batch_size = 4 vlads = context.parallel_map( ...
88f1c851915126cbe49cdf411d994afab287de18
3,600,966
def get_local_absolute_jitter(frequencies, p_floor, p_ceil, max_p_factor): """Given a sequence of frequencies, and some period conditions, compute the local absolute jitter, as per https://royalsocietypublishing.org/action/downloadSupplement?doi=10.1098%2Frsif.2010.0456&file=rsif20100456supp1.pdf Args...
3558c35fd9a1358c3220e32ddeaa78a8c56713d3
3,600,967
def impute_times(final, times_open, times_closed, columns, imputation_method="mean"): """ Impute open work items times with different methods :param final: Complete preprocessed dataframe :param times_open: Dataframe of work items that are not closed :param times_closed: Dataframe of work items that...
b176045cbc8bda516b2248f61db439cfad3f9a04
3,600,968
def complete_line(tile, row, tiles): """ Complete the line of tiles """ line = [tile] # Search before the start until we can't find any more try: if row: for x in xrange(tile[2] - 1, MIN_X - 1, -1): line.append(find_tile(x, tile[3], tiles)) else: ...
8a7cb1a2fd5991243f0c80ea829579aa3f59d782
3,600,969
import os import logging import torch def get_dataloaders(opt): """creates and returns the stock dataset and dataloaders, either with train/val split, or train+val/test split. :param opt: :return: train_loader, train_dataset, test_loader, test_dataset - corresponds to validation or test set depen...
8308e8b42b4109f4f6eeaca3e00c20739281b158
3,600,970
import os def _load_secret_yaml(secret_path: str) -> JSON_TYPE: """Load the secrets yaml from path.""" secret_path = os.path.join(secret_path, SECRET_YAML) if secret_path in _SECRET_CACHE: return _SECRET_CACHE[secret_path] _LOGGER.debug("Loading %s", secret_path) try: secrets = lo...
40337d27b449d7ca80c77734c1856f09e93bd6ea
3,600,971
def to_float_hours(hours, minutes, seconds): """ (int, int, int) -> float Return the total number of hours in the specified number of hours, minutes, and seconds. Precondition: 0 <= minutes < 60 and 0 <= seconds < 60 >>> to_float_hours(0, 15, 0) 0.25 >>> to_float_hours(2, 45, 9) 2.7...
f94f37585929fc45f4b417ab63ca9b7b501a2e57
3,600,972
def soft_round_conditional_mean(inputs, alpha): """Conditional mean of inputs given noisy soft rounded values. Computes g(z) = E[Y | s(Y) + U = z] where s is the soft-rounding function, U is uniform between -0.5 and 0.5 and `Y` is considered uniform when truncated to the interval [z-0.5, z+0.5]. This is des...
e473d5fce4e13e5618016fa82c2d6fa7eb9da1d2
3,600,973
import string def get_abbr_ratio(text, known_abbreviatures=None): """Returns the percentage of dissambiguated abbreviations of the text. INPUT: Textual data, [Abbreviatures already identified] OUTPUT: Percentage of identified abbreviatures""" spacy.prefer_gpu() nlp = spacy.load('en_core_sci_md') ...
7a5315e2e840b0e00c5147410f24780b024e356c
3,600,974
def print_policy_analysis(policies, game, verbose=False): """Function printing policy diversity within game's known policies. Warning : only works with deterministic policies. Args: policies: List of list of policies (One list per game player) game: OpenSpiel game object. verbose: Whether to print po...
d899fe3be974e15a9bb3bfe9a22f36e025d756e5
3,600,975
import re def decode_html(html_str): """Un-escape or decode HTML strings to more usable Python strings. From here: http://wiki.python.org/moin/EscapingHtml """ return re.sub('&(%s);' % '|'.join(name2codepoint), lambda m: unichr(name2codepoint[m.group(1)]), html_str)
3995e9f158d7e91e2a67bca4081d55cd696a4bb7
3,600,976
import torch def get_pose_estimation_prediction(config, pose_model, image, centers, scales, transform, device): """Predict the 2D human pose using the hrnet model Args: config ([type]): [description] pose_model ([type]): [description] image ([type]): [description] centers ...
e26b7b59dd38d0b823d7ebb31b935321367ca8b9
3,600,977
def fit_simulaid(phi): """ DEPRECATED AND WORKING FOR SMALL NUMBER OF SAMPLES -- Fit theta such as: phi_i = theta * i + phi_0 (E) Solving the system: | SUM(E) | SUM(E*i for i) that can be written: | a11 * theta + a12 * phi_0 = b1 | a21 * theta + a22 * ph...
98a9bf064e56a48312170a8c32e032654317d40f
3,600,978
def default_figure(climate_data: pd.DataFrame, column: str) -> go.Figure: """ Default figure generation Args: climate_data: DataFrame with column: Which column of the data should be displayed Returns: plotly Figure object """ fig = go.Figure( data=[ go...
3b8efdf3751c3d4c1448f505ec739eab1e2bfafe
3,600,979
import sys def find_correct(fragmented_smi, fragmented_smi_noIsotopes): """Function to find the correct co-ordinates of the 3D molecule. Takes the string of the fragments seperated by "." Returns the strings of the core and sidechains""" core = "" side_chains = "" f_array = fragmented_smi.spli...
1e8c2439aec628caaf71b631f0e346bfd3267f69
3,600,980
def _fpgrowth_filter(concept, winlen, max_c, min_neu): """ Filter for selecting closed frequent items set with a minimum number of neurons and a maximum number of occurrences and first spike in the first bin position """ intent = np.array(concept[0]) keep_concept = (min(intent % winlen) == 0...
89e1c8e265b9b2213dd260878463b3618c0d0d41
3,600,981
from typing import List import numba def multiplicative_variance_trees( X: List[np.ndarray], y2: np.ndarray, *, q: List[float]=np.r_[:1:11j][1:-1], num_trees: int, max_depth: int, min_gain: float, learning_rate: float=0.3, min_child_size: int=1000, threads: bool=True ): """...
66c1825db1a86926e7526d632d37c97add7c5504
3,600,982
def _callable_tabular_policy(tabular_policy): """Turns a tabular policy into a callable. Args: tabular_policy: A dictionary mapping information state key to a dictionary of action probabilities (action -> prob). Returns: A function `state` -> list of (action, prob) """ def wrap(st...
302081ec400101b63351e699f0dace34b1cf3e8f
3,600,983
import os import logging import pickle def gather_files(path, config, file_inventory) -> int: """:returns file count""" if not os.path.isdir(path): logging.error("Not a directory: '%s', skipping indexing", path) return logging.info("Indexing %s", path) logging.info("Calculating number ...
064ec557f2306a07e57e6024ebf6f383eeeb321b
3,600,984
def _create_raid_adapter(node): """Create RAID adapter info on a RAID controller. :param node: an ironic node object. :raises: IRMCOperationError on an error from python-scciclient. """ irmc_info = node.driver_info target_raid_config = node.target_raid_config try: return client.el...
164c335d4057e237329bc7f3e9940a800077b10d
3,600,985
def orthogonal_directional(vector, count=1): """ """ dimensionality = len(vector) subspace_basis = [] if vector[-1] != 0: identity = np.eye(dimensionality - 1, dimensionality) else: idx = np.nonzero(vector)[0] identity = np.eye(dimensionality, dimensionality) ide...
379c198f881ea6d1d7b68aaf29f70ff5037813bb
3,600,986
import functools def condition(cls, status): """ Encapsulates a behaviour and wait for it's status to flip to the desired state. This behaviour will tick with :data:`~py_trees.common.Status.RUNNING` while waiting and :data:`~py_trees.common.Status.SUCCESS` when the flip occurs. Args: ...
902b664bf3008fc3aece059aeea24859ac02f667
3,600,987
from typing import List from typing import Tuple import os import inspect import zipfile from datetime import datetime import time import jinja2 def write_pdx_file(output_file_name : str, database : odxtools.Database, auxiliary_content_specifiers : List[Tuple[str, str]] = [], ...
868c65d0a912148a7a6869492f5b8b5186b57773
3,600,988
def open_nb(name: str, src: str) -> nbformat: """ Open notebook file :param name: name of notebook to open :param src: source directory :return: notebook object """ print("Reading...", end=" ") nb = nbformat.read( "{src}/{name}/{name}.ipynb".format(name=name, src=src), as_versio...
963a48e72c9cbf8a12c0be672f084c20d0ea7683
3,600,989
def create_idle(): """ creates a subtree which causes the robot to idle on each tick, with status of RUNNING """ idle = py_trees.behaviours.Running(name="Idle") return idle
76fde31723f4ad51a135595cc4d461021f28cf36
3,600,990
import difflib def _get_suggestion(provided_string, allowed_strings): """ Given a string and a list of allowed_strings, it returns a string to print on screen, with sensible text depending on whether no suggestion is found, or one or more than one suggestions are found. :param provided_string: th...
ebd1b963116bddebbc340312f2d7a16be36b11c6
3,600,991
def NHWC_to_HWNC(x, name='NHWC_to_HWNC'): """Convert data format from NHWC to HWNC, may be used for re-indexing. """ x = tf.transpose(x, [1, 2, 0, 3]) return x
6838048568c35627445224668bf6abc9c5457d6c
3,600,992
import array def kmeans_train(pm_options, spark): """ Kmeans Training function :param pm_options: :param spark: :return: """ # Import Data ################################## input_data = (spark.read.format("csv") .option("header", pm_options.with_headers) ...
933878e5c89013638eaa18e963dfe73aebf14248
3,600,993
def iso_8601(datetime): """Convert a datetime into an iso 8601 string.""" if datetime is None: return datetime value = datetime.isoformat() if value.endswith('+00:00'): value = value[:-6] + 'Z' return value
968b9d9edfe13340e4c2f74fb78c11cb38d6c013
3,600,994
def tuple_subtract(tuple1, tuple2): """Perform element-wise subtraction of two tuples or numbers.""" return tuple_add(tuple1, tuple_mul(tuple2, -1))
7700c544d96257c906215c75f665266630d6aea0
3,600,995
from typing import Tuple from typing import Sequence def _binlbins(glon: float, vterm: float, dl: float = 1.0) -> Tuple[Sequence, Sequence]: """Bin l bins.""" minglon, maxglon = ( np.floor(np.amin(glon)), np.floor(np.amax(glon)), ) minglon, maxglon = int(minglon), int(maxglon) nout...
51f47be874dbfcb3337b21c7c483a3b80de4c8b3
3,600,996
import math def colorize(im, total_fr, fr_no): """ motion representation of the input pose maps from consequent frames based on the color codeing of the time proceeding ====== input ====== im: pose map with gray scale intensity ( all the channels have are identical) total_fr : total number of ...
39830525df94bf30f518dea1503e8be5518ff42b
3,600,997
def previous_request_handler(username): """Request handler for previewing all previous requests of a given user Args: username (str): user who initiated the request Returns: tuple: data in json form and status code """ user_exists = validate_previous_request(username) if not us...
1233f7b82f7ac9aaa2c50f92b490b7fc1e6b5531
3,600,998
def tox_configure(config): """ :param tox.config.Config config: Configuration object to observe. :rtype: tox.config.Config """ return _ensure_envs_recreated_on_requirements_update(config)
2876fc37badbb59ddb8149882fb5bec0ae22b542
3,600,999