content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List from typing import Union def bytes_to_string( bytes_to_convert: List[int], strip_null: bool = False ) -> Union[str, None]: """ Litteral bytes to string :param bytes_to_convert: list of bytes in integer format :return: resulting string """ try: value = "".joi...
a04dee89fb8aed33b6069a7ff0ca8c497d0a6062
16,300
def interpolate(t,y,num_obs=50): """ Interpolates each trajectory such that observation times coincide for each one. Note: initially cubic interpolation gave great power, but this happens as an artifact of the interpolation, as both trajectories have the same number of observations. Type I error wa...
2418aaf207b214069f45571a21a2b97ecd25f244
16,301
import re def locktime_from_duration(duration): """ Parses a duration string and return a locktime timestamp @param duration: A string represent a duration if the format of XXhXXmXXs and return a timestamp @returns: number of seconds represented by the duration string """ if not duration: ...
c65339ee00e750e4425a68215b0600c71136ee68
16,302
def black_payers_swaption_value_fhess_by_strike( init_swap_rate, option_strike, swap_annuity, option_maturity, vol): """black_payers_swaption_value_fhess_by_strike Second derivative of value of payer's swaption with respect to strike under black model. See :py:fun...
0645992c65e9e13ee44ad3debfe30fb0b05bfae7
16,303
def get_resource(cls): """ gets the resource of a timon class if existing """ if not cls.resources: return None resources = cls.resources assert len(resources) == 1 return TiMonResource.get(resources[0])
370f0af23fcfe0bf5da3b39012a5e1e9c29b6f0e
16,304
def _log(x): """_log to prevent np.log_log(0), caluculate np.log(x + EPS) Args: x (array) Returns: array: same shape as x, log equals np.log(x + EPS) """ if np.any(x < 0): print("log < 0") exit() return np.log(x + EPS)
e7e7b963cf3cec02ace34256ccdf954a2d61dd4a
16,305
import math def gauss_distribution(x, mu, sigma): """ Calculate value of gauss (normal) distribution Parameters ---------- x : float Input argument mu : Mean of distribution sigma : Standard deviation Returns ------- float Probability, values f...
05cf2c14b337b45a81ddbe7655b4d7cf21e352cd
16,306
def extend_vocab_OOV(source_words, word2id, vocab_size, max_unk_words): """ Map source words to their ids, including OOV words. Also return a list of OOVs in the article. WARNING: if the number of oovs in the source text is more than max_unk_words, ignore and replace them as <unk> Args: source_w...
2d1b92d9d6b9b3885a7dda6c8d72d80d3b8ecad0
16,307
def isint(s): """**Returns**: True if s is the string representation of an integer :param s: the candidate string to test **Precondition**: s is a string """ try: x = int(s) return True except: return False
b15598aee937bcce851ee6c39aa2ba96a84a5dd5
16,308
def create_app(config_name): """function creating the flask app""" app = Flask(__name__, instance_relative_config=True) app.config.from_object(config[config_name]) app.config.from_pyfile('config.py') app.register_blueprint(v2) app.register_error_handler(404, not_found) app.register_error_han...
7e49a1ee9bae07a7628842855c3524794efaa9c5
16,309
def build_attention_network(features2d, attention_groups, attention_layers_per_group, is_training): """Builds attention network. Args: features2d: A Tensor of type float32. A 4-D float tensor of shape [batch_size, height,...
c665994b88027c24ed86e01514fa3fc176a3258a
16,310
def get_catalog_config(catalog): """ get the config dict of *catalog* """ return resolve_config_alias(available_catalogs[catalog])
4d36bc8be8ca2992424f0b97f28d3ac8d852c027
16,311
def manhatten(type_profile, song_profile): """ Calculate the Manhatten distance between the profile of specific output_colums value (e.g. specific composer) and the profile of a song """ # Sort profiles by frequency type_profile = type_profile.most_common() song_profile = song_profile.mo...
4703585f9f60551bf2a5e2762612d45efb47a453
16,312
def raven(request): """lets you know whether raven is being used""" return { 'RAVEN': RAVEN }
3e047db45a597cf808e5227b358a9833fc0a4fc3
16,313
from typing import Union def _non_max_suppress_mask( bbox: np.array, scores: np.array, classes: np.array, masks: Union[np.array, None], filter_class: int, iou: float = 0.8, confidence: float = 0.001, ) -> tuple: """Perform non max suppression on the detection output if it is mask. ...
742261f1854f2ad6d01046926c6017b72a1917a4
16,314
import sys import os import csv def main(args): """ In order to detect discontinuity, two lines are loaded. If the timestamp differs by more than the threshold set by -time-threshold, then the distance between points is calculated. If the distance is greater than the threshold set by -distance-threshold then t...
0371b44a1855bce71e411c24413fabd100d9ad79
16,315
def _mark_untranslated_strings(translation_dict): """Marks all untranslated keys as untranslated by surrounding them with lte and gte symbols. This function modifies the translation dictionary passed into it in-place and then returns it. """ # This was a requirement when burton was written, but...
d15ac2d0fe8d50d5357bcc1e54b9666f7076aefd
16,316
import warnings import codecs def build(app, path): """ Build and return documents without known warnings :param app: :param path: :return: """ with warnings.catch_warnings(): # Ignore warnings emitted by docutils internals. warnings.filterwarnings( "ignore", ...
09049aad0d46d07144c3d564deb0e5aaf1b828ca
16,317
import argparse def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Fasta parser for GC content', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'fasta', metavar='FILE', nargs='+', help='FASTA file(s)') ...
6222faed678045afb430bd993df1b53f12130ddc
16,318
def SMWatConstrained(CSM, ci, cj, matchFunction, hvPenalty = -0.3, backtrace = False): """ Implicit Smith Waterman alignment on a binary cross-similarity matrix with constraints :param CSM: A binary N x M cross-similarity matrix :param ci: The index along the first sequence that must be matched to c...
a66f17bb40e201a6758c1add4a1590672724dc3e
16,319
def check_images( coords, species, lattice, PBC=[1, 1, 1], tm=Tol_matrix(prototype="atomic"), tol=None, d_factor=1.0, ): """ Given a set of (unfiltered) frac coordinates, checks if the periodic images are too close. Args: coords: a list of fractional coordinates ...
20f3ada0aa391d989b638a835581226bd79439f7
16,320
def get_hamming_distances(genomes): """Calculate pairwise Hamming distances between the given list of genomes and return the nonredundant array of values for use with scipy's squareform function. Bases other than standard nucleotides (A, T, C, G) are ignored. Parameters ---------- genomes : list...
dad2e9583bd7fcbbbb87dd93d180e4de39ea3083
16,321
from typing import Dict def serialize(name: str, engine: str) -> Dict: """Get dictionary serialization for a dataset locator. Parameters ---------- name: string Unique dataset name. engine: string Unique identifier of the database engine (API). Returns ------- dict ...
9ab11318050caf3feb4664310e491ed48e7e5357
16,322
import torch def repackage_hidden(h): """ Wraps hidden states in new Variables, to detach them from their history. """ if isinstance(h, torch.Tensor): return h.detach() else: return tuple(v.detach() for v in h)
0ab8cffeaafaf6f39e2938ce2005dbca1d3d7496
16,323
import shutil import os import stat def test_exception_during_cleanup(capfd): """ Report exceptions during cleanup to stderr """ original_rmtree = shutil.rmtree delete_paths = [] def make_directory_unremoveable(path, *args, **kwargs): os.chmod(path, stat.S_IRUSR) # remove x permission so we ...
668643b56cce15c75ea4b2560aa7c58c4b8cff62
16,324
def support_acctgroup_acctproject(version): """ Whether this Lustre version supports acctgroup and acctproject """ if version.lv_name == "es2": return False return True
858ec772a90e66431731ffcdd145fa7e56daad02
16,325
def decodeInventoryEntry_level1(document): """ Decodes a basic entry such as: '6 lobster cake' or '6' cakes @param document : NLP Doc object :return: Status if decoded correctly (true, false), and Inventory object """ count = Inventory(str(document)) for token in document: if token.p...
a283f3630a18cdbb0cc22664e583f00866ff759b
16,326
import os def target_precheck(root_dir, configs_dir, target_name, info_defaults, required_scripts): """ Checks: 1. That the target (subsys or experiment) config includes an 'active' field indicating whether to run it 2. If the target is active, check that all required scripts a...
fc5bb4f3406805dffcbd06a30e41af41fbf270bb
16,327
from typing import Collection def from_ir_objs(ir_objs: Collection[IrCell]) -> AnnData: """\ Convert a collection of :class:`IrCell` objects to an :class:`~anndata.AnnData`. This is useful for converting arbitrary data formats into the scirpy :ref:`data-structure`. {doc_working_model} Param...
55e95b2673d6aec02ae5aa7fb5cec014db17cdc7
16,328
def s3_is_mobile_client(request): """ Simple UA Test whether client is a mobile device @todo: parameter description? """ env = request.env if env.http_x_wap_profile or env.http_profile: return True if env.http_accept and \ env.http_accept.find("text/vnd.wap.wml") > 0...
916e6b01c6375c18335f332a0411cb2a034c962a
16,329
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start<br/>" f"/api/v1.0/start/end" )
bac64c3b2d2e5d883f627dada658cdd9359b61b0
16,330
from typing import List def get_cases_from_input_df(input_df: pd.DataFrame) -> List[Case]: """ Get the case attributes :return: """ cases: List[Case] = [] for index, row in input_df.iterrows(): # Create a case object from the row values in the input df cases.append(Case.from_...
34b820880691456fde3ab260be02646590aeafd7
16,331
import torch def init_STRFNet(sample_batch, num_classes, num_kernels=32, residual_channels=[32, 32], embedding_dimension=1024, num_rnn_layers=2, frame_rate=None, bins_per_octave=None, time_support=No...
bdc39fef1889c21d18fda8da308f81f5f03a485c
16,332
from typing import AnyStr import unicodedata def normalize_nfc(txt: AnyStr) -> bytes: """ Normalize message to NFC and return bytes suitable for protobuf. This seems to be bitcoin-qt standard of doing things. """ str_txt = txt.decode() if isinstance(txt, bytes) else txt return unicodedata.norm...
12b6e037225878e0bbca1d52d9f58d57abb35746
16,333
from typing import Callable from typing import Any import threading import functools def synchronized(wrapped: Callable[..., Any]) -> Any: """The missing @synchronized decorator https://git.io/vydTA""" _lock = threading.RLock() @functools.wraps(wrapped) def _wrapper(*args, **kwargs): wit...
39da1efeb93c8dbdba570763d2e66dc8d9d84fc5
16,334
def corrgroups60__decision_tree(): """ Decision Tree """ return sklearn.tree.DecisionTreeRegressor(random_state=0)
fb2405c54208705a105b225e1dd269d45892b7be
16,335
def auth_required(*auth_methods): """ Decorator that protects enpoints through multiple mechanisms Example:: @app.route('/dashboard') @auth_required('token', 'session') def dashboard(): return 'Dashboard' :param auth_methods: Specified mechanisms. """ login_...
c6613e594abbb979352fe3ec96018fe52109bab0
16,336
def _get_default_data_dir_name(): """ Gets default data directory """ return _get_path(DATA_DIR)
b4207e108a9f08a72b47c44ab43b3971e67e8165
16,337
def point_inside_triangle(p, t, tol=None): """ Test to see if a point is inside a triangle. The point is first projected to the plane of the triangle for this test. :param ndarray p: Point inside triangle. :param ndarray t: Triangle vertices. :param float tol: Tolerance for barycentric coordina...
a7a4dd52dfa65fdd9e3cb3ac151c7895acb3abb8
16,338
from datetime import datetime def merge_dfs(x, y): """Merge the two dataframes and download a CSV.""" df = pd.merge(x, y, on='Collection_Number', how='outer') indexed_df = df.set_index(['Collection_Number']) indexed_df['Access_Notes_Regarding_Storage_Locations'].fillna('No note', inplace=True) tod...
9856d4394ca628fd7eb0f58e6cc805494410c51e
16,339
def consumer(func): """A decorator function that takes care of starting a coroutine automatically on call. See http://www.dabeaz.com/generators/ for more details. """ def start(*args, **kwargs): cr = func(*args, **kwargs) next(cr) return cr return start
e834a081c1f43545684bb4102a92b186c8825f30
16,340
def convert_openfermion_op(openfermion_op, n_qubits=None): """convert_openfermion_op Args: openfermion_op (:class:`openfermion.ops.QubitOperator`) n_qubit (:class:`int`): if None (default), it automatically calculates the number of qubits required to represent the given operator ...
416eccc82fbd7dbdcf61ba62f5176ca3e12a01db
16,341
def ssqueeze(Wx, w, ssq_freqs=None, scales=None, fs=None, t=None, transform='cwt', squeezing='sum'): """Calculates the synchrosqueezed CWT or STFT of `x`. Used internally by `synsq_cwt` and `synsq_stft_fwd`. # Arguments: Wx or Sx: np.ndarray CWT or STFT of `x`. w: ...
4c862d13b1cf046c927e187a4b3c9aaed55a7277
16,342
def ConvertStringsToColumnHeaders(proposed_headers): """Converts a list of strings to column names which spreadsheets accepts. When setting values in a record, the keys which represent column names must fit certain rules. They are all lower case, contain no spaces or special characters. If two columns have the...
dd3ce0f9710aeaa778975b1c14d5166d1d2a2446
16,343
import os def parse_interactions(filename="train.csv"): """ Parse the train data and return the interaction matrix alone """ with open(os.path.join(data_path, filename), "r") as f: # Discard first line lines = f.readlines()[1:] num_lines = len(lines) # Create container ...
fb35ccee5cf577a2c85239175859781c84fe7eed
16,344
def recommend(uid, data, model, top_n = 100): """ Returns the mean and covariance matrix of the demeaned dataset X (e.g. for PCA) Parameters ---------- uid : int user id data : surprise object with data The entire system, ratings of users (Constructed with reader from surpri...
b156826359e3310c8872a07428d0073795ef071b
16,345
import os import threading def threading_data(data=None, fn=None, thread_count=None, path = None): """Process a batch of data by given function by threading. Usually be used for data augmentation. Parameters ----------- data : numpy.array or others The data to be processed. thread_co...
5a21912de3ac6f146975b26390a9a7d6a719de52
16,346
def cluster_info(arr): """ number of clusters (nonzero fields separated by 0s) in array and size of cluster """ data = [] k2coord = [] coord2k = np.empty_like(arr).astype(np.int64) k = -1 new_cluster = True for i in range(0,len(arr)): if arr[i] == 0: new_clu...
23a3d58b13ba4af4977cd25a1dc45d116fd812b5
16,347
def set_or_none(list_l): """Function to avoid list->set transformation to return set={None}.""" if list_l == [None]: res = None else: res = set(list_l) return res
ee5fb4539e63afc7fd8013610229d9ab784b88c5
16,348
import re def case_mismatch(vm_type, param): """Return True if vm_type matches a portion of param in a case insensitive search, but does not equal that portion; return False otherwise. The "portions" of param are delimited by "_". """ re_portion = re.compile( "(^(%(x)s)_)|(_(%(x)s)_)|(...
e7fb565ac6e10fd15dd62a64fbf7f14a8bcfde6b
16,349
def _async_os(cls): """ Aliases for aiofiles.os""" return aiofiles.os
ad37b21f22ed5203451ac8eb4b7a53f4572fec73
16,350
import torch def corruption_function(x: torch.Tensor): """ Applies the Gsaussian blur to x """ return torchdrift.data.functional.gaussian_blur(x, severity=5)
54b98c6bddb187689c0e70fc2dbf0f3c56e25ad1
16,351
def filter_by_filename(conn, im_ids, imported_filename): """Filter list of image ids by originalFile name Sometimes we know the filename of an image that has been imported into OMERO but not necessarily the image ID. This is frequently the case when we want to annotate a recently imported image. This f...
bf9625c06929a80f21a4683b1da687535f296e59
16,352
def get_count(): """ :return: 计数的值 """ counter = Counters.query.filter(Counters.id == 1).first() return make_succ_response(0) if counter is None else make_succ_response(counter.count)
be0ab2773e661b8e5e34f685b59f16cfdee6b26d
16,353
import math def perm(x, y=None): """Return the number of ways to choose k items from n items without repetition and with order.""" if not isinstance(x, int) or (not isinstance(y, int) and y is not None): raise ValueError(f"Expected integers. Received [{type(x)}] {x} and [{type(y)}] {y}") return ma...
c9ad65c6ce3cc3e5ba488c5f2ddd1aabbdc7da6a
16,354
import os import logging def check_if_need_update(source, year, states, datadir, clobber, verbose): """ Do we really need to download the requested data? Only case in which we don't have to do anything is when the downloaded file already exists and clobber is False. """ paths = paths_for_year(...
407824edcaa783f22cdf03814ffd110a88fd06e4
16,355
import sys import os import shutil import textwrap def main(argv, cfg=None): """Main method""" # Replace stdout and stderr with /dev/tty, so we don't mess up with scripts # that use ssh in case we error out or similar. if cfg is None: cfg = {} try: sys.stdout = open("/dev/tty", "w"...
7d820da8b1303fa1b0bfe7236ab42c277ab4c0c6
16,356
from typing import Union def ui(candles: np.ndarray, period: int = 14, scalar: float = 100, source_type: str = "close", sequential: bool = False) -> Union[float, np.ndarray]: """ Ulcer Index (UI) :param candles: np.ndarray :param period: int - default: 14 :param scalar: float - default: 100 ...
1f99a6ee849094f3a695812e37035a13f36e8c49
16,357
def _padwithzeros(vector, pad_width, iaxis, kwargs): """Pad with zeros""" vector[: pad_width[0]] = 0 vector[-pad_width[1] :] = 0 return vector
1a3a9fc4fd3b0fc17a905fa9ecd283d60310655d
16,358
def fill_from_sparse_coo(t,elems): """ :param elems: non-zero elements defined in COO format (tuple(indices),value) :type elems: list[tuple(tuple(int),value)] """ for e in elems: t[e[0]]=e[1] return t
73c6892464d7d7cf34f40fe1dde9973950cdef79
16,359
def download_responses(survey_id): """Download survey responses.""" if request.method == 'GET': csv = survey_service.download_responses(survey_id) return Response( csv, mimetype='text/csv', headers={'Content-disposition': 'attachment; filename=surveydata.csv'})
8513caf582b87bf0cd5db80622c530d1ec1c3ef2
16,360
from collections import deque from typing import Iterable from typing import Deque def array_shift(data: Iterable, shift: int) -> Deque: """ left(-) or right(+) shift of array >>> arr = range(10) >>> array_shift(arr, -3) deque([3, 4, 5, 6, 7, 8, 9, 0, 1, 2]) >>> array_shift(arr, 3) deque(...
c14e115808592808bc9b0cf20fa8bc3d5ece7768
16,361
def convert_to_timetable(trains): """ 列車データを時刻表データに変換する関数 Args: trains (list of list of `Section`): 列車データ Returns: timetable (list): 時刻表データ timetable[from_station][to_station][dep_time] = (from_time, to_time) -> 現在時刻が dep_time の時に from_station から to_station まで直近...
042238b090af1b4b4e4a8cf469f9bbcd49edc9af
16,362
import math def parents(level, idx): """ Return all the (grand-)parents of the Healpix pixel idx at level (in nested format) :param level: Resolution level :param idx: Pixel index :return: All the parents of the pixel """ assert idx < 12 * 2 ** (2 * level) plpairs = [] for ind in ...
355c3acffa07065de10049059ef064abefdd7ca0
16,363
def precise_inst_ht(vert_list, spacing, offset): """ Uses a set of Vertical Angle Observations taken to a levelling staff at regular intervals to determine the height of the instrument above a reference mark :param vert_list: List of Vertical (Zenith) Angle Observations (minimum of 3) in Decimal Deg...
d88cf0dc289f2ef96d4b60dabf17c6e4bd04e549
16,364
def _parse_transform_set(transform_dict, imputer_string, n_images=None): """Parse a dictionary read from yaml into a TransformSet object Parameters ---------- transform_dict : dictionary The dictionary as read from the yaml config file containing config key-value pairs imputer_strin...
47e3bf72c9e70bff22bebee7e73a14c349761116
16,365
import json import random def initialize_train_test_dataset(dataset): """ Create train and test dataset by random sampling. pct: percentage of training """ pct = 0.80 if dataset in ['reddit', 'gab']: dataset_fname = './data/A-Benchmark-Dataset-for-Learning-to-Intervene-in-Online-Hate-S...
bac5876be313a85213badcce667af550e8f3f65a
16,366
def load_raw_data_xlsx(files): """ Load data from an xlsx file After loading, the date column in the raw data is converted to a UTC datetime Parameters ---------- files : list A list of files to read. See the Notes section for more information Returns ------- list ...
a2aebdb4d972ef7f46970b3e8fc14ef40ae42bb8
16,367
def filter_production_hosts(nr): """ Filter the hosts inventory, which match the production attribute. :param nr: An initialised Nornir inventory, used for processing. :return target_hosts: The targeted nornir hosts after being processed through nornir filtering. """ # Execute filter ba...
006524e7b014d3f908955fb81d9f928ac7df25d8
16,368
import random def get_lightmap(map_name="random"): """ Fetches the right lightmap given command line argument. """ assert map_name in ["default", "random"] + list(CONSTANTS.ALL_LIGHTMAPS.keys()), f"Unknown lightmap {map_name}..." if map_name == "random": map_name = random.choice(list(CONS...
04ea7e901bbde8ba900469d8ed87b1b3c158809a
16,369
def kill_instance(cook_url, instance, assert_response=True, expected_status_code=204): """Kill an instance""" params = {'instance': [instance]} response = session.delete(f'{cook_url}/rawscheduler', params=params) if assert_response: assert expected_status_code == response.status_code, response.t...
3daa954579b15deedc5a66e77a2178a5682bd1a3
16,370
def _get_n_batch_from_dataloader(dataloader: DataLoader) -> int: """Get a batch number in dataloader. Args: dataloader: torch dataloader Returns: A batch number in dataloader """ n_data = _get_n_data_from_dataloader(dataloader) n_batch = dataloader.batch_size if dataloader.batc...
182e5566c6b9c83d3dabc3c99f32aedf1e3c21e7
16,371
def get_hidden() -> list: """ Returns places that should NOT be shown in the addressbook """ return __hidden_places__
8d201c25dd3272b2a3b2292ef3d8fa5293a97967
16,372
def wait_for_unit_state(reactor, docker_client, unit_name, expected_activation_states): """ Wait until a unit is in the requested state. :param IReactorTime reactor: The reactor implementation to use to delay. :param docker_client: A ``DockerClient`` instance. :param unicode...
73278f8762a9b0c5d78ea4d5e098bb7a41b97072
16,373
def get_list_primitives(): """Get list of primitive words.""" return g_primitives
2429b646fbe2fbcc344e08ddffb64ccf2a2d853d
16,374
def make_graph(edge_list, threshold=0.0, max_connections=10): """Return 2 way graph from edge_list based on threshold""" graph = defaultdict(list) edge_list.sort(reverse=True, key=lambda x: x[1]) for nodes, weight in edge_list: a, b = nodes if weight > threshold: if len(graph...
c9414a0b8df8b9de46ad444b376c5316f1960cd0
16,375
def ping(request): """Ping view.""" checked = {} for service in services_to_check: checked[service.name] = service().check() if all(item[0] for item in checked.values()): return HttpResponse( PINGDOM_TEMPLATE.format(status='OK'), content_type='text/xml', ...
09b3bd76c59e4d69678a6ce9c3018f638248ff88
16,376
import numbers def _num_samples(x): """Return number of samples in array-like x.""" message = 'Expected sequence or array-like, got %s' % type(x) if hasattr(x, 'fit') and callable(x.fit): # Don't get num_samples from an ensembles length! raise TypeError(message) if not hasattr(x, '__l...
18133457621ec7c79add6d0ff9ab8b1b0c17d524
16,377
def inf_compress_idb(*args): """ inf_compress_idb() -> bool """ return _ida_ida.inf_compress_idb(*args)
fd4ef3c50b9fef7213d9f37a0326f5e9f06b9822
16,378
def tokens_history(corpus_id): """ History of changes in the corpus :param corpus_id: ID of the corpus """ corpus = Corpus.query.get_or_404(corpus_id) tokens = corpus.get_history(page=int_or(request.args.get("page"), 1), limit=int_or(request.args.get("limit"), 20)) return render_template_with_n...
d87e4486cb2141b3c59e86a3483f4c445476ca20
16,379
def find_pattern_clumps( text: str, substring_length: int, window_length: int, minimum_frequency: int ): """TODO: [summary] Returns: [type]: [description] """ patterns = set() for index in range(len(text) - window_length + 1): window = text[index : index + window_length] ...
28b102a563008a297a7d1815f99c01211081a86a
16,380
def Hidden(request): """ Hidden Field with a visible friend.. """ schema = schemaish.Structure() schema.add('Visible', schemaish.String()) schema.add('Hidden', schemaish.String()) form = formish.Form(schema, 'form') form['Hidden'].widget = formish.Hidden() return form
3f5d96339c39c7cf186d4d45d837b0e95402d328
16,381
def train_and_eval(trial: optuna.Trial, study_dir: str, seed: int): """ Objective function for the Optuna `Study` to maximize. .. note:: Optuna expects only the `trial` argument, thus we use `functools.partial` to sneak in custom arguments. :param trial: Optuna Trial object for hyper-parameter...
07e1cff3ab9954172ce4c09f673881109df6f08c
16,382
def random_active_qubits(nqubits, nmin=None, nactive=None): """Generates random list of target and control qubits.""" all_qubits = np.arange(nqubits) np.random.shuffle(all_qubits) if nactive is None: nactive = np.random.randint(nmin + 1, nqubits) return list(all_qubits[:nactive])
c9bab4d02a0afc569907c6ec838d0020878a345a
16,383
import re import requests import random import hashlib from bs4 import BeautifulSoup def main(host: str, username: str, password: str): """メイン. Args: host: ホスト名又はIPアドレス username: ユーザ名 password: パスワード """ url: str = f"http://{host}/" rlogintoken: re.Pattern = re.compile(r"c...
36efbd8dc18b891934f690091ef8709e0eddb3ce
16,384
from typing import List import requests def create_label(project_id: int, label_name: str, templates: list, session=konfuzio_session()) -> List[dict]: """ Create a Label and associate it with templates. If no templates are specified, the label is associated with the first default template of the project....
4dda5f7ac6473be76212c03deb6beb7980b44105
16,385
def home(): """ Home page """ return render_template("index.html")
0ac607593cc98871d97c111fc2ca89aa980af83f
16,386
import argparse def get_argparser(): """Argument parser""" parser = argparse.ArgumentParser(description='Bort pretraining example.') parser.add_argument('--num_steps', type=int, default=20, help='Number of optimization steps') parser.add_argument('--num_eval_steps', type=int, ...
2f35f40fc8276b6895ac16ef91187b6d0f60551f
16,387
def get_from_parameterdata_or_dict(params,key,**kwargs): """ Get the value corresponding to a key from an object that can be either a ParameterData or a dictionary. :param params: a dict or a ParameterData object :param key: a key :param default: a default value. If not present, and if key is no...
864936e9b43c18e4a8dfd7d88c1cedda28fdb23d
16,388
import torch def test_input_type(temp_files, fsdp_config, input_cls): """Test FSDP with input being a list or a dict, only single GPU.""" if torch_version() < (1, 7, 0): # This test runs multiple test cases in a single process. On 1.6.0 it # throw an error like this: # RuntimeErro...
6bf7d03f51088518e85d3e6ea8f59bcc86e4a0b4
16,389
def get_heroesplayed_players(matchs_data, team_longname): """Returns a dict linking each player to - the heroes he/she played - if it was a win (1) or a loss (0) """ picks = get_picks(matchs_data, team_longname) players = get_players(picks) results = get_results(matchs_data, team_longname) ...
53dc68642a4cca7b80ede7b2d54098eb9274b1af
16,390
def autofmt(filename, validfmts, defaultfmt=None): """Infer the format of a file from its filename. As a convention all the format to be forced with prefix followed by a colon (e.g. "fmt:filename"). `validfmts` is a list of acceptable file formats `defaultfmt` is the format to use if the extension is ...
3e39325f43f8b4a87074a38f7d576d17669151fb
16,391
def get_or_add_dukaan(): """ Add a new business """ if request.method == "POST": payload = request.json # payload = change_case(payload, "lower") business = db.dukaans.find_one({"name": payload["name"]}) if business is not None: return ( jsonify( ...
e522ac8394b7b70949e2854e10251f3bc51279ae
16,392
def nearest(a, num): """ Finds the array's nearest value to a given num. Args: a (ndarray): An array. num (float): The value to find the nearest to. Returns: float. The normalized array. """ a = np.array(a, dtype=float) return a.flat[np.abs(a - num).argmin()]
cadbad68add910ced502a6802592d1c043f1c914
16,393
def hex_string(data): """Return a hex dump of a string as a string. The output produced is in the standard 16 characters per line hex + ascii format: 00000000: 40 00 00 00 00 00 00 00 40 00 00 00 01 00 04 80 @....... @....... 00000010: 01 01 00 00 00 00 00 01 00 00 00 00 ........ ....
7f827b4f8049b43e86d35bd972f5b6aaa2190869
16,394
import os import re def load_codes_mat(backup_dir, savefile=False, thread_num=1): """ load all the code mat file in the experiment folder and summarize it into nparrays""" if "codes_all.npz" in os.listdir(backup_dir): # if the summary table exist, just read from it! with np.load(os.path.join(b...
1d368c3b4b337de5a9b42853eda7e30a0826a8b4
16,395
def extract_ego_time_point(history: SimulationHistory) -> npt.NDArray[int]: """ Extract time point in simulation history. :param history: Simulation history. :return An array of time in micro seconds. """ time_point = np.array( [sample.ego_state.time_point.time_us for sample in history....
4860b2c7032ea232ace2680c704e4a59051b6c5c
16,396
def compare_data_identifiers(a, b): """Checks if all the identifiers match, besides those that are not in both lists""" a = {tuple(key): value for key, value in a} b = {tuple(key): value for key, value in b} matching_keys = a.keys() & b.keys() a = {k: v for k, v in a.items() if k in matching_keys} ...
f0f5f08e4cc685b62b2af19e0c724561988ed1b9
16,397
import re def expand_abbr(abbr, doc_type = 'html'): """ Разворачивает аббревиатуру @param abbr: Аббревиатура @type abbr: str @return: str """ tree = parse_into_tree(abbr, doc_type) if tree: result = tree.to_string(True) if result: result = re.sub('\|', insertion_point, result, 1) return re.sub('\|',...
23d0edebd9660303d4c361b468c5cb2f6e0e0f03
16,398
def SaveSettings (event=None, SettingsNotebook=None, filename = "settings.hdf5", title="Open HDF5 file to save settings", OpenDialog=True ) : """ Method for saving setting """ if OpenDialog : # Ask user to select the file openFileDialog = wx.FileDialog(SettingsNotebook, title, "", filename, "HDF5 files (*.hdf5...
7e2a221c78ef78f542877a754034084ed8dd8492
16,399