content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import csv def get_first_last_onset(csv_file): """Gets the first and last onset times.""" with open(csv_file) as f: full_track = list(csv.reader(f)) first_onset = float(full_track[0][0]) if first_onset < 0: first_onset = abs(first_onset) # we only store the first onset if it is ...
d567530abf15fa5e256f7f826a813ad5982e3b0e
3,610,567
def extractBivectorParameters_complicated(B): """ B must be a general rotation object on the format $ \phi*P + t n_{\inf}} $ """ omega = float(B | E0) phi, P, t_par, t_nor = extractBivectorParameters(B - omega * E0) return phi, P, t_par, t_nor, omega
cede286088241caf8a2e28b009ae23a7295a85ec
3,610,568
def ionic_strength(c,z): """Compute ionic strength from charges and concentrations Arguments: c: bulk concentrations [concentration unit, i.e. mol m^-3] z: number charges [number charge unit, i.e. 1] Returns: float: I, ionic strength ( 1/2 * sum(z_i^2*c_i) ) [concentration unit, i.e. mol m^-3]...
4abe692e499f17d1d38feac48842cc2f3494becb
3,610,570
from typing import Type def sign_extend_3(val, width, tmp): """ Sign extension. High-order bit of val is left extended. :param val: VexValue :param width: VexValue :param tmp: VexValue of 0xffffffff """ mask_sign_bit = (1 << (width-1)).cast_to(Type.int_32) cond_sign_bit_1 = ex...
6bd958e700a25eee3b7dfdaafbab49ede8ca0b45
3,610,571
def __check_if_alive(processes): """ Quickly check if at least one of the list of processes is alive. Returns True if at least one process is still running. """ c = set([x.exitcode for x in processes]) return None in c
22458fa4b2ca07fe8c1c21a60eac87d6546f8abd
3,610,572
def previous_next_placement(doc_filter: DocumentFilter) -> pd.DataFrame: """ Calculate mu teamPlacement before and after a teamPlacement. :param doc_filter: Input DocumentFilter. :type doc_filter: DocumentFilter :return: Previous and next expected placement based on current placement. :rtype: p...
a8585550ec39e6572c5a447d2c17787d821616d0
3,610,573
def prices_to_returns(prices: pd.DataFrame, log: bool = False): """ Calculate the returns given prices. Parameters ---------- :param prices: pd.DataFrame A pandas DataFrame with asset prices :param log: bool Whether to compute logarithmic returns Default is False -> line...
ce01815e530e634daa9500913d073afee1f1fdb9
3,610,574
def check_array(arr: Data) -> np.ndarray: """ Utility function for checking and validating input arrays. """ # Check array type if isinstance(arr, (pd.DataFrame, pd.Series)): arr = arr.to_numpy() elif sparse.issparse(arr): arr = arr.toarray() elif isinstance(arr, np.nd...
8bdb541c1cc92a3c1c22d0570aa5cc773f0ef13a
3,610,575
def _SeriesFactory(ser): """ Return an instance of the appropriate subclass of _BaseSeries based on the xChart element *ser* appears in. """ xChart_tag = ser.getparent().tag try: SeriesCls = { qn("c:areaChart"): AreaSeries, qn("c:barChart"): BarSeries, ...
e0ca78113a68e363c4f3de7acb9086a156fddf47
3,610,576
from typing import Union from typing import Any from datetime import datetime def create_access_token( subject: Union[str, Any], expires_delta: timedelta = None ) -> str: """Encodes a JWT Args: subject (Union[str, Any]): The content of the JWT. expires_delta (timedelta, optional): The JWT...
e4301ca6eed32e5bd417d65fd5caf0483fcd17fb
3,610,577
def n_mat_propostas(votadas = True): """ Recebe um boleano que define se o retorno. Se votadas for verdadeiro retorna um dicionário cuja chave é o nome do parlamentar e o conteudo é o número de matérias propostas, pelo parlamentar, que foram votadas. Se votadas for falso retorna um dicionário cuja chave é o nome...
12c06ed57e0608ad27af555ac5de7d54f1e32ef3
3,610,579
def CreateDictionary(name_fmt, codeset, src_dir, out_dir, wrapper=None): """Creates a dictionary used for configs.""" exports = {} if wrapper is None: wrapper = lambda c: c for code_class in registry.classes.values(): def Closure(code_class): def Registerer(src, *args, **kwargs): codeset.a...
47bd7c991a5b044b517c023d4199f6700079f0e8
3,610,580
import glob def test_data_list() -> list: """Return the list of paths to the test input data files Parameters: None Returns: list: The list of paths to the test input data files """ return glob.glob("test_data/*.rws.gz")
da3362910d0727fb21f433b34a77ad437ea0ccb1
3,610,581
def test_module(client, params): """ Returning 'ok' indicates that the integration works like it is supposed to. \ Connection to the service is successful. Anything else will fail the test. :param client: client to use :param params: parameters obtained from demisto.params() """ res = clien...
ddf10c97b841f00044d9cc11d04b8725e134d8cf
3,610,582
def _url(data={}): """Helper method to generate URLs.""" data = "&".join(["{}={}".format(name, value) for name, value in data.items()]) return "{}{}locative?{}".format(HTTP_BASE_URL, const.URL_API, data)
09fa191aa45ab4c90390eb99962ba40930531f32
3,610,583
def model_from_json(json_string, custom_objects=None): """Parses a JSON model configuration string and returns a model instance. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> config = model.to_json() >>> loaded_model ...
ea22de5736876edd252d25713ffc02a0abffce57
3,610,584
def route_vm_logic(logicFn): """ Decorates a function to indicate the viewmodel logic that should be executed after security checks and business logic passes. :param logicFn: The viewmodel logic function to assign. :return: The decorated function. """ def decorator(fn): fn.route_vm_...
6dcbd274bd35b34f9faffb455d121940821cfa04
3,610,585
def format_obs_ensemble(obs_ensemble, obgnme): """ Reformat observation ensemble. Parameters: =========== obs_ensemble: pd.DataFrame, the observation ensemble Returns: =========== obs_ensemble: pd.DataFrame, the observation ensemble after new format. """ obs_ensemble.index =...
898e6022297616dbd91d96067d883666c932bfa1
3,610,586
from typing import Iterable def to_ideogram_html_str(gene_symbols: Iterable[str]) -> str: """Get an Ideogram HTML document as a string.""" annotations = get_ideogram_annotations(gene_symbols) logger.info("using %d annotations in ideogram", len(annotations)) return get_ideogram_template().render(annota...
27977573f3d64d5c35bd0f69c61e0c3aff82a75e
3,610,587
import struct def read2byte(i2cBus: SMBus, i2cAddr: int, lowByteAddr: int, highByteAddr: int) -> int: """ Read two byte from i2c Bus by using SMBus library :param i2cBus: SMBus instance :type i2cBus: SMBus :param i2cAddr: i2c address, a one byte address :type i2cAddr: int :param lowByteAd...
9a97dd7242930d10298834bb24702da21c29f019
3,610,588
import inspect def typechecked(f): """ Use the @typechecked decorator on a function to perform run-time typechecking. The docstring for `check_type` describes how type annotations should look. """ argspec = inspect.getfullargspec(f) annotations = f.__annotations__ @wraps(f) def g(*args...
0801bb4e418fdc06c9293e6118ffc002b6bbc23f
3,610,589
def top_k_incidence_decision(k: int = 3) -> IncidenceDecisionFunctionType: """Select exactly k subjects with highest probabilities. Chooses random subjects if less than k subjects have positive probability. Parameters ---------- k: int the maximum number of subjects that are selected and r...
56197f0254292be06c285f63bd3c6eb24045dde8
3,610,590
def draw_turn(row, column, input_list, user): """ Draw the game board after user typing a choice. Arguments: row -- the row index. column -- the column index. input_list -- a two dimensional list for game board. user -- the user who type the choice Returns: input_list -- a two ...
6f44e770a2fa04b5992ffd21cad5a799c3423de5
3,610,591
import math def normal_vec(triplet): """ Return the unit normal vector to the plane defined by a triplet of atom positions [[x1,y1,z1],[x2,y2,z2],[x3,y3,z3]] """ p1 = [triplet[0][0], triplet[0][1], triplet[0][2]] p2 = [triplet[1][0], triplet[1][1], triplet[1][2]] p3 = [triplet[2][0], triplet[2...
0d4a13814f75a1747544f348b5e78a0d758b480c
3,610,592
def t_from_CT(SA, CT, p): """ Calculates *in-situ* temperature from Conservative Temperature of seawater. Parameters ---------- SA : array_like Absolute salinity [g kg :sup:`-1`] CT : array_like Conservative Temperature [:math:`^\circ` C (ITS-90)] p : array_like ...
5ddd89c39ee100c3c114f1886d39284feda6587d
3,610,593
import socket def is_open_port(port): """ Check if a port is open (listening) or not on localhost. It returns true if the port is actually listening, false otherwise. :param port: The port to check. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex...
4eb8f52744cc7f330dd101b613d5db4ab8d0d0fc
3,610,594
def hashid(obj, suffix=""): """ Returns a per-class unique hash that combines the object's class name with its idnum and creation time. This makes this id unique also between different typeclassed entities such as scripts and objects (which may still have the same id). """ if not obj: ...
511403801d81576e8f07999e4b27befd5b7429a6
3,610,595
def window_indices(frame, window=30, center=None, **kwargs): """ Get the linear indices for each satellite spot Parameters ---------- frame : ArrayLike image frame window : float, Tuple, optional window size, or tuple for each axis, by default 30 center : Tuple, optional ...
646b92c0a2b057ffb8bc50c6f4d9adc9542c43c8
3,610,596
def open_pbobject(path, pb_class, verbose=True): """Load JSON as a protobuf (pb2) object. Any calls to load protobuf objects from JSON in this repository should be through this function. Returns `None` if the loading failed. Parameters ---------- path: str JSON file path to load p...
d920919086ebd40f9d0e711b8475ebd2ac8d259e
3,610,597
def _is_table(client, dataset_id, table_id, project_id): """Check whether a `table_id` is a view or not.""" if (dataset_id is None) or (table_id is None): return False dataset_ref = bigquery.DatasetReference(project_id, dataset_id) table_ref = dataset_ref.table(table_id) table = client["b...
cf355e9d3d332b30e0cb11f6c9880960de431567
3,610,598
def class_name(n): """ Formats a valid C# class name from the name format used in the XML. @param n: The class name to format in C# style. @type n: string @return The resulting valid C# class name @rtype: string """ if n == None: return None try: return native_types[n] ex...
4bd999c25ee2a51192668bee6534d300241652d9
3,610,599
import torch def batched_soft_nms(boxes, scores, idxs, method, sigma, threshold): """ Performs soft non-maximum suppression in a batched fashion. Each index value correspond to a category, and NMS will not be applied between elements of different categories. Args: boxes (Tensor[N, 4]): ...
ebe231fe2114fa437b01ac8fc0e05ddd10fe20a1
3,610,600
import re def match_id(url): """匹配歌单ID""" try: res = re.findall('id=(\d{4,12})', url) return res[0] except Exception as e: pass return None
8a84cfe0ca0ebea154c451064ce838d4816e62d6
3,610,601
def decompress_files(filepaths, remove=False): """ This function ... :param filepaths: :param remove: :return: """ # Initialize a list for the decompressed file paths new_paths = [] # Loop over the files for filepath in filepaths: # Get the name of the file fi...
a17134badfe9b259fdc599ec47ee294b40060951
3,610,603
def new_combo_column(title, data_func=None, changed_callback=None, edited_callback=None, editing_started_callback=None, editing_canceled_callback=None, spacing=0, visible=True, resizable=True, sizing=1, fixed_width=-1, min_width=-1,...
035fc4ebee4cc8cefe163c94ddaf4569da2facfb
3,610,604
import contextlib import sqlite3 def query_summary(fname): """Query and opsim database for visits Args: - fname :: the name of the sqlite3 database file Returns: a named tuple with the summary and proposal tables """ table_contents = [] with contextlib.closing(sqlite3.connect(f...
d2ae294e35ce6ccc5815a9a812a5e24d9ed7f0ac
3,610,605
def prepare_pcoa(pcoa, number_of_features): """Selects top N biplot features by magnitude (coped from q2-emperor). Parameters ---------- pcoa : skbio.stats.ordination.OrdinationResults number_of_features : int Returns ------- skbio.stats.ordination.OrdinationResults """ feats =...
c5403b554ae40a1740733a2b6d9e6a61d8794b2b
3,610,607
def _jupyter_bundlerextension_paths(): """ Entrypoint for Jupyter Notebook Bundler Shows up in the 'Download' menu on Jupyter Classic Notebook """ return [{ 'name': 'chrome_pdf_export', 'label': 'PDF via Chrome (.pdf)', 'module_name': 'nbpdfexport.bundler', 'group': ...
1d948a5eed6f4240e760c52bec776c3fbf291f14
3,610,608
def DecodeVigenereLongueurCle(message, mot=3): """ Cette fonction determine la longueur de la clé, elle repère les groupes de trois lettres qui se répète dans le message codé et suppose qu'il y a une très forte probabilité qu'un même groupe de trois lettres soit codé avec les mêmes trois lettres du ...
3ee2f974e82e9cb30d049bfd4550305605950815
3,610,609
def median(data_list): """ Finds the median in a list of numbers. :type data_list list """ data_list = list(map(float, data_list)) length = len(data_list) data_list.sort() # Test whether the length is odd if length & 1: # If is is, get the index simply by dividing it in half...
c41a1336d17e5e991101bd91c9c56cb59624dc82
3,610,610
import functools def on_package_attributes(**attr_dict): """Decorator: executes instance function only if object has attr valuses. Executes the decorated method only if at the moment of calling the instance has attributes that are equal to certain values. Args: attr_dict (dict): dictionary m...
9c3f4be4bbe02d0d70b97ae5d9437480262b5e79
3,610,611
def filelineno(): """ Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file. """ if not _state: raise RuntimeError("no active input()") retur...
d5c86e0c2232b35fa5b714226f832449b60c5b63
3,610,612
def create_dual_point_kernel(size, distance_apart, padding=0): """Generates a square float image with two, single-pixel point sources. The top source has double the intensity of the bottom source. The sources are distributed along the vertical center and are spaced a set distance apart. :param size...
ebbfdc6d3843ba3f4b05f2c616ba1d123dd86a55
3,610,613
def auc(actual, posterior): """ auc """ r = tied_rank(posterior) num_positive = len([0 for x in actual if x == 1]) num_negative = len(actual)-num_positive sum_positive = sum([r[i] for i in range(len(r)) if actual[i] == 1]) auc = ((sum_positive - num_positive * (num_positive + 1) / 2.0) /...
cc3822ede98c25e89cabd9d25fc2218ff42b4e4e
3,610,614
from django.test import SimpleTestCase as TestCase from django.test import TestCase def is_django_unittest(item): """Returns True if the item is a Django test case, otherwise False""" try: except ImportError: if sys.version_info < (3, 0): return (hasattr(item.obj, 'im_class') and ...
13702023578bf029ea9d130114b13dff26592f3e
3,610,615
def parametrized(f): """Is this function or object decorated with @parametrize or @matrix?""" return Mark.marked(f, PARAMETRIZED) or Mark.marked(f, MATRIX) or Mark.marked(f, DEFAULTS)
b4cf00ab71a365a477678a11a276ece8248e5fcb
3,610,616
import asyncio def analyze_body(sdf, address=("127.0.0.1", 11346)): """ Single body analyzer. Opens a new connection, analyzes the body, and returns the result. If you already have a manager running doing other things, create an instance of `BodyAnalyzer` instead. :param sdf: SDF object consi...
2b75241c6aedd0bac524eadbcd3968caf57f021a
3,610,617
def cmd_trade_info(strategy: Strategy, strategy_trader: StrategyTrader, data: dict) -> dict: """ Get trade info according data on given strategy_trader. @note If trade-id is -1 assume the last trade. """ results = { 'messages': [], 'error': False } trade_id = -1 ...
eb89294444f28a80eff8f1527a048341d17bc88c
3,610,618
def drift_confidence(df_resample, out_path, fps, pca=1, save_fig=0): """ Args: df_resample: out_path: fps: pca: save_fig: Returns: """ if pca: flow_key = 'diffflow_pca' acc_key = 'acc_pca' else: flow_key = 'diff_flowx' ac...
e3dce48e9747c4f22ee71f4029faa16cd6864c75
3,610,619
def power_factor(s: np.ndarray) -> np.ndarray: """Given a numpy array of complex values, compute power factor. If the power factor is lagging, a positive value will be returned. If the power factor is leading, a negative value will be returned. Reference: Power System Analysis and Design, 5th Edit...
0cc50fdeaa485e1194c2ab897322963a9b1a39a1
3,610,620
def pad_factor(input_image, spatial_dims, factor): """Pad `input_image` (N,C,H,W) such that H and W are divisible by `factor`.""" if isinstance(factor, int) is True: factor_H = factor factor_W = factor_H else: factor_H, factor_W = factor H, W = spatial_dims[0], spatial_dims[1] ...
7b07bf7fcca5f05ecdd47420ac2493b7aed37277
3,610,621
def zeropad(data, m=2): """Pad with zeros to make an array with an even multiple of m voxels in all dimensions """ if data.ndim < 2 or data.ndim > 3: raise RuntimeError('Unsupported number of dimensions {}. We only supports 2 or 3D arrays.'.format(data.ndim)) if data.ndim == 2: ...
43cf2e5974b4ad0b64e998d33bd9faf724d51300
3,610,622
def h2fk5(rh, dh, drh, ddh, pxh, rvh): """ Wrapper for ERFA function ``eraH2fk5``. Parameters ---------- rh : double array dh : double array drh : double array ddh : double array pxh : double array rvh : double array Returns ------- r5 : double array d5 : double...
108e3f241bce70ed5dc6a6d6c36ca44b13d352d1
3,610,624
def Connect(*args, **kwargs): """Factory function for connection.Connection.""" return connection.Connection(*args, **kwargs)
9b65dcd4fb73af1e52fa4dffa7b91cfc58532730
3,610,625
def solve_lp_puzzle(lp, boxsize): """Solve a linear program Sudoku and return puzzle dictionary.""" lp.simplex() for col in lp.cols: col.kind = int lp.integer() return lp_to_dict(lp, boxsize)
b4ceee41dddbb74adc6be96ae31b762cd46ce582
3,610,627
def show_error_info(title, message, unknown_error=False, netflix_error=False): """Show a dialog that displays the error message""" prefix = (30104, 30102, 30101)[unknown_error + netflix_error] return xbmcgui.Dialog().ok(title, (common.get_local_string(prefix) + '\r\n' + ...
a0e2f5971debf94d0cbc6032126a9966ad3dd840
3,610,628
def is_token_expired(token): """Checks if given token is valid""" try: decoding = jwt.decode(token, config['jwt_secret'], config['jwt_algorithm']) return False except jwt.ExpiredSignatureError: return True
30bfc86d5b4d516b0257fa58755c51264dd2ec24
3,610,629
import re import csv def _getIdsFromQuery(queryString, syn, downloadLocation): """Helper function that extracts the ids out of returned query.""" if re.search('from syn\\d', queryString.lower()): tbl = syn.tableQuery(queryString, downloadLocation=downloadLocation) check_for_id_col = filter(l...
3f38f02c01c87932317d1241645dca6fac3b484e
3,610,630
def get_sshkey(sshkey): """ Get start ip for ip range CLI Example: .. code-block:: bash salt 'maas-node' maasng.get_sshkey sshkey salt-call maasng.get_sshkey sshkey """ try: return list_sshkeys()[sshkey] except KeyError: return {"error": "SSH key not found ...
774edde0d7f3e63b81d5365b7226599e979e1de7
3,610,631
from pathlib import Path from typing import Dict def process_image(in_img_path: Path, out_img_dir: Path) -> Dict[Path, Path]: """ Extract EXIF data from image and return path mapping """ with open(in_img_path, "rb") as image_file_stream: image = Image(image_file_stream) if hasattr(image, "date...
454f8a5ffec9ea06435bfd7bc9bbfcbc0de82687
3,610,632
def get_vars_maybe_avg(var_names, ema, **kwargs): """utility for retrieving polyak averaged params.""" vars_tf = [] for vn in var_names: vars_tf.append(get_var_maybe_avg(vn, ema, **kwargs)) return vars_tf
0e35821d8883031dceca0e05d31b792c92adbd78
3,610,633
from typing import List from typing import Tuple def open_files( file_names: List[str], mode: str = "readonly" ) -> Tuple[List[fits.HDUList], List[np.ndarray]]: """Gets the HDULS and data handles for all the files in file_names. This is a convience function to opening multiple FITS files using m...
c26a9f9d6348c6279851aeb4993f79682c7c0838
3,610,636
def multi_to_single(y, combinations): """Convert multilabel indices to singlelabel strings.""" single = [] for y_i in y: y_i_str = ", ".join([str(i) for i in y_i]) single.append(combinations.index(y_i_str)) return single
7e8839173b047cb0bb89d143ce2b30b928630f2d
3,610,637
def _parse_taxa_report(local_path, **kwargs): """Return a dict of taxa_name to read_counts.""" out, abundance_sum = {}, 0 with open(local_path) as taxa_file: for line_num, line in enumerate(taxa_file): line = line.strip() tkns = line.split('\t') if not line or len...
b3b18010820dbc409b66c8c1d5636430c052382d
3,610,640
def build_conservation_status_message(data: list[str]) -> str: """ Builds a string describing the conservation status of the species. :param data: Data containing conservation status information :return: Description of the conservation status (or empty if no data) """ if data: return CON...
7457234d64300baa42047067d81799881a406ff8
3,610,641
def get_col_reduced_right(A, symb, T = None, return_internals = False): """ Takes a polynomial matrix A(s) and returns a unimod Transformation T(s) such that A(s)*T(s) (i.e. right multiplication) is col_reduced. Approach is taken from appendix of the PHD-Thesis of S. O. Lindert (2009) :args: ...
77a499f272848afedd6a6869fa6166c993e4e9ae
3,610,642
def ivarName(value, position): """A name of a class.""" if not value[0] == '_' or not value[1].islower(): return Error( 'BadInstanceVariableName', 'Instance variable names start with _ and not be capitalized', position, LINES) return None
1ba3d34a949aaf6d2bee235fe8885fac827f0f9a
3,610,643
def verilog_value_to_int(verilog_value): """ Convert VerilogValue model to width, value, value_format """ width = None if verilog_value.plain_decimal: return width, int(verilog_value.plain_decimal), ValueFormat.PLAIN if verilog_value.width: width = int(verilog_value.width) if veri...
e8d1c938cea56b8cd3277f445dd5d6eb85de60eb
3,610,644
import random def create_quiz_form(quiz): """Create quiz form with all its question choices, shuffle the choices for quiz page""" form = QuizForm() for i in range(10): form.questions[i].answers.choices = [ quiz.questions[i].correct_answer, quiz.questions[i].wrong_...
56c73d48532df049aec2f2c78d0ae35c89351cd7
3,610,645
from typing import Tuple def drop_zeros_ctg(fhr: np.array, uc: np.array, time: np.array) -> Tuple[np.array, np.array, np.array]: """ Removes all missingvalues, encoded as zeros Args: uc, fhr signals: (np.arrays) 1D signals time: (np.array) 1D time signal Output: Tuple(n...
19f0d90a5cf08057b08186754c262afe9d16d294
3,610,646
def report_and_reset_timings(): """Returns the pass timings report and resets the LLVM internal timers. Pass timers are enabled by ``set_time_passes()``. If the timers are not enabled, this function will return an empty string. Returns ------- res : str LLVM generated timing report. ...
76fabaca3e99823182d1c6623e7c01126966c856
3,610,647
from typing import Union from typing import Iterable def transform_coords(x: Union[DataArray, Dataset], targets: Union[str, Iterable[str]], graph: GraphDict, *, rename_dims: bool = True, keep_aliases: bool = True,...
b8777248c7ff4313f239a91a5ec5c6001ba0835c
3,610,648
def Answer_f(text): """ :param text: The "text" of this Answer """ return '\\begin{block}{Answer}\n' + text + '\n\\end{block}\n'
2de98b286d31e31f2b934760f715af1ecda83daa
3,610,649
def gather_states(ii): """ Return the current state (position/probability/bias) of walkers in a given window. Parameters ---------- ii : integer The index of the umbrella to get the state of. Returns ------- state : list The state of window ii. """ retu...
46b2f3db3ff71fbca2f1b54b39f627f32e3a5ff5
3,610,650
def word_embeddings_rbo(list1, list2, p, index2word, word2vec, norm): """Complete RBO analysis (lower bound, residual, point estimate). ``list`` arguments should be already correctly sorted iterables and each item should either be an atomic value or a set of values tied for that rank. ``p`` is the proba...
5fc29129d4722dc7381c6edbc6df465d993f0528
3,610,651
def drop_na_inputs(*, input_data: pd.DataFrame) -> pd.DataFrame: """ Check model inputs for na values and filter them based on the ones the model knows how to handle. """ validated_data = input_data.copy() new_vars_with_na = [ var for var in config.model_config.inputs if...
0b757add023c34c8f081d58e56f01da59dc87ca4
3,610,652
import re import json def geojsonfeature(source, params=''): """ :params: A string with the following optional tokens: "properties:field:srid" """ parse = re.search(r'(?P<properties>((\w+)(,\w+)*)?)(:(?P<field>(\w+)?))?(:(?P<srid>(\d+)?))?', params) if parse: parse = parse.gro...
4fd0e2e8d9d461ff2775dd21ce39fceca1905118
3,610,653
def expected_return_time(M, backward=False): """Find the expected returning time. Parameters ---------- M: :class:`~numpy.ndarray` (dimension n x n, where n is the cell number) The transition matrix. backward: bool (default False) Whether the backward transition will...
2a0963e20c09f92f7e1ae2177d4277f589052620
3,610,654
def att_moment_metric(mass, att_moment): """ This function calculates the metric for the attitude moment. It does not consider moments of inertia for the satellite, nor passive sources of moment :param mass: :param att_moment: :return: """ return np.float64(1.25 * (att_moment / mass)).cl...
87ac22c1ddd58aa257fa4485fbd48189599215ce
3,610,655
from typing import Sequence from typing import Dict def get_largest_area(rect: Rect, points: Sequence[Point]) -> int: """Find the largest bounded area around all the points. This basically is creating a voronai using the manhattan distance, and throwing out any ties. If any of the cells are on the edge o...
0f6b3e0085b963435e2da40a399d12d5704a9acc
3,610,656
import json def body_part_to_headers_and_data(part): """ convert part (of multi-part body) to headers dict and content. de-serializes json if content-type is application/json. :param part: BodyPart decoded by MultipartDecoder :return: tuple pair of headers dict and content """ if b'applic...
edd95f6dba9f4157c6a51b2dd6a6c4fb8a34e9db
3,610,657
def flip_marker_states(aut): """ Return an automaton that has all marker states flipped @param aut: Input automaton @type aut: L{Automaton} @return: Flipped automaton of L{aut} @rtype: L{Automaton} """ new_aut = aut.copy() for state in new_aut.get_states(): flip_single_ma...
e7fd6e539cb1dc3a35b41779fd4a6823a454a806
3,610,658
def find_all_presented_sfs(stim_df, ecc_step=1, ecc_range=(1, 12), size=1080, max_visual_angle=24, stimulus_mask=None): """Find average spatial frequency presented in eccentricity bands for each stimulus. Only works on square images. Returns a dataframe with the average spatial ...
67398f4fdfb01178acd38f676846943ef3c155dc
3,610,659
def encapsulateTable(string_table,column_labels, caption,ttype=None): """Uses the output of makeTables to render a complete latex table""" if ttype in ("kolmDiff3","kolmDiff3_","kolmSamp_","kolmSamp","textCorr","allFloat"): header="\\begin{table*}[h!]\n\\begin{center}\n\\begin{tabular}{| l |"+" c |"*(st...
63af2164b79ca73c3362cd535c4a98855495e18f
3,610,660
from twistdb.sampletrack import Sample, PlateType def bulk_to_temp_transform( db, bulk_plate_barcode, pca_plates ): """ returns a transform for consumption by echo_csv """ pd = primer_dict( db, pca_plates ) rows = [] primer_ct = defaultdict(int) layout = db.query(PlateType).get('SPTT_000...
331799b500b4d342a8bb58b6744210cae1485614
3,610,662
def gaussian1d_variant1(x, *p): """ Create a normalised gaussian (Area == 1) from mean and variance :param x: [numpy array] x axis data (array/list) :param p: [Tuple] (mean , variance) Area of gaussian is 1 --> A = 1/(c*sqrt(2pi)) Returns a Gaussian array one value for each x valu...
876b8b62ce4a6d632efc94539d0dfc54900b1e29
3,610,663
import urllib import traceback def evtimer(request, ettype, config_id, query=''): """ [メソッド概要] タイマー管理するイベントを管理する [引数] ettype : イベント管理種別('cron' or 'timer') config_id : イベント管理するシステム設定ID """ logger.logic_log('LOSI00001', 'ettype=%s, config_id=%s' % (ettype, config_id)) re...
595f7508cbcfd2434636e78b3a9d71de0603761c
3,610,664
def dc_node(request, hostname, data=None): """ Show (:http:get:`GET </dc/(dc)/node/(hostname)>`), create (:http:post:`POST </dc/(dc)/node/(hostname)>`), change (:http:put:`PUT </dc/(dc)/node/(hostname)>`) or remove (:http:delete:`DELETE </dc/(dc)/node/(hostname)>`) a compute node (hostname) asso...
0cd7725319ea944c0a3da99c62610a669ee60550
3,610,665
from datetime import datetime def parseDateTag(tag: bs4.element.Tag) -> str: """Parse date tag. :param tag: html table data element :return: date string """ date = datetime.strptime(tag.text, '%m/%d/%Y').strftime(DATE_FORMAT) return date
9be00eafe72b251e19ca480f1eb058da03ea7b1c
3,610,667
def get_utm_zone(lon): """ Calculate UTM zone. Arguments: lon: float Longitude, in degrees. West: negative, East: positive. Returns: zone: int UTM zone number. """ zone = int(1+(lon+180.0)/6.0) return zone
cf8c0d596f146417ebf0d3a18cd0b70e825388aa
3,610,668
def create_eyelid_follicle_system(driver_object="", selected_vertices=(), surface_mesh_name=""): """ creates follicle drivens that drives the joints that are driven by the driver controllers. This is a complicated system that requires these steps: 1. select vertices. 2. get the closest UV from the s...
a580d4aa955511b05d33fabdefd664f5111b83c5
3,610,669
from typing import List def create_chassis(world: b2World, vertices: List[b2Vec2], densities: List[float]) -> b2Body: """ Creates a chassis to be the body of the car. """ if len(vertices) != len(densities): raise Exception('vertices and densities must be same length') # Create body defini...
bd8ac60df9c9e217923099c3f8d7c2476f3360eb
3,610,670
def napalm_cli(task, commands, hostname=None, username=None, password=None, driver=None, timeout=60, optional_args=None): """ Run commands on remote devices using napalm Arguments: commands (list): list of commands to execute on the device hostname (string, optional): default...
00abff61eddfac22d3f867252c403ca70ffb43cf
3,610,671
import torch def _create_zero_states(model: RecurrentLM) -> ActivationDict: """Zero-initialized states if no init state is provided. Returns ------- init_states : ActivationTensors Dictionary mapping (layer, name) tuple to zero-tensor. """ init_states: ActivationDict = { a_nam...
8ece9f249099b2de678e2f173f1428f8b635bb0d
3,610,672
def append_iqa_scores(df): """Load image quality assessment scores and append to a dataframe of observation records""" # Sort user IDs by number of observations (in the current dataset) per user scores = load_iqa_scores() first_result = list(scores.values())[0] for key in first_result.keys(): ...
2f04bd2e2c8b440fd5159cddff9b1205eb4d974b
3,610,673
from typing import List def _setup_entities(hass, device_ids: List): """Set up Tuya Climate.""" device_manager = hass.data[DOMAIN][TUYA_DEVICE_MANAGER] entities = [] for device_id in device_ids: device = device_manager.deviceMap[device_id] if device is None: continue ...
bee211a1b67690ad064b05189b73d05e8a9841db
3,610,674
import collections def _iterateOverDicts(ob, func): """ This function iterates a function over a nested dict/list see https://stackoverflow.com/questions/32935232/python-apply-function-to-values-in-nested-dictionary """ assert type(ob) == dict, '**** _iterateOverDicts requires a dict input' fo...
04aacf2513dd0a702379ec3506943255a9dce137
3,610,675
def mask_rcnn_functional(config: dict) -> tf.keras.Model: """ Construct a model in functional API Args: config: General MaskRCNN config, dict Returns: tf.keras.Model: """ # Prevent creating keras names with index increment. # It is important for weights setting from training to infe...
1c73e43b3980e957c5a774d87da85997760a9e69
3,610,676
def ast_from_input(input, mode, transformer, parser): """converts a source input into an AST - input : the source to be converted - mode : 'exec', 'eval' or 'single' - transformer : the transfomer instance to use to convert the nested tuples into the AST XXX: transformer co...
23c8884736559f3b6334e288af2e6cc751b09045
3,610,677
def CvSepFilter_init_gaussian_kernel(*args): """ init_gaussian_kernel(CvMat kernel, double sigma=-1) CvSepFilter_init_gaussian_kernel(CvMat kernel) """ return _cv.CvSepFilter_init_gaussian_kernel(*args)
e45f3cd87f17e3a2dfecbcf92bed7e7ff512ad7b
3,610,678