content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Tuple from typing import Optional import io import textwrap from re import I def _define_property_shape( prop: intermediate.Property, cls: intermediate.ClassUnion, url_prefix: Stripped, class_to_rdfs_range: rdf_shacl_common.ClassToRdfsRange, constraints_by_property: infer_for_sc...
29483d27548a7fbd208f820e8e0821e0b121132f
3,632,314
def row2string(row, sep=', '): """Converts a one-dimensional numpy.ndarray, list or tuple to string Args: row: one-dimensional list, tuple, numpy.ndarray or similar sep: string separator between elements Returns: string representation of a row """ return sep.join("{0}".form...
f81a2ec54b8c37285715cadca4458918962440b9
3,632,315
def apply_kNNO(Xs, Xt, ys=None, yt=None, scaling=True, k=10, contamination=0.1): """ Apply kNNO. k-distance is the distance of its k-th nearest neighbour in the dataset KNNO ranks all instances in a dataset by their k-distance, with higher distances signifying more anomalous instances Parameter...
6a90757063ff20dba11075508bce7038295920a1
3,632,317
def build_aggregation(facet_name, facet_options, min_doc_count=0): """Specify an elasticsearch aggregation from schema facet configuration. """ exclude = [] if facet_name == 'type': field = 'embedded.@type' exclude = ['Item'] elif facet_name.startswith('audit'): field = facet...
b8c3f337143a229401b9a41a8fde8903027cf67e
3,632,320
def route_wrap_01_version(request_mapping: str): """ flask 路由映射包裹器 增加API_VERSION :param request_mapping: :return: """ return '{}/{}'.format(API_VERSION, request_mapping)
0a3db2ed132c1f2233817a8154c5c1c87872d6dc
3,632,322
def spawn(pool): """spawn a greenlet it will be automatically killed after the test run """ return pool.spawn
fadea4b814e77f7fb26af27f0cc7bce1189a7dcf
3,632,323
from typing import Any import json def from_json_util(json_str: str) -> Any: """Load an arbitrary datatype from its JSON representation. The Out-of-proc SDK has a special JSON encoding strategy to enable arbitrary datatypes to be serialized. This utility loads a JSON with the assumption that it follo...
5da695fb260b1df35dc91dfb8ef9026b04472d6a
3,632,324
def min_row_dist_sum_idx(dists): """Find the index of the row with the minimum row distance sum This should return the index of the row index with the least distance overall to all other rows. Args: dists (np.array): must be square distance matrix Returns: int: index of row wit...
7bddc4e58344e519a2bd928187db3a6b65e17118
3,632,325
def inline(text): """ Convert all newline characters to HTML entities: &#10; This can be used to prevent Hypertag from indenting lines of `text` when rendering parent nodes, and to safely insert `text` inside <pre>, <textarea>, or similar elements. """ return text.replace('\n', '&#10;')
658f7e5adbf5747ea069fad8a9599e9bd499a381
3,632,326
def align_pos(xyz, test_crd, ref_crd, ind=None): """Translates a set of atoms such that two positions are coincident. Parameters ---------- xyz : (N, 3) array_like The atomic cartesian coordinates. test_crd : (3,) array_like Cartesian coordinates of the original position. test_c...
ffa6001e20a4e4a1379e6a95139946aa91a5bdd0
3,632,327
from typing import Optional from typing import Sequence def get_orderable_db_instance(availability_zone_group: Optional[str] = None, engine: Optional[str] = None, engine_version: Optional[str] = None, instance_class: Optional[st...
6557de19d6c14d903d9f3058f7428ffe700633d0
3,632,328
def publish_channel_url(): """open_channel_url: returns url to publish channel Args: None Returns: string url to publish channel """ return PUBLISH_CHANNEL_URL.format(domain=DOMAIN)
7ba59e32746b9ffa9c9a46fd073cfbb1c3905e9f
3,632,329
def hist_counts(df_acts=None, lst_acts=None, df_ac=None, y_scale="linear", idle=False, figsize=None, color=None, file_path=None): """ Plot a bar chart displaying how often activities are occurring. Parameters ---------- df_acts : pd.DataFrame, optional recorded activities fr...
4e9820d25bd2f33de8269f413fbce0b1898fd7fa
3,632,330
def random_dense(shape, fortran): """Generate a random qutip Dense matrix of the given shape.""" return qutip.core.data.Dense(random_numpy_dense(shape, fortran))
869c8cd2972b40f82d73403ed5c54d170fe3dcb5
3,632,331
import torch def bo_step(X, y, objective, bounds, GP=None, acquisition=None, q=1, state_dict=None, *GP_args, **GP_kwargs): """ One iteration of Bayesian optimization: 1. Fit GP model using (X, y) 2. Create acquisition function 3. Optimize acquisition function to obtain cand...
e752091e5aaf3b42e3e8f21a21f0368485f60c25
3,632,332
def validate_inputs(input_data): """Check prediction inputs against schema.""" # set many=True to allow passing in a list schema = InsuranceDataRequestSchema(strict=True, many=True) errors = None try: schema.load(input_data) except ValidationError as exc: errors = exc.messages ...
e0faacabb729d191308bdf1d5710525b529d4793
3,632,333
def published_stats_list(request): """ List cumulative stats about projects published. The request may specify the desired resource type """ resource_type = None # Get the desired resource type if specified if 'resource_type' in request.GET and request.GET['resource_type'] in ['0', '1']: ...
308ef79fb6f51d192adb31849dd6bb75a46fe469
3,632,334
def get_entity(name): """Get an entity by the given name. Args: name (str): namespace.entity_name Returns: OntologyEntity: The entity with the given name. """ ns, n = name.split(".") return _namespace_registry._get(ns)._get(n)
bd00058f8d3af4d29b35bcf0cc336f4c567baf8a
3,632,335
def tst(): """members page.""" return render_template('users/testing2.html')
042463af7cc3742e78f744bc66ad09c3060ca877
3,632,336
def get_bq_col_type(col_type): """ Return correct SQL column type representation. :param col_type: The type of column as defined in json schema files. :return: A SQL column type compatible with BigQuery """ lower_col_type = col_type.lower() if lower_col_type == 'integer': return 'I...
86cac08a04d804cc6addbeee86014f1aa6d35735
3,632,337
def _do_boundary_search(search_term): """ Execute full text search against all searchable boundary layers. """ result = [] query = _get_boundary_search_query(search_term) with connection.cursor() as cursor: wildcard_term = '%{}%'.format(search_term) cursor.execute(query, {'term'...
b2cc74b7ba436c0c57bbb7505d964d79354a36f5
3,632,338
def prices(identifier, start_date=None, end_date=None, frequency='daily', sort_order='desc'): """ Get historical stock market prices or indices. Args: identifier: Stock market symbol or index start_date: Start date of prices (default no filter) end_date: Last date (defaul...
145d8ea607a1e374e205ef337345f7b9d6064479
3,632,339
def x1y1x2y2_to_xywh(x1y1x2y2): """Convert [x1 y1 x2 y2] box format to [x y w h] format.""" if isinstance(x1y1x2y2, (list, tuple)): # Single box given as a list of coordinates assert len(x1y1x2y2) == 4 ct_x, ct_y = (x1y1x2y2[3] + x1y1x2y2[1]) / 2, (x1y1x2y2[2] + x1y1x2y2[0]) / 2 ...
b5535ace312ca2f790f4dcb66ed9e53223b90649
3,632,341
def col(loc, strg): """ Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See :class:`ParserElement.parseString` for more ...
0dfc4387e391c4823939350ad19c60d106211a58
3,632,342
def create_model_fn(model_class, hparams, use_tpu=False): """Wraps model_class as an Estimator or TPUEstimator model_fn. Args: model_class: AstroModel or a subclass. hparams: ConfigDict of configuration parameters for building the model. use_tpu: If True, a TPUEstimator model_fn is returned. Otherwise ...
83be600771b8e64c610db0d3d16fe10ba668fbd0
3,632,343
from typing import Any def boolean(value: Any) -> bool: """Validate and coerce a boolean value.""" if isinstance(value, str): value = value.lower() if value in ("1", "true", "yes", "on", "enable"): return True if value in ("0", "false", "no", "off", "disable"): ...
781dbb2e30448065d8dc65b42ab02914a3338b43
3,632,344
def unmap(data, count, inds, fill=0): """ Unmap a subset of item (data) back to the original set of items (of size count) :param data: input data :param count: the total count of data :param inds: the selected indices of input data :param fill: filled value :return: unmaped data """ ...
3cc361650644275673e6340f8d6a216071b0c3c9
3,632,345
def recursive_feature(G, f, n): """ G: iGraph graph with annotations func: string containing function name n: int, recursion level Computes the given function recursively on each vertex Current precondition: already have run the computation for G, func, n-1. """ retur...
4516e85cddea50dc9a1f14448a7b950a0620e3f0
3,632,347
import unicodedata def remove_accents(string): """ Removes unicode accents from a string, downgrading to the base character """ nfkd = unicodedata.normalize('NFKD', string) return u"".join([c for c in nfkd if not unicodedata.combining(c)])
41c8e05aa8982c85cf5cf2135276cdb5e26fefec
3,632,348
from typing import Optional def __get_a0( # pylint: disable=invalid-name n: int, a0: Optional[np.ndarray] = None ) -> np.ndarray: """ Returns initial parameters for fitting algorithm. :param n: Number of parameters :param a0: Initial parameters value. Optional :return: nd.array """ i...
80b5d974dd6187746215191cc1f4de1ae135b93e
3,632,349
def convert_yaw_to_old_viewpoint(yaw): """ we initially had viewpoint coordinates inverted Example: >>> import math >>> TAU = 2 * math.pi >>> old_viewpoint_labels = [ >>> ('left' , 0, 0.000 * TAU,), >>> ('frontleft' , 45, 0.125 * TAU,), >>> ...
7659e15bf7f4693ac7c6223b8f4600450bc7f2fe
3,632,350
def extract_lexical_features_test(nlp, tweet_list): """Provides tokenization, POS and dependency parsing Args: nlp (spaCy model): Language processing pipeline """ result = [] texts = (tweet for tweet in tweet_list) for doc in nlp.pipe(texts, batch_size=10000, n_threads=3): setti...
b0f87996558c4b2e1d77b59068e8ad259524a455
3,632,352
def get_hostname(): """ Return hostname. """ return tg.config.get('workbox.hostname')
367dda60f71d169c6490913a3ee3f8befc83b738
3,632,353
import http def geocode_location(api_key, loc): """Get a geocoded location from gooogle's geocoding api.""" try: parsed_json = http.get_json(GEOCODING_URL, address=loc, key=api_key) except IOError: return None return parsed_json
95c820abc58a13cd57e662e78bfab8fceac5eadf
3,632,354
def degree(f, *gens, **args): """ Return the degree of ``f`` in the given variable. The degree of 0 is negative infinity. Examples ======== >>> degree(x**2 + y*x + 1, gen=x) 2 >>> degree(x**2 + y*x + 1, gen=y) 1 >>> degree(0, x) -inf """ allowed_flags(args, ['gen'...
a6b5e2ba9228ea1477234c0e16477dd603fb9598
3,632,355
from typing import Dict def fit_model_sector(sector_corpus: Dict[DocId, Token]) -> sbmtm: """Fits the model taking the sector corpus data structure as an input Args: sector_corpus: a dict where keys are doc ids and values are the tokenised descriptions Returns: The model ...
d025a0f4faac53b4b21486e159a0310c78dc72b8
3,632,356
def get_simulated_matches(path, met, sample_to_match, pop_var): """Selects initial conditions from cosmic data to match to star sample Parameters ---------- path : `str` path to cosmic data met : `float` metallicity of cosmic data file sample_to_match : `DataFrame` A d...
ecbb46f284f7b6748031b0907813deaad8967eba
3,632,357
def _get_url_ext(url: str): """ >>> _get_url_ext('http://example.com/blog/feed') 'feed' >>> _get_url_ext('http://example.com/blog/feed.xml') 'xml' >>> no_error = _get_url_ext('http://example.com') """ try: url_path = urlparse(url).path.strip('/') except ValueError: re...
61b94bd2c98686192a47ade9bb240bc4c58904c2
3,632,358
def connect_server(): """Connect to azure cosmos DB. Connet to azure cosmos DB. Need to insert ID, DB name, table name, and key. Args: None Returns: clt(str): an instance for connecting to azure cosmos DB server """ clt = client.Client( 'wss://<YOURID>...
1826b4676af381882710a8802392f7f1d4f2253e
3,632,359
def checkCpuTime(sleeptime=0.2): """Check if cpu time works correctly""" if checkCpuTime.passed: return True # First test that sleeping does not consume cputime start1 = process_time() sleep(sleeptime) t1 = process_time() - start1 # secondly check by comparing to cpusleep (where we ...
5b7db840f56b5eafdbfa857c470c316c257c9bac
3,632,360
def load_ply(path): """ Loads a 3D mesh model from a PLY file. :param path: A path to a PLY file. :return: The loaded model given by a dictionary with items: 'pts' (nx3 ndarray), 'normals' (nx3 ndarray), 'colors' (nx3 ndarray), 'faces' (mx3 ndarray) - the latter three are optional. """ ...
289c0854bc3270dafab5689bc53d2507ff27c67c
3,632,362
def parse_range(rng, dictvars={}): """Parse a string with an integer range and return a list of numbers, replacing special variables in dictvars.""" parts = rng.split('-') if len(parts) not in [1, 2]: raise ValueError("Bad range: '%s'" % (rng,)) parts = [int(i) if i not in dictvars else dictva...
214109a71c84d06241e29cacaa052d9ce00302c5
3,632,363
from typing import Union from typing import Iterable from typing import List from pathlib import Path def relpaths(basepath: _path_t, pattern: Union[str, Iterable[_path_t]]) -> List[str]: """Convert a list of paths to relative paths Parameters ---------- basepath : Union[str, Path] Path to us...
80c9febd541d8fd1ab190b2ef36e8929ee387b08
3,632,364
def binary_backtests_returns( backtests: pd.DataFrame, ) -> pd.DataFrame: """ Converts a Horizon backtest data frame into a binary backtests of directions """ return backtests.diff().apply(np.sign).dropna()
0355cd48620cbdbe54eb4ee48e82f7315f069263
3,632,365
def calculate_students_features_csv(entry_id, xmodule_instance_args): """ Compute student profile information for a course and upload the CSV to an S3 bucket for download. """ # Translators: This is a past-tense verb that is inserted into task progress messages as {action}. action_name = ugettex...
ccf8eae3b9732535c94381ba1909f36bce52556d
3,632,366
def save_genre(row: dict): """Genre's control and save in data base.""" try: result: Genres = session.query(Genres) \ .filter(Genres.name == row.get('genre_name')) \ .one() return result except MultipleResultsFound: pri...
0c7e26082816a2639cc4561a1e9ee5f2697a4175
3,632,368
def specializations(examples_so_far, h): """Specialize the hypothesis by adding AND operations to the disjunctions""" hypotheses = [] for i, disj in enumerate(h): for e in examples_so_far: for k, v in e.items(): if k in disj or k == 'GOAL': continue ...
5f21edd18477c09d37a03026073c0120b6be41b9
3,632,369
def formulate_contingency(problem: LpProblem, numerical_circuit: OpfTimeCircuit, flow_f, ratings, LODF, monitor, lodf_tolerance): """ :param problem: :param numerical_circuit: :param flow_f: :param LODF: :param monitor: :return: """ nbr, nt = ratings.shape ...
ecc5deb3b689a5802341d48e81382d2d602f1ebc
3,632,370
def max_pooling3d(inputs, pool_size, strides, padding='valid', data_format='channels_last', name=None): """Max pooling layer for 3D inputs (e.g. volumes). Arguments: inputs: The tensor over which to pool. Must have rank 5. pool_size: An integer or tuple...
49756ea26e58549115408fbcb4ce179442a09942
3,632,371
def parareal_engine(x_0, U, num_iter, coarse_model="learned"): """Rolls out a trajectory using Parareal Args: x_0: Initial state U: Control sequence num_iter: Number of Parareal iterations to use for prediction coarse_model: Learned/Analytical coarse model Returns: X: The corresponding state seq...
bd589650711d510fcffb2033dd5f7a501dc4e041
3,632,372
def plot_posterior_op(trace_values, ax, kde_plot, point_estimate, round_to, alpha_level, ref_val, rope, text_size=16, **kwargs): """Artist to draw posterior.""" def format_as_percent(x, round_to=0): return '{0:.{1:d}f}%'.format(100 * x, round_to) def display_ref_val(ref_val): ...
13d7d12dfac13f803fb08b49970471e4f97c7bff
3,632,373
from operator import sub from re import M def change_theme(file: str, theme_name: str, logfile: str) -> bool: """ Change Oh My ZSH Theme """ if get_zsh_theme(file, logfile): current_file = read_file_log(file, logfile) current_theme = get_zsh_theme(file, logfile)[1] new_theme = ...
55438f7d93779417aff4dfa4170997269b200dca
3,632,374
def check_tensor(data): """Ensure that data is a numpy 4D array.""" assert isinstance(data, np.ndarray) if data.ndim == 2: data = data[np.newaxis,np.newaxis,...] elif data.ndim == 3: data = data[np.newaxis,...] elif data.ndim == 4: pass else: raise RuntimeError('...
d641645e9a2c780d52c5e635859bdfcce61f86ab
3,632,375
from typing import Type from typing import Optional def _find_first_ref(ref: Ref, message_type: Type[B]) -> Optional[B]: """ Finds and returns (if exists) the first instance of the specified message type within the specified Ref. """ # Get the body message, if it exists body = _get_ref_body(ref) ...
474ad2a2c874c6ae226475fc1e4b144fdd4f72a1
3,632,376
def verify_activation_token(*, uidb64, token): """ :param uidb64: (str) Base 64 of user PK. :param token: (str) Hash. :return: (bool) True if user verified, False otherwise. """ user_id = force_text(urlsafe_base64_decode(uidb64)) try: user = User.objects.get(pk=user_id) except ...
f184a85852906526434dc54b2e26491ad3dafc51
3,632,377
def read_protein_from_file(file_pointer): """The algorithm Defining Secondary Structure of Proteins (DSSP) uses information on e.g. the position of atoms and the hydrogen bonds of the molecule to determine the secondary structure (helices, sheets...). """ dict_ = {} _dssp_dict = {'L': 0, 'H': 1,...
071a7b04b652261f83311e250e92884e95a4e818
3,632,379
def match(string, rule='IRI_reference'): """Convenience function for checking if `string` matches a specific rule. Returns a match object or None:: >>> assert match('%C7X', 'pct_encoded') is None >>> assert match('%C7', 'pct_encoded') >>> assert match('%c7', 'pct_encoded') """ ...
c6c2079786651bfaa1ba819251e1d51a276bf8cd
3,632,380
from typing import List def verify_td3(mrz: List[str]) -> bool: """Verify TD3 MRZ""" if mrz[0][0] != "P": return False # if mrz[0][1]: # At the discretion of the issuing State or organization or "<" # if mrz[0][2:5]: # ISSUING STATE OR ORGANIZATION # if mrz[0][5:44]: # NAME if calculat...
13dca85d0f91cac9bbf759f8a5171e73ddfb4836
3,632,381
def compute_pwcca(acts1, acts2, epsilon=0.): """ Computes projection weighting for weighting CCA coefficients Args: acts1: 2d numpy array, shaped (neurons, num_datapoints) acts2: 2d numpy array, shaped (neurons, num_datapoints) Returns: Original cca coefficient mean and weighted mean ...
17f0b6674cd1c45435eb73bc4e754543640543d6
3,632,382
def read_table(srm_file): """ Reads SRM compositional data from file. For file format information, see: http://latools.readthedocs.io/en/latest/users/configuration/srm-file.html Parameters ---------- file : str Path to SRM file. Returns ------- SRM compositions : panda...
6ec87cab30162af55e3cce659b3ef7a205857595
3,632,383
def walker_method(for_class=object, methods_list=None): """A decorator to add something to the default walker methods, selecting on class """ if methods_list is None: # handle early binding of defaults methods_list = fallback_walker_method_list def wrap(walker): # wrap a walker wi...
b500f04510695e5cfd88590feaa75b27aee3b5b8
3,632,384
import pandas as pd from IPython.display import display def get_data(name_dataset='index', verbose=True, address="../datasets/",): """ This function is to load dataset from the git repository :param name_dataset: name of dataset (str) :param verbose: :param address: url o...
fa518e744d43950ebcf65d00a5aa474d4fb36443
3,632,385
import torch def copy_valid_indices( acts, # type: torch.Tensor target, # type: List[List[int]] act_lens, # type: List[int] valid_indices, # type: List[int] ): # type: (...) -> (torch.Tensor, List[List[int]], List[int]) """Copy the CTC inputs without the erroneous samples""" if len(val...
9eac2b7304ff5157ca13fae9d790af6c2b67d9c7
3,632,386
def is_odd(num: int) -> bool: """Is num odd? :param num: number to check. :type num: int :returns: True if num is odd. :rtype: bool :raises: ``TypeError`` if num is not an int. """ if not isinstance(num, int): raise TypeError("{} is not an int".format(num)) return num % 2 ==...
0e5781596a99909e58583859948332c3afb06fb0
3,632,387
def cross_entropy_loss(y_hat, y): """ Cross entropy loss y_hat: predict y after softmax, shape:(M,d), M is the #of samples y: shape(M,d) """ loss = np.mean(np.sum(- y * np.log(y_hat), axis=-1)) dy = y_hat - y return loss, dy
81f6dc61d0ed9d9e5eac4a41042679b3ea01167d
3,632,388
import string def string_list(resource_name, encoding='utf-8'): """Package resource wrapper for obtaining resource contents as list of strings. The function uses the 'string' method and splits the resulting string in lines. Params: resource_name: Relative path to the resource in the pack...
88e7103056e38020670a74a19bfeee90326e7d38
3,632,389
from typing import Optional def rpc_get_name() -> Optional[str]: """Retrieve the JsonRpc id name.""" global _RpcName return _RpcName
2b7d7e9b37b00281b0791e446e5ad4bacee78c4b
3,632,391
def _epd_platform_from_raw_spec(raw_spec): """ Create an EPDPlatform instance from the metadata info returned by parse_rawspec. if no platform is defined ('platform' and 'osdist' set to None), then None is returned. """ platform = raw_spec[_TAG_PLATFORM] osdist = raw_spec[_TAG_OSDIST] i...
b6757206e6753441478629519531b0ec5adfc83a
3,632,392
def index(request): """The home page for Distance Tracker.""" if request.user.is_authenticated: today = date.today() cur_week = today.isocalendar()[1] cur_month = today.month cur_year = today.year exercises_week = Exercise.objects.filter(owner=request.user, ...
279f6e7c1cb9f2821ebee7b138c7b8b22e60768e
3,632,393
import runpy import imp def mod_from_file(mod_name, path): """Runs the Python code at path, returns a new module with the resulting globals""" attrs = runpy.run_path(path, run_name=mod_name) mod = imp.new_module(mod_name) mod.__dict__.update(attrs) return mod
3ea8109d912582555b76816f55fbb632ba82f189
3,632,394
def interpolation(x0: float, y0: float, x1: float, y1: float, x: float) -> float: """ Performs interpolation. Parameters ---------- x0 : float. The coordinate of the first point on the x axis. y0 : float. The coordinate of the first point on the y axis. x1 : float. T...
f8fc96c6dc6c2eeeeceb22f92b32023f3873fe3e
3,632,395
import collections def product_counter_v3(products): """Get count of products in descending order.""" return collections.Counter(products)
22c57d50dc36d3235e6b8b642a4add95c9266687
3,632,397
def remove_noise(line,minsize=8): """Remove small pixels from an image.""" if minsize==0: return line bin = (line>0.5*np.amax(line)) labels,n = ndimage.label(bin) sums = ndimage.sum(bin,labels,range(n+1)) sums = sums[labels] good = np.minimum(bin,1-(sums>0)*(sums<minsize)) return good
1e19fad38a081db35ac31e3e19d224f4cb8e7d59
3,632,398
import textwrap def _ParseFormatDocString(printer): """Parses the doc string for printer. Args: printer: The doc string will be parsed from this resource format printer. Returns: A (description, attributes) tuple: description - The format description. attributes - A list of (name, descript...
f5aaffb91cbedbc1b6e0da64cdfb3ff4adfa684e
3,632,399
def build_answers_xml(selector, args): """ builds an answers xml string for a selector class using default answers for the selector's questions. If any other attributes were included in the call, they are appended to as part of the work-info. """ # build an answers xml tree answers = ET.Ele...
9290190fef3396990a3a4199d81c50f413ee3bc1
3,632,400
import time def give_me_the_answer(question, clever=False): """This gives you the answer. Parameters ---------- question: str the question you are asking. clever: bool, optional whether or not the answer should be clever or not Returns ------- The answer """ ...
a2b8f7fd9cd131caa6d2d99c694d76cef34ead82
3,632,401
def round_down(x: float, decimal_places: int) -> float: """ Round a float down to decimal_places. Parameters ---------- x : float decimal_places : int Returns ------- rounded_float : float Examples -------- >>> round_down(1.23456, 3) 1.234 >>> round_down(1.2345...
f1accd23ffef4fbceb0aa75098862dfb75e03c61
3,632,402
import importlib def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: parts = val.split(".") module_path, class_name = ".".join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr...
45bd96b219c808a5cf928e1b7364aa3c3178160a
3,632,403
def datatype_to_tracktype(datatype): """ Infer a default track type from a data type. There can be other track types that can display a given data type. Parameters ---------- datatype: str A datatype identifier (e.g. 'matrix') Returns ------- str, str: A track type ...
fb0679ade37478ee0b9a451ce667bfd23f86e1ae
3,632,404
def rossler(x, y, z, a, b, c): """ Rössler System of Ordinary Differential Equations """ dx = - y - z dy = x + a*y dz = b + z*(x - c) return dx, dy, dz
bcf27c7ff8223681d6dc7d0c49497e975b826d80
3,632,405
import re def get_extension(filename): """ Extract file extension from filename using regex. Args: filename (str): name of file Returns: str: the file extension """ match = re.search(r"\.(?P<ext>[^.]+)$", filename) if match: return match.group("ext") raise Val...
8f5195b339a153d5fa144182505dba986992d4df
3,632,407
import asyncio def run_async(func): """ Allows you to run a click command asynchronously. """ func = asyncio.coroutine(func) def inner_handler(*args, **kwargs): run(func(*args, **kwargs)) return update_wrapper(inner_handler, func)
29b0d731d101159f7ec7311dc6beb6ab56523022
3,632,408
def Conv2D(input_tensor, input_shape, filter_size, num_filters, strides=1, name=None): """ Handy helper function for convnets. Performs 2D convolution with a default stride of 1. The kernel has shape filter_size x filter_size with num_filters output filters. """ shape = [filter_size, filter_size, input_shape, nu...
91505ed82eaf1585023edba55848a33e4145bbc3
3,632,409
def scale_val(val, factor, direction): """Scale val by factor either 'up' or 'down'.""" if direction == 'up': return val+(val*factor) if direction == 'down': return val-(val*factor) raise ValueError('direction must be "up" or "down"')
16c2efe16fc787fe4461fb0ae640e2cf22d556e0
3,632,410
def ttee(iterable, n=2): """ >>> ttee("ABC") (('A', 'B', 'C'), ('A', 'B', 'C')) """ return tuple(map(tuple, tee(iterable, n)))
7b5b6ff83492f4df5cbe845367d73bbadd0c6b10
3,632,411
def addattrs(field, css): """ 在模板的form的field中,特别是input中添加各种attr """ attrs = {} definition = css.split(',') for d in definition: if '=' not in d: attrs['class'] = d else: t, v = d.split('=') attrs[t] = v return field.as_widget(attrs=attrs)
cdbb2b4b44b6e7facbe2af44d503c3118eb31ef7
3,632,412
def regular_periodic(freqs, amplitudes, phase, size=501): """Generate periodic test data sampled at regular intervals: superposition of multiple sine waves, each with multiple harmonics. """ times = np.linspace(0, 2, size) values = np.zeros(size) for (i,j), amplitude in np.ndenumerate(amplitudes...
bfe23122e8edd3a279caed27a758edd353f15bc7
3,632,413
from bread.contrib.reports.fields.queryfield import parsequeryexpression def generate_excel_view(queryset, fields, filterstr=None): """ Generates an excel file from the given queryset with the specified fields. fields: list [<fieldname1>, <fieldname2>, ...] or dict with {<fieldname>: formatting_function(o...
ca03a09ee3a6a2e17df542ab4c124c4078677b4a
3,632,414
def get_tag_by_name(repo: Repository, tag_name: str) -> Tag: """Fetches a tag by name from the given repository""" ref = get_ref_for_tag(repo, tag_name) try: return repo.tag(ref.object.sha) except github3.exceptions.NotFoundError: raise DependencyLookupError( f"Could not find...
d8191f819e7a2f1cdcaeabb52cda452fd3e555bf
3,632,416
def get_geo_selected(results, datas, extras, filters=False): """Get specific Geography based on existing ids.""" wards = [] all_list = get_all_geo_list(filters) datas.remove('') if '' in datas else datas extras.remove('') if '' in extras else extras results['wards'] = datas area_ids = list(m...
755b8461f0decc320c54174541bef0672585bcc8
3,632,417
def notify(text, boxwidth=60): """Create a 'notification' styled textbox""" return box(text, decor="*", boxwidth=boxwidth)
1fe8d98b890bf7c2cd6aaee27b2c11dca6b8046c
3,632,418
def returns_player(method): """ Decorator: Always returns a single result or None. """ def func(self, *args, **kwargs): "decorator" rfunc = returns_player_list(method) match = rfunc(self, *args, **kwargs) if match: return match[0] else: ret...
22549888600556804ae3446a6c7442e94841813f
3,632,419
def tracks(date): """ Query the charts/beatport/tracks endpoint for the given date. Data available on Fridays. https://api.chartmetric.com/api/charts/beatport **Parameters** - `date`: string date in ISO format %Y-%m-%d **Returns** A list of dictionary of tracks on Beatport ch...
e117fe57e78eb4780f2ba8850b1fe80d7ab43c0c
3,632,420
def cos_sim(A_mat, B_vec): """ item-vevtorの行列(またはベクトル)が与えられた際にitem-vevtor間のコサイン類似度行列を求める """ d = np.dot(A_mat, B_vec) # 各ベクトル同士の内積を要素とする行列 # 各ベクトルの大きさの平方根 A_norm = (A_mat ** 2).sum(axis=1, keepdims=True) ** .5 B_norm = (B_vec ** 2).sum(axis=0, keepdims=True) ** .5 # それぞれのベクトルの大きさの平方根で...
823778eaaeb8bb85e93544c5b6d09001cba0e236
3,632,421
def parse_dtype(space): """Get a tensor dtype from a OpenAI Gym space. Args: space: Gym space. Returns: TensorFlow data type. """ if isinstance(space, gym.spaces.Discrete): return tf.int32 if isinstance(space, gym.spaces.Box): return tf.float32 raise NotImplementedError()
903824c5c013c9081bd988ca437f123ebb322ef8
3,632,422
def tf_efficientnet_b2_ap(pretrained=True, **kwargs): """ EfficientNet-B2. Tensorflow compatible variant """ kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' out_indices = [1, 2, 4, 6] model = _gen_efficientnet( 'tf_efficientnet_b2_ap', channel_multiplier=1.1, depth_multipli...
61ebd0953be7024d262ecd509bfd6d4886431afb
3,632,423
def plot_ld_curves(ld_stats, stats_to_plot=[], rows=None, cols=None, statistics=None, fig_size=(6,6), dpi=150, r_edges=None, numfig=1, cM=False, output=None, show=False): """ Plot single set of LD curves LD curves are named as given in statistics ld_stats is th...
5bf8128cce7a4b85347787e4552444f69f68873a
3,632,424
def onehottify_2d_array(a): """ https://stackoverflow.com/questions/36960320/convert-a-2d-matrix-to-a-3d-one-hot-matrix-numpy :param a: 2-dimensional array. :return: 3-dim array where last dim corresponds to one-hot encoded vectors. """ # https://stackoverflow.com/a/46103129/ @Divakar def a...
a612b6fa7ba2bc59f48aec85ee2e63e9d3cf86ac
3,632,425
def getUserCompetencies(cnx, exceptUserIDs): """ Returns array of persons with their competences as values """ competencies = {} cnx = establishDBConnection(dbconfig) cursor = cnx.cursor() placeholder = '%s' placeholders = ', '.join(placeholder for unused in exceptUserIDs) query = ("...
4cd73c2e01fe76abad337cfd4929edcce297c92e
3,632,426
def add_induct_def(name, T, eqs): """Add the given inductive definition. The inductive definition is specified by the name and type of the constant, and a list of equations. For example, addition on natural numbers is specified by: ('plus', nat => nat => nat, [(plus(0,n) = n, plus(Suc(m), n) ...
7de7884e36cceba2a49377230a7932ff133f902f
3,632,427