content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def sum_fun(x, backend): """ Base function for summing all elements in a tensor """ func = "sum" if backend == "tensorflow": backend = "tensorflow.math" func = "reduce_sum" return get_func(func, backend)(x)
6c5231f67ed3f464dd7bf3bbbe3b0ed6c6fb6740
67,365
def measure_naptan_groups(gdf, naptan_column_name="LocalityName"): """[summary] this function measures the number of groups present within the given geodataframe, when groupbed the [default LocalityNames] Args: gdf ([type]): [description] naptan_column_name ([type]): [description] Ret...
725ce929fb19f0e2fdf051f6daf9c1d86e125d0f
67,367
def CreateParser(): """Expose _CreateParser publicly.""" # Name _CreateParser is needed for commandline library. return _CreateParser()
888ec2237c0e4bda8c44f5fece4f184f1e870e2c
67,368
def update_dataset(dataset_id: int, request: schemas.DatasetUpdate, db: Session = Depends(deps.get_db), current: model.User = Depends(deps.get_current_user)): """ Update a dataset. """ dataset = crud.dataset.get(db=db, id=dataset_id) if datase...
5a72a30b0a27cd9df97c6131cd76785fc5050504
67,369
def calculate_ts_stability_index_batch(ts, **kwargs): """Returns series with stability index calculated for every point of ts, where possible""" si_values = [] timestamps = [] for time, row in ts.iterrows(): ts_history = ts[:time].iloc[:-1] try: si_value = calculate_ts_stabil...
a9bfaa3e3d8393443c1113d5356616067795ca0b
67,370
import click import functools def ip_lookup_command(function): """Decorator that groups decorators common to ip and quick subcommand.""" @click.command() @click.argument("ip_address", callback=ip_addresses_parameter, nargs=-1) @click.option("-k", "--api-key", help="Key to include in API requests") ...
1da900e8fd96e486f58e10708c99e797a818905a
67,371
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV def _is_parameter_search_estimator(estimator): """ :return: `True` if the specified scikit-learn estimator is a parameter search estimator, such as `GridSearchCV`. `False` otherwise. """ parameter_search_estimators = [ ...
24a1c51cea98b36923d6ac827d1c4481d75bb460
67,372
from typing import Dict from typing import List import re def clean_utterance(utterance: Dict[str, str], remove_english: bool = False, english_words: set = None, punctuation: str = None, special_cases: List[str] = None) -> (List[str], int...
362b835ec894495d74c984b082bb173ca2e27e1a
67,373
def get_all_functiondef(root): """ Get all FunctionDef nodes :param root: :return: """ if root['name']=='FunctionDef': # block(FunctionDef) begin id begin_id=root['id'] end_id=get_end_id(root) return 'begin:%s,end:%s'%(begin_id,begin_id+end_id-1) else: ...
b6687059c958d49795f0d2fb521bd8ca488c5507
67,374
def bookmark_json(userkey, urlhash): """ Serialise bookmark to json """ try: bookmark = Bookmark.get( Bookmark.url_hash == urlhash, Bookmark.userkey == userkey, Bookmark.status == Bookmark.VISIBLE ) return jsonify(bookmark.to_dict()) except Bookmar...
30321366ee5a32484664599d9223ff56ee0768e9
67,375
from typing import Mapping def betaReduce(lhs, lhsEnv, rhs, rhsEnv): """β-reduction: (λV.M)N → M[V := N]""" exp = lhs.exp if isinstance(exp, Mapping): return (exp.exp, Env(Mapping(exp.var, clos(rhs, rhsEnv)), lhsEnv)) else: return (exp, Env(clos(rhs, rhsEnv), lhsEnv))
1bd36a551280721596e502be0db2e5aa0a0b6d8b
67,376
def _check_for_iocs(loop, context, indent): """ Check the variables modified in a loop to see if they were set to interesting IOCs. """ indent_str = " " * indent lhs_visitor = lhs_var_visitor() loop.accept(lhs_visitor) lhs_var_names = lhs_visitor.variables ioc_str = indent_str + "# C...
f9d4a8fa2e1953314cb422882a2eb6d1e1f7b7eb
67,377
import ssl import concurrent async def patch( uri: str, headers: t.Dict[str, str] = {}, body: t.Optional[bytes] = None, json: t.Union[t.Dict[str, t.Any], JsonApiData] = None, query: t.Dict[str, t.List[str]] = {}, timeout: t.Optional[float] = None, blocksize: int = 8192, datacls: t.Type...
32101f2a036ee846fdd8a0c5ed7873f5726a3bfe
67,378
def edit_orcid(request): """ Send a user to orcid.org for authorization to link to their ORCID account, then redirect them to views/auth_orcid to save their iD and other token information. Also provide the option to unlink their ORCID account from their account. """ if request.method == 'POST'...
2305ac8e38430919a807bdd0612115992b416065
67,379
import math def calculate_distance(psi, angle_in_degrees): """ Calculate the distance the mudball flies. """ angle_in_radians = math.radians(angle_in_degrees) distance = .5 * psi ** 2 * math.sin(angle_in_radians) * math.cos(angle_in_radians) return distance
47eb9acb71f5c11b26002ec38e37410db62c2e05
67,380
import json def clear_dataflow_run(dataflow_run_id:str): """ Clear an orphaned dataflow run. :param dataflow_run_id: :return: """ payload = {"orchAction": "clear_dataflow_run", "dataflow_run_id": dataflow_run_id} json_payload = json.dumps(payload) pickledJsonObj = __bo...
453fee04e72c54b7f2891f5e7f5b89d913778f42
67,381
def custom_path_fs_io_manager(init_context): """Built-in IO manager that allows users to custom output file path per output definition. It requires users to specify a base directory where all the step output will be stored in. It serializes and deserializes output values (assets) using pickling and stores ...
04aeaa321d0b998959401ca6190cc45385edae79
67,382
def sghmc_naive_nomh_noresample_multi(du_hat_func, epsilon, nt, m, M, V, theta_init, r_init, formula): """ This is a function to realize Naive Stochastic Gradient Hamiltonian Monte Carlo without Metropolis-Hastings correction in multidimensional cases without resampling procedure. """ B = 1/2*...
e704394e1f7f8960bea804e6f1a9188acc069ff5
67,383
import pathlib import json def load_json(filepath): """ Loads the metrics in a dictionary. :param log_dir: The directory in which the log is saved :param metrics_file_name: The name of the metrics file :return: A dict with the metrics """ if isinstance(filepath, pathlib.Path): fil...
1dd8ff7822228bc0173a66df626902a723338d55
67,384
def super_scrub(data): """Run words through a comprehensive list of filtering functions. Expects a dictionary with key "words" """ for technique in data['words']: data['words'][technique] = normalization.uniquify( normalization.remove_odd_sounding_words( normalizatio...
d81557232ac99b89d24144c5d44bd94d41340d87
67,385
from typing import Callable import random def choose(option1: Callable = lambda: None, option2: Callable = lambda: None): """ Randomly run either option 1 or option 2 :param option1: a possible function to run :param option2: another possible function to run :return: the result of the function ...
0f0ecbc945de9f6d5698cd86103265eccf5708e6
67,386
def compute_embeddings(encoder, data_batches): """Computes sequence embeddings according to a specified encoder.""" vectors = [] for batch in iter(data_batches): X, Y = batch X_embedded = encoder(X) for vec in np.array(X_embedded): vectors.append(vec) vectors = np.ar...
5c9d6e9bb617e43522044255948639c01d6b06a4
67,387
def while_array_parser(self, desc, node=None, parent=None, attr_index=None, rawdata=None, root_offset=0, offset=0, **kwargs): """ """ try: orig_offset = offset if node is None: parent[attr_index] = node = desc.get(NODE_CLS, self.node_cls)\ ...
365d8d115f4b677177f1214c78d4957a78745252
67,388
def get_all() -> [User]: """ Helper function to return all users :returns: all users. """ return User.objects.all()
79864d2a862610bed414f2ad7cebbee20055e638
67,389
def get_category(id): """ Get category. """ category = Category.query.get(id) if category is not None: response = {"category": category.to_dict()} return make_response(jsonify(response), 200) abort(404)
15e1030b4c3b6e5d00f7697cd7e392a5bc5fcd8d
67,390
def get_repo_service(): """Factory method that returns configured RepoService instance. If the service is not configured, returns None. Also acts as a mocking point for unit tests. """ cas_service = cas.get_cas_service() if not cas_service: # pragma: no cover return None return RepoService( ca...
75966851961208486c1d28e5051f30266dfe7d0d
67,391
from typing import List def search_etfs(to_search) -> List[str]: """Search for an etf string in list of ETFs Parameters ---------- to_search: str String to match Returns ------- matching_etfs: List[str] List of matching ETF names """ all_symbols, all_names = get_a...
f56972605a45c5308a311eef1dac5ea34736aa2d
67,392
def separable_hnn_siren(input_h_s=None, input_model=None): """ Separable Hamiltonian network using Siren network. :return: """ if input_h_s: h_s = input_h_s model = input_model else: network = SirenNet( dim_in=2, dim_hidden=100, dim_ou...
08a1ef7d25304fcbd1d5ef568a420b70e0da0464
67,393
async def update_password(username: str = Form(...), old_password: str = Form(...), new_password: str = Form(...)): """パスワードの更新""" res = search_username(cur=cur,username=username) if res == None: raise HTTPException(status_code = 400,detail="ユーザーが登録されていません。") if not verify_password(old_pass...
bbec78a71eaf91fa92eeb1dd6d0f19fb7b767f63
67,394
import time def num_to_str_data(str_date: int) -> str: """ num to str format :param str_date: time of int format :type str_date: int :return: format time :rtype: str """ str_date = str_date / 1000 str_date = time.localtime(str_date) strp_time = time.strftime("%Y-%m-%d %H:%M:%S"...
e3fb56132a9d365d7bbc89e11e010d0d1ed19ea9
67,395
def transform_response_to_context_format(data: dict, keys: list) -> dict: """ Transform API response data to suitable XSOAR context data. Remove 'x-ms' prefix and replace '-' to '_' for more readable and conventional variables. Args: data (dict): Data to exchange. keys (list): Keys to fi...
34f1a613654deb71581bcd33757b8741840ae44f
67,396
def GetsoftwareVersions(node, layers='core') : """Get the schema:softwareVersion(s) we find on this node (or [] ), within any of the specified layers.""" return GetTargets(Unit.GetUnit("softwareVersion", True), node, layers=layers )
851678659540482c4b289410f1e9407c97990fbc
67,397
from typing import List import re from typing import Iterator def txt_channel_finder(bot: Red, chaninfo: str) -> List[discord.TextChannel]: """ custom text channel finder """ _id_regex = re.compile(r"([0-9]{15,21})$") def _get_id_match(argument): return _id_regex.match(argument) matc...
f751af05bdcdf207a42fd08e77fc780e14478fef
67,398
import torch def calculate_gradcam_metrics(no_norm_gc_mask_numpy: torch.Tensor, segm: torch.Tensor): """ Measure gradcam metric @param segm - true mask, shape B x 3 x H x W @param no_norm_gc_mask_numpy - Grad-CAM output w/o normalization, shape B x 1 x H x W @return sum of gradcam attention of ev...
4d3ab9c9a694b88ef83efcc94271d21d0c1f8e17
67,399
def gaussian_noise(img): """ Apply random noise to the image. """ cv.randu(img, 0, 255) return { "points": None, "line_map": None }
3ec289b7eb71db0c235082ea476952c0140f4f53
67,400
def per_field_value(values, fields): """ This normalises all patches relative to their field. 'fields' is a map of field numbers to a list of patches in that field. """ field_list = list(fields.values()) # We calculate the maximum and minimum values for each field. maxs = [max((values[inde...
b51e344463d4d75f21ab8fc3a58d6201249fc2dc
67,401
import torch def one_hot(y, K, smooth_eps = 0): # pylint: disable=invalid-name """One-hot encodes a tensor with optional label smoothing. Args: y: A tensor containing the ground-truth labels of shape (N,), i.e. one label for each element in the batch. K: The number of classes. smooth_eps: Labe...
ee47f9c778d875834c49c098ded4936edb104887
67,402
def grids(request, template_name="grid/grids.html"): """lists grids Template context: * ``grids`` - all grid objects """ # annotations providing bad counts #grids = Grid.objects.annotate(gridpackage_count=Count('gridpackage'), feature_count=Count('feature')) return render(request, template...
36110a0d5ce9192c9cf931b44c6aba2d193947bf
67,404
import random def generate(): """ Generates a quote based on the internal markov chain. :raises: ValueError: if parsing has not occured and the internal chain is invalid """ # If not parsed, fail. if not _GRAPH[_START]: raise ValueError("Please initilise the internal chain using parse(...
1b5f55c2c6387dd829508c8eb2f9789f8685b42f
67,405
def f_rank_classif(X, y): """ Same idea as f_classif, but computed on ranks """ X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"]) assert(isinstance(X, np.ndarray)) X = np.array([rankdata(feat_vector) for feat_vector in X]) args = [X[safe_mask(X, y == k)] for k in np.unique(y)] ...
958e4bfb2d9c82f55094a2957eae197fc0d702e3
67,406
def index(request): """The home page.""" continent_counts, total_countries = display_country_totals() context = { 'countries_per': continent_counts, # amount of countries per continent 'total_countries': total_countries, # total amount of countries in world } return render(request, '...
11439688de8f20ca559d257e96ccfe15050e0716
67,407
def get_order_coeff_from_expr(expr, symb, order): """ example: 3*s**2 -4*s + 5, s, 3 -> 0 3*s**2 -4*s + 5, s, 2 -> 3 3*s**2 -4*s + 5, s, 1 -> -4 3*s**2 -4*s + 5, s, 9 -> 0 """ p = sp.Poly(expr, symb, domain = "EX") default = 0 return p.as_dict().get( (order,), def...
791205bf4af1f8aeeb12fb22bfeb73ca8037885a
67,408
def decodeTcpdump(FileName,**options): """ Function to extract RSSI information stored in a .txt file Input FileName Name of .txt file, input as string including file type termination Output addressList Dictionary with address names and index where they are stored RSSI m...
ca04d1fa2e3d1d103ee032112461aedfb5d211ef
67,409
import torch def train(model, scaler, train_loader, epochs, optimizer, criterion, train_on_gpu): """ This is the training method that is called by the PyTorch training script. The parameters passed are as follows: model - The PyTorch model that we wish to train. scaler - Scaler object...
8ddad0b42a1fbabc961db8ae3bf8b2a9ac4c0714
67,410
from datetime import datetime def home(): """Renders the home page.""" return render_template('index.html', posts=posts, title='Contact', year=datetime.now().year, message='Your contact page.')
6b97257331bae9134e6f92022f89dfaa3b30e7ba
67,411
def getClasses(): """ Returns a list of class ids from the database """ if 'email' not in session or session['email'] is None: abort(401) email = mailsane.normalize(session['email']) if email.error: abort(400) return jsonify({'classList' : dbworker.getClasses(str(email)), '...
cc83b795dbfed3a0f7beb957d93683669d9e7e13
67,412
from typing import Optional def disconnect(ip: Optional[str]) -> bool: """ Disconnect from the given device ip :param ip: device ip :return: true if successfully disconnected """ log().verbose(f"Disconnecting from {ip}..") if execute("disconnect", ip=ip): zope.event.notify(events.A...
88198c24324b8eedfcb91c418a66980914e2636b
67,413
def run_in_executor(executor, func, *args, **kwargs): """Run a blocking function in a separate thread in the tornado ioloop. Copied from function which is added in a later version: https://www.tornadoweb.org/en/stable/_modules/tornado/ioloop.html#IOLoop.run_in_executor Improves a little on the function by...
b31fc90a91c1a2cc021c5bb0b573283bc110e5b0
67,414
from typing import Callable def trigger_redraw(fn: Callable) -> Callable: """Method decorator for functions that need to trigger a re-draw. Parameters ---------- fn : Callable The function that needs to trigger a re-draw, e.g. because it changes the appearance of the canvas. Retu...
4ef063fd85a81e3167cddf98a1311bd40ae04c1c
67,416
def rsa_pkcs1v15_verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an RSASSA-PKCS-v1.5 signature. When the hash_algorithm is "raw", the operation is identical to RSA public key decryption. That is: the data is not hashed and no ASN.1 structure with an algorithm identi...
788b5473fc8310c3b88ec7c39514039cb8f988d0
67,417
from typing import Optional def to_timedelta( arg, unit: Optional[str] = None, errors: str = "raise", ): """ Convert argument to timedelta. Parameters ---------- arg : str, timedelta, list-like or Series The data to be converted to timedelta. unit : str, optional D...
77ec21509d69b60512d31be81dce6cf5d2317e9b
67,418
def scheduling_blocks(): """Return list of Scheduling Block instances known to SDP.""" sbi_list = SchedulingBlockInstanceList() return dict(active=sbi_list.active, completed=sbi_list.completed, aborted=sbi_list.aborted)
a3171d351ca0a863340e22d2610c5c96999a393c
67,419
def odd_ext(x, n, axis=-1): """Generate a new ndarray by making an odd extension of x along an axis. Parameters ---------- x : ndarray The array to be extended. n : int The number of elements by which to extend x at each end of the axis. axis : int The axis along which t...
bd5b1da526e8a97dcc8d26f42f56d695057021b2
67,420
import itertools def patches_from_ct(ct_array, meta, patch_shape=None, centroids=None, stride=None, pad_value=0): """ Given a CT scan, and a list of centroids return the list of patches of the desired patch shape. This is just a wrapper over crop_patch generator. Args: ct_array (np.ndarray):...
dd3f7e034477938c3239eda210904034de3ab64a
67,421
def delivery_point_deliveries_waiting(request, campaign_id, delivery_point_id, campaign, delivery_point, multi_tenant): """ :return: JsonResponse """ columns = _columns if multi_tenant: deliveries = GoodDelivery.objects.filter(Q(choosen_delivery_point__c...
4411159e21d013c4e9218715c26cf4d809e51912
67,422
def inserisciNumero(): """Permette di inserire all'utente un numero di fibonacci valido""" num = int(raw_input("Inserisci il numero di Fibonacci da calcolare:\n")) while num < 0: num = int(raw_input("Inserisci un numero di Fibonacci valido (>= 0):\n")) return num
54c4315085201478232a8361910d349fc1fef210
67,423
def eval_generalized_normal_pdf(eval_at, mu=0.0, alpha=1.0, p=10.0, lower=-np.inf, upper=np.inf): """Evaluate the generalized normal pdf, scaled/shifted See `sample_generalized_normal` for parameter definitions. """ generalized_normal = stats.gennorm(beta=p, loc=mu, scale=alpha) unnormed_eval_pdf ...
5fb01f00ad8d47630c02c60387fdd09a02d85a98
67,424
import re def wrap_with_span(string, arg): """ Wraps all instances of a string with a span element""" words = arg.split(' ') for word in words: if word[-1].lower() == 's': word = word[:-1] pattern = re.compile(r'\b({0}[\w\d]*)\b'.format(word), flags=re.I) for (match) ...
9390f0f12d673c9a809760c1e7ff614d4fc079ef
67,425
import pathlib def resolve_extension_name(ext): """Search in extension folders and return fully-qualified extension name.""" basepath = pathlib.Path(".").resolve() matching_ext = list(basepath.glob(f"**/*extension*/{ext}.py")) if len(matching_ext) != 1: matching_ext = list(basepath.glob(f"**/*...
7582e47057417ac1b1b0e41c4cb61637222f91e9
67,426
def get_content_success(app_name): """ Retorna a mensagem de sucesso em caso de execução bem sucedida :param app_name: Nome do app que está sendo criado :type app_name: str """ params = {'app': app_name} return render_to_string('app_generator/command/success.txt', params)
d5b5bb84a4e69b3866c396b3e7ee8e6cf7ac93ab
67,427
def encumberance_desc( pc, show_ceiling=True ): """Return a string describing this PC's encumberance level.""" mass = sum( i.mass for i in pc.contents ) ec = pc.get_encumberance_ceilings() el = pc.encumberance_level() if show_ceiling: return "{0}.{1}/{2}.{3}lbs {4}".format( mass//10, mass%10...
833d3f66d50243902910b6af98809c529f397ae2
67,428
def correlation_by_exemplar(brands, exemplars, validation_scores, analyze_fn_str, outf): """ Report the overall correlation with the validation scores using each exemplar in isolation. """ analyze_fn = getattr(analyze, analyze_fn_str) keys = sorted(k for k in validation_scores.keys() if k in set(x[0] for x ...
e600e1a9b82a448dcff9d865a4366696d76131f0
67,430
def get_discont_price(S: float, i: float, n: int) -> float: """ " Parameters ---------- S : float Сума i : float Річна ставка складних відсотків n: int Кількість років Returns ------- P : float ціна """ return S / ((1 + i) ** n)
a5578e8dc80a27c9188c9213d43c3caae09b030a
67,431
def plot_matrix_sizes(plots_no): """Calculate the size of the matrix fitting 'plots_no' plots. Args: plots_no (int): the number of plots in the matrix. Returns: tuple containing the number of row 'rows_no' and columns 'cols_no'. """ rows_no = floor(sqrt(plots_no)) cols_no = rows_no + ceil((plots_no - rows_no...
bcab52b63ac6973a92541b68073df0ac18a8847c
67,432
def de_unicode(input): """ json output ends up as unicode strings some/all of the time this turns them into strings. """ if isinstance(input, dict): foo=dict() for key,value in input.iteritems(): foo[de_unicode(key)] = de_unicode(value) return foo elif isinstance(input, list): foo = [] ...
003eea311e22c7c0b1ff2bcadf83a61be406601d
67,433
def import_name(modulename, name=None): """ Import identifier ``name`` from module ``modulename``. If ``name`` is omitted, ``modulename`` must contain the name after the module path, delimited by a colon. Parameters: modulename (str): Fully qualified module name, e.g. ``x.y.z``...
a320063e878db935f8a2409c7487617e2c9f1802
67,434
def get_widgets(request): """Return a set of all available widgets.""" return WIDGETS
b286e3468f3e323617feb76541d5b01059c4cd5b
67,436
def find_bounding_shape(virtual_size, available_shape): """ Finds a tuple of the same length as ``available_shape``, with every element not greater than the corresponding element of ``available_shape``, and product not lower than ``virtual_size``. """ assert virtual_size <= product(available_sha...
46801faf463b34fe39ecaf71e7821444d29bb0eb
67,437
def path_to_route(path_dataframe,edge_dataframe,tiploc_mapping_nodes): """Map the TIPLOC route onto the network route by mapping TIPLOC to network nodes and Finding the equivalent route on a network for given node-node paths that might not be adjacent to each other By estimating the shortest path between co...
8bb849a6dcbfba47dd29bfccdbe6e7876b0a268d
67,438
def thickness_params(xarray, mask_values= 0): """Return the plotting parameters for the surface oil thickness :arg xarray: Output netcdf Lagrangian file loaded with xarray :returns: tuple consisting of truncated array bounding the oil data needed, the x and y bounds for further visualisation...
ac0f413376ef5c185f389d2a2814667b14366716
67,439
def createOutputTask1(DLmodel, testTokenizedSentences, testEncodedSentences, testClasses, testDocMapping, bertUtils, neji_classes=None): """ Runs the trained model on the unseen data split (validation or test), returning the resulting entity predictions :param DLmodel: :param testTokenizedSentences: ...
dfcbc32d394d76093a073a452d83206fff81080d
67,441
def sort_012(arr): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: arr(list): List to be sorted """ if arr is None: return arr zero_index = 0 current_index = 0 two_index = len(arr) - 1 while current_index < len(arr...
d1fa4ee67c9d6b62928b5ea1e2fc1daf011db29d
67,442
def handle_aborted(fsm_ctx): """ :param ctx: FSM Context :return: True if successful other False """ global plugin_ctx if plugin_ctx.nextlevel: nextlevel_processing(plugin_ctx) report_install_status(ctx=plugin_ctx, op_id=get_op_id(fsm_ctx.ctrl.before)) # Indicates the failure ...
07488733031cf4989ece92728054f56363f7bc97
67,443
from operator import and_ def get_next_cat(last_index: int) -> models.Cat: """Get next cat. Args: last_index (int): View index of last seen cat. """ cat = None if last_index != -1: cat = models.Cat.query.filter(and_(models.Cat.disabled == False, models.Cat.index > last_index)).orde...
055493449a0ad56739c16553474f767a2488c011
67,444
def txt_split(filename): """Strip '#' from first line and get string list of column :filename: file to get header from :returns: [string],ndarray """ with open(filename,'r') as f: header=f.readline() #strip header and split into words header=header.translate(None,'#') ...
52799d21f60a5a23f1571bbf3ea98b9d921f0ef5
67,445
def QueryChanges(host, param_dict, first_param=None, limit=None, o_params=None, sortkey=None): """ Queries a gerrit-on-borg server for changes matching query terms. Args: param_dict: A dictionary of search parameters, as documented here: http://gerrit-documentation.googlecode.com/svn...
c0618cbcb6975c7bafd3eec366fade451e040b47
67,446
def update(user_id, account_id, calendar_id, event_id, body): """ This function updates an account based on the provided information :param user_id: user_id passed-in URL :param account_id: account_id passed-in URL :param calendar_id: calendar_id passed-in URL :param event_id: event_id passed-i...
e432c33de97aaaf3da000a7f8641189aad64b6ab
67,447
def stop_process(client, pid): """获取进程状态""" stop_result = "" command = 'kill -9 "%s" ' stdin, stdout, stderr = client.exec_command(command % pid) # 执行bash命令 kill_status = stdout.read() error = stderr.read() if error or kill_status: error = error.split(':')[3].strip() stop_re...
454bb8763017119efe360cb5f7c07b9a353ba345
67,448
from typing import OrderedDict from typing import Union def match_state_dict( model_dict : OrderedDict[str, Tensor], pretrained_dict: OrderedDict[str, Tensor], exclude : Union[tuple, list] = () ) -> OrderedDict[str, Tensor]: """Filter out unmatched keys btw the model's `state_dict` and the ...
4e27bab6d14c074a4d39b9ade24c2bb78045b36d
67,449
import json def get_original_df(handler): """Get the original dataframe which was uploaded to the webapp.""" data_dir = get_user_dir(handler) meta_path = op.join(data_dir, 'meta.cfg') if op.isfile(meta_path): with open(meta_path, 'r') as fout: # noqa: No encoding for json meta = j...
71b1e49aef8ab43f2d029caa663c10ba0fe54139
67,450
def pil_gen(pil_mask_c, hmi_dat, threshperc=0.05, lx=800, ly=800, polyor=4): """ Generate PIL polynomial. Parameters ---------- pil_mask_c : list PIL mask. hmi_dat : list Array of HMI values associated with the flare. threshperc: float, optional Percentag...
0ebd5c967336ce4bb90763c2413e2d46d11c99df
67,451
def _append_x(clifford, qubit): """Apply an X gate to a Clifford. Args: clifford (Clifford): a Clifford. qubit (int): gate qubit index. Returns: Clifford: the updated Clifford. """ clifford.table.phase ^= clifford.table.Z[:, qubit] return clifford
73a747ec0f8ea7245f6be9fe3805fa9fecf0665d
67,453
def isprime(n, k=10): """test if n is a prime number if n is less than 100, check if n is in a set of small primes else check if n is prime using the Miller-Rabin test >>> isprime(2) and isprime(2**1279-1) True >>> isprime(1) or isprime(-2) False""" if n == 2: return True if ...
d02d84e97ab545e084d90a1dcfe30c2693d51092
67,454
def add_overlap_ellipse(segm, ellipse_params, label, thr_overlap=1.): """ add to existing image ellipse with specific label if the new ellipse does not ouvelap with already existing object / ellipse :param ndarray segm: segmentation :param tuple ellipse_params: parameters :param int label: selected...
a2b3e7d5c96854114793c22e7e9bb34a7f061ae6
67,455
import functools def cowell(k, r, v, tofs, rtol=1e-11, *, ad=None, **ad_kwargs): """Propagates orbit using Cowell's formulation. Parameters ---------- k : ~astropy.units.Quantity Standard gravitational parameter of the attractor. r : ~astropy.units.Quantity Position vector. v ...
c6b188130811216b0f72912e3918623a8e20702f
67,459
from typing import Tuple import bisect def find_closest(m: 'Metric', key: metric_key) -> Tuple[metric_key, metric_key]: """ assumes keys are sorted.""" if m.keysmin >= key: # neet to extrapolate left, right = m.all_keys[:2] elif m.keysmax <= key: left, right = m.all_keys[-2:] else: ...
a92f6d1eef1b05727395652c2a904216a0b51781
67,460
def list_rune(*args, nodes, attrs, context): """Creates an unordered list.""" style = " - " if len(args) < 1 else args[0] def list_recurse(s, i, n): # style, indent, nodes for node in n: if isdata(node): yield i + s + node.data if len(node.nodes) > 0: ...
260456b0035796f57807b0c3f1e30c8684dd8fa6
67,462
def calculate(): """ Perform a super important calculation. """ return 12
b6aa643b9f6e24f579fdc273c2dec512692cdc4b
67,463
from typing import List def connect_mini_buckets(mini_buckets:List[Bucket])->List[int]: """ connect mini buckets with possibly different variable labels by maximal separators """ mini_bucket_inds = [] g_score = dict() for src in range(len(mini_buckets)): g_score[src] = dict() f...
b0a3d03d4faa1c912fa2952a2edb376be9d2a280
67,464
def check_if_get_event_types_succeeds(frauddetector_client, event_type_to_check: str): """ This calls get_event_types and returns True if the response contains an event type: (True, event_type) If the call does not return any event types, return (False, None) :param frauddetector_client: frauddetector b...
ceb961770f643f8c88b20b2ee0cea2209d9ffcd3
67,465
def get_cleanse_logs(user_cleanse_id): """Shows all cleanse logs for a specific user cleanse""" return CleanseLog.query.filter(CleanseLog.user_cleanse_id == user_cleanse_id).all()
f3be3573d19e9aa6065e2546a02cdc9b3c802fb6
67,466
def shard_hset(connection, base, key, value, total_elements, shard_size): """分片式的hset函数""" shard = shard_key(base, key, total_elements, shard_size) return connection.hset(shard, key, value)
444511a3ce202f0bd5992cdfe33ec9e99c1e50a4
67,467
def load_fermi_image(): """Load Fermi counts image for the Galactic center region. Returns ------- hdu : `~astropy.io.fits.ImageHDU` Image HDU Examples -------- .. plot:: :include-source: from photutils import datasets hdu = datasets.load_fermi_image() ...
94ae2e1ee302897ff7989e3f8ca88ae1a3f7c544
67,468
def color(red: int, green: int, blue: int, white: int = 0): """Convert the provided red, green, blue color to a 24-bit color value. Each color component should be a value 0-255 where 0 is the lowest intensity and 255 is the highest intensity. Note the sequencing has been changed from RGB (most signific...
e821999f1a66d1bc8a7bec4dc298679b205165ad
67,469
def N_(msg): """Designate a string to be found by gettext but not to be translated.""" return msg
e82c1f4219e53be05e863bfd636bec932ddd7f5c
67,470
def getticket(): """ 获取 jsapi_ticket http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95 """ access_token = request.args.get('access_token', None) if not access_token: ret...
33c5477109ae2a2a40fec4444e18de32d7129026
67,471
import json def _get_needed_packages(json_file, test=None): """ Returns a dict with needed packages based on a JSON file. If a test is specified it will return the dict just for that test. """ needed_packages = {} with open(json_file) as f: test_packages = json.load(f) for key,va...
b929e57beda05372b03936598db275e87a318962
67,472
def calc_eigenvectors(verts: [[float]]): """ It computes eigenvectors from a set of vertices. ---------------------------- Args: verts (obj: 'list' of obj: 'list' of float): The list of vertices Returns: eigenvalues (obj: 'list'): The list of eigenvalues eigenvectors (obj: 'l...
e8d7e6a675718075da23fc4cc461fd9cff4e485c
67,474
def get_parser(): """ Get parser object for `eco_mocks_create.py` script. Returns ------- args: input arguments to the script """ ## Define parser object description_msg = 'Downloads the necessary catalogues from the web' parser = ArgumentParser(description=description_msg,...
a3fd681a723abff5b1e5526e33598483fe84997d
67,476
def grid_creator(): """formats the given grid from project euler""" a = '08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08' b = '49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00' c = '81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65' d = '52 70 95 23 04 60 11 42 69 2...
1a08ad9671fb14a03671b803e4045c5c7d3b9286
67,477