content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def dm_only() -> AC: """A :func:`.check` that indicates this command must only be used in a DM context. Only private messages are allowed when using the command. This check raises a special exception, :exc:`.ApplicationPrivateMessageOnly` that is inherited from :exc:`.ApplicationCheckFailure`. ...
6d86ff53b4c73d5a753aef41f8bd9c14cc02abc6
59,423
from typing import Sequence from typing import Union from typing import AbstractSet from typing import Optional import warnings def get_time_series(cube: xr.Dataset, geometry: GeometryLike = None, var_names: Sequence[str] = None, start_date: Date = None, ...
b5418da1ae8198d200e1181042557e3abb9a8904
59,424
def communitiesandcrime(display=False): """ Predict total number of non-violent crimes per 100K popuation. This dataset is from the classic UCI Machine Learning repository: https://archive.ics.uci.edu/ml/datasets/Communities+and+Crime+Unnormalized """ raw_data = pd.read_csv( cache(github_d...
144831dd5112417c18ce6f0cf587441680e340f5
59,425
def insert_discrete_time_mutations(ts, num_times=4, num_sites=10): """ Inserts mutations in the tree sequence at regularly-spaced num_sites positions, at only a discrete set of times (the same for all trees): at num_times times evenly spaced between 0 and the maximum time. """ tables = ts.tables...
c011525a7f810aec3eaacda3c016d82df5c3afbb
59,426
def combine_shape(shape, comm=None): """ Return the shape of the global array resulting from stacking local arrays along the first dimension. """ shape = tointtuple(shape) comm = comm or MPI.COMM_WORLD with timer_mpi: shapes = comm.allgather(shape) if any(len(s) != len(shapes[0]...
2e45b29de7a48e0682a818b6cd2c3d8241993245
59,427
def make_zoomlock_radio(): """Generates radio buttons for selecting whether or not to save map zoom/position settings between filtering steps. @return dash.dcc RadioItems object """ radio = dcc.RadioItems( id='lock-zoom', options=[{'label': i, 'value': i} for i in ['...
0dcf871e00a37f48c27cc8ce55af25f9b4e3192b
59,428
def nested_select(d, v, default_selected=True): """ Nestedly select part of the object d with indicator v. If d is a dictionary, it will continue to select the child values. The function will return the selected parts as well as the dropped parts. :param d: The dictionary to be selected :param v: Th...
84aa16adfb324fef8452966087cbf446d57893d2
59,429
import time def timestamp_2_datetime_str(timestamp): """将时间戳转为日期时间字符串""" datetime_tuple = time.localtime(timestamp) return time.strftime("%Y-%m-%d %H:%:%S", datetime_tuple)
1b8b5e4338d1fa49729fa253b029c0521a7f5f55
59,430
def gen_point_cloud(n, scale=1.0): """ sample points on the unit square """ return np.random.uniform(low=-scale, high=scale, size=(n,2))
75248dc91efe73922c92d1b79077afa691a3e867
59,431
def refine_group_exit_event_msg(ctx: EventMsg) -> _GroupExitEventMsg: """群成员退出群聊事件""" if not isinstance(ctx, EventMsg): raise InvalidContextError("Expected `EventMsg`, but got `%s`" % ctx.__class__) if ctx.EventName == EventNames.ON_EVENT_GROUP_EXIT: return _GroupExitEventMsg(ctx) return...
466c0f504940ae90fd19b5ab1fb5174610cf918b
59,432
def xlconvertJSON(workBook, jsonObject={}, sheetName="all", testing=False): """ sheetName used to specify a single sheet to convert otherwise default is all sheets workBook is excel workbook object returned by xlrd.open""" # Function Variables # none if sheetName == "all": sheetL...
4e6b2a4c91654b1492c0a97eddf8f9077be3e66f
59,434
from typing import List def video_segment_is_repeat( video_segment: VideoSegment, video_segments_used: List[VideoSegment] ) -> bool: """ Returns ------- True if a video segment is a repeat of a video segment already used, False otherwise """ for used_segment in video_segments_used: ...
71a603fe07a20a1842cadad3be30cac7c9ced9a5
59,436
def mle(x): """ Fit distribution parameters to sample by maximum likelihood estimation Parameters ---------- x : array_like sample Notes ----- MLE equation set is given in 'Statistical Distributions' by Forbes et.al. (2010) and referred at [4] """ def mle_eq(p, z):...
2e6ad0dc5751a4cd3e32a7ff7fc1570e5cdc7f94
59,437
def is_trans(reaction): """Check if a reaction is a transporter.""" return len(reaction.metabolites) == 1
a0b9be30b4a88156e7a89cf48b8ecb76345e4cab
59,438
def VSH_far(n, m, mode=vsh_mode.outgoing): """electric and magnetic vector spherical harmonic function in the far field n: int order m: int degree mode: vsh_mode type of VSH (outgoing, incident) returns (N(r,θ,ϕ,k) -> [2,...], M(r,θ,ϕ,k) -> [2,...])...
c99c679c7c011550034a123c15560847e42ae7d3
59,439
def compile_ir(llvm_ir): """ Compile the LLVM IR string with the given engine. The compiled module object is returned. """ # Create a LLVM module object from the IR mod = llvm.parse_assembly(llvm_ir) mod.verify() # Now add the module and make sure it is ready for execution engine.add...
5140091da854accb330a3c009ce4fc8220670485
59,440
from datetime import datetime def average_plot_ondatetime(FEDs, groups, dependent, average_bins, average_error, shade_dark, lights_on, lights_off,**kwargs): """ FED3 Viz: Create an average line plot for Grouped FED3 Files; averaging is only done for periods where all devices we...
eace2f7181268e9d1a32dc4573ac0f8079f73bd2
59,441
import json def verify_mail(data): """ data:{ 'email': 'test@gmail.com', 'key':'KB7Y2OBU0iuhgulTbNCf8xmqxsGOAUC5' } enables user through key """ try: response = frappe._dict({}) args = json.loads(data) if frappe.db.exists("User", args.get("email")) and args.get("key"): user = frappe.db.get_val...
40a454f7d0b591cc180efa047ca7192edcb0cecc
59,442
def Code(*content, **attrs): """ Wrapper for code tag >>> Code().render() '<code></code>' """ return KWElement('code', *content, **attrs)
e190070fe9c080b59b68bd9278e4bf07e35164b9
59,443
def format_tile(tile, tile_format, format_str='{x} {y} {z}'): """Convert tile to necessary format. Parameters ---------- tile: pygeotile.tile.Tile Tile object to be formatted. tile_format: str Desired tile format. `google`, `tms`, or `quad_tree` format_str: str String to...
e7ce2653f49f0c535bb3ea0a0c4bec3b48a74331
59,444
def percent(a, b): """ Given a and b, this function returns a% of b """ return (a/100)*b
d8adae353bb1b7aba6eb0149af065182bf752449
59,445
def create_plan( plan: plan_schemas.PlanDTO, db: orm.Session = Depends(get_db), user: users_schemas.User = Depends(is_authenticated)): """Creates a new plan Args: plan (plan_schemas.PlanDTO): body of the request db (orm.Session, optional): [description]. Defaults to Depends(get_db...
59d650e5b131c3a00f98fb13b09ccacb8b9b91eb
59,446
import math def filter_none(mongo_dict): """Function to filter out Nones and NaN from a dict.""" for key in list(mongo_dict.keys()): val = mongo_dict[key] try: if val is None or math.isnan(val): mongo_dict.pop(key) except Exception: continue ...
6853a7153f98466dc00d262bfaf4a63db1b0cd5c
59,447
def get_audio_features(signal, sr, frame_length, frame_skip, feature_set='eGeMAPSv02', feature_level='LLDs'): """Extract ComParE16 features using the OpenSMILE toolkit Parameters ---------- signal : ndarray Array of signal data from audio file sr : int Sampling rate of audio frame_length : float ...
3a49107538166cd50a23689d42c45728c45e46a8
59,448
def axiom_generator_percept_sentence(t, tvec): """ Asserts that each percept proposition is True or False at time t. t := time tvec := a boolean (True/False) vector with entries corresponding to percept propositions, in this order: (<stench>,<breeze>,<glitter>,<bump>,<scream...
a1be06bb64043bd1a8b1250b7c8d3884ae5a0a2a
59,449
import configparser def read_configfile(): """Read the config file :returns: The ConfigParser object """ c = configparser.ConfigParser() c.read("config.conf") return c
cdc8b63cca40af1cc516161746ffd016aeb4d65d
59,451
from typing import List from typing import Tuple def parse_intensity_bounds( image: Image, out_channels: List[int], out_zslices: List[int], out_timepoints: List[int], min_intensities: Intensities, max_intensities: Intensities, allow_none: bool = False ) -> Tuple[List[int], List[int]]: """ Parse intens...
80dfa51a9dee9b366e9edb0f778bcfec2a156212
59,452
def subresultants(f, g, *gens, **args): """Computes subresultant PRS sequence of `f` and `g`. """ gens = _analyze_gens(gens) try: F, G = _polify_basic(f, g, *gens, **args) except CoercionFailed, (f, g): raise GeneratorsNeeded("can't compute subresultants of %s and %s without generators"...
1fdfdb59b15be6d8b2ae5a1af8f46a75e0ac2ae5
59,453
from ray.experimental.serve.handle import RayServeHandle def get_handle(endpoint_name): """Retrieve RayServeHandle for service endpoint to invoke it from Python. Args: endpoint_name (str): A registered service endpoint. Returns: RayServeHandle """ assert endpoint_name in global_s...
00542dac4e7900de42fd2e07bc9a9083b81ac9a5
59,454
def _normal_surface_single(obj, uv, normalize): """ Evaluates the surface normal vector at the given (u, v) parameter pair. The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself. :param obj: input surface :type obj: Abstract.Surface :param uv: (u...
3402616985b04fc2161a21009901c56bc8de6d8d
59,456
import csv def read_us_counties_csv(file_name): """ """ # read the data with open(file_name) as csv_file: # convert each row to a list of strings csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 counties_with_deaths = [] for row in csv_reader...
2b203f200d7efbe26cbcaff17c150afde388f7e3
59,457
def measure(word1, word2, ALPHA=0.7): """ combine phonetic association value and semantic association value @word1 -- the first word @word2 -- the second word @ALPHA -- contribution parameter of phonetic association value @return -- a combined metric value to determine how associated these two ...
c97a452c6fdf343b1eedc53bffe5b367818e7bcc
59,458
def ARGmetric_params_from_row(row): """ Create some ARGmetric params (see ARGmetrics.py) from a row We hack the same polytomy seed as inference seed This stupidly has to be defined at the top level, since it is part of the function passed in to a multiprocessing Pool, and hence needs to be 'pic...
eeb43b5fdf0b1fd8705d95ab7dd6a2d7f6422801
59,459
def encrypt_password(password, salt): """ Encrypts the password with the given salt using SHA-256. The salt must be cryptographically random bytes. :param password: the password that was provided by the user to try and authenticate. This is the clear text version that we ...
89c6f7e24c6f76e599095937f7f347f28e434fb7
59,460
def calc_ratio_significance(odd, even): """Calculate ratio significance between odd and even. Parameters ---------- odd, even : float Returns ------- ratio : float Ratio of odd to even. sigma : float Significance that the ratio is not 1. """ error_ratio = ((od...
bf34ed6b4e9c8c202ec152e4df802b92c498a2ae
59,461
def rgba_to_rgb(image: np.ndarray) -> np.ndarray: """Convert an image from RGBA to RGB. Args: image (np.ndarray[B, 4, H, W]): RGBA Image to be converted to RGB. Returns: rgb (np.ndarray[B, 3, H, W]): RGB version of the image. """ return cv2.cvtColor(image, c...
ac5f62b61bc5316de98ed5bb9dc2b155abca0af4
59,462
def upload(): """Process a file upload""" if request.files["image"].filename != '': image = request.files["image"] # Write image to GCS bucket = storage_client.bucket(BUCKET_NAME) blob = bucket.blob(image.filename) blob.upload_from_file(image) # Create entry in Fi...
3e20e0fc9f97061f7bd0f1f0b98002015881891d
59,463
def UserDecode(user_str): """Returns User with string encoding of: <user_id>|<email>. Note that the encoding must match that of UserEncode() """ try: user_id, email = user_str.split('|', 1) except ValueError: # only 1 part given return users.User(email=user_str) return users.User(email=email, _use...
e8f4e049a3cd87423f630f408ecba83428300db5
59,464
def interval_evalf(interval): """Proper implementation of evalf() on Interval. Examples ======== >>> from sympy.core import Interval, Symbol >>> from sympy.solvers.inequalities import interval_evalf >>> interval_evalf(Interval(1, 3)) [1.0, 3.0] >>> x = Symbol('x', real=True) >>> ...
bcbdc5b044b6d1286cccde76eba3eba6fbef3e3b
59,465
def _migrate_database(main_app): """ :param main_app: :return: """ migrate = Migrate(main_app, db) manager = Manager(main_app) manager.add_command('db', MigrateCommand) migrate.init_app(main_app, db) return main_app
d9fb79d070d92e1b989c77b233b43b99fa94e575
59,466
import immcli def usage(msg, parser, version): """ Emit usage from docstring at top of file. msg - message string parser - command line parser object returned by argparse.ArgumentParser() """ lines = list() lines.append(msg) lines.append('') lines.append("Version: %s" % ve...
72e2a08e6587dfe8ea280edba5fadd33e9257766
59,467
def parse3ds(file): """ returns a geometry """ logger.info('parsing %s' % file) infile = File3Ds.open(file) # only one object OBJ = infile.main.children.editor.children.object if type(OBJ) is list: # there are several models, return a list models = [] for obj in...
c8c412f85b51ba75cc9446f5786d22f7f527c091
59,468
def create_sparse_W_prior(shape, cutoff, slope): """Constructs sparsity parameters for W (alphaW) to learn pattern length Follows equation (6) in the ISMIR paper referenced in this module's docstring. """ # W.shape is (ndim, nseg, nwin) prior = np.zeros(shape[-1]) prior[cutoff:] = prior[0] + slope * np.arange(...
13648670905826fbda5364599eb8f4b034dfadb5
59,469
def argument(*name_or_flags, **kwargs): """Helper function to satisfy argparse.ArgumentParser.add_argument()'s input argument syntax""" return (list(name_or_flags), kwargs)
24748b59202964d1bca05c5c24dac144e67d964e
59,470
import scipy def generate_signals(n_features=17, n_confounds=5, length=41, same_variance=True, order="C"): """Generate test signals. All returned signals have no trends at all (to machine precision). Parameters ---------- n_features, n_confounds : int, optional respe...
658e406539682dc35aeb524113f45b2c6c794478
59,471
def kde_gauss(events_x, events_y, xout=None, yout=None): """ Gaussian Kernel Density Estimation Parameters ---------- events_x, events_y: 1D ndarray The input points for kernel density estimation. Input is flattened automatically. xout, yout: ndarray The coordinates at which ...
147b8b4f857342d1db4f5ecb2f292255141b62c9
59,472
import io def is_service_running(service_name): """ Checks if the named Service is running. :param service_name: :return: """ resultbuf = io.StringIO() with settings(warn_only=True, stdout=resultbuf): result = sudo('jps') resultstring = resultbuf.getvalue() resultbu...
4de95200a6e8f3b1b6382156d5cfb50b23692d88
59,473
def _get_3rd_point(a, b): """To calculate the affine matrix, three pairs of points are required. This function is used to get the 3rd point, given 2D points a & b. The 3rd point is defined by rotating vector `a - b` by 90 degrees anticlockwise, using b as the rotation center. Args: a (np.n...
1619429fe77a490013d6a7a3d7a49f722f03831b
59,474
import torch def compute_rpn_class_loss(rpn_match, rpn_class_logits): """RPN anchor classifier loss. rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive, -1=negative, 0=neutral anchor. rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for FG/BG. """ # Squeeze la...
87246f4201fd253d22fee54ae20860d238f6f83f
59,475
def xception_internal(inputs, hparams): """Xception body.""" with tf.variable_scope("xception"): cur = inputs if cur.get_shape().as_list()[1] > 200: # Large image, Xception entry flow cur = xception_entry(cur, hparams.hidden_size) else: # Small image, conv cur = common_layers.co...
519bf118f76acfbab60222e64cee9236457e79d1
59,478
import re def fetch_geneid(fn): """ fetch gene id from GTF records gene_id "FBgn0267431"; gene_name "Myo81F"; gene_source "FlyBase"; gene_biotype "protein_coding"; """ assert isinstance(fn, str) ps = fn.split(';') dn = {} for i in fn.split(';'): if len(i) < 8: # shortest field ...
c3ddb9c5c820799800131c6e11dc2ef91d4556c1
59,479
def model_users(user1, user2, text): """Input the two users and the tweet you are predicting. Outputs good the goods.\n ```json { "winner": <prediction results>, "user1": { "name": <user 1 display name>, "tweetAmount": <user 1 tweet amount> }, "use...
06d1175c8277f53c9f7a6326a12845bf932cbf67
59,480
def merge(G, nodes_to_merge): """ This method merges the list of nodes_to_merge in a 'Caterpillar' fashion, having the node of largest size closest to the root. The method sorts the nodes in decreasing order of their sizes and constructs the tree recursively :param G: A networkx graph :param nodes_...
0ed6dda1ec6618b5269c32bf1313131540b5edf6
59,481
def get_account_list_from_organization(config): """ use config file parameters to query the account list from organization """ # Getting root session if config.get('ProfileName'): root_session = boto3.Session(profile_name=config.get('ProfileName')) else: root_session = boto3.Session(...
72bb9d05c438360954cf8d79a8e25e85a7587c24
59,482
def password_set(username=None, password=None): """ Stores a password in a keychain for a particular environment and configuration parameter pair. """ try: keyring.set_password('superironic', username, password) return True except: return False
956d70bb133b99171a483e1e7e33140773f28b23
59,483
def fieldsMatch(f0, f1): """ Checks whether any entry in one list appears in a second list. """ for f in f0: if f in f1: return True return False
172772fca613fe97e32bb6860c3bd217b643fe2d
59,484
def _are_git_files_changed() -> bool: """ Check changes in the local repo. If any file in the local repo changed, returns False. """ result = True changed_files = hgit.get_modified_files() if changed_files: _LOG.warning("Modified files: %s.", changed_files) result = False ...
d500c540b4bed08569e430a415fe8b1bdddc4dea
59,485
def list_to_str(lst): """convert list/tuple to string split by space""" result = " ".join(str(i) for i in lst) return result
1e6c59f834b98b1d49ca1c0919d2d976fd1de1de
59,486
def _real_entropy(indi, gs): """ Calculates actual entropy for series of symbols :param indi: unique identifier :param gs: series of symbols :return: an unique identifier and entropy value """ return indi, np.power(np.mean(matchfinder(gs)), -1) * np.log2(len(gs))
02884de548da4a2253a6042ac999ceba1e27b8d0
59,487
def match(pattern, term): """Try to match a pattern. Args: pattern : a term with optional free nominal variables term : a term Returns: None if no match was found; otherwise a dict from NVARs to values. """ assert isinstance(pattern, Term), pattern assert isinstance(term, Te...
aa2e954c23eff7e56a3f366b243054af74a270c7
59,488
def hillshade(az, ze, slope, aspect): """Computes hillshade""" azimuth = radians(ee.Image.constant(az)) zenith = radians(ee.Image.constant(90).subtract(ee.Image.constant(ze))) return azimuth \ .subtract(aspect).cos().multiply(slope.sin()).multiply(zenith.sin()) \ .add(zenith.cos().multi...
800b22b357d09a738e7e6b44ff2f900d63b3cbb1
59,489
def element_damage(raw_element, sharpness, monster_ehitbox): """ Calculate elemental damage to a monster part with the given elemental attack, the given sharpness, and the given monster elemental weakness. Note that this is independent of the motion value of the attack. """ return floor(element_...
22699ed3eb73a02277babb06a9b36be4cad26196
59,490
def extract_bias_diagonal(module, S, sum_batch=True): """Extract diagonal of ``(Jᵀ S) (Jᵀ S)ᵀ`` where ``J`` is the bias Jacobian. Args: module (torch.nn.Conv1d or torch.nn.Conv2d or torch.nn.Conv3d): Convolution layer for which the diagonal is extracted w.r.t. the bias. S (torch.Ten...
b2f8aaefa22d1ae915c59f80f98341059a4d1ad3
59,491
def _memmaps_to_file_paths(obj): """Convert memmap objects to corresponding file paths. Acts recursively on arbitrary 'pytrees' of nested dict/tuple/lists with memmap leaves. Arg: obj: NumPy memmap object or pytree of memmap objects to convert. Returns: File path string or pytree ...
1b79a95075a6f0df2f35519c6a2f3839c03c265f
59,493
from sklearn.tree import DecisionTreeClassifier import time def run_decision_tree(X_train, X_test, y_train, y_test, complexities): """ Run a decision tree classification over the dataset The complexity here is ruled by the number of samples considered for every split """ dtc_list, dtc_pred, dtc_a...
bae1f64bbf531ab55bd02041e718cf40a1ba37e9
59,494
def squarespace(start, end, N, center=0): """ Generate a grid from start to end with N points that is uniform after taken square root. :param float start: the start of the mesh, must be non-negative :param float end: the end of the mesh, must be non-negative :param int N: the total number of mesh p...
2f2144e39b3fe8e14673f24744a63e8c0a1fb6fd
59,495
def load(source_file): """ Load a GeoJSON `dict` object from a ``source_file`` containing GeoPackage (as a byte string). :param source_file: Open and readable file-like object. :return: A GeoJSON `dict` representing the geometry read from the file. """ return loads(source_f...
87f8967028dc6290c9101e9f60bb5cb10663834e
59,497
def is_template_update_possible(client): """Check if the project can be updated to a newer version of the project template.""" return _update_template(client, check_only=True)
6f8ecb0bf6ca8a3d03a71a48435efba1f72ce4c6
59,498
from operator import sub def ejectDrive(drivePath): """Eject drive""" args = ['eject', drivePath] try: p = sub.Popen(args, stdout=sub.PIPE, stderr=sub.PIPE, shell=False) output, errors = p.communicate() exitStatus = p.returncode except Exception: # I don't even want...
60f607428202f0ad1e489c8b629acbe3559df619
59,499
import time def read_device(net_connect, sleep=1): """Sleep and read channel.""" time.sleep(sleep) output = net_connect.read_channel() print(output) return output
b0c4c300a088886558203649f57c10cc34b88e21
59,500
import PIL def Solarize(img, v): """ Applies PIL.ImageOps.solarize to the image """ assert 0 <= v <= 256, f"{v} out of range [0, 256]" return PIL.ImageOps.solarize(img, v)
b43bacce81b8fee0dd60603e610d7c17280f552e
59,502
def is_numeric_array(x): """ Returns whether an object is a ground numeric array. """ return False
8d119f10f08f08552c9dfb59fa13dd0bf644f47c
59,503
def cosine(vector1, vector2): """ related documents j and q are in the concept space by comparing the vectors : cosine = ( V1 * V2 ) / ||V1|| x ||V2|| """ return float(np.dot(vector1,vector2) / (np.linalg.norm(vector1) * np.linalg.norm(vector2)))
dd4daeec53440625532c50608a2914481bc8b0d1
59,504
def parse_coach_ec_df(infile): """Parse the EC.dat output file of COACH and return a dataframe of results EC.dat contains the predicted EC number and active residues. The columns are: PDB_ID, TM-score, RMSD, Sequence identity, Coverage, Confidence score, EC number, and Active site residues Args: ...
2abad4b8b2ab8013e16e6cd6fac6eda3f1338d80
59,505
from pathlib import Path from typing import Optional from typing import Tuple def get_grouping( inpDir: Path, pattern: Optional[str], groupBy: Optional[str], chunkSize: Optional[int] = None, ) -> Tuple[str, int]: """This function produces the best combination of variables for a given chunksize ...
1b818e331af105e4999677d9a4dca7ddf7896f7d
59,506
import requests def line_notify(func): """ プログラムの終了をLINEに通知 Parameter ---------- func : function 関数 Return ------- wrapper : function 関数 """ @wraps(func) def wrapper(*args, **kwargs): """ デコレーターの中身 Parameters ---------- ...
6218bbce72196a1fd35b1d12b242cdce65d58037
59,507
def config_item_context(CONFIG_SCHEMA): """Create a configuration context. Args: CONFIG_SCHEMA: This is a function which can take a minimum of zero arguments and returns an instance of BaseConfig. This BaseConfig defines the schema for all configuration objects manipulated...
28eaff4bd7bab3f88fd9558a35906127ce686d73
59,508
from gzip import GzipFile from typing import Any import json def gzip_load_var(gzip_file:str) -> Any: """ Load variable from .json.gz file (arbitrary extension!) Parameters ---------- gzip_file : str Filename containing the gzipped JSON variable Returns ------- var : Any ...
b9f6fbad33b40bb18a1418f3134b0889d5344183
59,509
def evaluate_classification(dataset, classification_algorithm, n_folds, *args): """ Evaluates a provided classification algorithm on a given dataset using cross-validation with n folds """ # creates cross-validation folds folds = cross_validation_split(dataset, n_folds) fold_accuracies = list()...
255d4c30792a86d7662ca3774300b8456a2a9187
59,511
from pathlib import Path def project_gitignore(path: Path): """Parse all project gitignores (including in folders)""" ignores = [] for item in path.iterdir(): if item.name == ".gitignore": ignores += gitignore(item, for_path=True) if item.is_dir(): ignores += projec...
e58b42f6b64a4fa0a701f964dc724856cf82db97
59,512
def calc_average_sfs(freqs, lineage_sizes, lineage_uids, bins): """ Calculate mean SFS over an ensemble by taking mean value at each bin """ S = np.empty((len(lineage_uids), len(bins)-1)) for i, lineage_uid in enumerate(lineage_uids): myFreqs = freqs[lineage_uid].values() myLeaves = lineage_...
c72d6ad183532fef05040ccf431b58612bbddccd
59,513
def item_validator(name, func): """Class factory for item validators""" return type(name, (ItemBaseValidator,), { '__call__': lambda self, x: func(x), 'setup': lambda self: None, 'teardown': lambda self: True })
de5b9649be6394d3cbfdfcf9f021bc96eb589f33
59,514
import numpy def mult_arrays( target_raster_path, gdal_type, target_nodata, raster_path_list): """Multiply arrays and be careful of nodata values.""" nodata_array = numpy.array([ pygeoprocessing.get_raster_info(path)['nodata'][0] for path in raster_path_list]) def _mult_arrays(*ar...
186fc9542ab71df8121068771f9eb0a5730bd934
59,515
def generate_infrared_noise(duration: float, f_sample: float) -> np.ndarray: """ generates a real valued time domain signal of 'infrared' noise. Signal is aprox. scaled to ~[-1;1]. :param duration: duration the noise signal should have in seconds :param f_sample: sample frequency, determines the frequen...
88456ee9258e5b1b25252f6787235c7793b46e89
59,516
def generateMoons(n): """ 生成月牙型数据 """ data, _ = make_moons(n_samples=n, noise=0.08) return data
5630d518731b3f66e3cb6f8aff9df3d33bd7ea03
59,517
from lmfit import Parameters from astropy.coordinates import SkyCoord from astropy import units as u def pars_to_params(pars, params=None): """ Converts a dictionary of par file parameters from read_par() to an lmfit Parameters() class to use in models By default, parameters are not varied """ ...
f7d32441462443aadce2e3ed2620c1a512dfdd51
59,519
import traceback def local_bestrefs(parameters, reftypes, context, ignore_cache=False): """Perform bestref computations locally, contacting the network only to obtain references or mappings which are not already cached locally. In the case of the default "auto" mode, assuming it has an up-to-date client...
07dc3195207c92c9d973b3bcb9390b84195cd1de
59,520
def get_azure_ctx(): """ Construct context object to allow tiledb to access Azure container. """ config = tiledb.Config() config["vfs.azure.storage_account_name"] = azconfig["account_name"] config["vfs.azure.storage_account_key"] = azconfig["account_key"] config["vfs.azure.blob_endpoint"] = ...
44ee1d286680d7d7736525e5d6ce3aab062c3d6b
59,521
def five_point_derivative(f,x,h): """#5-point function to calaculate 1st derivative""" h = float(h) return (1/(12*h))*(f(x-2*h)-f(x+2*h)- 8*f(x-h)+8*f(x+h))
186eb1ad0a01d96a85fb0d52bf0def8d3a0d00c0
59,522
def play(data: list, turns: int): """ Play the game. """ # Start the game. previous = {} # No comp so speak exists. for turn, speak in enumerate(data, 1): previous[speak] = turn # Take 4th turn. A bit annoying. spoke = 0 turn += 1 # Carry on... for turn in range(tu...
1b444ac7d1975bade8b7757eeb6429370a24f867
59,523
import decimal def get_total_income(fn): """Quick analysis returning total income for this CSV""" headers, data = headers_data(fn) total = 0 for row in data: d = dict(zip(headers, row)) amount = d['Amount'] if amount[0].isdigit(): total += decimal.Decimal(row[3]) ...
3a4bbe69ab704fac4ea4c3d5c94caf38d1c83131
59,524
def is_half_ended(line: str) -> bool: """ Check if we a given a last line of a multiline statement with brackets """ if line.count(')') > line.count('('): return True if line.count('}') > line.count('{'): return True if line.count(']') > line.count('['): return True
1bb5e0cbb3eca1addde477706fb090ce5c7a9090
59,525
def fraction_of_critical_cases_60(): """ Real Name: b'fraction of critical cases 60' Original Eqn: b'0.1' Units: b'dmnl' Limits: (None, None) Type: constant b'' """ return 0.1
69e397e2b319494b899122ce1efd3a27f96b06de
59,526
def cmd(c): """ Run an external process and return the results. """ if type(c) is str: c = c.split() process = Popen(c, stdout=PIPE, stderr=PIPE) out, err = process.communicate() return process.returncode, to_str(out), to_str(err)
ad3b8ed3f7e7f243d256e020932c461c22c695a5
59,527
def unique_count(value): """Count the number of unique characters in the string representation of a scalar value. Parameters ---------- value: scalar Scalar value in a data stream. Returns ------- int """ unique = set() for c in str(value): unique.add(c) ...
3a1481e06e6b5a57a2e4c28dc3b9b34dd5c3a977
59,528
def process_fft(procstatus, dscfg, radar_list=None): """ Compute the Doppler spectra form the IQ data with a Fourier transform Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries ...
f3b99891c0308decd12d1c0410b0843bddf12163
59,529
def get_dataset_data_masked(dataset, bands=None, x=0, y=0, x_size=None, y_size=None, ndv=NDV, mask=None): """ Return one or more bands from the dataset with pixel quality applied :type dataset: datacube.api.model.Dataset :type bands: list[Band] :type x: int :type y: int :type x_size: int ...
bdd5af5c48d990805396bc206d920a50105df5a8
59,530
def me(): """Return user information including name, picture and email.""" url = config.get('base_uber_url') + 'me' response = app.requests_session.get( url, headers=generate_ride_headers(session.get('access_token')), ) if response.status_code != 200: return 'There was an er...
2aed075f9406b20dddc97830a903b6c07f61effd
59,532
def category_table_build(osm_table_name, categorysql): """ Returns an SQL OSM category table builder Args: osm_table_name (string): a OSM PostGIS table name Returns: sql (string): a sql statement """ sql = ("INSERT INTO category_%s (osm_id, cat) " "SELECT DISTINCT o...
147812bb68845e3fd0dca7e805f610d26428eac3
59,535
def cspad_cctbx_from_psana(nda_in): """returns cctbx array of ASICs (64, 185, 194) from cspad array (32, 185, 388) """ segs, rows, cols = shape_in = (32,185,388) size = segs * rows * cols colsh = cols/2 if nda_in.size != size: raise ValueError('Input array size: %d is not consistent wit...
d1ac54519a5dc2605717b220c6bc3b15d9414264
59,536