content
stringlengths
22
815k
id
int64
0
4.91M
def main(): """ Runs the main program. """ prob1a() return GOOD_RET
69,100
def init_tenses(): """initialises the tenses dict.""" tenses = {} for t in VerbTense: tenses[t] = {} for d in VerbDependency: tenses[t][d] = {} for p in VerbPerson: tenses[t][d][p] = [] return tenses
69,101
def prim(w_graph_d): """Prim's algorithm for minimum spanning tree in "undirected weighted" graph, G(V, E). Time complexity for : O((|V|+|E|)log(|V|)). Space complexity: O(|V|). """ min_pq = MinBinaryHeapAttribute() key_d = {v: float('inf') for v in w_graph_d.keys()} previous_d = {v: ...
69,102
def get_row_headers(data): """ Take a dictionary and walk the dictionary identifying allthe unique row headers. """ headers = set() try: for key, value in data.iteritems(): try: iter(value) if not isinstance(value, basestring): ...
69,103
def tanh_by_lbub(dom: AbsDom, ntimes: int = 10): """ Validate that the Tanh approximation is correct by checking its afterward LB/UB. """ for _ in range(ntimes): t1t2 = torch.stack((torch.randn(3, 3, device=device), torch.randn(3, 3, device=device)), dim=-1) lb, _ = torch.min(t1t2, dim=-1) ...
69,104
def filter(args): """filter vcf output records""" input_handle = open(args.input, 'r') output_handle = open(args.output, 'w') template = vcf.Reader(args.template, 'r') vcf_handle = vcf.Reader(input_handle) vcf_out = vcf.Writer(output_handle, template, ) for record in vcf_handle: if r...
69,105
def Compile(expr): """ Given an XPath expression as a string, returns an object that allows an evaluation engine to operate on the expression efficiently. This "compiled" expression object can be passed to the Evaluate function instead of a string, in order to shorten the amount of time needed t...
69,106
def f1(myList): """Solves x = Sqrt((120-y)/8)""" return math.sqrt((120-myList[1])/8) #return 120-8*myList[0]**2
69,107
def get_pet_labels(image_dir): """ Creates a dictionary of pet labels (results_dic) based upon the filenames of the image files. These pet image labels are used to check the accuracy of the labels that are returned by the classifier function, since the filenames of the images contain the tru...
69,108
def mfccf(num, s, Fs): """ 计算并返回信号s的mfcc参数及其一阶和二阶差分参数 :param num: :param s: :param Fs: :return: """ N = 512 # FFT数 Tf = 0.02 # 窗口的时长 n = int(Fs * Tf) # 每个窗口的长度 M = 24 # M为滤波器组数 l = len(s) Ts = 0.01 # 帧移时长 FrameStep = int(Fs * Ts) # 帧移 lift...
69,109
def checkout_working_copy(request, identifier): """ post: Checkout a working copy (database, file system) A stored data set without a working copy cannot to be edited or changed directly. It is required to checkout a working copy first. To checkout the information package use the following com...
69,110
def check_security_credentials(auth_method, params, client_int_name, entry_name): """ Verify only the credentials for the given authentication method are in the params. @type auth_method: string @param auth_method: authentication method of an entry, defined in the config @type params: dictionar...
69,111
def make_index(fpath_db): """ Create index for tables that already exist. Add additional indexes other than pre-determined primary keys to speed up queries. """ engine = create_engine('sqlite:///' + fpath_db) id_year = Index('id_year', Sims.year) print('>> making id_year') id_year...
69,112
def cloudstorage_copy_objects_task(source, destination, start_date: str = None, file_filter=None, zip_files=False): """ Cloud Task: Copies all objects matching the source to the destination. Both source and destination use the following format: /bucket/prefix/ """ ...
69,113
def mesh_reader(path): """Read a mesh in using pymeshlab. Parameters ---------- path : str or list of str Path to file, or list of paths. Returns ------- layer_data : list of tuples List of surfaces, one per file path. """ # handle both a string and a list of string...
69,114
def get_git_string(): """ Return a string with information on the git version """ sha = get_git_hash() return "Git branch hash: " + sha
69,115
def parse_args(): """Parse command line arguments""" parser = common_exe.cli_parser() parser.add_argument("file", help="Obfuscated file to grab the data from") opts = parser.parse_args() if opts.debug_log: opts.debug = True return opts
69,116
def estimate_dmg_size(app_bundles: List[Path]) -> int: """ Estimate size of DMG to hold requested app bundles The size is based on actual size of all files in all bundles plus some space to compensate for different size-on-disk plus some space to hold codesign signatures. Is better to be on a ...
69,117
def main_operation(abs_src_path: str, abs_target_path:str, logger: logging.Logger, e: threading.Event = None): """List all files to be checked, then go over them and move if necessary. Args: abs_src_path (str): Absolute source directory (where...
69,118
def _initialize_full_precision( model: torch.nn.Module, optimizer: torch.optim.Optimizer ) -> Tuple[torch.nn.Module, torch.optim.Optimizer]: """ Initialize full precision training - leaves model and optimizer untouched. Flattens fp-32 parameters and gradients. """ global model_params_fp32, model...
69,119
def do_database_delete(cs, args): """Deletes a database from an instance.""" instance, _ = _find_instance_or_cluster(cs, args.instance) cs.databases.delete(instance, args.database)
69,120
def register_blueprints(app): """注册应用的蓝本""" # app app.register_blueprints(index_bp) # api app.register_blueprints(api_v1_main, url_prefix='api/v1')
69,121
def test_claim_8(base_settings): """No. 8 tests collection for Claim. Test File: claim-example-pharmacy-medication.json """ filename = ( base_settings["unittest_data_dir"] / "claim-example-pharmacy-medication.json" ) inst = claim.Claim.parse_file( filename, content_type="applicat...
69,122
def while_U(): """printing capital 'U' using while loop""" i=0 while i<5: j=0 while j<4: if j==0and i!=4 or j==3 and i!=4 or i==4 and j not in(0,3) : print("*",end=" ") else: print(" ",en...
69,123
def serialize(obj: Serializable) -> JSON: """Serialize object to JSON. Args: obj: An object to serialize. Returns: Its JSON representation. """ return _serializers[type(obj)](obj)
69,124
def scale_fill_brewer(type=None, palette=None, direction=None, name=None, breaks=None, labels=None, limits=None, na_value=None, guide=None, trans=None): """ Sequential, diverging and qualitative color scales from colorbrewer.org for fill aesthetic. Color schemes provided are particular...
69,125
def resize_image(image, size=140): """Get squared-resized image """ BLACK = [0, 0, 0] h = image.shape[0] w = image.shape[1] if w < h: border = h-w image = cv2.copyMakeBorder(image, 0, 0, border, 0, cv2.BORDER_CONSTANT, value=BLACK) else: border = w-h image = c...
69,126
def get_families(cxn): """Extract the families from the taxonomy table.""" sql = """SELECT DISTINCT family FROM taxonomy;""" families = pd.read_sql(sql, cxn).set_index('family') return families.to_dict(orient='index', into=OrderedDict)
69,127
def _filter_by_variance(frame, threshold=0.005): """Removes from frame any columns with a relative variance beneath the given threshold. """ # first, for each column X, compute relative variance as # var((X-min(X))/(max(X)-min(X))) numerators = frame.subtract(frame.min(axis='index'), axis='colum...
69,128
def test(p, parameters): """ Runs the quality control check on profile p and returns a numpy array of quality control decisions with False where the data value has passed the check and True where it failed. """ # Get temperature values from the profile. t = p.t() # Make the quality...
69,129
def getDate(signature): """Function that returns the date present on the signature.""" return getToken(signature, "Date: ", '\x00')
69,130
def delete_disconnected(): """ This function will clean nodes without connections from the content database table. """ node_type = "S3" nodes = [] connections = [] for node_type in NODE_TYPES: nodes = nodes + cached_by_service(node_type) for conn_type in CONNECTION_TYPES: ...
69,131
def monadic(f): """Decorate a unary function to return a Maybe monad.""" @functools.wraps(f) def wrapped(a): try: b = f(a) except Exception: b = None if b is None: return Nothing() else: return Just(b) return wrapped
69,132
def jacobian(variables, functions): """Returns the Jacobian matrix containing the first derivative of each input function with respect to each input variable""" derivatives = [] try: # Case where functions is a list of AD objects if type(functions) is list: if l...
69,133
def parse(filename): """Parse a wheel filename, sdist filename, or setup.py file and return the attributes. Args: filename (str): Filename that ends in .whl, sdist filename that ends with .tar.gz, or setup.py filename. Returns: attrs (dict): Dictionary of attributes "name", "version", "bui...
69,134
def kron_diag(diags): """Returns diagonal of kronecker product from list of diagonals. """ return reduce(flattened_outer, diags)
69,135
def mint(account: UInt160, amount: int): """ Mints new tokens. This is not a NEP-17 standard method, it's only being use to complement the onPayment method :param account: the address of the account that is sending cryptocurrency to this contract :type account: UInt160 :param amount: the amount of ...
69,136
def get_nodes_with_services(G): """ Based on the render of app_operator.py for visual inspection :param sim: :return: """ HwReqs = nx.get_node_attributes(G, name="HwReqs") currentOccupation = {} for n in G.nodes: currentOccupation[n] = np.zeros(int(HwReqs[n])).astype(int) ...
69,137
def GetXML(archiveUID=None,table=None): """ :param archiveUID: Archive UID :param table: Table :return: XML String """ sqlXML = "select XMLType.GetClobVal(xml) from ALMA.XXXXYYY where archive_uid='ZZZZCCCC' " sqlXML = sqlXML.replace('XXXXYYY',tables[table]).replace('ZZZZCCCC',archiveUID) ...
69,138
def f_to_R(f_df, R_dict): """Calculates robustness from performance values. Uses a set of performance values, `f`, determined from simulations across multiple decision alternatives, `l`, different scenarios, `s`, and calculates robustness, `R`, using a variety of given robustness metrics. Para...
69,139
def plt_infer_actual(ytest_pred_df_avg, band_df, filename=None): """Compare the actual and inference predicted data in timeseries format. Args: ytest_pred_df_avg: actual data to plot band_df: inference data to plot with different quantiles filename: save filename """ plt.fig...
69,140
def test_graphviz_extended(tmpdir): """ Check that the graphviz export work. """ # Skip if dot is missing dot_exec = find_executable('dot') if dot_exec is None: pytest.skip('Missing Graphviz "dot" executable') # Create base topology mgr = common_mgr() # Plot graphviz file ...
69,141
def is_not_csv_file(filename): """Retun an indication if the file entered is the clusterserviceversion (csv) file """ return not filename.endswith('clusterserviceversion.yaml')
69,142
def get_key(app_id: Optional[str] = None, developer_id: Optional[str] = None, key_id: Optional[str] = None, organization_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKeyResult: """ Gets details for a consumer key for a deve...
69,143
def _shellBucklingOneSection(h, r1, r2, t, gamma_b, sigma_z, sigma_t, tau_zt, E, sigma_y): """ Estimate shell buckling for one tapered cylindrical shell section. Arguments: h - height of conical section r1 - radius at bottom r2 - radius at top t - shell thickness E - modulus of elastici...
69,144
def get_ngrams(corpus_sents, gram, corpus_name, target_dir): """ Generates a set of n-grams for the specified granularity, corpus-wise; here: used for 2-grams and 3-grams. """ print('Generating the {:d}-gram file for the {:s} corpus ...'.format(gram, corpus_name)) # Collect n-grams present within the co...
69,145
def split_multi_class_train_eval_dataset(dataset_name): """Splits the dataset into Training and Eval samples. For aircraft models with more than one example, the aircraft bodies will be divide, 75% to Train and 25% to Eval. The samples are separated using tags. Args: dataset_name (): The na...
69,146
def cc_score_fct(i): """ CC (Chamberlin-Courant) marginal score function. This is the additional (marginal) score from a voter for the `i`-th approved candidate in the committee. Parameters ---------- i : int We are calculating the score for the `i`-th approved candidate in...
69,147
def set_user_student_info(openid, studentid, studentpwd): """写入绑定的教务管理系统账号""" redis_prefix = "wechat:user:" auth_info = Auth.query.filter_by(openid=openid).first() if not auth_info: auth = Auth(openid=openid, studentid=studentid, studentpwd=studentpwd) ...
69,148
def create_plan(response): """Create plan""" # if user is logged in if response.user.is_authenticated: if response.method == 'POST': form = CreateNewPlan(response.POST) # chcek form validation if form.is_valid(): # clean data t = f...
69,149
def engage(): """ switch relay to active """ if debug: print(" ==> engaging") if not dry_run: relay.on()
69,150
def sun( hass: HomeAssistant, before: str | None = None, after: str | None = None, before_offset: timedelta | None = None, after_offset: timedelta | None = None, ) -> bool: """Test if current time matches sun requirements.""" utcnow = dt_util.utcnow() today = dt_util.as_local(utcnow).dat...
69,151
def test_full_metadata_xml_schema(app, full_metadata): """Test metadata schema.""" metadata = Marc21TestSchema() data = metadata.load({"metadata": full_metadata}) _test_metadata( data["metadata"], marc21.do(create_record(full_metadata["xml"])), ) assert "xml" not in data
69,152
def load_snapshot(model_path): """ Load snapshot :param model_path: path to snapshot :type model_path: str :return: built state :rtype: dict """ state = torch.load(model_path) return state
69,153
def find_last_built_pipeline(): """Finds the pipeline config file for the last built pipeline. The last built pipeline is the pipeline whose generated configuration directory has the most recent timestamp. Returns: the path to the pipline config file for the last built pipeline, or ...
69,154
def nfc_open(source): """ Opens a connection to the nfc reader. :param source: The source of the nfc reader (e.g. 'usb'). """ clf = nfc.ContactlessFrontend() clf.open(source) target = clf.sense(nfc.clf.RemoteTarget('106A'), nfc.clf.RemoteTarget('106B'), ...
69,155
def import_secondary_context_membership(): """Add docstring.""" log.info('Read in secondary context membership') SecondaryContextMembership = pd.read_csv(inputpath + 'SecondaryContextMembership.csv') return SecondaryContextMembership
69,156
def _parse_tasks(tasks: List, file_name: str, collections: Optional[List] = None) -> List: """ Parse Ansible tasks and prepare them for scanning :param tasks: List of Ansible task dicts :param file_name: Name of the original file with tasks :param collections: List of Ansible collections for tasks ...
69,157
def _get_compiler_args( compiler_lang, flags, options, **_kwargs): """ Return compiler args when compiling for ocaml. """ _ignore = compiler_lang args = [] # The OCaml compiler relies on the HS2 compiler to parse .thrift sources to JSON args.append("-c") ...
69,158
def create_dataset(dataset_folder,dataset_name,val_size,gt,horizon,delim="\t",train=True,eval=False,verbose=False): """ gt:obs length horizon:pred length """ if train==True: #训练集 datasets_list = os.listdir(os.path.join(dataset_folder,dataset_name, "train")) ...
69,159
def which_set( filename, validation_percentage=VALIDATION_PERCENTAGE, testing_percentage=TESTING_PERCENTAGE): """Determines which data partition the file should belong to. This function is from the dataset github page: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/...
69,160
def view_vote_entities_map_proposal(self, request): """ A static link to the map of the proposal. """ ballot = getattr(self, 'proposal', None) if ballot: return redirect(request.link(ballot, name='entities-map')) raise HTTPNotFound()
69,161
def check_nip(client: Client, nip: str, account: str, date: str) -> None: """Check if given nip and account belongs to the same subject.""" click.echo(client.check_nip(nip=nip, account=account, date=date, raw=True))
69,162
def _format_artifact(tuple, flink_version, scala_version, classifier = None, neverlink = False): """Formats the given artifact tuple. """ group = tuple[0] artifact_id = _replace_scala_artifact_version(tuple[1], scala_version) version = None if group == _FLINK_GROUP: version = flink_versi...
69,163
def create_input_list(pdb_list_fname): """ create a list of tuples (pdb_id, chain) from a text file """ pdb_list = [] with open(pdb_list_fname, 'r') as f: for record in f.read().splitlines(): pdb_id, chain = record[:-1], record[-1] # check PDB ID and chain are valid ...
69,164
def PreDataViewCtrl(*args, **kwargs): """PreDataViewCtrl() -> DataViewCtrl""" val = _dataview.new_PreDataViewCtrl(*args, **kwargs) return val
69,165
def guess_industries(companies, return_prob=False, cutoff=ind_cutoff): """ The function guesses industries and probabilities based on company names. """ try: global _model _model = IndustryModel.load() if companies: return cur_model.predict(_model, companies, return_prob, cut...
69,166
def setShellAnimateKeys(typeNode): """ #sets keys for TRS on the animaiton attributes """ pass
69,167
def get_drawing(doc_id, drawing_num): """Summary Args: doc_id (str): Document identifier (e.g. patent number) drawing_num (str): Drawing number, e.g. "1" Returns: bytes: Image data """ key_prefix = _drawing_prefix(doc_id) key = f'{key_prefix}{drawing_num}.tif' tif_d...
69,168
def test_rnn_module(caplog): """Unit test of RNN Module""" caplog.set_level(logging.INFO) n_class = 2 emb_size = 10 lstm_hidden = 20 batch_size = 3 seq_len = 4 # Single direction RNN rnn = RNN( num_classes=n_class, emb_size=emb_size, lstm_hidden=lstm_hidden...
69,169
def _query_worrying_level(time_elapsed, state): """ Gives a "worriness" level to a query For instance, long times waiting for something to happen is bad Very long times sending is bad too Return a value between 0 and 1 rating the "worrying level" See http://dev.mysql.com/doc/refman/5.7/en/genera...
69,170
def do_color(msg, style): """ print the message in color if it can be handled""" return msg if can_handle_color() else colorit(msg, style)
69,171
def sce2t_vector(k1, in11): """sce2t_vector(SpiceInt k1, ConstSpiceDouble * in11)""" return _cspyce0.sce2t_vector(k1, in11)
69,172
def cross_entropy_loss(pred,labels): """ Does an internal softmax before loss calculation. args: pred- batch,seq,input_size labels-batch,seq(has to be transformed before comparision with preds(line-133).) """ checkdatadim(pred,3) checkdatadim(labels,2) batch,seq,size=pred.sha...
69,173
def latitude_from_cross_section(cross): """Calculate the latitude of points in a cross-section. Parameters ---------- cross : `xarray.DataArray` The input DataArray of a cross-section from which to obtain latitudes. Returns ------- latitude : `xarray.DataArray` Latitude of ...
69,174
def dict_to_casl_rules(rules: dict): """ Given a dict where the keys are the subject and the values are the actions, return a list of dicts ready to be serialized as JSON :return: """ perms = [] for key, actions in rules.items(): perms.append({ 'subject': key, ...
69,175
def svn_fs_paths_changed2(*args): """svn_fs_paths_changed2(svn_fs_root_t * root, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_paths_changed2(*args)
69,176
def xmlout(fasta, genome): """Parses variables from supplied tuples? dictionaries?""" global path # Extract the variables from the passed variables gene = fasta.split('/')[-1] # split file from path, could use os.path.split genename = gene.split('.')[0] genomename = os.path.basename(genome).spl...
69,177
def clamp(x, lower, upper): """ Naive Clamping in [2] A [[ x ]]_b = min(max(u,b_lower),b_upper) :param x: :param lower: :param upper: :return: """ # Not None assert x.shape == lower.shape assert x.shape == upper.shape assert (lower.array <= upper.array).all(), " lower is larg...
69,178
def main(lr=None, log_path_end='', bs=None, train_epoch=None, lambda_list=None, random_mirror=False, random_scale=False, model_weight=None): """Create the model and start the training.""" tf.reset_default_graph() args = get_arguments() """ Get configurations here. We pass some arguments fr...
69,179
def make_category_to_builders_dict() -> Dict[ str, List[tfds.core.DatasetBuilder] ]: """Loads all builders with their associated category.""" datasets = _all_tfds_datasets() print(f'Creating the vanilla builders for {len(datasets)} datasets...') with futures.ThreadPoolExecutor(max_workers=_WORKER_COUNT_DATA...
69,180
def trajnet_sample_eval(pred, gt): """Calculate ADE, FDE, Pred_Col, GT_Col for one sample. pred = Num_ped x Num_timesteps x 2 gt = Num_ped x Num_timesteps x 2 """ return ade(pred, gt), fde(pred, gt), pred_col(pred, gt), gt_col(pred, gt)
69,181
def bbox_hflip(bboxes, img_width): """horizontal flip the bboxes ^ ............. . . . . . . . . . . . . ............. ^ Args: bbox (ndarray): bbox ndarray [box_nums, 4] flip_code (int, optional): [description]. Defaults...
69,182
def create_arg_parser(): """" Creates and returns the ArgumentParser object. """ parser = argparse.ArgumentParser(description='Parses git log output object for change-log generation.') parser.add_argument('-b', '--branch', default='dev', help='current git branch checked out') ...
69,183
def _pathjoin(a, b): """ POSIX-like path join for Globus Transfer paths As with _normpath above, this is meant to behave correctly even on Windows systems """ if not b: # given "" as a file path return a elif b.startswith("/"): # a path starting with / is absolute return b ...
69,184
def extract_kernel_version(deb_package): """ Read filename for linux-image Debian package and return only the kernel version it would install, e.g. "4.4.4-grsec". """ # Convert to basename in case the filter call was not prefixed with '|basename'. deb_package = os.path.basename(deb_package) ...
69,185
def is_current_user_admin(request): """Checks whether the current user is an admin.""" user = get_current_user(request) if user: return user.is_superuser else: return False
69,186
def _load_fidel_to_opt_parameters(param): """ Loads fidel_to_opt parameters. """ if isinstance(param, (list, tuple)): ret = [] for elem in param: ret.append(_load_fidel_to_opt_parameters(elem)) else: ret = param # just return the param if isinstance(param, unicode): ret = unicode_to_st...
69,187
def get_sans(names): """ :param SubjectAltNames names: :rtype: dict[str, bool] """ sans = dict() if names.dns_allowed is not None: sans[RPA.TPP_DNS_ALLOWED] = names.dns_allowed if names.ip_allowed is not None: sans[RPA.TPP_IP_ALLOWED] = names.ip_allowed if names.email_all...
69,188
def get_observed_I_and_R(country: str, is_country: bool = True): """ Gets the data for the number of confirmed cases and the number of recovered. :param country: The country or province for which to get the cases :param is_country: Whether the country variable is for a country or for a province :re...
69,189
def ClearChannelRequestHeader(sid, cid): """ Construct a ``MessageHeader`` for a ClearChannelRequest command. Clears a channel. This command will cause server to release the associated channel resources and no longer accept any requests for this SID/CID. Parameters ---------- sid : ...
69,190
def refine_pic_group_msg(ctx: GroupMsg) -> _PicGroupMsg: """群图片/表情包消息""" if not isinstance(ctx, GroupMsg): raise ContextTypeError('Expected `GroupMsg`, but got `%s`' % ctx.__class__) if ctx.MsgType == MsgTypes.PicMsg: return _PicGroupMsg(ctx) return None
69,191
def crunch_samples(standards, standards_exclude, timestamps_standard, signal_standard, peaks_idx_standard, peaks_area_standards, samples_filename=None, samples_directory='samples', ...
69,192
def copy27_for_setup(file_or_folder): # pragma: no cover """ Prepares a copy of the source for :epkg:`Python` 2.7, assuming the module follows the same design as *pyquickhelper*. @param file_or_folder file ``setup.py`` or folder which contains it """ # delayed import from .py3to2...
69,193
def str_static_gen(size): """Returns an encoded static string of length 'size'.""" msg = '\n' msg += '__________Hello_World__________' while (len(msg)) < (size): msg += num_to_char(len(msg) % 16) msg = (msg[:size]) if len(msg) > size else msg return msg.encode('ascii', 'replace')
69,194
def rank(M,pref=None): """ Rank solutions: - By Pareto front subpopulation - Distance to ideal vector """ distance = dist(M,pref=np.abs(pref)) fr, fix = fronts(M) strata = np.zeros(shape=len(distance),dtype=int) for i in np.arange(0,len(fix)): for j in fix[i]: ...
69,195
def test_update_used_keys(db_context: DatabaseContext): """3 main scenarios to test: - 2 x settled txs and zero balance -> used key gets deactivated - 2 x unsettled tx -> not yet used (until settled) - 2 x settled tx BUT user_set_active -> keeps it activated until manually deactivated""" masterkey_...
69,196
def test_filter_single(): """Applying filtering to a single observation sequence""" assert_equal(filt(X), Filter(**filt_kwargs)(X))
69,197
def calculate_temperature_factor( temperature_active: float, power_ratio: float, ) -> Tuple[float, float]: """Calculate the temperature factor (piT). :param temperature_active: the ambient operating temperature of the resistor in C. :param power_ratio: the ratio of operating to rated power ...
69,198
def probability(vector, x, t): """ Finds the probability of vector[x] in t occurnences If x is not in vector then the probability is .001/t @param {Vector} vector {int} x {float} t @return {float} """ t = t*1.0 return vector[x] / t or 0.001 / t
69,199