content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def sched_var(func): """This decorator marks the given function as a scheduler variable. The function must take no arguments (other than self).""" # The scheduler plugin class will search for these. func.is_sched_var = True func.is_deferable = False # Wrap the function function so it keeps it'...
99a01aa59ec633cf8d0cd06258f0d726d21df6f7
3,611,611
import logging def posgres_raw(query_sql, query_args=None, *, as_dict=True, alias=None, filterData=None, modifyData=None, **kwargs): """ Returns the answer to a raw sql statement to ther database. table (str) - Which table to get data from Example Input: posgres_select("SELECT * FROM property") Example Input: ...
11168f2e882674bb967841c48f84e55c08496e56
3,611,612
def file_upload_url(): """ file_upload_url: returns url to upload files Args: None Returns: string url to file_upload endpoint """ return FILE_UPLOAD_URL.format(domain=DOMAIN)
4ac3a8f20fd212d4f9c28697a793bb6d8759e38d
3,611,613
def parse_command_line(version=None, self_description=None, version_date=None, default_config_file_path=None, ): """parse command line arguments Also add current version and version date to description """ # de...
fbf9613087d7a629f56d4b1f6260b71ab36e283f
3,611,614
def appium_bytes(value, encoding): """ Return a bytes-like object. Has _appium_ prefix to avoid overriding built-in bytes. :param value: A value to convert :type value: string :param encoding: A encoding which will convert to :type encoding: string :return: A bytes-like object :rtype:...
b7acc045584ffad834bb24f30fe930736f55d699
3,611,616
from typing import List import csv def read_sts_inputs(path: str) -> List[str]: """Read input texts from a tsv file, formatted like the official STS benchmark""" inputs = [] with open(path, 'r', encoding='utf8') as fh: reader = csv.reader(fh, delimiter='\t', quoting=csv.QUOTE_NONE) for row...
6af4e934d648b550298e71584eaf47e4267316ac
3,611,617
def extract_keys(dict, keys, no_key_val=_sentinel): """Removes the specified keys from the given dictionary, and returns a dictionary containing those key:value pairs. Default behaviour is to ignore those keys which can't be found in the original dictionary. The optional argument :no_key_val: can be set to ...
eb420734b1969e8a01b47caef023443d0e1f48e7
3,611,619
def resnet101(num_classes, pretrained=False, dropout1=0.25, dropout2=0.25, alpha=0.25, gamma=2.0, loss_with_no_bboxes=False, no_bboxes_alpha=0.5, no_bboxes_gamma=2, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet ...
688e0ded410033c63c3db6c10f65a334447a2b97
3,611,620
def vuvu_to_vuhw(vuvu): """ Function to transform between top left and bottom right corner box representation (vuvu) to center_dimensions box representation (vuhw) . :param vuvu: N x 4 tensor represeting v_min, u_min, v_max, u_max, the corners of the bounding boxes. :return: vuhw: N x 4 tensor rep...
a9dc162d1b7d8d66099f2fb500d808e10d492809
3,611,621
import asyncio async def async_unload_entry(hass, config_entry): """Unload an AirVisual config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(config_entry, component) for component in PLATFORMS ...
14b761200e6ec54340f6543e447d7c240ebfb5ca
3,611,622
def application_doesnt_match(service, custom_application, custom_app_plan, lifecycle_hooks, request): """Second application that doesn't match jwt claim check policy""" plan = custom_app_plan(rawobj.ApplicationPlan(blame(request, "aplan")), service) application = custom_application(rawobj.Application(blame(...
19b6ef733e505522423d88f9de14ef753854cde3
3,611,623
def delete_appliance_for_rediscovery( self, ne_pk: str, ) -> bool: """Delete an appliance from Orchestrator for rediscovery .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - appliance - DELETE - /appliance/delete...
8be2817f55408314ef27baac022801059f3f2340
3,611,624
def increase_index(idx: str) -> str: """Increases an index by one unit. If the index is numeric, in the range '00' to '98', it adds one to the index and returns an index in the range '01' to '99'. If the index is already '99', there is an Exception error. If the index is alphanumeric, with the fir...
1bcaa8d27ed83d295197c4f398e77d49ad47bb6d
3,611,626
def compare_flow_fields(F1, F2, n_min=1): """Compare two flow fields. """ # Compute the element-by-element difference dX_diff = F1.dX_fit - F2.dX_fit dX_diff_mag = np.linalg.norm(dX_diff, axis=2) # n_grid x n_grid # Filter by the number of observations. Find the number of observations for ...
26dc0cd321861050899cfe5e0189966eff6efd4f
3,611,627
import itertools def rollup_dataseries(dataseries): """ Rollup dataseries. Roll up a sites data series by parameter group if a series has them. Data types for the parameter group is the join of the data types for each measured parameter code. Similarly, the start and end dates are the earliest an...
9ac13333d05a6410b1fd4497528f8eca6d1d7f45
3,611,628
def determine_smallest_atom_index_in_scan(atom1: 'rdkit.Chem.rdchem.Atom', atom2: 'rdkit.Chem.rdchem.Atom', ) -> int: """ Determine the smallest atom index in mol connected to ``atom1`` which is not ``atom2``. Returns a heav...
dd15837711401f52ff9ab3f561b4d82556990a9c
3,611,629
def quartiles(xs): """Divisions between quartiles.""" return quantiles(xs, 0.25, 0.5, 0.75)
599d8a81c8b7774096eb2f062448cf8dd4818a17
3,611,632
from datetime import datetime import time def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) ...
9723ab0656ff4017412ab1fbd5465375ec8df1af
3,611,633
from datetime import datetime def get_utc_timestamp() -> Text: """Get utc timestamp. Returns: Text: utc timestamp """ return str(datetime.datetime.utcnow().timestamp() * 1000)
85de30cf745c545dadc26d7dbc6c866238e6c5cf
3,611,634
def ConvolutionalVAE(*args, **kwargs): """ Constructs a Convolutional VAE. References [1]. Oktay, Ozan, et al. “Attention U-Net: Learning Where to Look for the Pancreas.” ArXiv:1804.03999 [Cs], May 2018. arXiv.org, http://arxiv.org/abs/1804.03999. >>> import deeply >>> model = deeply.hub("...
fd082d63e2940dc07a2ce007b8f4da251411c834
3,611,635
def to_2d_np(a: ndarray, type: str="col") -> ndarray: """ Turns a 1D Tensor into 2D """ assert a.ndim == 1, \ "Input tensors must be 1 dimensional" if type == "col": return a.reshape(-1, 1) elif type == "row": return a.reshape(1, -1)
07933cd3851d65b61034b3b3d7b9caa46b809c1e
3,611,636
def standardize_parameter_type(original_type): """Standardize parameter type descriptions Args: original_type (str): The original type Returns: str: The standarized type name """ original_type = original_type.lower() if 'unc' in original_type: return 'uncertainty' i...
49a93bebd8ee4918bdf420ee8c285d6574a3d3d0
3,611,639
def insert_xlnx_pragmas(lines): """Insert HLS pragmas for Xilinx program Replace the comments of "// hls_pipeline" and "// hls_unroll" with HLS pragmas For "// hls pipeline", find the previous for loop before hitting any "}". Insert "#pragma HLS PIPELINE II=1" below the for loop. For "// hls un...
9ad5e5253473ecbcf82d4e739b7c6d7dd82ba7c6
3,611,642
def check_unboundness(A_times_delta_x): """Check if LP is unbounded """ if np.all(A_times_delta_x <= 0): logger.info('LP is unbounded') return True else: return False
c8a91036fd3768b1774fba650796886d8eafa913
3,611,643
from typing import Tuple import torch import math def real_fourier_basis(n: int) -> Tuple[torch.Tensor, torch.Tensor]: """Make a Fourier basis. Args: n: The basis size Returns: An array of shape `(n_domain, n_funs)` containing the basis functions, and an array containing the spec...
704aacf8e34f2713ee5e01b8c0de2350c8e03ae2
3,611,644
def to_output_type(array, output_type, order='F'): """Used to convert arrays while creating datasets for testing. Parameters ---------- array : array Input array to convert output_type : string Type of to convert to Returns ------- Converted array """ if out...
701691824ddd2364ff6770d93d13389cf8aa4dc4
3,611,645
def _define_names(d_t, d_y, treatment_names, output_names): """ Helper function to get treatment and output names Parameters ---------- d_t: tuple of int Tuple of number of treatment (exclude control in discrete treatment scenario). d_y: tuple of int Tuple of number of outcome. ...
a475968ed70070175f5ef164d1748def62548c9d
3,611,646
import urllib3 def scrape_lat_lon_fly(stationID): """ Add latitude, longitude and elevation data to the stationID that is inputted as the argument to the function. Boom. :param stationID: str a unique identifier for the weather underground personal weather station :return: (latitud...
e1a78f3adfb7ce890306d31deba4e15410bb079c
3,611,647
from typing import List from typing import Callable def _add_standard_processes(process_registry: ProcessRegistry, process_ids: List[str]): """ Add standard processes as implemented by the openeo-processes-python project. """ def wrap(process: Callable): """Adapter to connect the kwargs style...
da5b162fdc8002670864cd1e1e5069b40f0d8a8b
3,611,648
def __num_children(self, vertex=None): """ Get the the number of children of the given vertices. If :attr:`vertex` is ``None``, the function will return the number of children of every non leaf node of the tree. :param vertex: a vertex index or a 1d array of vertex indices (default to ``np...
e1385a67cfc79dd1fa18805c85e8e2fd59336c16
3,611,649
from datetime import datetime def parse_time_interval(time_start, time_end): """created time values for time_start and time_end, while time_end will be replaced with time_start+ a duration if the duration is given in time_end. The format of the duration is intuitive through the timeparse module. YOu c...
b4348e1995514030528fad9330d726eb5079d758
3,611,650
def _as_vw_string(x, y=None): """Convert {feature: value} to something _VW understands Parameters ---------- x : {<feature>: <value>} y : int or float """ result = str(y) x = " ".join(["%s:%f" % (key, value) for (key, value) in list(x.items())]) return result + " | " + x
89e10d3bb8ad47ad4add6baee83280fa700ca65e
3,611,651
from io import StringIO import csv def _read_header(f, header_param): """ Read and parse data from 1st line of a file. :param f: :func:`file` or :class:`~StringIO.StringIO` object from which to read 1st line. :type f: file :param header_param: Parameters used to parse the data from the he...
294bb6846384378b1dd9950e649757a6448089d0
3,611,652
def classifier_layer_fn(in_dim, out_dim, layer_name, fn=tf.nn.relu): """Build a function for a neural network classifier layer.""" with tf.name_scope(layer_name + '_vars'): weights, biases = classifier_variables(in_dim, out_dim) def nn_layer_ops(x): with tf.name_scope(layer_name + '_ops')...
ce0f153f033ab603373763368edc4e70d5b53590
3,611,653
def svn_client_revprop_get(*args): """ svn_client_revprop_get(char propname, svn_string_t propval, char URL, svn_opt_revision_t revision, svn_revnum_t set_rev, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return apply(_client.svn_client_revprop_get, args)
b4725ec347ea9fbd7ab15d0a2ffb10112907b5b3
3,611,654
import typing def do_action(view: View, defx: Defx, action_name: str, context: Context) -> bool: """ Do "action_name" action. """ if not defx._source: return True actions: typing.Dict[str, ActionTable] = defx._source.kind.get_actions() if action_name not in actions: ...
bb45de3c896b7bdcef8d40236a5743517d5230d1
3,611,656
from numpy import where def qinit(x,y): """ Dam break """ eta = where(x<10, 40., 0.) return eta
aa81ca9782917ce730ec70f4281a7b708c368308
3,611,657
def parkinson_volatility(high_prices, low_prices, window, time_scale=1, plot=False): """ Estimando a volatilidade a partir dos preços de Alta e de Baixa Args: high (pd.DataFrame): série de preços de alta de uma ação low (pd.DataFrame): série de preços de baixa de uma ação window (in...
49b0f4b10eb80d17a801660c04cfe32e9d9e7dd9
3,611,658
def DatetimeToUTCMillis(date): """Converts a datetime object to milliseconds since the epoch in UTC. Args: date: A datetime to convert. Returns: The number of milliseconds since the epoch, in UTC, represented by the input datetime. """ return DatetimeToUTCMicros(date) / 1000
0020e7b15ee0e7ff541d4e1691940e4114de42c5
3,611,660
from typing import AsyncIterable from typing import Optional from typing import Union from typing import IO from typing import List async def _async_forward(async_chunks: AsyncIterable, out: Optional[Union[TeeCapture, IO[str]]] ) -> Optional[str]: """Prints/capture...
2e9d861cd905a2f4576e6ba026e98bfccb8b80c2
3,611,661
def _try_parse_int(value: str): """ try parse integer from string param value: string to parse return int """ try: return int(value) except ValueError: raise ValueError("Cannot parse int from string")
50b4f5c3d3e703c2c6c329e2f1abb25a948e488d
3,611,662
import numpy as np def df_to_latex( df, col_aligns="", header="", caption="", bold_max_cols=None, na_rep="-", supertabular=False, midrule_after=None): """Converts a pandas dataframe into a latex table. :col_aligns: Optional format string for...
6f073dd35c343a81e3222ac2e90fea2c2f5bd1d1
3,611,663
def _gather_shape_rule(operand, indices, *, dimension_numbers, slice_sizes, unique_indices, indices_are_sorted, mode, fill_value): """Validates the well-formedness of the arguments to Gather. The code implements the checks based on the detailed operation semantics of ...
052ac40add46eadc3e0d4cd43096290cf5d86c62
3,611,664
def tf_mixed_norm_solver(M, G, alpha_space, alpha_time, wsize=64, tstep=4, n_orient=1, maxit=200, tol=1e-8, log_objective=True, active_set_size=None, debias=True, return_gap=False, verbose=None): """Solve TF L21+L1 inverse solver with BCD an...
12dd13a8d45ef4afd0b515b4c4d6dcdf82f3c154
3,611,665
def stddev(in_list): """ Calculates standard deviation of given list :param in_list: list of values :return: float rounded to 5 decimal places """ var = zvariance.variance(in_list) std_dev = sqrt(var) return round(std_dev, 5)
8225b943b87ea2c966b130fd5afc9b06d6306b8e
3,611,666
def retrieve_single_timeseries(ticker, secs=60, ndays=5): """ Grabs data from Google finance. It retrieves the data for `ticker` at `secs` intervals for the most recent `ndays`. The fields it retrieves for each interval is (time, open price, close price, volume of trade) Parameters ---------- ...
95fc69f4920d92895d2c9f8a8e852f78f2a06a8d
3,611,667
def select_os(parsed_host: dict): """ Out of all suggested OSs for the given host from Nmap, select the most likely one using cosine similarity string matching. First a string of relevant information is created, second the OS whose information is the most similar to the matching string is returned. ...
4216686c724e1738471c939d567befc3d6f1c08d
3,611,668
def index_settings(shards=5, refresh_interval=None): """Configure an index in ES with support for text transliteration.""" return { "index": { "number_of_shards": shards, "refresh_interval": refresh_interval, "analysis": { "analyzer": { ...
29028b545da2e5ee2b0239029d34f863d1d9d943
3,611,669
def create_gray_frame(frame): """Create and return an undistorted grayscale image""" h, w = frame.shape[:2] new_matrix, _ = cv2.getOptimalNewCameraMatrix(Pose.camera_matrix, Pose.dist_coeffs, (w, h), 1, (w, h...
748aff0f5a02a7a98bc56f2c46645c59b630c4a7
3,611,670
def make_nan_inf_summary(df: pd.DataFrame, max_loss: float) -> pd.DataFrame: """ makes a summary fot the the amount of nan and infinity values in the given data frame will throw a ValueError if the percent of nan and inf is greater than the given threshold prints a summary of the nan's and inf of there ...
0ea0be6a822861e5896176cf96d5a6bb9d50954f
3,611,671
def choose_downloaded_komoot_tour(): """ Choose a previously downloaded tour. Tour can be passed to :func:`komoog.gpx.convert_tour_to_gpx_tracks` afterwards. """ tours = read_tours() for idx in range(len(tours)): print(f"({idx+1}) {tours[idx]['name']}") tour_id = int(input("To...
66cf0878728fab6fa6265d61f2a488dde2478091
3,611,672
from datetime import datetime def list_(limit: int = None, offset: int = None, siri_route_ids: str = None, siri_route__line_refs: str = None, siri_route__operator_refs: str = None, journey_ref_prefix: str = None, journey_refs: str = None, vehicle_refs: str = None, sch...
86fc2ce2a2609e6f2325f755c64812c8bbd093ba
3,611,674
def fit_cpmfgp_with_dataset(dataset, *args, **kwargs): """ Fits and returns a CPMFGP. """ config = dataset.config mfgp_fitter = cpgp.CPMFGPFitter(dataset.ZZ_train, dataset.XX_train, dataset.YY_train, fidel_space=config.fidel_space, domain=config.domain, fidel_space_kernel_ordering=config.fidel_space_order...
4478386e52d121d32951d84152c77e50bb5f4408
3,611,675
import time def test_approach(approach: str, sample_no: int, func, args: tuple) -> str: """ For a given Sample #sample_no evaluates an approach by running func with provided args and logs run time """ res = f"{approach.capitalize()} Programming Approach for the Example #{sample_no}\n" start = time.time()+...
ef34e7552a887fd4bee221a5d80bb3d5ab0003a9
3,611,676
def call_command(cmd, verbosity="ERROR"): """ simple wrapper for call command """ p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, err = p.communicate("get output") rc = p.returncode if not rc == 0: raise Exception("{0} ==> command: {1}".format(err, " ".join(cmd))) return output
2b153bb00f920fb9c5509fa6f76953073a8eec49
3,611,677
def walk(i, j): """ Walks through the String without crossing the boundaries, making sure that i < j-1 """ if i < j - 1: i += 1 # It is necessary to check again if i < j-1, after we incremented i if i < j - 1: j -= 1 return i, j
1597c41408179f5a371ec14e36494ec5ee3a7aa0
3,611,678
def run(configbase, filebase, options, progname): """ Command line tool to create and display ROs managed by the Overlay RO service. """ status = 0 # Create new Overlay RO and returns its URI with HTTP_Session(options.serviceuri) as rovsession: try: rovsession.doRequest(optio...
de8d13f7f520dcf728f73c5485d50494ae631d79
3,611,679
def equation_loglogw2(x, a, b, c, d, e): """Equation form for loglogw2 """ return exp(a + b * log(log(x+1)) + (sqrt(x) * (c/2)))
662fa157f5b4073780f5bbb383841867af7f6cd7
3,611,680
import uuid def converter_spark_em_pandas(df): """ Converte o dataframe Spark em Pandas, adicionando uma coluna de identificador unico e deterministico para cada linha da tabela """ data = df.toPandas() data["ID_REGISTRO_TABELA"] = data.apply( lambda row: uuid.uuid5( uuid.UUID('a658b648-167e-4d4...
99febbc364025afb39772fa6008f5b4217f394ae
3,611,681
def kwargs_to_str(kwargs): """ Returns a string of the form '(kw1=val1, kw2=val2)'. """ if len(kwargs) == 0: return "" else: return "(" + ", ".join(f"{k}={v}" for k, v in kwargs.items()) + ")"
39d50d77620061b99861fb7a1fea77ae2a2dc376
3,611,682
def get_crypt_key(): """ Lazily generate the crypt key and return it """ # pylint: disable=global-statement global __CRYPT_KEY__ if not __CRYPT_KEY__: __CRYPT_KEY__ = _get_system_uuid() return __CRYPT_KEY__
b95972e33deb86450295da8440a6fe9213b3aed3
3,611,683
def index(): """ Parameters: ---------- None. Returns -------- A rendered version of index.html and a http response code 200 The function renders the index page for the app """ global core_module if not core_module: core_module = core_module() ...
897b29517b9f8e566cd853eb81c529c3aac78001
3,611,684
def fpH(pH, c_Na, c_acide): """ Calcule la valeur de la fonction dont la racine correspond à l'équilibre de la solution. Entrée : pH c_Na (mol/L) c_acide (mol/L) Sortie : valeur de la fonction """ Ke = 10**(- pKe) Ka = 10**(...
7ece0157f041057344239f0901f50c62dbc34719
3,611,685
def detect(source, config=None, path=None): """Analyze and detect minimum versions from source code. A default config will be used if it isn't specified. If path is specified, it will occur in errors instead of the default '<unknown>'. """ visitor = visit(source, config, path) if isinstance(visitor, SourceVis...
a71d576c877aa1ed9284b40f7047926833a5da98
3,611,687
def set_coredump_network_config( host, username, password, dump_ip, protocol=None, port=None, host_vnic="vmk0", dump_port=6500, esxi_hosts=None, credstore=None, ): """ Set the network parameters for a network coredump collection. Note that ESXi requires that the dump...
a047c3f4c5ed866c34fd65c10cb251d04bbb3f52
3,611,688
def Verification(verification_list, value): """ Essa função verifica se algum jogador já venceu a partida, retorna um valor booleano que determina o próximo jogador. :param verification_list: :param value: :return bool: """ cont = 0 # define um contador. for i in DIM.WIN: # verifi...
f90b6c53a385d409d6b2f973d7bac61d6dc58529
3,611,689
import json def train_agent(env_config_path, agent_config_path, num_episodes): """train agent""" f1, f2 = open(env_config_path), open(agent_config_path) env_config, agent_config = json.load(f1), json.load(f2) env, agent = config(env_config, agent_config) evaluation = MyEvaluation(env, agent, outpu...
e02e20491c068bd9fb8c403ce74fb47eae07121e
3,611,690
def add_CRUD_pset(pset, sm, model_name): """Adds the ServerModel CRUD function to the Primitve Set Parameters ---------- pset : PrimitiveSet the primitive set for adding the controller functions sm : ServerModel the ServerModel with the CRUD functions model_name : str ...
f0960c3b96789adfa2e56039ca7c072819438984
3,611,691
def to_litres(gallons): """Convert US gallons to metric litres""" return 3.78541 * gallons
d1a7be6f01c89b848128218cbec19913e76658cd
3,611,692
import requests def get_nioshtic_wikidata_mapping(): """ Retrieves a mapping between NIOSHTIC and Wikidata identifiers from the Wikidata Query Service, query.wikidata.org @return dictionary {nioshtic: {identifier_label: value}} """ prefix = 'http://www.wikidata.org/entity/' q = ( ...
7216f8ed354bb394e39ceb906d41e19d1e41e589
3,611,694
import uuid from datetime import datetime def create_new_fabric_person_from_token(headers, check_unique=False): """ Extract info from identity token and create a FabricPerson entry for this person, including a new UUID. Return a PeopleLong based on that info. :param headers: request headers with cooki...
83f76bec65c644aaf79708d33d98a43d64806a05
3,611,695
def _gsspp(X,p,n,fun=ss): """ Generalized Spatial Sign Pre-Processing for Centred Data """ return(np.multiply(X,fun(_norms(X),p,n)))
bfa85e78bdffed7e152dbde1c9590f5bee52dd40
3,611,696
import random import copy def distr_labeldata_unequal(label_data, num_workers): """ Idea: 1. For each label, distribute disproportionate allocation to workers. 2. Apply the worker's allocation to label_data and store in distr_labeldata, where the keys are workers and the values are the labeled...
dab112ba98e9d5d68fbb519f1c7e3f2a6ea24e17
3,611,697
def random_conv_encode(k, generator_matrix, memory, p=0.5): """ Generates a random sequence of k-bits, each Bernoulli(p) and then encodes them convolutionally. Returns the original sequence, and the convolutionally encoded one, using the generator matrix and memory. """ message_bits = generate_random_binar...
1419fcda911f0d52161b0e8091ef076e86efc1b7
3,611,699
import json def readJsonTextarea2(request): """JSONでの応答練習""" template = loader.get_template('practice/json-textarea2.html') # ---------------------------- # 1 # 1. host1/webapp1/templates/practice/json-textarea2.html を取ってきます # ...
df428a65fbd0e29801e4aeb2f11226ae251a2928
3,611,700
def _smart_fusion_strategy(ents): """This strategy adds the entities scores if one entity occurs multiple times with the same tag, and afterwards applies the fusion strategy.""" deduplicated_ents = [] for idx, ent in enumerate(ents): next_ent = ents[idx + 1] if idx + 1 < len(ents) else None ...
7b1fd80fe7a7feec69502fc240c045bca9f722cf
3,611,701
def bayesian_regret(voters, winner): """ Calculate bayesian regret voters : array (a, n) Voter preferences; n-dimensional voter cardinal preferences for n issues. winner : array shape (n) Winner preferences for winner and `n`-dimensional issues. """ voters =...
faf1d9e4b16c410665be4179bceeeca7339f6fba
3,611,702
def run(process_class, *args, **inputs): """ Synchronously (i.e. blocking) run a workfunction or process. :param process_class: The process class or workfunction :param _attributes: Optional attributes (only for process) :param args: Positional arguments for a workfunction :param inputs: The li...
44dc23b378b51bb30b3bba74558df909083a60e8
3,611,703
from datetime import datetime def plotter(fdict): """ Go """ pgconn = get_dbconn('coop') ctx = get_autoplot_context(fdict, get_description()) station = ctx['station'] t1 = ctx['t1'] t2 = ctx['t2'] table = "alldata_%s" % (station[:2],) nt = NetworkTable("%sCLIMATE" % (station[:2],)) ...
8313ed7cb5da0a607f194b874ad23aa3a7de606c
3,611,705
def cu_projection(param: str, date: date, cu_projections) -> int: """ Get the Columbia model's prediction of the param for the date """ scenario = cu_model_scenario(tuple([s for s in cu_projections.keys()])) quantile = cu_model_quantile() # Extract quantiles of the model distribution xs...
16e240e1553b52c2fdd60e46fe55b3c18b4b7b71
3,611,707
def dicthash(d:dict)->Hash: """ Calculate hashsum of a Python dict. Top-level fields starting from '_' are ignored """ string="_".join(str(k)+"="+str(v) for k,v in sorted(d.items()) if len(k)>0 and k[0]!='_') return md5(string.encode('utf-8')).hexdigest()
39adff8a7cec0ec70695013332db9eed5b03b0ab
3,611,708
def _urlparse_qs(url): """ Parse a URL query string and return the components as a dictionary. Based on the cgi.parse_qs method.This is a utility function provided with urlparse so that users need not use cgi module for parsing the url query string. Arguments: :type url: str :param ur...
3516b35f814d5bf9a549540858d632cfb0a99e17
3,611,709
def erfc_inverse(x): """ erfc-1(x) = - 1/sqrt(2) * normal_quantile( 0.5 * x)""" return -0.70710678118654752440 * normal_quantile(0.5 * x)
f1994c8fdee5ae94624562210fe4621594636204
3,611,710
def extract_8_statistical_features(data): """ Extract 8 statistical features: mean, standard deviation, length, minimum val, first quartile, second quartile, third quartile, maximum val :parameter data: pandas DataFrame of the data who...
9aae0c143fd0eb1183fa77e7cb86d3806d73cd99
3,611,711
import array def bin_stats(x, y, xbins, stat='average'): """Given the variable y=f(x), and the bins limits xbins, return the corresponding statistics, e.g. <y(xbins)> Options are rms, median y average """ nbins = len(xbins) if stat == 'average' or stat == 'mean': func = mean elif sta...
ea97d56cde01bfa4ebd7eaf4d0c53a5f2d48c4c8
3,611,712
from typing import Sequence def all_unique(lst): """Returns True if all elements of Sequence `lst` are unique. False otherwise. """ assert isinstance(lst, Sequence) return bool(len(set(lst)) == len(lst))
546d4254d5ca287952eec6af2bda048e60bb6b89
3,611,713
def ingredient_fractions_predictor() -> IngredientFractionsPredictor: """Build a Ingredient Fractions predictor for testing.""" return IngredientFractionsPredictor( name='Ingredient fractions predictor', description='Computes total ingredient fractions', input_descriptor=formulation, ...
934ab59171ceb3bd2227092ab3e5eea300884d95
3,611,714
def record_fuzz_target(engine, binary_name, job_type): """Record existence of fuzz target.""" if not binary_name: logs.log_error('Expected binary_name.') return None project = data_handler.get_project_name(job_type) key_name = data_types.fuzz_target_fully_qualified_name( engine, project, binary_n...
5b88599944eeb74c2da43d395e9877d4e9d7eba9
3,611,715
def svm_loss(x: NPArray, y: NPIntArray) -> tuple[float, NPArray]: """ Computes the loss and gradient using for multiclass SVM classification. Inputs: - x: Input data, of shape (N, C) where x[i, j] is the score for the jth class for the ith input. - y: Vector of labels, of shape (N,) where y[i...
e5d8709d3323e9a8dacc3ed7344c6208fdbcfefc
3,611,716
def make_constellation(config): """Builds the constellation model.""" n_caps = 3 encoder = SetTransformer( n_layers=4, n_heads=4, n_dims=128, n_output_dims=32, n_outputs=n_caps, layer_norm=True, dropout_rate=0., ) decoder = ConstellationCapsule( n_caps=n_caps...
a250df9a70be5637eee079e1471e3a4baa2f3ba9
3,611,717
def scale_matrix( factor: float, origin: np.ndarray = None, direction: np.ndarray = None ) -> np.ndarray: """ Return matrix to scale by factor around origin in direction. Use factor -1 for point symmetry. """ if direction is None: # uniform scaling M = np.array( ...
92b000567245b4cf7732ee66ffd32e389fbf365c
3,611,719
def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs): """ Plot horizontally Args: data: DataFrame of data cols: columns to be plotted wspace: spacing between plots plot_kw: kwargs for each plot **kwargs: kwargs for the whole plot Returns: axes for p...
dc3f62442da33f3bc45df70ec0e6ee41cab658ab
3,611,720
def generate_average_csv(fname, fields, trait_list): """ Generate CSV called fname with fields and trait_list """ csv = open(fname, 'w') csv.write(','.join(map(str, fields)) + '\n') csv.write(','.join(map(str, trait_list)) + '\n') csv.close() return fname
43195ea054ea537a4860c07c03c96efc263c472f
3,611,721
from typing import Set def get_s2_patches_with_no_19_class_target() -> Set[str]: """ List all patches from the BigEarthNet-S2 dataset that have _no_ defined classes with the 19-class nomenclature. Note: This set still includes patches with snow, clouds, or shadows. To re-build the file, it is ne...
9132457f706df6dfe2f538a25210c936d528d565
3,611,723
import torch from typing import Tuple from typing import List def winnow_model(model: torch.nn.Module, input_shape: Tuple, list_of_modules_to_winnow: List[Tuple[torch.nn.Module, List]] = None, reshape=True, in_place=False, verbose=False): """ This API is used to winnow a model w...
41643e9bb832669293220693282d2232b7ae321a
3,611,724
import tqdm def get_expr_dict(input_tuple): """Returns the quantification results as a dict of dicts.""" bamfname, contig, start, stop, length, worker_ind = input_tuple if worker_ind == None: worker_ind = 0 if contig is None: desc_str='all_reads' else: desc_str='chr_'+contig region = dict( ...
036f8f683e32c189ca64be0e2b8a7a2b4564bfd2
3,611,725
def arg_parsing(req): """ :type req: class 'ow_lander.srv._Grind.GrindRequest' """ if req.use_defaults : # Default trenching values x_start = 1.65 y_start = 0.0 depth = 0.05 length = 0.6 parallel = True ground_position = constants.DEFAULT_GROUND_HEIGHT else : x_start = req...
981d0faca672fe5d508dde24cef24500f0885ca5
3,611,726
def adjacency_lattice_square(sidelength, num_cells, search_radius, periodic_bc=False): """ periodic_bc: wrap around boundary condition (False default) """ assert num_cells == sidelength ** 2 adjacency_arr_uptri = np.zeros((num_cells, num_cells)) # build only upper diagonal part of A for a in...
4fedf6dffc6b9fe92bf164d8a2ae8a176126f026
3,611,727
import math def determine_aha_part(seg_sa, affine_sa, three_slices=False): """ Determine the AHA part for each slice. """ # Label class in the segmentation label = {'BG': 0, 'LV': 1, 'Myo': 2, 'RV': 3} # Sort the z-axis positions of the slices with both endo and epicardium # segmentations X, ...
0fe5f26f172a9fc77fcfb98b562b583760982949
3,611,728
def swap_scientific_notation_float(line: deque, precision: int) -> deque: """ Returns a deque representing 'pycode_as_deque' with any python floats that will get "cut-off" by the 'precision' arg when they are rounded as being rendered as strings in python's "e format" scientific notation. A float ...
8ddc47cff96a98309f6c646769116e26e6c693db
3,611,729