content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_app(config): """Docstring for create_app method.""" app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config]) jwt = JWTManager(app) app.register_blueprint(version_2) create_tables() return app
5b263fff394ca99df4d581bc1add0e6f10222d89
43,500
from yt.data_objects.time_series import DatasetSeries import os def load(*args ,**kwargs): """ This function attempts to determine the base data type of a filename or other set of arguments by calling :meth:`yt.data_objects.api.Dataset._is_valid` until it finds a match, at which point it returns a...
93048a591700f8b13762ed38e0f4d303aab90ea4
43,501
import re def get_index_of_tone_vowel(syllable): """ Returns the index of the vowel that should be marked with a tone accent in a given syllable. The tone marks are assigned with the following priority: - A and E first - O is accented in OU - otherwise, the *final* vowel Returns -1 if n...
97d4f724f56ce3270e317b4d885b3ac5730e59f5
43,502
def IterateQueue(queue_head, element_ptr_type, element_field_name, backwards=False, unpack_ptr_fn=None): """ Iterate over an Element Chain queue in kernel of type queue_head_t. (osfmk/kern/queue.h method 2) params: queue_head - value : Value object for queue_head. element_ptr...
7d2b0192286f50217e374965578dff277462b3c3
43,503
import glob import random def mediaGenerator(request): """Randomly picks an content file from the requested database. `request`: selects prefered database """ folder = 'content/' + request mediaPaths = glob(folder + '/*') return random.choice(mediaPaths)
d8a6c68ba98b8ae905319e44b901a5c9553b0f42
43,504
def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def auth_filter(app): return FederatedAuthentication(app, conf) return auth_filter
9d75d3ecd01cbba8046a470b3cfc4b4e595fb637
43,505
import time import os def contrast_luvoir_num(coro_floor, norm, design, matrix_dir, rms=1*u.nm): """ Compute the contrast for a random segmented mirror misalignment on the LUVOIR simulator. :param coro_floor: float, coronagraph contrast floor :param norm: float, normalization factor for PSFs: peak of...
24da9b73b3b6d4d319a01776e5c18f888afe6101
43,506
def create(document_dir): """ creates an inverted index given an English text corpus for movies. If the directory provided does not exist, the program will print an error. If the filenames in the test corpus do not match with the description, the program will print an error and will skip the ...
757aa0b974972bcb751a84d4e7cbb76d425e10fc
43,507
import shutil def get_drive_info(action, drive) -> any: """ This allows us to query specific information about our drives including temperatures, smart assessments, and space available to use for plots. It allows us to simply hand it a drive number (drive0, drive22, etc) and will present us with t...
6d196402462bf5b31cdb76f249eaf81e906a6f7a
43,508
from typing import List def filter_violations(violations: List[Violation], exclude_categories: List[str], exclude_severities: List[int]) -> List[Violation]: """ Filter violations according to rules specified by the user. :param violations: all violations :pa...
dfa7ac8acc72d3c4350e2592149fcd840086e29b
43,509
def notary_info(request): """get notary details""" name = request.POST.get('name') if not name: return format_return(13000) msg_code, msg_data = interface.get_notary_info(name=name.strip('')) return format_return(msg_code, data=msg_data)
cb379479f816d4037d34f5c98af05f0693d9fe95
43,510
import sys def reject_on_exception(func): """ Decorator on actor callback functions that handles exceptions by sending it to caller as promise rejections. The function should have an argument called ``callback``. """ arg_names = getargspec(func).args callback_pos = None if arg_names: ...
27ac0833261a3dbc118a4aa8d800ce89e6913c9f
43,511
from unittest.mock import Mock def get_mock_discovery(host_list, invalid_interface=False, invalid_key=False): """Return a mock gateway info instance.""" gateway_discovery = Mock() gateway_dict = {} for host in host_list: gateway = Mock() gateway.ip_adress = host gateway.port ...
d99e01cdcc856ca8d193893e229be76d005ac3db
43,512
def get_raw_text(xml_tree_element): """ get raw text with xml encodings a string """ text = ET.tostring(xml_tree_element) return text
caaa94ae3dd5be182bb55632d203e54767a0eccc
43,513
def rankingMinPath(matrix,seeds,levels): """ errado, analisar """ chosen = np.full(matrix.shape[0], np.inf) height_vector = np.zeros(matrix.shape[0],dtype=int) parent = np.full(matrix.shape[0], np.inf) fila = [] for s in seeds: fila.append(s) height_vector[s] = 0 parent[s]=-1 chosen[s] = 0 print(fil...
fde9a5908dd53cddf7d7963147b80e5afddbe191
43,514
def register_run_config(name): """Registers a run configuration class.""" basecls = BaseConfig registry = RUN_CONFIG_REGISTRY reg_func = partial(_register, name=name, basecls=basecls, registry=registry) return reg_func
871d6cfa0952c38dee08159610c66c8aadd4e272
43,515
def statement_block(evaluator, ast, state): """Evaluates statement block "{ ... }".""" state.new_local_scope() for decl in ast["decls"]: evaluator.eval_ast(decl, state) for stmt in ast["stmts"]: res, do_return = evaluator.eval_ast(stmt, state) if do_return: state.remo...
e38575e5e2119cd9794ea5f0b1629cecf411a0e9
43,516
def _create_query_dict(query_text): """ Create a dictionary with query key:value definitions query_text is a comma delimited key:value sequence """ query_dict = dict() if query_text: for arg_value_str in query_text.split(','): if ':' in arg_value_str: arg_valu...
2e4478bdf110911d4ca9fcc6c409aab3504a0b8a
43,517
def nan_gaussian_filter(T, fwhm, mode="constant", cval=0, preserve_nan=True, **kwargs): """default parameters mimic convolve(x,kernels.Gaussian2DKernel(fwhm),preserve_nan=True,boundary='fill',fill_value=np.nan) fill_value = np.nan basically continues the interpolation beyond the boundary """ V = T.c...
fd97a3c36332aa36df59781224eddb4cc12ecfc5
43,518
def _getVersionString(value): """Encodes string for version information string tables. Arguments: value - string to encode Returns: bytes - value encoded as utf-16le """ return value.encode("utf-16le")
36646a686c17f2c69d71a0cdeede56f0a1e514e2
43,519
def h_n(n, z): """ Spherical Hankel function of order n Parameters ---------- n : numpy.array(M,N) Order of the function z : numpy.array(M,N) Function argument Returns ------- yn(z) : numpy.array(M,N) Function value """ return ...
c253db485dfca3949a1ba6a9895576a5c11a833d
43,520
from bs4 import BeautifulSoup import sys def get_org_projects_info(org_link): """Get organisation's projects information :param org_link: Valid link to the organisation's info page of a specific year :type org_link: str :returns: A list of dictionaries of each project's title, descrition and link of ...
351bbda1cae7d3bd4b58ff0ec71d804341140b68
43,521
from typing import List from typing import Optional def get_shift_of_one_to_one_match(matches: List[List[bool]]) -> Optional[int]: """ Matches is an n x n matrix representing a directed bipartite graph. Item i is connected to item j if matches[i][j] = True We try to find a shift k such that each item ...
f8168e72dab64acc26841a49122dcf08d473ea1f
43,522
from bs4 import BeautifulSoup import urllib from datetime import datetime def parse_zebet(url=""): """ Retourne les cotes disponibles sur zebet """ if not url: url = "https://www.zebet.fr/fr/competition/96-ligue_1_conforama" if "/sport/" in url: return parse_sport_zebet(url) tr...
e29bd5093c65511507a8c2dc227b62bdcdfc381a
43,523
def background(f): """ Call a function in a simple thread, to prevent blocking Taken from the Jupyter Qtconsole project """ t = Thread(target=f) t.start() return t
d231192f895c5e5914f375172e045b4d7cc52ee2
43,524
from joblib import Parallel, delayed, parallel_backend from typing import Union def calculate_entropy_batch_mixing( adata: ad.AnnData, use_rep: str = "delta", batch_col: str = "batch_indices", n_neighbors: int = 50, n_pools: int = 50, n_samples_per_pool: int = 100, random_state: int = 0, ...
8c62a9ee0b951bfab6b307efcde853494868ec90
43,525
import re from datetime import datetime def get_leap_seconds(truncate=True): """ Gets a list of GPS times for when leap seconds occurred Keyword arguments ----------------- truncate: Reduce list of leap seconds to positive GPS times Returns ------- GPS time (seconds since 1980-01-06T...
c2bf09bf4dbfb734adccd13a4a6a259a6ffe64c7
43,526
from typing import Any import json def serialize(obj: Any) -> str: """ Serializes object into a string JSON DEPRECATED use json_encoder.to_json directly :param obj: object to serialize :return: JSON string """ return json.dumps(obj, cls=EnhancedJSONEncoder)
52fa105779465cf3ca2ee9d9a6b4cf16cfe1dd60
43,527
import re def block2dict(block: list, kind: str = None, sequence: int = -1) -> dict: """Takes a text block from a SerialEM .nav file and converts it into a dictionary.""" patt_split = re.compile(r'\s?=\s?') d = {} for item in block: key, value = re.split(patt_split, item) try: ...
7169d95d88e6e68d7f5716a5d50b629030ae8783
43,528
def plurality(l): """ Take the most common label from all labels with the same rev_id. """ s = l.groupby(l.index).apply(lambda x:x.value_counts().index[0]) s.name = 'y' return s
4e363648e79b5e9049aca2de56fd343c1efe1b93
43,529
import uuid def trace_using(logger): """Decorator factory to trace callables. Args: logger: The logger to use for tracing Returns: The decorator, which takes a function and decorates it. """ def real_decorator(func): """Decorate a callable to report args, kwargs and ret...
51b6dacfd36b52dde7a3bdf3b3c939b51adb2eb2
43,530
def lowpass_filter(data: FLOATS_TYPE, sampling_freq_hz: float, cutoff_freq_hz: float, numtaps: int) -> FLOATS_TYPE: """ Apply a low-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :mat...
4bb15468e3a26d15c0184c1094e07b3675aa321c
43,531
def uncollect_if_test_explainer(**kwargs): """ This function is used to skip combinations of explainers and classifiers that do not make sense. This is achieved by using the hooks in conftest.py. Such functions should be passed to the @pytest.mark.uncollect_if decorator as the func argument. The...
cca68a9ff3656fcfa0181c84554f920b5beee0fc
43,532
def trimAndStandardizeMates(target_seq_ID, bam_lines, references, reference_lengths, primer_seqs): """1) Trim reads upstream of primer sequence(s), relative to primer sequences(s) 2) Relabel reads <umi_5p>_<umi_3p> """ aux_info = None reject_reason, mate1, mate2 = processBamLinesForTarget(target_...
ffee32c5e07a7773d6d4edeb8cb24a16896c387d
43,533
def electric_field(relative_permittivity, relative_permeability, frequency, current, length, r, theta): """ Calculate the electric far field for the Hertzian dipole. :param relative_permittivity: The relative permittivity. :param relative_permeability: The relative permeability. :param frequency: Th...
9e154f9c7110027b1e67f991b59d04df259d7c46
43,534
def get_messages_per_week(msgs): """Gets lists of messages for each calendar week between the first and the last message. Args: msgs (list of Mymessage objects): Messages. Returns: A dictionary such as: { week (datetime.date): list of messages within this week ...
43ade76498c38d9977e6baddd8c651abc03e6ee7
43,535
def _handle_text_outputs(snippet: dict, results: str) -> dict: """ Parse the results string as a text blob into a single variable. - name: system_info path: /api/?type=op&cmd=<show><system><info></info></system></show>&key={{ api_key }} output_type: text outputs: - name: system_in...
693a3e5cba6d72d09b2adb3745abb4fcf07f92d3
43,536
from kivy.core.window import Window import inspect import sys def run_app(cls_or_app): """Entrance method used to start the App. It runs, or instantiates and runs a :class:`MoreKivyApp` type instance. """ handler = _MoreKivyAppHandler() ExceptionManager.add_handler(handler) app = cls_or_app()...
862d9fd70a9303cfd4cdf275cdb7a313c2f1e507
43,537
def make_uuid(): """generate uuids even on Python 2.4 which has no 'uuid'""" return _uuids.pop(0)
596702b0eed0c6f7563e25c0fd6f33756d8811ae
43,538
from datetime import datetime def _to_iso_format(traintime: datetime) -> str: """Return isoformatted utc time.""" return dt.as_utc(traintime).isoformat()
04b0c7f8695bcec1de3a759d46f54a4b3a890a4c
43,539
from datetime import datetime def parse_timestamp(datetime_repr: str) -> datetime: """Construct a datetime object from a string.""" return datetime.strptime(datetime_repr, '%b %d %Y %I:%M%p')
ddacf877c55466354559f751eac633b5bcd7313c
43,540
def proxy_request(request, **kwargs): """ generic view to proxy a request. Args: destination: string, the proxied url prefix: string, the prrefix behind we proxy the path headers: dict, custom HTTP headers no_redirect: boolean, False by default, do not redirect to "/" ...
539e1bd2e70e49435ec6272888193943076d0129
43,541
def image_stabilisation_proj( image: xpArray, axis: int = 0, projection_type: str = "max-min", **kwargs ) -> SequenceRegistrationModel: """ Computes a sequence stabilisation model for an image sequence indexed along a specified axis. Instead of running a full nD registration, this uses projections inste...
86e04bdcb529bbe3abbec42b4334b280f6404f4f
43,542
def get_LOR_colors(LOR_list, min_max=(-2, 2)): """Use Log Odds Ratios list to create color map for allele columns """ cmap = cm.coolwarm if min_max!=False: norm = Normalize(vmin=min_max[0], vmax=min_max[1]) else: bnd_Val = max(abs(min(LOR_list)), abs(max(LOR_list))) print("mi...
6b6f6c35bf38ce70a5f9a1f17600a332d99d0459
43,543
from typing import Tuple def _shard(split: Split, shard_index: int, num_shards: int) -> Tuple[int, int]: """Returns [start, end) for the given shard index.""" assert shard_index < num_shards arange = np.arange(split.num_examples) shard_range = np.array_split(arange, num_shards)[shard_index] start,...
ffb6410e0e806f3a91e7959e047bdc93f51d8ce9
43,544
def refractive_index(h_gp): """average atmospheric refractive index""" delta = 2.93e-4 rho = atmosphere(h_gp) n = 1. + delta * (rho / RHO0) return n
75dd302a50ff56abc9a93f3a815435b681b564c3
43,545
import random def randvec(n): """ Given the number of vertices n returns a random 2^n x 1 basis vector Parameters ---------- n : integer Number of bits in string which represents the number of verticies in graph. Returns ------- v : ndarray A random 2...
2c97e7907bd6972bb791a60142f95e26001d960b
43,546
def assemble_result_str(ref_snp, alt_snp, flanking_5, flanking_3): """ (str, str, str, str) -> str ref_snp : str DESCRIPTION: 1 character (A, T, G or C), the reference SNP. alt_snp : str DESCRIPTION: 1 character (A, T, G or C), the variant SNP. flanking_5 : str DESCRIPTI...
bc0b43464124d0d19f4bfc5646730a1f951a5ced
43,547
def encrypt_blob(raw_data, public_key) -> bytes: """Return RSA + AES encrypted byte data from raw data input. :ivar raw_data: Bytes rsa + aes data. :raw_data raw_data: bytes :ivar public_key: urlsafe base64encoded rsa public key string value. :public_key public_key: string""" decrypted_bytes = b...
f9a1f592014cb02b0d11c39d665ab1cba1dea490
43,548
import requests def get_api_data(session, url, date_time): """Get the JSON-formatted response from the AMM API for the desired date-time. """ session = session or requests.Session() return session.get(url, params={"dt": date_time.format("DD/MM/YYYY")}).json()
ff44be4a958c4f05cc5bd562854059c552f693e1
43,549
import os import itertools def trackedcmd(ui, repo, remotepath=None, *pats, **opts): """show or change the current narrowspec With no argument, shows the current narrowspec entries, one per line. Each line will be prefixed with 'I' or 'X' for included or excluded patterns, respectively. The narr...
18d18022a71c92cde8ac2ba9d766225a76bbc426
43,550
def validate_cnpj(doc): """Basic function to validate the CNPJ number for serializer field Args: doc (str): The CNPJ number, accepts with or without characters Raises: ValidationError: CNPJ inválido! Returns: doc: The CNPJ number """ if not cnpj(doc): raise Val...
e1cc1b4c0287efb02c80fccb2ae3c9dc15d1b5ea
43,551
def make_trefoil(size=100, noise=0.0, a=2, b=2, c=3, **kwargs): """Generate synthetic trefoil dataset. Params ----- :size = int (default = 1000) - the number of data points to use """ # generate trefoil phi = np.linspace(0, 2*np.pi, size) x = np.sin(phi) + a*np.sin(a*phi) y = n...
ed75bde74997dd29d599d1cffe3900f882c33f90
43,552
def _makeOperator(operatorInput, expectedShape): """Takes a dense numpy array or a sparse matrix or a function and makes an operator performing matrix * blockvector products. Examples -------- >>> A = _makeOperator( arrayA, (n, n) ) >>> vectorB = A( vectorX ) """ if operatorInput i...
df6246eabfae83b11c77570ffc091dac9166f447
43,553
def search(state, goal_state): """Iterative deepening depth-first""" depth = 0 def dls(node): if node.is_goal(goal_state): return node if node.depth < depth: node.expand() for child in node.children: result = dls(child) if ...
f29c8d2abeb3f4f98bb2b37da880ed815c94aead
43,554
from rasterio._io import window_union def union(*windows): """Union windows and return the outermost extent they cover. Parameters ---------- windows: list-like of window objects ((row_start, row_stop), (col_start, col_stop)) Returns ------- ((row_start, row_stop), (col_start, co...
5a0b331e9b6eb923c553e6e4aef3cf590b9d0792
43,555
from typing import Mapping def create_remote_executor( channel: GRPCChannel, cardinalities: Mapping[placements.PlacementLiteral, int], ) -> _executor_bindings.Executor: """Constructs a RemoteExecutor proxying service on `channel`.""" uri_cardinalities = data_conversions.convert_cardinalities_dict_to_strin...
264d2a02547fb1bae7e7b35a5d3136a03f3488df
43,556
def complex_abs(data): """ Compute the absolute value of a complex valued stacked input array. Args: data (numpy.array): A complex valued array with real and imaginary parts stacked,where the size of the final dimension should be 2. Returns: numpy.array: Absolute value of data """ ...
70d4a9691e6a4697dec4a3a6778bb4bd2ae7f50d
43,557
def _build_batch_norm_params(batch_norm, is_training): """Build a dictionary of batch_norm params from config. Args: batch_norm: hyperparams_pb2.ConvHyperparams.batch_norm proto. is_training: Whether the models is in training mode. Returns: A dictionary containing batch_norm parameters. """ batc...
892cf0891c5738e89f98f95c900d2e70dc99974d
43,558
import os import contextlib import subprocess def _slice_chr22(in_bam, data): """ return only one BAM file with only chromosome 22 """ sambamba = config_utils.get_program("sambamba", data["config"]) out_file = "%s-chr%s" % os.path.splitext(in_bam) if not utils.file_exists(out_file): ba...
4442a04deb8e9ee984ac0dcf91e792ee6262ec27
43,559
def search_abstracts(search_terms, reldate): """ :arg list search_terms: :arg int reldate: :returns object: """ query = '"{}"'.format('" OR "'.join(search_terms)) return Entrez.read(Entrez.esearch( db='pubmed', term=query, reldate=reldate, datetype='pdat', usehistory='y'))
5a4b47ba6c0f51a91fae218168ca5e9edf04d566
43,560
def tokenize(string: str) -> [str]: """Tokenize a string. :param string: [description] :type string: str """ return string.split(" ")
dfc2d11e0445a6b2f867660f101e7ade7823d8ed
43,561
from datetime import datetime import html import requests def get_liste_match(nb_jour): """ Fonction permettant de chercher les matchs qui vont avoir lieu entre aujourd'hui et un horizon en paramètre. :param nb_jour: Le nombre de jour à parcourir :return: Un dictionnaire contenant pour chaque date la ...
57f754484e3bed11f9e4abe3fa2b220a481911f2
43,562
def setBvar(value): """If `value` is a dict returns a generic_json object, otherwise it returns the value - - - - - **Args**: - `value` (any type): value to assing **Returns** - `generic_json` if value is a dict, otherwise it returns the value """ if type(value) == dict: retur...
c9832f81f8d9fc2ab4fc1b3f1cfb5a698b6181a4
43,563
def convex_attributes(variables): """Returns a list of the (constraint-generating) convex attributes present among the variables. """ return attributes_present(variables, CONVEX_ATTRIBUTES)
d46605e5a5240271cbfb94732182c387f166a4c6
43,564
def LMStep4InitializePyBrainNetworkForLearning(fNetwork): """ This function realize Learning mode step: 4. Initialize empty PyBrain network for learning or reading network configuration from file. fNetwork is a PyBrain format neural network, created at 1st step. Function returns True if all operatio...
7d5721447e63bbf2d3982c4ed36e86604006b3e5
43,565
def is_installed(service): """Check whether the Snips service `service` is installed. Args: service (str): The Snips service to check. Returns: bool: True if the service is installed; False otherwise. Example: >>> is_installed('snips-nlu') True .. versionadded:: ...
d892d12095a458fd90f7822d86bfad57f2c3bba8
43,566
def trunc(s, length): """Truncate a string to a given length. The string is truncated by cutting off the last (length-4) characters and replacing them with ' ...' """ if s and len(s) > length: return s[:length - 4] + ' ...' return s or ''
ea6d1702d709ac7d94cc2bcb2e945da71009c0fe
43,567
def user_preference_form_builder(instance, preferences=[], **kwargs): """ A shortcut :py:func:`preference_form_builder(UserPreferenceForm, preferences, **kwargs)` :param user: a :py:class:`django.contrib.auth.models.User` instance """ return preference_form_builder( UserPreferenceForm, ...
a53b3e0f6bfef2b7ad80c522786223a7a9e52c50
43,568
def get_parser(subparsers, parent=None): """ "Define and return a subparser for the tune subcommand.""" parser = subparsers.add_parser( "tune", description="Tune model using the ML on MCU flow.", parents=[parent] if parent else [], add_help=(parent is None), ) parser.set_...
cc351315ab5852d3cbad00cc3784f260018c8a6a
43,569
from re import M def find_prime(bits: int) -> int: """Returns a prime number with the specified amount of bits.""" p = random_odd(bits) while True: # if p is not coprime with M then it isn't prime. if gcd(p, M) != 1: p += 2 continue if miller_rabin(p, 10): ...
7a10c8346986dc037bde486ef61b4f056170c84d
43,570
import operator def sort_values(values: list[tuple]) -> list[tuple]: """Returns a list of tuples sorted by x value (the value at index 0 of the inner tuple.""" return sorted(values, key=operator.itemgetter(0))
f172f68418988d4e01dcc406de8ec467abfe7aa8
43,571
def calc_rank(age, is_veteran=False, has_disability=False): """ Calculate a participant's rank. A higher number is higher ranked (top of the list). (i.e., Reverse this when sorting.) Change this function to change the ranking algorithm. The code in the comments below is a ranking system based ...
2c3ab7446ac12e634ffe47b0e57e2232908b12b9
43,572
def say(text: str) -> str: """Return an ASCII art skeleton with a speech bubble Args: text: What to put in the speech bubble >>> print(say("Hello")[1:28]) ------- ( Hello ) ------- """ template = Template(template_path.read_text()) return template.render(text=text)
42222ac2a54c7d15da9366327937b0f24a0e6cb6
43,573
import re import os def clean_lines(text): """Clear out comments, blank lines, and leading/trailing whitespace.""" lines = (line.strip() for line in text.splitlines()) lines = (line.partition('#')[0].rstrip() for line in lines if line and not line.startswith('#')) glob_all = ...
e9355b0aee27172e8d5fdd59df1b4d8b38939fdd
43,574
def jwtauth(handler_class): """ Class decorator to check for authorization """ # pylint: disable=W0613 def wrap_execute(handler_execute): def require_auth(handler, kwargs): auth = handler.request.headers.get('Authorization') token_validation_res = validate_toke...
3b66460a4d41883beb9efe32b86a66f9f8c79726
43,575
def js_prerelease(command): """decorator for building minified js/css prior to another command""" class DecoratedCommand(command): def run(self): print('inner runnn.....') try: self.distribution.run_command('jsdeps') except Exception as e: ...
5856d5765383415f2c994bf0d10b921b38f23f98
43,576
from typing import Sequence def is_sequence(obj): """Check if `obj` is a sequence, but not a string or bytes.""" return isinstance(obj, Sequence) and not BinaryClass.is_valid_type(obj)
ec25a6bc25c1feeacb460ea14d788369b718c0f4
43,577
from pathlib import Path import os import zipfile import re def list_geo_file(folder=""): """Lists all the files in the folder named "folder" contained in GeoWatch Labs Agricultural Maps. Args: folder (str): folder name in which to search in GeoWatch Labs Agricultural Maps folder. Re...
6d233447bcba53401900b3073843e8c435c967dd
43,578
def is_user_stasised(nick): """Checks if a user is in stasis. Returns a tuple of two items. First parameter is True or False, and tells if the user is in stasis. If the first parameter is False, the second will always be None. If the first parameter is True, the second is an integer of the amount o...
f61f4bf5554a046724d1c5cc0eedcd9323b3d46c
43,579
def expose(class_method): """ Decorator which exposes given method into interface :param class_method: method to expose :return: given method with modifications """ class_method.is_exposed = True return class_method
ee234bd7535f29c39fc80643997b89aeb3c0f533
43,580
def merge_length_list(lists): """ Merge the list that demonstrates the word length """ res_list = [] for l in lists: if len(res_list) < len(l): res_list[len(res_list):] = [0] * (len(l)-len(res_list)) for length, num in enumerate(l): res_list[length] += num ...
564742fd7e0a7f3a0a8535a1f02c343d193a69ac
43,581
def func(pseudo_state, a1, a2, b1, b2, c1, c2, d1, d2): """ quadratic fit function for the Bellman value at given pseudo-state :param pseudo_state: list(float) - list of the four state variables for a given state :param a1, a2, ... d2: float - parameters of the quadratic fit function """ sum = a1*pseudo_state[0...
6478219704999dc4cfcbc915126d919e15fe3043
43,582
async def fav_(request:Request,user_id:int=None,authorization: str = Header(None),info : dict=Depends(is_valid_token),insert:str=None,delete:str=None,toggle:str=None): """gallerys endpoint""" token_user_id=int(info['id']) token_user_secret=info["secret"] username=None if user_id: resp=await ...
0d308b266cf1bdff6f1e716ab187adaf9906984f
43,583
def intersection(box1, box2): """ Args: box1: bounding box box2: bounding box Returns: float: the area that intersects the two boxes """ y_min1, x_min1, y_max1, x_max1 = box1 y_min2, x_min2, y_max2, x_max2 = box2 min_ymax = min(y_max1, y_max2) max_ymin = max(y_mi...
71746d93ead54aa5b36e7e6a5eb40e757711bef5
43,584
import json def make_json_buffer(json_obj): """Returns a file-like object containing json_obj serialized to JSON >>> f = make_json_buffer([1, 2, 3, True, {u'distance': 4.5}]) >>> f.read() '[1, 2, 3, true, {"distance": 4.5}]' """ return make_string_buffer(json.dumps(json_obj))
41d1306722583a302a440cfb5d79e923c5e04615
43,585
import re def remove_emoji(string): """ Remove emoticons from a text string and return a cleaned string """ emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs ...
436b71c2a9c36621b659630d5eb3b141800025bb
43,586
def delete_project(): """ 删除项目 :return: """ data = request.get_json() project_id = data["project_id"] project = Project.objects.filter(id=project_id).first_or_404() project.delete() devices = Device.objects.filter(project_id=project_id).get_or_404() for device in devices: ...
41fc3a09f65518e6bc63b6c95e52c01550bb9c52
43,587
def verify_proof(request: VerifyProofRequest) -> bool: """Verifies the proof Args: request: Request for the proof verification operation Return: True if verification was successful, False if not """ handle = bbs_verify_proof.bbs_verify_proof_context_init() bbs_verify_proof.bbs_v...
a8fa27924df8004e0ba86294e9d402fadbaf08bf
43,588
def _wrapAngle360(lon): """wrap angle to [0, 360[.""" lon = np.array(lon) return np.mod(lon, 360)
501a0004f7162369acea5db145e079f5de86275a
43,589
async def purge_all(ctx, amount, *args, **kwargs): """ Removes messages in given channel Args: ctx: amount: *args: **kwargs: Returns: """ channel = ctx.channel num = int(amount) + 1 # call is additional if num >= 1: def check_true(m): ...
bfb806b37ce5400ed08c5d8ea3693761bdb21e9a
43,590
def extended_5_3_predict(t, power_anaerobic_alactic, power_anaerobic_decay, cp, tau_delay, cp_delay, cp_decay, cp_decay_delay, tau): """ Credits to Damien Grauser. Source: https://github.com/GoldenCheetah/GoldenCheetah/blob/master/src/Metrics/ExtendedCriticalPower.cpp """ model ...
0b73eb9c4bde57cef9612418b30792d3091d191a
43,591
def tuplesums(tuplelist): # type: (List[Tuple[int, int]]) -> Tuple[int, ...] """[(a, b), (c, d), (e, f)] -> [sum(a, c, e), sum(b, d, f)] """ return tuple(sum(x) for x in zip(*tuplelist))
7367bb63789218b4ce4beb4f164ebbba5daed14c
43,592
def remove_emoji(data: str) -> str: """Remove the emoji from the 'data' string.""" return demoji.replace(data)
270d280152d79eb8b9c98361e34aa48df9c20944
43,593
import numpy def evaluateVariableResults(variable, timeColumnRef, timeColumnData, refData, testData, starts, ends, weightFactors, timeIndicator): """ Performance difference calculation between variable data sets. we use different statistical metrics to perform deep comparisions o...
368075ef5ef1a0da533590c1ad0a4c6305225f18
43,594
def session_login_basic(response: Response, request: Request, client_id:int=Depends(get_client_id), session_info=Depends(login_via_pads) ): """ ## Function <b>Basic login Authentication.</b> Supply us...
c0201a8eb691deb99d0792ede1ae970fff59d39b
43,595
def get_header_value(header_list, key): # type: (List[Tuple[str, str]], str) -> List[str] """Filter the header_list with provided key value. This method is used to parse through the header list obtained from the SMAPI response header object and retrieve list of specific tuple objects with keys like...
8cdd0630b5539c6229135a53ec4eb1add35fd1be
43,596
def data_by_variable(datalines, variable): """ This function takes in a list of datalines and returns a new list of datalines for a specified variable. Parameters: ----------- datalines : list This is a list of datalines output by Temoa. variable : string This is the variabl...
93c87625c9fce159424819a3fcfedeaa0fffd8b1
43,597
import torch def compute_gradient_penalty(D, real_samples, fake_samples, opt): """Calculates the gradient penalty loss for WGAN GP""" # Random weight term for interpolation between real and fake samples alpha = torch.tensor(np.random.random((real_samples.size(0), 1, 1, 1))).float() if opt.cuda: ...
3996eaf7c2600be1b8184e39d4c5108ac4deccb3
43,598
import glob def remove_skipped_echo_direct_transfer(df, fn): """Remove wells that were reported as skipped in the Echo protocol (xml). This functions works with Echo direct transfer protocols. Function supports using wildcards in the filename, the first file will be used. Returns a new dataframe witho...
a8ef266ad859fe1118c21f5d46925d86314b60e8
43,599