content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def async_get_url( hass: HomeAssistant, *, require_ssl: bool = False, require_standard_port: bool = False, allow_internal: bool = True, allow_external: bool = True, allow_cloud: bool = True, allow_ip: bool = True, prefer_external: bool = False, prefer_cloud: bool = False, ) -> st...
1d4e13a8fa5d26bbc9132e85937a24d320136112
12,236
def strip(prefix: Seq, seq: Seq, partial=False, cmp=NOT_GIVEN) -> Iter: """ If seq starts with the same elements as in prefix, remove them from result. Args: prefix: Prefix sequence to possibly removed from seq. seq: Sequence of input elements. partial: ...
8d2a9a62157e3b55adcc976d5c7693cb67513c92
12,238
def _read_unicode_table(instream, separator, startseq, encoding): """Read the Unicode table in a PSF2 file.""" raw_table = instream.read() entries = raw_table.split(separator)[:-1] table = [] for point, entry in enumerate(entries): split = entry.split(startseq) code_points = [_seq.de...
e27e59b57d10cb20dd4ddc832c65cb8802984d44
12,239
from click.testing import CliRunner def runner(): """Provides a command-line test runner.""" return CliRunner()
82b75c8dcaa0105c623a1caea5b459c97e3e18fd
12,240
def matsubara_exponents(coup_strength, bath_broad, bath_freq, beta, N_exp): """ Calculates the exponentials for the correlation function for matsubara terms. (t>=0) Parameters ---------- coup_strength: float The coupling strength parameter. bath_broad: float A parameter cha...
4d6a1691234f12a5cbdec13b2520891c0f30eb77
12,241
def reverse(array): """Return `array` in reverse order. Args: array (list|string): Object to process. Returns: list|string: Reverse of object. Example: >>> reverse([1, 2, 3, 4]) [4, 3, 2, 1] .. versionadded:: 2.2.0 """ # NOTE: Using this method to reverse...
5eb096d043d051d4456e08fae91fb52048686992
12,242
def compute_segregation_profile(gdf, groups=None, distances=None, network=None, decay='linear', function='triangular', precomput...
3598d7c72660860330847758fc744fcd1b1f40ce
12,243
def calculate_lbp_pixel(image, x, y): """Perform the LBP operator on a given pixel. Order and format: 32 | 64 | 128 ----+-----+----- 16 | 0 | 1 ----+-----+----- 8 | 4 | 2 :param image: Input image :type: numpy.ndarray :param x: ...
14f6bd557355a71379b638e52f21d72ccd30a7cb
12,244
def test_gradient_sparse_var(): """ https://www.tensorflow.org/beta/guide/effective_tf2 """ target = tf.constant([[1., 0., 0.], [1., 0., 0.]]) v = tf.Variable([0.5, 0.5]) x = tx.Lambda([], fn=lambda _: tf.SparseTensor([[0, 0], [1, 1]], v, [2, 3]), n_units=3,...
e43a84a052313fecd11eca60a027f00385cd252f
12,245
def get_setup_and_moves(sgf_game, board=None): """Return the initial setup and the following moves from an Sgf_game. Returns a pair (board, plays) board -- boards.Board plays -- list of pairs (colour, move) moves are (row, col), or None for a pass. The board represents the posi...
a933c067baa49d8e6c7309f7762298244a192d2e
12,246
def help_text_metadata(label=None, description=None, example=None): """ Standard interface to help specify the required metadata fields for helptext to work correctly for a model. :param str label: Alternative name for the model. :param str description: Long description of the model. :param exa...
a1fb9c9a9419fe7ce60ed77bc6fadc97ed4523f8
12,247
def conv1d_stack(sequences, filters, activations, name=None): """Convolve a jagged batch of sequences with a stack of filters. This is equivalent to running several `conv1d`s on each `sequences[i]` and reassembling the results as a `Jagged`. The padding is always 'SAME'. Args: sequences: 4-D `Jagged` ten...
33248627280ea0c127d710128790e58e0ca5bb9a
12,248
def dh_mnthOfYear(value, pattern): """ Helper for decoding a single integer value. The value should be >=1000, no conversion, no rounding (used in month of the year) """ return dh_noConv(value, pattern, _formatLimit_MonthOfYear[0])
5dd1027a0713cb93ea6e3504f1a07517f228a037
12,249
import traceback import six def serialize_remote_exception(failure_info): """Prepares exception data to be sent over rpc. Failure_info should be a sys.exc_info() tuple. """ tb = traceback.format_exception(*failure_info) failure = failure_info[1] kwargs = {} if hasattr(failure, 'kwargs'...
549b996afc2b07b9e72f69cd2c6ddaee4010f5af
12,251
def process_polygon(coordinates): """Pass list of co-ordinates to Shapely Polygon function and get polygon object""" return Polygon(coordinates)
fe644dc41e7951a030df511bb7e76b2e74883cae
12,254
def split_function(vector, column, value): """ Split function """ return vector[column] >= value
c6129422fd5bf0b16229e6346adde5f50b203e7b
12,255
def _excitation_operator( # pylint: disable=invalid-name edge_list: np.ndarray, p: int, q: int, h1_pq: float ) -> SparsePauliOp: """Map an excitation operator to a Pauli operator. Args: edge_list: representation of graph specifying neighboring qubits. p: First Fermionic-mode index. q: Se...
0ae0ace12884c507977cf2e555a354c80f83e7ad
12,257
def send_message( message, node, username, password, resource, max_attempts=1 ): """ broadcast this message thru lvalert """ tmpfilename = "tmpfile.json" tmpfile = open(tmpfilename, "w") tmpfile.write( message ) tmpfile.close() cmd = "lvalert_send -a %s -b %s -r %s -n %s -m %d --file %s"%(user...
5ebec2f3487b431a6d1131b11c8ab2d672308b48
12,258
def create_bcs(field_to_subspace, Lx, Ly, solutes, V_boundary, enable_NS, enable_PF, enable_EC, **namespace): """ The boundary conditions are defined in terms of field. """ boundaries = dict(wall=[Wall()]) bcs = dict( wall=dict() ) bcs_pointwise...
d1e72d30404ee68b877c6761a6309884e3054b6c
12,259
def get_response_rows(response, template): """ Take in a list of responses and covert them to SSE.Rows based on the column type specified in template The template should be a list of the form: ["str", "num", "dual", ...] For string values use: "str" For numeric values use: "num" For dual values:...
c3c3e4bf53929895959948836a77893b2f961221
12,260
def stations_within_radius(stations, centre, r): """function that returns a list of all stations (type MonitoringStation) within radius r of a geographic coordinate x.""" close_stations = [] for station in stations: if haversine(station.coord, centre) < float(r): close_stations.appe...
9877020f56f25435d1dad6fae32ebbae0e7cfdaf
12,261
import torch def jacobian(model, x, output_class): """ Compute the output_class'th row of a Jacobian matrix. In other words, compute the gradient wrt to the output_class. :param model: forward pass function. :param x: input tensor. :param output_class: the output_fz class we want to compute t...
07364b8cc58d3ba51431d07e6bf5d164da7ab380
12,264
def render_face_orthographic(mesh, background=None): """ mesh location should be normalized :param mesh: :param background: :return: """ mesh.visual.face_colors = np.array([0.05, 0.1, 0.2, 1]) mesh = pyrender.Mesh.from_trimesh(mesh, smooth=False) # mesh = pyrender.Mesh.from_trimesh(...
21cc7adaaebec7d8114f8192ccdc133075a19bc3
12,265
def check_and_join(phrase, symbols=None, filter=None): """ Joins characters of ``phrase`` and if ``symbols`` is given, raises an error if any character in ``phrase`` is not in ``symbols``. Parameters ========== phrase String or list of strings to be returned as a string. symbols ...
64ddcedf19ecba17b169e4bc3a3c205fe3192eb7
12,266
def drawLaneOnImage(img): """ Find and draw the lane lines on the image `img`. """ left_fit, right_fit, left_fit_m, right_fit_m, _, _, _, _, _ = findLines(img) output = drawLine(img, left_fit, right_fit) return cv2.cvtColor( output, cv2.COLOR_BGR2RGB )
aa42679c7ff8f90b906d8cf74af9207edeadc430
12,268
import numpy def ss(a, axis=0): ### taken from SciPy """Squares each value in the passed array, adds these squares, and returns the result. Parameters ---------- a : array axis : int or None Returns ------- The sum along the given axis for (a*a). """ a, axis = _chk_asarray(a, axis) return numpy.sum(a...
75569fa96fd866f20b57c5f5c52a38e1b9663968
12,270
def Journaling_TypeInfo(): """Journaling_TypeInfo() -> RTTI""" return _DataModel.Journaling_TypeInfo()
24cdb273b6463874e71668a304af3a13305fff24
12,271
def _maven_artifact( group, artifact, version, ownership_tag = None, packaging = None, classifier = None, exclusions = None, neverlink = None, testonly = None, tags = None, flatten_transitive_deps = None, aliases = None): ...
9f97cd8cadfc3ad1365cb6d291634a9362fea4e8
12,272
def get_anchors(n): """Get a list of NumPy arrays, each of them is an anchor node set""" m = int(np.log2(n)) anchor_set_id = [] for i in range(m): anchor_size = int(n / np.exp2(i + 1)) for _ in range(m): anchor_set_id.append(np.random.choice(n, size=anchor_size, replace=False...
4adbaa291740ab3d9cb0a3d6b48c39665d8d5b06
12,274
def diag_gaussian_log_likelihood(z, mu=0.0, logvar=0.0): """Log-likelihood under a Gaussian distribution with diagonal covariance. Returns the log-likelihood for each dimension. One should sum the results for the log-likelihood under the full multidimensional model. Args: z: The value to compute the l...
7265103ddfc5c521fd9612524413cd15e237be9b
12,275
def _filter_option_to_config_setting(flt, setting): """ Encapsulates the logic for associating a filter database option with the filter setting from relay_config :param flt: the filter :param setting: the option deserialized from the database :return: the option as viewed from relay_config """ ...
41694d340285b722daf91fb0badeb1ec33eb0587
12,276
def get_svg(accession, **kwargs): """ Returns a HMM sequence logo in SVG format. Parameters ---------- accession : str Pfam accession for desired HMM. **kwargs : Additional arguments are passed to :class:`LogoPlot`. """ logoplot = plot.LogoPlot(accession, **kwargs) ...
952c6afa4d63f46be579cd70a4e2756b061b9f9b
12,277
def wl_to_en( l ): """ Converts a wavelength, given in nm, to an energy in eV. :param l: The wavelength to convert, in nm. :returns: The corresponding energy in eV. """ a = phys.physical_constants[ 'electron volt-joule relationship' ][ 0 ] # J return phys.Planck* phys.c/( a* l* 1e-9 )
a9d428d7aed3a6c88a1906e026649ee74f700c81
12,278
from typing import Optional def get_local_address_reaching(dest_ip: IPv4Address) -> Optional[IPv4Address]: """Get address of a local interface within same subnet as provided address.""" for iface in netifaces.interfaces(): for addr in netifaces.ifaddresses(iface).get(netifaces.AF_INET, []): ...
ee7061633d72c3b0ac578baf6119e5437395ce17
12,279
def atSendCmdTest(cmd_name: 'str', params: 'list'): """ 发送测试命令,方便调试 ATCore """ func_name = 'atSendCmdTest' atserial.ATraderCmdTest_send(cmd_name, params) res = recv_serial(func_name) atReturnChecker(func_name, res.result) return res.listResult
4cbe127ea7291893d64d8554c5a405c24085320a
12,280
def unlabeled_balls_in_unlabeled_boxes(balls, box_sizes): """ OVERVIEW This function returns a generator that produces all distinct distributions of indistinguishable balls among indistinguishable boxes, with specified box sizes (capacities). This is a generalization of the most common formulation o...
13743a7207f1d4fd2635f35c9eaef0a9acf53fa0
12,281
def get_version(): """Extract current version from __init__.py.""" with open("morphocell/__init__.py", encoding="utf-8") as fid: for line in fid: if line.startswith("__version__"): VERSION = line.strip().split()[-1][1:-1] break return VERSION
69a00c2e5544dfd8d86cdab8be53c17b73764aca
12,282
def get_neighbor_v4_by_id(obj_id): """Return an NeighborV4 by id. Args: obj_id: Id of NeighborV4 """ try: obj = NeighborV4.get_by_pk(id=obj_id) except NeighborV4NotFoundError as e: raise NeighborV4DoesNotExistException(str(e)) return obj
30b00e2fb1f954299a331ce6b198f1e5465122e5
12,283
from typing import Dict def get_resources_json_obj(resource_name: str) -> Dict: """ Get a JSON object of a specified resource. :param resource_name: The name of the resource. :returns: The JSON object (in the form of a dictionary). :raises Exception: An exception is raised if the specified reso...
ce625ecbaad0ec4cea93da78c9c213e37ffef3ed
12,284
def skip_if(predicate, reason=None): """Skip a test if predicate is true.""" reason = reason or predicate.__name__ def decorate(fn): fn_name = fn.__name__ def maybe(*args, **kw): if predicate(): msg = "'%s' skipped: %s" % (fn_name, reason) raise ...
56089515f8cae4f977b1eac96a8de6c6ee59e711
12,285
from pyrap.measures import measures from pyrap.quanta import quantity as q def synthesized_uvw(ants, time, phase_dir, auto_correlations): """ Synthesizes new UVW coordinates based on time according to NRAO CASA convention (same as in fixvis) User should check these UVW coordinates carefully: if ti...
f3261545f85981d353a05acf3176bf0317ea4c86
12,286
from datetime import datetime def execute_pso_strategy(df, options, topology, retrain_params, commission, data_name, s_test, e_test, iters=100, normalization='exponential'): """ Execute particle swarm optimization strategy on data history contained in df :param df: dataframe with historical data :para...
a9a4fffe335ab34ca584a4fe1d3b6116a2a7866c
12,287
def env_get(d, key, default, decoders=decoders, required=None): """ Look up ``key`` in ``d`` and decode it, or return ``default``. """ if required is None: required = isinstance(default, type) try: value = d[key] except KeyError: if required: raise re...
844c6ac9931af97bdc92da6d5014659c3600d50e
12,288
from sympy.functions.elementary.complexes import re, im from .add import Add from re import S def get_integer_part(expr: 'Expr', no: int, options: OPT_DICT, return_ints=False) -> \ tUnion[TMP_RES, tTuple[int, int]]: """ With no = 1, computes ceiling(expr) With no = -1, computes floor(expr) No...
6e00897786581134480a6d7fd16b559760a1a4e7
12,289
def inv_last_roundf(ns): """ ns -> States of nibbles Predict the states of nibbles after passing through the inverse last round of SomeCipher. Refer to `last_roundf()` for more details. """ return inv_shift_row(ns)
12561f9815ecad4cd08909be1e0c77dd61500cce
12,290
def get_screen(name, layer=None): """ :doc: screens Returns the ScreenDisplayable with the given `name` on layer. `name` is first interpreted as a tag name, and then a screen name. If the screen is not showing, returns None. This can also take a list of names, in which case the first screen ...
a6496e453a80f1ad286bbe5201aba92fa922794b
12,291
import random import csv def generate_address_full(chance=None, variation=False, format=1): """ Function to generate the full address of the profile. Args: chance: Integer between 1-100 used for realistic variation. (not required) variation: Boolean value indicating whether variation is requested. (optional)...
364cbe0f033d0500014583c550beb36a6cb6db55
12,292
import urllib def binder_url(repo, branch="master", filepath=None): """ Build a binder url. If filepath is provided, the url will be for the specific file. Parameters ---------- repo: str The repository in the form "username/reponame" branch: str, optional The branch, defa...
f9ac9e28a1cc6b88bce788e63668f1e4a4b45f61
12,293
def _create_group_hub_without_avatar(_khoros_object, _api_url, _payload): """This function creates a group hub with only a JSON payload and no avatar image. .. versionadded:: 2.6.0 :param _khoros_object: The core :py:class:`khoros.Khoros` object :type _khoros_object: class[khoros.Khoros] :param _a...
43222666b5a5f5dcec91a4fa1025278f84275e9c
12,294
def ulstrip(text): """ Strip Unicode extended whitespace from the left side of a string """ return text.lstrip(unicode_extended_whitespace)
191e0654cdab79778c64ec874bbc9b945b0ed4a3
12,295
def clone_dcm_meta(dcm): """ Copy an existing pydicom Dataset as a basis for saving another image :param dcm: the pydicom dataset to be copied :return: """ newdcm = pydi.Dataset() for k, v in dcm.items(): newdcm[k] = v newdcm.file_meta = mk_file_meta() newdcm.is_little_en...
e208ee11241b4194bb0d02357e625d0ee4f52d2e
12,296
import toml import itertools from pathlib import Path def load_plate(toml_path): """\ Parse a TOML-formatted configuration file defining how each well in a particular plate should be interpreted. Below is a list of the keys that are understood in the configuration file: 'xlsx_path' [string]...
cc92a9dae783de915628984979119ca9d2b591a2
12,297
def reduce_entropy(X, axis=-1): """ calculate the entropy over axis and reduce that axis :param X: :param axis: :return: """ return -1 * np.sum(X * np.log(X+1E-12), axis=axis)
68a7d86bf0ad204d989fddceee9e4f75c77a4cb5
12,298
def compile_pbt(lr: float = 5e-3, value_weight: float = 0.5): """ my default: 5e-3 # SAI: 1e-4 # KataGo: per-sample learning rate of 6e-5, except 2e-5 for the first 5mm samples """ input_shape = (N, N, dual_net.get_features_planes()) model = dual_net.build_model(input_shape) opt = keras....
e625915c55a44a8c128431ae220401c451ee69a5
12,299
from typing import List def _hostnames() -> List[str]: """Returns all host names from the ansible inventory.""" return sorted(_ANSIBLE_RUNNER.get_hosts())
8c1ed3f61887ff637d9a9091a20cc3f9e4144dde
12,300
def seabass_to_pandas(path): """SeaBASS to Pandas DataFrame converter Parameters ---------- path : str path to an FCHECKed SeaBASS file Returns ------- pandas.DataFrame """ sb = readSB(path) dataframe = pd.DataFrame.from_dict(sb.data) return dataframe
7988da0adb19e59d7c898658d2fe659b2d145606
12,301
def countVisits(item, value=None): """This function takes a pandas.Series of item tags, and an optional string for a specific tag and returns a numpy.ndarray of the same size as the input, which contains either 1) a running count of unique transitions of item, if no target tag is given, or 2) a running ...
dbb677cc356d867d7f861fe18e2d5c653598d20c
12,302
import numpy as np import torch from pathlib import Path def test_run_inference(ml_runner_with_container: MLRunner, tmp_path: Path) -> None: """ Test that run_inference gets called as expected. """ def _expected_files_exist() -> bool: output_dir = ml_runner_with_container.container.outputs_fol...
dc38c5582f8d69ff53f24c34d403ed3f14f964f9
12,303
def gen_accel_table(table_def): """generate an acceleration table""" table = [] for i in range(1001): table.append(0) for limit_def in table_def: range_start, range_end, limit = limit_def for i in range(range_start, range_end + 1): table[i] = limit return table
53d96db86068d893dfbb216e9e1283535cad9412
12,304
from typing import Tuple import torch def dataset_constructor( config: ml_collections.ConfigDict, ) -> Tuple[ torch.utils.data.Dataset, torch.utils.data.Dataset, torch.utils.data.Dataset ]: """ Create datasets loaders for the chosen datasets :return: Tuple (training_set, validation_set, test_set) ...
175e45640e85df7f76331dc99b60d73fccbbdc43
12,305
def get_metrics(actual_classes, pred_classes): """ Function to calculate performance metrics for the classifier For each class, the following is calculated TP: True positives = samples that were correctly put into the class TN: True negatives = samples that were correctly not put into the class ...
925d80d146ca29984886324338b9f99688c721b8
12,309
import dateutil def extract_tika_meta(meta): """Extracts and normalizes metadata from Apache Tika. Returns a dict with the following keys set: - content-type - author - date-created - date-modified - original-tika-meta The dates are encoded in the ISO format.""" ...
d5e73afa3b7747d31f295acb840c3730a3e60ed1
12,310
def __gen_pause_flow(testbed_config, src_port_id, flow_name, pause_prio_list, flow_dur_sec): """ Generate the configuration for a PFC pause storm Args: testbed_config (obj): L2/L3 config of a T0 testbed src_...
953a6d3a3741b6af0b06bd8165abd7350b838b41
12,311
def parse_str_to_bio(str, dia_act): """ parse str to BIO format """ intent = parse_intent(dia_act) w_arr, bio_arr = parse_slots(str, dia_act) bio_arr[-1] = intent return ' '.join(w_arr), ' '.join(bio_arr), intent
951cd110acd5fa53def9e781c0ab9b545d2931b8
12,312
def train_early_stop( update_fn, validation_fn, optimizer, state, max_epochs=1e4, **early_stop_args ): """Run update_fn until given validation metric validation_fn increases. """ logger = Logger() check_early_stop = mask_scheduler(**early_stop_args) for epoch in jnp.arange(max_epochs): (...
a9dc6e76d2796edacc0f55b06e9cf258a90dffea
12,313
from typing import List def get_povm_object_names() -> List[str]: """Return the list of valid povm-related object names. Returns ------- List[str] the list of valid povm-related object names. """ names = ["pure_state_vectors", "matrices", "vectors", "povm"] return names
cb80899b9b3a4aca4bfa1388c6ec9c61c59978a4
12,314
def choose(a,b): """ n Choose r function """ a = op.abs(round(a)) b = op.abs(round(b)) if(b > a): a, b = b, a return factorial(a) / (factorial(b) * factorial(a-b))
30b70dc950e9f6d501cf5ef07bfed682dce41c43
12,315
from typing import List import torch from typing import Optional def pad_and_stack_list_of_tensors(lst_embeddings: List[torch.Tensor], max_sequence_length: Optional[int] = None, return_sequence_length: bool = False): """ it takes the list of embeddings as the input, then appl...
78c3a11f7ff79798d9b86703318eabb8da32695a
12,316
from typing import List def bq_solid_for_queries(sql_queries): """ Executes BigQuery SQL queries. Expects a BQ client to be provisioned in resources as context.resources.bigquery. """ sql_queries = check.list_param(sql_queries, 'sql queries', of_type=str) @solid( input_defs=[InputDe...
0b7d71d6ec6aca87a581c8e0876bc1d88e7242c8
12,317
def mock_accession_unreplicated( mocker: MockerFixture, mock_accession_gc_backend, mock_metadata, lab: str, award: str, ) -> Accession: """ Mocked accession instance with dummy __init__ that doesn't do anything and pre-baked assembly property. @properties must be patched before instantia...
c221c34a72809737d22b76beff89a18eece128ff
12,318
from typing import Optional def get_prepared_statement(statement_name: Optional[str] = None, work_group: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPreparedStatementResult: """ Resource schema for AWS::Athena::Prepare...
e3bcd74b2bc9093a0fff822a4f35b0de4dab3e03
12,319
def handle_col(element, box, _get_image_from_uri, _base_url): """Handle the ``span`` attribute.""" if isinstance(box, boxes.TableColumnBox): integer_attribute(element, box, 'span') if box.span > 1: # Generate multiple boxes # http://lists.w3.org/Archives/Public/www-style/...
ef9fe04982bbb278df1453104823235ecf23113f
12,320
def get_dotted_field(input_dict: dict, accessor_string: str) -> dict: """Gets data from a dictionary using a dotted accessor-string. Parameters ---------- input_dict : dict A nested dictionary. accessor_string : str The value in the nested dict. Returns ------- dict ...
2c82c0512384810e77a5fb53c73f67d2055dc98e
12,321
import re def separa_frases(sentenca): """[A funcao recebe uma sentenca e devolve uma lista das frases dentro da sentenca] Arguments: sentenca {[str]} -- [recebe uma frase] Returns: [lista] -- [lista das frases contidas na sentença] """ return re.split(r'[,:;]+', sentenca)
d3ac427172e34054119659adc55295ac27965e6c
12,322
import pathlib import json import importlib def read_datasets(path=None, filename="datasets.json"): """Read the serialized (JSON) dataset list """ if path is None: path = _MODULE_DIR else: path = pathlib.Path(path) with open(path / filename, 'r') as fr: ds = json.load(fr) ...
ade3b9169d0f1db45d3358f27a54ea634f6d883e
12,323
def as_actor(input, actor) : """Takes input and actor, and returns [as <$actor>]$input[endas].""" if " " in actor : repla = "<%s>"%actor else : repla = actor return "[as %s]%s[endas]" % (repla, input)
dc9bd33bd6b2156f4fa353db2a0b01bfa6dd1357
12,324
def error_403(request): """View rendered when encountering a 403 error.""" return error_view(request, 403, _("Forbidden"), _("You are not allowed to acces to the resource %(res)s.") % {"res": request.path})
1e104b006100f296ab8f816abae8272b35c9399b
12,325
def _format_param(name, optimizer, param): """Return correctly formatted lr/momentum for each param group.""" if isinstance(param, (list, tuple)): if len(param) != len(optimizer.param_groups): raise ValueError("expected {} values for {}, got {}".format( len(optimizer.param_gr...
52904bdfb1cba7fe3175606bf77f5e46b3c7df80
12,326
def as_binary_vector(labels, num_classes): """ Construct binary label vector given a list of label indices. Args: labels (list): The input label list. num_classes (int): Number of classes of the label vector. Returns: labels (numpy array): the resulting binary vector. """ ...
176a1148d90dcd336ea29ac13b73cc7a6c0cdc60
12,327
def evaluation_lda(model, data, dictionary, corpus): """ Compute coherence score and perplexity. params: model: lda model data: list of lists (tokenized) dictionary corpus returns: coherence score, perplexity score """ coherence_model_lda = CoherenceModel(model=model, texts=data, di...
c38e3ed3728b9a598ec0cf36c07d606daeb8f388
12,328
def get_map_with_square(map_info, square): """ build string of the map with its top left bigger square without obstacle full """ map_string = "" x_indices = list(range(square["x"], square["x"] + square["size"])) y_indices = list(range(square["y"], square["y"] + square["size"])) M = map_i...
20d405edd8e5e86e943c297455ebfbeb54b669f8
12,329
def bgr_colormap(): """ In cdict, the first column is interpolated between 0.0 & 1.0 - this indicates the value to be plotted the second column specifies how interpolation should be done from below the third column specifies how interpolation should be done from above if the second column does not equal the t...
ffeb0d415c237a5f8cc180e86bb08d73e443b133
12,330
def autovalidation_from_docstring(): """ Test validation using JsonSchema The default payload is invalid, try it, then change the age to a valid integer and try again --- tags: - officer parameters: - name: body in: body required: true schema: i...
82cb9d043666b465226712e6b12be94291ac5792
12,331
import requests def get_vlan_groups(url, headers): """ Get dictionary of existing vlan groups """ vlan_groups = [] api_url = f"{url}/api/ipam/vlan-groups/" response = requests.request("GET", api_url, headers=headers) all_vlan_groups = response.json()["results"] for vlan_group in all_vl...
c0494708e4d2cb5b61a8e4c7ac4136051b1903c7
12,332
def getLastReading(session: Session) -> Reading: """ Finds the last reading associated with the session NB: Always returns a Reading, because every Session has at least 1 Reading Args: session (Session): A Session object representing the session record in the database Returns: date...
87f9e86316bf3975077797832225bbe9b027e648
12,333
def process_outlier(data, population_set): """ Parameters ---------- data population_set Returns ------- """ content = list() for date in set(map(lambda x: x['date'], data)): tmp_item = { "date": date, "value": list() } for val...
e793aa85bf6b14406d495775a89d37a68ae6bf8b
12,334
import six def valid_http(http_success=HTTPOk, # type: Union[Type[HTTPSuccessful], Type[HTTPRedirection]] http_kwargs=None, # type: Optional[ParamsType] detail="", # type: Optional[Str] content=None, # typ...
6c88712cd501291fe126b87086ee29700f44832b
12,335
def operating_cf(cf_df): """Checks if the latest reported OCF (Cashflow) is positive. Explanation of OCF: https://www.investopedia.com/terms/o/operatingcashflow.asp cf_df = Cashflow Statement of the specified company """ cf = cf_df.iloc[cf_df.index.get_loc("Total Cash From Operating Activities"...
ed6a849fa504b79cd65c656d9a1318aaaeed52bf
12,336
from io import StringIO def generate_performance_scores(query_dataset, target_variable, candidate_datasets, params): """Generates all the performance scores. """ performance_scores = list() # params algorithm = params['regression_algorithm'] cluster_execution = params['cluster'] hdfs_add...
b8cb09973f17aab2c16515a026747c3e006bfd35
12,337
import cmath import math def correct_sparameters_twelve_term(sparameters_complex,twelve_term_correction,reciprocal=True): """Applies the twelve term correction to sparameters and returns a new sparameter list. The sparameters should be a list of [frequency, S11, S21, S12, S22] where S terms are complex number...
e957c8eebd905b93b45e79a7349c1fca895c5430
12,338
def api_activity_logs(request): """Test utility.""" auth = get_auth(request) obj = ActivityLogs(auth=auth) check_apiobj(authobj=auth, apiobj=obj) return obj
7b13f382e71971b6ed93154a591a27f95fd81a2c
12,339
def RNAshapes_parser(lines=None,order=True): """ Returns a list containing tuples of (sequence,pairs object,energy) for every sequence [[Seq,Pairs,Ene],[Seq,Pairs,Ene],...] Structures will be ordered by the structure energy by default, of ordered isnt desired set order to False """ resu...
3c45a4f6efb190cb26512dea4a55c44292191e0f
12,340
from typing import Callable from typing import Optional from typing import Union from typing import Dict from typing import Any def get_case_strategy( # pylint: disable=too-many-locals draw: Callable, operation: APIOperation, hooks: Optional[HookDispatcher] = None, data_generation_method: DataGenerat...
d46fde928b0ceaa3886904e35876c245e7fcb245
12,341
def type_from_value(value, visitor=None, node=None): """Given a Value from resolving an annotation, return the type.""" ctx = _Context(visitor, node) return _type_from_value(value, ctx)
92568581d8f7b47ac469d0575f549acb1b67c857
12,342
def _accesslen(data) -> int: """This was inspired by the `default_collate` function. https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/ """ if isinstance(data, (tuple, list)): item = data[0] if not isinstance(item, (float, int, str)): return len(item) ...
df709ee8a97c920a1413c9d7240f83d0406577a6
12,343
def createSkill(request, volunteer_id): """ Method to create skills and interests :param request: :param volunteer_id: :return: """ if request.method == 'POST': volunteer = Volunteer_User_Add_Ons.objects.get(pk=volunteer_id) skills = request.POST.getlist('skills') in...
f612ef94b02664526018fd2ea948a36587cb15bf
12,344
def analyticJacobian(robot : object, dq = 0.001, symbolic = False): """Using Homogeneous Transformation Matrices, this function computes Analytic Jacobian Matrix of a serial robot given joints positions in radians. Serial robot's kinematic parameters have to be set before using this function Args: robot (Seria...
a906148f26fea9bb9d833ac95dffde87a704e372
12,345
def test_sharedmethod_reuse_on_subclasses(): """ Regression test for an issue where sharedmethod would bind to one class for all time, causing the same method not to work properly on other subclasses of that class. It has the same problem when the same sharedmethod is called on different instan...
829ad4fafb32cb18d8da7b8144be25746f892ce5
12,346
def triu_indices_from(arr, k=0): """ Returns the indices for the upper-triangle of `arr`. Args: arr (Union[Tensor, list, tuple]): 2-dimensional array. k (int, optional): Diagonal offset, default is 0. Returns: triu_indices_from, tuple of 2 tensor, shape(N) Indices for t...
b95a7ed3fac1810bdfe9659471cbcd2d14fc8c99
12,348
def func(var): """Function""" return var + 1
a6ca4247f7f7307c384708ed9535046e4ec7d4e3
12,350