content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from grouper.permissions import permission_intersection def get_public_key_permissions(session, public_key): # type: (Session, PublicKey) -> List[Permission] """Returns the permissions that this public key has. Namely, this the set of permissions that the public key's owner has, intersected with the permi...
9e9d33cda6fb342d00fb3e00b668ba89c654bc68
8,100
def _format_breed_name(name): """ Format breed name for displaying INPUT name: raw breed name, str OUTPUT name : cleaned breed name, str """ return name.split('.')[1].replace('_', ' ')
0c2680de9bd19e61d717fb84c1ce01e5095ddf35
8,101
import os def loadIndianPinesData(): """ 加载数据 :return: data, labels """ data_path = os.path.join(os.getcwd( ), '../Indian Pines') data = sio.loadmat(os.path.join(data_path, 'Indian_pines_corrected.mat'))['indian_pines_corrected'] labels = sio.loadmat(os.path.join(data_path, 'Indian_pines_g...
3d54f79417fc5cec98708a38c47c3e34100ad639
8,102
def create_pid_redirected_error_handler(): """Creates an error handler for `PIDRedirectedError` error.""" def pid_redirected_error_handler(e): try: # Check that the source pid and the destination pid are of the same # pid_type assert e.pid.pid_type == e.destination_p...
3137c4d6447c5da9f500b3d4cd7a6a3a68325a92
8,103
def is_var_name_with_greater_than_len_n(var_name: str) -> bool: """ Given a variable name, return if this is acceptable according to the filtering heuristics. Here, we try to discard variable names like X, y, a, b etc. :param var_name: :return: """ unacceptable_names = {} if len(var_...
c4509b33cc7326c1709f526137e04a590cf3c7ad
8,104
from re import L def stacked_L(robot: RobotPlanar, q: list, q_goal: list): """ Stacks the L matrices for conviencne """ LL = [] LLinv = [] Ts_ee = robot.get_full_pose_fast_lambdify(list_to_variable_dict(q)) Ts_goal = robot.get_full_pose_fast_lambdify(list_to_variable_dict(q_goal)) fo...
a329ad79b9add95307195329b937a85cf9eeda50
8,105
from typing import Dict async def help() -> Dict: """Shows this help message.""" return { '/': help.__doc__, '/help': help.__doc__, '/registration/malaysia': format_docstring(get_latest_registration_data_malaysia.__doc__), '/registration/malaysia/latest': format_docstring(get_...
4d72c66069956c469aea1d39fd68e20454f68e40
8,106
def eliminate_arrays(clusters, template): """ Eliminate redundant expressions stored in Arrays. """ mapper = {} processed = [] for c in clusters: if not c.is_dense: processed.append(c) continue # Search for any redundant RHSs seen = {} for...
2d5a59d9d5758963e029cc102d6a123c62ed8758
8,107
def data_generator(batch_size): """ Args: dataset: Dataset name seq_length: Length of sequence batch_size: Size of batch """ vocab_size = 20000 (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size) x_train, y_train, x_test, y_test = tf.ragged.constan...
ed1edfd0cbeac01bd1fcad6cc1fe36a94dc006e8
8,108
from datetime import datetime def now(): """ Get current timestamp Returns: str: timestamp string """ current_time = datetime.now() str_date = current_time.strftime("%d %B %Y, %I:%M:%S %p") return str_date
4c487416fa119cae0c5310678dfd96e0f737b937
8,109
def open_mfdataset( fname, convert_to_ppb=True, mech="cb6r3_ae6_aq", var_list=None, fname_pm25=None, surf_only=False, **kwargs ): # Like WRF-chem add var list that just determines whether to calculate sums or not to speed this up. """Method to open RFFS-CMAQ dyn* netcdf files. P...
59639b4bb45d4c1306ea8ecfa1241b86247ce16b
8,110
def projection(projection_matrix: tf.Tensor, flattened_vector: tf.Tensor) -> tf.Tensor: """Projects `flattened_vector` using `projection_matrix`. Args: projection_matrix: A rank-2 Tensor that specifies the projection. flattened_vector: A flat Tensor to be projected Returns: A flat Ten...
7954247be2f3d130ac79f53e44b0509608fe85d6
8,111
def free_vars(e): """Get free variables from expression e. Parameters ---------- e: tvm.relay.Expr The input expression Returns ------- free : List[tvm.relay.Var] The list of free variables """ return _ir_pass.free_vars(e)
bfab6f5ff0ccadf8dba7af518401e6026efbcb20
8,112
def image_as_uint(im, bitdepth=None): """ Convert the given image to uint (default: uint8) If the dtype already matches the desired format, it is returned as-is. If the image is float, and all values are between 0 and 1, the values are multiplied by np.power(2.0, bitdepth). In all other situati...
a906eb7022a1823cd49bedb3858bac34e59fdf02
8,113
def unary_operator(op): """ Factory function for making unary operator methods for Factors. """ # Only negate is currently supported. valid_ops = {'-'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) @with_doc("Unary Operator: '%s'" % op) @with_name(u...
04bc43c2f5e84db29b7a913de35d7a366464dfda
8,114
def compute_cost_with_regularization(A3, Y, parameters, lambd): """ Implement the cost function with L2 regularization. See formula (2) above. Arguments: A3 -- post-activation, output of forward propagation, of shape (output size, number of examples) Y -- "true" labels vector, of shape (output size...
5904cab44af1768779ed983fa001876d14faeb1d
8,115
import matplotlib.pyplot as plt from shapely.geometry import Point, MultiPolygon, MultiLineString from scipy import spatial def catalog_area(ra=[], dec=[], make_plot=True, NMAX=5000, buff=0.8, verbose=True): """Compute the surface area of a list of RA/DEC coordinates Parameters ---------- ra, dec : `...
bcc8f834b5ea7404213c629c2837e45ba42cd690
8,116
from operator import and_ def user_page(num_page=1): """Page with list of users route.""" form = SearchUserForm(request.args, meta={'csrf': False}) msg = False if form.validate(): search_by = int(request.args.get('search_by')) order_by = int(request.args.get('order_by')) search...
3acf9cc4a274de456ad5ea0ee609857f550867ee
8,117
def validate_input(data: ConfigType) -> dict[str, str] | None: """Validate the input by the user.""" try: SIAAccount.validate_account(data[CONF_ACCOUNT], data.get(CONF_ENCRYPTION_KEY)) except InvalidKeyFormatError: return {"base": "invalid_key_format"} except InvalidKeyLengthError: ...
56ced7cf0d3b02a484910b599c266e928303ddd7
8,118
import importlib def file_and_path_for_module(modulename): """Find the file and search path for `modulename`. Returns: filename: The filename of the module, or None. path: A list (possibly empty) of directories to find submodules in. """ filename = None path = [] try: ...
4e8d0edb3a5844bb3c523aed66f8eb7f0c646aaa
8,119
def hello_page(request): """Simple view to say hello. It is used to check the authentication system. """ text = "Welcome to test_project" if not request.user.is_anonymous: text = "Welcome '%s' to test_project" % request.user.username return HttpResponse(text, content_type='text/plain')
fee98ccca3c89d1f110bc828521cbc26af004325
8,120
from typing import Dict def hash_all(bv: Binary_View) -> Dict[str, Function]: """ Iterate over every function in the binary and calculate its hash. :param bv: binary view encapsulating the binary :return: a dictionary mapping hashes to functions """ sigs = {} for function in bv.functions:...
3a3a046c9c7fe786c55d3e0d3993679f8ee71465
8,121
from typing import Union from typing import List def apply_deformation( deformation_indices: Union[List[bool], np.ndarray], bsf: np.ndarray ) -> np.ndarray: """Return Hadamard-deformed bsf at given indices.""" n = len(deformation_indices) deformed = np.zeros_like(bsf) if len(bsf.shape) == 1: ...
87e6a3403190f1139fef223d374df5f7e5f59257
8,122
def index(request): """Return the index.html file""" return render(request, 'index.html')
7ac6c9418e332aebe29a25c3954152adca3f7716
8,123
import logging def execute(cx, stmt, args=(), return_result=False): """ Execute query in 'stmt' over connection 'cx' (with parameters in 'args'). Be careful with query statements that have a '%' in them (say for LIKE) since this will interfere with psycopg2 interpreting parameters. Printing the ...
eaf02dd3177d56d7ca313cec476f3b3b110ee007
8,124
from typing import Optional from typing import Iterable from typing import Dict from typing import Type import click def parse_custom_builders(builders: Optional[Iterable[str]]) -> Dict[str, Type[AbstractBuilder]]: """ Parse the custom builders passed using the ``--builder NAME`` option on the command line. :para...
95216d12dfeacf319464b4f14be249ab3f12f10a
8,125
def construct_user_rnn_inputs(document_feature_size=10, creator_feature_size=None, user_feature_size=None, input_reward=False): """Returns user RNN inputs. Args: document_feature_size: Integer, length of document features...
cdc42e86ff7fee9a7487d05badeae1ef995a3357
8,126
def numpy_read(DATAFILE, BYTEOFFSET, NUM, PERMISSION, DTYPE): """ Read NumPy-compatible binary data. Modeled after MatSeis function read_file in util/waveread.m. """ f = open(DATAFILE, PERMISSION) f.seek(BYTEOFFSET, 0) data = np.fromfile(f, dtype=np.dtype(DTYPE), count=NUM) f.close() ...
9fc4b2de3eecefc649cb78fe7d8b545a09b8f786
8,127
def _process_pmid(s: str, sep: str = '|', prefix: str = 'pubmed:') -> str: """Filter for PubMed ids. :param s: string of PubMed ids :param sep: separator between PubMed ids :return: PubMed id """ for identifier in s.split(sep): identifier = identifier.strip() if identifier.start...
9a1fc49bf570c81f10b6b5470620d7fc0b54275e
8,128
import ast def _get_import(name, module: ast.Module): """ get from import by name """ for stm in ast.walk(module): if isinstance(stm, ast.ImportFrom): for iname in stm.names: if isinstance(iname, ast.alias): if iname.name == name: ...
bc33a882c65f7fe44d446376db3a71631629ff04
8,129
import os def load_FIPS_data(): """ Load FIPS ref table """ directory = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) filename = os.path.join(directory, 'ref_data', 'FIPS_ref_data.csv') df = pd.read_csv(filename) df['fips'] = df['fips'].astype(str) return df
e6e819cb8e820b96af2850f23b9f69af6fa4136e
8,130
from typing import Optional from typing import Tuple def number_of_qucosa_metadata_in_elasticsearch( host: str = SLUB_ELASTICSEARCH_SERVER_URL, http_auth: Optional[Tuple[str, str]] = None, index_name: str = "fulltext_qucosa", ) -> int: """Return the number of qucosa documents currently available at th...
9e3628998f7c93d12b4855ec2d2c88278b1a5e2a
8,131
from typing import Tuple from typing import Sequence from typing import List from typing import Any from typing import get_type_hints from typing import Optional def codegen_py(typeit_schema: TypeitSchema, top: bool = True, indent: int = 4) -> Tuple[str, Sequence[str]]: """ :para...
55a58893cb05a21e1d0c9715de7bad73ceec8fe4
8,132
def _tuple_to_string(tup): """ Converts a tuple of pitches to a string Params: * tup (tuple): a tuple of pitch classes, like (11, 10, 5, 9, 3) Returns: * string: e.g., 'et593' """ def _convert(pitch): pitch = mod_12(pitch) if pitch not in (0, 1, 2, 3, 4, 5, 6, 7...
61ee32199b85fe5ec645887641d6b28ff701eabd
8,133
def dashboard(): """Logged in Dashboard screen.""" session["redis_test"] = "This is a session variable." return render_template( "dashboard.jinja2", title="Flask-Session Tutorial.", template="dashboard-template", current_user=current_user, body="You are now logged in!...
48472e2ad8c3b81adab98524103959a812ab9b30
8,134
def choose_top_k(scores_flat, config): """Chooses the top-k beams as successors. """ next_beam_scores, word_indices = tf.nn.top_k(scores_flat, k=config.beam_width) return next_beam_scores, word_indices
e8bbf86c8452b0b2153f591968370612986673e2
8,135
def train_valid_test_split(data, proportions='50:25:25'): """ Splits the data into 3 parts - training, validation and test sets :param proportions: proportions for the split, like 2:1:1 or 50:30:20 :param data: preprocessed data :return: X_train, Y_train, target_rtns_train, X_valid, Y_valid, target_...
b8a9d160860aea9c224b72af32ef843b43b44656
8,136
def basis_ders_on_quad_grid(knots, degree, quad_grid, nders, normalization): """ Evaluate B-Splines and their derivatives on the quadrature grid. If called with normalization='M', this uses M-splines instead of B-splines. Parameters ---------- knots : array_like Knots sequence. de...
be1678ab5e758d9d7f9fa7710336fa892c46f9bf
8,137
import opcode def analyze_jumps(jumps): """takes the list of Jump tuples from group_jumps. returns JumpCmp. fails if input is weird (tell me more). """ # todo: more of a decompile, AST approach here? look at uncompyle. if jumps[-1].head is not None: raise BadJumpTable("last jump not an else") if len(jumps...
3f8730c957ad89b649281cf615ff826529c55b3c
8,138
def data(*args, **kwargs): """ The HTML <data> Element links a given content with a machine-readable translation. If the content is time- or date-related, the <time> must be used. """ return el('data', *args, **kwargs)
c948ea946b29369b78fbda0564a822d7b9bb0a06
8,139
import traceback import os def process_dir(dir, doc_type = 'Annual Return', parallel = False): """ Process all document directories in a directory. Parameters ---------- dir : str Relative path to directory containing the document directories doc_type : str Type of documents (...
5d9dbb2d2df553b26ad94c306d282fa52c81baf1
8,140
import copy def get_crops(nodules, fmt='raw', nodule_shape=(32, 64, 64), batch_size=20, share=0.5, histo=None, variance=(36, 144, 144), hu_lims=(-1000, 400), **kwargs): """ Get pipeline that performs preprocessing and crops cancerous/non-cancerous nodules in a chosen proportion. Parameters ...
51bc314a8675790f83d0b6b7276e094986317187
8,141
def get_dict_from_args(args): """Extracts a dict from task argument string.""" d = {} if args: for k,v in [p.strip().split('=') for p in args.split(',')]: d[k] = v return d
8fb05329f6119393f94215808c6ab9b3116ec759
8,142
import warnings import cupy as cp from netver.utils.cuda_code import cuda_code def multi_area_propagation_gpu(input_domain, net_model, thread_number=32): """ Propagation of the input domain through the network to obtain the OVERESTIMATION of the output bound. The process is performed applying the linear combinat...
a81aad5e05b7054c5b7fc5016941ffc6abea5948
8,143
def opensslCmsSignedDataCreate( conveyedInfoFile, cert, privateKey ): """Create a signed CMS encoded object given a conveyed-info file and base64 encode the response.""" opensslCmdArgs = [ "openssl", "cms", "-sign", "-in", conveyedInfoFile, "-signer", cert, "-inkey",...
905ddbec7c252de6169f4fdedab19e0c6818fb39
8,144
import os def compute_kv(config): """Parse log data and calling draw""" result = {} for _cfg in config['data']: data = data_parser.log_kv(_cfg['path'], _cfg['phase'], _cfg['keys']) # clip from start idx if 'start_iter' in _cfg: start_idx = 0 for idx, iteration in enumerate(data['iter'])...
074563650c701820a8c8cf88b5cb56e25259f164
8,145
def change_app_header(uri, headers, body): """ Add Accept header for preview features of Github apps API """ headers["Accept"] = "application/vnd.github.machine-man-preview+json" return uri, headers, body
3610d1d482e057ba73a1901aed8430ff35d98f3b
8,146
def fib_fail(n: int) -> int: """doesn't work because it's missing the base case""" return fib_fail(n - 1) + fib_fail(n - 2)
6e8138b7ce330c9ab191367e3911fe8146240c25
8,147
def int2str(num, radix=10, alphabet=BASE85): """helper function for quick base conversions from integers to strings""" return NumConv(radix, alphabet).int2str(num)
6a7b6e7e090cccc20a0e0e3196e81f79cc5dabc5
8,148
def randomize_onesample(a, n_iter=10000, h_0=0, corrected=True, random_seed=None, return_dist=False): """Nonparametric one-sample T test through randomization. On each iteration, randomly flip the signs of the values in ``a`` and test the mean against 0. If ``a`` is two-dimensi...
2af8b9592f82b14dda1f59e41663e7253eb7dbe8
8,149
from typing import Optional from typing import Dict def git_get_project( directory: str, token: Optional[str] = None, revisions: Optional[Dict[str, str]] = None ) -> BuiltInCommand: """ Create an Evergreen command to clones the tracked project and check current revision. Also, applies patches if the ...
b4cc4e3335c6c91556d02c76761082d95baee775
8,150
import sys def main(args=None): """ec2mc script's entry point Args: args (list): Arguments for argparse. If None, set to sys.argv[1:]. """ if args is None: args = sys.argv[1:] try: # Classes of available commands in the commands directory commands = [ c...
a59c99d1c8f63f64ef69d45b7e19f239584ed7b0
8,151
def body_contour(binary_image): """Helper function to get body contour""" contours = find_contours(binary_image) areas = [cv2.contourArea(cnt) for cnt in contours] body_idx = np.argmax(areas) return contours[body_idx]
0ccfa7340d492f89c6c0090c296e7aede379754a
8,152
def rule_like(rule, pattern): """ Check if JsonLogic rule matches a certain 'pattern'. Pattern follows the same structure as a normal JsonLogic rule with the following extensions: - '@' element matches anything: 1 == '@' "jsonlogic" == '@' [1, 2] == '@' {'+': [1, 2]...
cd058d799cdee4d548c3e2075e1555ea28e594f1
8,153
def apt_repo(module, *args): """run apt-repo with args and return its output""" # make args list to use in concatenation args = list(args) rc, out, err = module.run_command([APT_REPO_PATH] + args) if rc != 0: module.fail_json(msg="'%s' failed: %s" % (' '.join(['apt-repo'] + args), err)) ...
d4572cb9d586b973d461e4ac33709e582c26dda7
8,154
from typing import Optional from typing import Dict from typing import Any import httpx async def get_data( *, config: Box, region: Region, start: Optional[int] = None, end: Optional[int] = None, ) -> Dict[Any, Any]: """Return a new consumer token.""" lookup = f"awattar.{region.name.lower(...
ed3795e1ae85f7bd65ce2f71fd922c261e993452
8,155
def get_rasterization_params() -> RasterizationParams: """ Construct the RasterizationParams namedtuple from the static configuration file :return: the rasterization parameters """ if cfg is None: load_cfg() # get rasterization section rasterization_dict = cfg[compute_dsm_tag][...
9adea0ffd838cbf3425cad5a0ab30bfe92829bc7
8,156
def rain_attenuation_probability(lat, lon, el, hs=None, Ls=None, P0=None): """ The following procedure computes the probability of non-zero rain attenuation on a given slant path Pr(Ar > 0). Parameters ---------- lat : number, sequence, or numpy.ndarray Latitudes of the receiver points...
728879dc2b51de813f8e1c83a99a8117883c423f
8,157
import os import glob def discover(paths=None): """Get the full list of files found in the registered folders Args: paths (list, Optional): directories which host preset files or None. When None (default) it will list from the registered preset paths. Returns: list: valid .js...
c793fb1b6096cc99f5a5f337517a34b34008e71f
8,158
import itertools def largets_prime_factor(num): """ Returns the largest prime factor of num. """ prime_factors = [] for n in itertools.count(2): if n > num: break if num%n == 0: prime_factors.append(n) while (num%n == 0): num = num/n return max(prime_factors)
12100b6cdc2e0553295c1803e699544aa930bbfb
8,159
import os def delete_md5(md5): """Delete the data of the file that has the MD5 hash.""" file = File.query.filter(File.md5 == md5).one_or_none() schema = FileSchema() result = schema.dump(file) if file is not None: filename = f"{result['file_name']}.{result['file_type']}" if not os....
7bfd1491805d7430ee02423cc739d364c17264ed
8,160
def compute_eigenvectors(exx, exy, eyy): """ exx, eyy can be 1d arrays or 2D arrays :param exx: strain component, float or 1d array :param exy: strain component, float or 1d array :param eyy: strain component, float or 1d array :rtype: list """ e1, e2 = np.zeros(np.shape(exx)), np.zeros...
524fe0cabeda91ca3086c3e46e88f19a919ff489
8,161
def name_looks_valid(name: str) -> bool: """ Guesses if a name field is valid. Valid is defined as being at least two words, each beginning with a capital letter and ending with a lowercase letter. :param name: the name to check :return: whether this name is considered valid """ existing_pa...
3f980ac4db9623c599733794253e6563abe698cb
8,162
import tqdm from pathlib import Path def convert_polygons_to_lines(src_polygons, dst_lines, crs=None, add_allone_col=False): """Convert polygons to lines. Arguments: src_polygons {path to geopandas-readable file} -- Filename of the the polygon vector dataset to be converted to lines. ...
7340eccc3b02f70d38967f3c325c968bcec67f26
8,163
def format_decimal(amount): """ jinja2 filter function for decimal number treatment """ amt_whole = int(amount) amt_whole_len = len(str(amt_whole)) if amount < 1: amt_str = '{:0.15f}'.format(amount).rstrip("0").rstrip(".") elif amt_whole_len < 4: amt_str = '{:0.3f}'.format(amount).r...
55ee4b6134abd409ade396233fa07061d0a30764
8,164
def remove_special_char(df, col): """Removes special characters such as % and $ from numeric variables and converts them into float""" df[col] = df[col].replace(regex = True, to_replace = r'[^0-9.\-]', value=r'') df[col] = df[col].astype("float") return df[col]
c6c4c86eb480d2f045e40b3eb831d0b8d5381d33
8,165
def getNonlinearInfo(numHiddenLayers, numBinary, unaryPerBinary): """ Generates a 2D list to be used as a nonlinearInfo argument in building an EQL/EQL-div model # Arguments numHiddenLayers: integer, number of hidden layers (i.e. layers including nonlinear keras layer components) ...
e62f8d016501ad48aeae09ebd8e61b659618e0b0
8,166
import types def construct_magmad_gateway_payload(gateway_id: str, hardware_id: str) -> types.Gateway: """ Returns a default development magmad gateway entity given a desired gateway ID and a hardware ID pulled from the hardware secrets. Args: gateway_id: ...
87826b72fd2f33a4a862ffbacbbce14f206dc086
8,167
import uuid import types import sys import traceback def endpoint(fun): """ REST HTTP method endpoints should use this decorator. It converts the return value of the underlying method to the appropriate output format and sets the relevant response headers. It also handles RestExceptions, which are...
794e99aede341eef177cf1b5e617613a0ee5aeb1
8,168
def script_rename_number(config): """ The scripting version of `rename_number`. This function applies the rename to the entire directory. It also adds the tags to the header file of each fits. Parameters ---------- config : ConfigObj The configuration object that is to be used for...
bd0c14cbec43644ed5b6e7b9e23e1c1f71f51984
8,169
def jasper10x4(**kwargs): """ Jasper 10x4 model from 'Jasper: An End-to-End Convolutional Neural Acoustic Model,' https://arxiv.org/abs/1904.03288. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chain...
4b8e210a619a28ca0d28ee6ba85fd7a7acf15335
8,170
def swap(lst, idx1, idx2): """ >>> swap([0, 1, 2], 0, 1) [1, 0, 2] >>> swap([0, 1, 2], 0, 0) [0, 1, 2] """ # print("Swapping [{}, {}] from {}".format(idx1, idx2, lst)) lst[idx1], lst[idx2] = lst[idx2], lst[idx1] # print("resulting to {}".format(lst)) return lst
81dee804db05eedaa1a9b5611e836a4c1da89b4b
8,171
def substring_index(column, delim=' ', cnt=1): """ Returns the substring from string ``column`` before ``cnt`` occurrences of the delimiter ``delim``. If ``cnt`` is positive, everything the left of the final delimiter (counting from left) is returned. If ``cnt`` is negative, every to the right of the fi...
b17fe73e19ece0d9e2511f8b45c43accb65f4138
8,172
def askPrize(mon: int) -> str: """ Args : n:欲查詢的期別 Returns: 查詢結果字串 """ (date, data) = initData(mon) date = f"{date}月\n" ssp_prize = f"特別獎:{data[0]}\n" sp_prize = f"特獎:{data[1]}\n" first_prize = f"頭獎:{data[2]}、{data[3]}、{data[4]}\n" six_prize = f"六獎:{data[2][5:]}、{...
1fcd388a38823a53719e8b50b02d2758b8ebe6dc
8,173
import pickle import tokenize def get_letters_df(letters_dict_pickle): """Get the letters Pandas Dataframe Parameters ---------- letters_dict_pickle: string Path to the dict with the letters text Returns ------- Pandas DataFrame Pandas DataFrame with a columns with the to...
f6c40627ae917d51ce30cd572bb02c378ca7f7e2
8,174
def lorenzmod1(XYZ, t, a=0.1, b=4, dz=14, d=0.08): """ The Lorenz Mod 1 Attractor. x0 = (0,1,0) """ x, y, z = XYZ x_dt = -a * x + y**2 - z**2 + a * dz y_dt = x * (y - b * z) + d z_dt = -z + x * (b * y + z) return x_dt, y_dt, z_dt
17dbd87b25968ca0e24b6e6fc602007932983f54
8,175
def binomial_p(x, n, p0, reps=10**5, alternative='greater', keep_dist=False, seed=None): """ Parameters ---------- sample : array-like list of elements consisting of x in {0, 1} where 0 represents a failure and 1 represents a seccuess p0 : int hypothesized number of successes in...
486257dfc1c517313556d08c8e2ad4ed3e85980d
8,176
def is_guild_owner() -> commands.check: """ Returns True under the following conditions: - **ctx.author** is the owner of the guild where this command was called from """ def predicate(ctx): if ctx.guild is None: raise commands.NoPrivateMessage('This command can only be used...
3f3c9a5d5990794bced7b021c646041e514e72ed
8,177
def round_grade(grade: int) -> int: """ Round the grade according to policy. Parameters ---------- grade: int Raw grade. Returns ------- rounded_grade: int Rounded grade. """ if grade < 38: rounded_grade = grade else: closest_multiple_5 = (gr...
8f1be9575d98b4ed24ff1e5904a5345d7ebc3e48
8,178
def patch_indecies(i_max: int, j_max: int, ps: int, pstr: int): """ Given the sizes i_max and j_max of an image, it extracts the top-left corner pixel location of all the patches of size (ps,ps) and distant "pstr" pixels away from each other. If pstr < ps, the patches are overlapping. Input: ...
6b760311513b3ded56f85690bab6622c999cc40d
8,179
def model_fn(): """ Defines a convolutional neural network for steering prediction. """ model = Sequential() # Input layer and normalization model.add(InputLayer(input_shape=(20, 80, 1))) model.add(Lambda(lambda x: (x / 255.0) - 0.5)) # Convolutional layer 1 model.add(Conv2D(filter...
42b85775635ee71ac6ed76f64170776eb36b5953
8,180
def authenticate(request): """Return the user model instance associated with the given request If no user is retrieved, return an instance of `AnonymousUser` """ token, _ = get_token_from_request(request) jwt_info = { 'token': token, 'case': TokenCase.OK, 'payload': None, ...
15d2d4343673cd30f2b201b834bd26889813d4ab
8,181
def _urpc_test_func_2(buf): """! @brief u-RPC variable length data test function. @param buf A byte string buffer @return The same byte string repeated three times """ return buf*3
f13f7dcf45eaa0706b69eb09c63d29ba2bbd3d60
8,182
from datetime import datetime def main(): """ Use Netmiko to connect to each of the devices. Execute 'show version' on each device. Record the amount of time required to do this """ start_time = datetime.now() for device in devices: print() print('#' * 40) output = show...
9182a63ea3e6a98d995c4ae00126175164cd6dfc
8,183
from typing import Iterable import warnings def infer_data_type(data_container: Iterable): """ For a given container of data, infer the type of data as one of continuous, categorical, or ordinal. For now, it is a one-to-one mapping as such: - str: categorical - int: ordinal - float: ...
9618aef33e45908dcb29981c52e8d53821c98642
8,184
import typing import subprocess def Preprocess( src: str, cflags: typing.List[str], timeout_seconds: int = 60, strip_preprocessor_lines: bool = True, ): """Run input code through the compiler frontend to inline macros. This uses the repository clang binary. Args: src: The source code to preprocess...
bc9bb6b451cf4d9883c4d76637871d244b490e86
8,185
def versionString(version): """Create version string.""" ver = [str(v) for v in version] numbers, rest = ver[:2 if ver[2] == '0' else 3], ver[3:] return '.'.join(numbers) + '-'.join(rest)
2feec3f8ac5a1f2b848d0805dfa0c3ff53a44ead
8,186
import warnings import builtins def any(iterable, pred): """Returns True if ANY element in the given iterable is True for the given pred function""" warnings.warn( "pipe.any is deprecated, use the builtin any(...) instead.", DeprecationWarning, stacklevel=4, ) return builti...
32f48ab7a6be329b8758ba3dbbe6721923890e11
8,187
import argparse import os def get_parser(): """ Parser of nuth kaab independent main TODO: To clean with main. Keep independent main ? """ parser = argparse.ArgumentParser( os.path.basename(__file__), description="Universal co-registration method " "presented in Nuth & Kaab...
9bc9e8318704ecd50bf504c54c24a1684146db42
8,188
def build_prev_df_n( dispositions) -> pd.DataFrame: """Build admissions dataframe from Parameters.""" days = np.array(range(0, n_days)) data_dict = dict( zip( ["day", "hosp", "icu", "vent"], [days] + [disposition for disposition in dispositions], ) ) proj...
e17ca1ab78e16aeaeac0afa5a1a9fa193cb9777f
8,189
import html def main() -> VDOMNode: """Main entry point.""" vdom = html("<{Heading} />") return vdom
c29d55ec4d469373e5504cc089e8370d0573a719
8,190
def GT(x=None, y=None): """ Compares two values and returns: true when the first value is greater than the second value. false when the first value is less than or equivalent to the second value. See https://docs.mongodb.com/manual/reference/operator/aggregation/gt/ for more details ...
62a4321d5d36306b9cc5b910e7eac0eec4d914f3
8,191
def pymongo_formatter(credentials): """Returns a DSN for a pymongo-MongoDB connection. Note that the username and password will still be needed separately in the constructor. Args: credentials (dict): The credentials dictionary from the relationships. Returns: (string) A f...
69216575258f297c368ec3015c1c14569bb82cd2
8,192
def sigma_disp_over_vcirc(gal, R=None): """The velocity dispersion over circular velocity computed at R=x*Rs [km/s]. Isotropic NFW is assumed. :param R: radius [kpc] :param gal: galaxy object """ # get Rs (rho, rs, c) = reconstruct_density_DM(gal, DM_profile='NFW') # make array of r, pre...
f05bb1f1a7ca2e0899ab67bb1c2a355236e3e810
8,193
def filters(param: str, default_value: str, base_key: str, key_manager: KeyManager) -> list: """Filter combo box selector for parameter""" update_type = '|filters|' row = combo_row(param, default_value, base_key, key_manager, update_type) return row
6645d369116d10cc4392810c9228f0e72fc21fd5
8,194
def get_scanner(fs_id): """ get scanner 3T or 1.5T""" sc = fs_id.split("_")[2] if sc in ("15T", "1.5T", "15t", "1.5t"): scanner = "15T" elif sc in ("3T", "3t"): scanner = "3T" else: print("scanner for subject " + fs_id + " cannot be identified as either 1.5T or 3T...") ...
f905bd16f3103b0c6c02193d30fb945646afb54c
8,195
def _find_query_rank(similarities, library_keys, query_keys): """tf.py_func wrapper around _find_query_rank_helper. Args: similarities: [batch_size, num_library_elements] float Tensor. These are not assumed to be sorted in any way. library_keys: [num_library_elements] string Tensor, where each column...
f3b002b77c77845681b35c3d6f629f6290324a47
8,196
def random_adjust_brightness(image, max_delta=0.2, seed=None): """Randomly adjusts brightness. """ delta = tf.random_uniform([], -max_delta, max_delta, seed=seed) image = tf.image.adjust_brightness(image / 255, delta) * 255 image = tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=255.0) re...
9d371ebb268708b983a523ce71a64103d3e46717
8,197
import re def get_assign_ops_and_restore_dict(filename, restore_all=False): """Helper function to read variable checkpoints from filename. Iterates through all vars in restore_all=False else all trainable vars. It attempts to match variables by name and variable shape. Returns a possibly empty list of assign_...
d93583c914bbe066b6a62d1f2041ab60cd511ab6
8,198
def log_creations(model, **extra_kwargs_for_emit): """ Sets up signal handlers so that whenever an instance of `model` is created, an Entry will be emitted. Any further keyword arguments will be passed to the constructor of Entry as-is. As a special case, if you specify the sentinel value `INSTANCE` as...
4eee202ccb335c658c1f6bf15b02f00955eb3da7
8,199