content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_fixxation_map(eye_x, eye_y, fixxation_classifier): """ :param eye_x: an indexable datastructure with the x eye coordinates :param eye_y: an indexable datastructure with the y eye coordinates :param fixxation_classifier: a list with values which indicate ...
bccf37777eb4d74fcb48a8316fc3d2695a209371
12,400
from re import T from typing import Any def with_metadata(obj: T, key: str, value: Any) -> T: """ Adds meta-data to an object. :param obj: The object to add meta-data to. :param key: The key to store the meta-data under. :param value: The meta-data value to store. :return: ob...
566f9a2c1d083bbe44b86f0a8716e5bb44892b13
12,401
import hashlib def checksum(uploaded_file: 'SimpleUploadedFile', **options): """ Function to calculate checksum for file, can be used to verify downloaded file integrity """ hash_type = options['type'] if hash_type == ChecksumType.MD5: hasher = hashlib.md5() elif hash_type == Che...
766a288a09791242029669a63734143cf8e2c007
12,402
import requests def get_page(url): """Get source of url Keyword Arguments: url : string """ logger.debug(f'Getting source for {url}') res = requests.get(url) logger.debug(f'Status code for {url} is {res.status_code}') if res.status_code < 200 or res.status_code >= 300: raise E...
3b273e895fe36f050423b514e046961045a30017
12,403
import types from typing import Optional from typing import Tuple def preceding_words(document: Document, position: types.Position) -> Optional[Tuple[str, str]]: """ Get the word under the cursor returning the start and end positions. """ lines = document.lines if position.line >= len(lines): ...
9d1078084045ac468639a903c74dd24e45ed1087
12,404
def check_gpu(gpu, *args): """Move data in *args to GPU? gpu: options.gpu (None, or 0, 1, .. gpu index) """ if gpu == None: if isinstance(args[0], dict): d = args[0] #print(d.keys()) var_dict = {} for key in d: var_dict[key] = ...
e4849a0a99dd6ca7baeacadc130e46006dd23c3a
12,405
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up the SleepIQ config entry.""" conf = entry.data email = conf[CONF_USERNAME] password = conf[CONF_PASSWORD] client_session = async_get_clientsession(hass) gateway = AsyncSleepIQ(client_session=client_session)...
e4a4765113c7bc1e3c50290c72f3ca8196ba2bf2
12,406
def expansion(svsal,temp,pres,salt=None,dliq=None,dvap=None, chkvals=False,chktol=_CHKTOL,salt0=None,dliq0=None,dvap0=None, chkbnd=False,useext=False,mathargs=None): """Calculate seawater-vapour thermal expansion coefficient. Calculate the thermal expansion coefficient of a seawater-vapour parc...
78c47eabf1d8e96c655652c3c8847b391264b05b
12,407
import yaml def yaml_to_dict(yaml_str=None, str_or_buffer=None): """ Load YAML from a string, file, or buffer (an object with a .read method). Parameters are mutually exclusive. Parameters ---------- yaml_str : str, optional A string of YAML. str_or_buffer : str or file like, opti...
37aefe8e5b1bcc734626cbf7177e3b3dffda2416
12,408
from typing import Dict from typing import Any from typing import Tuple def verify_block_arguments( net_part: str, block: Dict[str, Any], num_block: int, ) -> Tuple[int, int]: """Verify block arguments are valid. Args: net_part: Network part, either 'encoder' or 'decoder'. block: ...
cead023afcd72d1104e02b2d67406b9c47102589
12,409
from pathlib import Path def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()): """ Compute the average precision, given the recall and precision curves. Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. # Arguments tp: True positives (nparray, nx1 ...
9a41478f8b85b7d43ceeaaaf6425ece67672fc64
12,410
from typing import Optional def frame_aligned_point_error( pred_frames: r3.Rigids, target_frames: r3.Rigids, frames_mask: paddle.Tensor, pred_positions: r3.Vecs, target_positions: r3.Vecs, positions_mask: paddle.Tensor, length_scale: float, l1_clamp_distance: Optional[float]...
fe66fea6d3d6ca418b64a2d18bdc75a6e10d6707
12,411
def remove_app_restriction_request(machine_id, comment): """Enable execution of any application on the machine. Args: machine_id (str): Machine ID comment (str): Comment to associate with the action Notes: Machine action is a collection of actions you can apply on the machine, for ...
f4dd44cbef6194b9fcc301fb19bb5c3ba77ad269
12,412
import torch def fix_bond_lengths( dist_mat: torch.Tensor, bond_lengths: torch.Tensor, delim: int = None, delim_value: float = ARBITRARILY_LARGE_VALUE) -> torch.Tensor: """ Replace one-offset diagonal entries with ideal bond lengths """ mat_len = dist_mat.shape[1] b...
1112ad7019c1cb82360ad6e784f7f8262dc7b4a0
12,413
def CommandToString(command): """Returns quoted command that can be run in bash shell.""" return ' '.join(cmd_helper.SingleQuote(c) for c in command)
bcb6d3f108997b35336a68a559243931ca50a2c5
12,414
def sample_trilinear(t, coords, img_h=128, img_w=128): """ Samples noise octaves in one shot :param t: noise cube [n_octaves, noise_res, noise_res, noise_res] (same noise foreach sample in batch) :param coords: octave-transformed sampling positions [bs, n_octaves, 3, img_h*img_w] :param img_h: heig...
251a0eeaefe3eccd1d4d72ba16aa121a5f17c483
12,415
import re def version(output): """ `git --version` > git version 1.8.1.1 """ output = output.rstrip() words = re.split('\s+', output, 3) if not words or words[0] != 'git' or words[1] != 'version': raise WrongOutputError() version = words[2] parts = version.split('.') try: ...
21a16245cf7729b56588016f358667b210113eec
12,416
def set_up_s3_encryption_configuration(kms_arn=None): """ Use the default SSE-S3 configuration for the journal export if a KMS key ARN was not given. :type kms_arn: str :param kms_arn: The Amazon Resource Name to encrypt. :rtype: dict :return: The encryption configuration for JournalS3Export. ...
dd8663c17e040423a08c772fd9ca64d25abd2850
12,417
import click import json def search(dataset, node, aoi, start_date, end_date, lng, lat, dist, lower_left, upper_right, where, geojson, extended, api_key): """ Search for images. """ node = get_node(dataset, node) if aoi == "-": src = click.open_file('-') if not src.isatty(): ...
309a98cf3cfc81f12631bbc15ee0325d16385338
12,418
from typing import Callable def _make_rnn_cell(spec: RNNSpec) -> Callable[[], tf.nn.rnn_cell.RNNCell]: """Return the graph template for creating RNN cells.""" return RNN_CELL_TYPES[spec.cell_type](spec.size)
48cf85bcb8d39ab7b4dd150fc890eb281d9b83d9
12,419
def run_baselines(env, seed, log_dir): """Create baselines model and training. Replace the ppo and its training with the algorithm you want to run. Args: env (gym.Env): Environment of the task. seed (int): Random seed for the trial. log_dir (str): Log dir path. Returns: ...
2a020c5efe548d3722155569fbe69cd836efeebd
12,420
from config import STL10_PATH import os def load_stl(): """Loads the STL-10 dataset from config.STL10_PATH or downloads it if necessary. :return: (x_train, y_train), (x_test, y_test), min, max :rtype: tuple of numpy.ndarray), (tuple of numpy.ndarray), float, float """ min_, max_ = 0., 1. # D...
a521cb4d5ff5bcc095cccaab256297ac21b38cc2
12,421
def count_transitions(hypno): """ return the count for all possible transitions """ possible_transitions = [(0,1), (0,2), (0,4), # W -> S1, S2, REM (1,2), (1,0), (1,3), # S1 -> W, S2, REM (2,0), (2,1), (2,3), (2,4), # S2 -> W, S1, SWS, REM ...
4a0dc835c2e72bf46ad8d3ebe33256f32ce2ede9
12,422
def mu_ref_normal_sampler_tridiag(loc=0.0, scale=1.0, beta=2, size=10, random_state=None): """Implementation of the tridiagonal model to sample from .. math:: \\Delta(x_{1}, \\dots, x_{N})^{\\beta} \\prod_{n=1}^{N} \\exp(-\\frac{(x_i-\\mu)^2}{2\\sigma^2} ) dx_...
75e7d46ec4816bbfa46443537f66cd27043b212d
12,423
import os import re def get_ofi_info(hosts, supported=None, verbose=True): """Get the OFI provider information from the specified hosts. Args: hosts (NodeSet): hosts from which to gather the information supported (list, optional): list of supported providers when if provided will limit the ...
dbb9669d642a68e70aaaee7bc0e4f78e15474b0b
12,424
def get_pokemon(name:str) -> dict: """ Busca el pokémon dado su nombre en la base de datos y crea un diccionario con su información básica. Paramétros: name(str): Nombre del pokémon a buscar Retorna: Diccionario con la información básica del pokémon y sus evoluciones. """ try: ...
fa19704b2dfb6d2223a73264df6b5dc9e866fb8e
12,425
def create_cluster(module, switch, name, node1, node2): """ Method to create a cluster between two switches. :param module: The Ansible module to fetch input parameters. :param switch: Name of the local switch. :param name: The name of the cluster to create. :param node1: First node of the clust...
a7f0a415d019b7fa3622d18da396879df566b365
12,426
from typing import List import random def random_terminals_for_primitive( primitive_set: dict, primitive: Primitive ) -> List[Terminal]: """ Return a list with a random Terminal for each required input to Primitive. """ return [random.choice(primitive_set[term_type]) for term_type in primitive.input]
b3160800bb5da87c0215ed4857f2596934d28c05
12,427
def _specie_is_intermediate_old( specie_id: str, specie_dict: dict = None, ) -> bool: """Detect is a specie should be considered as an intermediate compound. FIXME, this needs to be refined so that we don't rely on the specie ID. :param specie_id: specie ID :type: str :param specie_di...
b1a4f99abf0379ea3cacf6ab53f45fca636072c5
12,428
def where_from_pos(text, pos): """ Format a textual representation of the given position in the text. """ return "%d:%d" % (line_from_pos(text, pos), col_from_pos(text, pos))
587387f017fe32b297c06123fc3853c18a7aea46
12,429
def generateHuffmanCodes (huffsize): """ Calculate the huffman code of each length. """ huffcode = [] k = 0 code = 0 # Magic for i in range (len (huffsize)): si = huffsize[i] for k in range (si): huffcode.append ((i + 1, code)) code += 1 code <<=...
60d5a2bd5524627dd5cc624dbb6b0ea09b8032d4
12,430
def one_hot_df(df, cat_col_list): """ Make one hot encoding on categoric columns. Returns a dataframe for the categoric columns provided. ------------------------- inputs - df: original input DataFrame - cat_col_list: list of categorical columns to encode. outputs ...
d47978a551edbc11f93f9a2e87dbe1598e39161b
12,431
from typing import List from typing import Optional import select from typing import Dict async def load_users_by_id(user_ids: List[int]) -> List[Optional[User]]: """ Batch-loads users by their IDs. """ query = select(User).filter(User.id.in_(user_ids)) async with get_session() as session: ...
ac9d0a16a40d478ed7fec590bf591aa0124270d9
12,432
def create_timetravel_model(for_model): """ Returns the newly created timetravel model class for the model given. """ if for_model._meta.proxy: _tt_model = for_model._meta.concrete_model._tt_model for_model._tt_model = _tt_model for_model._meta._tt_model = _tt_model r...
6a2557f3737ce014e14ba9dd36cd7a6d9c8c78b7
12,433
def public_route_server_has_read(server_id, user_id=None): """ check if current user has read access to the given server """ user = user_id and User.query.get_or_404(user_id) or current_user server = DockerServer.query.get_or_404(server_id) if server.has_group_read(user): return Respons...
b9f812feac7c7e951f8c37178fd1dc2913601631
12,434
def isValidPublicAddress(address: str) -> bool: """Check if address is a valid NEO address""" valid = False if len(address) == 34 and address[0] == 'A': try: base58.b58decode_check(address.encode()) valid = True except ValueError: # checksum mismatch ...
a99f08c289f9d3136adf7e17697645131e785ecb
12,435
def cost_to_go_np(cost_seq, gamma_seq): """ Calculate (discounted) cost to go for given cost sequence """ # if np.any(gamma_seq == 0): # return cost_seq cost_seq = gamma_seq * cost_seq # discounted reward sequence cost_seq = np.cumsum(cost_seq[:, ::-1], axis=-1)[:, ::-1] # cost to ...
bea4de4cb32c3a346ebe8ea532c2c94589893e65
12,436
import re def parse_args(): """ Parses the command line arguments. """ # Override epilog formatting OptionParser.format_epilog = lambda self, formatter: self.epilog parser = OptionParser(usage="usage: %prog -f secret.txt | --file secret.txt | --folder allmysecrets", epilog=EXAMPLES) parser.add_option("-p", "-...
8f696bb8b419269766bceadb42b36f2a3e052e5b
12,437
def x_to_ggsg(seq): """replace Xs with a Serine-Glycine linker (GGSG pattern) seq and return value are strings """ if "X" not in seq: return seq replacement = [] ggsg = _ggsg_generator() for aa in seq: if aa != "X": replacement.append(aa) # restart li...
53885ca76484f25a04ffc4220af0d7b0e56defd4
12,438
from typing import OrderedDict def gini_pairwise(idadf, target=None, features=None, ignore_indexer=True): """ Compute the conditional gini coefficients between a set of features and a set of target in an IdaDataFrame. Parameters ---------- idadf : IdaDataFrame target : str or l...
aa886c8d44e54597e86f0736ea383671bda2e13f
12,439
def init_isolated_80(): """ Real Name: b'init Isolated 80' Original Eqn: b'0' Units: b'person' Limits: (None, None) Type: constant b'' """ return 0
5511cac38bf9bd68446fcb1dc41ac96807ea57a2
12,440
def xcom_api_setup(): """Instantiate api""" return XComApi(API_CLIENT)
1a47066f389ab2846f1aa31ce8338389def07e6d
12,441
def zeros_tensor(*args, **kwargs): """Construct a tensor of a given shape with every entry equal to zero.""" labels = kwargs.pop("labels", []) dtype = kwargs.pop("dtype", np.float) base_label = kwargs.pop("base_label", "i") return Tensor(np.zeros(*args, dtype=dtype), labels=labels, ...
3baba23ba763afb51c715a85aa6f84c8c2d99c43
12,442
from typing import Tuple def reg_split_from( splitted_mappings: np.ndarray, splitted_sizes: np.ndarray, splitted_weights: np.ndarray, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ When creating the regularization matrix of a source pixelization, this function assumes each source pixel has be...
545f0bd7345a8ab908d2338eaa7cb4c3562f4234
12,443
def get_initiator_IP(json_isessions): """ pull the IP from the host session """ print("-" * 20 + " get_initiator started") for session in json_isessions['sessions']: session_array[session['initiatorIP']] = session['initiatorName'] return session_array
4140b9f32727d1e5e1e98fd6714e8d91276b2272
12,444
def get_data_for_recent_jobs(recency_msec=DEFAULT_RECENCY_MSEC): """Get a list containing data about recent jobs. This list is arranged in descending order based on the time the job was enqueued. At most NUM_JOBS_IN_DASHBOARD_LIMIT job descriptions are returned. Args: - recency_secs: the thres...
032f27b55c70947a44cd6ed244291118e3660f77
12,445
def construct_outgoing_multicast_answers(answers: _AnswerWithAdditionalsType) -> DNSOutgoing: """Add answers and additionals to a DNSOutgoing.""" out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, multicast=True) _add_answers_additionals(out, answers) return out
65f0a2a42f9d3f1bd8fbc74e8303248adf01e65d
12,446
import struct def load_analog_binary_v1(filename): """Load analog traces stored in the binary format by Logic 1.2.0+ The format is documented at https://support.saleae.com/faq/technical-faq/data-export-format-analog-binary Returns (data, period) where data is a numpy array of 32-bit floats of sh...
5fcb97c4da367a8abeb12d7dc2852dbb7412956d
12,447
import click def setup_phantomjs(): """Create and return a PhantomJS browser object.""" try: # Setup capabilities for the PhantomJS browser phantomjs_capabilities = DesiredCapabilities.PHANTOMJS # Some basic creds to use against an HTTP Basic Auth prompt phantomjs_capabilities[...
5a8e536850e2a3c39adaf3228fc1a1f7ad4694dd
12,448
def normal_pdf(x, mu, cov, log=True): """ Calculate the probability density of Gaussian (Normal) distribution. Parameters ---------- x : float, 1-D array_like (K, ), or 2-D array_like (K, N) The variable for calculating the probability density. mu : float or 1-D array_like, (K, ) ...
4cdb573e1283a5740cb8d5b518b69c02bc013fe6
12,449
import sqlite3 from datetime import datetime def get_quiz(id, user): """Get Quiz""" conn = sqlite3.connect(DBNAME) cursor = conn.cursor() if user == 'admin' or user == 'fabioja': cursor.execute( "SELECT id, release, expire, problem, tests, results, diagnosis, numb from QUIZ where i...
7e517e2ca84ebd320883950d4c3d6e572f82c226
12,450
def filesystem_entry(filesystem): """ Filesystem tag {% filesystem_entry filesystem %} is used to display a single filesystem. Arguments --------- filesystem: filesystem object Returns ------- A context which maps the filesystem object to filesystem. """ return {'fi...
3afbd0b8ee9e72ab8841ca5c5517396650d2a898
12,451
def haversine(lat1, lon1, lat2, lon2, units='miles'): """ Calculates arc length distance between two lat_lon points (must be in radians) lat2 & and lon2 can be numpy arrays units can be 'miles' or 'km' (kilometers) """ earth_radius = {'miles': 3959., 'km': 6371.} a = np.square(np.s...
cadfa496f39e0a02115140d827bebfa6ff96a2dd
12,452
from typing import Optional def OptionalDateField(description='',validators=[]): """ A custom field that makes the DateField optional """ validators.append(Optional()) field = DateField(description,validators) return field
66695ca94ff7d7283ff5508b4ef3f78efba9a988
12,453
def init_brats_metrics(): """Initialize dict for BraTS Dice metrics""" metrics = {} metrics['ET'] = {'labels': [3]} metrics['TC'] = {'labels': [1, 3]} metrics['WT'] = {'labels': [1, 2, 3]} for _, value in metrics.items(): value.update({'tp':0, 'tot':0}) return metrics
755dc706f7090d78dac18a989745041b8617a9d6
12,454
def add_rse(rse, issuer, vo='def', deterministic=True, volatile=False, city=None, region_code=None, country_name=None, continent=None, time_zone=None, ISP=None, staging_area=False, rse_type=None, latitude=None, longitude=None, ASN=None, availability=None): """ Creates a new R...
3b41e227ea64c5f03d80ae8734c29b24f9c3bed9
12,455
from typing import Dict from typing import Tuple from typing import List def multi_graph_partition(costs: Dict, probs: Dict, p_t: np.ndarray, idx2nodes: Dict, ot_hyperpara: Dict, weights: Dict = None, predefine_barycenter: bool = False) -> ...
a3743cd9cc9e7f9a10eb84992fb74e7fe57f5792
12,456
def TDataStd_BooleanArray_Set(*args): """ * Finds or creates an attribute with the array. :param label: :type label: TDF_Label & :param lower: :type lower: int :param upper: :type upper: int :rtype: Handle_TDataStd_BooleanArray """ return _TDataStd.TDataStd_BooleanArray_Set(*ar...
c458a1182474432d2df049ae3126a6b6b2b49a8e
12,457
def py_list_to_tcl_list(py_list): """ Convert Python list to Tcl list using Tcl interpreter. :param py_list: Python list. :type py_list: list :return: string representing the Tcl string equivalent to the Python list. """ py_list_str = [str(s) for s in py_list] return tcl_str(tcl_interp_g.e...
7f42044b8a0b28089abf453e7a1b65d5cb1fb399
12,458
def get_post_count(user): """ Get number of posts published by the requst user. Parameters ------------ user: The request user Returns ------- count: int The number of posts published by the requst user. """ count = Post.objects.filter(publisher=user).count() return...
6000bcd43ef2b8edf3c1dd04df89dcef38f110d5
12,459
from config import employee_required_fields def create_new_employee(employees): """ Create a new employee record with the employees dictionary Use the employee_sections dictionary template to create a new employee record. """ subsidiary = input('Employee Subsidiary (SK, CZ):') emp...
aa5d0981c2b81ad65ed5ad0368fd1b3b79796a40
12,460
def gather_squares_triangles(p1,p2,depth): """ Draw Square and Right Triangle given 2 points, Recurse on new points args: p1,p2 (float,float) : absolute position on base vertices depth (int) : decrementing counter that terminates recursion return: squares [(float,float,float,float)...] : absolut...
de4e720eb10cb378f00086a6e8e45886746055c0
12,461
def update_node(node_name, node_type, root=None): """ ! Node is assumed to have only one input and one output port with a maximum of one connection for each. Returns: NodegraphAPI.Node: newly created node """ new = NodegraphAPI.CreateNode(node_type, root or NodegraphAPI.GetRootNode()) ...
916beec7de527ee56d5326061aa2c367af17434f
12,462
def dan_acf(x, axis=0, fast=False): """ Estimate the autocorrelation function of a time series using the FFT. Args: x (array): The time series. If multidimensional, set the time axis using the ``axis`` keyword argument and the function will be computed for every other axis. ...
85273d95564f0e8c0afb9ff00ac23dc04539f291
12,463
from datetime import datetime def schedule_decision(): """最適化の実行と結果の表示を行う関数""" # トップページを表示する(GETリクエストがきた場合) if request.method == "GET": return render_template("scheduler/schedule_decision.html", solution_html=None) # POSTリクエストである「最適化を実行」ボタンが押された場合に実行 # データがアップロードされているかチェックする。適切でなければ元のページに...
6f259961d027b6e4a3dc88289a5ba62b162705f6
12,464
def infection_rate_asymptomatic_30x40(): """ Real Name: b'infection rate asymptomatic 30x40' Original Eqn: b'contact infectivity asymptomatic 30x40*(social distancing policy SWITCH self 40*social distancing policy 40\\\\ +(1-social distancing policy SWITCH self 40))*Infected asymptomatic 30x40*Susceptible 4...
16aebdca2259933dcdab1a00ed8d37b10d5b8714
12,465
def slug(hans, style=Style.NORMAL, heteronym=False, separator='-', errors='default', strict=True): """将汉字转换为拼音,然后生成 slug 字符串. :param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ). 可以使用自己喜爱的分词模块对字符串进行分词处理, 只需将经过分词处理的字符串列表传进来就可以了。 :type hans: unicode 字符串或字符串列表 ...
124431e3ea8747dfdc024f93e88f692746797013
12,466
def A_weight(signal, fs): """ Return the given signal after passing through an A-weighting filter signal : array_like Input signal fs : float Sampling frequency """ b, a = A_weighting(fs) return lfilter(b, a, signal)
1c6abdd90b85762db4383972de7508d00b561065
12,467
import argparse from pathlib import Path def getCommandLine() -> argparse.ArgumentParser: """Получить агрументы коммандной строки Returns: argparse.ArgumentParser: _description_ """ parser = argparse.ArgumentParser(description='Конвертация тестов с TFS в xml формат Testrail/TestIT') actio...
c0b27d2488115c059a713776dd4fc209f1db7011
12,468
def listall(context, uri=None): """ *musicpd.org, music database section:* ``listall [URI]`` Lists all songs and directories in ``URI``. """ result = [] root_path = translator.normalize_path(uri) # TODO: doesn't the dispatcher._call_handler have enough info to catch # the e...
f9d2be6b8155b3110aa085ac2664665ee8393c23
12,469
from typing import Tuple from typing import Union import traceback def send_task_to_executor(task_tuple: TaskInstanceInCelery) \ -> Tuple[TaskInstanceKey, CommandType, Union[AsyncResult, ExceptionWithTraceback]]: """Sends task to executor.""" key, _, command, queue, task_to_run = task_tuple try: ...
cbc93ac3a3c146b748c0ec88eaa9cb2cd631ac85
12,470
import pathlib import os def createPyarchFilePath(filePath): """ This method translates from an ESRF "visitor" path to a "pyarch" path: /data/visitor/mx415/id14eh1/20100209 -> /data/pyarch/2010/id14eh1/mx415/20100209 """ pyarchFilePath = None if isinstance(filePath, str): filePath = pa...
daf7cf23126ae51cd30492981dbcae9fe0431afd
12,471
def get_embed(input_data, vocab_size, embed_dim): """ Create embedding for <input_data>. :param input_data: TF placeholder for text input. :param vocab_size: Number of words in vocabulary. :param embed_dim: Number of embedding dimensions :return: Embedded input. """ # TODO: Implement Fun...
b4c280e10df338633b69cf4b3c65967c1f80b9c5
12,472
def geometries_from_bbox(north, south, east, west, tags): """ Create a GeoDataFrame of OSM entities within a N, S, E, W bounding box. Parameters ---------- north : float northern latitude of bounding box south : float southern latitude of bounding box east : float ea...
32aeebe7f644df00b613ef6e0d4f30baef1a5743
12,473
def dBzdtAnalCircT(a, t, sigma): """ Hz component of analytic solution for half-space (Circular-loop source) Src and Rx are on the surface and receiver is located at the center of the loop. Src waveform here is step-off. .. math:: \\frac{\partial h_z}{\partial t} = -\\...
18b9428528ed11a121ad01578d2bfc35faceae21
12,474
def count_increasing(ratings, n): """ Only considering the increasing case """ arr = [1] * n cnt = 1 for i in range(1, n): cnt = cnt + 1 if ratings[i - 1] < ratings[i] else 1 arr[i] = cnt return arr
9fe274527fbba505467a195bf555c77d2f3e6aed
12,475
import copy def load_train_data_frame(train_small, target, keras_options, model_options, verbose=0): """ ### CAUTION: TF2.4 Still cannot load a DataFrame with Nulls in string or categoricals! ############################################################################ #### TF 2.4 still cannot load ten...
85c496b485bbc26afbadf181a2231e3f5bd93706
12,476
def stat_float_times(space, newval=-1): """stat_float_times([newval]) -> oldval Determine whether os.[lf]stat represents time stamps as float objects. If newval is True, future calls to stat() return floats, if it is False, future calls return ints. If newval is omitted, return the current setting. """ state =...
e183f0cc2ce56bc7b4ac6ce95d8cb671a963422f
12,477
def decorate(rvecs): """Output range vectors into some desired string format""" return ', '.join(['{%s}' % ','.join([str(x) for x in rvec]) for rvec in rvecs])
31a3d4414b0b88ffd92a5ddd8eb09aaf90ef3742
12,478
def update_topic_collection_items(request_ctx, collection_item_id, topic_id, **request_kwargs): """ Accepts the same parameters as create :param request_ctx: The request context :type request_ctx: :class:RequestContext :param collection_item_id: (required) ID :type collection_it...
06b0709f5fa4acf189baef8f2665bee81b3c4993
12,479
def upsample(inputs, factor=(2, 2), interpolation='nearest'): """ Upsampling layer by factor Parameters ---------- inputs: Input tensor factor: The upsampling factors for (height, width). One integer or tuple of two integers interpolation: A string, one of [`nearest`, `bilinear`, 'b...
dfbd42871e63cb685f9cfbf9185da38839a9ee4e
12,480
def root_mean_squared_error(*args, **kwargs): """ Returns the square-root of ``scikit-learn``'s ``mean_squared_error`` metric. All arguments are forwarded to that function. """ return np.sqrt(mean_squared_error(*args, **kwargs))
51084b2ec55d14657fa128f0df2bd3f438c2367b
12,481
def idwt2(Wimg, level=4): """ inverse 2d wavelet transform :param Wimg: 2d array wavelet coefficients :param level: int level of wavelet transform - image shape has to be multiples of 2**level :return: 2d array image """ coeffs = _from_img_to_coeffs(Wimg, levels=level) ...
521ceca879b0961730b1efd6dac54772a2b41ca3
12,482
def get_color(card): """Returns the card's color Args: card (webelement): a visible card Returns: str: card's color """ color = card.find_element_by_xpath(".//div/*[name()='svg']/*[name()='use'][2]").get_attribute("stroke") # both light and dark theme if (color == "#ff0101...
452266b81d70973149fed4ab2e6cbc9c93591180
12,483
from typing import Dict from typing import Any def is_valid_path(parameters: Dict[str, Any]) -> bool: """Single "." chars and empty strings "" are excluded from path by urllib3. A path containing to "/" or "%2F" will lead to ambiguous path resolution in many frameworks and libraries, such behaviour have ...
5f80ff76c535b3913efc7ba83e04c4c049a9e50b
12,484
import torch def to_tensor(x): """ Arguments: x: an instance of PIL image. Returns: a float tensor with shape [3, h, w], it represents a RGB image with pixel values in [0, 1] range. """ x = np.array(x) x = torch.FloatTensor(x) return x.permute(2, 0, 1).unsqu...
6ff19bd7549a4fce455f03559420216020658c44
12,485
import tqdm import os def load_messier_catalog_images(path, img_size=None, disable_tqdm=False): """ Data loader for Messier catalog images. The images are available in `messier-catalog-images` repository of MiraPy organisation. :param path: String. Directory path. :param img_size: Final dimension...
2a0df9e99ff0c442df9bf78776af59a2659cdc46
12,486
import os def load_stl10(data_dir, flatten=False, one_hot=True, normalize_range=False, whiten_pixels=True, border_pad_size=0): """ Large part of this loader and the associated functions has been inspired from, https://github.com/mttk/STL10/blob/master/stl10_input.py """ # path to the binar...
d72f033175c8377442215fbab3f43b53705dfa03
12,487
def fetch_data(fold_path): """Fetch data saving in fold path. Convert data into suitable format, using csv files in fold path. :param fold_path: String. The fold in which data files are saved. :return: training_data: Dataframe. Combined dataframe to create training data. testing_data:...
42ea9ea6d1d9d597acc4ed1a14099711642608f4
12,488
def add_chr_prefix(band): """ Return the band string with chr prefixed """ return ''.join(['chr', band])
08a99220023f10d79bdacdb062a27efcb51086ce
12,489
def disable_text_recog_aug_test(cfg, set_types=None): """Remove aug_test from test pipeline of text recognition. Args: cfg (mmcv.Config): Input config. set_types (list[str]): Type of dataset source. Should be None or sublist of ['test', 'val'] Returns: cfg (mmcv.Config):...
bda3a5420d32d55062b23a6af27cee3e203b878c
12,490
def layer_svg(svg_bottom, svg_top, offset: list = [0.0, 0.0]): """ Adds one SVG over another. Modifies the bottom SVG in place. :param svg_bottom: The bottom SVG, in in xml.etree.ElementTree form :param svg_top: The top SVG, in in xml.etree.ElementTree form :param offset: How far to offset the top S...
6c6a8151d17f4aff9f1491d1ed71772d9434ae4c
12,491
import os def get_data_home(data_home=None): """Return a path to the cache directory for example datasets. This directory is then used by :func:`load_dataset`. If the ``data_home`` argument is not specified, it tries to read from the ``CF_DATA`` environment variable and defaults to ``~/cf-data``. ...
8e530b44db3387cb07da78dfbf3bc43f4855e9e0
12,492
def utxo_cmd(ctx, dry_run): """Get the node's current UTxO with the option of filtering by address(es)""" try: CardanoCli.execute(cmd=["cardano-cli", "query", "utxo"], dry_run=dry_run, include_network=True) except CardanoPyError as cpe: ctx.fail(cpe.message) return cpe.return_code
52807294a445fc2f641c1b921807bba898ad8c34
12,493
def delta_in_ms(delta): """ Convert a timedelta object to milliseconds. """ return delta.seconds*1000.0+delta.microseconds/1000.0
4ed048155daf4a4891488e28c674e905e1bbe947
12,494
import slicer, collections, fnmatch def getNodes(pattern="*", scene=None, useLists=False): """Return a dictionary of nodes where the name or id matches the ``pattern``. By default, ``pattern`` is a wildcard and it returns all nodes associated with ``slicer.mrmlScene``. If multiple node share the same name, ...
6d6c44987a800f361d45f4538167acb65e738418
12,495
from typing import Union from typing import Type from re import X from typing import Mapping from typing import Optional def get_cls( query: Union[None, str, Type[X]], base: Type[X], lookup_dict: Mapping[str, Type[X]], lookup_dict_synonyms: Optional[Mapping[str, Type[X]]] = None, default: Optional...
e5f805df5ef19de9939344beee21834e3f2556ab
12,496
def selection_sort(data): """Sort a list of unique numbers in ascending order using selection sort. O(n^2). The process includes repeatedly iterating through a list, finding the smallest element, and sorting that element. Args: data: data to sort (list of int) Returns: sorted l...
8b745be41c857669aedecb25b3006bbdc1ef04eb
12,497
def _conv(args, filter_size, num_features, bias, reuse, w_init=None, b_init=0.0, scope='_conv'): """convolution: Args: args: a Tensor or a list of Tensors of dimension 3D, 4D or 5D batch x n, Tensors. filter_size: int tuple of filter height and width. reuse: None/True, whether to reuse vari...
104d91623949e4506c4b72001c23b6ab7fb312ca
12,498
import time import os def make_bright_star_mask_in_hp(nside, pixnum, verbose=True, gaiaepoch=2015.5, maglim=12., matchrad=1., maskepoch=2023.0): """Make a bright star mask in a HEALPixel using Tycho, Gaia and URAT. Parameters ---------- nside : :class:`int` (NE...
c82768cd652feca5f07f857f6225a96931669d07
12,499