content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def consistent(a, b): """ It is possible for an argument list to satisfy both A and B """ return (len(a) == len(b) and all(issubclass(aa, bb) or issubclass(bb, aa) for aa, bb in zip(a, b)))
e79ec485c667d9d85692eb43de3f8442a28e94ec
3,616,600
from io import StringIO def adjust_image(f, max_size=(800, 800), new_format=None, jpeg_quality=90, fill=False, stretch=False, return_new_image=False, force_jpeg_save=True): """ Підганяє зображення під параметри. max_size - максимальний розмір картинки. один з розмірів може бути None (авто...
50b61e6f21639f7cca74b8dfcf5cb24ade4fff59
3,616,601
import urllib def is_cloneable(owner, name): """Verify if a repository is clone-able. Parameters ---------- owner : string User name of the owner of the repository. name : string Name of the repository to clone. Returns ------- cloneablility : 2-tuple A 2-tupl...
eb58a5ebc32f7253c58c220a34c70494d5e4f0bf
3,616,602
import os from datetime import datetime import json import mimetypes def audio_upload(): """ To POST files to this endpoint: $ curl -F "audio=@some_file.mp3" localhost:8080/api/v0.1/audio TODOs: - Store user data (who uploaded this? IP address?) - File metadata """ app.logger.inf...
692a21ea5e405d45d528e1d31bf97c36969b8254
3,616,603
import pandas def limit_to_appropriate_columns( *, res: pandas.DataFrame, transform: VariableTreatment ) -> pandas.DataFrame: """ Limit down to appropriate columns. :param res: :param transform: :return: """ assert transform.plan_ is not None # type hint assert transform.score_fr...
9dba8339b0a7d15964199e5ab2ebfc4d3b4d443c
3,616,604
from typing import Union def Optional(trait: TraitType) -> Union: """ Return Union of function argument and Instance(_Undefined) Args: trait (TraitType): optional trait Returns: union with undefined instance """ return Union(trait, Instance(_Undefined))
4fa6bf6017022e652f9af38f2db43d52ec1ed2f5
3,616,605
def mda_1D_Xindex(ScanNum,DetectorNum,coeff=1,bckg=0,filepath=None,prefix=None,scanIOC=None): """ Return x=index and y=detector(DetectorNum) for a given detector number DYY (as shown in dview). """ try: (data_file,det)=mda_unpack(ScanNum,filepath,prefix,scanIOC) index=det[DetectorNum][1] ...
827f950b3d793a0f7c8c39ce9236aba1ff9ff893
3,616,606
def requires_admin(func): """Decorator requiring the requesting user be a website admin""" @wraps(func) def inner(*args, **kwargs): if g.user is None: return JsonResponse.create(StatusCode.LOGIN_REQUIRED, {'message': "Login Required"}) if not g.user.website_admin: re...
f9793b3f1a9d8a7732842930784eab8578a4eb96
3,616,607
from cesiumpy.base import _CesiumObject, _CesiumEnum import six def to_jsscalar(x): """ convert x to JavaScript representation """ if isinstance(x, (_CesiumObject, _CesiumEnum)): return x.script if isinstance(x, bool): # convert to JavaScript repr x = 'true' if x else 'false' ...
b4049e067a0bbec29da83ffecc7110212050ced2
3,616,608
import os def createMatcapMaterial(material_name, matcap_image_name): """ matcapのマテリアルをshaderFXから作る matcap_image_name : imageファイルの名前 return : マテリアルの名前 """ selection = cmds.ls(sl=True) if not cmds.pluginInfo("shaderFXPlugin", q=True, loaded=True): cmds.loadPlugin("shaderFXPlugin") ...
4cc7a88cb5293c76f080d22f7d3095eb63b222ca
3,616,609
def covid_API_request(location:str = data['location'], location_type:str = data['location_type']) -> dict: """This function returns live data from the uk-covid19 API. Args: location (str, optional): Location of data needed from API. Defaults to data["location"]. location_type (str, ...
e22247bd74c06ca2b77ad4aa6136b26c46bdc82f
3,616,610
def pgloss(y_true, y_pred): """Policy Gradients loss. Maximizes log(output) · reward""" return - K.mean(K.log(y_pred) * y_true)
0f446fe4bc7bbf90bdea8a9557313e754b7f0dc5
3,616,611
from pathlib import Path def remove_venv_config(name: str) -> Path: """Removes a vsh virtual environment configuration file Args: name: name of virtual environment path: path to virtual environment working: path of working dir when entering virtual environment Returns: co...
df62e7d9e6468360dfd17a3c7affdf877f57b97f
3,616,612
def open(**kwargs): """ A factory function to open new ``Vim`` object. ``with`` statement can be used for this. """ return Vim(**kwargs)
459bc8663f48a7dffb3e28a02455b3d935721d3d
3,616,613
def difference(geometries, spatial_ref, geometry, gis=None): """ The difference function is performed on a geometry service resource. This function constructs the set-theoretic difference between each element of an array of geometries and another geometry ...
36142825006076adebee7260d1141e9a07e7a61a
3,616,614
from .main import round_trip_load def load_yaml_guess_indent(stream, **kw): # type: (StreamTextType, Any) -> Any """guess the indent and block sequence indent of yaml stream/string returns round_trip_loaded stream, indent level, block sequence indent - block sequence indent is the number of spaces be...
f8b7c6df5bc45aafe3b0551ace1c3e3ce7fe058e
3,616,615
from pathlib import Path def get_stats_test(): """Test the HTML page digestion against a test stats.html.""" # Hack function for developing new functionality without # hammering the RWR servers with requests logger.debug("Loading stats from stats.html example for testing") html = Path("stats.html"...
27ee7837fd1f9b6e88903fbfac667efbb153010a
3,616,616
def remove_duplicate_edges(G, max_ratio = 1.5): """ function for deleting duplicated edges - where there is more than one edge connecting a node pair. USE WITH CAUTION - will change both topological relationships and node maps :param G: a graph object :param max_ratio: most of the time we see duplicate ...
bc2a23081749e3dcb135ceea5aad004a7331e794
3,616,617
from typing import Sequence from typing import Callable def conv_classifier_deterministic_loss( params: utils.Params, batch: utils.Batch, num_classes: int, layer_channels: Sequence[int], l2_reg: float = 0.0, explicit_tagging: bool = False, activation: Callable[[LayerInputs], LayerInputs] =...
1432767d83c27826e06574ea825117c764708dfc
3,616,618
def repo_changed(directory): """Determine if the Git repository in directory is dirty""" ret = _call_git("status", "--porcelain", directory=directory) return bool(ret.stdout)
9956fb3211b7e9d689bc72f5a09ecb46f4f95b00
3,616,619
def color_bar(mode): """ Create different colormap for each mode :param mode: 1 -- Rate, 2 -- Occupancy, 3 -- Recommanded :type mode: int :returns: color map :rtype: branca.Colormap """ cm_name = {1: cm.linear.YlGnBu_07, 2: cm.linear.RdPu_06, 3: cm.linear....
28e0e7f91fa0edde6edc9325e5d1cbf7a9672bf7
3,616,620
def just_nucs(seqs): """eliminate sequences containing gaps/Ns, along the 1st axis, match each base in seqs to <= 3 element-wise, give the indices of those just_nucs seq idx. """ (indices,) = (seqs <= 3).all(axis=1).nonzero() just_bases = seqs.take(indices, axis=0) return just_bases
142bb7aa905e34d5e12fcfe3233bc3f80d440916
3,616,621
def plot_image_as_3d_histogram(image, save_path=None, image_title='Image', histogram_title='Histogram'): """ plot an image as a 3d histogram beside itself. :param image: a 2D numpy array that is the image to plot :param save_path: the path to save the plot to. if None the figure is displayed. :param...
620a7cf9351ef845dc82be5eb86fb1f6f5e44158
3,616,622
def read_clip(path, undersample=4): """Read a GIF a return an array of shape (C, W, H, T).""" gif = Image.open(path) frames = [] for i in range(gif.n_frames): gif.seek(i) frames.append(np.array(gif.convert('RGB'))) frames = frames[::undersample] array = np.stack(frames).transpose...
322e54057454822068e0cc6eb048cf899e1f49f6
3,616,623
import copy def fir(nb, nk, u, y): """ Estimates a FIR model based on input (u(t)) and output (y(t)) vectors. Returns the polynomial B(q) relative to the MIMO FIR model with nu inputs and ny outputs, also affected by white gaussian noise e(t), as follows: y(t) = B(q)*u(t) + e(t) Parame...
c156d98f824e825a1a82e00f94a0113d4309d936
3,616,624
import warnings def random_forest_error(forest, X_train, y_train, X_test, alpha_level=0.05, n_fixed_points=50, n_mc_samples=500, n_trees_var=500, use_built_trees=True, random_state=None, n_jobs=None...
8d110d90aab17514c253d42cff80d0c24dabe081
3,616,625
def descriptive_stats(x, feature_prefix=''): """Create a pandas dataframe containing the features calculated on x. x is an input array for which the features below are calculated. feature_prefix is prepended to each of the feature names to create unique columns.""" feature_names = [ 'minimum'...
f97843f0bdff307ca40a16bf5c3b970f43ca0f4d
3,616,626
from typing import Callable from typing import Optional from datetime import datetime def init_daemon(config, given_logger, handler: Callable, complete_callback: Optional[Callable] = None, post_mortem_callback: Optional[Callable] = None, ...
d689d19dbae1e651f476b0917e6e15f262220a50
3,616,627
from typing import Callable def bind( function: Callable[ [_FirstType], KindN[_BindableKind, _UpdatedType, _SecondType, _ThirdType], ], ) -> Kinded[Callable[ [KindN[_BindableKind, _FirstType, _SecondType, _ThirdType]], KindN[_BindableKind, _UpdatedType, _SecondType, _ThirdType], ]]: ...
3dcd70a5f72ffd41df89e92b89a3761faf75576f
3,616,628
import numbers def transforms_rowskipfilter( data, output_data=None, model=None, count=0, **params): """ **Description** Allows limiting input to a subset of rows by skipping a number of rows. :param count: Number of items to skip (inputs). :par...
9fa574924c1c130acd6efaa1a4231175fc8d206d
3,616,629
from astropy.io import fits import os import shutil def get_lc_file_and_data(yourpath, target): """ goes in, grabs the data for the target, gets the time index, intensity,and TIC if connection error w/ MAST, skips it. Also masks any flagged data points according to the QUALITY column. parameters: ...
a3ce960fe39f457192ba92820a2913d6cbded2a3
3,616,630
def startofday(expr, offset=None): """Get the start of day for a timestamp (round to preceding midnight). Parameters ---------- expr: str, Column or expression. The datetime column/expression to round to the start of the day. offset: int, default None The number of days to shift the...
c5a6439880bc2e64771fc760e7bdd1159d6773ad
3,616,631
def polar2cart(angle, magnitude, retField=False): """ Returns the field from the input phase angle and magnitude. Args: - angle, phase angle of the field (2 dims); - magnitude, magnitude of the field (2 dims); - retField, if True returns a field, otherwise returns (x,y). """ if retField: if np.isscalar(m...
1fe837256e89b9dafdbbf5148a85ccbf88100d3a
3,616,632
def grant_role(role, user, tenant=None): """Grants `role` to `user` (and optionally, on `tenant`)""" role = db_api.ROLE.get_by_name(name=role).id user = db_api.USER.get_by_name(name=user).id if tenant: tenant = db_api.TENANT.get_by_name(name=tenant).id obj = db_models.UserRoleAssociation()...
62e6344d64085b0cedb34ff02145a550566c99ff
3,616,633
def get_domain_server_version(domain): """ Get the Server version based on the Server header for the web server. """ if domain.canonical.server_version is not None: return domain.canonical.server_version if domain.https.server_version is not None: return domain.https.server_version ...
56966c986a5390c8a9aaa0fb71b19bfe2ca7361a
3,616,634
from pathlib import Path from typing import Union def load_gan(path: Path, cuda: Union[bool, str] = False) -> ctgan.CTGANSynthesizer : """ Loads a ctgan model. Caches the models so that repeated models are only loaded once Parameters ---------- path : Path Path to the file to load the ...
09c481b3b0c3ecf9651ec555c01fd6022e269710
3,616,635
def convert_celsius_to_fahrenheit(temperature): """ Converts the temperature from degrees Celsius to degrees Fahrenheit. :param temperature: The value to convert, which must be in degrees Celsius :type temperature: int | long | decimal.Decimal :return: The temperature in degrees Fahrenheit to three decimal places...
df6b20631a548ea28a07ece7b0649761329b2fed
3,616,636
def torify(x, size): """shift points to canonical torus domain # Arguments x: points to be shifted size: torus size # Result points shifted to canonical torus domain """ rep_size = np.repeat(np.expand_dims(size,-1), x.shape[-1], -1) return x - rep_size * np.floor( (x/rep_...
41278b7907f2d316c11a3578e37a3b8a8c5f9d55
3,616,637
def build_lst(a, b): """ function to be folded over a list (with initial value `None`) produces one of: 1. `None` 2. A single value 3. A list of all values """ if type(a) is list: return a + [b] elif a: return [a, b] else: return b
1e47b7bf2987a52b77266d6949af40f1c7df0109
3,616,638
from typing import List def get_mean_at_row(dfs: List[pd.DataFrame], row: int, column: str) -> np.double: """ Return the mean value of a certain column among the given list of benchmark dataframes in a certain row :param dfs: list of benchmark dataframes :param row: index of the row to be selected ...
872975a8848ec160a8581e3a6505952ab6fe08ee
3,616,639
def foo_1(x): """ test >>> foo_1(4) 2.0 """ return x ** .5
e8f7d3e9486e8c794a8c5761cea156b770851971
3,616,640
def add_extra_information(record=None, log_record={}): """ Adds extra useful information to logging """ if 'request' in log_record: request = log_record['request'] del log_record['request'] for key, value in META_KEYS.items(): log_record[value] = request.META.get(key...
c0cbb92b154a1ae29cc23aa377d7dee7e03bc337
3,616,641
def sentence_perplexity(model, sentence): """Compute sentence perplexity for trigrams""" words = sentence.split() num_words = len(words) trigrams = ngrams( words, 3, pad_left=True, pad_right=True, left_pad_symbol=PADDING.left_pad_symbol, right_pad_symbol=PADDING.r...
1dcecb7b49e0f5c01e07e4f40b199fb92448322f
3,616,642
def VectorEnv( env_id: str, n_envs: int = 2, parallel: int = False, env_type: str = "gym", ) -> VecEnv: """ Chooses the kind of Vector Environment that is required :param env_id: Gym environment to be vectorised :param n_envs: Number of environments :param parallel: True if we want environments...
61ddf820e61391e742ec485a5a80070a4c302cfc
3,616,643
def requires_atoms(): """A function requiring atoms to run""" def func_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): molecule = args[0] assert hasattr(args[0], 'n_atoms') assert hasattr(args[0], 'atoms') if molecule.atoms ...
7358c3dc05b6607582cf68f9306bcfed36c5dbe2
3,616,644
def acceptsArguments(method, numberOfArguments): """ Returns True if the given method will accept the given number of arguments: method - the method to perform introspection on numberOfArguments - the numberOfArguments """ if 'method' in method.__class__.__name__: num...
9cdf528d50fa4c7f99cf8c2674751148d499ae19
3,616,645
from typing import List from typing import Union from typing import Dict def string_match_classifier_from_yaml(f) -> StringMatchClassifier: """Build StringMatchClassifier from a yaml file. Yaml is much easier to edit in real-world classifiers that often include 50+ lines Example ------- The YAML ...
8bdb1fa2a660749e52b194d27ef28b4e517e909b
3,616,646
def kl_multi_div(params_1, params_2): """Kullback-Leibler divergence for multivariate diagonal-covariance gaussians. The divergence is defined as: D( (mu_1, sig_1) || (mu_2, sig_2) ) = .5 * ( Spur(sig_2**(-1) * sig_1) + (mu_2 - mu_1).T * sig_2**(-1) * (mu_2 - mu_1) - k + ln(det(sig_2) ...
006f4a98d8d084eed74eb359cf4ff07bce8bfbec
3,616,647
from typing import Dict from typing import List import copy def _make_coco_images(df: pd.DataFrame, image_map: Dict) -> List: """makes images list for coco""" df = copy.deepcopy(df) df.drop_duplicates(subset=["image_id"], keep="first", inplace=True) df = ( df[["image_id", "image_height", "imag...
c4d78b638df2a15cc2637349301bc82fd4446b4c
3,616,648
from cbflib_adaptbx import uncompress import binascii def get_raw_data_from_file(imageset, i): """Use cbflib_adaptbx directly to access the raw data array rather than through the imageset, in order to work for multi-panel detectors and other situations where the format class modifies the raw array""" ...
19cbb82d5470f8f473f673cff5ed95cdf7afd6c7
3,616,649
import copy def _get_intpol(root, gridfile, freqpath=None): """ Extract interpolation settings. Parameters ---------- root : Element Element object of the whole xml inputfile gridfile : str Name of the inputted gridfile freqpath : str or None If fitting frequencies...
11b879f177e034a9d50a1d17eadc95e680133534
3,616,650
def is_trusted_idb(*args): """ is_trusted_idb() -> bool Is the database considered as trusted? """ return _ida_loader.is_trusted_idb(*args)
eddc1fc63e5634a8b3cfe331487fd9e9c86f9c22
3,616,651
def _restore_namedtuple_gt_255_fields(typename, fields, values): """Creates an namedtuple_gt_255_fields objects along based its __reduce__ description. The __reduce__ protocol to support pickling requires: - a callable method that returns the pickled object on restore - a tuple of its arguments. T...
0bb5e0e1d995e7bf9eb77a29c877e085fe1b9eaf
3,616,652
def range_(x: pd.Series, w: int = 0) -> pd.Series: """ Range of series over given window :param x: series: timeseries :param w: window: number of observations to use (defaults to length of series) :return: timeseries of range **Usage** Returns the range of the series (max - min) over roll...
311535c9f5d07a64a66bdc118dd2e93bb8f3b3e1
3,616,653
def normal_ordered_ladder_term(term, coefficient, parity=-1): """Return a normal ordered FermionOperator or BosonOperator corresponding to single term. Args: term (list or tuple): A sequence of tuples. The first element of each tuple is an integer indicating the mode on which a fermion ...
744ebaa139c514271a2b6788d4333f2eaf7d39eb
3,616,654
def findPams (seq, pam, strand, startDict, endSet): """ return two values: dict with pos -> strand of PAM and set of end positions of PAMs Makes sure to return only values with at least GUIDELEN bp left (if strand "+") or to the right of the match (if strand "-") If the PAM is cpf1, then this is inverse...
07330d13acfcabed543bb1dff0759dd960e784a4
3,616,655
import json import sys import locale import os from datetime import datetime def form_02(request_data): """ Процедурный лист """ num_dir = json.loads(request_data["hosp_pk"]) ind_card = Napravleniya.objects.get(pk=num_dir) patient_data = ind_card.client.get_data_individual() if sys.platf...
94731384ff5e2113eed116e3f6359f19d9956f46
3,616,656
def decode_depthimg(depthimg): """ depthimg.shape should be (H,W,C) where H is height, W is width, C is RGB channel i.e. C=3 In each depth png file the top 8 bits of depth are packed into the green channel and the lower 8 bits into blue. """ r = depthimg[:, :, 0] g = depthimg[:, :, 1].astype(np....
7cf9431b50e696c652c77698db5b1ccfb1a18ace
3,616,657
def self_att(tensor, tensor_val=None, mask=None, mask_is_length=True, logit_fn=None, scale_dot=False, normalizer=tf.nn.softmax, tensors=None, scope=None, reuse=False): """Performs self attention. Pe...
13d41ba2b04306de52b6f4d24ff7c08a28c1fd19
3,616,658
def ogda_train(X, Y, priors=None): """Train a omoscedastic GDA classifier. Parameters ---------- X : ndarray, shape (m, n) training features. Y : ndarray, shape (m,) training labels with values in {0, ..., k - 1}. priors : ndarray, shape (k,) Prior probabilities for the ...
e7ab4a73646770272d7105ec32ec5059bfa821ba
3,616,659
def local_align(x, y, score=ScoreParam(10, -5, -7)): """Do a local alignment between x and y with the given scoring parameters. We assume we are MAXIMIZING. example: >>>local_align("acgt", "cg", ScoreParam(gap=-5, match=10, mismatch=-5)) """ # create a zero-filled matrix A = make_matrix(l...
0aa837f9e2c0b797ad182fb9f495f64be9bd74ba
3,616,660
def sigma_ss_to_xx(self, e_cm): """ Cross section for mediator annihilations into DM. """ return sig_ss_to_xx( e_cm, self.mx, self.ms, self.gsxx, self.gsff, self.gsGG, self.gsFF, self.lam, self.width_s, self.vs, )
5f60a26dc7a57821a5a8f3f713a7217f94e8a8a8
3,616,661
import re import json import time import requests import traceback def track(headers, body): """ 数据追踪,解决1金币问题 :param headers: :param body: :return: """ try: url = 'https://mqqapi.reader.qq.com/log/v4/mqq/track' timestamp = re.compile(r'"dis": (.*?),') body = json.du...
71ce3ca86a49877abde9d598114c0b9899a1bea4
3,616,662
def global_handle_allocate(flags, size): """Allocate a specified number of bytes via a global handle. Parameters: :param size: The number of bytes to be allocated .. note:: Can only be used with twain 1.x sources """ return _GlobalAlloc(flags, size)
8642ad1db71d22eae74c3a052f31d8d928856a98
3,616,663
from typing import Optional from typing import List def match_difficulty(our_doc_filter: DocumentFilter, other_doc_filter: DocumentFilter, mu_lst: Optional[List[str]] = None, sum_lst: Optional[List[str]] = None, test: Optional[bool] = False) -> pd.DataFrame: """ Calc...
d6c1ef3a1dea63dd7011cab06147eade74f64cf6
3,616,664
def delete_feedback(user_feedback_id): """ Allows Admin to delete user feedback comments from the db """ # Checks if user is in session if "user" in session: # Checks if user is admin if session["user"] == "admin".lower(): # Removes a specific feedback entry from the db ...
f538c863e30c00f7a3c4b67035ef1eb01c12ca7b
3,616,665
def FormDis(dfr, num=5): """ Format and display num number of rows of dataframe dfr, with float-type values in 2 decimals and yellow color. """ ftn = {"z":"{0:,.2f}"} ftc = {"z":"green"} for com in dfr.columns: try: one = dfr.loc[0,com] if float(one): ...
1b1bfdf58a0acdaff0611210a68000e862354ca6
3,616,666
def hash_transaction(transaction: Transaction) -> str: """ Generate a hash for the transaction to make them identifiable. """ data = transaction.data payload = "%s:%s:%s:%s:%s" % ( data["date"], data["applicant_name"], data["purpose"], data["amount"], data.get...
e64a1f2a2ea1935fe2fd02c4bbdd1a27aa851b07
3,616,667
import pandas import numpy def try_to_datetime(x, frmt=''): """Try to convert a string to a date. In case of failure, return nan""" try: if frmt == '': return pandas.to_datetime(x) else: return pandas.to_datetime(x, format=frmt) except: return numpy.nan
f639a5fdc4170531b3bf660ee0979041a8aab123
3,616,668
def crs_from_layers(source_layers: t.List[t.SourceLayer]) -> t.List[t.Crs]: """Return an intersection of crs supported by each source layer.""" cs = set() for sl in source_layers: if not sl.supported_crs: continue if not cs: cs.update(sl.supported_crs) else:...
c4bd62a84941e04bb7f51724c73229f96b8d18d5
3,616,669
import os def food_image_upload_path(filename): """美食图片上传路径""" return os.path.join( "food_image", "%Y/%m", filename )
d7ee8ed6f0027edc0fecba6aa2c3e64919abb7ab
3,616,670
def test_app(): """Return a test Application.""" return Application('testing')
0dd417db575116c7ef2841a68a9ec9e8ad2f6904
3,616,671
import random import os import io def main_cli(opts, args, gt_instance_uuid=None): """! This is main CLI function with all command line parameters @details This function also implements CLI workflow depending on CLI parameters inputed @return This function doesn't return, it exits to environment with prop...
09d8db2686f7ecd73aa9d5f98b44ea1e98a45cae
3,616,672
def determine_torsion_symmetry(label, top1, mol_list, torsion_scan): """ Check whether a torsion is symmetric. If a torsion well is "well defined" and not smeared, it could be symmetric. Check the groups attached to the rotor pivots to determine whether it is indeed symmetric We don't care about th...
11026d207cd20d0e79e456a00823fb74e0cbdb82
3,616,673
def check_holdings(asset_id, address): """ Checks the asset balance for the specific address and asset id. """ account_info = client.account_info(address) assets = account_info.get("assets") if assets: asset_holding = None for i in account_info["assets"]: if i['asset-...
7cf31751cb63616a104c7222f34be6f59369e881
3,616,674
import re def isValidGUID(guid): """ Verify the GUID generated with uuidgen """ status = False pattern = "[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}" m = re.search(pattern, guid.upper()) if not m: tolog("!!WARNING!!2333!! GUID=\'%s\' does not follow pattern \'%s\'" % (g...
54dfc207945bcb3052da240b43160c5e95ce8efb
3,616,675
from pathlib import Path def read_probabilties(proba_folder, subset='valid', model_names=model_names): """Reads saved .npy validation and test predicted probabilities from PsychicLearners/data/probabilities""" proba_folder = Path(proba_folder) all_probabilities = [] for folder in...
dc0f75eb50295f3bf023a942ee731f9fdae1006e
3,616,676
import argparse def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Faster R-CNN demo') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--cpu', dest='cpu_mode', ...
516568f4c9cae51faf9f7d5547d05ea28731590c
3,616,677
from typing import Union from typing import Callable def filter_bad_ids( data: DataFrame, bad_ids: Union[Series, list[str], str], filter_col: str, filter_method: Union[str, Callable] = "odo", ): """ Filter observation IDs that are flagged as badded, either from an online Google Sheet or fr...
1e96e3cdc3ac69ab24c1d6f88ada13dc4bb3682d
3,616,678
def normalized_abl1(): """Return normalized Gene Descriptor for ABL1.""" params = { "id": "normalize.gene:ABL1", "type": "GeneDescriptor", "gene_id": "hgnc:76", "label": "ABL1", "xrefs": { "ensembl:ENSG00000097007", "ncbigene:25" }, ...
72c6393dc47f285be5f20a2dc7a3349b7bba0d65
3,616,679
import zipfile import os import shutil def download_tif(image, polygon, bandsId, filepath): """ Downloads a .TIF image from the ee server. The image is downloaded as a zip file then moved to the working directory, unzipped and stacked into a single .TIF file. Two different codes based on which ve...
7b05d1f8eff209bd09a5f3e4aba5f39601434def
3,616,680
def lookup_school_reverse(school_id): """ A function to lookup school name from school_id Args: school_id as int Returns: school (str): the name of the school Examples: lookup_school_id_reverse(167) >>> "Cornell" """ school_row = _SCHOOL_ID_LU...
4aacefbffe689056e91c9afc7c83b700ce2b883c
3,616,681
def flip(x): """ flip image(翻轉影像) """ x = tf.image.random_flip_left_right(x) # 隨機左右翻轉影像 return x
e864e7277a5ded7717e279f43fddef72a73fb637
3,616,682
def three_to_one(s): """ Three letter code to one letter code. For example: ALA to A. """ i=d3_to_index[s] return dindex_to_1[i]
14464de8f7cf04da379aad1492a9f4a0d746e449
3,616,683
def get_queue_index(name='default'): """ Returns the position of Queue for the named queue in QUEUES_LIST """ queue_index = None connection = get_connection(name) connection_kwargs = connection.connection_pool.connection_kwargs for i in range(0, 100): q = get_queue_by_index(i) ...
c8dcc822e67ef886ec45acb866afd60cdc8f4fa5
3,616,684
def to_hash_str(source, encoding="ascii"): # pragma: no cover -- deprecated & unused """deprecated, use to_native_str() instead""" return to_native_str(source, encoding, param="hash")
df745e66337965501bbc42eef502f2710fd98c97
3,616,685
def k_pod(data, n_clusters,max_iter=300,tol=0,random_state=0): """ Compute cluster centers and predict cluster index for sample containing missing data. Parameters ---------- data: {array-like, sparse matrix} of shape (N, P) Data to predict clusters for. n_clusters: int The number ...
3962e9f6bf6c3d5eb4cd346fc171ae69a5041cdb
3,616,686
def _get_datemapping(df, events): """ return the mapping of human_readable dates to integer numbers for plotting. Mapping is a dict. Furthermore return a sorted list of the dates. """ dates = sorted(df.human_readable.unique(), key=_date_key_function) date_mapping = {} for in...
2e88a3d01aff568c75205e397e07fe32c65a35a2
3,616,687
import datasets def load_rotated_mnist(data_dir, image_size=32, train=True, rotation=0): """ Load a MNIST dataset where each image has a rotation. """ rotate_image = rotate_transform(rotation) image_transforms = [ transforms.Resize(image_size), transforms.CenterCrop(image_size), ...
fb7b39267e7a7df2d5c265a33b5942832ffb1a40
3,616,688
import logging def appendProduct(prod_properties, userID): """Move products from aggregated tab onto pending invoices one""" db = MySQLdb.connect(passwd=db_password, db=db_name, user='orsys') logging.debug("This is output from appendProduct") logging.debug(prod_properties) (sku, price, qty, suppli...
f02ca50f422caaef0a500f01d05d883b6d31f3fa
3,616,689
def slave_delete(request): """ 接令人删除为同意的召集令请求 """ # body = json.loads(request.body) body = request.GET req = body.get('request_id', '') try: Request.objects.filter( uid__exact=req, request_status__exact=0).delete() except Request.DoesNotExist: return HttpResp...
cfee53adfee8db9881fc3546778ce2c7efe60d3e
3,616,690
import collections def meetup(date): """ Displays the meetup taking place on the given date. """ meetup = _get_meetup(date) user_upvotes = [] user_downvotes = [] ideas = meetup.sessionideas idea_ids = [idea.id for idea in ideas] vote_results = collections.defaultdict(int) for v...
9a8d874f70b3b2249f8bcd8fc120060e2cf48f9e
3,616,691
import math def is_hilbert_squarefree_number(n): """ I define a "Hilbert squarefree" number as a positive integer not divisible by the square of any Hilbert number, i.e. by a Hilbert square. Note: the given n need not be a Hilbert number but could be any positive integer. """ ubound = ma...
28f2339aafd5ef7a319bfb7ff618f9ec9861ad39
3,616,692
def get_plotting_specs_somato(beamf_type, plot_type): """Get all parameters and settings for plotting.""" if plot_type not in ('corr', 'foc', 'ori'): raise ValueError('Do not know plotting type "%s".' % plot_type) if beamf_type == 'lcmv': xmax = 130 if plot_type == 'foc': ...
7da949136d3042c3fb99f779fc626e1247b98447
3,616,693
import types def parse_fp(source, module_name, lexer=None, parser=None, enable_cache=True): """Parse a file-like object to thrift module object, e.g.:: >>> from thriftpy.parser.parser import parse_fp >>> with open("path/to/note.thrift") as fp: parse_fp(fp, "note_thrift") <...
3b929594d1006e42ae1c23695e6d6754caf652ab
3,616,694
from typing import List def create_streaming_params(client_params: List[ClientParam]) -> str: """Build the C++ parameter list for streaming functions.""" params = _to_parameter_list(client_params) client_context_param = "::grpc::ClientContext& context" params = [stub_param()] + [client_context_param] ...
5d48c3a29c41327152768412a09dd61f6915e953
3,616,695
def app(request): """AioHTTP application with configurable endpoints. Endpoint names should be passed as positional arguments to `pytest.mark.endpoints` decorator. """ marker = request.node.get_closest_marker("endpoints") if marker: endpoints = marker.args else: endpoints = ("su...
eeb90127e74c89403bd4efb21bbfa62c4ede4673
3,616,696
def scraperMode(): """ The operating mode of the scraper. It can either send notification if text is found on the page, or waiting and keep refreshing until the text goes away from the page. :return: the mode """ print("In which mode should the scraper behave?\nInsert the...
f60a2fdb73ed92c970c764d8327b11f40edfbd45
3,616,697
import numpy def checkCoordinateList(coordinates, varname="coordinates"): """ Check that the given coordinates is a valid Nx3 sequence of numbers. :param coordinates: The object to test. To pass the test this must be an Nx3 array of floating point numbers. :param varname: The ...
7048c5a7fa4231ce8849d0a67ee07e10ea80e6ad
3,616,698
import re def validate_enum(temp_enum): """ Strips spaces & converts values that could be interpreted in yaml as nonstring, to double quotation string """ enum = stripper(temp_enum) # enum = enum.replace(':', '-') if enum != 'open' and '/' not in enum: if isinstance(enum, str) an...
a1ffbb3713a1e4ae025d01ab38e12beb28c8499f
3,616,699