content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _one_q_pauli_prep(label, index, qubit): """Prepare the index-th eigenstate of the pauli operator given by label.""" if index not in [0, 1]: raise ValueError(f'Bad Pauli index: {index}') if label == 'X': if index == 0: return Program(_RY(pi / 2, qubit)) else: ...
4c4f02c6e1ffcbb57ca161f3cb0f17a678563b0b
3,631,041
def get_movie_data_from_wikidata(slice_movie_set: pd.DataFrame): """ Function that consults the wikidata KG for a slice of the movies set :param slice_movie_set: slice of the movie data set with movie id as index and imdbId, Title, year and imdbUrl as columns :return: JSON with the results of the qu...
a4c3a9a7e7cce1a2eb85326422afcb4ff3463db4
3,631,044
def run_dpc( filename, i, j, ref_fx=None, ref_fy=None, start_point=[1, 0], pixel_size=55, focus_to_det=1.46, dx=0.1, dy=0.1, energy=19.5, zip_file=None, roi=None, bad_pixels=[], max_iters=1000, solver="Nelder-Mead", hang=True, reverse_x=1, reve...
e7d96201350cb84c323066434d8257631de353f7
3,631,045
def api_converter(): """ Handler for conversion API request :return: Text of response :rtype: str """ try: parsed_args = parse_request_arguments() conversion_result = convert_core.convert_currency(**parsed_args) except (APIRequestError, CurrencyConversionError) as exc_msg: ...
591961f92a5e1e831976bcb09396630b515785cb
3,631,047
import pytz def plot1(ctx): """Do main plotting logic""" df = read_sql(""" SELECT * from sm_hourly WHERE station = %s and valid BETWEEN %s and %s ORDER by valid ASC """, ctx['pgconn'], params=(ctx['station'], ctx['sts'], ctx['ets']), index_col='valid') i...
8c94e9b989bbf0f04db99cffdc54cc9ec46b8e40
3,631,048
from typing import Tuple from typing import Optional def is_royal_flush(hand: Tuple[Card]) -> Optional[Tuple[str, PokerHand, int]]: """ If this hand contains a royal flush, return string representation of it """ straight_flush = is_straight_flush(hand) if straight_flush is not None and "Ten to Ace" in str...
9e530d3c1ff44b35e6e17bc068f4557e059e3415
3,631,049
import torch def make_complex_matrix(x, y): """A function that takes two tensors (a REAL (x) and IMAGINARY part (y)) and returns the combine complex tensor. :param x: The real part of your matrix. :type x: torch.doubleTensor :param y: The imaginary part of your matrix. :type y: torch.doubleTe...
faae031b3aa6f4972c8f558f6b66e33d416dec71
3,631,050
def array(dtype, ndim): """ :param dtype: the Numba dtype type (e.g. double) :param ndim: the array dimensionality (int) :return: an array type representation """ if ndim == 0: return dtype return minitypes.ArrayType(dtype, ndim)
f9b89a414d9bfb7a1e154df34c1c75a47943bca5
3,631,051
def as_pandas(data): """Returns a dataframe if possible, an error otherwise""" if isinstance(data, pd.DataFrame): return data elif isinstance(data, dict): return pd.DataFrame(data) else: raise TypeError( f"Expected a DataFrame or dict type, got: {type(data)} insead" ...
a9243c327f8f7851b0b8347a9df684db7b152561
3,631,052
def scale3(v, s): """ scale3 """ return (v[0] * s, v[1] * s, v[2] * s)
4993c072fb66a33116177023dde7b1ed2c8705fd
3,631,053
def _get_last_ext_comment_id(connection): """Returns last external comment id. Args: connection: An instance of SQLAlchemy connection. Returns: Integer of last comment id from external model. """ result = connection.execute( sa.text(""" SELECT MAX(id) FROM ...
5cc139e3c4490293ebb305b7cac03d4803c51df6
3,631,054
from typing import SupportsAbs import math def is_unit(v: SupportsAbs[float]) -> bool: # <2> """'True' if the magnitude of 'v' is close to 1.""" return math.isclose(abs(v), 1.0)
0b31da2e5a3bb6ce49705d5b2a36d3270cc5d802
3,631,055
def atom_eq(at1,at2): """ Returns true lits are syntactically equal """ return at1 == at2
43aab77292c81134490eb8a1c79a68b38d50628d
3,631,056
def is_valid_month (val): """ Checks whether or not a two-digit string is a valid date month. Args: val (str): The string to check. Returns: bool: True if the string is a valid date month, otherwise false. """ if len(val) == 2 and count_digits(val) == 2: month = int(val) ...
53d825473cf497441d09e08402e833fa9c362a83
3,631,057
def env_repos(action=None): """ Perform an action on each environment repository, specified by action. """ actions = { 'add': _add_repo, 'reset': _reset_repo, 'rm': _rm_repo } def validate_action(input): if input not in actions: raise Exception('Inval...
f9b9ab0e671757bbcdf7bf4f50fe05e079aca115
3,631,058
import re def get_job_definition_name_by_arn(job_definition_arn): """ Parse Job Definition arn and get name. Args: job_definition_arn: something like arn:aws:batch:<region>:<account-id>:job-definition/<name>:<version> Returns: the job definition name """ pattern = r".*/(.*):(.*)" ...
d55bab5bbc62bf6d9f7907e26cb2a4a418bd9c50
3,631,059
def get_polyline_length(polyline: np.ndarray) -> float: """Calculate the length of a polyline. Args: polyline: Numpy array of shape (N,2) Returns: The length of the polyline as a scalar """ assert polyline.shape[1] == 2 return float(np.linalg.norm(np.diff(polyline, axis=0), axi...
9fb76a611c961af8ca10fda33029a55eb8589be1
3,631,060
def add_update_stock(symbol, is_held): """This function takes a stock symbol as a string, makes a call to yfinance, and gets back the necessary data to add the symbol to the database. `is_held` must also be specified, to mark the is_held flag in the database True/False.""" session = connect_to_sessio...
df5c7782fd07f916e61e4d5dc1f8f8cf9be86eec
3,631,062
import math def k2(Ti, exp=math.exp): """[cm^3 / s]""" return 2.78e-13 * exp(2.07/(Ti/300) - 0.61/(Ti/300)**2)
6c1f471b31767f2d95f3900a8811f47dc8c45086
3,631,063
async def add_source(request): """ API Endpoint to add new datasets to an instance API Params: file: location of the json or hub file filetype: 'hub' if trackhub or 'json' if configuration file Args: request: a sanic request object Returns: success/fail after addi...
624218d1e773c43a35fa3579d892cc6207e1ee1d
3,631,064
def clean_counties_data(): """Clean US Counties data from NY Times Returns: DataFrame -- clean us counties data Updates: database table -- NYTIMES_COUNTIES_TABLEs database view -- COUNTIES_VIEW """ _db = DataBase() data = _db.get_table(US_COUNTIES_TABLE, parse_dates=['d...
083e9720de9bfa422984d01fec08c0c4b33b0861
3,631,065
def get_3D_hist(sub_img): """ Take in a sub-image Get 3D histogram of the colors of the image and return it """ M, N = sub_img.shape[:2] t = 4 pixels = sub_img.reshape(M * N, 3) hist_3D, _ = np.histogramdd(pixels, (t, t, t)) return hist_3D
c582ec9b7d6bb24585ce5f95d2a770b4b7a06c37
3,631,066
import math import torch def magnitude_prune(masking, mask, weight, name): """Prunes the weights with smallest magnitude. The pruning functions in this sparse learning library work by constructing a binary mask variable "mask" which prevents gradient flow to weights and also sets the weights to z...
4bac89da952338e133ac0d85735e80631862c7da
3,631,068
import requests def delete_post(post_id): """Authenticates and proxies a request to users service to delete a post.""" try: my_user_id = get_user()['user_id'] response = requests.delete(app.config['POSTS_ENDPOINT'] + post_id, data={'author_id': my_user_id}) ...
a558ab58ac3129fb543c89c8b3c236126d26ddac
3,631,069
import collections def file_based_convert_examples_to_features_single(examples, label_list, max_seq_length, tokenizer, output_file): """Convert a set of `InputExample`s to a TFRecord file.""" writer = tf.python_...
444afd74b8bccd7e014e727d4be41be75fbdbb11
3,631,070
def less_equal(x, y): """Element-wise truth value of (x <= y). # Arguments x: Tensor or variable. y: Tensor or variable. # Returns A bool tensor. # Raise TypeError: if inputs are not valid. """ scalar = False if isinstance(x, KerasSymbol): x = x.sym...
566c46cc4882f167275cb6bc400800413efdc85b
3,631,071
from datetime import datetime def annual_reports(): """ Return list of all existing annual reports """ database = DataProvider() total = count(database.objects, lambda x: x.with_cafe) * 2 + \ count(database.objects, lambda x: not x.with_cafe) reports_list = list() # calculate count of ...
2e6daacd7150e47b299948b60866238589881ef5
3,631,072
def definition_for_include(parsed_include, parent_definition_key): """ Given a parsed <xblock-include /> element as a XBlockInclude tuple, get the definition (OLX file) that it is pointing to. Arguments: parsed_include: An XBlockInclude tuple parent_definition_key: The BundleDefinitionLocator...
325de830231c9b21a3c7cfce4262fef291ab6fbf
3,631,074
def verify_user(uid, token_value): """ Verify the current user's account. Link should have been sent to the user's email. Args: token_value: the verification token value Returns: True if successful verification based on the (uid, token_value) False if token is not valid for...
e63e7044e66bb29e8f44d7fa0a08128597e7b07e
3,631,075
def cholesky_metric(chol: JAXArray, *, lower: bool = True) -> Metric: """A general metric parameterized by its Cholesky factor The units of the Cholesky factor are length, unlike the dense metric. Therefore, .. code-block:: python cholesky_metric(jnp.diag(ell)) and .. code-block:: p...
406d0db5d3f6f9317a0b45895823c3927564653a
3,631,076
import typing def format_roman(value: int) -> str: """Format a number as lowercase Roman numerals.""" assert 0 < value < 4000 result: typing.List[str] = [] index = 0 while value != 0: value, remainder = divmod(value, 10) if remainder == 9: result.insert(0, ROMAN_ONES[...
259b205ffa25bbdeccb0ca6883c02c99d194f60d
3,631,077
def isint(s): """Does this object represent an integer?""" try: int(s) return True except (ValueError, TypeError): return False
dbcb20b437f1ccfb09f5cb969b7d5b9d369d2e38
3,631,079
def embed_vimeo(url): """ Return HTML for embedding Vimeo videos or ``None``, if argument isn't a Vimeo link. The Vimeo ``<iframe>`` is wrapped in a ``<div class="responsive-embed widescreen vimeo">`` element. """ match = VIMEO_RE.search(url) if not match: return None d = ma...
7923991466ec3eafa4c991bb93b2244ebcf99c47
3,631,080
def random_sample(random_state, size=None, chunk_size=None, gpu=None, dtype=None): """ Return random floats in the half-open interval [0.0, 1.0). Results are from the "continuous uniform" distribution over the stated interval. To sample :math:`Unif[a, b), b > a` multiply the output of `random_samp...
441a8d1b6e972ab961cf5910cd3737e5a21578e7
3,631,081
def anndata_file(): """Pytest fixture for creation of anndata files.""" def _create_file(nvals): size = 15289 * nvals vals = np.zeros(size, dtype=np.float32) non_zero = size - int(size * 0.92) non_zero = int(np.random.normal(loc=non_zero, scale=10, size=1)) rand = np.rand...
0f9c1ff260ae48837e9f925c65fd87c7b5f75768
3,631,082
def _heatmap_summary(pvals, coefs, plot_width=1200, plot_height=400): """ Plots heatmap of coefficients colored by pvalues Parameters ---------- pvals : pd.DataFrame Table of pvalues where rows are balances and columns are covariates. coefs : pd.DataFrame Table of coefficien...
32dae78fbaa3e978d418255e387e63f6346315ff
3,631,083
from datetime import datetime def get_warehouse_latest_modified_date(email_on_delay=False): """ Return in minutes how fresh is the data of app_status warehouse model. """ last_completed_app_status_batch = Batch.objects.filter( dag_slug='app_status_batch', completed_on__isnull=False ).order...
541dba13fde93acc51a41a9079a6da5f0344514a
3,631,084
async def async_unload_entry(hass, config_entry): """Handle removal of an entry.""" return True
28005ececbf0c43c562cbaf7a2b8aceb12ce3e41
3,631,086
def render_links(link_dict): """Render links to html Args: link_dict: dict where keys are names, and values are lists (url, text_to_display). For example:: {"column_moistening.mp4": [(url_to_qv, "specific humidity"), ...]} """ return { key: " ".join([_html_l...
c07f388e97f9e723cfc42ee66ef1eea654167820
3,631,087
import json def is_valid_json(text: str) -> bool: """Is this text valid JSON? """ try: json.loads(text) return True except json.JSONDecodeError: return False
3013210bafd5c26cacb13e9d3f4b1b708185848b
3,631,088
import signal def peri_saccadic_response(spike_counts, eye_track, motion_threshold=5, window=15): """ Computes the cell average response around saccades. params: - spike_counts: cells activity matrix of shape (t, n_cell) - eye_track: Eye tracking data of shape (t, x_pos, y_pos, ...) ...
85455106bb1cd438b2aeb25ee0fc3708a166d4b7
3,631,089
import operator def assign_subpopulation_from_region(pop, region, criteria, verbose=False): """ Compute required consistencies and assign subpopulations to a population of models based on results from a simulation region. Inputs: pop - a PopulationOfModels class region - a list of simulations ...
5279d7e398ed164aed4131bb1c826c5f1604c4a4
3,631,090
def op_structure(ea, opnum, id, **delta): """Apply the structure identified by `id` to the instruction operand `opnum` at the address `ea`. If the offset `delta` is specified, shift the structure by that amount. """ ea = interface.address.inside(ea) if not database.type.is_code(ea): raise E...
95d45003c86b4a99bb60d00eb584bb358f1cf350
3,631,091
from pathlib import Path def get_config_path(root: str, idiom: str) -> Path: """Get path to idiom config Arguments: root {str} -- root directory of idiom config idiom {str} -- basename of idiom config Returns: Tuple[Path, Path] -- pathlib.Path to file """ root_path = Path...
86d65f11fbd1dfb8aca13a98e129b085158d2aff
3,631,092
def status(): """ Method to get the list of components available. :return: It yields json string for the list of components. """ data = pgc.get_data("status") return render_template('status.html', data=data)
012431c843d051aec85df45fad005b9d17c71a5d
3,631,093
from typing import Union from typing import Iterable from typing import Tuple from typing import List import heapq def dijkstra( graph: LilMatrix, source: Union[int, Iterable[int]] ) -> Tuple[List[int], List[int]]: """Dijkstra Parameters ---------- graph Weighted Graph source ...
62278adeda336344eadaac00b9240cddd747b496
3,631,094
def stdev(some_list): """ Calculate the standard deviation of a list. """ m = mean(some_list) var = mean([(v - m)**2 for v in some_list]) return sqrt(var)
4a8cf5d19af1e07e8228d285d1f2fcfb702a2158
3,631,095
def get_hg19_chroms(): """Chromosomes in the human genome Returns: list: list of chromosomes """ return get_hg38_chroms()
2565eb2fa1ca1dd1b513a2a7dc836777911c7fc8
3,631,096
def track(im0, im1, p0, lk_params_, fb_threshold=-1): """ Main tracking method using sparse optical flow (LK) im0: previous image in gray scale im1: next image lk_params: Lukas Kanade params dict fb_threshold: minimum acceptable backtracking distance """ if p0 is None or not len(p0): ...
4a35dbb3c206f3b2e967f2b15853b19c7d579eb9
3,631,097
def get_kernel(X, Y, type='linear', param=1.0): """Calculates a kernel given the data X and Y (dims x exms)""" _, Xn = X.shape _, Yn = Y.shape kernel = 1.0 if type == 'linear': #print('Calculating linear kernel with size {0}x{1}.'.format(Xn, Yn)) kernel = X.T.dot(Y) if type == ...
98bd634456bbc4ec115de58fd58a1cd6df84b3a5
3,631,098
def MIDPOINT(ds, count, timeperiod=-2**31): """MidPoint over period""" return call_talib_with_ds(ds, count, talib.MIDPOINT, timeperiod)
0315f5148bbd4621db30aa572fd984f23cb6ee79
3,631,099
def dtype(): """A fixture providing the ExtensionDtype to validate.""" return RaggedDtype()
d441f5e211c57edf009d9311e411dfb6d9833f75
3,631,101
import numpy def geod2cart(rlat, rlon, height): """ Geodetic to Cartesian coordinate conversion Call cart = geod2cart(rlat, rlon, height) Input rlat -- NumPy float array of Geodetic latitudes rlon -- NumPy float array of Geodetic longitudes height -- NumPy float array...
02dbb30ef4960ac523d43a89a3a76336e7b1b564
3,631,103
import requests import json import traceback def check_deluge(): """ Connects to an instance of Deluge and returns a tuple containing the instances status. Returns: (str) an instance of the Status enum value representing the status of the service (str) a short descriptive string represent...
8cc129a4c7465c52e1d9b82da949c33aa5929c8a
3,631,105
def minor_min_width(G): """Computes a lower bound for the treewidth of graph G. Parameters ---------- G : NetworkX graph The graph on which to compute a lower bound on the treewidth. Returns ------- lb : int A lower bound on the treewidth. Examples -------- Thi...
649ea7fe0a55ec5289b04b761ea1633c2a258000
3,631,106
def generate_dataset(size=10000, op='sum', n_features=2): """ Generate dataset for NALU toy problem Arguments: size - number of samples to generate op - the operation that the generated data should represent. sum | prod Returns: X - the dataset Y - the dataset labels """ X...
3bd1b437d64c5260ec03a60114e9b8828f868c24
3,631,108
def glob2regexp(glob: str) -> str: """Translates glob pattern into regexp string. """ res = "" escaping = False incurlies = 0 pc = None # Previous char for cc in glob.strip(): if cc == "*": res += ("\\*" if escaping else ".*") escaping = False elif cc...
1ae8d180663468aaeed44974da3e409b803e4a37
3,631,109
def distance(array1, array2): """计算两个数组矩阵的欧式距离; axis=0,求每列的 axis=1,求每行的 """ distance = np.sqrt(np.sum(np.power(array1 - array2, 2))) return distance
bf6d38c4f6ebf19a048c732bc95796ab9837907f
3,631,110
import IPython.parallel from engine_manager import EngineManager def parallel_map(function, *args, **kwargs): """Wrapper around IPython's map_sync() that defaults to map(). This might use IPython's parallel map_sync(), or the standard map() function if IPython cannot be used. If the 'ask' keyword ar...
111219097c46ed719e67063ccb079f01d2f38363
3,631,111
def init_glorot(shape, name=None): """Glorot & Bengio (AISTATS 2010) init.""" init_range = np.sqrt(6.0/(shape[0]+shape[1])) initial = tf.random_uniform(shape, minval=-init_range, maxval=init_range, dtype=tf.float32) return tf.Variable(initial, name=name)
05467f77de85c2dada59785e1b211055ce38ebda
3,631,112
def securities(identifier=None, query=None, exch_symbol=None): """ Get securities with optional filtering using parameters. Args: identifier: Identifier for the legal entity or a security associated with the company: TICKER SYMBOL | FIGI | OTHER IDENTIFIER query: Search of secur...
4c839dc2bc606ee10a70fa6e81f706b3c0ea0f1a
3,631,113
def stations_within_radius(stations, centre, r): """The function stations_within_radius returns a list of the stations within a radius r from a centre""" stations_new=[] for s in stations: # distance can be computed using haversine library d=haversine.haversine(s.coord, centre) ...
de690076ff6d9b58176a3bb14612892344f3c78c
3,631,114
def normalize_email(email): """Normalizes the given email address. In the current implementation it is converted to lower case. If the given email is None, an empty string is returned. """ email = email or '' return email.lower()
6ee68f9125eef522498c7299a6e793ba11602ced
3,631,115
def _parse_hostname(url, include_port=False): """ Parses the hostname out of a URL.""" if url: parsed_url = urlparse((url)) return parsed_url.netloc if include_port else parsed_url.hostname
af37380619121274c608a22f151726ac79a05ad2
3,631,116
def voy(lr_angle): """ Returns y component for reference velocity v_0""" return -np.sin(np.radians(lr_angle))*9+np.cos(np.radians(lr_angle))*(12.+220.)
156238dec8630b7c98535d54f826682a94e29ed1
3,631,117
def get_l8turbidwater(rho1, rho2, rho3, rho4, rho5, rho6, rho7): """Returns Boolean numpy array that marks shallow, turbid water""" watercond2 = get_l8commonwater(rho1, rho4, rho5, rho6, rho7) watercond2 = np.logical_and(watercond2, rho3 > rho2) return watercond2
2690390eab21b53581979f71e1e144a178bcaa75
3,631,118
def string_extract_only_alphabets(inputString=""): """ Returns only alphabets from given input string """ return loader.string_extract_only_alphabets(inputString)
118cf8b6f16585cf7a7418abfe85d4fba54c4d5a
3,631,120
from typing import Optional def get_trigger(location: Optional[str] = None, project: Optional[str] = None, project_id: Optional[str] = None, trigger_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTriggerResult: ...
c146b8f8bfb47d3207501004531d1d90926dda60
3,631,121
def selu(x): # https://gist.github.com/naure/78bc7a881a9db17e366093c81425184f """Scaled Exponential Linear Unit. (Klambauer et al., 2017) # Arguments x: A tensor or variable to compute the activation function for. # References - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706....
784e82c3921f1b7656a3acbb81c2974d4220b113
3,631,123
import logging import importlib def __clsfn_args_kwargs(config, key, base_module=None, args=None, kwargs=None): """ Utility function called by both create_object and create_function. It implements the code that is common to both. """ logger = logging.getLogger('pytorch_lm.utils.config') logger...
66aae2787426dc2fd7fdc06b3d0e191c2d77d170
3,631,124
def parse_read_options(form, prefix=''): """Extract read options from form data. Arguments: form (obj): Form object Keyword Arguments: prefix (str): prefix for the form fields (default: {''}) Returns: (dict): Read options key - value dictionary. """ read_options = { ...
660e836172015999fe74610dffc331d2b37991c3
3,631,125
def get_app_version_info(domain, build_id, xform_version, xform_metadata): """ there are a bunch of unreliable places to look for a build version this abstracts that out """ appversion_text = get_meta_appversion_text(xform_metadata) commcare_version = get_commcare_version_from_appversion_text(a...
78e04bb736fd7d5e7a84e2e4661f3d5c9dde4492
3,631,127
def plot_components_plotly( m, fcst, uncertainty=True, plot_cap=True, figsize=(900, 200)): """Plot the Prophet forecast components using Plotly. See plot_plotly() for Plotly setup instructions Will plot whichever are available of: trend, holidays, weekly seasonality, yearly seasonality, and add...
cbc9eccfc2cc12a8f0d9a2b13c0846a87f260e4e
3,631,128
def _format_as_geojson(results, geodata_model): """joins the results to the corresponding geojson via the Django model. :param results: [description] :type results: [type] :param geodata_model: [description] :type geodata_model: [type] :return: [description] :rtype: [type] """ # re...
5d0cde796dc4687af352de40e22df8d8e412bf8b
3,631,129
def crosscorr(dfA, dfB, method='pearson', minN=0, adjMethod='fdr_bh'): """Pairwise correlations between A and B after a join, when there are potential column name overlaps. Parameters ---------- dfA,dfB : pd.DataFrame [samples, variables] DataFrames for correlation assessment (Nans will be ...
3c326a642cb7891298913db303792305b8f01b12
3,631,130
import torch def normalize_gradient(netC, x): """ f f_hat = -------------------- || grad_f || + | f | x: real_data_v f: C_real before mean """ x.requires_grad_(True) f = netC(x) grad = torch.autograd.grad( f, [x], torch.ones_like(f), create...
ff1b8b239cb86e62c801496b51d95afe6f6046d4
3,631,131
import numbers def compile_snippet(tmpl, **kwargs): """ Compiles selected snipped with jinja2 :param tmpl: snippet name :param kwargs: arguments passed to context :return: generated HTML """ def wrapper(val): if isinstance(val, numbers.Number): return val elif i...
02926dc6b451d42d48c488811f8c4db9806f589e
3,631,133
from typing import Optional from re import T def not_none(t: Optional[T], default: T): """ Returns `t` if not None, else `default`. :param t: the value to return if not None :param default: the default value to return :return: t if not None, else default """ return t if t is not None else...
b49d9fb621af64e347dc02aebd93c6fb987e94c1
3,631,134
def fallback_feature(func): """Decorator to fallback to `batch_feature` in FeatureModule """ def wrapper(self, *args, **kwargs): if self.features is not None: ids = args[0] if len(args) > 0 else kwargs['batch_ids'] return FeatureModule.batch_feature(self, batch_ids=ids) ...
cb1fd52c6ddcbbf1d0065f70b5656ddda937440e
3,631,135
def extract_segment_features(y, sr): """ Extract audio features from a segment of audio using librosa. Input: An array of a audiofile. Output: Dictionary of segments with keys: tempo, beats, chroma_stft, rms, spec_cent, spec_bw, rolloff, zcr, and mfcc values from 1-12. """ tem...
a64fde839199c8d800c9bae39799f353f71a4b5e
3,631,136
def find_info_by_ep(ep): """ 通过请求的endpoint寻找路由函数的meta信息""" return manager.find_info_by_ep(ep)
3fd834c9b17b1e0e2e58a60e790998c751c70743
3,631,137
def obtener_cantidad_total_turistas_entrantes_en_ciudad_anio(Ciudad, Anio): """ Dado una ciudad y un año obtiene la cantidad total de personas que llegan a esa ciudad de forma total Dado una ciudad y un año obtiene la cantidad total de personas que llegan a esa ciudad de forma total :param Ciudad: Ciuda...
c7512aa8e640afc3a84f94d1f0c1c3d82094921d
3,631,138
def update_from_file(params, par_file): """Update the config dictionary params from file. Args: params (dict): Dictionary holding the to-be-updated values. par_file (str): Name of the parameter file with the update values. Returns: params (dict): ...
1de0f3fc3f379508cb29d38c6e9bd1b70fa1e9c7
3,631,139
def accumulated_other_comprehensive_income(ticker, frequency): """ :param ticker: e.g., 'AAPL' or MULTIPLE SECURITIES :param frequency: 'A' or 'Q' for annual or quarterly, respectively :return: obvious.. """ df = financials_download(ticker, 'bs', frequency) return (df.loc['Accumulated other ...
81b02370790457db598cac699cc0ffa835b9f6ac
3,631,140
def PDifHist (inPixHistFDR): """ Return the differential pixel histogram returns differential pixel histogram inPixHistFDR = Python PixHistFDR object """ ################################################################ # Checks if not PIsA(inPixHistFDR): raise TypeError("inPixHist...
eae6b0c354482b48c3ef9d39bb556ce7e9ef93ca
3,631,141
def SendToRietveld(request_path, payload=None, content_type="application/octet-stream", timeout=None): """Send a POST/GET to Rietveld. Returns the response body.""" def GetUserCredentials(): """Prompts the user for a username and password.""" email = upload.GetEmail() password = getp...
d0937307a894b55f4ed5534de81bb60bf1f46333
3,631,142
def _parse_args(): """ For parsing args when run as __main__. """ parser = ArgumentParser(description='Simulates the action of a Turing Machine.') parser.add_argument('path', help="Path of a file containing rule quintuples.") parser.add_argument('input', help="Input string.") parser.add_argument('--rules', ac...
0b059e467703f34ac2358db19b87c06ab90b9771
3,631,143
def join_2_steps(boundaries, arguments): """ Joins the tags for argument boundaries and classification accordingly. """ answer = [] for pred_boundaries, pred_arguments in zip(boundaries, arguments): cur_arg = '' pred_answer = [] for boundary_tag in pred_boundari...
9801ca876723d092f89a68bd45a138dba406468d
3,631,144
def qac_image(image, idict=None, merge=True): """ save a QAC dictionary, optionally merge it with an old one return the new dictionary. This dictionary is stored in a casa sub-table called "QAC" image: input image idict: new or updated dictionary. If blank, it return QAC ...
32bd3ffac05455a7157c7471bad559df24702b6e
3,631,145
import random def get_random_useragent(): """生成随机的UserAgent :return: UserAgent字符串 """ return random.choice(USER_AGENTS)
f70de4e52399a291e8d65633e8f555d748905fc6
3,631,146
def product_detail_view(request, pk='', **kwargs): """ Display a detailed view of a product, showing all specifications """ ctxt = {'pk': pk} # Empty (thus invalid) pk if pk == '': return client_error_view(request, ERROR_MSG['wrong_prod_pk'].format(pk), 404) matching_products = Product.objects.filter(pk=pk...
3244156920798b4c3008ee2e8a19d5fd5de86559
3,631,147
def _convert_velocities( velocities: np.ndarray, lattice_matrix: np.ndarray ) -> np.ndarray: """Convert velocities from atomic units to cm/s. Args: velocities: The velocities in atomic units. lattice_matrix: The lattice matrix in Angstrom. Returns: The velocities in cm/s. "...
8848d58a37244b2109455a73c2fd2458b0e21c58
3,631,148
import operator import math def unit_vector(vec1, vec2): """ Return a unit vector pointing from vec1 to vec2 """ diff_vector = map(operator.sub, vec2, vec1) scale_factor = math.sqrt( sum( map( lambda x: x**2, diff_vector ) ) ) if scale_factor == 0: scale_factor = 1 # We don't have an actu...
79e2cff8970c97d6e5db5259801c58f82075b1a2
3,631,150
def shuffle_list(gene_list, rand=np.random.RandomState(0)): """Returns a copy of a shuffled input gene_list. :param gene_list: rank_metric['gene_name'].values :param rand: random seed. Use random.Random(0) if you like. :return: a ranodm shuffled list. """ l2 = gene_list.copy() rand...
3e3660a2266bb8f5d7ea2172148806d20a4b1b2b
3,631,151
def my_map(f, lst): """this does something to every object in a list""" if(lst == []): return [] return [f(lst[0])] + my_map(f, lst[1:])
20016cd580763289a45a2df704552ee5b5b4f25e
3,631,152
import struct import ipaddress def read_ipv6(d): """Read an IPv6 address from the given file descriptor.""" u, l = struct.unpack('>QQ', d) return ipaddress.IPv6Address((u << 64) + l)
c2006e6dde0de54b80b7710980a6b0cb175d3e19
3,631,153
def normalizeRounding(value): """ Normalizes rounding. Python 2 and Python 3 handing the rounding of halves (0.5, 1.5, etc) differently. This normalizes rounding to be the same (Python 3 style) in both environments. * **value** must be an :ref:`type-int-float` * Returned value is a ``int``...
442bbee5838f5bef0edbe6ce6e42f8c744f7d220
3,631,154
def pin_light(a: np.ndarray, b: np.ndarray) -> np.ndarray: """Combines lighten and darken blends. :param a: The existing values. This is like the bottom layer in a photo editing tool. :param b: The values to blend. This is like the top layer in a photo editing tool. :param colorize: (Op...
f551bc26cebdbc6750fb42653ff23b4aeda09d6f
3,631,155
from pathlib import Path def sun(): """Get Sun data source""" filename = ( Path(nowcasting_dataset.__file__).parent.parent / "tests" / "data" / "sun" / "test.zarr" ) return SunDataSource( zarr_path=filename, history_minutes=30, forecast_minutes=60, )
06f9db778662d65e7a157b314b8a1cd3e647c7e7
3,631,156
def generate_level08(): """Generate the bricks.""" bricks = bytearray(8 * 5 * 3) colors = [2, 0, 1, 3, 4] index = 0 col_x = 0 for x in range(6, 111, 26): for y in range(27, 77, 7): bricks[index] = x bricks[index + 1] = y bricks[index + 2] = colors[col_...
c1535d8efb285748693f0a457eb6fe7c91ce55d4
3,631,157