content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _element(_tag_name, *args, **kwargs): """Construct a subclass instance of :class:`TagBase` with the given tag name. All other arguments are forwarded to the :class:`TagBase` constructor Parameters ---------- _tag_name : str The name of the tag type to create *args Arbitr...
64d9669aca47d4b525a3f25e72ef66eb8217792d
70,200
def missing_pmids(rsid, pmids): """Check DB, return list of missing pmids (article ids) for given rsid Args: rsid (str): rs12345 pmids (list): list of all pmids for given rsid; pulled from LitVar Returns: list: list of pmids not yet in DB """ cnx = fn.create_connection...
4610d248691ca2e880a011445ca4566b6ca68a02
70,201
def pool_forward(A_prev, hparameters, mode="max"): """ Implements the forward pass of the pooling layer Arguments: A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) hparameters -- python dictionary containing "f" and "stride" mode -- the pooling mode you would like to...
e3bc415424ed26a76270ae9c1c9016109cfef7c7
70,202
def get_user_ratings(top_100_path='../data/processed/top_100.csv'): """Collects user (i.e., person requesting recommendations) ratings for a set of ten movies randomly selected from the top 100 movies (i.e., those movies with the best ratings from the set of movies with more than 50 ratings.) Returns ...
d27cc8cbdc1c488b36e05cdc44d9a91b864462aa
70,203
def generate_relationship(min_rel_tuple): """ Generate full relationship object from minimal description. Generates full scholix relationship object from minimal relationship description provided as a triplet (source, relation, target). """ def _gen_identifier(identifier, scheme=None, url=None)...
0451732efbef35708502a4d78b530959e3055ff8
70,204
def vTLTscaled(y, g, rho, eta): """ """ return (2 - (1 - np.power(eta, 2)) * (1 + np.power(rhom(rho, eta), -2))) * np.power(rho * eta - 0.5 * (1 + np.power(y, 2)), 2)
f8207b18ce0978b2d57eba5f470a15d5f9220dff
70,205
import unittest def run_tests(): """Run test complete test_suite""" runner = unittest.TextTestRunner() if not runner.run(suite()).wasSuccessful(): print("Test suite failed") return 1 else: print("Test suite succeeded") return 0
b1ff6714828035487b322e930dfbc5d4cac98419
70,206
def solution(InitCond,ParamStruct,ClockStruct,weather_step,Outputs, canopy_step=np.nan): """ Function to perform AquaCrop-OS solution for a single time step *Arguments:*\n `InitCond` : `InitCondClass` : containing current model paramaters `ClockStruct` : `ClockStructClass` : model time parama...
b3b8e97fd16fda7e3587a4d68bba82a37896a2ef
70,207
def getViewAndType(iView): """Returns the view boolean and YieldTypes enum given the give number 0-3.""" if iView == 0: return (False, YieldTypes.YIELD_FOOD) elif iView in (1, 2, 3): return (True, YIELDS[iView - 1]) else: BugUtil.error("RawYields - invalid view number %d", iView) return (False, YieldTypes.Y...
c200d7311f6fd8ec7930202f086785484cd0fbb8
70,208
def transform(record: dict, key_ref: dict, country_ref: pd.DataFrame, who_coding: pd.DataFrame, prov_measure_filter: pd.DataFrame): """ Apply transformations to JH_HIT records. Parameters ---------- record : dict Input record. key_ref : dict Reference for key mapping. countr...
5a66bfb9f11580efbf5ff8ef1d991db19387b98c
70,209
def sell(): """Sell shares of stock""" if request.method=="POST": if not request.form.get("symbol"): return apology("must provide correct Symbol") if not request.form.get("shares"): return apology("must provide correct Share") if not request.form.get("shares...
4224ba25dedaf3001d9b417f7cc0f1228b5c0b9b
70,210
from typing import Union import os def token(wb, args: Union[None, list] = None) -> int: """(Re)create the tokencert and tokenkey files""" if not wb: return 1 if not args: args = [] global AlienSessionInfo tokencert, tokenkey = get_token_names(True) ret_obj = SendMsg(wb, 'token', args, opts =...
7f51505ff8f1e2e9ac9ec6290463b3ecb1d743e5
70,211
def max_chroma(Jp, hp, Cpmin=0.0, Cpmax='auto', eps=1024*np.finfo(np.float).eps, clip=True): """Compute the maximum allowed chroma given lightness J' and hue h'""" Jpmin = 5.54015251457561e-22 Jpmaxv = 98.98016 Jpmax = 99.99871678107648 if clip: ...
663370f27fdf2e309eab6ab7591739fc8c4f014d
70,212
def add1(arr1, arr2): """ This version is hard-coded to accept 2 arrays only. """ output = [] for inner_list1, inner_list2 in zip(arr1, arr2): inner_output = [] for num1, num2 in zip(inner_list1, inner_list2): inner_output.append(num1 + num2) output.append(inner_o...
7d90bb432f77c34e743282e391c4ffe38623d659
70,213
def clean_text(text): """ text: a string return: modified initial string """ text = text.lower() text = REPLACE_BY_SPACE_RE.sub(' ', text) text = BAD_SYMBOLS_RE.sub('', text) text = text.replace('x', '') text = ' '.join(word for word in text.split() if word not in STOPWORD...
f2f719525e856d006713b5fe88f0eccb5574301e
70,214
def process_velocity(obs, pred): """ This function compose the velocity component of each trajectory and append it to the observed part of the trajectory. :param obs: observed parts of the trajectories (must be an Ntrajs x Ntime_step x 2 numpy array) :param pred: predicted parts of t...
1a8b10c40950317349b1d8abe61bb6ab3509f317
70,215
def basic_z_dipole_monopole(prefactor=Z_DIP_PREFACTOR, \ z_redshift=REDSHIFT, \ beta=Z_DIP_BETA, \ theta=THETA, \ monopole=Z_DIP_MONOPOLE,\ *args,\ **kw...
1927866e9d3976f0fa29c1c8943421697a3af8a2
70,216
import time def wait_for_results_to_refresh(driver): """ Wait for the results to refresh Wait for 90 seconds for the element indicating that the results are being refreshed to be gone. Parameters ---------- driver : WebDriver Webdriver for the Terna web page. ...
ed4c01371eff720e3377d2ff63fb314536ffffd0
70,217
def _to_list(x): """This normalizes a list/tuple or single element into a list. If a single element is passed, we return a list of size 1 containing the element. Arguments: x: list or tuple or single element. Returns: A list. """ if isinstance(x, (list, tuple)): return list(x) return [x]
526a1446fde7217518a26b6f17993fb7f9d74227
70,218
def aggPosition(x): """Aggregate position data inside a segment Args: x: Position values in a segment Returns: Aggregated position (single value) """ return x.mean()
e9305d26f05710cc467a7fa9fd7b87737b8aa915
70,219
from typing import List def evaluate_population(population: List[Image]) -> List[Image]: """ Calculate fitness per entity, return ordered """ scores = [fitness(entity) for entity in population] for i in range(len(population)): population[i].fitness = scores[i] # sort population in or...
1db3ee445000a99390aed97af16abcc8555ac1ba
70,220
def compute_bwd(node_pot, msg_in): """Compute the new backward message from the given node potential and incoming message.""" node_pot = node_pot.unsqueeze(1) msg_out = msg_in.clone() msg_out[:, 1:] = logaddexp( msg_out[:, 1:], node_pot.expand_as(msg_in[:, :-1]) + msg_in[:, :-1] ) # ...
94c3c3509bd0b3138a5f093bf5658adabbd54e19
70,221
from operator import eq def normal_qr_transform(in_expr, out_expr): """Produce a relation for normal-normal regression and its QR-reduced form. TODO XXX: This isn't entirely correct (e.g. it needs to also transform the variance terms), but it demonstrates all the requisite functionality for this kind...
c5a57daa4c1bf10a58990e57d09ac5fbe9b4c4bd
70,222
import functools def wraps(wrapped, wrapper): """Contionally copies all the attributes a Wapi function can define""" assigned = ('__module__', '__name__', '__doc__') conditionally_assigned = ('_required_parameters_', '_optional_parameters_', '_read_only_', '_write_only_', '...
0ffeebc62b9c5569ff991fcd09cfbdb425d9f267
70,223
def dupfilter(cls=None, **kwargs): """ 去重服务 :param cls: :param kwargs: :return: >>> bf = dupfilter() >>> url1 = 'http://a.com/1' >>> bf.add(url1) >>> bf.add(url1) >>> bf.add(url1) >>> url2 = 'http://a.com/2' >>> bf.get(url1) True >>> bf.get(url2) >>> bf.add('...
c8776f60a36fa1cddbc64714d3ca2870e27a0eef
70,224
def wish_dist(Wi,Wj,k): """function to find the Wishart between two covariance matrice Returns distance Parameters ---------- Wi,Wj : comaplex amtrix covariance matrices k : int distance definition type to be used for calculation. Returns ------- data : float ...
2d795c5800fff2f12277340331d4ba697e930882
70,225
def task_check(): """ Check the system dependencies. """ return dict( file_dep=['check_system.py'], targets=[fname.system_check], actions=['python check_system.py'] )
e4fa25d62e53c5b5c708d1a0a10c3f0a434e1829
70,226
def is_authenticated(): """ Check if token for is not expired """ curr_user = User.check_request(request) user_is_authenticated = curr_user.is_authenticated() username = curr_user.username if user_is_authenticated else None return {'is_authenticated': user_is_authenticated, 'username':...
693e2d39a33f49ddc71c0c7cb9e04afb46bf5361
70,227
import logging def cpu_allocation_ratio_check(): """ cpu_allocation_ratio_check """ logger = logging.getLogger(__name__) traced_value = trace_cpu_allocation_ratio() required_value = required_cpu_allocation_ratio() result = {'category': 'compute', 'case_name': 'cpu_allocatio...
3e35ad85794c0781c3100150e6eeb15ec75e663a
70,228
import json def get_mempool_descendants(bitcoin, txid, verbose=False): """ Get all in-mempool descendants if txid is in the mempool More info: https://developer.bitcoin.org/reference/rpc/getmempooldescendants.html :param bitcoin: src.bitcaviar.config.Bitcoin, required :param txid: string, required...
ed718a2e40197cd7021457f55e09d7a993814c12
70,229
def _saml_args(): """Get entity_id and acs_url from request.headers.""" entity_id = request.url_root[:-1] # remove trailing slash acs_url = urljoin(request.url_root, POSTBACK_ROUTE[1:]) if 'X-Saml-Entity-Id' in request.headers: entity_id = request.headers['X-Saml-Entity-Id'] if 'X-Saml-Acs'...
5501544b8bc53ace9d6addb09494f3c544fa8db0
70,230
def _autoformat(char, val, field_to_unpack=None): """ Given a characteristic and 'val' bytes, obtain the BitField values """ fields = {} if not field_to_unpack: for field in char.fields: if "Ctype" in char.fields[field]: # ctype = char.fields[field]['Ctype'] ...
c4425a3cca092b2a1f86fd57806ee9a28d070a37
70,231
from typing import Tuple def empty_handler() -> Tuple[()]: """ A stub function that represents a handler that does nothing """ return ()
1450ea04fefc4ad432e5d66a765bda0f5239b002
70,232
def hash_tweet_dataFrame(dataFrame_dict): """ 根据每一条记录的origin_tweet_id将所有的tweet重新hash一下,这样就能保证一个相同的origin_tweet都放在一个dataFrame中,不用在进行夸dataFrame查找。 :param dataFrame_dict:原始按照文件存储的dataFrame。 :return:hash之后的dataFrame。 """ tweet_hash_dict = {} for index in range(0,100,1): tweet_hash_dict['...
a24a47869947da90eebdf20f1cc2392823e62aa9
70,233
def get_search_results(twitter_dict, spec_dict): """(Twitterverse dictionary, search specification dictionary) \ -> list of str precondition: The first parameter represents the data in the \ valid Twitterverse dictionary format, and the second parameter represents \ the search specification in the ...
7d74e5c70e6509a4ab6a1a29ae7e3b358a320662
70,234
def test_has_quorum_intersection_true_sccs(): """Test has_quorum_intersection() with intersection with three sccs""" slices_by_node = { 1: [{1, 2}, {1, 3}], 2: [{2, 1}, {2, 3}], 3: [{1, 3}, {2, 3}], 4: [{1, 4}], 5: [{2, 5}] } def is_slice_contained(nodes_subset, ...
2fc76c768f34cf785a79a35a2a662da0c42adaf1
70,235
import torch from typing import Tuple from typing import Union import warnings def data_parallel(raw_model: torch.nn.Module, *args, **kwargs) -> Tuple[Union[torch.nn.Module, torch.nn.parallel.DataParallel], bool]: """ Make a `torch.nn.Module` data parallel - Parameters: - raw_model: A target `tor...
5b98f0e7c67ac067aba9a9c5202cceded91827ac
70,236
def set_srcpath(sourcepath): """ Set the sourcepath where the inspection is conducted """ inspsettings.set_sourcepath(sourcepath.strip("'")) return get_srcpath()
0e63dddb57e7b4afb68da8b6a1e0923b595575fd
70,237
def find_gpa(courses): """ The function reads the list input courses. The function next initializes the variables total_grade_point_credit and total_credits by setting the equal to 0. Next the function uses a for loop to read the course list. Then the loop iterates through the course list and adds the total n...
72d04443cc3993b225214f670854e8f4704f9ccf
70,238
def register(): """Register a new user, and send them a confirmation email.""" form = RegistrationForm() if form.validate_on_submit(): zip_code = ZIPCode.create_zip_code(form.zip_code.data) user = User(first_name=form.first_name.data, last_name=form.last_name.data, ...
dea62f5ffd36da5504be9cbbad389817dc338ba7
70,239
def _register_visited_model(json_reference, model_spec, model_name, visited_models, is_blessed, swagger_spec): """ Registers a model that has been tagged by a callback method. :param json_reference: JSON Uri where model spec could be found :type json_reference: str :param model_spec: swagger specif...
8603ad81349cd0c0839e88ee75de18fb397a3374
70,240
def collide_circle(left, right): """detect collision between two sprites using circles pygame.sprite.collide_circle(left, right): return bool Tests for collision between two sprites by testing whether two circles centered on the sprites overlap. If the sprites have a "radius" attribute, then that ...
3e55b7b854bcc3032e93cad79f00b28b3f14715d
70,241
def quote(data): # type: (str) -> str """Percent Encodes the string. Args: data (str): String which is required to be Percent Encoded. Returns: str: Percent encoded string. """ # With current setting, it will encode all necessary characters. # To prevent any character from...
7dc168a40a5e44f76e8f1ed8360ee71dfa668190
70,242
import argparse def int_type_check(min_val, max_val = None, metavar = None): """ Creates an argparse type for a range-limited integer. The passed argument is declared valid if it is a valid integer which is greater than or equal to min_val, and if max_val is specified, less than or equal to max_val. ...
4baa0b9a4b78cb3c493518781f4f7365e1137c73
70,243
from datetime import datetime def extent_pid(*args): """ This function provides the lat lon extent limits for different durations during which the Edmond-Carney supercell was analyzed SPECIFICALLY FOR PID ANALYSIS. The utility is to restrict our computations only to the domain within which...
7acf8ab2d86481815e2411579f62343b1fd822a4
70,244
def spamhaus_call_error(res): """ :param res: Object returned from ResilientCommon.execute_call_v2 call :return: res or raise an SpamhausRequestCallError with the reason """ if res.status_code == 200 or res.status_code == 404: return res else: raise IntegrationError("Call to Spa...
33c25c3a22a49851bb56c3cbe8d0065432b6b2e2
70,245
import torch def structure_entropy(relation_matrix): """ :param relation_matrix: (B, Ni, Nj) :return: (B, Ni) """ nj = relation_matrix.size(-1) # convert to tensor nj = torch.tensor(float(nj), device=relation_matrix.device) out = entropy(relation_matrix) / torch.log2(nj) return ...
c5499b0e62b1f24fd666afa137c355e72821b1a9
70,246
def _reindex_dates(group, freq): """ Helper function for fill_missing_dates() """ date_range = pd.date_range(group.index.min(), group.index.max(), freq=freq) group = group.reindex(date_range) return group
7f6ef0e8c18a166fbf77cc67f43afc0bc458b540
70,247
def epoch_from_nc(ncfile): """ Extract the epoch from a netCDF data set and return as a datetime. (Assumes the netCDF dataset schema matches those used in AWRAMSI - notably that there is a 'time' variable with the epoch expressed in the units property) """ epoch = ncfile.variables['time'].u...
ef20f81140888701fbb4778baaa3745aad18c4b0
70,248
import re def abs(table, field): """ For a given <fieldname>, returns the absolute <tablename>.<fieldname>. This is useful when constructing queries with relations to other tables. """ def _format(s): if "." not in s: # Field could be wrapped in a function: year(date) => year(t...
9204e16555773c5bc6fe7328ef499a458849f87c
70,249
import syslog import pickle def writestatusdict(status): """ Writes our status file to disk """ try: syslog.syslog("Attempting to write noip-settings.txt") fh = open("noip-settings.txt", "w") except IOError as ioerr: syslog.syslog("%s" % ioerr) return False else...
f225c5622179df7d52cf16371f1c60a5fdcb2f7c
70,250
from datetime import datetime def to_utc(dt): """ Convert a datetime into datetime as utc time""" return datetime.datetime.utcfromtimestamp(dt.timestamp())
73c633fcfd696e91a02b6d3e4f684e40cb1bdc16
70,251
import ast def macro_bindings(tree, *, syntax, expander, **kw): # tree argument is unused """[syntax, name] Capture the macro expander's macro bindings. This macro snapshots the macro expander's current macro bindings at macro expansion time (when the invocation of `macro_bindings` is reached), and ...
660cc2b9cb9864fd95d16624a6eb7a40e8e73475
70,252
def get_vgg_rcnn(num_classes=config.NUM_CLASSES): """ Fast R-CNN with VGG 16 conv layers :param num_classes: used to determine output size :return: Symbol """ data = mx.symbol.Variable(name="data") rois = mx.symbol.Variable(name='rois') label = mx.symbol.Variable(name='label') bbox_t...
3489363a2ad4f339895b7d3a60e4279c46a8809d
70,253
from typing import Any from typing import List def parse_args_and_update_config(config: Any, args: List[str]) -> Any: """ Given a model config and a list of command line arguments, creates an argparser, adds arguments from the config parses the list of provided args and updates the config accordingly. Ret...
c9d5fbb1806f8a3c0698581e4cbf2fb267db7430
70,254
from typing import Tuple import warnings def tune(kernel, kernel_name: str, device_name: str, strategy: dict, tune_options: dict, profiling: bool) -> Tuple[list, int]: """ Execute a strategy, return the result, runtime and optional profiling statistics """ def tune_with_kerneltuner(): """ interface w...
5bf7474460fdade7502f70d2f4faf74a66ea09da
70,255
import random def hibachi(pop,gen,rseed,showall): """ set up stats and population size, then start the process """ MU, LAMBDA = pop, pop NGEN = gen np.random.seed(rseed) random.seed(rseed) pop = toolbox.population(n=MU) hof = tools.ParetoFront(similar=pareto_eq) if showall: ...
455988d73041ad3439be9f551efc5f1b031beced
70,256
def sbm(n_blocks, block_size, p, q, rng=None): """ (Symmetric) Stochastic Block Model Parameters ---------- n_blocks : int Number of blocks. block_size : int Block size. p : float Probability for intra-community edge. q : float Probability for inter-community...
dd5172fc449f42678f71e62c904c7efc88ceda0b
70,257
def negate(value, width = None): """ Returns the two's complement of 'value'. """ if width is None: width = context.bits mask = ((1<<width)-1) return ((mask+1) - value) & mask
26f954d795ad2bc08b663e4c91381b7a4546b349
70,258
def content(fid, share_key=None): """ Retrieve full content for the grid (normal retrieve only yields preview) :param (str) fid: The `{username}:{idlocal}` identifier. E.g. `foo:88`. :param (str) share_key: The secret key granting 'read' access if private. :returns: (requests.Response) Returns resp...
7c3ad46d94cd57c9a2c3efaf4272557b2dc28e18
70,259
def parse_args(args): """Parse the command line parameters.""" root_parser = ArgumentParser() root_parser.add_argument( '--version', action='version', version=__version__) file_parser = ArgumentParser(add_help=False) file_parser.add_argument( 'file', metavar...
6a8535422239c5dbb69b3bdf3319371f33f96516
70,260
def retrieve_context_topology_node_node_rule_group_name_name_by_id(uuid, node_uuid, node_rule_group_uuid, value_name): # noqa: E501 """Retrieve name by ID Retrieve operation of resource: name # noqa: E501 :param uuid: ID of uuid :type uuid: str :param node_uuid: ID of node_uuid :type node_uui...
18a41a66ed2d9d584cdff68d2cd2d42709df8fe0
70,261
def main(): """Script entry point.""" args, params = parse_args_curious_a2c(AgentCuriousA2C.Params) return train(params, args.env)
961b5a0d5c3577e8e0262304a94d59df67241379
70,262
from typing import Optional from typing import Dict import os import sys def _prepare_build_environment(cross_lib: Optional[str]) -> Dict[str, str]: """Prepares environment variables to use when executing cargo build.""" # Make sure that if pythonXX-sys is used, it builds against the current # executing ...
ef861b68dbdbef382afa03358f010ae281746943
70,263
def multitask_accuracy(*args) -> float: """ Accuracy for multiple simultaneous tasks. Args: *args: a list of `2n` inputs. The first `n` inputs are the correct answers for `n` tasks, and the last `n` are the predicted ones. Returns: The percentage of inputs where the answers...
a86a130811a6d77ca5eee9d07ce126951f4d2209
70,264
def generate_gp(params, fsample, flux_err): """ Sets up the initial parameters for all the walkers using optimized parameter values as starting values. The function generates a scattered multivatiate gaussian distribution of starting parameter values. Parameters ---------- params : lis...
ff7a09b11f07cd595d34f5fc42d8d7c6fe9102eb
70,265
def prepped_to_colloc(seedlist, nldata='news2011procd_dev', iterations=2, thesname="collocationthesaurus001.txt", nlevels=50, mincut=3, devmode=1): """take natural language passages, and isolate the most common ordered collocations (as if they are tuples). Using the lead ...
0fd55ba93f176bca68b0b06dcfcabd7f6c18e14a
70,266
import copy def disambiguate_stmts(G): """ Append a #number to statements in order to disambiguate them :param G: graph :return: disambiguated graph """ # Helper dictionary appear_dic = dict() for ed in list(set([e[2] for e in all_edges(G, data=True)])): appear_dic[ed] = 0 ...
66a08ddd6e187155b8615c64294f0e629c0e3b13
70,267
def get_logo_url(object): """ Gets firm_name from logged in user and obtains firm logo""" return FirmProfile.objects.get(firm_name="Mater Compan").logo.url
909072d2c45d493713467196cc8ae5039d3d3b0e
70,268
import logging import os def interactive_step(t, test_dir): """Execute an interactive demo step""" logging.info("Expect step: '{}'".format(t['name'])) cmd = open(os.path.join(test_dir, t['filename'])).read() child = pexpect.spawn(cmd) status = True for action in t['expect']: ...
e428c61b20d5d22cbeda126e12248751bb5d83eb
70,269
from typing import OrderedDict import time import os import csv import itertools def init_params(): """Set up the simulation parameters.""" p = OrderedDict() p['noPolicySim'] = False p['multiprocessing'] = False p['numberProcessors'] = 9 p['numRepeats'] = 1 p['startYear'] = 1860 ...
1161be980a63dbc5a29ff7852a4780d249822fcd
70,270
def imported_modules(repo): """Return a set (as tuple) of toplevel module names this repo could import.""" imports = set() for root in repo._calc('asts').itervalues(): for node in pyast.walk(root): if isinstance(node, pyast.Import): for alias in node.names: ...
4cc27ed3063fb9009bcdb83ee2d8b8456d99bbf8
70,271
import time def _request_confirmation(question): """require user input to continue""" while True: user_input = input(f"{question} [y/n] ").lower() if user_input not in {"y", "n"}: _log.info("Please enter 'y' or 'n'.") elif user_input[0] == "n": return False ...
c3dd3a8bf5c9d8e6b01793a6c218865f47e886f4
70,272
from typing import Optional from typing import Any def errorbar( hist: BootstrapHistogram, ax: Optional[MplAxes] = None, **kwargs: Any ) -> Any: """ Plot the bootstrap sample mean and standard deviation. Parameters ---------- hist: bootstraphistogram.BootstrapHistogram the :py:class:`...
cba5d33996c291025789c400f253b7c76cb5e93d
70,273
def add_to_list(str_to_add, groups): """ This will add a string to the GROUPS array if it does not exist. It will then return the index of the string within the Array """ if str_to_add.replace(".", REPLACE_CHAR) not in groups: groups.append(str_to_add.replace(".", REPLACE_CHAR)) return g...
6abf99460064899b49918b5d58246d69b5461750
70,274
def experiment_publish(request, pk, slug): """Experiment publish view: sets experiment to completed, saves it and shows publish view""" experiment = verify_and_get_experiment(request, pk) experiment.completed = True experiment.save() return render(request, 'experiments_manager/experiment_publish.htm...
eceddc4d91939b3d145a3934d7c92daaeee71e36
70,275
def get_visibilty(item_container): """ """ if item_container.visible_start == item_container.visible_end: return ' <i>[' + u'%s' % item_container.visible_start.strftime('%d.%m.%Y') + ']</i>' else: return ' <i>[' + u'%s-%s' % \ ( item_container.visible_start.strftime('%d.%m.%Y'), ...
ac3b433651acb5743ed6bcef88594575144312da
70,276
import io def get_version(sdf: str) -> str: """Returns the version of a SDF string. Parameters ---------- sdf : str The SDFormat XML to be parsed. Returns ------- version : str A string containing the SDF version, e.g. "1.8". Notes ----- This function only ch...
f5067dbb97599b6a9cde980a04190ec4e364940f
70,277
def edp_unordered_straight(r, c, black_list): """ Euclidean Distance with Penalties, for route starting and ending at different cities every 10th city is penalized if it is inside the black list The City IDS need not be sorted :param r: route :param c: cities (the city IDS must be sorted!) ...
f607c12d04ea95a8b4a19d7e6f55738e11666d81
70,278
def randomVector(n, seed=None, normalize=True): """ Computes a list of random normalized xyz axes """ np.random.seed(seed) if normalize: return _vectorNormalize(1 - np.random.random((n,3,))*2) return 1 - np.random.random((n,3,))*2
a4f0745f1854835ffa1c1ce777834a9bba339429
70,279
from typing import Collection from typing import Optional from typing import cast from typing import Dict def get_wards_for_sub_county(sub_county: str) -> Collection[FieldChoice]: """Return a `Collection` of choices of the wards of the given sub-county. If the given sub-county doesn't exist, an empty `Collec...
cc528b2520f868ed95ea11756b81c51999e1d76f
70,280
def get_cube_time_info(cube): """Return year, month and day from the cube.""" coord_time = cube.coord('time') time = coord_time.cell(0).point time_step = time.strftime("%Y%m%d") return time_step
35ea97aaecd41a4494753c11abd2ba6c9737faad
70,281
from typing import Union from typing import Sequence from typing import Optional from typing import Dict def exclude_subjects( excluded_subjects: Union[Sequence[str], Sequence[int]], index_name: Optional[str] = "subject", **kwargs ) -> Union[pd.DataFrame, Dict[str, pd.DataFrame]]: """Exclude subjects from dat...
fde9ce2dc5d8513a763faf8d81a9ae964d8da3e4
70,282
def expvals_mps(mps, oplist=[], sites=None, output_label=None, canonised=None): # TODO: Why canonised gives strange results? """ Return single site expectation values <op>_i for all i Parameters ---------- mps : MatrixProductState oplist : list or Tensor List of rank-two tensors rep...
d307a099cf323cec6dbd5d821173c5476d7d2511
70,283
def scale_samples(samples_norm, limits, limits_norm=(0, 1), do_log=False): """Scale samples to new limits, either log10 or linearly. Args: samples_norm (ndarray): The normalized samples to scale, with dimensions (nsamples,ndims). limits (list of tuples): A list of (min, max) for the...
36090311be4ccb07eb0c946d07b51b9ec20dc0e2
70,284
import itertools def get_account_record_list_only_latest_updated_records(pcoll): """Returns list of account records deduped by max updated field.""" return dedupe_account_records_by_max_updated_field( itertools.chain.from_iterable(map(attrgetter('account_list'), pcoll)))
76427176de6dc7b1ad97dadf63fcb37d39938769
70,285
def _merge_dart_context(dart_ctx1, dart_ctx2): """Merges two dart contexts whose package and lib_root must be identical.""" if dart_ctx1.package != dart_ctx2.package: fail("Incompatible packages: %s and %s" % (dart_ctx1.package, dart_ctx2.package)) if dart_ctx1.l...
4da2c2d35a306af73279c4b8d323affbe6ed83a9
70,286
def get_elmo(model, words, batch_size=16): """ Get elmo embeddings :param words: list :param model: elmo model :param batch_size: batch size (should be 16) :return: """ vector_list = [] # Create batches batch = [] for i in range(0, len(words)): word = words[i] ...
c258bc53b381bee952cbdda883e882f98ce2597b
70,287
async def async_setup(hass: HomeAssistant, config: dict): """Set up the Channels DVR Recently Recorded component.""" hass.data.setdefault(DOMAIN, {}) return True
f3c53d7425c5fc541ec430f4213d775d79423ae2
70,288
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understan...
71825a6fa06ff29095a1ce89e97c5d1ec687e97c
70,289
def comparador_3numeros(a,b,c): """int,int,int-->int,int,int OBJ:comparar los números introducidos""" if a>b and b>c: sol=str(a > b > c) elif a>b and c>b: sol=str(a > c > b) elif a<b and a>c: sol=str(b > a > c) elif c<b and a<c: sol=str(b > c > a) elif c>a and a>b: sol=str(c > a > b) els...
6d0fee4cffb72b41641702821491d98cd69bccb0
70,290
def list_articles(request, month, year): """liste des articles d'un mois precis.""" return HttpResponse( "Vous avez demande les articles de {0} {1}".format(month, year) )
cc6e2c6b11f1c5bbd6107c2177f0774aa7b26a79
70,291
from typing import Dict import http def ckey(attrs: Dict[str, str], f: http.HTTPFlow) -> TOrigin: """ Returns a (domain, port, path) tuple. """ domain = f.request.host path = "/" if "domain" in attrs: domain = attrs["domain"] if "path" in attrs: path = attrs["path"] ...
a9764288b3a33c6c91e071dc1b362613e3bd8713
70,292
def count_digit(n, digit): """Return how many times digit appears in n. >>> count_digit(55055, 5) 4 >>> count_digit(1231421, 1) 3 >>> count_digit(12, 3) 0 """ if n ==0: return 0 if n % 10 == digit : return count_digit(n//10,digit) + 1 else: return cou...
e1bf453825dbd00f91be3e86d9e6b2bc586f1e30
70,293
def double(x): """ >>> double(3) 6 :param x: :return: """ return np.multiply(2, x)
13ad47060e21930946927b5ab914d28f3124eb83
70,294
def get_current_organisation(): """ Get the current organisation. """ global organisation if organisation is None: organisation = gazu.person.get_organisation() return organisation
16ebd69312943814aa16293f5f41a3b8cb73b228
70,295
def get_fast_regressors(): """Get a list of very fast regressors. Returns ------- fast_regressors : list of sklearn estimators List of regression models that can be fitted and evaluated very quickly. """ return [ DummyRegressor(), DecisionTreeRegressor(max_depth=...
3e776e78c79d752627d50d30c7ee832d4cc8a912
70,296
def dataframe_from_bulk(data, tz_offset): """ Create a Timeseries dataframe from a dict of ndarrays. Args: bulk_data(dict): tz_offset: pandas Offset or None Returns: pandas DataFrame object """ timestamp = pd.DatetimeIndex(data['timestamp']) if tz_offset is not None...
46e2a5d827ed9f6b698907acb8b8d7723e099e38
70,297
def get_label_map_dict(label_map_path, use_display_name=False, fill_in_gaps_and_background=False): """Reads a label map and returns a dictionary of label names to id. Args: label_map_path: path to StringIntLabelMap proto text file. use_display_name: whether to ...
8d960c230cf32f514ebbcfc211a5c004ce9620df
70,298
def eq104 (A, B, C, D, E, T): """Chemsep equation 104 :param A: Equation parameter A :param B: Equation parameter B :param C: Equation parameter C :param D: Equation parameter D :param E: Equation parameter E :param T: Temperature in K""" return A + B/T + C/(T**3) + D/(T**8) + E/(T**9)
57789dd811dc09bd097a52aca6a776b94ee05b95
70,299