content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def extract_slices(img): """ Extract slices from images shapes Parameters ----------- imgs: list of n_sessions arrays of shape\ (n_voxels, n_timeframes) Returns -------- slices: list of slices """ slices = [] t_i = 0 for i in range(len(img)): n_voxels, n...
28376eb45e7efa19991879c9d6e4a615b6851a4c
3,626,200
def _generate_meta(): """ Generate Meta information for export """ d = {'root_url': request.url_root} return d
8f34c42183e12b36c5ae656e06d7b10b0f3d1715
3,626,201
def u2(vector): """ This function calculates the utility for agent 2. :param vector: The reward vector. :return: The utility for agent 2. """ utility = vector[0] * vector[1] return utility
93b9210db00ee9a3ddca4cd9b447a7348f63a659
3,626,202
from typing import Any from typing import Type from typing import Optional from typing import TypeGuard def assert_isinstance( instance: Any, cls: Type[TYPE], message: Optional[str] = None ) -> TypeGuard[TYPE]: """ A TypeGuard function that is equivalent to `assert instance, cls, message` that hides n...
c81390f0a409667ad1fef26e49cfb6623c8521ba
3,626,203
def build_url(url): """Build the actual URL to use.""" f = furl(url) return f.url
f5d2abdfc8bcb6b9d118d23c98bad371b3b7a3ed
3,626,204
def create_input_file(recipe=None, input_file=None, recipe_input=None, file_name='my_test_file.txt', media_type='text/plain', file_size=100, file_path=None, workspace=None, countries=None, is_deleted=False, data_type='', last_modified=None, source_started=None, source_ended=N...
7ed13eeac1edf5078fac8a1a9ab763fd2667e336
3,626,205
def mask_and_mean_loss(input_tensor, binary_tensor, axis=None): """ Mask a loss by using a tensor filled with 0 or 1 and average correctly. :param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy :param binary_tensor: A float tensor of shape [batch_size, ...] ...
099976441be4e50dbbd6a8fedb7a51f769c6b872
3,626,206
def counting_sort_integers(values, max_val=None, min_val=None, inplace=False): """ Sorts an array of integers using counting_sort. Let n = len(values), k = max_val+1 """ if len(values) == 0: return values if inplace else [] #Runs in O(n) time if max_val is None or min_val is None if...
d53b00b8753d8adc1782e5941b4b6dcce7c80ca3
3,626,207
import os def collision_type_interact(collision_type, map_detail='Low', data_directory="data/Collidium"): """ Queries database and returns maps based on data filtered by collision type Args: collision_type(str): Type of collision, characterized by entities involved. Values include Vehicle onl...
8a4469b26a80ed5371a49acbb72dc250da9cc41a
3,626,208
def xfun(p,B,pv0,f): """ Steady state solution for x without CRISPR """ return f/(B*p-p/pv0)
874d7d5a1d0d485aafa6f7298e1d214ca86ea90e
3,626,209
from onnx.helper import make_node def convert_npi_max(node, **kwargs): """Map MXNet's min operator attributes to onnx's ReduceMin operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) mx_axis = str(attrs.get("axis", 'None')) axes = convert_string_to_lis...
feda0ad9c4a301581f3c97f615214b37b558d1d9
3,626,210
def pattern_matching(pattern, genome): """Find all occurrences of a pattern in a string. Args: pattern (str): pattern string to search in the genome string. genome (str): search space for pattern. Returns: List, list of int, i.e. all starting positions in genome where pattern appea...
86ae704586fbac937e044f41a8831f2669c4e7dc
3,626,211
import glob def findLblWithoutImg(pathI, pathII): """ :param pathI: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/images/*.jpg" :param pathII: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/labels/*.txt" :return: num of image which not has label """ num = 0 pathI = glob.glob(pathI) pathII = g...
30edbff244acb0014b54cf3c85d86a47d779d226
3,626,212
import math def lcf_float(val1, val2, tolerance): """Finds lowest common floating point factor between two floating point numbers""" i = 1.0 while True: test = float(val1) / i check = float(val2) / test floor_check = math.floor(check) compare = floor_check * test if...
b4bef1a63984440f43a1b0aa9bf9805cb4bfd466
3,626,213
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" if await hass.config_entries.async_unload_platforms(entry, PLATFORMS): hass.data[DOMAIN].pop(entry.entry_id) return True return False
8f7e1a24098033294078d6bec2fcf768c080a398
3,626,214
def get_target_table(session, only_enabled=False, verbose=False): """ Get the complete target table or only the enabled entries """ # TODO why does it not expand the company???? dict_ = table2dict(Target, session, 'TargetID', ["Company", "CompanyName"]) return dict_
5b20397647688ddba824ecc809e2492a69efbf0d
3,626,215
def check_num_row(data): """ @param df: dataframe @return: return 1 if checking condition is true """ return data.shape[0] > 10
0761c4d31bc3a14132d6c1547d03149bd10013c5
3,626,216
def blog_post_feed_richtext_filters(request, format, **kwargs): """ Blog posts feeds - maps format to the correct feed view. """ try: return {"rss": PostsRSSRichtextFilters, "atom": PostsAtomRichtextFilters}[format](**kwargs)(request) except KeyError: raise Http404()
bb6798d1b2113d8d0205d5dc47b96b0fb6aae6b6
3,626,217
def _convert_text_to_logs_format(text: str) -> str: """Convert text into format that is suitable for logs. Arguments: text: text that should be formatted. Returns: Shape for logging in loguru. """ max_log_text_length = 50 start_text_index = 15 end_text_index = 5 return...
4f7ff95a5cd74bdccd41559f58292cc9b1003ba2
3,626,218
def force_langston_contact_agent_agent(r_tot, d, n, v, t, mu, kappa, damping): """Frictional contact force between agent and agent (Helbing, 2000).""" return mu * (r_tot - d) * n + kappa * (r_tot -d) * dot2d(v, t) * t + damping * dot2d(v, n) * n
b04500bf0ecc2c4e97803a3bca1b7f7bbc0aa435
3,626,219
def glossary(): """Generates glossary data""" data = [] for item in sorted(reference.ACRONYMS.items()): data.append({ "type": "Acronym", "code": item[1], "definition": item[0] }) for item in sorted(reference.ABBREVIATIONS.items()): data.appen...
7172c6f727ee1e9a6fe035d185f0e0e03537f65a
3,626,220
import random def generate_random_slug(length=40, prefix=None): """ This function is used, for example, to create Coupon code mechanically when a customer pays for the subscriptions of an organization which does not yet exist in the database. """ if prefix: length = length - len(prefix...
add5e68d0ed6d3831993410afc5ec7900eb212c4
3,626,221
import re def get_easy_variables(website_rules, url, settings): """Stuff that can be found without parsing the DOM -- its easy""" website_variables = {} website_variables["URL"] = { 'content': url.full_url, 'strength': 'high', 'type': 'attr' } website_variables["DOMAIN"] =...
9bec73093c3408c0616269054ce511239b15f4cd
3,626,222
def order_of_magnitude(x): """Determine the order of magnitude of the numeric input (`int`, `float`, :meth:`numpy.array` or :meth:`pandas.Series`). Examples -------- >>> order_of_magnitude(11) array(1.) >>> order_of_magnitude(234) array(2.) >>> order_of_magnitude(1) array(0.) >>...
f8a5a8f0dad2fc86c2cb00c4af6f9c970cd99fce
3,626,223
def lines_of_words(S, W, text_words): """Convert index of first words to list of lines Take the "S" that's computed by a line breaking algorithm and converts it to a list of lines, where each line is a list of words. """ assert sorted(S.keys()) == list(range(1, 1+max(S.keys()))), [ sort...
07d3adfcf0e6cb292e30fd829ded2fafd80ebe50
3,626,224
import argparse def set_cmd_line_args(): """ get the command-line arguments needed to convert the Excel input file into Define-XML :return: return the argparse object with the command-line parameters """ parser = argparse.ArgumentParser() parser.add_argument("-i", "--input_file", help="path an...
00f141f77bdfbaff54f82a9a24f5c98475e14f26
3,626,225
def digits_to_num(L, reverse=False): """Returns a number from a list of digits, given by the lowest power of 10 to the highest, or the other way around if `reverse` is True""" digits = reversed(L) if reverse else L n = 0 for i, d in enumerate(digits): n += d * (10 ** i) return n
1648073d46411fd430afea4f40f7fa9f4567793c
3,626,226
def dynamics(q, u, p): """ Returns state derivative qdot. Takes current state q, motor input torque u, and disturbance torque p. See <http://renaissance.ucsd.edu/courses/mae143c/MIPdynamics.pdf> (rederived with incline). """ # Angle of pendulum in incline frame ang = q[2] - incline # M...
9d36bdb0218b15f91d6d49a489dd39cc2785becd
3,626,227
import json def main(): """ This assumes that the offline model pipeline was already processed, meaning the feature extractors & model can be loaded from AWS S3 """ app = Flask(__name__) # build AWS S3 Client & point to the bucket s3 = build_s3() bucket_name = 'team-03-bucket' #...
3492e9b2a00fb313344fa1d07af9a9cf2e44219c
3,626,228
def escape_and_join(args): """Creates a shell-escaped string from a list of arguments.""" escaped = [] for x in args: if x.startswith("$"): # This is a hack because a rule in //fpga/defs.bzl wants to pass # $XCELIUM_PATH as an argument, and have the shell expand it correctly....
0b11fe4268ed3b2e6b7756faeaeace8dcfd248dd
3,626,229
import torch def mean_shift_smart_init(X, kappa, num_seeds=100, max_iters=10, metric='cosine'): """ Runs mean shift with carefully selected seeds @param X: a [n x d] torch.FloatTensor of d-dim unit vectors @param dist_threshold: parameter for the von Mises-Fisher distribution @param num_s...
a4661dbad7c415a75aa5ba06a2f1a69df5b79a97
3,626,230
def mergesort(*tables, **kwargs): """ Combine multiple input tables into one sorted output table. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... ['A', 9], ... ['C', 2], ... ['D', 10], ... ['A', 6], ...
724fb395f77e680b0641d3f953d926e41a0fe7c9
3,626,231
def _normalizeGlifPointAttributesFormat2(element): """ - Follow same rules as Format 1, but allow an identifier attribute. """ attrs = _normalizeGlifPointAttributesFormat1(element) identifier = element.attrib.get("identifier") if identifier is not None: attrs["identifier"] = identifier ...
60e7411c84cf45c255116d12e56ef449ee2aac37
3,626,232
def fetch_account_balance(pubKey: str = REWARD_PUBLIC_KEY) -> float: """ Returns the balance of the given account available to be send """ try: acc = server.accounts().account_id(pubKey).call() except Exception as e: print(f"Specified account ({pubKey}) does not exists:", e) ...
c1283b9d3e079a1168286ca6e5f4e73a22dca9f9
3,626,233
def identify_formation_channels(seeds, file): """Identify the formation channel that produced each seed. We consider 5 main channels: classic, only stable, single core CEE, double core CEE and other. We define the channels as follows (the numbers are what is put in the ``channels`` output): Classic...
d245f08a6d3192ea56117f9e2a9440029ce60f66
3,626,234
def _read_stimtime_FSL(stimtime_files, n_C, n_S, scan_onoff): """ Utility called by gen_design. It reads in one or more stimulus timing file comforming to FSL style, and return a list (size of [#run \\* #condition]) of dictionary including onsets, durations and weights of each event. Pa...
d83c27a3e3f1b80c224ec4b93c514a82eced6964
3,626,235
import collections def parse_map(map_file): """ Parse a given map file (compilation output). """ sections = [ "Preamble", "Allocating common symbols", "Discarded input sections", "Memory Configuration", "Linker script and memory map", "OUTPUT", ...
2aec206820540445e476cb4d4333e95e5b76d7e4
3,626,236
def parse_sge_script(local_script_path): """ Parse the SGE script :returns: A dictionary of the options for constructing AiiDAJobFirework """ with open(local_script_path) as handle: lines = handle.readlines() options = { 'stdout_fname': '_scheduler-stdout.txt', 'stderr...
df130f5af9d46dd2803cf04b833500aabb276856
3,626,237
from typing import Union from pathlib import Path from typing import Tuple from unittest.mock import Mock import unittest def run_using_a_configuration_file( configuration_path: Union[Path, str], file_to_lint: str = __file__ ) -> Tuple[Mock, Mock, Run]: """Simulate a run with a configuration without really la...
0d66f10f0b8cbe176aeca6c3ec4fdd04e0bc6cfb
3,626,238
import re from pathlib import Path def get_gromacs_version(gmx: str = "gmx") -> int: """ Gets the GROMACS installed version and returns it as an int(3) for versions older than 5.1.5 and an int(5) for 20XX versions filling the gaps with '0' digits. Args: gmx (str): ('gmx') Path to the GROMACS ...
0a1760ecd50ffb7fc0838e6eb7d0c82b10cb3c07
3,626,239
def StepToGeom_MakeConic2d_Convert(*args): """ :param SC: :type SC: Handle_StepGeom_Conic & :param CC: :type CC: Handle_Geom2d_Conic & :rtype: bool """ return _StepToGeom.StepToGeom_MakeConic2d_Convert(*args)
96e7da2ba814bdc2123217fff24784978eabe476
3,626,240
def AllNames(): """(read-only) Array of all Monitor Names""" return get_string_array(lib.Monitors_Get_AllNames)
86ae2263d6ded5a376da48288f40170801f32e5f
3,626,241
def k2_mean(success_tag, ms_results): """ Returns the expectation of k2, the rate constant for the unimolecular step of a resting-set reaction. """ success_kcolls = np.ma.array(ms_results['kcoll'], mask=(ms_results['tags']!=success_tag)) success_t2s = np.ma.array(ms_results['times'], mask=(ms_results['tags']!=s...
b328bd479c81412a86a902d8c4899240b9ae5ad9
3,626,242
def json_network(user, raw=True, callback=None): """ callback=NAME wrap the object definition in a function call NAME(...) ?raw a raw JSON object is returned, instead of an object named Delicious.posts """ url = 'http://del.icio.us/feeds/json/network/' +...
3f0598180b0865ea1624c3cb1cae591022700475
3,626,243
def perform_sigm_times_exp(tree, exp_x=None, exp_minus_x=None, sigm_x=None, sigm_minus_x=None, parent=None, child_idx=None, full_tree=None): """ Core processing of the `local_sigm_times_exp` optimization. This recursive function operates on a multiplica...
5a971326716ecc23517c158810516662108f159e
3,626,244
import time import os def gen_file_name(name=None, prefix='', output_dir='.', extension='log', append_time=True): """ Generate a file name. :param name: a base for the file name :param output_dir: the directory :param extension: give the file an extension :param append_time: append time to th...
8d3179e2cf643be3de19817c07fb074f92044709
3,626,245
def implode(space, w_arg1, w_arg2=None): """Join array elements with a string.""" if w_arg2 is None: if w_arg1.tp != space.tp_array: space.ec.warn("implode(): Argument must be an array") return space.w_Null else: w_arr = w_arg1 string = "" else...
90e78c0f2266b3396606eec50cf5378b2079fba6
3,626,246
def fill_matrix(X: np.ndarray, mixture: GaussianMixture) -> np.ndarray: """Fills an incomplete matrix according to a mixture model Args: X: (n, d) array of incomplete data (incomplete entries =0) mixture: a mixture of gaussians Returns np.ndarray: a (n, d) array with completed data...
18318c0b781706966a787a2a0d53e52714d43628
3,626,247
import torch import tqdm def get_pseudo(t_model, unlabeled_dataset): """ params: t_model: teacher model unlabeled_dataset: unlabeled dataset return: pseudo_label: ndarray[N, C], N=len(dataloader), C for num of class, dim C is output of softmax """ t_model.eval() device ...
fdb880925be00da5007b921ee8e8e0dbdb0caddc
3,626,248
import sys import os def executable(name): """Return the full path to an executable""" suffix = "" folder = "bin" if sys.platform == "win32": suffix = ".exe" folder = os.path.join(folder, "Release") return os.path.join("..", folder, name + suffix)
8fbc4aa30e5ad3aeb126f7c5adbbdd62e68091c2
3,626,249
def CountDictCall(keyfunc): """ Decorator for counting memoizer hits/misses while accessing dictionary values with a key-generating function. Like CountMethodCall above, it wraps the given method fn and uses a CountDict object to keep track of the caching statistics. The dict-key fun...
537a7595eb9cd1752e80e2a4694ec694ef569440
3,626,250
def GetEnumValue(name): """ Finds the value of a particular enum define. Ex kdp_req_t::KDP_VERSION => 0x3 params: name : str - name of enum in the format type::name returns: int - value of the particular enum. raises: TypeError - if the enum is not found ...
7a127a4726d239dad343be99b99ddce0ff82f839
3,626,251
def _group_map_list(_data, _f, *args, _keep=False, **kwargs): """List version of group_map""" return list( regcall( group_map, _data, _f, *args, **kwargs, _keep=_keep, ) )
7c28ddc689b896d96c31898c790e23da1c0ad302
3,626,252
def clean_zeros(a, b, M): """ Remove all components with zeros weights in a and b """ M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd) a2 = a[a > 0] b2 = b[b > 0] return a2, b2, M2
3e2def6e88a7ac5a67b9849a9dcd2f5f5156fb00
3,626,253
def compare(gene, classes): """ Compare the distribution of two or more groups and automatically selects the proper statistical test Args: gene (string): feature to be compared. classes (list of pandas dataframe): list of groups (classes) to compare. Re...
0aae0446b75be80d3b63eb1411599297bf5bba54
3,626,254
def get_powersph_errorbars(k, psph, params): """ Calculate the error bars on spherically-averaged P(k) (1-sigma uncertainty) as a function of k. This is a convenience method, which calls the internal method. Parameters ---------- k : 1D array Values of k at which to calculate error bar...
6ba2e75bbe7245e423cefe80addf313e8b868a98
3,626,255
from typing import List def sum_poly_areas(lop: List[shapely.geometry.Polygon],) -> float: """ Returns a float representing the total area of all polygons in 'lop', the list of polygons. """ sum_acc = 0 for poly in lop: sum_acc += poly.area return sum_acc
643df866d4a6548af85811549dcf895d50e09fcc
3,626,256
def build_importer_component_spec( importer_base_name: str, input_name: str, input_type_schema: pipeline_spec_pb2.ArtifactTypeSchema, ) -> pipeline_spec_pb2.ComponentSpec: """Builds an importer component spec. Args: importer_base_name: The base name of the importer node. dependent_task: The tas...
f3fc23129c4e68599032115c62405ed2bdadeca2
3,626,257
import types def hpat_pandas_series_max(self, axis=None, skipna=None, level=None, numeric_only=None): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.max Limitations ----------- Parameters ``axis``, ``level`` and ``n...
c5a88afb0baead19c950de46eb0694b467fb1bb7
3,626,258
def train_predictor(predictor, train_data, train_target, hyperparameter, metric='accuracy', n_folds=5): """ Cross validation training in order to find best parameter. :param predictor: :param train_data:...
8109d76d246388e30265da24f7ea64281777f146
3,626,259
from typing import Callable def make_vector_laplace(bcs: Boundaries) -> Callable: """make a discretized vector laplace operator for a cylindrical grid {DESCR_CYLINDRICAL_GRID} Args: bcs (:class:`~pde.grids.boundaries.axes.Boundaries`): {ARG_BOUNDARIES_INSTANCE} Returns: ...
dcb126a941fab660c0fae209df8959fbb9ed1e3c
3,626,260
import hashlib def extract_keys(key: bytes) -> str: """Derive a key1,key2, key3 from a password str and returns a hex tuple (key1, key2, key3) """ digest = hashlib.sha256(key).digest() key1 = hexlify(digest) key2 = hashlib.sha256(digest).hexdigest() key3 = hashlib.sha256(hashlib.sha256(digest).dig...
085c889c979949d92f6f887e1cddf4f3e2587041
3,626,261
def add_user(user): """ Add a user in the database return Boolean """ try: with session_scope() as session: u = User(**user) session.add(u) return True, None except exc.IntegrityError as e: return False, str(e)
1dfb33feda4ec68d7e4518229334da137806621e
3,626,262
def _port_speed_prices_table(port_speeds, prices=False): """Shows Server Port Speeds prices cost and capacity restriction. :param [] port_speeds: List of Hardware Server Port Speeds. :param prices: Create a price table or not """ if prices: table = formatting.Table(['Key', 'Speed', 'Hourly'...
50b437041d83606ccd547c56fa5898b6a38079a5
3,626,263
def conversion(pid, offset, sequences, directory, file_count): """ This function calls all functions required for the full latex to png conversion for a subset of the sequences. It is meant to be called for a single process. The respective subset depends on the given offset. :param pid: The identifier ...
a9cc2efbc0f99c240e59af336c08192ef06d2bb2
3,626,264
def conv_nested(image, kernel): """A naive implementation of convolution filter. This is a naive implementation of convolution using 4 nested for-loops. This function computes convolution of an image with a kernel and outputs the result that has the same shape as the input image. Args: ima...
92f88cd82370de680ea10ebe3e50355e2be6e1d1
3,626,265
import re def get_cheque_code(cheque: str): """Get code""" if ( re.search(r'BTC_CHANGE_BOT\?start=', cheque) or not re.search(r'BTC_CHANGE_BOT\?start=', cheque) and re.search(r'Chatex_bot\?start=', cheque) ): return re.findall(r'c_\S+', cheque)[0] elif re.se...
97d0b3cadfb6010b48ed6fb148083060c50720ff
3,626,266
def findKthLargest(nums, k): """ :type nums: List[int] :type k: int :rtype: int """ # sol 1 # nums.sort() # return nums[-k] # sol 2 # return select(nums, 0, len(nums)-1, k) # sol 3 return search(nums,k)
af5af39c4f0634f57ad4f9c26b8022611bd2ee9e
3,626,267
def check_round_change(fromBlock, toBlock): """Checks for round initilized txs between blockOld and block. If an event exists, get the blocknumber of this tx and the round number """ round_filter = w3.eth.filter({ "fromBlock": fromBlock, "toBlock": toBlock, "address": ROUND_MANAGER_PROX...
b5e2033918dd22b5ecf59ca131a32bc7cbdde53f
3,626,268
import logging import traceback def async_phonology(args, task_key, cache_kwargs, storage, sqlalchemy_url): """ Asynchronous phonology compilation. """ # This is a no-op with current settings, we use it to enable logging inside celery tasks, because # somehow this does it, and otherwise we couldn...
e51e63543ac1f791989ac1d643acd3844b457e28
3,626,269
def dice_coef_loss(target, prediction, axis=(1,2,3), smooth=1.0): """ Sorenson Dice loss Using -log(Dice) as the loss since it is better behaved. Also, the log allows avoidance of the division which can help prevent underflow when the numbers are very small. """ intersection = tf.reduce_sum(...
4bf384be1e9fe2073f412a7682f89f18403ccd2c
3,626,270
def option_names_not_in_cfg(cfg, options): """ Returns names of *options* not seen in the *cfg* dictionary, typically parsed from an external configuration file. Parameters ---------- cfg : dict options : :py:class:`~enrich2.plugins.options.Options` Returns ------- `list` ...
30f707d8420cef4d2021cf305e0065fe9649ea22
3,626,271
from datetime import datetime def _unpack_data(buffer): """Unpack received data >>> d = _unpack_data(bytes.fromhex('AA 11 00 08 00 BC 6E 00 3E 9C 01 89 00 00 1E 26 0F 0F 08 13 9E')) >>> d == {"datetime": "2019-08-15 15:38:30", "V": 105.534, "mA": 221.46875, "W": 0.685} True Args: buf...
65d97af9fbf27e23de831c8031cdfa0a9359e5d5
3,626,272
def fit_mgauss(x, y, x0, n, c=(-np.inf, np.inf), thresh=-1, ftol=1e-4, xtol=1e-4, scale=0, maxiter=100, verbose=False): """ Fit a symmetric multigauss to the provided 1-D data. *Arguments*: - x = x values of data to fit. - y = y values of data to fit. - x0 = the initial guess as a stacked (1...
9b67725a9c61be0c8cc06cb7d5347f591109469f
3,626,273
def list_files_with_extension(root_path, extension, full_path=True, recursively=True): """List all files paths in a folder, filtered by a given suffix. Parameters ---------- root_path : Path Top level folder, start search here. extension : str Extension...
5bd9d44573250c84ce7bcafb7c90b68fcd57d896
3,626,274
import torch def get_power_online(signal: ComplexTensor) -> torch.Tensor: """Calculates power for `signal` Args: signal : Single frequency signal with shape (F, C, T). axis: reduce_mean axis Returns: Power with shape (F, ) """ power = signal.real ** 2 + signal...
f7c1ad0dbdee60b7a0db14ea1d87fadeb8778f9e
3,626,275
def transform(model, pretrained=False, gamma=0.9, mem=False): """Return the MomentumNet counterpart of the model Parameters ---------- model : a torchvision model The resnet one desires to turn into a momentumnet pretrained : bool (default: False) Whether using a pretrained resnet ...
849c076b25ceb27ae17dbf9f2743c5b0cfe1c5be
3,626,276
def getListArrayDim(self, ainput, dim=0): """ get the dimension of a list returns -1 if it is no list at all, 0 if list is empty and otherwise the dimensions of it """ if isinstance(ainput, (list, np.ndarray)): if ainput == []: return dim dim = dim + 1 dim =...
c1c336b66f7a9412ed22877f1ac683c617f58280
3,626,277
def exp_two(arg1, arg2): """ (float, float) -> float Exponentiates two numbers (arg1 ** arg2) Returns the exponent """ try: return arg1 ** arg2 except TypeError: return 'Unsupported operation: {0} ** {1} '.format(type(arg1), type(arg2))
ec63d4d8d4e45590918a53ddc8654bc93bd4a435
3,626,278
import sys import six def crud_exceptions(fn): """A decorator designed to catch exceptions from the crud api methods.""" @wraps(fn) def wrapped(*args, **kwargs): try: return fn(*args, **kwargs) except: a = [x for x in (args or [])] kw = {k : v for k, v i...
4eb55f51b99e05ada94fddd76d320c9eeca070ca
3,626,279
def parse_problems(lines): """ Given a list of lines, parses them and returns a list of problems. """ return [len(p) for p in lines]
83747e57bddf24484633e38ce27c51c7c8fce971
3,626,280
import struct import binascii def decode_trace_resp(payload, offset, trace_resp_header_values): """Decode headers for a OAM Trace Response""" sf_type = None sf_name = None trace_header = payload[offset:offset+NSH_OAM_TRACE_HDR_LEN] _header_values = struct.unpack('!B B H I I I I', trace_header) ...
df2c263c4bd23c5baad3ca93b52dca5b0d94dee4
3,626,281
def standard_lv(env_name, remove_q=True, static_feeds_new=None, clear_loads_sgen=False, clear_gen=True, battery_locations=None, percent_battery_buses=0.5, batteries_on_leaf_nodes_only=True, init_soc=0.5, energy_capacity=20.0, gen_locations=None, gen_p_max=0.0, gen_p_min=-50.0, ...
dbe1d0cf30cc6c677daae0c74016e9841ac1a323
3,626,282
from .authorize import oauth from typing import Callable from typing import Any def oauth_require_read_schema_scope(f: 'Callable[..., Any]'): """(User以外の)メタデータを読むだけのScopeデコレータ. :param Callable f: Function """ return oauth.require_oauth(CRScope.SCHEMA_R.value, CRScope.SCHEMA_RW.value)(f)
908818816d696177ce761f453e0893d4777d241a
3,626,283
import urllib3 import certifi def load_content(site, host, links): """Tests a site.""" # Security: Verified HTTPS with SSL/TLS http = urllib3.PoolManager( cert_reqs='CERT_REQUIRED', # Force certificate check. ca_certs=certifi.where(), # Path to the Certifi bundle. ) start_page_sea...
5a599579133297c2e6ab3231b466f1b6184d22cc
3,626,284
def flag(request, comment_id, next=None): """ Flags a comment. Confirmation on GET, action on POST. Templates: :template:`comments/flag.html`, Context: comment_id The id of the comment the user is flagging. """ comment = get_object_or_404( get_comment_model(), ...
99f445fadcd088071651837e1d9fda9fea2b0d22
3,626,285
def decodeGsm7(encodedText): """ GSM-7 text decoding algorithm Decodes the specified GSM-7-encoded string into a plaintext string. @param encodedText: the text string to encode @type encodedText: bytearray or str @return: A string containing the decoded text @rtype: str """ ...
28ca699a8f1637637a76e375056b1f48d8807e9f
3,626,286
def Setup_Meta(): """Setup_Meta() -> MetaObject""" return _DataModel.Setup_Meta()
cc66b9e0e8e95ecaa1dd0211fd260ed4755d20a0
3,626,287
def get_types_dict(): """ :return: type name read in as string to type method mapping """ return {"str": str, "float": float, "int": int}
7a386fa63cba73e35672b15c31bc8b2c59361f24
3,626,288
def key_pressed(key): """ Takes a key, that's either a keycode or a character, and says if it was pressed down this frame. """ keycode = _to_keycode(key) return (keycode in current_frame_held_buttons) and \ (keycode not in last_frame_held_buttons)
26d1716cdfcb187a661418b77114611a8945e7b3
3,626,289
def makeDir(path, name): """ create dir for the generation process""" print "path", path print "name",name dirname = path + os.sep + name try: os.makedirs(dirname) return dirname except: print "makeDir> ERROR creating dir [%s]: %s" % (dirname, exc_info()[1]) retur...
1874d52e00e31aa3a2d1b67cb791af622a879438
3,626,290
def load_gp(param_file=None, **kwargs): """Return two Gaussian Processes objects, either using BSFH's internal GP objects or George. :returns gp_spec: The gaussian process object to use for the spectroscopy. :returns gp_phot: The gaussian process object to use for the photometry. "...
e216001c0942e2efacc2631c52d2c6dd42a0caed
3,626,291
from pydantic import BaseModel # noqa: E0611 def monte_carlo(model, num, qobs=None, **kwargs): """Perform Monte-Carlo-Simulation. This function performs a Monte-Carlo-Simulation for any given hydrological model of this repository. Args: model: Any instance of a hydrological model of this re...
95e29fa77535733214d6f5bee293fa4dfdf361c2
3,626,292
from typing import Union import os from typing import Any from typing import Optional from pathlib import Path import tempfile def read_file_sql( path: Union[str, "os.PathLike[Any]"], sql_stmt: str, sql_dialect: str = "SQLITE", layer: Optional[str] = None, ignore_geometry: bool = False, ) -> Union...
6d7d810fa8ea40b6dc794b7dedffa19e9a2125f8
3,626,293
def create_class_hierarchy_dict(cls): """Returns the dictionary with all members of the class ``cls`` and its superclasses.""" dict_extension_order = cls.__mro__[-2::-1] # Reversed __mro__ without the 'object' class attrs_dict = {} for base_class in dict_extension_order: attrs_dict.update(vars(...
0378fb3243a48964fcec42fddb38c0664a338ee4
3,626,294
def get_column_selection(summary_set): """ Given a analysis_settings summary definition, return either 1. the set of OED columns requested to group by 2. If no information key 'oed_fields', then group all outputs into a single summary_set :param summary_set: summary group dictionary from th...
2cdb9a74a65cb9a217f2296a7e8ce22557095314
3,626,295
from typing import List from typing import Optional def randomForestSearch( operations: OperatorSet, output: List[Individual], start_candidates: List[Individual], max_evaluations: Optional[int] = None, ) -> List[Individual]: """ Perform random search over all possible pipelines. Parameters ...
74197bfdd7b993db24a03f0f247a5eae40696859
3,626,296
from datetime import datetime def month_to_date(month): """ Convert month to date format. Keyword arguments: month -- the month to convert to date format """ month = datetime.strptime(month, '%Y-%m') date = month.strftime('%Y-%m-%d') # eg 2018-02-01 date = datetime.strptime(date, '...
e417eefa63430e422a53bd194fbb1e0d5e453c7b
3,626,297
from datetime import datetime def exact_cftime_datetime_difference(a, b): """Exact computation of b - a Assumes: a = a_0 + a_m b = b_0 + b_m Here a_0, and b_0 represent the input dates rounded down to the nearest second, and a_m, and b_m represent the remaining microseconds asso...
f05c6cdd7cb9c211fb50fc493f1bac25dce15b92
3,626,298
def encode(string): """Encode some critical characters to html entities.""" return string.replace('&', '&amp;') \ .replace('<', '&lt;') \ .replace('>', '&gt;') \ .replace(' ', '&nbsp;&nbsp;') \ .replace('\n', ...
faea4b2f2e032b5e05e2c99bc56a1cf35e60b85d
3,626,299