content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def irrf(valor=0): """ -> Função para cálcular o valor do IRRF. :param valor: Valor base do salário para cálculo do IRRF. :return: Retorna o valor do IRRF e alíquota utilizada. """ irrf = [] if valor < 1903.99: irrf.append(0) irrf.append(0) elif va...
53646b770b2c2359e1e8c4f725b27396cc972050
3,655,700
def find_adcp_files_within_period(working_directory,max_gap=20.0,max_group_size=6): """ Sorts a directory of ADCPRdiWorkHorseData raw files into groups by closeness in time, with groups being separated by more than 'max_gap_minutes'. This method first sorts the files by start time, and then spli...
6e3afc4dd8532c579870541fe42519078e86f935
3,655,701
def regular_transport_factory(host, port, env, config_file): """ Basic unencrypted Thrift transport factory function. Returns instantiated Thrift transport for use with cql.Connection. Params: * host .........: hostname of Cassandra node. * port .........: port number to connect to. * env ....
bccee131d61a9a251a63ee021e0ab0c5b6033c44
3,655,702
def smoothed_abs(x, eps=1e-8): """A smoothed version of |x| with improved numerical stability.""" return jnp.sqrt(jnp.multiply(x, x) + eps)
f0b63e9482e602b29b85ce3f0d602d9918557ada
3,655,703
def increment(t1, seconds): """Adds seconds to a Time object.""" assert valid_time(t1) seconds += time_to_int(t1) return int_to_time(seconds)
f7807fc12a9ed9350d13d0f8c4c707c79165e9d5
3,655,704
import os def add_absname(file): """Prefix a file name with the working directory.""" work_dir = os.path.dirname(__file__) return os.path.join(work_dir, file)
34d78ff980cbe16ace897cf164563badc9d36d2a
3,655,705
def dense(input_shape, output_shape, output_activation='linear', name=None): """ Build a simple Dense model Parameters ---------- input_shape: shape Input shape output_shape: int Number of actions (Discrete only so far) Returns ------- model: Mode...
6f7ba28834ecfe7b5e74aa40ef30fcd9aa531836
3,655,706
def dataset_labels(alldata, tag=None): """ Return label for axis of dataset Args: ds (DataSet): dataset tag (str): can be 'x', 'y' or 'z' """ if tag == 'x': d = alldata.default_parameter_array() return d.set_arrays[0].label if tag == 'y': d = alldata.default_...
4ccd3af38d3f18e9fbf43e98f8a898426c6c1440
3,655,707
from typing import Optional from typing import Any from typing import Callable from typing import Tuple from typing import List from typing import Union def spread( template: Template, data: Optional[Any], flavor: Flavor, postprocess: Optional[Callable] = None, start_at: int = 0, replace_missi...
db354b3d190f1bff5b78c29a3ff6b4021287b27f
3,655,708
from sklearn.model_selection import train_test_split def train_validate_test_split(DataFrame, ratios=(0.6,0.2,0.2)): """ Parameters ---------- DataFrame : pandas.DataFrame DataFrame ratios : tuple E.g. (train, validate, test) = (0.6, 0.25, 0.15) (trai...
3d4b8424f66e72d3dd28328afb6465768b1778cb
3,655,709
from typing import Union def is_error(code: Union[Error, int]) -> bool: """Returns True, if error is a (fatal) error, not just a warning.""" if isinstance(code, Error): code = code.code return code >= ERROR
347bde61feb36ce70bf879d713ff9feb41e67085
3,655,710
def unpack_triple(item): """Extracts the indices and values from an object. The argument item can either be an instance of SparseTriple or a sequence of length three. Example usage: >>> st = SparseTriple() >>> ind1, ind2, val = unpack_triple(st) >>> quad_expr = [[], [], []] >>> ind1, ...
bae536d313140952927875640f925876700bf981
3,655,711
def max_sequence(arr): """ The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers. :param arr: an array or list of integers. :return: the maximum value found within the subarray. """ best = 0 for x in range(len(arr...
3ae6dafb4879476ba6e15610645f26299a4c6719
3,655,712
def get_by_username(username): """ Retrieve a user from the database by their username :param username: :return: """ return database.get(User, username, field="username")
354d323c464cbdbaf72b88284b2305657d03a027
3,655,713
def evalPoint(u, v): """ Evaluates the surface point corresponding to normalized parameters (u, v) """ a, b, c, d = 0.5, 0.3, 0.5, 0.1 s = TWO_PI * u t = (TWO_PI * (1 - v)) * 2 r = a + b * cos(1.5 * t) x = r * cos(t) y = r * sin(t) z = c * sin(1.5 * t) dv = PVector() d...
a3598739dc28e9fcd47539e4a51b00c351eb4e3d
3,655,714
def decode_funcname2(subprogram_die, address): """ Get the function name from an PC address""" for DIE in subprogram_die: try: lowpc = DIE.attributes['DW_AT_low_pc'].value # DWARF v4 in section 2.17 describes how to interpret the # DW_AT_high_pc attribute based on th...
b322282b9f908311dedbd73ade3d31bbb86cebe8
3,655,715
def get_reddit_slug(permalink): """ Get the reddit slug from a submission permalink, with '_' replaced by '-' Args: permalink (str): reddit submission permalink Returns: str: the reddit slug for a submission """ return list(filter(None, permalink.split("/")))[-1].replace("_", "...
587239a0b7bbd88e10d49985dd6ebfd3768038d8
3,655,716
def newton_halley(func, x0, fprime, fprime2, args=(), tol=1.48e-8, maxiter=50, disp=True): """ Find a zero from Halley's method using the jitted version of Scipy's. `func`, `fprime`, `fprime2` must be jitted via Numba. Parameters ---------- func : callable and jitted ...
96531b47a399ee0d897e5feadaa93eb56bee2b52
3,655,717
def staff_dash(request): """Route for displaying the staff dashboard of the site. """ # Empty context to populate: context = {} def get_account_name(path): """Method contains logic to extract the app name from a url path. Method uses the django.urls.resolve method with basi...
83d1d3027b64349dba5560934ba9d7bdb3536c91
3,655,718
import csv def read_v1_file(path: str = "CBETHUSD.csv") -> tuple: """ Read the data from the file path, reconstruct the format the the data and return a 3d matrix. """ lst = [] res = [] with open(path) as data: reader = csv.reader(data) next(reader) # skip the header row ...
6fd80fda5f327464e63f34df1f16b923349bc7a4
3,655,719
import torch def get_adjacent_th(spec: torch.Tensor, filter_length: int = 5) -> torch.Tensor: """Zero-pad and unfold stft, i.e., add zeros to the beginning so that, using the multi-frame signal model, there will be as many output frames as input frames. Args: spec (torch.Tensor): input spect...
4009b41fd4e729e16c749f4893f61b61ca922215
3,655,720
def K2(eps): """ Radar dielectric factor |K|**2 Parameters ---------- eps : complex nd array of complex relative dielectric constants Returns ------- nd - float Radar dielectric factor |K|**2 real """ K_complex = (eps-1.0)/(eps+2.0) return (K_complex*K_complex....
8754bee38a46de14d205764c4843cad7c4d5d88f
3,655,721
def permutation_test_mi(x, y, B=100, random_state=None, **kwargs): """Permutation test for mutual information Parameters ---------- x : 1d array-like Array of n elements y : 1d array-like Array of n elements n_classes : int Number of classes B : int Number...
ea60f7ddf483f3a095971ab3c52a07e34ac863d5
3,655,722
def convert_time_units(value, value_unit="s", result_unit="s", case_sensitive=True): """ Convert `value` from `value_unit` to `result_unit`. The possible time units are ``'s'``,``'ms'``, ``'us'``, ``'ns'``, ``'ps'``, ``'fs'``, ``'as'``. If ``case_sensitive==True``, matching units is case sensitive....
dab3fdb88a5d137d45efe440a6075cd0339194ac
3,655,723
import tqdm def compute_distribution_clusters(columns: list, dataset_name: str, threshold: float, pool: Pool, chunk_size: int = None, quantiles: int = 256): """ Algorithm 2 of the paper "Automatic Discovery of Attributes in Relational Databases" from M. Zhang et al. [1]. This...
bdbdf233c02f6eced3504543c3adbd8ea12505f7
3,655,724
def get_eventframe_sequence(event_deque, is_x_first, is_x_flipped, is_y_flipped, shape, data_format, frame_width, frame_gen_method): """ Given a single sequence of x-y-ts events, generate a sequence of binary event frames. """ inp = [] wh...
9d65bfa59c42b327cc7f5c02a044f545ec5f5a5e
3,655,725
def creation_sequence_to_weights(creation_sequence): """ Returns a list of node weights which create the threshold graph designated by the creation sequence. The weights are scaled so that the threshold is 1.0. The order of the nodes is the same as that in the creation sequence. """ # Turn...
80147c53ccb7f44fdca148cc422a0c149a5b7864
3,655,726
def get_seg_features(string): """ Segment text with jieba features are represented in bies format s donates single word """ seg_feature = [] for word in jieba.cut(string): if len(word) == 1: seg_feature.append(0) else: tmp = [2] * len(word) ...
505ba3064cacc2719e11126ce504b8c84abe10e9
3,655,727
def print_device_info(nodemap): """ This function prints the device information of the camera from the transport layer; please see NodeMapInfo example for more in-depth comments on printing device information from the nodemap. :param nodemap: Transport layer device nodemap. :type nodemap: ...
7f0affa8e8acaab48df8dc96c631ca9043f07482
3,655,728
import sys def make_withdrawal(account): """Withdrawal Dialog.""" # @TODO: Use questionary to capture the withdrawal and set it equal to amount variable. Be sure that amount is a floating # point number. amount = questionary.text("How much would you like to withdraw").ask() amount = float(amoun...
c4d9da902da3b6b85950cd6faa1b6e582e0509fe
3,655,729
from typing import Optional def coerce_to_pendulum_date(x: PotentialDatetimeType, assume_local: bool = False) -> Optional[Date]: """ Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, as...
d2fb5d830736290eb9ddadf9fcd664d0cba88d4b
3,655,730
def loss_fixed_depl_noquench(params, loss_data): """ MSE loss function for fitting individual stellar mass histories. Only main sequence efficiency parameters. Quenching is deactivated. Depletion time is fixed at tau=0Gyr, i.e. gas conversion is instantaenous. """ ( lgt, dt, ...
c987b17b2a64081006addf8ed9af6a3535b77bdd
3,655,731
def plot_timeseries_comp(date1, value1, date2, value2, fname_list, labelx='Time [UTC]', labely='Value', label1='Sensor 1', label2='Sensor 2', titl='Time Series Comparison', period1=0, period2=0, ymin=None, ymax=None, dpi...
a33be4ba8fbbaa2c8ee31694a4ede0d43deb171c
3,655,732
def identityMatrix(nrow, ncol): """ Create a identity matrix of the given dimensions Works for square Matrices Retuns a Matrix Object """ if nrow == ncol: t = [] for i in range(nrow): t.append([]) for j in range(ncol): if i == j: ...
3584c75cd0683f4dd547ac9708d03cdc5500dcef
3,655,733
def extract_packages(matched, package_source): """ Extract packages installed in the "Successfully installed" line e.g. Successfully installed Abjad Jinja2-2.10 MarkupSafe-1.0 PyPDF2-1.26.0 Pygments-2.2.0 alabaster-0.7.10 \ babel-2.5.1 bleach-2.1.2 decorator-4.1.2 docutils-0.14 entrypoints-0...
a4cf9c18122dd89b2c46647fa328ab72c4d7dd8a
3,655,734
from typing import List from typing import Optional from datetime import datetime def create_relationship( relationship_type: str, created_by: Identity, source: _DomainObject, target: _DomainObject, confidence: int, object_markings: List[MarkingDefinition], start_time: Optional[datetime] =...
4d961aae8521c53c61090823484e8b12862b29e0
3,655,735
def _find_partition(G, starting_cell): """ Find a partition of the vertices of G into cells of complete graphs Parameters ---------- G : NetworkX Graph starting_cell : tuple of vertices in G which form a cell Returns ------- List of tuples of vertices of G Raises ------ Ne...
92c63176d6c2f366c549a24982dbc64c9879a9b7
3,655,736
import torch def projection_from_Rt(rmat, tvec): """ Compute the projection matrix from Rotation and translation. """ assert len(rmat.shape) >= 2 and rmat.shape[-2:] == (3, 3), rmat.shape assert len(tvec.shape) >= 2 and tvec.shape[-2:] == (3, 1), tvec.shape return torch.cat([rmat, tvec], ...
90039ba7002be31d347b7793d542b1ff37abae3e
3,655,737
def verify_df(df, constraints_path, epsilon=None, type_checking=None, **kwargs): """ Verify that (i.e. check whether) the Pandas DataFrame provided satisfies the constraints in the JSON .tdda file provided. Mandatory Inputs: df A Pandas DataFrame, to be checked. ...
477180d390e3090ec7d8211b8cee7235d58d4eba
3,655,738
import re def _getallstages_pm(pmstr): """pmstr: a pipelinemodel name in quote return a df: of all leaf stages of transformer. to print return in a cell , use print_return(df) """ pm=eval(pmstr) output=[] for i,s in enumerate(pm.stages): if str(type(s))=="<class 'pyspark.ml.p...
8bb5643361aa5aa74c1ba477d725b575a2f15f0b
3,655,739
def merge_config(log_conf: LogConf, conf: Config) -> Config: """ Create combined config object from system wide logger setting and current logger config """ #pylint: disable=too-many-locals name = conf.name # take individual conf value, ignore common log_conf value filename = _ITEM_OR_DEFAULT(...
f62d7a48d83dd201323ff710c17b4ffbf39750bc
3,655,740
def midpVector(x): """ return midpoint value (=average) in each direction """ if type(x) != list: raise Exception("must be list") dim = len(x) #nx = x[0].shape for i in range(1,dim): if type(x[i]) != np.ndarray: raise Exception("must be numpy array") #if x[i...
784dcfdeb012aa114167d4b965409ca2f81ed414
3,655,741
def buy_ticket(email, name, quantity): """ Attmempt to buy a ticket in the database :param owner: the email of the ticket buyer :param name: the name of the ticket being bought :param quantity: the quantity of tickets being bought :return: an error message if there is any, or None if register su...
cd64f745a44180594edce14eb0645f808ac645d8
3,655,742
from typing import Tuple def update_bounds( sig: float, eps: float, target_eps: float, bounds: np.ndarray, bound_eps: np.ndarray, consecutive_updates: int ) -> Tuple[np.ndarray, np.ndarray, int]: # noqa:E121,E125 """ Updates bounds for sigma around a target pri...
a3426220fe20a4857ac51048ab8d703decaf3e9f
3,655,743
def get_timeseries(rics, fields='*', start_date=None, end_date=None, interval='daily', count=None, calendar=None, corax=None, normalize=False, raw_output=False, debug=False): """ Returns historical data on one or several RICs Parameters ---------- rics: string ...
52f8cb2f5fc422df0c9b474f879797b997ae3a4d
3,655,744
def usd(value): """Format value as USD.""" return f"${value:,.2f}"
022502cebaced49e21a311fe0bed6feead124ee9
3,655,745
def random_mindist(N, mindist, width, height): """Create random 2D points with a minimal distance to each other. Args: N(int): number of points to generate mindist(float): Minimal distance between each point width(float): Specifies [0, width) for the x-coordinate height(float): ...
261627e47e72b95d90f9b9c409ce61535f2a4cf7
3,655,746
def deactivate_spotting(ID): """ Function to deactivate a spotting document in Elasticsearch Params: ID::str id of the document to deactivate Returns: bool If the changes have been applied or not """ if not ID: return False try: globa...
381c79a08e990b64a0a1032b5b54b874b8c53926
3,655,747
import watools.General.raster_conversions as RC import watools.Functions.Start as Start import numpy as np def Fraction_Based(nc_outname, Startdate, Enddate): """ This functions calculated monthly total supply based ETblue and fractions that are given in the get dictionary script Parameters ---------...
378c149cc239eee31b10d90235b78cf15527b0e0
3,655,748
def _qrd_solve(r, pmut, ddiag, bqt, sdiag): """Solve an equation given a QR factored matrix and a diagonal. Parameters: r - **input-output** n-by-n array. The full lower triangle contains the full lower triangle of R. On output, the strict upper triangle contains the transpose of the strict low...
3e9d75c135734770c248a39de5770c3b033262da
3,655,749
import re def find_version(): """Extract the version number from the CLI source file.""" with open('pyweek.py') as f: for l in f: mo = re.match('__version__ = *(.*)?\s*', l) if mo: return eval(mo.group(1)) else: raise Exception("No version in...
128f2399a37b27412d2fdf6cf0901c1486709a09
3,655,750
import pandas.core.algorithms as algos def remove_unused_levels(self): """ create a new MultiIndex from the current that removing unused levels, meaning that they are not expressed in the labels The resulting MultiIndex will have the same outward appearance, meaning the same .values and ordering. ...
8f07a2b943278d5d5ae7d78ab2c10e96acd349e4
3,655,751
def _transform_playlist(playlist): """Transform result into a format that more closely matches our unified API. """ transformed_playlist = dict([ ('source_type', 'spotify'), ('source_id', playlist['id']), ('name', playlist['name']), ('tracks', playlist['tracks']['total'])...
62c19c132cbb9438c7a4b993e1d79111b79b86fd
3,655,752
from typing import Dict from typing import Hashable from typing import Any def decode_map_states(beliefs: Dict[Hashable, Any]) -> Any: """Function to decode MAP states given the calculated beliefs. Args: beliefs: An array or a PyTree container containing beliefs for different variables. Returns:...
3d8b9feecb3d612a4ff361f710ef1841cd016239
3,655,753
def plot_stretch_Q(datas, stretches=[0.01,0.1,0.5,1], Qs=[1,10,5,100]): """ Plots different normalizations of your image using the stretch, Q parameters. Parameters ---------- stretches : array List of stretch params you want to permutate through to find optimal image normalization. ...
d4dc4d52019aac10fc15dd96fd29c3abf6563446
3,655,754
def _isSpecialGenerateOption(target, optName): """ Returns ``True`` if the given option has a special generation function, ``False`` otherwise. """ return _getSpecialFunction(target, optName, '_generateSpecial') is not None
387fcb96d0d13e45b38a645ee61f20441905a0f8
3,655,755
def count_active_days(enable_date, disable_date): """Return the number of days the segment has been active. :param enable_date: The date the segment was enabled :type enable_date: timezone.datetime :param disable_date: The date the segment was disabled :type disable_date: timezone.datetime :ret...
070a520c328dbe69491fc6eb991c816c9f4fccd8
3,655,756
def numpy_to_python_type(value): """ Convert to Python type from numpy with .item(). """ try: return value.item() except AttributeError: return value
f1d3a8ad77932342c182d7be76037fee3c869afe
3,655,757
import tqdm import os def bigEI_numerical(Ey, t, P=1): """Return the column kp=0 of the matrix E_I, computed numerically.""" lmax = int(np.sqrt(Ey.shape[0]) - 1) K = len(t) map = starry.Map(ydeg=lmax, lazy=False) theta = 360 / P * t bigEI = np.zeros(K) kp = 0 for k in tqdm(range(K), d...
f437a6b818b848fb8dc715ec04c693d6d3dbd161
3,655,758
import sys import traceback def db_select_all(db, query, data=None): """Select all rows""" logger_instance.debug("query = <<%s>>"% (query[:100],)) cursor = db.cursor() try: cursor.execute(query, data) except pymysql.MySQLError: exc_type, exc_value, exc_traceback = sys.exc_info() ...
44184540092ab698292fff9285f4bff0cb163be7
3,655,759
def threshold_abs(image, threshold): """Return thresholded image from an absolute cutoff.""" return image > threshold
5032f632371af37e81c3ebcc587475422d5ff2bf
3,655,760
def warp_images(img1_loc, img2_loc, h_loc): """ Fill documentation """ rows1, cols1 = img1_loc.shape[:2] rows2, cols2 = img2_loc.shape[:2] print("0") list_of_points_1 = np.array( [[0, 0], [0, rows1], [cols1, rows1], [cols1, 0]], np.float32).reshape(-1, 1, 2) temp_points = np.arr...
ab5b364ded7647efb13c686a32acc8ee6c6487ba
3,655,761
def ValidaCpf(msg='Cadastro de Pessoa Física (CPF): ', pont=True): """ -> Função para validar um CPF :param msg: Mensagem exibida para usuário antes de ler o CPF. :param pont: Se True, retorna um CPF com pontuação (ex: xxx.xxx.xxx-xx). Se False, retorna um CPF sem pontuação (ex: xxxxxxxxxxx) ...
3bdc298f7a2a3a4c16919a9caba21b71bbaf8539
3,655,762
def get_xml_path(xml, path=None, func=None): """ Return the content from the passed xml xpath, or return the result of a passed function (receives xpathContext as its only arg) """ #doc = None #ctx = None #result = None #try: doc = etree.fromstring(xml) #ctx = doc.xpathNewConte...
81bcce1806f11217a04fbc401226d727e0150735
3,655,763
def readXYdYData(filename, comment_character='#'): """ Read in a file containing 3 columns of x, y, dy Lines beginning with commentCharacter are ignored """ return read_columnar_data(filename, number_columns=3, comment_character=comment_character)
92fd9253e0b50688034e3d85d6f4589a589be066
3,655,764
def hexlen(x): """ Returns the string length of 'x' in hex format. """ return len(hex(x))+2
404ec4c3656bb35b87df6ae147db93922f2da059
3,655,765
def get_db(): """ connectionを取得します """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db
ba3d474ba854d9dea8e8f0056ebbfd81fc86b91a
3,655,766
def list_manipulation(lst, command, location, value=None): """Mutate lst to add/remove from beginning or end. - lst: list of values - command: command, either "remove" or "add" - location: location to remove/add, either "beginning" or "end" - value: when adding, value to add remove: remove ite...
c847257ea5508f60b84282c3ac8237b43cd3825a
3,655,767
import six def solve( problem, comm=_NoArgumentGiven, dispatcher_rank=0, log_filename=None, results_filename=None, **kwds ): """Solves a branch-and-bound problem and returns the solution. Note ---- This function also collects and summarizes runtime workload statistics,...
9c57c0748db0185fae1e731044e904d0f732b5de
3,655,768
def solution(lst): """Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions. Examples solution([5, 8, 7, 1]) ==> 12 solution([3, 3, 3, 3, 3]) ==> 9 solution([30, 13, 24, 321]) ==>0 """ #[SOLUTION] return sum([x for idx, x in enumerate(...
f98482cad7061d725389442c9811e33539df4fdc
3,655,769
def summarize_traffic_mix(l_d_flow_records, d_filters={}): """ Filter the traffic flow data and execute the processing analysis logic for network behavior metrics. """ o_tcp_src_analysis = TopProtocolAnalysis() o_tcp_dst_analysis = TopProtocolAnalysis() o_upd_src_analysis = TopProtocolAnalysis...
48b04cf0e1e4f8b50850a775994012af4a784728
3,655,770
def segment(X, upscale=1.0, denoise=False): """ :param X: :param upscale: :param denoise: :return: """ if upscale > 1.0: X = rescale(X, upscale) if denoise: X = denoise_wavelet(X) thresh = filters.threshold_otsu(X) bw = closing(X > thresh, square(3)) cleared...
e81be87bdb27b7cf1cf1de434997a87ecea0cae4
3,655,771
def get_image_info(doc): """Create dictionary with key->id, values->image information """ id_img = dict() #add image information for img_infor in doc['images']: filename = img_infor['file_name'] width = img_infor['width'] height = img_infor['height'] id_img[img_infor['id']] = [filename, width,...
b8c91e67572e5863f773db579ce26fa86530f32e
3,655,772
def __check_partial(detected,approx, width, height): """ Check if it's a partial shape It's a partial shape if the shape's contours is on the image's edges. Parameters ---------- detected : Shape The detected shape approx : numpy.ndarray Approximates a polygonal curves. ...
7808dd156de97fa467b7b471b77fa4abdeaede95
3,655,773
import re def get_svg_size(filename): """return width and height of a svg""" with open(filename) as f: lines = f.read().split('\n') width, height = None, None for l in lines: res = re.findall('<svg.*width="(\d+)pt".*height="(\d+)pt"', l) if len(res) > 0: # need to s...
7732df636657950b050be409ef2439c975d6940d
3,655,774
import time import os import glob def bin_mgf(mgf_files,output_file = None, min_bin = 50, max_bin = 850, bin_size = 0.01, max_parent_mass = 850, verbose = False, remove_zero_sum_rows = True, remove_zero_sum_cols = True, window_filter = True, filter_window_size = 50, filter_window_retain = 3, filter_parent_peak = True...
f787a46415bbdc3bdbb52c62805618ad9edcec17
3,655,775
def index(): """Video streaming home page which makes use of /mjpeg.""" return render_template('index.html')
2fcc16af5bfc160a71f5eb74d1854b3c7e22587f
3,655,776
def tex_quoted_no_underscore (s) : """Same as tex_quoted but does NOT quote underscores. """ if isinstance (s, pyk.string_types) : s = _tex_pi_symbols.sub (_tex_subs_pi_symbols, s) s = _tex_to_quote.sub (_tex_subs_to_quote, s) s = _tex_tt_symbols.sub (_tex_subs_tt_symbols, s) ...
96eca3b927e6c7cc84d721222ceb9e9405eb8763
3,655,777
import json def load_from_json_file(filename): """ function that creates an Object from a “JSON file” """ with open(filename, 'r') as f: return json.loads(f.read())
ed46cf62548cfb7e1eb3683b688d18246b34be23
3,655,778
def _variable_to_field(v): """Transform a FuzzyVariable into a restx field""" if isinstance(v.domain, FloatDomain): a, b = v.domain.min, v.domain.max f = fields.Float(description=v.name, required=True, min=a, max=b, example=(a + b) / 2) elif isinstance(v.domain, CategoricalDomain): r...
c97b25ff0abecedc6f44210d2672422d9c3eefd2
3,655,779
def abs_ang_mom(u, lat=None, radius=RAD_EARTH, rot_rate=ROT_RATE_EARTH, lat_str=LAT_STR): """Absolute angular momentum.""" if lat is None: lat = u[lat_str] coslat = cosdeg(lat) return radius*coslat*(rot_rate*radius*coslat + u)
57525fa5ed995208eced76b74e4263c695340575
3,655,780
def main(): """ Simple pyvmomi (vSphere SDK for Python) script that generates ESXi support bundles running from VCSA using vCenter Alarm """ # Logger for storing vCenter Alarm logs vcAlarmLog = logging.getLogger('vcenter_alarms') vcAlarmLog.setLevel(logging.INFO) vcAlarmLogFile = os.path.join('/v...
2c874bc06072896bb35f0288dd2ef4b5f69fe07f
3,655,781
import collections def _get_ngrams(segment, max_order): """Extracts all n-grams upto a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Ret...
561dfe8c18810ce40ce4c0ff391d6838816de116
3,655,782
def print_donors_list(): """ print a list of existing donors """ print(mr.list_donors()) return False
997860c036cac95f73242174198092a1d7d3ea9b
3,655,783
def log_cef(name, severity, env, *args, **kwargs): """Simply wraps the cef_log function so we don't need to pass in the config dictionary every time. See bug 707060. env can be either a request object or just the request.META dictionary""" c = {'cef.product': getattr(settings, 'CEF_PRODUCT', 'AMO'), ...
bb9631f32bf2a247760ff604e998e8058f203c9e
3,655,784
def collimate(S, r, phasevec, print_values = False): """Collimate r phase vectors into a new phase vector on [S]. Output: the collimated phase vector ([b(0),b(1),...,b(L'-1)], L') on [S]. Parameters: S: output phase vectors has all multipliers on [S] r: arity, the number of phase vectors that is co...
1e1eb6c55cd1b51e7303613d581fda97ad14bdb0
3,655,785
import io def parse_and_load(gw, subj, primitive, cgexpr, g): """ Parse the conceptual grammar expression for the supplied subject and, if successful, add it to graph g. :param gw: parser gateway :param subj: subject of expression :param primitive: true means subClassOf, false means equivalentClas...
cd5b1b27b5922fb6c0e377532192a6985a0a5783
3,655,786
def pushed(property_name, **kwargs) -> Signal: """ Returns the `pushed` Signal for the given property. This signal is emitted, when a new child property is added to it. From the perspective of a state, this can be achieved with the `ContextWrapper.push(...)` function.<br> __Hint:__ All key-wo...
999e6b20a92648d5042c075400af45c809f08a32
3,655,787
async def delete_data(table_name: str, filter: str = Header(None), filterparam: str = Header(None), current_user_role: bool = Depends(security.get_write_permission)): """ Parameters - **table_name** (path): **Required** - Name of the ...
ffcf6e1aba2089846f103820eda0960bbccd4bba
3,655,788
import dask.dataframe as dd def _is_dask_series(ddf): """ Will determine if the given arg is a dask dataframe. Returns False if dask is not installed. """ try: return isinstance(ddf, dd.Series) except: return False
5166928c0bd54bfc69a3d7862fadc41c3a0b6d19
3,655,789
import scipy def square(t, A=1, f=1, D=0): """ t: time A: the amplitude, the peak deviation of the function from zero. f: the ordinary frequency, the number of oscillations (cycles) that occur each second of time. D: non-zero center amplitude """ square_ = A*scipy.signal.square( ...
8e1899891d5f0df6c171404c401e94f729233147
3,655,790
def self_distance_array(reference, box=None, result=None, backend="serial"): """Calculate all possible distances within a configuration `reference`. If the optional argument `box` is supplied, the minimum image convention is applied when calculating distances. Either orthogonal or triclinic boxes are s...
71ee400ad48f719316a0c3f3c101f432067e2387
3,655,791
import numpy def mainRecursivePartitioningLoop(A, B, n_cutoff): """ """ # Initialize storage objects n = A.shape[0] groups = numpy.zeros((n,), dtype=int) groups_history = [] counts = {'twoway-single' : 0, 'twoway-pair' : 0, 'threeway-pair' : 0} to_split = {...
e2983585825f068ce1bdcc26dfd91dd85be2e060
3,655,792
def corrSmatFunc(df, metric='pearson-signed', simFunc=None, minN=None): """Compute a pairwise correlation matrix and return as a similarity matrix. Parameters ---------- df : pd.DataFrame (n_instances, n_features) metric : str Method for correlation similarity: pearson or spearman, optiona...
3d8d3ad9c992f1f1518c8fc7699058e76f616c95
3,655,793
def rank(values, axis=0, method='average', na_option='keep', ascending=True, pct=False): """ """ if values.ndim == 1: f, values = _get_data_algo(values, _rank1d_functions) ranks = f(values, ties_method=method, ascending=ascending, na_option=na_option, pct=pct) ...
0dbdb923281f7dbf592cd7bd41615b235b0e0868
3,655,794
def _cmpopts(x, y): """Compare to option names. The options can be of 2 forms: option_name or group/option_name. Options without a group always comes first. Options are sorted alphabetically inside a group. """ if '/' in x and '/' in y: prex = x[:x.find('/')] prey = y[:y.find('/...
9da8f8f5666b2ea3f32eb092c6a3568947655400
3,655,795
def ask(question, choices): """Prompt user for a choice from a list. Return the choice.""" choices_lc = [x.lower() for x in choices] user_choice = "" match = False while not match: print question user_choice = raw_input("[" + "/".join(choices) + "] ? ").strip().lower() for ch...
8a1f6019554dbb9e1ed6649b1a68040f99960fbe
3,655,796
def get_and_validate_user(username, password): """ Check if user with username/email exists and specified password matchs well with existing user password. if user is valid, user is returned else, corresponding exception is raised. """ user_model = apps.get_model("users", "User") qs = ...
05b6675c12446e961d85b8c39b0437d51a7c40b8
3,655,797
import re import string def process_tweet(tweet): """Process tweet function. Input: tweet: a string containing a tweet Output: tweets_clean: a list of words containing the processed tweet""" stemmer = PorterStemmer() stopwords_english = stopwords.words('english') # R...
2b69f70cfec5f90a6e58408fcd054cda7ad0f20a
3,655,798
def oracle_query_id(sender_id, nonce, oracle_id): """ Compute the query id for a sender and an oracle :param sender_id: the account making the query :param nonce: the nonce of the query transaction :param oracle_id: the oracle id """ def _int32(val): return val.to_bytes(32, byteorder...
aa97834efd3df10951e05b99035dbef8210ba33d
3,655,799