content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def account(): """Account and update account route """ form = UpdateAccountForm() if form.validate_on_submit(): # if form.picture.data: # picture_file = save_picture(form.picture.data) # current_user.image_file = form.picture.data current_user.image_file = form.pictur...
f8e4c90e525e5f3d05b8afcf9a719044853774a1
3,617,637
import warnings def keep_corelated_data(data: DataFrameOrArrayGeneric, threshold: float = 0.5) -> DataFrameOrArrayGeneric: """Remove columns that are not corelated enough to predicted columns. Predicted column is supposed to be 0. Args: data (DataFrameOrArrayGeneric): Time series data. thresh...
3d082b026641aedabc26d071bbed6f7be3810267
3,617,638
def max_pool_forward_naive(x, pool_param): """ A naive implementation of the forward pass for a max pooling layer. Inputs: - x: Input data, of shape (N, C, H, W) - pool_param: dictionary with the following keys: - 'pool_height': The height of each pooling region - 'pool_width': The width of each pool...
8e38f5d72a35ee206aada709a93152db04a232f7
3,617,639
import operator def give_recom_result(user_vec, item_vec, userid): """ user lfm model result give fix userid recom result :param user_vec: lfm model result :param item_vec: lfm model result :param userid: user :return: list :[(itemid,score),(itemid1,score1)] """ fix_num = 80 if u...
fe796936916b403523b96627f520f16464eb94e3
3,617,641
import requests def save_file(fileName): """Saves a file of a given name, and returns the json response.""" return requests.post(BASEURL+"documents",headers=HEADS,files={'requester.py': open('requester.py', 'rb')})
12e227f5fa0b5684b34c38c3c6c4543c1bb63ca5
3,617,642
import json def load_label(label_path): """ Loads a label from a JSON file """ with open(label_path, 'r') as label_file: label = json.load(label_file) return label
f6a2873abee024d64ede78f18a96f0a1b95abd0b
3,617,643
def get2d23d(depth, camera_pose, K, pt1, pt2, znear, zfar, width=480, height=640): """ input: depth: image depth(in coordinate) camera_pose: orign camera_pose K: camera intrinsic pt1: orign 2d Point pt2: matchinfg 2d point znear,zfar: depth clip range retur...
dace3aa40b0c9792d005b974347200f4f1812896
3,617,644
import copy def clip_image(image,roi=[],rotangle=0.0,cp=False): """ Clip an image given the roi Parameters: ----------- * roi is a list [c1,r1,c2,r2] = [x1,y1,x2,y2] Note take x as the horizontal image axis index (col index), and y as vertical axis index (row index). Therefore,...
4fe385cf7a15fac59f0a4989970b1523a922deb6
3,617,645
from platypush.backend import Backend from typing import Optional import re def get_backend_name_by_class(backend) -> Optional[str]: """Gets the common name of a backend (e.g. "http" or "mqtt") given its class. """ if isinstance(backend, Backend): backend = backend.__class__ class_name = backen...
13fc8c76df9446ded5c81d7f6db1ae52cc8214e4
3,617,646
import time import torch def run_one_epoch( epoch, loader, model, criterion, optimizer, meters, phase='train', ema=None, scheduler=None, eta=None, epoch_dict=None, single_sample=False): """run one epoch for train/val/test/cal""" t_start = time.time() assert phase in ['train', 'val', 'test', 'cal']...
40aae97098058122fe70acb518bbe531d1928874
3,617,647
def load_signature_library(filename): """ Load a signature library from a .sig file. :param filename: input filename :return: instance of `TrieNode`, the root of the signature trie. """ with open(filename, 'rb') as f: buf = f.read() return SignatureLibraryReader().deserialize(buf)
ae8d639473ef0424688d315acc82c67a0b19aa09
3,617,649
def create_random_datetime(start, end): """ This function will return a random datetime between two datetime objects. Borrowed from: http://bit.ly/gM45o4 """ delta = end - start int_delta = (delta.days * 24 * 60 * 60) + delta.seconds random_second = randrange(int_delta) return (sta...
3d71be3bfe19bdbb0c0e4eca7c3a25b15733b3da
3,617,650
import yaml def get_task_config(task_name, is_remote): """Return powercycle task config.""" if is_remote: config_location = powercycle.abs_path( f"{powercycle_constants.REMOTE_DIR}/{POWERCYCLE_TASKS_CONFIG}") else: config_location = powercycle.abs_path(POWERCYCLE_TASKS_CONFIG)...
b03c6d3e3690d543c82b3780b4a8a72861cd11cd
3,617,651
def resize(anns, size, output_size): """ Parameters ---------- anns : List[Dict] Sequences of annotation of objects, containing `bbox` of [l, t, w, h]. size : Sequence[int] Size of the original image. output_size : Union[Number, Sequence[int]] Desired output size. If size...
800135ac9d65f55ae96d04fc645ac0d2b913b76c
3,617,653
def get_league_entries_by_summoner(summoner_ids): """ https://developer.riotgames.com/api/methods#!/985/3356 Args: summoner_ids (int | list<int>): the summoner ID(s) to get league entries for Returns: dict<str, list<League>>: the summoner(s)' league entries """ # Can only have ...
7e0b72e8502a59e8ae1728830497988a4e2a88be
3,617,654
def scheduler() -> BackgroundScheduler: """Retrieve the scheduler, intended mostly for unit testing purposes.""" if not _SCHEDULER: raise EngineError("Scheduler is not available") return _SCHEDULER
a45993a2806725fd315fa4d9926adfa6cc50c65d
3,617,655
def toDiscrete(m): """ Args: - m (m,n) : np.array with the occupancy grid Returns: - discrete_m : thresholded m """ y_size, x_size = m.shape m_occupied = np.zeros(m.shape) m_free = np.zeros(m.shape) m_occluded = np.zeros(m.shape) #Handpicked occupied_value = 0.8...
9d045d09a338ccf5dcd4a3a816f5eb0af77fdec6
3,617,656
def has_overlap(x0, xd, y0, yd): """Return True if the ranges overlap. Parameters ---------- x0, y0 : float The min values of the ranges xd, yd : float The widths of the ranges """ return x0 + xd >= y0 and y0 + yd >= x0
6b2a6eff892e28376ed08bf8f60c67f49cdeff44
3,617,657
def _ecdf_vals(data, formal=False): """ Get x, y, values of an ECDF for plotting. Parameters ---------- data : ndarray One dimensional Numpay array with data. formal : bool, default False If True, generate x and y values for formal ECDF (staircase). If False, generate x ...
1bae53fbbeeea51add956e1f4e6e7eb434b7ade0
3,617,658
def add_classification(hw_data, index): """ Add a column at the end of the data to capture wind severity. 0 if wind speed is < 50 1 if wind speed is >= 50 """ sev_wind = hw_data[:, index] >= 50 sev_wind = sev_wind.astype(int) sev_wind = sev_wind.reshape(len(sev_wind), 1) hw_data = ap...
c855043f1ba5b762b7abe347672c924209de648e
3,617,659
from typing import List import re def check_airflow_versions_in_quick_start_guide() -> List[DocBuildError]: """Check that a airflow version is presented in example in the quick start guide for Docker.""" build_errors = [] build_error = assert_file_contains( file_path=f"{DOCS_DIR}/apache-airflow/s...
4b775e8f1d84574e2fea8419fe7bf5065d5c9af0
3,617,660
def load(filename): """ Load nifti1 single or pair from `filename` Parameters ---------- filename : str filename of image to be loaded Returns ------- img : Nifti1Image or Nifti1Pair nifti1 single or pair image instance Raises ------ ImageFileError: if `filenam...
22d10861ea273d18a15f1ff385a8e9ae4a26b288
3,617,661
import attr def test_input_spec_func_1b_except(use_validator): """ the function w/o annotated, but input_spec is used metadata checks raise an error """ @mark.task def testfunc(a): return a my_input_spec = SpecInfo( name="Input", fields=[ ( ...
89c27fcd7fb6443fa950bb31acee4b19f42ce487
3,617,662
import itertools import math def corr1(xydata): """corr1(xydata) -> float Calculate an estimate of the Pearson's correlation coefficient with a single pass over iterable xydata. See also the function corr which may be more accurate but requires multiple passes over the data. >>> data = zip([0, 5...
a22261826b45b2cbbc48cba8c18dbff241865db3
3,617,663
from typing import Tuple def vehicle_capacity_is_respected(solution: Solution) -> Tuple[bool, str]: """ Verifies the vehicle capacities are respected by each tour of the solution. """ problem = Problem() for route in solution.routes: if any(stacks.used_capacity() > problem.capacity ...
0edb3c7d8ab464827e732c19d9d0bb2230872156
3,617,664
def get_pwn_cutoff(ra,dec,rad_search=2., deathline = 1.e34): """ Set cutoff for PWN based on association with pulsars in ATNF catalog Only pulsars with Edot > 1.e34 erg/s are considered, because cutoffs at ~1 TeV should have already been detected :param ra: R.A. of PWN center, deg :param dec: De...
23cb431ff933575ed537e5afbdc1b0df52291749
3,617,666
def _any(series, values): """ Returns the index of rows from series containing any of the given values. Parameters ---------- series : pandas.Series The data to be queried values : list-like The values to be tested Returns ------- index : pandas.index The i...
fb663895f97a2456e144e070ed2b09fd2308a13b
3,617,667
def CIFAR10(train=True, path=None): """Thin wrapper around torchvision.datasets.CIFAR10 """ mean, std = [0.491, 0.482, 0.447], [0.247, 0.243, 0.262] normalize = transforms.Normalize(mean=mean, std=std) if train: preproc = [transforms.RandomHorizontalFlip(), transforms.RandomCrop(32, 4)] ...
94e5a57a32786caa49746b754b1d961a6edf1731
3,617,669
def get_app_base_url(): """ Returns the QRadar app proxy prefix. """ return app_qpylib.get_app_base_url()
10fdac9e547ecae4bcdd99be8ef1b0338c264bb7
3,617,670
def create_plotgroup(template_plot_type='bitmap',**params): """ Create a new PlotGroup and add it to the plotgroups list. Convenience function to make it simpler to use the name of the PlotGroup as the key in the plotgroups list. template_plot_type: Whether the plots are bitmap images or curves ...
45cbb35054e44436e191b274ed0f4b88ae49c29a
3,617,671
import hashlib def create_file_map(directory_dict): """ Create a dictionary that maps the hash value of each unique file to a list of the full paths of each copy of that file, even if those files have different names. :param directory_dict: dictionary mapping directory -> list of files :retur...
f977a5a6737ba66965f630f3c230505a1fa442e9
3,617,672
def get_dc_token(region_name=constants.SYSTEM_CONTROLLER_REGION): """Get token for the dcmanager user. Note: Although region_name can be specified, the token used here is a "project-scoped" token (i.e., not specific to the subcloud/region name). A token obtained using one region_name can be re-used acr...
7dd77025b4e4ef40b616466cb233cb67b5b78a24
3,617,673
def calculate_multiplier(aggregate_add_on, value, RC): """ Calculates multiplier depending on Replacement Cost (RC). Returns ------- Multiplier. """ market_value = calculate_market_value(value) if RC > 0: multiplier = 1 return multiplier else: floor = 0.05 ...
710a228bfa3be2bd495aece19308dfff04175e5d
3,617,674
def gen_col_list(num_signals): """ Given the number of signals returns a list of columns for the data. E.g. 3 signals returns the list: ['Time','Signal1','Signal2','Signal3'] """ col_list = ['Time'] for i in range(1, num_signals + 1): col = 'Signal' + str(i) col_list.append(c...
35fe1457c9e256f90f7695e066dcc3202f212d98
3,617,675
def calculate_eigenspaces(kr_max, theta, phi, rad): """Calculate the eigenspaces for the corresponding eigenfrequencies of the sphere Parameters ---------- k_max : float The largest wave number to be included theta : array, float Azimuth angle phi : array, float Elev...
cb835533f65716336d3bc157c70d20a19743077c
3,617,676
def get_sequence(message, message_object_list, sequence_list, sequence=None, index=None): """Returns a sequence i.e. more than 2 messages""" if not sequence: sequence = [] index = 0 if message not in sequence and not any(message in s for s in sequence_list) is True: message[3] = True...
fcbc4b70839fbff9bdac4e30878a2e78ae9c2127
3,617,677
def fit_moffat(arr): """ Params ------ arr (2d np array of odd sizes) Return ------ model (astropy model object) """ # sanity check of input data type if isinstance(arr, ac.kernels.Kernel): arr = arr.array elif isinstance(arr, np.ndarray): pass else: raise Exception("[psfmatch] input needs to be a ...
fd630be0338f52735a457c6a1c6e0dbf4ed68c18
3,617,678
import random import calendar def date_generator( num_dates: int = 1, start_year: int = 1950, end_year: int = current_year, as_list: bool = False, ): """ Function to generate date(s). Specify the number of dates (num_dates, defaults to 1),\n start year (start_year, defaults to 1950),\n ...
888f1d10d29a2767a463ccc1e57f11b3a7a149b9
3,617,679
import requests def test_batch_create(requests_mock): """ Test batch creation """ metadata = Gen3Metadata("https://example.com") metadata_list = [ {"guid": "3c42c819-1dfe-4c3e-8d46-c3ec7eb99bf4", "data": {"foo": "bar"}}, {"guid": "dfa1a1dc-98f4-46be-ba8f-ae9b42b0ee50", "data": {"fo...
e4db6a3771dfcbd803b6f653223fecde9eca302e
3,617,680
def f_isASCII(*args): """f_isASCII(flags_t F, void ?) -> bool""" return _idaapi.f_isASCII(*args)
3fec966271398b648dc1dc5912a3a048e70523b7
3,617,681
def generate_ical_string(key: str) -> str: """generates iCalendar string from testdata and returns it""" c = Calendar() for row in _testdata["iCalendar"].get(key, []): c.events.add( Event( name=row["name"], begin=row["begin"], end=row["end"...
3b8bfb25b8d310eeb80c1c88c69d60cd79b054d3
3,617,682
def int_to_bytes(int_: int, architecture: int = None) -> Bytes: """Get Bytes object :param int_: number integer to convert to Bytes :type: int :param architecture: bytes length :type: int :return: bytes representation :type: Bytes """ bin_ = f'{bin(int_)[2:]}' bytes...
de16ba99ea770c34e6631532882d07f7f55da39f
3,617,684
import builtins def decode_bytes(b): """Tries to decode the bytes using XONSH_ENCODING if available, otherwise using sys.getdefaultencoding(). """ session = getattr(builtins, "__xonsh__", None) env = os_environ if session is None else getattr(session, "env", os_environ) enc = env.get("XONSH_EN...
b82fe9012d5a6f0ba5707bc6f0a04017f87a60cd
3,617,687
import numpy def cropobjects_merge_bbox(cropobjects): """Computes the bounding box of a CropObject that would result from merging the given list of CropObjects.""" # Find extremes. This will define the output cropobject. t, l, b, r = numpy.inf, numpy.inf, -1, -1 for c in cropobjects: t = m...
559e96dda48cb5e733c59a3168032037e0eb06e4
3,617,688
import psutil def starttime(pid): """starttime(pid) -> float Arguments: pid (int): PID of the process. Returns: The time (in seconds) the process started after system boot """ return psutil.Process(pid).create_time() - psutil.boot_time()
eda12b68605eb9602469f74884b812cdeb0abf26
3,617,689
def generate_nested_list(root,nodes): """ Generates a nested list representation of the tree with specified node as root. Useful for checking equality of trees or subtrees. To do: make the nested list form a property that is computed when needed. """ nl = [] if root.children is None: r...
fa75493c8ccc4b720ee404baa9eb3996ce78f3eb
3,617,690
def build_group_objects(env1, admin_api_key1, group_links): """ Builds a list of Group objects that will be used to more quickly check for users in groups """ Groups_List = [] # initialize a python list of objects if not (group_links is None): for i in np.arange(0, np.shape(group_links)[0])...
4438c3aae7e544091bbf463df0cf36a8381c6378
3,617,691
def queryset_filter_tag(queryset, **kwargs): """ template tag which allows queryset filtering. Usage: {% filter_tag books author=author as mybooks %} {% for book in mybooks %} {% endfor %} """ return queryset.filter(**kwargs)
5959285ec8b19945003a98f910028eb35d75299c
3,617,692
import torch def render(H, W, focal, cx, cy, chunk=1024*32, rays=None, c2w=None, ndc=True, near=0., far=1., use_viewdirs=False, c2w_staticcam=None, **kwargs): """Render rays Args: H: int. Height of image in pixels. W: int. Width of image in pixels. focal: flo...
1dba826206df1d951f10c3ab8aac7018cdd15d69
3,617,693
def abstract(func): """ An abstract decorator. Raises a NotImplementedError if called. :param func: The function. :return: The wrapper function. """ # noinspection PyUnusedLocal # pylint: disable=unused-argument def wrapper(*args, **kwargs): raise NotImplementedError('{} has...
3497ae41c4987499cddc610e518a8a9251cadb31
3,617,694
def is_greyscale_image(image: np.ndarray) -> bool: """ A function that checks if an image is a greyscale image (an image where pixels are a number - has 1 color channel) :param image: the image to be checked, a numpy array """ return len(image.shape) == 2
72df92a91b2720138f73aa8817a7ad7a8803685f
3,617,695
def __get_site_amp_ratio(pga: float, db_vs30: float, user_vs30: float, im: IM): """ Calculates a PGA_1100 estimate; uses it to calculate a site amplification ratio for the difference in vs30 between the user and the modelled vs30 Scaling is only defined for pSA and PGA otherwise no scaling is applied -...
31c0bc41beb92c6595019283a40f600be046c520
3,617,696
def cosineXform(a, b, c): """ Spherical trig transform to take alpha, beta, gamma to expressions for cos(alpha*). See ref below. [1] R. J. Neustadt, F. W. Cagle, Jr., and J. Waser, ``Vector algebra and the relations between direct and reciprocal lattice quantities''. Acta Cryst. (1968)...
537cf31ceb59189b71b1394598ca3b89ee5de40a
3,617,697
import pandas def load_escolas(): """Load and return the dadosabertos.poa.br escolas dataset. The escolas dataset is a public open dataset from Prefeitura de Porto Alegre, Rio Grande do Sul, Brazil. Examples -------- >>> from dyrapy.datasets import load_escolas >>> cadastro, matriculas = loa...
7f9f265564fb1ce18f4871bf124b3b14ed62b0ce
3,617,698
def svn_fs_node_created_path(*args): """svn_fs_node_created_path(svn_fs_root_t * root, char const * path, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_node_created_path(*args)
aecc149c53665815960a95966c20681e23cc9a93
3,617,699
def load_sce_and_metadata(file_path, local_env_yaml): """ For the given SCE audit file (file_path) under the specified environment (local_env_yaml), parse the file while expanding Jinja macros and read any metadata headers the file contains. Note that the last keyword of a specified type is the reco...
b416053721d90aca79f68ac53d4d1deec8e54b3d
3,617,702
def datetime_interpretation(raw): """Converts human-readable datetime into normal datetime instance. Args: raw (str or unicode): source string with datetime data. Returns: datetime: result datetime instance. None: if couldn't read value. """ if isinstance(raw, (unicode, str...
fb13511fa17ef5883a9f952aec24092397821d40
3,617,704
def model_3d_deep(n_classes: int, input_size: int, **kwargs) -> tf.keras.Sequential: """ Deep 3D convolutional model from: https://arxiv.org/pdf/1907.11935.pdf :param n_classes: Number of classes in the dataset :param input_size: Size of the input sample :param kwargs: Additional arguments. :re...
18dbf5500ec0db766778b4e58f93440d225b23dd
3,617,705
from typing import Counter def _pairing_consistency_check(files, errors): """checks the datastructure for consistency""" file_list = sorted([f for f in files if not files[f].get('symlink')]) pair_list = [] for f, info in files.items(): # skip links for secondary aliases if info.get('sy...
f49a1554dd920adfde65d10a95bfd7d574836a4d
3,617,706
def non_related_filter(questions_df, non_related_ids): """ Splits a questions dataframe between related and non-related discussions, based on an Ids list of non-related discussions. :param questions_df: > A pandas dataframe of stackoverflow questions containing posts Ids; :param non_...
b7e64287b2bdb6a8999bcd8e7efd8e2787b991dd
3,617,708
def _configure_features_for_binary( ctx, requested_features = [], unsupported_features = []): """Creates and returns the feature configuration for binary linking. This helper automatically handles common features for all Swift binary-creating targets, like code coverage. Args: ...
156e348b77d160b1d237808f90b5f5d98a8511d6
3,617,709
def update_assessment( db_session: Session, old_assessment: RestBewertungCreate, new_assessment: RestBewertungCreate ) -> RestBewertungReturn: """Update the comment and rating of a existing assessment Args: db_session (sqlalchemy.orm.Session): Session to the DB -> See `db: Session = Depends(get_db)...
2eeaeb8d672d0fdbbbc0a3149cdc2349dd8d9e99
3,617,710
def index(request): """index Args: request (request): api request """ return JsonResponse({"data": "theres nothing at this endpoint"})
06a36cc2665d72598063258c55cd78c8741f8596
3,617,711
import math def sin(x): """Return sin of x (x is in radians)""" return math.sin(x)
c5b091892e54df064b61a109812b3ea1206b1713
3,617,712
def get_resource_path(): """Return the path to general resources. Returns the path to general resources, terminated with separator. Resources are kept outside package folder in "resources". Based on function by Yaroslav Halchenko used in Neurosynth Python package. Returns ------- resource_...
2486d552c43f2fd4a1d191c62a44ea7732afd676
3,617,713
import test def launch(launcher, use_pycuerun=True): """ Launch the given L{OutlineLauncher}. :type launcher: L{OutlineLauncher} :param launcher: The OutlineLauncher to launch. :type use_pycuerun: bool :param use_pycuerun: Enable/Disable pycuerun. :rtype: opencue.Entity.Job :return: ...
ebeb09d3e2b02e42bb04ef8905d2cf3b8582c4fa
3,617,714
def _paramMinCount(callableObject): """ Given a callable object (function, method or callable instance), return pair (min,d) where min is minimum # of args required, and d is number of default arguments. The 'self' parameter, in the case of methods, is not counted. """ if type(callableObject...
d3ff64ce2c2ca4a25f225bc58ec0e30d352cb259
3,617,715
def acceleration(syn, obs, nt, dt, *args, **kwargs): """ Acceleration waveform for migration, second derivative of obs """ adj[1:-1] = (-obs[2:] + 2. * obs[1:-1] - obs[0:-2]) / (2. * dt) return adj
cb7e320cb4eaaaf7733681608428e1d16f755ca1
3,617,716
def format_pin(pnum, relatedpnum): """Formats a Parcel ID Number (PIN) from a BS&A PNUM.""" try: if relatedpnum is None or relatedpnum.startswith('70-15-17-6'): p = pnum else: p = relatedpnum p = p.split('-') del p[0] p = ''.join(p) except Inde...
8338fd5b329cf37d3fa59cd1b7d1f71e6694d706
3,617,718
from datetime import datetime def condense_log_events(log_stream, log_events): """Condense log events into single strings. expects list of dicts.""" condensed_events = [] for event in log_events: event_datetime = datetime.fromtimestamp(event['timestamp'] / 1000) message = "{} | {} | {}".fo...
94bfdc73d9fad7151162ca3e1bf114cc11950067
3,617,719
import datetime as dt def current_year(): """ Returns the current year. """ now = dt.datetime.now() return now.year
34fe2695dfb224d0db39af7dffc084058b93518a
3,617,722
import re import threading def register(): """ The register page endpoint --- get: parameters: None responses: 200: The register page html post: parameters: None responses: 301: redirects to login if re...
cad5d166463bf9c924fb9f8132104bf494b4a5c4
3,617,723
def get_router_port(endpoint): """ get the network device and port of where the endpoint is connected to. Args: endpoint (endpoint): endpoint A routerport is a dict with the following keys: router (string): name of the netork device port (string): port on the router....
30c331169a0c5e1a6b0bf91b8ad43c1db64dc532
3,617,724
import networkx def createGraph(input_edge_list): """ From list of edges create and return a graph. :param input_edge_list: list of edges :returns G: the graph """ # first thing, how are the nodes separated in an edge with open(input_edge_list, 'r') as f: l = f.readline() ...
5a92864aa78cc99218c45031c80a6b89a836f134
3,617,725
def dummy_callable(obj): """A callable that you probably shouldn't be using :)""" return []
2a0c71bd1a558d3df1c40c5a384fa98bf3cc15ad
3,617,726
from typing import List def get_accessory_files(model_id: str) -> List[DojoSchema.ModelAccessory]: """ Get the `accessory files` for a model. Each `accessory file` represents a single file that is created to be associated with the model. Here we store key metadata about the `accessory file` which...
c946af602e4433aab395e14c96e5354bbc41468b
3,617,727
def text_to_ascii_text(font, text, cols, lines): """Convert text to ASCII art text banner""" image = Image.new('RGB', (cols - 1, lines - 1), (255, 255, 255)) draw = ImageDraw.Draw(image) draw.text((0, 0), text, fill='black', font=font) width, height = image.size pixels = image.load() # conve...
6b63369a588192ed084610d4b65789d909ef57d4
3,617,728
from scipy import integrate def compute_auc(xpts, ypts): """ Calculates the AUC. :param xpts: Points on the X axis - the threshold values :param ypts: Points on the Y axis - the pck value for that threshold :return: The AUC value computed by integrating over pck values for all thresholds """ ...
6790f8183034351fc1d75c6baa10350e55864038
3,617,730
import math def cie76(c1, c2): """ Color comparision using CIE76 algorithm. Returns a float value where 0 is a perfect match and 100 is opposing colors. Note that the range can be larger than 100. http://zschuessler.github.io/DeltaE/learn/ LAB Delta E - version CIE76 https://en.wikipedia....
9470b66231252decd8be7f07af2591ddf1278edc
3,617,731
from typing import Any from typing import Tuple def fill_based_other_col(data: DataFrame, col_to_fill: str, ref_col: str, method: str = 'mode', replace: Any = np.nan) -> Tuple[Series, Any]: """Function to fill nulls on a DataFrame column based on other column. To fill based on multipl...
654c948896c6ad50145d7177fa0f7ce380f9edcc
3,617,732
def sparse_reset_shape(sp_input, new_shape=None): """Resets the shape of a `SparseTensor` with indices and values unchanged. If `new_shape` is None, returns a copy of `sp_input` with its shape reset to the tight bounding box of `sp_input`. This will be a shape consisting of all zeros if sp_input has no values....
77c2f6266fe50a1be77e859f9f876a56c60809a6
3,617,733
def project_new_folder(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /project-xxxx/newFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder """ return DXHTTPRequest('/%s/newF...
3236d824fe5ea8e9698647c16107e3ea1295f4bc
3,617,734
def PolyConvex(poligono): """ Funcion para calcular el poligono con una serie de cordenadas dada """ points = np.array(poligono) hull = ConvexHull(points) ps = set() for x, y in hull.simplices: ps.add(x) ps.add(y) ps = np.array(list(ps)) p = pd.DataFrame(points) ...
5ebf1d031889f3da495f2c5b96fb5c4cae98d271
3,617,736
def recycling_to_no3(vs, plankton, no3): """Recycling to nitrate needs no scaling""" return {no3: recycling(vs, plankton, no3, 1)[no3]}
7dde877ce204dfb97ddd249500bcd7a276293d31
3,617,737
def sharpe_ratio(returns): """Computes Sharpe Ratio from simple returns. Parameters ---------- returns : np.ndarray | pd.Series | pd.DataFrame Returns of the strategy as a percentage, noncumulative. Returns ------- sharpe_ratio : float | np.ndarray | pd.Series Sharpe ratio....
6039738f09c4aa1b016cbf17793ea5a3b6395bea
3,617,738
import copy import numpy def plot_2d(x_data, x_name='x_data', y_data=None, y_name='y_data', yerr=None, groups=None, identifiers=None, graph_type='scatter', line_width_=None, fit=None): """ Min part for plottings a 2d graph. If specified, args groups and identifiers specify the or...
a64910ee4bc9a403df759f31fcee0918362afe04
3,617,739
import typing import collections def serialize_some_embed( instance: some.graph.SomeEmbed, ordered: bool = False ) -> typing.MutableMapping[str, typing.Any]: """ serializes an instance of SomeEmbed to a JSONable representation. :param instance: the instance of SomeEmbed to be serialized ...
5b4f489ffde72b986c84522929e7985d6886080a
3,617,740
def get_current_user(*args): """Return the current user configured in middleware.""" if hasattr(LOGSFORHUMAN_THREAD, 'request'): return getattr(LOGSFORHUMAN_THREAD.request, 'user', None)
d81eed3783d48a29913d3d3daa961c0383e143ba
3,617,741
def get_pair_single(name): """ Given a fastq file name, determines if it's paired-end or single-end and returns the type + name. :param name: The name to check. :return: The combined file type ('single', 'forward', or 'reverse') and the name minus the direction-identifying part of the file name. ...
af2e8dbb459e2e4daa9836638dd885af863963d8
3,617,742
from pathlib import Path def parse_lst(lst_path): """Extract audio names of nnenglish.""" audio_names = [] with open(lst_path) as fd: for line in fd: audio_path, lang = tuple(line.strip().split()) if lang != "nnenglish": continue audio_name = Pa...
82ed0e7a0c13269416e4530157f2a67a68712676
3,617,743
import random def add_angle(r): """ Add angle for each r value to make up a coordinate of a polar coordinate. """ coords = [] for ri in r: theta = random.random() * 360 coords.append((ri, theta)) if len(coords) == 1: return coords[0] else: return coords
0e91e9c7999627885218dde42bc2849e89071eff
3,617,744
import re def Article_Add(request): """ 新增文章 :param request: :return: """ seo_list = get_object_or_404(Seo, name='文章') if request.method == 'GET': category = Category_Article.objects.all() return render(request,'pc/articlesadd.html',{"category":category,'seo_list':seo_list}...
367a20af9d175d8367ddeb2b83b727f5ca588843
3,617,745
def compute_cv_fold_stats(data_df, cv_splits): """ Computes CV fold size and class proportions for a given CV splitting. :param data_df: a DataFrame :param cv_splits: a given cv splitting as e.g. returned by cv_independent_associations() :return: a DataFrame that lists count and fraction of pos...
a39056a821c7527240c3151d11e03517e663c992
3,617,746
def lag_port_stats( data # type: "XDR Data" ): """LAG Port Statistics Counter - Type: Counter, Enterprise: 0, Format: 7""" sample_data = {} # Cache sample_data["dot3adAggPortActorSystemID"] = data.unpack_string() sample_data["dot3adAggPortPartnerOperSystemID"] = data.unpack_string() sample_data["dot3adAggPortAtt...
9c367a1d5aedb123854a77636f3d0cb6f50a839e
3,617,747
def fit(comb): """returns true if combination can be chosen and false otherwise""" if len(comb)>5|len(comb)<1: return False desk=list(filter(lambda x: x>4,comb)) if len(desk)<1: return True desk.sort() handOut = 5 - (len(comb)- len(desk)) deskLast=desk[-1] if handOut>=des...
3512dfb91bf4035c3e817c4bd110b446ef183c2d
3,617,748
import asyncio import inspect async def wait_for_reply(predicate: TYPE_CALLABLE_PREDICATE = None, timeout=30, default=None, raise_on_timeout=False) -> ReplyResult: """ waits for a message matching `predicate` to be received, when its received, it returns a ReplyResult instance with the response. if no me...
da14dd4bbddf7ca2c7cace92cb32eca886c1b2fb
3,617,749
import requests def query(session, qid, args={}): """Query AP system page by qid and args :param session: requests session object, the session must login first. :type session: class requests.sessions.Session :param qid: query id of ap system page :type qid: str :param args: arguments of query...
e5080f2e3d625eff94f442dd1b742f9f926011dd
3,617,750
def get_airflow_operation_client(): """ Get a client to operate airflow dags and tasks. """ global _default_airflow_operation_client ensure_project_registered() if _default_airflow_operation_client: return _default_airflow_operation_client else: return AirflowOperation(_default_proje...
0778e20b9260ce2ba1019bafc5951c16ef4fef6c
3,617,751
def FILTER(*args) -> Function: """ Returns a filtered version of the source range, returning only rows or columns which meet the specified conditions. Learn more: https//support.google.com/docs/answer/3093197 """ return Function("FILTER", args)
97139c2293430d4efcc076bb3e3c4cfcd85d344b
3,617,752
def get_args(): """ Command line arguments """ parser = ArgumentParser(description="Inspect sets of rts contained in hdfs store file(s) as pandas DataFrames.") parser.add_argument("files", help="XML file with RTS", nargs="+", type=str) parser.add_argument("--key", help="DataFrame key in store", default=...
bcbc1a3381a18975d68575742071c5d9151cd70a
3,617,753