content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_solution(program: Program, monomial: Poly): """ For a given monomial returns its expected value by first checking if it already has been computed and stored """ log(f"Start get solution, { monomial.as_expr() }", LOG_VERBOSE) global solution_store if monomial_is_constant(monomial): ...
0ad925e7de45155a6898606bd82896610c391882
3,618,400
def point_cloud_label_to_volume_batch(point_clouds, labels, weights, vsize=12, radius=1.1, flatten=True): """ Input is BxNx3 batch of point cloud Output is Bx(vsize^3) """ vol_list = [] label_list = [] weight_list = [] for b in range(point_clouds.shape[0]): vol, label, weight = p...
ea5ddf63f0bf433ea03da7db6739dae882f668bf
3,618,401
def box_to_center_scale(box, model_image_width, model_image_height): """convert a box to center,scale information required for pose transformation Parameters ---------- box : list of tuple list of length 2 with two tuples of floats representing bottom left and top right corner of a box ...
4286fcd73e71978a32d58b0631bbb55c8be5a276
3,618,402
def build_rgb_and_opacity(s): """ Given a KML color string, return an equivalent RGB hex color string and an opacity float rounded to 2 decimal places. EXAMPLE:: >>> build_rgb_and_opacity('ee001122') ('#221100', 0.93) """ # Set defaults color = '000000' opacity = 1 ...
06cb729338584c9b3b934a844f5a2ec53245e967
3,618,403
def design_sosmat_band_passes(order, band_edges, sample_rate, edge_correction_percent=0.0): """Return matrix containig sos coeffs of bandpasses. Parameters ---------- order : int Order of the band pass filters. band_edges : ndarray Band edge frequencies...
44a772245cb5fa0de8a81a96b01f85aaa01678f7
3,618,404
import aiohttp async def shorten(long_url: str, api_base: str, api_key: str): """ Creates a short url if valid. """ params = { 'url': long_url, 'key': api_key, 'response_type': 'json' } async with aiohttp.ClientSession() as sess: async with sess.get(api_base + '...
14bad17b0b39ab09526269ec105086e2ac497f4a
3,618,405
def policy_iteration(problem_data, problem_data_known, K0, L0, sim_options=None, num_iterations=100, print_iterates=True): """Policy iteration""" problem_data_keys = ['A', 'B', 'C', 'Ai', 'Bj', 'Ck', 'varAi', 'varBj', 'varCk', 'Q', 'R', 'S'] A, B, C, Ai, Bj, Ck, varAi, varBj, varCk, Q, ...
5269f527cadd1799c0bf37fc22a83b9730c11e43
3,618,406
def add_lldp_filter_by_host(query, hostid): """Adds a lldp-specific ihost filter to a query. Filters results by host id if supplied value is an integer, otherwise attempts to filter results by host uuid. :param query: Initial query to add filter to. :param hostid: host id or uuid to filter results...
8f9f46738a6e706f4ec1747422689ad473c966b2
3,618,407
import sys def usage_demo(): """ Demonstrates some ways to use the functions in this module. This demonstration reads the lines from this Python file and sends the lines in batches of 10 as messages to a queue. It then receives the messages in batches until the queue is empty. It reassembles the ...
9c71f6b4119b8217da0ebf091405750cf6e79c2f
3,618,408
import tempfile import ctypes def delta(f, s, d=None): """ Create a delta for the file `f` using the signature read from `s`. The delta will be written to `d`. If `d` is omitted, a temporary file will be used. This function returns the delta file `d`. All parameters must be file-like objects. ...
0330809209b3c3a33682b6d70f6c3a3d753b4d5d
3,618,409
def wrap(func): """ Return a wrapped function object. If arg is already a wrapped function object, return that. Parameters ---------- func : function or OMwrappedFunc A plain or already wrapped function object. Returns ------- OMwrappedFunc The wrapped function obj...
028bac0c8a6d380e90c9ffe49a72044e3303cf20
3,618,410
def delete_channel(medialive, event, context): """ Delete a MediaLive channel Return success/failure """ channel_id = event["PhysicalResourceId"] try: # stop the channel medialive.stop_channel(ChannelId=channel_id) # wait untl the channel is idle, otherwise the lambda w...
802f65dc310ffb44ef81f91606e0b26bf3b1a6a0
3,618,411
def relevant_files(root_dir, include_regex='', exclude="*****"): """Return list of files with inclusion regex and exclusion regex. inputs: "root_dir" is the root directory "include_regex" is the string that is searched for within filenames "exclude_regex" is the string that will exclude files if fo...
2c7d358619a716dbff5bcac82d9a66e9ba48073d
3,618,412
def edges_and_nodes_csv_to_graph(fpath_nodes, fpath_edges, u_tag = 'stnode', v_tag = 'endnode', geometry_tag = 'Wkt', largest_G = False): """ Function for generating a G object from a saved .csv of edges :param fpath_nodes: path to a .csv containing nodes :param fpath_edges: path to a .c...
7bc295a17744947e03d76b56fc6713442f802511
3,618,413
def compute_iou(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2]) * (rec1[3] ) S_rec2 = (rec2[2] ) * ...
2e445d7243ace1c3255cfa4c66d72a8bef405bdc
3,618,414
def fn_minimum_argcount(callable): """Returns the minimum number of arguments that must be provided for the call to succeed.""" fn = get_fn(callable) available_argcount = fn_available_argcount(callable) try: return available_argcount - len(fn.__defaults__) except TypeError: return av...
1eb56b741f5e77fdb2613737143304d7b013943e
3,618,415
async def get_by_id(id: str): """ ### Recurso que tem por objetivo buscar uma pessoa. #### Usa como parametro de busca o seu identificador: - id [str(ObjectId)] = "605dcc895dbd779d5e66bd90" """ try: manage_legal_person = ManageLegalPerson() legal_person = await ma...
861348057f69dd79b793992919701bd13b9df15c
3,618,416
import json import re import copy def fill_template(req_sig, responses): """ Fills the template and returns filled request signature else returns None if template is not fillable due to dependencies. """ req_sig_str = json.dumps(req_sig) matches = re.findall(r"{([a-zA-Z0-9\.]+)}", req_sig_str) for match in mat...
db0569f0fa1272685908f66973e322d2cc68ebce
3,618,417
def get_shader(material_name): """ Convenience function for obtaining the shader that the specified material (as an argument) is attached to. :param material_name: Takes the material name as an argument to get associated shader object :return: """ connections = mc.listConnections(material_n...
84b96bfac31ea20ff9a02fca555d99994e6c71ab
3,618,418
def _expr(lex): """Return an expression.""" return _ite(lex)
3b033271540cca9822f73f9bef06d3943677f2c5
3,618,419
import numpy def GQSignal_fetch_position_singal_day(start, end, frequence='day', market_type=QA.MARKET_TYPE.STOCK_CN, portfolio='myportfolio', ...
a2366001235089667fd4ba0aa878b46f62d5a45b
3,618,420
import base64 def return_diagram_as_base64(activities_count, dfg, format="svg", measure="frequency", maxNoOfEdgesInDiagram=75): """ Return process model in Base64 format Parameters ----------- activities_count Count of attributes in the log (may include attributes that are not in the DFG ...
6525f2faf61f85b568af6005ca6610de18a59b95
3,618,421
def url_add_api_key(url_dict: dict, api_key: str) -> str: """Attaches the api key to a given url Args: url_dict: Dict with the request url and it's relevant metadata. api_key: User's API key provided by US Census. Returns: URL with attached API key infor...
1442d0f67a1f3603205870d1af0baf30eb3f1d50
3,618,422
def validate(schema, data, name=None): """ Validate data against a schema """ try: return schema(data) except Invalid as exn: raise loudml.errors.Invalid( exn.error_message, name=name, path=exn.path, )
d2101b79ec9b7d64c7d692a55df291786fcb45d4
3,618,423
from pathlib import Path def config_file_path(token_file: str) -> Path: """Provide Path to config file""" if token_file is None: return Path.joinpath(Path.home(), ".rmapi") else: return Path(token_file)
8f31d64bcb720999080a9bf61b3f174d6882141c
3,618,424
from typing import BinaryIO def _read_ctb(stream: BinaryIO) -> ColorDependentPlotStyles: """ Read a CTB-file from from binary `stream`. """ content = _decompress(stream) content = content.decode() styles = ColorDependentPlotStyles() styles.parse(content) return styles
4e28d123c9c42a28efcc19b3816588067a9438ff
3,618,425
def _compute_fans(shape): """Computes the fan-in and fan-out for a depthwise convolution's kernel.""" if len(shape) != 4: raise ValueError( 'DepthwiseVarianceScaling() is only supported for the rank-4 kernels ' 'of 2D depthwise convolutions. Bad kernel shape: {}' .format(str(shape))) ...
a33bfdf32080147f092d32fca1d70a90b2b25e91
3,618,426
from typing import Mapping from typing import List from typing import Tuple from typing import Optional def _topological_sort( graph: Mapping[str, List[str]] ) -> Tuple[Optional[List[str]], Optional[str]]: """ Figure out the dependency graph using the topological sort. Return None if there is a cycle...
64bf5f4c230e6d7d8c1eb2c159ccecf2fc054bd8
3,618,427
def get_model(pretrained_model_file, latent_dim, n_init_retrain_epochs, n_retrain_epochs, retrain_from_scratch, ite, save_dir, data_enc, data_scores, data_weighter): """ load or train the model """ if ite == 1: print_flush("Loading pre-trained model...") new_weights_dir = pretrained_model_file ...
a1b7ebfe8ea7ec4e85c8290c51088199dfb212df
3,618,428
def get_relation_param_dict(relation: str, filename: str) -> RelationParams: """'Get the relation line parameters. Given a relation string with with the format ID\tREL_TYPE E1_TYPE:E1_ID E2_TYPE:E2_ID' Create a dictionary with the following entity properties: * fname: str * id...
83706798d6a1eb9d0e227cba78bb6aa09b41a885
3,618,429
def get_analog_unit(itf, sig_name, log=False): """ Return the unit of an analog channel. Parameters ---------- itf : win32com.client.CDispatch COM object of the C3Dserver. sig_name : str Analog channel name. log : bool, optional Whether to write logs or not. The defa...
aff3a886a4d766bc2a7ad0ee91294d8a4a4b176c
3,618,430
def truncated_mean(data, n): """Compute a truncated mean, n is truncation size""" return mean(truncated_list(data, n))
eb7698f40883081d4907a7b1119deb98f4f3cbe0
3,618,431
import pandas import math def HMA(df: pandas.DataFrame, period: int = 7, column: str = "positive") -> pandas.Series: """ HMA indicator is a common abbreviation of Hull Moving Average. The average was developed by Allan Hull and is used mainly to identify the current market trend. Unlike SMA (simple mo...
f40ffb434607c5a5b1b0143e9dffafe3a70d262e
3,618,432
def array_affine_coord(mask, affine): """Compute coordinates from a boolean array and an affine transform Parameters ---------- mask: nd array, input array, interpreted as a mask affine: (n+1, n+1) matrix, affine transform that maps the mask points to some embedding space ...
035f40ad950771b3baddaff3062611b538024068
3,618,433
def openssl_sha256(message: bytes) -> bytes: """ Hash function for signature and public key generation This functions wraps a hashfunction in a way that it takes a byte-sequence as an argument and returns the hash of that byte-sequence Args: message: Byte-sequence to be hashed Returns: ...
52604fcb8fae4f34cecb7ca4c14d271ce8c68284
3,618,434
def merge_shards(shard_data, existing): """ Compares ``shard_data`` with ``existing`` and updates ``shard_data`` with any items of ``existing`` that take precedence over the corresponding item in ``shard_data``. :param shard_data: a dict representation of shard range that may be modified by...
18704dd79274dd7ec6157cd28be04a5858e6cff7
3,618,435
def config() -> Config: """Give the rest of the plugin access to shared configuration.""" if _CONFIG is None: raise RuntimeError("Plugin state not initialized; call set_config() before config()") return _CONFIG
0218216dc911c0f7b7bc6b13df2758b6f111b70d
3,618,436
def densify(line, step): """ Given a line segment, return another line segment with the same start & endpoints, and equally spaced sub-points based on `step` size. All the points on the new line are guaranteed to intersect with the original line, and the first and last points will be the same. ...
9956ac13c1cdb586c8065e9bdc639dbe83630fee
3,618,437
import math import statistics def get_cell_types(cpath, tissue, connect=False, smooth=False): """ Prepare database and clusters for upcoming ranking calculations :param cpath: string :param tissue: string :param connect: boolean :param smooth: boolean :return: dictionary """ cluste...
ba28c157affec0ca12dc6bc0a7c869109227a4bc
3,618,438
async def _eqxdo(text): """Run xdotool against the display holding EverQuest""" return await _xdotool(await _eqdisplay(), text)
d2d824d2ebeb93f7319a9bd5745a9642e2c16792
3,618,439
from cacao_accounting.database import Cuentas, Entidad def obtener_catalogo_base(entidad_=None): """Utilidad para devolver el catalogo de cuentas.""" if entidad_: ctas_base = Cuentas.query.filter(Cuentas.padre == None, Cuentas.entidad == entidad_).all() # noqa: E711 else: ctas_base = ( ...
84e6fde0e0a73cd6d3690a08745e7e57a64b8366
3,618,440
from typing import Tuple def normalize_image(image: np.array, mean: Tuple[float, float, float] = (0.485, 0.456, 0.406), std: Tuple[float, float, float] = (0.229, 0.224, 0.225), max_pixel_value: float = 255.0) -> np.ndarray: """ Normalize image (with ...
3e39dc30909665b822b3e1be5feae91145eab384
3,618,441
def similar(a, b): """ Checks if wordlists are *very* similar in a *very naive* way. :param a: set of words :param b: set of words :return: True if the word lists are similar """ count = 0 for w in a: if w in b: count += 1 return _almost(count, len(a), len(b))
907b4b7fe20b20e31baf399bdac5ef9535d13203
3,618,442
from typing import Dict from typing import List from typing import Match from typing import Set def get_lines_to_display( flat_matches_dict: Dict[int, List[Match]], lines: List, nb_lines: int ) -> Set[int]: """ Retrieve the line indexes to display in the content with no secrets. """ lines_to_display: Set[...
9a31e1686576e1deac0a1e85f6dee0d708736ebb
3,618,443
def inFileDict(inFileList): """ generate a nested dictionary of the input files organized by sample and barcode in the format: dict[sample][barcodeGroup][dataType]=fileName """ outDict = {} for f in inFileList: sample = f.split('_')[-3].split('/')[-1] barcodes = f.split('_')[-2] ...
c67183b85890128b3b1728d15f7a45532ee490a3
3,618,444
def calendar(request): """ View for visualizing on the Javascript calendar tool the current user's events """ todos = ToDoList.objects.filter(teacher=request.user) ls = Lessons.objects.filter(teacher=request.user) assignments = Assignments.objects.filter(a_class__teacher=request.user) retur...
f9b187cf562ffaecd0b36028a7eb711063b37dde
3,618,445
import re def smi_tokenizer(smi): """ Tokenize a SMILES molecule or reaction """ pattern = "(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])" regex = re.compile(pattern) tokens = [token for token in regex.findall(smi)] assert smi == '...
f9a8702047659991d32945dd73def6f825542576
3,618,446
import time def disable_user(client, username): """ disables user in keystone. Takes: * keystone client object * username Returns True is succeeded, false if issues. """ try: desc = "disabled_at:%s" % time.strftime("%d.%m.%Y") uid = client.users.list(name=username)[0].id ...
acefcdf820629db5212af947efed9b88d0f459e0
3,618,447
def pairs2dm(pairs): """ Convert eigenpair entries into eigenvalue and density matrix pairs. """ return [(v, ket2dm(e)) for v, e in pairs]
fc5ef0b9262397dcd59d73f7237371337b65a2c1
3,618,448
def find_closest_vertex(desired_hop, available_vertices): """ Find the closest downstream (greater than or equal) vertex in availbale vertices. If nothing exists, then return -1. Keyword arguments: desired_hop -- float representing the desired hop location available_location -- np array of avai...
bf2600e9da8bce32d9e99cea3ac6c92a3b612408
3,618,449
def mat_(path="~/.opticks/GMaterialIndexLocal.json"): """ Customized names to codes arranged to place more important materials at indices less than 0xF:: simon:~ blyth$ cat ~/.opticks/GMaterialIndexLocal.json { "ADTableStainlessSteel": "19", "Acrylic": "3", ...
c4ae5fb0da48141bfcada896b31103bc9a5b3c43
3,618,450
def add_model_components(m, d, scenario_directory, subproblem, stage): """ :param m: :param d: :return: """ def total_performance_standard_emissions_rule(mod, z, p): """ Calculate total emissions from all performance standard projects in performance standard zone ...
6cb3aaeb75dc6d51a18150d9b5eebaeb81efd55e
3,618,451
from typing import Tuple from typing import Optional from typing import List def parse_episode(episode_title: str) -> Tuple[Optional[int], Optional[int]]: """ parse episode from title :param episode_title: episode title :type episode_title: str :return: episode of start, episode count """ ...
dbd6e073d0569485e89a8c7844ab79709d315a1d
3,618,452
from typing import Optional def exp(x: VariableLike, *, out: Optional[VariableLike] = None) -> VariableLike: """Element-wise exponential. Parameters ---------- x: Input data. out: Optional output buffer. Returns ------- : e raised to the power of the input. ...
670c665697e12543df6c2d9b402c63b1f3d95610
3,618,453
def _config_generator( local_config, min_iter=None, max_iter=None, warmup=False, callback=None, ): """Configuration generator. Turns the iterable config into a generator of config dictionaries. Args: local_config: The configuration dictionary. All values must be iterable. ...
cdf9e99105798b26ef4c8bf41665d8b48796280a
3,618,454
def longest_ORF(dna): """ Finds the longest ORF on both strands of the specified DNA and returns it as a string #TAA TGA TAG >>> longest_ORF("ATGCGAATGTAGCATCAAA") ['ATGCTACATTCGCAT', 3, -1] >>> longest_ORF("AAAAAAAA") [''] """ lenlist = [] orflist = find_all_ORFs_both_strands(dn...
f3b7d89e30dc657febeb4270f6e9723ff2e5c1b4
3,618,455
def update_file(): """更新""" data = request.form file_id = data.get('file_id', None) content = data.get('content', None) file = FileName.query.get(file_id) if not file: return jsonify({'code': '404'}) file.content = content db.session.commit() return jsonify({'code': '201', 'm...
4a3f363e990ef56f8f32d0c749b78703f95064bd
3,618,456
def distribute_permissions(request): """ 权限分配 :param request: :return: """ user_id = request.GET.get('uid') # 业务中的用户表 user_model_class = import_string(settings.RBAC_USER_MODLE_CLASS) user_object = user_model_class.objects.filter(id=user_id).first() if not user_object: u...
bf808e93cc22395b4220d90c732029c6beffacab
3,618,457
def load_exec001_data(file_name): """Loads data from a saved MCC numpy trial file.""" with open(file_name, 'rb') as file: mcc = np.load(file) inc = np.load(file) prf = np.load(file) dem = np.load(file) return mcc, inc, prf, dem
b260cedc00802b783356b44312e41ceb54d03e0f
3,618,458
def get_password(hostname: str, port: int = 1433, database: str = "MOSAIQ"): """Get password from keyring storage Parameters ---------- hostname : str The MSSQL server hostname port : int, optional The MSSQL server port, by default 1433 database : str, optional The MSSQL...
abf8f7914f66fd5a8e5ae562733f915f0d484573
3,618,459
def get_guest_mailbox(mailbox_id): """ Return all guest mailboxes of mailbox with provided id """ return (guest_mailbox for guest_mailbox in get_mailbox_guests_query(mailbox_id))
6cc130cf12fa1aaece0fa054016d7e87d6cea397
3,618,460
def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret
dd707700de52020102ad51ad6f8494d0db489463
3,618,461
import re def is_valid_regex(string): """ Checks whether the re module can compile the given regular expression. :param string: str :return: boolean """ try: re.compile(string) is_valid = True except re.error: is_valid = False return is_valid
3893410afd8d3e6ed9310550159b35cc504dfffa
3,618,462
def get_vcf_allele(hgvs, genome, transcript=None): """Get an VCF-style allele from a HGVSName, a genome, and a transcript.""" chrom, start, end = hgvs.get_vcf_coords(transcript) _, alt = hgvs.get_ref_alt( transcript.tx_position.is_forward_strand if transcript else True) ref = get_genomic_sequenc...
66a9b025624727ba06aa92c88365069612135c64
3,618,463
def lr_grid( adata: AnnData, num_row: int = 10, num_col: int = 10, use_lr: str = "cci_lr_grid", radius: int = 1, verbose: bool = True, ) -> AnnData: """Calculate the proportion of known ligand-receptor co-expression among the neighbouring grids or within each grid Parameters -------...
3358913007c1a00156df8ea70390d5f27c6c58cf
3,618,464
def _read_amplifier_data(gain_filename, phase_filename, gain_offset=0): """ Gather frequency-dependent amplifier data from data files. Each data file should have columns for frequency, gain or phase data, and a third empty column. The gain should be in dB and the phase should be in degrees. Pa...
4652d4198a0e45af3e7823e46ca7a981cc3c17ba
3,618,465
import numpy def oht_model( gw, oro, fsns, flns, shfl, lhfl ): """parameters; must be dimensioned as specified: gwi : gaussian weights (lat) oroi : orography data array (lat,lon) requires the lat and lon are attached coordinates of oro and that oro and the following variables are 2D arrays (...
58f3378172026fe700c38bfb8fa76ff0a1f9c016
3,618,466
from typing import Tuple import functools def partition_spmd_model_decode( mdl_params: InstantiableParams, init_key: PRNGKey, inputs_shape: NestedShapeDtypeStruct, ) -> Tuple[TrainState, TrainState, DecodeFn]: """Setup the SPMD model and return sharded decode step function. For partitioning inputs, i...
b2fa00fd239577fd364ab4a83cac1019bcd504ab
3,618,467
import logging def format_mulenc_args(args): """Format args for multi-encoder setup. It deals with following situations: (when args.num_encs=2): 1. args.elayers = None -> args.elayers = [4, 4]; 2. args.elayers = 4 -> args.elayers = [4, 4]; 3. args.elayers = [4, 4, 4] -> args.elayers = [4, 4]. ...
fbecf63e660ba0756e86a4334de95e7ae5f6736c
3,618,468
def expand_Hc(Hc): """Calculate the matricized quadratic operator that operates on the full Kronecker product. Parameters ---------- Hc : (r,s) ndarray The matricized quadratic tensor that operates on the compact Kronecker product. Here s = r * (r+1) / 2. Returns ------- ...
b041349e766b4de785b7a711d527b4c2400c389a
3,618,469
from typing import List from typing import Dict def get_best_paragraphs(data: pd.DataFrame, query: str, doc_id: str, sim, n_matching: int) -> List[Dict[str,str]]: """Retrieves the best paragraphs for expected doc using similarity model Args: data [pd.DataFrame]: data df with processed text at paragrap...
4503a9f476293607634abe6dc71d4e06efb36529
3,618,470
import re def set_or_clear_alarm_with_key_source_target(error_type, case, host, message): """ :param error_type: TsigBadTime, ZoneTransferFailed :param case: set/clear :param host: in ip address for example: 172.21.3.14 :param message: in string :return: "set" or "clear", keypair, err...
02128d371bf9ec2652a2a86e971079ec70d7f939
3,618,471
def get_word_stats(searchType, metaField): """ Return JSON with basic statistics concerning the distribution of a particular word form by values of one metafield. This function can be used to visualise word distributions across genres etc. If searchType == 'context', take into account the whole quer...
90c7be7320ba3b69fcb348cd6e6dd29330f8a915
3,618,472
import pickle import time import random def run_val_nbeatsx(hyperparameters, Y_df, X_df, data_augmentation, random_validation, trials, trials_file_name): """ Auxiliary function to run NBEATSx for hyperopt hyperparameter optimization. Return a dictionary with loss and relevant information. """ # T...
7945a3455f06a470f8c80715e18fa12b6de2366e
3,618,473
from typing import Optional def get_order_item_by_name(expand: Optional[str] = None, order_item_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOrderItemB...
392fec4b6e7ff4901a2c68004d04ac43840c5ff1
3,618,474
def did_detect(tuple_list, entry_zones, exit_zones): """ Determine if objects are coming or going """ # print('alwaysai.py: did_detect: entry zones: {}'.format(entry_zones)) global ENTER_CALLBACK global EXIT_CALLBACK for object_id, prediction in tuple_list: box = prediction.box ...
898f1666e1c0cbfed211da45b7a7bafd6afee3a8
3,618,475
def matmul_AT_B_A(a, b): """ Computes A.T * B * A, dealing automatically with sparsity and data modes. :param a: Tensor or SparseTensor with rank 2 or 3. :param b: Tensor or SparseTensor with rank 2 or 3. :return: Tensor or SparseTensor with rank = max(rank(a), rank(b)). """ at_b = matmul_AT...
6c86e6fb578298a218e310e147b8f14f32a44959
3,618,476
from sympy import besselj, besseli, jn, I, pi, Dummy from re import S def besselsimp(expr): """ Simplify bessel-type functions. This routine tries to simplify bessel-type functions. Currently it only works on the Bessel J and I functions, however. It works by looking at all such functions in turn...
5ba403c9530469a4f7a94b46d394d3c87f3eec6a
3,618,477
def run(): """Default Run Method""" return problem57(1000)
040a59863943c23fe1d595d66a225a60b1f8c08d
3,618,478
from typing import Optional import torch def elementwise_spatial_consistency_loss( input: Tensor, target: Optional[Tensor], pred: Tensor ) -> Tensor: """Apply elementwise weight and reduce loss between a batch of input and a batch of target. Args: input (Tensor): Original input shap...
e3dfa33c6e2c2ae91ec18732ac04a338a8e50a2f
3,618,479
def view_program_slides(eid): """ Creates the HTML slides for the songs associated with a program sheet. :param eid: The eid of the program for which the HTML slides are to be made. :type eid: int :returns: Renders the HTML slides. """ program = fill_program_information( pr...
d91211031c9efc9691f133aa85ef6705418c1e95
3,618,480
def register_implementation(card_view_flavor="simple", name=None): """Decorator for marking a function as implementation for an analysis function. :param card_view_flavor: defines how results for this function are displayed, see views.CARD_VIEW_FLAVORS :param name: human-readable name, default is to create...
66421af066723397c29256fdbec14eeee16d5d85
3,618,481
from .models import AbstractAttachment def get_attachment_model(): """ Returns the Attachment model that is active in this project. """ try: klass = django_apps.get_model(summernote_config["attachment_model"]) if not issubclass(klass, AbstractAttachment): raise ImproperlyCo...
777501f7f5ad6a8bc8a084eac965a7296cdfacf0
3,618,482
def get_date_effect_strategy(): """日历效应策略""" print("""根据天风证券研究表明,基金业绩在每年三月末具有较好的持续性,因此推荐在每年三月末测试日历效应策略""") funds = get_fund_ranking("gp") funds.extend(get_fund_ranking("hh")) funds.extend(get_fund_ranking("qdii")) funds = [f for f in funds if f["fundname"][-1] not in ["B", "C", "E", "H", "O"]] ...
15b26df314f97165568cb8a716a9f2bd88376efe
3,618,483
def setup_scanner(hass, config: dict, see, discovery_info=None): """Set up the iCloud Scanner.""" username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) account = config.get(CONF_ACCOUNTNAME, slugify(username.partition('@')[0])) icloudaccount = Icloud(hass, username, password, ac...
d96af1fa4b3f7ddac8ab80255a510d9b7be757a8
3,618,484
def parse_cluster_pubsub_numsub(res, **options): """ Result callback, handles different return types switchable by the `aggregate` flag. """ aggregate = options.get('aggregate', True) if not aggregate: return res numsub_d = {} for _, numsub_tups in res.items(): for chann...
0e499f8508b0f5507fa0b2c418d0a253d35a32f5
3,618,485
import warnings def get_font(font_name, font_size): """ Tries to load the named font at the given size but falls back on default font if this is not possible. @return: The named font at the given size if possible. """ try: return ImageFont.truetype(font_name, font_size) except: ...
d8890e2844ddc38a9ec2e2d8bccb91448db236cf
3,618,486
def convert_aux_to_base(new_aux: float, close: float): """converts the aux coin to the base coin Parameters ---------- new_base, the last amount maintained by the backtest close, the closing price of the coin Returns ------- float, amount of the last aux divided by the closin...
f76324e0a61a58a926d3f4cadf60315692d35fee
3,618,487
def _estimate_double_gaussian_parameters(x_data, y_data, fast_estimate=False): """ Estimate of double gaussian model parameters.""" maxsignal = np.percentile(x_data, 98) minsignal = np.percentile(x_data, 2) data_left = y_data[:int((len(y_data) / 2))] data_right = y_data[int((len(y_data) / 2)):] ...
6778a6c71c1ed1c0090d1a9a9d46c9b628ff9764
3,618,488
import numpy def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0): """Calculate a Sobel filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode_multiple)s %(cval)s Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplo...
b96357fee846ea61cd892ffcd06894a86c19332f
3,618,489
def clone_model_with_weights(model_to_clone): """Clone keras model with weights.""" cloned_model = keras.models.clone_model(model_to_clone) cloned_model.set_weights(model_to_clone.get_weights()) return cloned_model
6de9a1f1c15c80b0719532f6f83399648a3254c2
3,618,490
def fashion_mnist_load_data(): """Loads the Fashion-MNIST dataset. Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. """ file_path = '/file/oi-d/home/person/datasets/fashion_mnist' with gfile.Open('/gzip{}/train-labels-idx1-ubyte.gz'.format(file_path), 'rb') as l...
40b2d627a30e5063e81cae722093bce26d7ef2b2
3,618,491
def mk7z(): """ 创建7z包 Create 7z package :return: None """ return _mk7z()
b4efd4505034f315600bc390adef8c69687cc97f
3,618,492
def safe_str(obj): """ return the byte string representation of obj """ PY2=False basestring = str try: return str(obj) except UnicodeEncodeError: # obj is unicode mylogging("safe_str error", pr=True) return obj
988bfca47b499e0616e6e102863fe09860fd3784
3,618,493
def state_db(indicador="3102009001"): """Construct a State level DataFrame from INEGI API http://www.inegi.org.mx/desarrolladores/indicadores/apiindicadores.aspx """ #merge data from every state, create databases for each index: db_state, meta = INEGI(indicador=indicador,area="01") db_state.rese...
02f246a52423b71f6d2b90be05b4d9470ed150e2
3,618,494
def makeTernaryOperator(cond: ExprType, left: ExprType, right: ExprType) -> TernaryOperator: """ Create a TernaryOperator :param cond: Condition. :param left: Left-hand side. :param right: Right-hand side. """ expr = TernaryOperator() expr.cond.CopyFrom(makeExpr(cond)) expr.left...
ea02697512bfaf9b6aa7e712e789a824c1550eb2
3,618,495
def load_cbmc_json(json_file, root): """Load json file produced by goto-analyzer --reachable-functions --json.""" json_data = parse.parse_json_file(json_file, fail=True, goto_analyzer=True) return parse_cbmc_json(json_data, root)
545f16eee045ac1717659a8fda806ca5f34e8362
3,618,496
def get_coord(tic): """ Get TIC corrdinates Returns ------- TIC number """ try: catalog_data = Catalogs.query_object(objectname="TIC"+tic, catalog="TIC") ra = catalog_data[0]["ra"] dec = catalog_data[0]["dec"] return ra, dec except: print "ERROR: No gaia ID found for this TIC"
bf3a7d8e483f546fdccd5b441fd52d7e75b1f52b
3,618,497
import calendar def year_add(date, years): """Add number of years to date. >>> import datetime >>> year_add(datetime.datetime(2016, 2, 29), 1) datetime.date(2017, 2, 28) >>> year_add(datetime.date(2016, 2, 29), 1) datetime.date(2017, 2, 28) >>> year_add(datetime.date(2015, 2, 28), 1) ...
62be01b7051ddef27376ebae4b97f63e9b7ca979
3,618,498
def less_or_equal(a, b, *args): """Implements the '<=' operator with JS-style type coertion.""" return ( less(a, b) or soft_equals(a, b) ) and (not args or less_or_equal(b, *args))
309dd3f207244870f983c5875f0ea4068cc2bb3b
3,618,499