content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compute_condition(t, dt): """ Inputs are normalized times. `t` is the position of one dirac and `dt` is the distance between the two diracs. """ u0 = np.exp(-1j*2*np.pi*t) u1 = u0*np.exp(-1j*2*np.pi*dt) # eigenvalues from quadratic formula a = 1 b = -1*(1+u1) c = -1*(u...
e4a14f9c9c941f6a90acb96e755c2651508b13c9
42,717
def dot_general(lhs: np.ndarray, rhs: np.ndarray, contracting_dims: Axes, batch_dims: Axes, precision=None) -> np.ndarray: """`jax.lax.dot_general` with preserved dims order and shared lhs / rhs dims. Precisely, returns `jax.lax.dot_general(lhs, rhs, ...
5670783fe82d40fedc0a762f13d6b5acc0fd1ca7
42,718
def read_current_user_shops( current_user: usermodels.User = Depends(get_current_active_user), ): """ Retrieve a list of shops assigned to the currently logged in user. """ return current_user.shops
27d78ec27afac7e882006be09e58d66e3e6834c9
42,719
def check_sim_params(params={}): """ Checks simulation parameter dictionary for various keywords and sets to default values if not present Parameters ---------- params: dict, optional dictionary containing initial key/value pairs for simulation of catalog Returns ------- pa...
9028ef9de53c1155a6c9e1c4325954c1c418e47d
42,720
def points_on_circle(radius, points): """ returns a set of uniform points around a circle :param radius: radius of the circle :param points: number of points on the circle :return: """ angle = np.linspace(0, 2*np.pi, points) x_coord = np.cos(angle)*radius y_coord = np.sin(angle)*radi...
d5ccc7cd7bd50f7668194f8841aebd68fad046c3
42,721
import torch import tqdm def validate(data_loader): """ :return: validation accuracy, validation loss """ num_iteration = 0 deep_punctuation.eval() correct = 0 total = 0 val_loss = 0 with torch.no_grad(): for x, y, att, y_mask in tqdm(data_loader, desc='eval'): ...
f1b545df7d5b8bdfadb72915a285cf3806ce51e8
42,722
import time import random def show_secret(item): """ Show a secret for X seconds and erase it from the screen """ try: print("* The password will be hidden after %s seconds." % (global_scope['conf'].hideSecretTTL)) print('* The password is: %s' % (item.password), end...
027c422aa4dcd6a3ed4c94d1ee43079caaaf47b7
42,723
def analyze_data(fitsfn, observables_dir="", affine2d=None, psf_offset_find_rotation = (0.0,0.0), psf_offset_ff = None, rotsearch_d=None, set_pistons=None): """ returns: affine2d (measured or input), ...
c3fa54d252bc57a3bdf315e5918fe050285de1dd
42,724
def value_at_offset(obj_node, offset, dst_type): """ Perform (dst_type) (((char *) my_object) + offset) """ offset = ConstNode(offset, Py_ssize_t) pointer = PointerFromObject(obj_node) pointer = CoercionNode(pointer, char.pointer()) pointer = pointer_add(pointer, offset) value_at_offset ...
7d3d60a087efb9c3f0db3f72a9f2630263702413
42,725
def step_id(value): """return the test id from the test step object""" return f"{value.comment} {value.user_input}"
843d2ff24b86da8382c75f709a0fe18e8e897d0c
42,726
def _attributes_equal(new_attributes, old_attributes): """ Compare attributes (dict) by value to determine if a state is changed :param new_attributes: dict containing attributes :param old_attributes: dict containing attributes :return bool: result of the comparison between new_attributes and ...
11c92f000f1811254db48a8def3e681a09e8a9a9
42,727
from datetime import datetime from pathlib import Path import numpy import math def get_pass_times( start_time: datetime, end_time: datetime, pass_times_filename: PathLike = PASS_TIMES_FILENAME, ): """ Retreive array of datetimes of VIIRS passes within the given time interval, given initial period...
b1757ad1e8e5ba6f4f1dfb95135bb7ae30346046
42,728
def _recover_bin_edges(wave): """Recover the edges of a set of wavelength bins given the bin centers. This function is designed to work for standard linear binning along with other more exotic forms of binning such as logarithmic bins. We do a second order correction to try to get the bin widths as acc...
70bb5f10f3b6f47422aac16688f57e061cdd5eb7
42,731
def structured(inputSchema, outputSchema, schema_store=None, ignore_body=False): """ Decorate a Klein-style endpoint method so that the request body is automatically decoded and the response body is automatically encoded. Items in the object encoded in the request body will be passed to ...
99fb4581714fb7446988b876529faf918f56f744
42,732
def reweight_distribution(original_distribution, temperature = 0.5): """ :param original_distribution: 概率值组成的一维 Numpy 数组,数据之和等于1 :param temperature: 用于定量描述输出分布的熵的因子 :return: 将加权生的分布归一化,保证数组之和为1 """ distribution = np.exp(np.log(original_distribution) / temperature) return distribution / np.s...
c8040db76dc0768f2cc80d270bc541796abd3a75
42,733
import functools def resnet152_dropout(pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ block = functools.partial(DropoutBottleneck, dropout=args.dropout, ...
3064ae34636d8de6baf4638a8c66d75e5aa68cfc
42,734
from typing import List from pathlib import Path import glob async def yolov5_weights() -> List[str]: """ Get available weights options for model. Returns: List[str] of all YOLOv5 model weights files currently available to use. """ return [Path(f).as_posix().rsplit('/', maxsplit=1)[-1].sp...
f2cf44f0caa922c4971b1a39a8bd80fe813e1be1
42,735
import torch def load_celeba(input_size=224, num_workers=2, trainsize=10000, testsize=1000, batch_size=32, transform_type='normalize'): """Load CelebA dataset""" if transform_type == 'normalize': transform = transforms.Compose([ transforms.RandomResizedCrop(input_size), transf...
f2fe03cf4b713926cc048231165f534e12e3df92
42,736
def pass_if(expression, exc_type, exc_val=_const.CHAR_EMPTY): """ Raises an error of type *err_type* when *expression* is **falsy** and silently passes otherwise. Opposite of :func:`raise_if`. :param expression: An expression or value to evaluate. :param exc_type: The error to raise when *expre...
72035e25227e918f73934cdee64b208b4734031b
42,737
import re def parse_min_max_info(requirements_string): """ Get min max info from a requirements string. """ assert "MAXNUM" in requirements_string, "missing MAXNUM" assert "MINNUM" in requirements_string, "missing MINNUM" min_num_search = re.search( r"MINNUM(\d+)", requirements...
430812339720dfa735efc77510a148b8f40deac8
42,738
from typing import Iterable def dfs_iterative(graph: Graph, strategy: DFSStrategy, roots: Iterable[Vertex]) -> Iterable[Vertex]: """Iterative depth-first search algorithm. :param graph: a graph :param strategy: a searching strategy :param roots: starting vertices :return: iterable object of visit...
33019b0d635bcca78a8fc43f7762c3b7327f3717
42,739
def make_my_v1_running_example_dataset(num_items_per_dataset = 10, num_labels_per_item=10, minimal=False, include_hard_classifier=False, include_soft_classifier=False)->SyntheticDataset: """ Four states: stronghigh = 90/10, weakhigh = 70/30, weaklow = 30/70; stronglow = 10/90 ...
24febbdec522522a9973bee8a9bb3f800c9fe90a
42,742
def get_3d_bbox(actor_, camera_actor): """Get the 8 point coordinates of the actor in the camera view.""" # 1. get the 8 vertices of the actor box vertices = np.zeros((8, 4), dtype="float") extent = actor_.bounding_box.extent # x, y, z extension from the center vertices[0, :] = np.array([extent.x, extent.y, ...
445759300b633635c78674c2f55fe2d130ed32ef
42,743
def smt_curve(sig_df, window = 49, order = 1, PLOT = False): """ smoothe a noisy signal curve using multi-step savgol_filter Parameters ---------- sig_df : Pandas.Series the sigal to be smoothed window : int, optional maximum window size. The default is 49. order: int, optio...
b0870404a28b694a34aa02383b84abbb67f15fd6
42,745
def backpropagation(network, x, y): """ Calculate delta values of a network for array inputs x and outputs y. Return gradw and gradb of the cost function as lists of matrices for each layer. """ # Initialize lists to store gradwJ(W,b,x,y) = d(l+1)*a(l)t and gradbJ(W,b,x,y) = d(l+1) with each item in lis...
484ddcb0b3db03cd5445a7bc95da2a3de7d6b626
42,746
def vms_list(request): """Show the list of VMs""" liste = [] for server in Server.objects.filter(is_proxmox=True).exclude(proxmox_node_name='').all(): retour = gimme_prox_cox(server.ip_for_proxmox()).getNodeContainerIndex(server.proxmox_node_name) vm_list = [] vm_servers_linked = ...
af599ccabb849f477d556f0e1ea23d44a73bdf26
42,747
def load_school_collections() -> pd.DataFrame: """Load monthly tax collections for the School District.""" # Get the path to the files to load dirname = SchoolTaxCollections.get_data_directory("processed") files = dirname.glob("*-tax.csv") return _load_monthly_collections(files, total_only=True)
156b4652942cdf7130afbfad6a3eab9833a93da1
42,749
def get_curve(name): """Node Groupに作成したCurve Nodeを返す""" node_name = "MRGPEN_NODE_{}".format(name) node_groups = bpy.data.node_groups nodes = None if node_name in node_groups: nodes = node_groups[node_name].nodes else: nodes = node_groups.new( name=node_name, ...
bffe7caffd413b6f2bbe81b9fcba3c116988a04f
42,750
def parse_read(read): """parse bioseq to fastq.""" # dele = "-" dele = "" # check if there is MD tag # check whether query sequence is exist if not read.has_tag("MD") or (query_seq := read.query_sequence) is None: return None query_qual = read.query_qualities # init matched r...
2033481f6081e98d19c1e8d1f26b5c3b3f339b13
42,751
from datetime import datetime def update_policy(data, policy_id): """ Args: data: Dictionary with data to be updated policy_id: Policy's ID Returns: Update operation status wrapped on dictionary """ class UpdatePolicyError(Exception): pass try: policy_obj =...
d3ae44fda1bf27ecdfb97c6e18a11cee43e69f5f
42,752
def apply_bg_correction(mean_values, params): """ this function won't work with float16 in practice. limits use to float32 """ if not isinstance(params, BackgroundCorrectionParams): raise ValueError('params is not a BackgroundCorrectionParams instance') bg_mean = params.bg_mean bg_mad = params....
0aad31a0ed8be0298fc7cb0f11bd072d1fadf852
42,753
def run_state_evolution(x_ids, model, **algo_kwargs): """ Run state evolution for a given model. Parameters ---------- - x_ids : ids of the variables to infer (signals) - model : model that can be used in StateEvolution Returns ------- - records : list of x_id, v, n_iter """ ...
69e0f20acd6238a21fbd91bcfe1231a512edca9d
42,755
def open(self): """获取开盘价序列""" return self.openArray[-self.size:]
a254b5a389c9b450a685926083b849584ae2a6f9
42,756
def match_candidates_by_order(images, exifs, max_neighbors): """Find candidate matching pairs by sequence order.""" if max_neighbors <= 0: return set() n = (max_neighbors + 1) / 2 pairs = set() for i, image in enumerate(images): a = max(0, i - n) b = min(len(images), i + n) ...
75451de154e0ad2e2013ed63c5e6b3eadac5dc71
42,757
def meshTensor(value): """**meshTensor** takes a list of numbers and tuples that have the form:: mT = [ float, (cellSize, numCell), (cellSize, numCell, factor) ] For example, a time domain mesh code needs many time steps at one time:: [(1e-5, 30), (1e-4, 30), 1e-3] Means take 30 ...
7f23eadaf5b38c691cba40f47c9c15c2a4b886d4
42,758
import re def attr(*args, **kwargs): """Decorator wrapper for the nose 'attrib' attr decorator. This attr decorator recognizes the 'user' attribute when assigned and calls the `credentials_for` method of the TestTypePad class to apply the appropriate OAuth credentials. This wrapper also atte...
ee40f9349cd8dfee3537263aeaf526c408083394
42,759
def itrs2horizon(station,ts,ts_quasi_mjd,positions,coord_type): """ Convert cartesian coordinates of targets in ITRF to spherical coordinates in topocentric reference frame for a specific station. Usage: az,alt,r = itrs2horizon(station,ts,ts_quasi_mjd,positions,coord_type) Inputs: station ...
9e38ed0f4101c056ebaff618ed70b97f1f572347
42,761
from coldtype.pens.draftingpen import DraftingPen def ease(style, x): """ Though available as a general-purpose function, this logic is usually accessed through something like the `.progress` function on an animation or timeable. Return two values — the first is the easing result at a given time x; the s...
42409e8153a896cc3f83ab971fd11350a6c5cfd8
42,763
def getAllBlogs(con=None, cur=None, db=None): """ gets all blog details Returns: - rows: all blogs as list - [] : if no blogs are present in db """ sql = "SELECT * FROM blogs ORDER BY id ASC" rows = [] db(sql, ( )) rows = cur.fetchall() return rows or []
642db526bc9b96fe4b8ab58c552daee51584314e
42,764
def advanced_search(post_query): """ Perform advanced search using OFF search engine """ post_query['json'] = '1' url = utils.build_url(service='cgi', resource_type='search.pl', parameters=post_query) return utils.fetch(url, json_file=False)
d714af13eb72d948bd8a9a1ed6390db17a138955
42,765
def generate_percentiles(results, percentiles=DEFAULT_PERCENTILES): """Percentage distribution of the results. I.e. At what point had 50%, 75% and 90% of results completed? """ data = [] total = len(results) cur_index = 0 if not results: return data for percentile in percentil...
9bcfc51d6779c471adc8ae8590b892be80c6e9cb
42,767
def get_policy(name: str) -> Policy: """Returns the Policy with the given name, None if there is none""" return _registry.get(name)
b58a0146f40a7fe3b85c262ad20484eef6f00c23
42,768
from typing import Any def build_patch200_succeeded_ignore_headers_request( *, json: Any = None, content: Any = None, **kwargs: Any ) -> HttpRequest: """Long running put request, service returns a 200 to the initial request with location header. We should not have any subsequent calls after receiving this...
abfc1e80d833cd1ca270c09d1b43cb5f30bb1d6a
42,769
from datetime import datetime def htmlpage(): """For testing: Example HTML page, if you want to use templates.""" # just some data for the template clock = datetime.datetime.now() return render_template('example.html', clock=clock)
216622f59acc4c5053651070fee4deb6202e70c5
42,770
import math def test_fallback_abs_float(): """ Feature: JIT Fallback Description: Test abs(float) in graph mode Expectation: No exception """ @ms_function def foo(): x = -1.0 return abs(x) assert math.isclose(foo(), 1.0, abs_tol=1e-5)
996253f3b6090422e1c4340f8607053a0dfbc788
42,771
def sensAnalysis(locator, extraCosts, extraCO2, extraPrim, solarFeat, ntwFeat, gen): """ :param locator: path to input locator :param extraCosts: costs calculated before optimization of specific energy services (process heat and electricity) :param extraCO2: green house gas emissions calculated bef...
11da0be9d25aac235014c4fbd26ac8a9568093d7
42,772
import requests def account_addresses_assets(self, stake_address: str, **kwargs): """ Obtain information about assets associated with addresses of a specific account. Be careful, as an account could be part of a mangled address and does not necessarily mean the addresses are owned by user as the account....
b6b0e276f49c2df90bdd25c61d560a669e93d929
42,773
import logging def _get_logger(logger_name): """根据名称获取日志器""" __ = logging.getLogger(logger_name) _ = LogProxy(__) loggers.append(_) return _
17b0dc2e8d5fadeb9a3936d6fbf02f20293cc861
42,774
from datetime import datetime def detect_resolution(d1: datetime, d2: datetime) -> int: """ Detects the time difference in milliseconds between two datetimes in ms :param d1: :param d2: :return: time difference in milliseconds """ delta = d1 - d2 return int(delta.total_seconds() * 1e3)
a5300254b9f2d84d8111fcb3ad9f222ce6b5a9a6
42,775
import typing import re import html def parse_image_spec(path: str) -> typing.Tuple[str, utils.ArgDict, typing.Optional[str]]: """ Parses out a Publ-Markdown image spec into a tuple of path, args, title """ title: typing.Optional[str] = None # Parse out the title.. match = re.match(r'(.+)\s+\"(.*)\"...
86374f0ae6dc489d4fd35ad70354e3012a0dd52e
42,776
from typing import List from typing import Optional from datetime import datetime def create_indicates_relationships( created_by: Identity, sources: List[_DomainObject], targets: List[_DomainObject], confidence: int, object_markings: List[MarkingDefinition], start_time: Optional[datetime] = No...
8e59a256c5b60373dac17b3177b59d3f20fd8917
42,777
def preprocess_doc(doc: str): """ Preprocessing of the string Args: doc str: document as string, e.g span Returns: []: tokenized and processed str """ return simple_preprocess(doc, deacc=True)
30f9e1f1242510e05e3165a4e1a888e3b93237d1
42,778
def _transform_datasets(metadata: dict) -> pd.DataFrame: """Transform datasets metadata into a formatted DataFrame.""" df = pd.DataFrame.from_dict(metadata.get("dataSets")) df = df[ [ "id", "code", "shortName", "name", "periodType", ...
11fe69ec4dcf093f1400f192795a0c9320224492
42,779
import json def read(socket, freq_start, freq_end, rbw, video, atten, with_data): """Return list of satis data.""" socket.send(get_string({ Key.Request: 5, Key.Start: freq_start, Key.End: freq_end, Rbw.name: rbw, Key.Video: video, Attenuation.name: atten, Mode.name: M...
6560e6347b029aadf789eaad08b02a950d473ab3
42,781
def request_issues_by_sprint(cfg): """Request all issues associated with given sprint""" issues = [] sprint_issues_url = cjm.request.make_cj_agile_url( cfg, "sprint/{0:d}/issue".format(cfg["sprint"]["id"])) start_at = 0 max_results = 50 while True: response = cjm.request.make_...
115805a74d593f08e1b0257b1508f49b9cdd00e2
42,782
def SimulateIntervals(daily, iters=101, func=RunLinearModel): """Run simulations based on different subsets of the data. daily: DataFrame of daily prices iters: number of simulations func: function that fits a model to the data returns: list of result objects """ result_seq = [] starts...
95ec7cf9bb2a88b8d0b5d8d0e2bb8900390da54d
42,784
from re import T def sheva_nah_after_short_vowel(last_vowel, guess): """`sheva` after short vowel is `sheva-nah` Source: [Simanim] 3.5 > According to the opinion of the _Minchat Shai_, after a short vowel it > is a `sheva-nah` even when there is a `meteg` near the short vowel. Source: [HaMillon]...
dfb895fd1e5add1925b9804117028f5ae2851530
42,785
def min(col: ColumnExpr) -> ColumnExpr: # pylint: disable=redefined-builtin """SQL ``MIN`` function (aggregation) :param col: the column to find min .. note:: * this function can infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition...
a3098e470748cf1dc69fafc025f019824db8e3ef
42,786
def trigger_build(project_name, branch_name): """ This task runs our CircleCI builds. If you look at our "celeryconfig.py" file you would see that we have CircleCI builds that are scheduled for every 15 minutes, etc. This basically is responsible for building all of our projects and uploading th...
951a67fa3d9dc123fc7ead5b730665b2c639db0c
42,787
def total_distance(solution, distanceMap): """ Calculate the total distance among a solution of cities. Uses a dictionary to get lookup the each pairwise distance. :param solution: A list of cities in random order. :distanceMap: The dictionary lookup tool. :return: The total distance between all...
b478c09540fb93d210df895a9ed31939bf889121
42,788
def get_design_condition(lineIn): """ """ key = {"hydrotest": r"\b(hydro(test)?)\b", "operating": r"\b(op(erating)?)\b", "ultimate": r"\b((ultimate|user))\b"} keyWord, lineOut, _match = search_line(lineIn, key) return keyWord
9a9399996e4f0164f4ee010a752d9a3efb4f0406
42,789
def get_tite_box(box_in, px_coord=[100, 0]): """ Get tight box, px_coord for determine left right border """ BORDER = 0 mid_xp = 0 if px_coord[0] < px_coord[1]: BORDER = 1 mid_xp = (px_coord[1]+px_coord[0])/2 out_boxes = [] ycord, xcord, _ = np.where(box_in == 1) ...
75e0921b9285c909b0e7e903130af600eaedff7e
42,790
import struct def py_float2float(val, be=False): """ Converts Python float to 4 bytes (double) """ sig = '>f' if be else '<f' return struct.pack(sig, val)
e828bdedc1bca3536d6c6b5c90bf0cb4bf958066
42,791
def arg_name(name): """Convert snake case argument name to a command line name. :param str name: The argument parameter name. :returns: str """ return "--" + name.replace('_', '-')
e66284c3a99fe9a75799d4123ad23322089ec2ee
42,794
def stack_str(offset=0, fmt=None, sep=None): """ It creates a string representing calling stack from where this function is called. Args: offset: remove the lowest `offset` frames. Because usually one does not need the frame of the `k3log.stack_str` line. ...
a7fd63d2ae8ad3a61138bf760b3e0e51e08540b0
42,795
def get_latest_model_version(city: str) -> int: """Returns the version number of the latest model belonging to the passed city. Parameters ---------- city: str Name of the city. Returns ------- latest_version: int Latest model version. """ trained_model_query = ( ...
6e5bb6aa62f7012cabc69874bcf5334dedde6be4
42,796
def delete_event(request, event_id): """Event deletion view. Delete the event specified by the event ID and redirect the user to the events list. Arguments: request - Django object containing request information. event_id (int) - ID of Event to delete. Returns: redirect - Django funct...
bfcd59644b652bc4c4734d8c58609a9636f5505a
42,797
def single_window( landsat_band_10: np.ndarray, landsat_band_4: np.ndarray, landsat_band_5: np.ndarray, lst_method: str = "mono-window", emissivity_method: str = "avdan", unit: str = "kelvin", ) -> np.ndarray: """Provides an interface to compute land surface temperature from landsat ...
d24c0640a3488ed8fe370c3517ddc4f7a182f5e2
42,798
import numpy def get_cosine(vec1, vec2): """Get cosine for two given vectors""" OPS = get_current_ops() v1 = OPS.to_numpy(OPS.asarray(vec1)) v2 = OPS.to_numpy(OPS.asarray(vec2)) return numpy.dot(v1, v2) / (numpy.linalg.norm(v1) * numpy.linalg.norm(v2))
cc723051d5168ba05ffcdfb97007539fe4f76b07
42,799
def hdu_records(hdu_list: fits.BinTableHDU) -> fits.FITS_rec: """ Generator function to yield each record in hdu_list :param hdu_list: HDUList object (containing data) :return: List of HDU records """ return hdu_list.data
9054a6724dcab5096580f17b3543d82c6f32d568
42,801
def format_italic(value): """ Wrap the input value in the ANSI escape sequence for italic. """ return _format_code(value, 3)
eec1b505505206a5da0b4730db9aafe3689885b7
42,802
import json import base64 import hashlib import time def publish_jsonl_to_s3(key, row, target_bucket, max_retries=5, validate_payload_checksum=False): """ Publishes individual rows to S3 as minified JSON. This assumes that the entire 'row' element is written as a single JSON object to the target file. ...
39ea3c835313f059d0d174f6384ffe5d7ffbddf7
42,803
from typing import Union def generate_target_points(subject_paths) -> \ Union[np.ndarray, list[np.ndarray]]: """ This function generates the coordinates for a target point or list of target points. It calls upon a GUI implemented in `gui.targetSelection` """ target_points = gui.target...
6ca1d567dc95f8eed14d08ebc5eb8a1aa16bf34a
42,804
def roc_auc(y_true, y_score): """ Returns are under the ROC curve """ notnull = ~np.isnan(y_true) fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true[notnull], y_score[notnull]) return sklearn.metrics.auc(fpr, tpr)
3fc34285b4e73440f194c495230831673d8c0d3b
42,805
def config_stp_vlan_param(dut, cfgdictionary={}): """ config spanning_tree vlan <enable/disable> <vlanid> cfgdictionary={'' : ['enable', 'vlanid']} cfgdictionary={'' : ['disable', 'vlanid']} config spanning_tree vlan forward_delay <vlanid> <forward_delay> cfgdictionary={'forward_delay' : ['vid'...
12b526e878e6ea928bc90f0807ae38a3fd9dff69
42,806
def Events_detail(request, query): """ Retrieve, update or delete a serie. """ try: map_columns=names_to_representation(Cleanevent) map_columns={i[1]:i[0] for i in map_columns} parameters=query.split("-") dict_params={} for i in parameters: spli...
6b99f8c7c7867b7289bbb3c1dc646d102779be21
42,807
def splice_in_preproc_name(base_env_name, preproc_name): """Splice the name of a preprocessor into a magical benchmark name. e.g. you might start with "MoveToCorner-Demo-v0" and insert "LoResStack" to end up with "MoveToCorner-Demo-LoResStack-v0". Will do a sanity check to ensure that the preprocessor a...
61262abd54d0f3c9be5ee59fdc36c8d2a6cd10eb
42,808
def load(thing=None, working_directory=None): """ Loads site files (customization files) from various locations. Without an argument, loads all default site customization options. With a specific argument, load that argument as a customization file (real file or URL). """ if thing is None: ...
bd6a06340f64b462d5e1a80bca48f085004cbd3e
42,809
def invert_node_predicate(node_predicate): """Build a node predicate that is the inverse of the given node predicate. :param node_predicate: An edge predicate :type node_predicate: (pybel.BELGraph, BaseEntity) -> bool :rtype: (pybel.BELGraph, BaseEntity) -> bool """ def inverse_predicate(graph...
b6132728d17d520fd9ee22f228c45b364704d5ef
42,810
from typing import List from typing import Dict from typing import Any def from_protos_v2( proto_list: List[fra.ForwardRateAgreement], config: "ForwardRateAgreementConfig" = None ) -> Dict[str, Any]: """Creates a dictionary of preprocessed swap data.""" prepare_fras = {} for fra_proto in proto_list:...
8d1ad55d3e5253f18991139f9011038c79c9864b
42,811
def query(q): """Run query exacly as provided.""" con = get_db() c = con.cursor() c.execute(q) con.commit() return c.fetchall()
28f75670b24f3e4da08fbfdc410d21a76e1fb02e
42,812
def adjacent_moves(self): """Returns all moves for adjacent tiles.""" moves = [] if world.tile_exists(self.x + 1, self.y): moves.append(actions.MoveEast()) if world.tile_exists(self.x - 1, self.y): moves.append(actions.MoveWest()) if world.tile_exists(self.x, self.y - 1): mov...
ad91a7727fb4c3990c597458bf215f57c049df34
42,813
import random def get_number_by_pro(number_list, pro_list): """ :param number_list:数字列表 :param pro_list:数字对应的概率列表 :return:按概率从数字列表中抽取的数字 """ # 用均匀分布中的样本值来模拟概率 x = random.uniform(0, 1) # 累积概率 cum_pro = 0.0 # 将可迭代对象打包成元组列表 for number, number_pro in zip(number_list, pro_list):...
34e367cb0e29df59ddf1e15deec1837d71a922f9
42,814
def _pauli2circuit(pauli_ansatz): """Transform a pauli ansatz to parameterized quantum circuit.""" circuit = Circuit() for k, v in pauli_ansatz.items(): circuit += decompose_single_term_time_evolution(k, v) return circuit
afc82c4a121e087b275d52f9db02a8510ba04eaf
42,815
def is_valid_source_state(value): """This function makes exeptions for special source states. E.g. It explicitly allows '*' (for any state) and `None` (as this is default value for sqlalchemy colums) """ return (value == '*') or (value is None) or is_valid_fsm_state(value)
f71bac70eb8c8420ae3ec8ff7dcf77606918bceb
42,816
def is_valid_ip_whitelist_name(name): """True if string looks like a valid IP whitelist name.""" return bool(IP_WHITELIST_NAME_RE.match(name))
953ba7bd5c9afd3a546f65bba4da85b51a8860dc
42,818
def gcd_fast(a: int, b: int) -> tuple: """ GCD using Euler's Extended Algorithm generalized for all integers of the set Z. Including negative values. :param a: The first number. :param b: The second number. :return: gcd,x,y. Where x and y are bezout's coeffecients. """ gcd=0 x=0 y=0 x=0 """ if a < 0: s...
d29cf59b310a7035555a04aaa358410319c3d1b3
42,819
def get_option_name(flags): """ Function to get option names from the user defined arguments. Parameters ---------- flags : list List of user defined arguments Returns ------- flags : list List of option names """ for individualFla...
359ab05c563aac217d8f275bb946fbafc37f3af2
42,820
def write_ros_handshake_header(sock, header): """ Write ROS handshake header header to socket sock @param sock: socket to write to (must be in blocking mode) @type sock: socket.socket @param header: header field keys/values @type header: {str : str} @return: Number of bytes sent (for stati...
d115af5aa095cc8c5a99b7cd89c11943bdb5fbad
42,821
def _rrv_add_ ( s , o ) : """Addition of RooRealVar and ``number'' >>> var = ... >>> num = ... >>> res = var + num """ if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve () elif hasattr ( o , 'getVal' ) : o = o.getVal () # v = s.ge...
6b7070ece98cd25afb7f5cff7ae245440383f2e4
42,822
def NarrowToOctaveBand(freq, dat, n): """ Convert dat from narrowband freq to 1/n octave band """ df = np.mean(np.diff(freq)) lowf = 1000 # Start at 1000 Hz prevf = lowf*(2**(1.0/n)) while (prevf-lowf)>df: prevf = lowf lowf = lowf/(2**(1.0/n)) # Calculate center freque...
296f73b1b1d3e319e1fe4d90dbd7c619e061ce91
42,824
def acq_max(f_acq, gp, y_max, bounds, space, num_warmup, num_starting_points): """ A function to find the maximum of the acquisition function It uses a combination of random sampling (cheap) and the 'L-BFGS-B' optimization method. First by sampling ``num_warmup`` points at random, and then running ...
49e88b9156fce77b888b4217766e7b87094576db
42,825
def openthread_suppress_error_flags(): """Suppress errors for openthread""" return [ '-Wno-error=embedded-directive', '-Wno-error=gnu-zero-variadic-macro-arguments', '-Wno-error=overlength-strings', '-Wno-error=c++11-long-long', '-Wno-error=c++11-extensions', '-Wno-error=variadic...
a6379b1b6133ca24226ca996d9275e4ada8dc3eb
42,826
from typing import Callable def signal_rshift(shift: int) -> Callable[[int], int]: """A circuit element performing a fixed RSHIFT on a signal.""" return lambda x: limit_signal(x >> shift)
54cb582a22a18c73147302be969b48a33d709218
42,828
def es_indices(prefix="", conn=None): """ es_indices gets a potentially filtered list of index names. :type prefix: str :param prefix: the prefix to filter for :type conn: Elasticsearch :param conn: an ES connection object :return: _all or list of index names """ if prefix is not "": ...
1d7831b5b5aa0b8caf16108e33d307e2a16c6128
42,829
import random def wakeup(): """Determine whether the afflicted should wake up.""" return random.randint(0, 99) < WAKEUP_RATE
43af55085c98fbb40165362a9d1ace7bbaf348e0
42,830
def validate(val_loader, model, p_model, criterion): """ Run evaluation """ losses = AverageMeter() top1 = AverageMeter() # switch to evaluate mode _set_fix_method_eval_ori(model) model.eval() with torch.no_grad(): for i, (input, target) in enumerate(val_loader): ...
ad6599b37efbee6cf436da70e5ec05f6bacac638
42,832
def ServiceRequest(opener, host, method, request_dict): """Makes service request to '/service/' + "method" API method.""" req = _MakeRequest(host, '/service/%s' % method, request_dict) return _HandleResponse(method, opener.open(req))
697a032a0f726f5df23631e9b36ee3a2be5dc309
42,833
def test_catch_failure(): """Test case for when the function called with catch raises an exception.""" def f_fail(): return 1 / 0 assert catch(f_fail) is None
211cfe2428610c509dd3ae5ddefa5baa3838b230
42,834
import copy def get_content_node_args(node_data): """ Returns (source_id, title, license) from node_data dictionary. """ node_data = copy.deepcopy(node_data) source_id = node_data.pop('source_id') title = node_data.pop('title') license = node_data.pop('license') return source_id, title...
69aa006fa5b2475f59d52bebb5b5b2424d804eb7
42,835