content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _make_decorator( obj: Wrappable, to_wrap: tp.Iterable[str] ) -> tp.Callable[[tp.Type[WrapperInjector]], tp.type[WrapperInjector]]: """Makes the decorator function to use for wrapping. Parameters ---------- obj : :obj:`ModuleType`, :obj:`type` or :obj:`object` The source object to wr...
33ab2d7670f518f15c55ebafcde3667447c73c4d
25,400
import numbers import warnings def logistic_regression_path(X, y, pos_class=None, Cs=10, fit_intercept=True, max_iter=100, tol=1e-4, verbose=0, solver='lbfgs', coef=None, class_weight=None, dual=False, penalty='l2', ...
8f42d708532d255f0d61f7e695eab778b5aad99c
25,401
def merge_labels_below_minsize(labels: np.array, min_size: int, connectivity: int = 8) -> np.array: """ Takes labels below min_size and merges a label with a connected neighbor (with respect to the connectivity description). Ignores label 0 as ...
9d9af5e1ddcc288149304d8138f8076dccab1ad8
25,402
def custom_cnn_model(config, labels, model_weights=None): """ Convolutional Neural network architecture based on 'Photonic Human Identification based on Deep Learning of Back Scattered Laser Speckle Patterns' paper. :param conf: Configuration list of models hyper & learning params :param labels: Lis...
1440c1ac911c4fc4dce06e10ced5b94ae97f407b
25,403
def check_day_crossover(tRxSeconds, tTxSeconds): """ Checks time propagation time for day crossover :param tRxSeconds: received time in seconds of week :param tTxSeconds: transmitted time in seconds of week :return: corrected propagation time """ tau = tRxSeconds - tTxSeconds if tau > ...
f44b5ef90e130fbcbc741f79bea69ee79f55a574
25,404
def matrix2xyx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Ry(k2) @ Rx(k1) = [[c2, s1s2, c1s2], [s2s3, -s1c2s3+c1c3, -c1c2s3-s1c3], [-s2c3, s1c2c3+c1s3, c1c2c3-s1s3]] """ rotation_matrices = rotation_matrices.reshap...
74185b505e54239128e4b22eb709e1d08f50b206
25,405
def _merge_low_rank_eigendecomposition(S1, V1, S2, V2, rank=None): """Private helper function for merging SVD based low rank approximations. Given factors S1, V1 and S2, V2 of shapes [K1], [M, K1] and [K2], [M, K2] respectively of singular value decompositions A1 = U1 @ np.diag(S1) @ V1.T ...
9a04fb922e87b78ee217890c0094f3cdd8690f60
25,406
def usgs(path): """Reads USGS-formatted ASCII files. Reads the ascii format spectral data from USGS and returns an object with the mean and +/- standard deviation. Reference: https://www.sciencebase.gov/catalog/item/5807a2a2e4b0841e59e3a18d Args: path: file path the the USGS spectra text file....
329df0fe919cf126ae363f384619c8fc5419b073
25,407
import json def change_service(**kwargs): """Makes a given change to a MRS service Args: **kwargs: Additional options Keyword Args: service_id (int): The id of the service change_type (int): Type of change url_context_root (str): The context root for this service ...
ed1cc6725f26791becd37733068cae468cc5486b
25,408
def text_3d(string, depth=0.5): """Create 3D text.""" vec_text = _vtk.vtkVectorText() vec_text.SetText(string) extrude = _vtk.vtkLinearExtrusionFilter() extrude.SetInputConnection(vec_text.GetOutputPort()) extrude.SetExtrusionTypeToNormalExtrusion() extrude.SetVector(0, 0, 1) extrude.Se...
7f851303bf9eea1a4777e70f697d7679a37cfcf8
25,409
from typing import Optional def get_secret_version(project: Optional[str] = None, secret: Optional[str] = None, version: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSecretVersionResult: """ Get a Secret ...
bda99d80fe49f7e799272c48418b605a327f6dfa
25,410
import logging def logged_class(cls): """Class Decorator to add a class level logger to the class with module and name.""" cls.logger = logging.getLogger("{0}.{1}".format(cls.__module__, cls.__name__)) return cls
4a6c878c0061b2b1587e8efcdfae21de87a96e71
25,411
import os import inspect def get_available_plugin_screens(): """ Gets the available screens in this package for dynamic instantiation. """ ignore_list = ['__init__.py'] screens = [] for plugin in os.listdir(os.path.join(os.path.dirname(__file__))): if (os.path.isdir(os.path.join(os.pat...
454659f02fa4a13105d4e849db7ed3e35d21f6a2
25,412
def crop_point(image, height_rate, width_rate): """Crop the any region of the image. Crop region area = height_rate * width_rate *image_height * image_width Args: image: a Image instance. height_rate: flaot, in the interval (0, 1]. width_rate: flaot, in the interval (0, 1]....
f00992597aa5d03fd2aab724668071a17120efbd
25,413
import ast def test_name_rename(): """ Test a simple transformer to rename """ class Renamer(NodeTransformer): def visit_Name(self, node, meta): node.id = node.id + '_visited' return node renamer = Renamer() mod = ast.parse("bob = frank") transform(mod, ren...
a609211bb1f7fc0055abe4cf99cdc0e131f0924b
25,414
import logging import random import string def fileobj_video(contents=None): """ Create an "mp4" video file on storage and return a File model pointing to it. if contents is given and is a string, then write said contents to the file. If no contents is given, a random string is generated and set as t...
d3fb1d9c9e97c53853489486e37af1f2497ae0d3
25,415
def _toIPv4AddrString(intIPv4AddrInteger): """Convert the IPv4 address integer to the IPv4 address string. :param int intIPv4AddrInteger: IPv4 address integer. :return: IPv4 address string. :rtype: str Example:: intIPv4AddrInteger Return --------------------------------- ...
ac5f55146eedaf0b7caca19327ae0a88c9d5282a
25,416
def expand_case_matching(s): """Expands a string to a case insensitive globable string.""" t = [] openers = {"[", "{"} closers = {"]", "}"} nesting = 0 drive_part = WINDOWS_DRIVE_MATCHER.match(s) if ON_WINDOWS else None if drive_part: drive_part = drive_part.group(0) t.appe...
7d9f32e641671cf570c7c95397d9de559bab84b4
25,417
import re def look_behind(s: str, end_idx: int) -> str: """ Given a string containing semi-colons, find the span of text after the last semi-colon. """ span = s[: (end_idx - 1)] semicolon_matches = [ (m.group(), m.start(), m.end()) for m in re.finditer(r"(?<=(;))", span) ] if l...
0cc478e73edd713fa72743f36e29001bb214e26c
25,418
def sum_fspec(files, outname=None): """Take a bunch of (C)PDSs and sums them.""" # Read first file ftype0, contents = get_file_type(files[0]) pdstype = ftype0.replace("reb", "") outname = _assign_value_if_none( outname, "tot_" + ftype0 + HEN_FILE_EXTENSION ) def check_and_distribute...
8d8eb0f9f75e44b2d1e34abcff4479a055c40483
25,419
import six import pytz def make_aware(dt, tz=None): """ Convert naive datetime object to tz-aware """ if tz: if isinstance(tz, six.string_types): tz = pytz.timezone(tz) else: tz = pytz.utc if dt.tzinfo: return dt.astimezone(dt.tzinfo) else: retur...
b5003de5055c5d283f47e33dfdd6fbe57d6fce96
25,420
def decrypt(ctxt, kx, spice, blocksize): """ Main decryption function Args: ctxt: ciphertext kx: key expansion table spice: spice blocksize: size of block Returns: Decrypted ciphertext """ spice = int_to_arr(spice, 512) c...
56ca0b7cb61f3eca1c20fcf174b14b6ba79c5dfe
25,421
from itertools import product def listCombination(lists) -> list: """ 输入多个列表组成的列表,返回多列表中元素的所有可能组合 :param lists: 多个列表组成的列表 :return: 所有元素可能的组合 """ result = [] resultAppend = result.append for i in product(*lists): resultAppend(i) return result
6023cdc205b2780c5cd2cf56113d48a0675b98bf
25,422
import os def DoChopTraj(trajf, chopf, startns, stopns, translate=False): """ Chops a provided trajectory file based on a given start time and end time in nanoseconds. Assuming 2 fs time step and writing results every 1000 steps. Helpful for seeing how PMF evolves over time. Paramete...
e0f3d22c4bae850e33ae846229b41c6e88e86ac8
25,423
import warnings def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs): """DEPRECIATED - use to_sql Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame name : string con : DBAPI2 connection flavor : {'sqlite', 'mysql'...
0fe3bf204d48489c65ad2497c54f009000ce89b8
25,424
def edge_slope(e): """Calculate the slope of an edge, 'inf' for vertical edges""" v = edge_vector(e) try: return v.z / round(v.xy.length, 4) except ZeroDivisionError: return float("inf")
742427d4f97712504fcb9dc09c2168178f500ac8
25,425
def pkt_addrs(addr_fragment: str) -> tuple[Address, Address, Address, Address, Address]: """Return the address fields from (e.g): '01:078710 --:------ 01:144246'. Will raise an InvalidAddrSetError is the address fields are not valid. """ # for debug: print(pkt_addrs.cache_info()) try: addr...
9855b9ed9ecc78d66094fadcd0e662155217a3d5
25,426
import torch def token_downup(target_dict, source_dict): """Transform token features between different distribution. Returns: x_out (Tensor[B, N, C]): token features. Args: target_dict (dict): dict for target token information source_dict (dict): dict for source token information...
2fab5ef8aabc9231b0342d74fb07b2b89000dca3
25,427
def get_score(train_data,train_labels,test_data,test_labels,problem_type): """ Returns the f1 score resulting from 3NN classification if problem_type = 'classification', or the mse from regression if problem_type = 'regression' """ if (problem_type=="classification"): predictor = KNeighborsClassifier(n_neighb...
fc957b09d0d0a60ea21b0fc50fbca94ac8ba4647
25,428
def build_client_datasets_fn(train_dataset, train_clients_per_round): """Builds the function for generating client datasets at each round. Args: train_dataset: A `tff.simulation.ClientData` object. train_clients_per_round: The number of client participants in each round. Returns: A function which re...
bcdb7d9c450401bff88635b5bd74c0eb6a0e7da5
25,429
def get_simple_grid(xbounds, ybounds, shift_origin=None): """ """ xbounds = np.atleast_1d(xbounds) if len(xbounds)==1: xmin,xmax = 0,xbounds[0] else: xmin,xmax = xbounds ybounds = np.atleast_1d(ybounds) if len(ybounds)==1: ymin,ymax = 0,ybounds[0] else: ...
8580e37ca98dc5d8214b7da563b31e8819b870cd
25,430
def query_hecate(session, ra, dec, _radius, _verbose: bool = True): """ Query the HECATE catalog """ m=0 gal_offset = []; mag = []; filt = []; dist = []; dist_err = []; gal_ra = []; gal_dec = []; distflag = []; source = [] # set up query try: query = session.query(HecateQ3cRecord) ...
bf321d6151226d801479ef5c9170bed597cac903
25,431
def all_main_characters(raw_data: AniListRawResponse) -> list[Character]: """Returns all of the main characters from the data.""" characters: list[Character] = anime_media(raw_data)["mainCharacters"]["nodes"] return characters
9ec3f0cc2757fdbec24923aa0953a0c8f094bd24
25,432
from typing import List def sequence_to_ngram(sequence: str, N: int) -> List[str]: """ Chops a sequence into overlapping N-grams (substrings of length N) :param sequence: str Sequence to convert to N-garm :type sequence: str :param N: Length ofN-grams (int) :type N: int :return: List of n...
8cbe97ee34c75ca3aad038236bd875ea0c3450cd
25,433
def _convert_for_receive(profile): """Convert profile to be fed into the receive model. Args: profile (pandas.DataFrame): Profile to convert. Returns: pandas.DataFrame: Converted profile. """ without_profile = profile[profile.age.isna()].reset_index(drop=True) profile = profil...
16196499547c7f6e25e75ee8e814d8c89f8ea30d
25,434
def _format_path(path): """Format path to data for which an error was found. :param path: Path as a list of keys/indexes used to get to a piece of data :type path: collections.deque[str|int] :returns: String representation of a given path :rtype: str """ path_with_brackets = ( ''.j...
1809080453af154824e867cd8104cedbd616b937
25,435
import os def common_mean_watson(Data1, Data2, NumSims=5000, print_result=True, plot='no', save=False, save_folder='.', fmt='svg'): """ Conduct a Watson V test for a common mean on two directional data sets. This function calculates Watson's V statistic from input files through Monte Carlo simulation...
7d329d06f2bcc3de137cf0bb007d274cda5bb744
25,436
def GetLayouts(): """Returns the layout proxies on the active session. Layout proxies are used to place views in a grid.""" return servermanager.ProxyManager().GetProxiesInGroup("layouts")
8099264d77e4daab61d24eb22edb397aeacfa294
25,437
import os def GetRelativePath(starting_dir, dest): """Creates a relative path from the starting_dir to the dest.""" assert starting_dir assert dest starting_dir = os.path.realpath(starting_dir).rstrip(os.path.sep) dest = os.path.realpath(dest).rstrip(os.path.sep) common_prefix = GetCommonPa...
75678142a26d8b0dea47d539c9251f2a1b580ac4
25,438
def _calculate_mean_cvss(): """Calcuate the mean CVSS score across all known vulnerabilities""" results = db.osvdb.aggregate([ {"$unwind": "$cvss_metrics"}, {"$group": { "_id": "null", "avgCVSS": {"$avg": "$cvss_metrics.calculated_cvss_base_score"} }} ]) l...
5d0f7ca346dd9077127351f60d1b0da7849c5144
25,439
def decomposition_super1(centroid, highway, coherence,coordinates,input): """ Function to perform Experiment 2: Differential Decomposition with level-specific weight Args: centroid: Cluster centroid of super pixels highway: Super pixels after Stage I Super pixeling coherence: Coherence value a...
9649d1d267bc442cd999f3afd622156f4c5e1895
25,440
from typing import List import math def get_deck_xs(bridge: Bridge, ctx: BuildContext) -> List[float]: """X positions of nodes on the bridge deck. First the required X positions 'RX' are determined, positions of loads and abutments etc.. After that a number of X positions are calculated between each ...
75447a1929035685aeb14f212beea74bb7b814ad
25,441
def helicsGetFederateByName(fed_name: str) -> HelicsFederate: """ Get an existing `helics.HelicsFederate` from a core by name. The federate must have been created by one of the other functions and at least one of the objects referencing the created federate must still be active in the process. **Parame...
a262ee67a4b87212be401442d99482a569862f92
25,442
import functools import logging def persistant_property(*key_args): """Utility decorator for Persistable-based objects. Adds any arguments as properties that automatically loads and stores the value in the persistence table in the database. These arguments are created as permanent persistent propert...
bba4de85830496d414c80960b59422d51af30572
25,443
import pkg_resources import csv def states(): """ Get a dictionary of Backpage city names mapped to their respective states. Returns: dictionary of Backpage city names mapped to their states """ states = {} fname = pkg_resources.resource_filename(__name__, 'resources/City_State_Pairs.csv') with ope...
4781170b9f8c8ab654ebb39dd733577351571b3e
25,444
def matrix_set_diag(input_x, diagonal, k=0, alignment="RIGHT_LEFT"): """ Calculate a batched matrix tensor with new batched diagonal values. Args: input_x (Tensor): a :math:`(..., M, N)` matrix to be set diag. diagonal (Tensor): a :math`(..., max_diag_len)`, or `(..., num_diags, max_diag_le...
e8dddc42438ae2bc8bf70ef9a0db1b1cdce9dad3
25,445
def execute_payment(pp_req): """Executes a payment authorized by the client.""" payment = paypalrestsdk.Payment.find(pp_req['paymentId']) if payment.execute({"payer_id": pp_req['PayerID']}): return True return False
4d7f94610b6f8360371099d3774fd4902e47b6c7
25,446
def create_structural_eqs(X, Y, G, n_nodes_se=40, n_nodes_M=100, activation_se='relu'): """ Method to create structural equations (F:U->X) and the original prediction model (M:X->Y). This also calculates and stores residuals. Parameters ---------- X : pandas DataFrame input features of the ...
f8ebc336360fa7d04ac1aa90dbb8165e54181f6b
25,447
import logging def twitch_checkdspstatus(_double_check: bool) -> bool: """ Uses current Selenium browser to determine if DSP is online on Twitch. :param _double_check: Internally used to recursively call function again to double check if DSP is online :return: True if DSP is online. False is DSP is of...
7ffac955b3cd415e5deac41eda380655bcbed876
25,448
import random import math def random_walk(humans, dt, energy, temperature): """ calculates location, speed and acceleration by adding random values to the speed Args: humans (list): list of all humans dt (float): time step in which the movement is calculated energy (float): amount...
bfc04b4d0ae1a5c6a7c510a72a9ae2607a225a37
25,449
def format_name(name_format: str, state: State): """Format a checkpoint filename according to the ``name_format`` and the training :class:`~.State`. The following format variables are available: +------------------------+-------------------------------------------------------+ | Variable ...
72c9d5a50f1c05e726702f33befe3373a0ba4486
25,450
from mpi4py import MPI def allsync(local_values, comm=None, op=None): """Perform allreduce if MPI comm is provided.""" if comm is None: return local_values if op is None: op = MPI.MAX return comm.allreduce(local_values, op=op)
d10174d7774e5691193ae4c08d7fe6838e8c1ee4
25,451
def vec_bin_array(arr, m): """ Arguments: arr: Numpy array of positive integers m: Number of bits of each integer to retain Returns a copy of arr with every element replaced with a bit vector. Bits encoded as int8's. """ to_str_func = np.vectorize(lambda x: np.binary_repr(x).zfill(m)) ...
bb56f94413ef611b9a685b835203aad9064b3092
25,452
from typing import Iterator from typing import List def parse_bafs(stream: Iterator[str]) -> List[BAF]: """Parses allelic counts output from GATK ModelSegments, which is a SAM-style header comprising lines starting with @ followed by single line with column names (CONTIG, POSITION, REF_COUNT, ALT_COUNT,...
b490b007841afd707576780f436175aec6526f14
25,453
import mpmath def logpdf(x, chi, c): """ Logarithm of the PDF of the ARGUS probability distribution. """ if c <= 0: raise ValueError('c must be positive') if chi <= 0: raise ValueError('chi must be positive') if x < 0 or x > c: return mpmath.mp.ninf with mpmath.ex...
8df44305dfaeaa9b725de7a9224259929c4c8900
25,454
def sample(colors: list, max_colors: int = 8, sensitivity: int = 75) -> list: """ Sample most common colors from a PIL Image object. :param colors: list of RGB color tuples eg. [(0, 0, 0), (255, 255, 255)] :param max_colors: maximum number of colors to return :param sensitivity: how perceptively di...
5d90dfa3d097ea923f25deafda5b907a41c5909d
25,455
def tf_example_to_feature_description(example, num_timesteps=DEFAULT_NUM_TIMESTEPS): """Takes a string tensor encoding an tf example and returns its features.""" if not tf.executing_eagerly(): raise AssertionError( 'tf_example_to_reverb_sample() only works under eag...
edf4f829b1c0746a34093ea36672a094412794f1
25,456
def setupmethod(f: F) -> F: """Wraps a method so that it performs a check in debug mode if the first request was already handled. """ def wrapper_func(self, *args: t.Any, **kwargs: t.Any) -> t.Any: if self._is_setup_finished(): raise AssertionError( "A setup function...
be268e747fce91d2d2ffc368b54d6a2843cec4b5
25,457
import numpy def generateStructuredGridPoints(nx, ny, v0, v1, v2, v3): """ Generate structured grid points :param nx: number of x cells :param ny: number of y cells :param v0: south west corner :param v1: south east corner :param v2: north east corner :param v3: north west corner :...
0de9a3a3a47b26c3c3d56088c7ec55d241edeff3
25,458
def Keywords(lang_id=0): """Returns Specified Keywords List @param lang_id: used to select specific subset of keywords """ return [PY_KW, PY_BIN]
1a0f0ac7d22e4da00438d823c50258cb5ade8574
25,459
def clear(keyword): """``clear`` property validation.""" return keyword in ('left', 'right', 'both', 'none')
c16cc980b9af82b4210e3c8c430cd65934596aa1
25,460
from typing import List def PermissionsListOfUser(perm_list: List[str]) -> List[str]: """ Takes a list of items and asserts that all of them are in the permissions list of a user. :param perm_list: A list of permissions encoded as ``str`` :return: The input perm_list :raises Invalid...
811adedcdc9b90a066d6253269de33e0813c8d7b
25,461
import collections def PrepareForBuild(input_proto, output_proto, _config): """Prepare to build toolchain artifacts. The handlers (from _TOOLCHAIN_ARTIFACT_HANDLERS above) are called with: artifact_name (str): name of the artifact type. chroot (chroot_lib.Chroot): chroot. Will be None if the chroot ...
5c77d9ad318e0b5dd604e5127e9864aac50e7d77
25,462
from pathlib import Path import json def for_properties(path: Path = Path('config.json')): """ Simple externalized configuration loader. Properties are loaded from a file containing a JSON object. :param path: Path to the file. :return: Simple namespace with the key/value pairs matching the loaded jso...
44e377ff28cef3b77adbbcc653f6b1ec196f2a2d
25,463
import os def guess_components(paths, stop_words=None, n_clusters=8): """Guess components from an iterable of paths. Args: paths: list of string containing file paths in the project. stop_words: stop words. Passed to TfidfVectorizer. n_clusters: number of clusters. Passed to MiniBatch...
9d53a2961b4ea1316facc64327f536cf90a7292f
25,464
def get_instance_tags(ec2_client: boto3.Session.client, instance_id: str): """Get instance tags to parse through for selective hardening""" tag_values = [] tags = ec2_client.describe_tags( Filters=[ { "Name": "resource-id", "Values": [ ...
94506f230e44d730a89b15263ef74367c777f654
25,465
from scorer.controller import prediction_app def create_app(config_name=None) -> Flask: """Create a flask app instance.""" app = Flask("__name__") app.config.from_object(config[config_name]) config[config_name].init_app(app) # import blueprints app.register_blueprint(prediction_app) _l...
f973bca064792d6c39b783b55e75f319a6bc702f
25,466
from typing import Dict def getmasterxpub(client: HardwareWalletClient, addrtype: AddressType = AddressType.WIT, account: int = 0) -> Dict[str, str]: """ Get the master extended public key from a client :param client: The client to interact with :return: A dictionary containing the public key at the ...
58e20780672b0c7cd1dc0912ef3565e83e220a53
25,467
from typing import Any def serialize( obj: Any, annotation: Any, config: SerializerConfig ) -> str: """Convert the object to JSON Args: obj (Any): The object to convert annotation (Annotation): The type annotation config (SerializerConfig): The serializer confi...
6fc0fab725798c4d5b643c2dfb6a76929173f601
25,468
def validate_dvprel(prop_type, pname_fid, validate): """ Valdiates the DVPREL1/2 .. note:: words that start with integers (e.g., 12I/T**3) doesn't support strings """ if validate: msg = 'DVPREL1: prop_type=%r pname_fid=%r is invalid' % (prop_type, pname_fid) #if prop...
fa3129485081d4b7312fda74e87b1203c97e9adc
25,469
def is_ligature(archar): """Checks for Arabic Ligatures like LamAlef. (LAM_ALEF, LAM_ALEF_HAMZA_ABOVE, LAM_ALEF_HAMZA_BELOW, LAM_ALEF_MADDA_ABOVE) @param archar: arabic unicode char @type archar: unicode @return: @rtype:Boolean """ return archar in LIGUATURES
721c6135064e21ba681c43fc776c0f64f290e2d3
25,470
def _get_embl_key(line): """Return first part of a string as a embl key (ie 'AC M14399;' -> 'AC')""" # embl keys have a fixed size of 2 chars return line[:2]
b54f1a94f120f7ac63a0dd2a22bd47d5a5d5eeb9
25,471
import os def size_too_big(path): """Returns true is file is too large (5MB) """ five_mb = 5242880 return os.path.getsize(path) > five_mb
62e926247ab5439732ce61c8e59fe4a50366cba0
25,472
from h2o.job import H2OJob from h2o.utils.typechecks import assert_is_type from h2o.frame import H2OFrame from h2o import api import os def store_h2o_frame(data, directory, filename, force=False, parts=1): """ Export a given H2OFrame to a path on the machine this python session is currently connected to. ...
d2fd4d38748cfa47cd1d29306a7d646fd96ab2c8
25,473
import scipy def get_region_data(region, lastday=-1, printrows=0, correct_anomalies=True, correct_dow='r7'): """Get case counts and population for one municipality. It uses the global DFS['mun'], DFS['cases'] dataframe. Parameters: - region: region name (see below) - lastday...
e35b41eca663d25d065d2b656745e7c41e038dc1
25,474
def MONTH(*args) -> Function: """ Returns the month of the year a specific date falls in, in numeric format. Learn more: https//support.google.com/docs/answer/3093052 """ return Function("MONTH", args)
86a44c35e989ccc149935515550d3176549ee82e
25,475
import os def local_tmp_dir(): """tmp directory for tests""" tmp_dir_path = "./tmp" if not os.path.isdir(tmp_dir_path): os.mkdir(tmp_dir_path) return tmp_dir_path
3f1f710ba18ec336982c69225c999a75fed9c481
25,476
import logging import time def Install(browser): """Installs |browser|, if necessary. It is not possible to install an older version of the already installed browser currently. Args: browser: specific browst to install. Returns: whether browser is installed. """ # Only dynamic installation o...
93bc5b7ad0b1bc8b4d4496a9ae608d2b9fa1848f
25,477
def get_query_string_from_process_type_string(process_type_string: str) -> str: # pylint: disable=invalid-name """ Take the process type string of a Node and create the queryable type string. :param process_type_string: the process type string :type process_type_string: str :return: string that c...
1380ad90a98da26237176890c52a75684e92964e
25,478
def get_column(fn): """Get column from Cellomics filename. Parameters ---------- fn : string A filename from the Cellomics high-content screening system. Returns ------- column : string The channel of the filename. Examples -------- >>> fn = 'MFGTMP_14020618000...
5582b6952af2cfcc6c2bcf0aeb7d472420766c9c
25,479
def add_tables(): """ Generates tables in postgres database according to SQLAlchemy model when this script is invoked directly via terminal. """ return database.Base.metadata.create_all(bind=database.engine)
e7da7d2ccef81197faa3393a4e0a04cf1a656b7d
25,480
import os def isloggedin(userdir): """If user has sent us an in date, valid cookie then return updated cookie header, otherwise return False.""" try: rawcookie = os.environ['HTTP_COOKIE'] except KeyError: return False thecookie = SimpleCookie(rawcookie) try: cookiestrin...
250c4860160607bbf228ab6204b87ca232cd25c7
25,481
import os import time def enable(name, start=False, **kwargs): """ Start service ``name`` at boot. Returns ``True`` if operation is successful name the service's name start : False If ``True``, start the service once enabled. CLI Example: .. code-block:: bash s...
6863f09820389443604d2b313d5f841551ebb1ee
25,482
def label_vertices(ast, vi, vertices, var_v): """Label each node in the AST with a unique vertex id vi : vertex id counter vertices : list of all vertices (modified in place) """ def inner(ast): nonlocal vi if type(ast) != dict: if type(ast) == list: # pr...
1216c3ff1f5995e24f0f3a245fad5db820335f4d
25,483
import logging def standardize_batch(inputs, is_training, decay=0.999, epsilon=1e-3, data_format="NHWC", use_moving_averages=True, use_cross_replica_mean=None): """Adds TPU-enabled bat...
6e5d39704877c797bb568d09e7b3c6e8899d0900
25,484
def bias_variable(shape): """Create a bias variable with appropriate initialization.""" #initial = tf.constant(0.1, shape=shape) initial = tf.constant(0.0, shape=shape) return tf.Variable(initial)
046c9fc01bba5af90b166e16d3dce9a294decc58
25,485
import sys def getPortNumber(): """ Check the command-line arguments for the port number. The program can exit in this method if Too few arguments are passed into the program Too many arguments are passed into the program The port number argument is non-numeric The port number argument is less than 0 sinc...
f92a079313e585138e7b548b9bd2d8c383b7418f
25,486
def object_gatekeeper(obj, is_auth, ignore_standalone=False): """ It's OK to use available_to_public here because the underlying logic is identical. """ if not obj: return False if is_auth: return True else: try: return obj.available_to_public except: ...
66f0749788f462ba9a0dfee6edf890245aca15ba
25,487
def l1_l2_regularizer(scale_l1=1.0, scale_l2=1.0, scope=None): """Returns a function that can be used to apply L1 L2 regularizations. Args: scale_l1: A scalar multiplier `Tensor` for L1 regularization. scale_l2: A scalar multiplier `Tensor` for L2 regularization. scope: An optional scope name. Retur...
6fe25d5f90d23d192c2b0d9897d5e025d534813c
25,488
def test013_ip_range(): """ to run: kosmos 'j.data.types.test(name="iprange")' """ ipv4 = j.data.types.get("iprange", default="192.168.0.0/28") assert ipv4.default_get() == "192.168.0.0/28" assert ipv4.check("192.168.23.255/28") is True assert ipv4.check("192.168.23.300/28") is False ...
4ac18b32aef77b5d4c1080150dd218a8f96efcf3
25,489
def _create_hive_cursor(): """ Initializes a hive connection and returns a cursor to it :return: hive cursor """ _print_info('Initializing hive cursor.') return _initialize_hive_connection()
52e0250b1a163a6ae8f43bbb3ce723cd79518e98
25,490
import os import pickle def load_pretrained_wts(featurizer_params, ExtendedEncoder_params): """Merging pre-trained and initialised parameters""" param_idx = config['restart_from']//config['total_steps'] if os.path.isfile(config['params_dir']+f'params_{param_idx}'): with open(config['params_di...
67798e37aa8fc1a9c1f1a96788d8c845be479a3a
25,491
def to_vector_single(text, embeddings, maxlen=300): """ Given a string, tokenize it, then convert it to a sequence of word embedding vectors with the provided embeddings, introducing <PAD> and <UNK> padding token vector when appropriate """ tokens = tokenizeAndFilterSimple(clean_text(text)) ...
3000691c9bbb75c9c86b6d740ff2559e10228db4
25,492
import numpy def eval_tensor_density( tens: tf_compat.Tensor, sess: tf_compat.Session = None ) -> float: """ Get the density (fraction of non zero values) in a tensor :param tens: the tensor to get the density for :param sess: the session to use for evaluating the tensor, if not supplied ...
38ed298cdef732a1465a4221a9fbac82535b6d2c
25,493
import collections def get(key, default): """Get a config bloc from the YAML config file. Args: default (dict): The default bloc if the key is not available Returns: dict: The config bloc (or the default one) """ if not key.lower() in _YAML_DICT or isinstance(_YAML_DICT[key.lower...
40a7ac19bf64667bccd183c28c2fb0c772c8f748
25,494
def adaptsim(f, a, b, eps=1e-8, max_iter=10000): """自适应 Simpson 求积 P.S. 这个函数名来自 Gander, W. and W. Gautschi, “Adaptive Quadrature – Revisited,” BIT, Vol. 40, 2000, pp. 84-101. 该文档可以在 https://people.inf.ethz.ch/gander/ 找到。 但该函数的实现并没有使用此文中的递归方法。 Args: f: 要求积的函数 ...
b24ed3c2493b8ece19a69cf781a75e7a9e0f9cd0
25,495
def get_next_position(grid): """Returns best next position to send.""" width = len(grid[0]) unprepared = [inspect_around_position(grid, x) for x in range(1, width - 1)] return unprepared.index(max(unprepared)) + 2
8d1a75766e830ee49c895a5fe90adc3208011c3d
25,496
from typing import Optional def which_subdir(sha: str) -> Optional[str]: """ Determine which subset (if any) sha is represented in """ fname = sha + '.json' for k, v in subdir_contents.items(): if fname in v: subdir_contents[k].remove(fname) return k subdir_contents[MIS...
f5a32354724604f15710bbf9a69c1e5d38e84a83
25,497
import numpy as np def smoothedEnsembles(data,lat_bounds,lon_bounds): """ Smoothes all ensembles by taking subsamples """ ### Import modules print('\n------- Beginning of smoothing the ensembles per model -------') ### Save MM newmodels = data.copy() mmean = newmodels[-1,:,:,:...
ed8fe2bc3d4e77384179d6a1a1406ca9446dc973
25,498
def conv7x7_block(in_channels, out_channels, strides=1, padding=3, use_bias=False, use_bn=True, bn_eps=1e-5, activation="relu", data_format="channels_last", *...
9de1518d95417877a0bf5e094ebb907c3534434f
25,499