content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def sync_data(request): """ View to call sync_data management command. """ if not request.user.is_superuser: raise PermissionDenied form = SyncDataForm() if request.method == "GET": return render(request, "sync_data.html", {"form": form}) call_command("sync_data") retu...
9166aba3be9c033b30d51a571e76ec51b7e8ee63
3,603,840
def search_data_in_documents(search_str): """Search data in all the documents Args: search_str (str): String to be search in all the documents Returns: List of tuples containing document object and content """ list_of_documents = [] data_list = models.Data.objects.filter(data__...
56ec6f3da2acd8b3d1f98b1704defba152f10c7d
3,603,841
def weight_on_edge(data, zxing): """ This weight is independent of the cell_width. So even, when we have already a good estimation of the cell width, this weight does not need to take the width into account. """ value_before = data[zxing] value_after = data[zxing + 1] slope = value_aft...
3af14f15589dd5227a21b53598b896a8cca4c79a
3,603,842
import dill def hashable(a) -> int: """ Hashes many kinds of objects, including some that are unhashable through the builtin `hash` function. Lists and tuples are hashed based on their elements. """ if isinstance(a, dict): # first hash the keys and values with hashable # then hash ...
29f55a4586f09156618a70e8443dc8b847260e14
3,603,844
def pygal_parser(preprocessor, tag, markup): """ Simple pygal parser """ # Find JSON payload data = loads(markup) if tag == 'pygal' and data is not None: # Run generation of chart output = run_pygal(data) # Return embedded SVG image return '<div class="pygal" style="text-...
a6b8abb3c688ccfa13c05c3ca14db3f4ff0a8cd3
3,603,845
def effective_kernel(kernel_shape, dilations): """ Args: kernel_shape: tuple[int] representing the kernel shape in each given dimension. dilations: tuple[int] representing the dilation of the kernel in each given dimension. Must be the same length as kernel_...
a955d185c924514bf981c2512a8e78646d523144
3,603,846
from typing import Union from typing import Optional from typing import Tuple from typing import Any def eval_step_single_learner( jax_task: base_task.SingleTask, states: TrainState, prng_key: JTensor, inputs: Union[JTensor, NestedMap], data_parallel_axis_name: Optional[str] = 'batch', fprop_d...
6af0eab44e1c112b4358d7e67da87ed3ac33f0ad
3,603,847
def get_or_create_global_step(): """ Checks if global step variable exists otherwise creates it :return: Global step tensor """ global_step = tf.train.get_global_step() if global_step is None: global_step = tf.train.create_global_step() return global_step
52d4b64874d8f0295be6c606ba5851a384bc6c7e
3,603,848
from typing import Sequence def fasta_reader(fasta_path): """ :param fasta_path: the path to the file to parse :type fasta_path: string :return: a sequence :rtype: Sequence instance """ with open(fasta_path, 'r') as fasta_infile: id_ = '' comment = '' sequence = '' ...
325aafabf553cf2880bdfc4116ee1e03b4a1e39f
3,603,849
def get_slice_hostnames( slice_name ): """ Query the Django DB and get the list of hosts running in a slice. """ openstack_slice = Slice.objects.get( name=slice_name ) if openstack_slice is None: logger.error("No such slice '%s'" % slice_name) return None hostnames = [s.node.name for s...
5bf374d4252189fb21ca0dc8d461b671d5ef39bf
3,603,850
def CreateFigure(FigSizeFormat="default", AspectRatio=16./9.): """ This function creates a default matplotlib figure object Args: FigSizeFormat: the figure size format according to journal for which the figure is intended values are geomorphology,ESURF, ESPL, EPSL, JGR, big ...
3b88c73bc197d129db3f7f8a8a45e9b5d0f8657a
3,603,851
def choose_random_nm(odd=False): """Choose random n and m. Optional argument specifies whether n and m are seperated by a factor of 2 or not. """ m = np.nan n = np.nan # make sure m and n are seperated by a factor of 2 otherwise # we'll get all zeros while (m - n + odd) % 2: # c...
a82c7b1953de3991cc6461bbfddadffb8a3ff215
3,603,852
def int_from_32bit_array(val): """Converts an integer from a 32 bit bytearray :param val: the value to convert to an int :type val: int :rtype: int """ rval = 0 for fragment in bytearray(val): rval <<= 8 rval |= fragment return rval
ca2f32c7eac6f42aeed688510fa57e717edfacdf
3,603,854
def build_evaluation_from_config_item(configuration_item, compliance_type, annotation=None): """Form an evaluation as a dictionary. Usually suited to report on configuration change rules. Keyword arguments: configuration_item -- the configurationItem dictionary in the invokingEvent compliance_type -- ei...
05769fc549acdcec7ed611abeff5f0b4f695e57e
3,603,855
from typing import Union def STEP(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]: """ A. Dudek, Z. Szkutnik, "Minimax unfolding spheres size distribution from linear sections", Statistica Sinica 18 (2008) 1063–1080 """ return np.where(x <= 1 / 3, 0.6, np.where(x <= 3 / 4, 0.9, 1.7))
de66d9b75d1c4d86109db3c448201a2042913b79
3,603,859
import functools def requires_attr(attr_name, raiser): """ Methods wrapped in this decorator raise an error if a required attribute is not set. """ def decorator(meth): @functools.wraps(meth) def wrapper(self, *args, **kwargs): if getattr(self, attr_name, None) is None:...
e88d5ecfc39688683c7c29fbfc68db79cc760216
3,603,860
def to_qsw(orbit): """In the QSW Local Orbital Reference Frame, x is oriented along the position vector, z along the angular momentum, and y complete the frame. The frame is sometimes also called RSW (where R stands for radial) or LVLH (Local Vertical Local Horizontal). Args: orbit (list):...
1aa4b1f82626e0a6176202708ce4f25eeeb3c1c7
3,603,862
from typing import List def get_possible_proteins(fasta_data: List[str]) -> str: """ :param fasta_data: A DNA sequence in FASTA format :return: a formatted set of possible proteins encoded in DNA """ strands = parse_fasta(fasta_data) # there should be only one sequence strand, = strands ...
67a3b9b42badf2a74d82075cd610c7691e961d23
3,603,864
def theta(flag, S, K, t, r, sigma): """Return Black-Scholes theta of an option. :param S: underlying asset price :type S: float :param K: strike price :type K: float :param sigma: annualized standard deviation, or volatility :type sigma: float :param t: time to expiration in years :...
ae962cb0e7111140de01909a797f361a3aa8964f
3,603,865
def _pretty_print_label(d): """Internal utility to pretty print point label info.""" s = " %s: "%repr(d[0]) entry_keys = list(d[1].keys()) ki = 0 kimax = len(entry_keys) for k in entry_keys: keys = list(d[1][k].keys()) if len(keys) == 0: s += "{%s: {}}"%k else...
4972b54d2402d87e6fe276605c59d21cfdc91533
3,603,866
def test_load_snapshot_default(): """Loads the default snapshot. """ sp = GOSnapshot() summaries = [] summaries.append(sp.summary) df = to_df(summaries) return True
1a37e07151f5a21dd15c15350554476176167253
3,603,867
def traverse_graph(prev_layer, layers): """Traverse keras sequential graph.""" for layer in layers: if isinstance(layer, (tf.keras.Sequential, tf.keras.Model)): prev_layer = traverse_graph(prev_layer, layer.layers) else: prev_layer = layer(prev_layer) return prev_layer
75ccdc55b6ec9b141c3a7d15fa554ce894afb7f3
3,603,868
def peak_locked_percentile(signals, fs, peak_loc, t_plot, percentiles=['mean']): """ Compute the mean of each signal in signals, locked to the peaks Parameters ---------- signals : shape (n_signals, n_epochs, n_points) fs : sampling frequency peak_loc ...
1c99ed358c05e0d33dd906bda3e7b64a641d2364
3,603,869
def dict2obj(target, change_dict=True): """ 将dict转换成obj对象 change_dict 用于控制是否转换target内部dict为obj :param target: dict :param change_dict: bool :return: obj """ class Obj(object): def __init__(self, d, change_dict): for a, b in d.items(): if change_dict ...
4beec4d45528e2939a0c63333b8a401e34df3b3d
3,603,870
def simulate_output_data(func, xvals, param_dict, **metadata): """Generate arbitrary fit data.""" __shots = 100000 expected_probs = func(xvals, **param_dict) counts = np.asarray(expected_probs * __shots, dtype=int) data = [ { "counts": {"0": __shots - count, "1": count}, ...
2c0c143cf533f6aab8c06ac399b4f62efcd6709f
3,603,871
def user_logged_in(): """Checks if user logged in. """ if 'active_user' not in app.session: return False username = app.session['active_user'] return mongo.db.users.count({'username': username}) > 0
7ff3b4f6f7882fc48f9cc0cadfc6e895765fadb1
3,603,872
def ewins(freq, H, nf='None', residues=False, type='d', o_fr=0): """ Arguments: - freq - frequency vector - H - a row or a column of FRF matrix - o_fr - list of optionally chosen frequencies in Hz. If it is not set, optional points are set automatically and are ...
8bb249a8c6fd8805cad724c73256635612746b4c
3,603,873
def splitbycharset(txt, charset): """Splits a string at the first occurrence of a character in a set. Args: txt: Text to split. chars: Chars to look for (specified as string). Returns: (char, before, after) where char is the character from the character set whic...
c23577eb96c9621909acaa816e8791e95dbf493d
3,603,874
from typing import Optional def mean( x: ArrayLike, axis: Axis = None, keepdims: bool = False, *, constant: Optional[bool] = None ) -> Tensor: """ Mean of tensor elements over a given axis. Parameters ---------- x : ArrayLike axis : Optional[int, Tuple[ints, ...] ...
816abd2b2a1f9c8c868bc1e7be52b650f35be166
3,603,875
def mmdagg( seed, X, Y, alpha, kernel_type, approx_type, weights_type, l_minus, l_plus, B1, B2, B3 ): """ Compute MMDAgg as defined in Algorithm 1 in our paper using the collection of bandwidths defined in Eq. (16) and the weighting strategies proposed in Section 5.1. inputs: seed: integer random se...
dee823fecde9ab44172e0d80ee721e45ac914a81
3,603,877
def _get_masses(fitnesses): """Convert fitnesses into masses, as given by GSA algorithm.""" # Obtain constants best_fitness = max(fitnesses) worst_fitness = min(fitnesses) fitness_range = best_fitness - worst_fitness # Calculate raw masses for each solution raw_masses = [] for fitness i...
12e2b4414ce53a9477420ed0d58006f7f0248081
3,603,878
from typing import Optional from typing import List def format( # pylint: disable=redefined-builtin files: Optional[List[str]] = typer.Argument(default=None), # noqa: B008 check: bool = typer.Option( # noqa: B008 default=False, help='Only checks instead of modifying.' ), ) -> List[Result]: ...
c12a02170751fbf09ff88b059fc90518b7f45d8b
3,603,879
def make_plot(source): """Creation of simple graphs in bokeh""" # Set up plot p = figure(plot_width=400, plot_height=400, tooltips=tooltips) #p.vline_stack(['S', 'R', 'I'], x='t', source=source) p.vline_stack(['S'], x='t', source=source, color='blue', width=4, legend_label="Susceptible") p.vlin...
ecf0a7cf9bab6518d94f799e1956fcd7e2eb0507
3,603,880
def makeGeneratorConfig(couchDatabase): """ _makeGeneratorConfig_ Create a bogus config cache document for the montecarlo generation and inject it into couch. Return the ID of the document. """ newConfig = Document() newConfig["info"] = None newConfig["config"] = None newConfig["m...
b65015b6c06311d6de0d6b031a736bdecf084318
3,603,881
def poly2ac(poly, efinal): """ Convert prediction filter polynomial to autocorrelation sequence :param array poly: the AR parameters :param efinal: an estimate of the final error :return: the autocorrelation sequence in complex format. .. doctest:: >>> from numpy import array >>>...
1993bdca9cb6642a03307bb013b157ef4f3c7e11
3,603,882
def arctan(x): """Returns a new Var with arctangent applied to the input Var x :param x: object on which arctangent is applied, required :type x: AD_Object.Var :return: new object with arctangent applied to input :rtype: AD_Object.Var :example: >>> from autodiff.AD_BasicMath import...
aa889e8056a44defbc509616ef9831f6c35c6e43
3,603,883
def process_meta_review(meta_review): """ Do something with the meta-review JSON! This is where you would: 1. Translate meta_review["ty_id"] to your own hotel ID, dropping any unmapped hotels 2. Traverse the JSON structure to find the data you are interested in, documented at http://api.trustyo...
681ace9b9685f4bfd284ac6e41efde12bafbb1b9
3,603,884
def ray_partition_get_data_label(partition_data, allow_tuple=True, allow_list=True, has_label=True): """ :param partition_data: The data partition from Spark RDD, which should be a list of records. :param allo...
e99c316a22e1828556abfef6928e74634955cfa8
3,603,885
def get_pdf_of_normal_distribution(x, mu, sigma): """Compute the probability of ``x`` under a normal distribution. This implementation is faster than calling ``scipy.stats.norm.pdf``. Parameters ---------- x : float or np.ndarray The probability is calculated for this value. mu : float...
8f8f8ec43f21d4f2596337fb9b5f799358faa23e
3,603,886
def compute_mesh_laplacian(verts, tris): """ computes a sparse matrix representing the discretized laplace-beltrami operator of the mesh given by n vertex positions ("verts") and a m triangles ("tris") verts: (n, 3) array (float) tris: (m, 3) array (int) - indices into the verts array compute...
118300945fa1573e29f389bf807ada5f11e36cac
3,603,887
def find_natural_number(position: int) -> tuple: """Return natural number at specified position and number its a part of.""" num_range = "" counter = 0 while len(str(num_range)) < position: counter += 1 num_range += str(counter) return int(num_range[-1]), counter
62aff0c400ac007fc67dafd25eb4cacf63262105
3,603,888
def camel_case(snake_case: str) -> str: """Converts snake case strings to camel case Args: snake_case (str): raw snake case string, eg `sample_text` Returns: str: camel cased string """ cpnts = snake_case.split("_") return cpnts[0] + "".join(x.title() for x in cpnts[1:])
b3080a3e3520209581cbd381ffaff24045343115
3,603,889
def get_onnx_shape(model): """Just input shape""" shape = {} for t in model.graph.input: name, etype, dims, dynamic = value_info_parse(t) shape[name] = dims return shape
c36335c1a13c80cb66e8aa51cd7d08d7a9b27c16
3,603,890
def calculate_mp_value( pert_df: pd.DataFrame, control_df: pd.DataFrame, params: dict = {}, ) -> pd.Series: """Given perturbation and control dataframes, calculate mp-value per perturbation Usage: Designed to be called within a pandas.DataFrame().groupby().apply(). See :py:func:`cytominer_eval....
24e5e7dae2cb894fe01e1ad47c12fbbfb8a1c21c
3,603,892
from unittest.mock import patch def test_query_asset_movements_sandbox( sandbox_kuckoin, inquirer, # pylint: disable=unused-argument ): """Unfortunately the sandbox environment does not support deposits and withdrawals, therefore they must be mocked. Below a list of the movements and the...
6e5269d4b69afc71a56992e0795d3036c1c58557
3,603,893
def ellipse_params(uamp, upha, vamp, vpha): """Calculates ellipse parameters based on the amplitude and phase for a tidal constituent. :arg uamp: u fitted amplitude of the chosen constituent :type uamp: :py:class:`numpy.ndarray` :arg upha: u fitted phase of the chosen constituent :type upha: :...
a7e9b98f71bb36c157288ba8d38a7670a822d7f8
3,603,894
def _guess_bounds(cube, coords): """Guess bounds of a cube, or not.""" # check for bounds just in case for coord in coords: if not cube.coord(coord).has_bounds(): cube.coord(coord).guess_bounds() return cube
44cdcdc8ee0dd821d3abdef880efe11c7cf8d48e
3,603,895
def render_to(template): """ Decorator for Django views that sends returned dict to render function. If view doesn't return dict then decorator simply returns output. Additionally view can return two-tuple, which must contain dict as first element and string with template name as second. This strin...
d053cc3ddb7cd0406da19b64ed09c61347c19c6a
3,603,896
def eigenvals( tb_model: orm.SinglefileData, kpoints: orm.KpointsData ) -> orm.BandsData: """Calculate the eigenvalues of a model at given k-points. Parameters ---------- tb_model : The tight-binding model. kpoints : The k-points at which the eigenvalues should be evaluated. ...
93eb57d8c448bbdd524fd791914d0724f62d70bf
3,603,897
def get_segment_model(): """ Returns the review model class. """ if get_review_app_name() != DEFAULT_REVIEWS_APP and hasattr(get_review_app(), "get_segment_model"): return get_review_app().get_segment_model() else: return ReviewSegment
0ca78bcf2e0b88cade7f2a4e9b06d53c903be336
3,603,898
def histograms(coordinate_sets, r_max, n_bins): """Distance histogram calculation on the CPU using Cython kernels. Calculate histograms from sets of species coordinates by calling the pwd() and pwd2() CPU functions from the Cython dist_knl. Serves as the reference implementation for the pydh and cudh ...
0700c85c3b0cc749cecc7caffe8634a482e0886c
3,603,900
import numpy def cv_image_from_bytes(image): """Convert image bytes to OpenCV image.""" import cv2 # pylint: disable=import-error # pylint: disable=no-member return cv2.imdecode(numpy.asarray(bytearray(image)), cv2.IMREAD_UNCHANGED)
820a25490b6bcce8f39f9c4aeb6520dbba1e5083
3,603,901
def form_url(main_url: str, url: str, data: t.Optional[t.Dict[str, t.Any]] = None) -> str: """ Form and return the URL for the Hypixel API with GET Params. Parameters ---------- main_url: str The Main URL With the root domain. url: str The Route in the Main URL to access the JSO...
9ddcb110bbd79820b11cfe0aa1ac9cd7d5ded1c1
3,603,902
def return_figures(stocks=default_portfolio, index=default_index): """Creates four plotly visualizations Args: None Returns: list (dict): list containing the four plotly visualizations """ def get_stock_history (tiker, invest_period): """ input: ...
1f289abfd46b2ee2811f1081841c282083d810f2
3,603,903
def reduce_repeat_bb(text_list, break_token): """ convert ['<b>Local</b>', '<b>government</b>', '<b>unit</b>'] to ['<b>Local government unit</b>'] PS: maybe style <i>Local</i> is also exist, too. it can be processed like this. :param text_list: :param break_token: :return: """ count = 0 ...
1c9d88ca295ab31831773264c2ede597b707f3f6
3,603,904
def get_spectrogram_data(data:np.array, sr:int, n_mels:int=32, types:str="4d") -> np.array: """ @topic: Convert 1-D audio wave to 2-D spectrogram and build 4-D dataset. @topic: wave: audio wave; sr: sample rate; n_mels: the size of output spectrogram; types: type of data. @return: 4-D spectrogram datase...
017dc78348c03185a194457855a25628e71a4c49
3,603,905
def is_preprocessor_punctuator(c): """Returns true if a preprocessor delimiter""" result = preprocessor_punctuator.match(c) return result is not None
1c9498f9bda541eb6883bf9f042d169031949aaf
3,603,906
def calculate_probability_contour(pdf,axes,pvals,axis=0): """ Calculates the probability level below which the PDF integrates to pval. input: ------ pdf : a conditional PDF from fastKDE axes : a list of axis values returned from fastKDE ...
19abdbb5b30f5dca1f4d6efa49db3c70cace47da
3,603,907
def model_tide_points(ds, points_gdf, extent_buffer=0.05): """ Takes an xarray.Dataset (`ds`), extracts a subset of tide modelling points from a geopandas.GeoDataFrame based on`ds`'s extent, then uses the OTPS tidal model to model tide heights for every point at every time step in `ds`. T...
47aaac8c6fd045bb5af2b09caaf244ffeb57e8dc
3,603,908
def verify() -> str: """Respond to the webhook verification (GET request).""" return request.args.get("challenge", "")
9f1de9d5ab33c6a3d689b818aa75d99108b962f7
3,603,909
def report_old(): """Redirect old bookmarked reports to the new path format.""" try: path = flask.request.args['q'] except: app.logger.info('Unable to decode valid domains from q GET param') return flask.redirect('/error/1') return flask.redirect('/search/{}'.format(path))
5ba17bb479a462d795e47c48c1f7bf9a337e8648
3,603,910
from typing import Union from typing import List from typing import Tuple def suggest_udict_terms( text: Union[str, List[str]], silent: bool = False, spinner: bool = True, ) -> Tuple[List[str], List[str]]: # fmt: on """ suggest userdict terms. >>> filename = "data/hlm-ch1-en.t...
48a7f9fb32b34b1e3cb0b762131d28a336594482
3,603,911
def ferret_result_limits(efid): """ Abstract axis limits for the shapefile_writexyval PyEF """ return ( (1, 1), None, None, None, None, None, )
ba5c3d3a5760b11384b551c08464c16587e58437
3,603,912
def get_provider_context(client=None): """Read the manager provider context.""" if client is None: client = get_rest_client() context = client.manager.get_context() return context['context']
d98112cece070abb88a368f224d9ceacb9cdc24a
3,603,914
def has_provider(provider): """Verifies that module has support for requested API provider.""" return provider.lower() in API_ALL
26215c8f664fdc54b2f625b0431723641200a5ce
3,603,915
def get_chisq_kctl(): """ Obtain chisq from kctl """ output_filen = ofile_for_fitresult read_on = False with open(output_filen, "r") as f: for l in f: if l.find('Results') != -1: read_on = True if read_on and (l.find('Chi**2 (normalized)') != -1): ...
4a2f49686e984e30d497412ba20a446c51707a6a
3,603,917
import re def get_converted_games(): """ Loads converted game movements CSV files and returns list of games to get event descriptions from """ # Try converted directory..maybe user removed csv directory to free up memory potential_game_dirs = [CONFIG.data.movement.converted.dir] names = [] ...
2b1d4301039f13e7e88d0d3e152da689a2785942
3,603,918
def configmap(): """ https://kubernetes.io/docs/tasks/configure-pod-container/configmap/ """ return { 'apiVersion': 'v1', 'kind': 'ConfigMap', 'metadata': { 'name': 'testcfgmap-game-config' }, 'data': { 'game.properties': "enemies=aliens\n...
aadc00e8046be12370202f82adca12b222b0696f
3,603,919
def node(auth, node): """Get node by ID or the ``uuid`` key out of a dictionary.""" if isinstance(node, dict): node = node['uuid'] response = API.get(auth, '/v1/nodes/{}'.format(node)) return response.json()
96650abc8c8482c2a6c685a4cb7c7a8af0e9fefe
3,603,921
def identify_contentType(url): """ Given a URL for a content, it identifies the type of the content :param url(str): URL :returns: Type of the content """ extensions = ['mp3', 'wav', 'jpeg', 'zip', 'jpg', 'mp4', 'webm', 'ecar', 'wav', 'png'] if ('youtu.be' in url) or ('youtube' in url): ...
720a9ea9adaab547309f61b6858b0eb19ddebafe
3,603,922
def wrap_annotation(annotation): """Wraps a dict as an instance of the registered Annotation model class. Arguments: - `annotation`: a dictionary-like object containing the model data """ request = get_current_request() cls = request.registry.queryUtility(interfaces.IAnnotationClass) resul...
b49962de4ad4bb06d48cbec02a232f8d1401b38a
3,603,923
def get_L_dash_HB_wall_floor_90_IS(): """主開口方向から時計回りに90°の方向の外気に面した壁と床の熱橋長さ (m) Args: Returns: float: 主開口方向から時計回りに90°の方向の外気に面した壁と床の熱橋長さ (m) """ return get_table_3(62, None)
2675decfd323d679d38452c1c9719f4e0898a3c9
3,603,924
import functools def profile_function(game, function, profiles, num_resamples, *, percentiles=None, processes=None): """Compute a function over profiles Parameters ---------- game : SampleGame The sample game to bootstrap the function value over. function : Game, prof...
20971cd84a0e35f88f2a13ac56e0ebe6266cc0b2
3,603,925
def nice_frequency(frequency): """return a string of the frequency with SI unit and a reasonable number of digits""" if frequency < 1e3: return "%dHz" % frequency elif frequency < 10e3: return "%.3fkHz" % (frequency / 1e3) elif frequency < 100e3: return "%.2fkHz" % (freque...
8fefa58236c57878be9f051e9cbfff85d398f87c
3,603,927
def stack(x, filters, num_blocks, block_fn, use_bias, stride1=2, name=None): """A set of stacked residual blocks. Arguments: x: input tensor. filters: integer, filters of the bottleneck layer in a block. use_bias: boolean, enables or disables all biases in conv layers. num_blocks: integ...
1ed366778a5abba4e05c070da05e3c87cbd92560
3,603,928
import http async def get_user(access_token: str) -> dict: """Coroutine to fetch User data from discord using the users `access_token`""" async with http.session.get( "%s/v6/users/@me" % DISCORD_ENDPOINT, headers={"Authorization": "Bearer %s" % access_token}, ) as response: return ...
71796cb8ce70759de902ed9fad17f64a092b6772
3,603,929
def mel2hz(mel): """Convert a value in Mels to Hertz :param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise. :returns: a value in Hertz. If an array was passed in, an identical sized array is returned. """ return 700*(10**(mel/2595.0)-1)
c61d0ce485fe5ca241cfca358a51d1aba4bf4462
3,603,930
def row_as_diagonal(a): """ Returns the per row diagonal matrices of the given array. Parameters ---------- a : array_like Array to perform the diagonal matrices computation. Returns ------- ndarray References ---------- :cite:`Castro2014a` Examples ------...
d33be00c44998273bd17ed9b91a54b86d98d29b4
3,603,932
def compute(x, y): """Compute sum of passed in arguments :param x: Integer (operand 1) :param y: Integer (operand 2) :rtype: Integer """ if x > 100 or x < 0 or y > 100 or y < 0: raise ValueError("Passed in value out of bounds") return x + y
beb518f7f9b23f1fa5dc7ac82386a9cbf34a5cd5
3,603,933
def is_weaviate_object_url(url: str) -> bool: """ Checks if the input follows a normal Weaviate 'beacon' like this: 'weaviate://localhost/28f3f61b-b524-45e0-9bbe-2c1550bf73d2' Parameters ---------- input : str The URL to be validated. Returns ------- bool True if 'i...
d9d435e75eec3068aca75db33ee776917fd3bfd2
3,603,934
import requests def response_to_resources(resources_response: requests.Response) -> pd.DataFrame: """ Extracts an API response into an dataframe containing all resources. :param resources_response: a response from the API to the resources request :type resources_response: requests.Response :retur...
2a5b18becd9d1434eebacc9cbd1f563ed08fb655
3,603,935
def config_value(name): """Return callable that returns config value if it exists.""" def get(): try: return config.get('yourls', name) except (NoOptionError, NoSectionError): return None return get
27dedaa666b21636daaf66b0eda59c07d45ba829
3,603,936
from numpy import zeros, sort, array, where def find_ridges(obj, only_min=True, max_guess=600.0, min_guess=1750.0, fast=True): """Finds the ridges of minimal and maximal values within e.g. temperature time series. That is, where the warming changes to a cooling or vice versa. The ridges can then be plot in a...
a8c2128c71b43106a64b5c4d727030e9316e2120
3,603,937
import re def _resolve_operator(statistic: str): """Find the operator corresponding to the statistic.""" statistic = statistic.lower() kwargs = {} # special cases if statistic == 'std': logger.warning( "Changing statistics from specified `std` to `std_dev`, " "sinc...
b83c3bd9daf1c248b00defbc05d9b802db7f1d3a
3,603,938
def crystal_matrix_to_lattice_parameters(crystal_matrix): """ This function takes any strained crystal lattice matrix and return the lattice parameters **Required Inputs crystal_matrix = crystal lattice matrix ([[Vxx,Vxy,Vxz], [Vyx,Vyy,Vyz], ...
b344d54a3177122c13290649777fbd7aa6ed8729
3,603,939
from datetime import datetime def about(): """Renders the about page.""" return render_template( 'about.html', title='About', year=datetime.now().year )
910a8e408caafe5682c4ef869d690fdad381266d
3,603,940
def retrieve_redcap_subjects(url, token, fields, max_time=30): """Read the list of subjects from the REDCap instance using the API""" data = redcap_api_call(url, token, content='record', fields=fields, max_time=max_time) # print("subjects: {}".format(data)) return data
123304e0547c41d522259d8c06f97c75129c29a4
3,603,941
def host_delete_route(host_id): """delete host""" form = ButtonForm() if form.validate_on_submit(): db.session.delete(Host.query.get(host_id)) db.session.commit() return redirect(url_for('storage.host_list_route')) return render_template('button-delete.html', form=form)
f0e031fef11d0933774a11abffdfa2afdd147f44
3,603,943
import json def predict_img_class(img, device_opt): """Get image class determined by network inference running on GPU.""" # Copy input image data to GPU workspace.FeedBlob("data", img, device_option=device_opt) workspace.RunNet("AlexNet", 1) # Fetch results of AlexNet's last layer output -- prob...
64198940da1c8b8cd69d513e05786f4fa38deca2
3,603,944
def get_subject_id(subject_code: str) -> str: """This function gets the subject ID from the database Args: subject_code (str): Subject code from the subject to get the ID. Returns: subject_id (str): Subject ID from the subject. """ query = "select idMaterias from Materias where Mat...
eab6baa9f9d085f8e83fd03c9059043a0630fbd7
3,603,945
def pid_info(output_line): """ Take a line of 'ps -o pid,comm' output and return the PID number and name. The line looks something like: 9108 orterun or 10183 daos_server Need both items. Return a tuple (name, pid) Note: there could be leading spaces on the pid. """ info =...
479c51e562b7bbeb7e812fad4b2cb1f771e2e830
3,603,946
import json def get_search_subawards_ajax(request): """Provide full search subaward data as JSON to improve render time""" query = get_search_filters_query(request, 'subaward') subawards = Subaward.objects.filter(query).distinct() response = {'data': []} for subaward in subawards: ...
f7c40f91b52333671a2a2e698641cba656e0ae70
3,603,948
def reset_model_using_weights(model_wireframe, weights): """A tool to load flattened weights into model wireframe.""" all_boundaries = { 0: [(0, 16), (16, 160)], 1: [(160, 176), (176, 2480)], 2: [(2480, 2496), (2496, 4800)], 3: [], # GlobalAvgPool has no params 4: [(4800, 4810), (4810...
60771eb220a67c04119f86edb36be741cdbece0d
3,603,949
def memory_function(op, is_regularization, num_alive_inputs, num_alive_outputs, reg_inputs, reg_outputs, batch_size=1): """Calculates memory cost or regularization loss for an op. Args: op: A tf.Operation. is_regularization: Boolean indicating whether to calculate regularization l...
9297c83d62dda928dd9eba619a3f509a80ef75d2
3,603,950
def unshift(array, *items): """Insert the given elements at the beginning of `array` and return the modified list. Args: array (list): List to modify. items (mixed): Items to insert. Returns: list: Modified list. Warning: `array` is modified in place. Example:...
d5177e751c3ce8f95b3c51cfe09e99a50d2561c2
3,603,951
import torch from typing import Optional from typing import List from typing import Union def accuracy( tp: torch.LongTensor, fp: torch.LongTensor, fn: torch.LongTensor, tn: torch.LongTensor, reduction: Optional[str] = None, class_weights: Optional[List[float]] = None, zero_division: Union...
3292ba1cf2c344167958b308d5f69c95594b5991
3,603,952
import torch def test_conv2d_memory_analytical(): """Compute the memory of activation analytically""" # arguments and test data N, H, W, CI, CO, kernel_size, stride, padding, dilation, groups = 256, 28, 28, 256, 256, 3, 1, 1, 1, 1 data_np = np.random.randn(N, CI, H, W).astype('float32') weight_np...
b3485db912c7f4d21aae30f7cf1e65ba05d3c379
3,603,953
def update_dimension( response: Response, answer_id: int, request: AnswerRequestSchema, db: Session = Depends(get_database_connection), token: str = Depends(token_bearer) ): """ Update an existing dimension. """ result = VerifyToken(token.credentials).verify() if ...
f378c6f9b97f14c3d51af04e450a967d9aa6ab1e
3,603,955
def load_MACHO_example(): """lightcurve of 2 bands (R, B) from the MACHO survey. The Id of the source is 1.3444.614 Notes ----- The files are gathered from the original FATS project tutorial: https://github.com/isadoranun/tsfeat """ return load_MACHO("lc_1.3444.614")
cd34c640d6909f5b6d49cb033af5054e5871b1a9
3,603,956
def quarter(expr): """ --------------------------------------------------------------------------- Returns calendar quarter of the specified date as an integer, where the January-March quarter is 1. Parameters ---------- expr: object Expression. Returns ------- str_sql SQL expression. """ expr = ...
a9c639ee1fa8a477a03f062473f11efcce769608
3,603,957