content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_framingham_data(fdir, fname='framingham_heart_study_exam7.csv'): """ Gets framingham heart study dataset: framingham_heart_study_exam7.csv: Data retrieved on 2015/10/28 from: http://sphweb.bumc.bu.edu/otlt/MPH-Modules/BS/BS704_Confidence_Intervals/BS704_Confidence_Intervals5.html :p...
77e61ac37a80e5f66710992015c7de009f8f95c5
63,000
from typing import List import tqdm def convert_examples_to_features( examples: List[InputExample], label_list: List[str], max_length: int, tokenizer: PreTrainedTokenizer, ) -> List[InputFeatures]: """ Loads a data file into a list of `InputFeatures` """ label_map = {label: i for i, l...
aad59a4fa9c1f9a82ab26e60d28ed5bf2c037e3c
63,001
def get_log_location(name): """ Return a Path object corresponding to the log file with name provided. The name will be cleaned to ensure it is a valid filename. """ name = utils.clean_filename(name) return get_log_dir() / f"{name}.log"
093ede7b820f7c145396a290a73f3eb03446ff0d
63,002
def list_remove(bin_name, index, ctx=None): """Create list remove operation. The list remove operation removes an item located at `index` in the list specified by `bin_name` Args: bin_name (str): The name of the bin containing the item to be removed. index (int): The index at which to remo...
b8583fc25dcbb8bcf1883a9a59889bc77386827c
63,003
import copy import multiprocessing def new_scan(): """ new scan through the API Returns: a JSON message with scan details if success otherwise a JSON error """ api_key_is_valid(app, flask_request) form_values = dict(flask_request.form) for key in nettacker_application_config: ...
5d49ddb3354f7a4783232f33fe327dcc8534c9b1
63,004
def sample_flight_time(parameters, arr_dep): """ Sample hour in 5-minute buckets """ profile = parameters["daily_demand"] assert 1440 % len(profile[arr_dep]) == 0 interval_len = 288 / len(profile[arr_dep]) minutes = sample_par_from_list(profile[arr_dep])[0] * interval_len * 5 minu...
77c8a09740a8892c84f10ddd578508cfb004a641
63,005
def modify_resnet_model(model, *, cifar_stem=True, v1=True): """Modifies some layers of a given torchvision resnet model to match the one used for the CIFAR-10 experiments in the SimCLR paper. Parameters ---------- model : ResNet Instance of a torchvision ResNet model. cifar_stem : bool...
00c7bcc9f0754da3049816ae8086597db17d4ffc
63,006
def gene_sym(symfile): """ One representative of each gene symbol is chosen. """ # TODO: change the selection from the first to the longest gene body # return {"refseq":["symbol","chr"]} fp = open(symfile) symdict = {} # {"gene_symbol": ["refseq_ID", "chr"]} the first refseq ID in the TS...
65fd23cd499ef48694f1564460aff270c93c0a8c
63,007
def format_review(__, data): """Returns a formatted line showing the review state and its reference tags.""" return ( "<li>[{state}] <a href='{artist_tag}/{album_tag}.html'>" "{artist} - {album}</a></li>\n" ).format(**data)
ab13b83c7ec317b23a7bdcc8e1d205fe2b77afbe
63,008
from io import StringIO def wparse(datafiles): """ Parses the file containing the SUMO-WordNet mapping. Args: - path: The path to the SUMO-WordNet mapping files Returns: - Dictionary """ mapping = dict() total, processed = 0, 0 for data, pos in datafiles: data.seek(0) ...
39218d316b4456372168ff350afb2c173bb3ca19
63,009
from unittest.mock import patch def create_message_handler(tmp_path): """Helper to create a message handler. Always in a temp directory, maybe with patched modes. """ temp_log_file = tmp_path / "test.log" patchers = [] def factory(modes=None): p = patch("tempfile.mkstemp", lambda pre...
e69ea095d1c8d7cf64f084d2ed0c7c1b236068d6
63,010
def stpColor(node_parent): """Find topnode Class and set tile_color""" node_top_name = nuke.tcl("full_name [topnode %s]" % node_parent.name()) node_top_class = nuke.toNode(node_top_name).Class() node_color = 0 if node_top_class.startswith('Roto'): node_color = 1908830719 # system roto class color elif node_to...
8d0f6ea3b9730060d27b861e4ef9b098788f9c35
63,011
async def list_packs( request: Request, namespace=None, configuration: Configuration = Depends(get_configuration)): """ WARNING: should not be used in prod: use allow filtering """ headers = generate_headers_downstream(request.headers) doc_db = configuration.doc_db where_...
838145f9b79bc977a7ea0114cf717370da75c377
63,012
from typing import Callable from typing import Optional from typing import Sequence from typing import Dict import copy import json import tempfile def create_custom_training_job_op_from_component( component_spec: Callable, # pylint: disable=g-bare-generic display_name: Optional[str] = '', replica_count:...
5569a2e3ba4478955564b58c9605b3fc47e33f40
63,013
def distance_between_nodes(source_node=None, target_node=None): """ Returns the distance between 2 given nodes :param str source_node: first node to start measuring distance from. If not given, first selected node will be used. :param str target_node: second node to end measuring distance to. If not giv...
1db376fe29e6a200345cf174a8e0b5a84e6bd841
63,014
def histogram(self, column_name, num_bins=None, weight_column_name=None, bin_type="equalwidth"): """ Compute the histogram for a column in a frame. The returned value is a Histogram object containing 3 lists one each for: the cutoff points of the bins, size of each bin, and density of each bin. Pa...
63c7a552f1c38f2059356301e4addf1b99e5f63c
63,015
def get_block(env, blockhash): """ Assumption: blocks loaded from the db are not manipulated -> can be cached including hash """ assert isinstance(env, Env) blk = rlp.decode(env.db.get(blockhash), Block, env=env) return CachedBlock.create_cached(blk)
02c23299b8903991179f5cfa94d45181b41f2e5b
63,016
def Drag(density, velocity, reference_area): """Calculates the drag force acting on the rocket. Args: density (float): From rocket.Atmosphere_Density(), Density of Atmosphere_Density velocity (float): From rocket.Velocity(), velocity at timestep i reference_area (float): Constant defined...
19626e4c11b21c2cd2c87be2970ced819509ed1b
63,017
def _execute4(*args, **kargs): """Return predefined results based on EXECUTE_TABLE4.""" cmd = args[1:-3] if args[0] == 'raidcom' else args result = EXECUTE_TABLE4.get(cmd, CMD_SUCCEED) return result
72b8b29b75c9561ee791ad82f3a9234d2077f2d1
63,018
import logging import click def generate_secret(number_rolls: int = 5, number_dice: int =5, how_many: int = 1, output_type: str = 'words', password_length: int = 20): """ Generate a password or passphrase with either random characters, words, or numbers. Optionally,...
678d3cd2976549e7617357272760cf24e454a7a3
63,019
def Error(msg): """ Helper class to raise parser errors. """ def raise_error(s, loc, toks): raise ParseFatalException(msg + "\n" + s) empty = Empty() empty.setParseAction(raise_error) return empty
dfcea16ad510e319e7441b4766e9d31f97600e86
63,020
import torch def minmax_to_xywh_torch(boxes: torch.Tensor) -> torch.tensor: """ :param boxes: :type boxes: :return: :rtype:""" xmin, ymin, xmax, ymax = boxes.unbind(1) return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1)
cc3fbc8aa246d030b0f52833c8a2f4383c380fe8
63,021
import ctypes def uiFormPointer(obj): """ Casts an object to uiForm pointer type. :param obj: a generic object :return: uiForm """ return ctypes.cast(obj, ctypes.POINTER(uiForm))
70150fcb522c4a3dc1b7c103aad9c8d8362c8ead
63,022
def random_abs(zobs,Wobs,Nrand,wa,fl,er,sl=3.,R=20000,FWHM=10.,wa0=1215.67,zmax=None,zmin=None): """From a list of observed redshifts (zobs) and observed rest-frame equivalent widths (Wobs), it creates a random catalog. For a given real absorber with Wobs it creates Nrand random ones at the new zrand, ...
34b5ee4588f030abecb69a093262a7bb38ac60db
63,023
def read_ref_energy(input_string): """ read in the reference energy """ pattern = ('RefEnergy' + one_or_more(SPACE) + capturing(FLOAT)) block = _get_training_data_section(input_string) keyword = first_capture(pattern, block) assert keyword is not None retur...
4f90b909b97ca77c5ad50e4283be37ce7f7476f0
63,024
def dnn_batch_normalization_train(inputs, gamma, beta, mode='per-activation', epsilon=1e-4, running_average_factor=0.1, running_mean=None, running_var=None): """ Performs batch normalization of the given inputs, using the mean and variance ...
17ad7da51bb83e71541b1744ee6f76e422d71946
63,025
def _plot_train_val_loss(model, title=None, figsize=(12,4)): """Plots training and validation loss on single plot.""" # Format title if title is None: title = model.history.params.get('name') + "\n" + \ "Training and Validation Loss" # Extract training and validation loss ...
ed86cf6aefee90c812a414f60176c0292642e4ea
63,026
import datasets def create_samples_from_MNIST(ds_name, img_size, img_invert=True, verbose=True): """create_samples from MNIST dataset returning samples_df with image attributes Args: ds_name ([type]): [description] img_size ([type]): [description] img_invert (bool, optional): [descrip...
0fa8ea695564845b784fc77371afd4780a4f9bbc
63,027
def is_unit_paused_set(): """Return the state of the kv().get('unit-paused'). This does NOT verify that the unit really is paused. To help with units that don't have HookData() (testing) if it excepts, return False """ try: with unitdata.HookData()() as t: kv = t[0] ...
05d7191e7340969d7d46215c65ba7ec9a15d2ae8
63,028
def int_value_provider(value, gettext): """Converts ``value`` to ``int``.""" if value is None or type(value) is int: return value value = str(value).strip() if value: s = thousands_separator(gettext) if s in value: value = value.replace(s, "") return int(value...
4461f7ebe181750215a9ad153bc7625accf7e5f5
63,029
def create_serial(*args, **kwargs): """ Creates a serial port with the args provided :return: The serial object :rtype: serial.SerialBase """ if _is_test_mode(): return mock_serial.Serial(*args, **kwargs) return serial.Serial(*args, **kwargs)
76d6d5f811703925bb5a53687554195bd5f536f8
63,030
def get_field_locs(working_data, fields): """ Finds fields index locations. Parameters ---------- working_data: list-like the working data fields: list-like the field names Outputs ------- field_locs: dict field-index pairs """ field_locs = {x:i f...
884c55211e9129222763b04c2e5cfc9ea4e371a3
63,031
def get_avg_spec(img, wlmin=0, wlmax=1e5, wls=None): """Return the wavelengths and mean spectrum within the specified img array. Optionally specify min and max wavelengths to crop spectrum.""" arr = np.nanmean(img, axis=(0, 1)) # Average along z (spectral) axis return get_spec(arr, wlmin, wlmax, wls)
2c90aab6402803b9aee84fe1454ff28b19fe229a
63,032
def get_py2exe_options(): """ Prepares and returns the py2exe options dictionary. """ # We don't really need a few of the pywin32 includes excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon", "pywin.dialogs", "pywin.dialogs.list", "win32com.server", 'curses', 'emai...
c8b27db5e495a2ed6bbe4ff0638a38586c053b0f
63,033
def add_category_to_first(column, new_category): """Adds a new category to a pd.Categorical object Keyword arguments: column: The pd.Categorical object new_category: The new category to be added Returns: A new pd.Categorical object that is almost the same as the given one, ...
78c2bb09e439bd941653e599f1c872e858195239
63,034
def normalize_padding(value): """A copy of tensorflow.python.keras.util.""" if isinstance(value, (list, tuple)): return value padding = value.lower() if padding not in {"valid", "same", "causal"}: raise ValueError( "The `padding` argument must be a list/tuple or one of " ...
43ba467adf0c9c32323dd5bf87f798b640932417
63,035
from pathlib import Path def x2char_star(what_to_convert, convert_all=False): """ Converts `what_to_convert` to whatever the platform understand as char*. For python2, if this is unicode we turn it into a string. If this is python3 and what you pass is a `str` we convert it into `bytes`. If `conv...
a612063372d22e5ef310356c74981b6e5f8f12bd
63,036
import random def random_key(minor=False, output_on=True): """Returns a random major or minor key. Minor in lower case, major in upper case.""" keys = ['A', 'Bb', 'B', 'C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab'] key = random.choice(keys) if minor and random.choice([0, 1]): # minor or major ...
c0e5597c9d0931af6c7a8d62fbe827918ea4a09c
63,037
def mk_cert(): """ Make a certificate. Returns a new cert. """ cert = X509.X509() cert.set_serial_number(2) cert.set_version(2) mk_cert_valid(cert) cert.add_ext(X509.new_extension('nsComment', 'SSL sever')) return cert
ac6baee6dfbf4a6af8a0ac050291d4b4fa45d0d9
63,038
def just_words(df): """ remove all punctuation from given DataFrame :param file_data: DataFrame :return: DataFrame """ df = df.query('POS != "y"').query('POS != "\\""') return df[df["POS"].notnull()]
ab69d1ae9a2c55b8ba8b6cc353b0ffe8a734b1b2
63,039
def _read_tf(trans_func_loc): """ Returns a 1D interpolated function of input """ trans_func = _initialise(trans_func_loc) x_axis = np.array([i for i in trans_func['ws']]) y_axis = np.array([j for j in trans_func['trans']]) return interpolate.interp1d(x_axis, y_axis)
8f3176e04c6153d19b5fc22c32a5391be5af940c
63,040
import urllib import shutil def url_fetch(url, filename='', attempts=0, interval=0): """ Fetches an URL into a file or returns a file descriptor. If attempts and interval are not specified, they get their values from brisa.url_fetch_attempts and brisa.url_fetch_attempts_interval. @param url: URL to b...
8a9fcf6c6680b5a121084364ef93a1b1faed8470
63,041
from datetime import datetime def datetime_to_timestamp(value): """Converts UTC datetime to integer timestamp in microseconds since epoch.""" if not isinstance(value, datetime.datetime): raise ValueError( 'Expecting datetime object, got %s instead' % type(value).__name__) if value.tzinfo is not None...
8da729c86e3ba78a627859dd27528644b1a97f31
63,042
import os def qac_ingest(tp, tpout = None, casaworkaround=[1,3], ms=None, ptg=None): """ Check (and optionally correct) that a TP image is a valid input for TP2VIS. This is also meant as a workaround certain CASA features (see bugs.txt) Currently you will need CASA 5.0 or above. Inputs: tp ...
808f4c5fbfd87538f0c749f36c3eed935ee07382
63,043
def require_one_of(_return=False, **kwargs): """ Validator that raises :exc:`TypeError` unless one and only one parameter is not ``None``. Use this inside functions that take multiple parameters, but allow only one of them to be specified:: def my_func(this=None, that=None, other=None): ...
294bbb73136fd722a3b998881ef491977c2d0639
63,044
def api_program_level_ordering(request, program): """Returns program-wide RF-aware ordering (used after indicator deletion on program page)""" try: data = ProgramLevelUpdateSerializer.update_ordering(program).data except Program.DoesNotExist: logger.warning('attempt to access program page or...
5eac23bcc0ce3f177eefaa13ce62b89838fd0b5d
63,045
import torch def log2(input_): """Wrapper of `torch.log2`. Parameters ---------- input_ : DTensor Input dense tensor. """ return torch.log2(input_._data)
36943a41cf908973cf03278ea24858810e6b9f89
63,046
def points_from_mesh(mesh, invertZ = True): """ Create a point cloud (represented as a PointSet) from a visvis mesh object, or from a filename pointing to a .stl or .obj file. """ if isinstance(mesh, str): mesh = vv.meshRead(mesh) if invertZ == True: for vertice in mesh._vertices: ...
1bd60ff42bd018624cacf0522fa61be9d81743b7
63,047
import torch def split_mask_upsample(orig_mask, split_masks, crop_indices): """Upsample split masks to original size. Args: orig_mask: a [H, W] torch.FloatTensor of values in {0, 1} split_masks: a [H', W'] torch.FloatTensor of values in {0, 1, 2, ...} crop_indices: a [4] torch.FloatTe...
0560d1c05f042d090aaab9fe6ad3cfa75e144a53
63,048
def get_context_command_parameter_converters(func): """ Parses the given `func`'s parameters. Parameters ---------- func : `async-callable` The function used by a ``SlasherApplicationCommand``. Returns ------- func : `async-callable` The converted function. ...
b72941bfb62e2be79ee916cf101e2d820c92ffc8
63,049
def calculate_previous_version(version: str, is_point: bool) -> str: """Calculate the previous version to compare to. In the case of -rc to final that verison is the previous .0 release, (19.3.0 in the case of 20.0.0, for example). for point releases that is the last point release. This value will be t...
a1591454f307bd3180c65f3c908de870092debe5
63,050
from clubs.views import find_relationship_helper def find_membership_helper(user, club): """ Finds the membership instance in the family tree of a club with the most authority. Returns None if there is no membership between the specified club and user. """ related_codes = codes_extract_helpe...
3556336b8f60a6e4092233c5793c170d9acef14e
63,051
def fib(n): """Print the Fibonacci series up to n.""" a, b = 0, 1 c = [] while b < n: c.append(b) a, b = b, a + b return c
8f46ccc2c6bcde70b370408dcf1c5f02f8b3b588
63,052
def all_neighbor_distances(lat,vector_table,cell_rad = 1): """ Creates an n x n*(1+2*cell_rad)**3 table of bond lengths between all n atoms in the unit cell and every atom in the same unit cell and the (1+2*cell_rad)**3 -1 surrounding cells (the cell_rad number of layers of cells surrounding the c...
91190085bf5398f6b7a0a183ac8d8246eb2de459
63,053
def convert_board2san(coord): """ Takes a PRE-VALIDATED coordinate of the form: tuple(row, col) Returns a coordinate in SAN (Standard Algebraic Notation) : "a4" or "h6" for example Completely capable of crashing the program if input is not valid """ result = [] if coord: rank =...
a3ad0384822cd0d4b0ec86ac7f33167065c977de
63,054
def upgrade_repos(c: InvokeContext, pull_master: bool = True, pull_develop: bool = True, run_scripts: bool = False): """ Update your repos. :argument pull_master - Should we pull down the latest master :argument pull_develop - Should we pull down the latest develop(will skip if not defined in config...
5902df7054a081783f73a729c3b8f1a7be370261
63,055
def basic_segment_classifier(dir, out_model): """ Train audio models :param dir: directory which contains audio organized in folders of classes :param output_model: path to save the output model :return: None """ basic_features_params = config['basic_features_params'] feature_ext...
7f53d686b0b0cad6872d9953fec6a8db12972bdb
63,056
def fixed_axion_routine(ga_ref, output, source_input=default_source_input, data=default_data, Snu_echo_kwargs=default_Snu_echo_kwargs ): """ Computes the full echo routine of both source and echo for a fixed referenc...
4d63b995dd1d77e85b15eb366832dc2e91fa64e6
63,057
def delDotPrefix(string): """Delete dot prefix to file extension if present""" return string[1:] if string.find(".") == 0 else string
792d4f72dcbc641de5c3c11f68a78c73fa0d9ecd
63,058
def afx_adafactor(): """Adafactor with recommended learning rate schedule.""" hparams = afx_adam() hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_warmup_steps = 10000 return hparams
70686e309e00d8068885e48598a026c7eb26a3fd
63,059
import subprocess import sys def run_cmd(cmd, error_message='', input=None, log_error=True, exit=False): """Run a command, optionally logging error message if return code not zero. Exit program on error if required.""" p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdi...
cbc0f06757db81a714ede032a459efeb8b2fd172
63,060
def str_compare(str1: str, str2: str) -> bool: """문자열 비교 Parameters ---------- str1: str string str2: str string Returns ------- bool 문자열이 동일하다면 True """ str1 = str1.strip().lower() str2 = str2.strip().lower() return str1 == str2
a4e0d6d88b28b2851b1403ab63c8e808e16d60ab
63,061
import sys from pycaret.utils import __version__ import logging import secrets from platform import python_version, platform, python_build, machine import psutil from pandas import __version__ from numpy import __version__ from sklearn import __version__ from kmodes import __version__ from mlflow.version import VERSION...
7657f3ba13245fff4ec1601fbb936e3fa1466dd3
63,062
from typing import TextIO from typing import Optional def next_line(fh: TextIO) -> Optional[str]: """ Return the next line from a filehandle """ try: return next(fh).rstrip() except StopIteration: return None
92077359720b6ac72637943d86c7ab6250158194
63,063
def define_form(request, hostname): """ Ajax page for updating compute node settings. """ node = get_node(request, hostname, sr=('owner',)) form = NodeForm(request, node, request.POST) if form.is_valid(): status = form.save(args=(hostname,)) if status == 204: return ...
d47aee2abc7dfb4a604d9b164e4c6aa019bc1fec
63,064
def hash_suffix(path, reclaim_age): """ Performs reclamation and returns an md5 of all (remaining) files. :param reclaim_age: age in seconds at which to remove tombstones """ md5 = hashlib.md5() for hsh in sorted(os.listdir(path)): hsh_path = join(path, hsh) try: fil...
0a3f19c7eb466bdcb1f6d83d9fd5193fab1515a2
63,065
def get_ua(): """Get first user agent in the 'user_agents' list Returns: str: User agent """ return user_agents[0]
02effeede93e729b4cb953d235890601328bf42f
63,066
def drop_dimension(data, name) -> ProcessBuilder: """ Remove a dimension :param data: The data cube to drop a dimension from. :param name: Name of the dimension to drop. :return: A data cube without the specified dimension. The number of dimensions decreases by one, but the dimension prope...
b67a7b347554105d5c088a0fed5a0cac29f2e85d
63,067
def locations(): """Fetches and displays the locations in Delhi""" status, body = api.locations(city='Delhi') return str(body['results'])
17a02bad20b0c4ab3d86f5b726f0bc800c7897fe
63,068
import numpy import scipy def _golbub_welsch(orders, coeff1, coeff2): """Recurrence coefficients to abscisas and weights.""" abscisas, weights = [], [] for dim, order in enumerate(orders): if order: bands = numpy.empty((2, order)) bands[0] = coeff1[dim, :order] ...
7edd7918c33482b3d33b49e9c90dfeab4f73fc6d
63,069
import array def solve(self): """Compute the parameters dict for the equivalent electrical circuit cf "Advanced Electrical Drives, analysis, modeling, control" Rik de doncker, Duco W.J. Pulle, Andre Veltman, Springer edition <--- ---> -----R-----wsLqIq-...
c24cb121508e0ef1b079d59192c2876712c4b11a
63,070
def register(request): """A view that manages the registration form""" if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): user_form.save() user = auth.authenticate(email=request.POST.get('email'), ...
44f61c8ff8b55e11a544eec098ad93fcbea6a2b2
63,071
from typing import Union def reference(context: RuntimeContext, x: Union[ObjectRow, str]): """YAML-embeddable function to Reference another object.""" if hasattr(x, "id"): # reference to an object with an id target = x elif isinstance(x, str): # name of an object obj = context.field_vars...
fc5dd50caf998cf351f89627db9551dff444d64c
63,072
def merge_coordinate_molecular(coor, lattice, wyckoffs, w_symm_all, tol, orientations, PBC=[1,2,3]): """ Given a list of fractional coordinates, merges them within a given tolerance, and checks if the merged coordinates satisfy a Wyckoff position. Used for merging general Wyckoff positions into special ...
1c21fd7f2dbe1ddc6acb0d70790cf67d1d4fce53
63,073
def _validate_perf_config(config_contents, required_parameters): """Validates the perf config file contents. This is used when we're doing a perf try job, the config file is called run-perf-test.cfg by default. The parameters checked are the required parameters; any additional optional parameters won't be c...
052244699de20ea18453efccb0c4ae01080d7678
63,074
def insert(root: Node, value: int) -> Node: """ Insert element Split current tree with a value into left, right, Insert new node into the middle Merge left, node, right into root """ node = Node(value) left, right = split(root, value) return merge(merge(left, node), right)
529ffce8f107a40cd161f10b6a77a65c0ed363ba
63,075
def get_thickness_stats_for_both_hemispheres(subjects_dir, subject_id, mask_file): """ This function.. :param subject_id: :param subjects_dir: :param mask_file: :return: """ stats = dict() lh_thickness, rh_thickness = get_thickness_files_for_both_hemispheres( subjects_dir, s...
d82c9bb9af3e9a505097e652ff95598998d17cbb
63,076
from typing import Iterable from typing import Callable from typing import Tuple from typing import List def segment(iterable: Iterable[P], filter: Callable[[P], bool]) -> Tuple[List[P], List[P]]: """ :param iterable An iterable bunch of data to be split into two :param filter A filter to run over each el...
89daed0cdf3577f10afd12b740bd37cdd271bf12
63,077
def uridefrag(uristring): """Remove an existing fragment component from a URI string.""" parts = uristring.partition('#') return DefragResult(parts[0], parts[2] if parts[1] else None)
dd211bac44834a481a3f8bbc018992df36fd8e8b
63,078
import os def read_version(setup_file, name, default_value=None, subfolder=None): """ Extracts version from file `__init__.py` without importing the module. :param setup_file: setup file calling this function, used to guess the location of the package :param name: name of the package ...
5facdfc402fe4545f5a2f0e8b5de2b8fc4079c64
63,079
def getExtraAtomInfo(model, useNeutronDistances = False, probePhil = None): """ Helper function to provide a mapper for ExtraAtomInfo needed by Probe when scoring models. It first tries to find the information in CCTBX. If it cannot, it looks the information up using the original C-code Probe tables and...
d447f449cf923870d436699416a115f44e5c656b
63,080
from re import L def _miso_op(data_list, func, *args, **kwargs): """Create multi input and single output Caffe op""" n = caffe.NetSpec() if not isinstance(data_list, (tuple, list)): raise TypeError("Need tuple or list but get {}".format(type(data_list))) input_list = list() for idx, data i...
02cdd3c38c3ff027a5ef748eeb5fddd55f735fff
63,081
def autodl_auc(solution, prediction, valid_columns_only=True): """Compute normarlized Area under ROC curve (AUC). Return Gini index = 2*AUC-1 for binary classification problems. Should work for a vector of binary 0/1 (or -1/1)"solution" and any discriminant values for the predictions. If solution and predict...
f1a810fd5bce751bfdcea4021444a55a2eb7618c
63,082
def dectobin(x): """Convert Decimal to Binary. Input is a positive integer and output is a string.""" ans = '' while x > 1: tmp = x % 2 ans = str(tmp) + ans x = x // 2 ans = str(x) + ans return ans
21a6c0c161088f1e73afe87707503667b4651c87
63,083
import functools import os def need_issue(fn): """Post-parse args to create a Rietveld object.""" @functools.wraps(fn) def hook(parser, args, *extra_args, **kwargs): old_parse_args = parser.parse_args def new_parse_args(args=None, values=None): options, args = old_parse_args(args, values) a...
77cb499c11a77609a18bef8963990b5fe54be1da
63,084
def normalize_signals(signals) -> np.ndarray: """ Normalizes the data based on the variance Args: signals: (U x T) data streams Returns: Normalized (U x T) data streams """ signals = signals - np.min(signals, axis=1).reshape(signals.shape[0], 1) return signals / (3 * np.std(s...
412d3213e5d84d227f949f3d04fd7c9915784c6c
63,085
def muscovite(): """ Elastic constants of muscovite mineral (GPa) from Vaughan and Guggenheim (1986), in Voigt notation - Abbreviation: ``'ms'`` Returns: (tuple): tuple containing: * C (np.ndarray): Elastic stiffness matrix (shape ``(6, 6)``) * rho (float): Density ...
c16439359688042114460e6fb70b64c4fc740f1b
63,086
def fftshift(x, axes=None): """ Shift the zero-frequency component to the center of the spectrum. This function swaps half-spaces for all axes listed (defaults to all). Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. Parameters ---------- x : array_like, Tensor ...
1fc2d602ef282ed9897967904a37098b018049e1
63,087
import hmac import base64 import hashlib def gen_signature(url: str, signed_nonce: str, nonce: str, data: str) -> str: """Request signature based on url, signed_nonce, nonce and data.""" sign = '&'.join([url, signed_nonce, nonce, 'data=' + data]) signature = hmac.new(key=base64.b64decode(signed_nonce), ...
e5ae94aa83711bec555eb4adec5b8d9e4985c3bc
63,088
def get_comment_url_xml(content_object, parent=None): """ Wraps ``get_comment_url_ajax`` with ``ajax_type='xml'`` """ try: return get_comment_url_ajax(content_object, parent, ajax_type="xml") except template.TemplateSyntaxError: raise template.TemplateSyntaxError, "get_comment_url_xm...
2810edb8f2f94c4acad2b8d5da901ea34f81762f
63,089
def create_connection_from_config(): """ Returns Google API client for Compute. It detects credentials for Service accounts and User accounts. """ credentials = ServiceAccountCredentials.get_application_default() return googleapiclient.discovery.build( 'compute', 'v1', credentials=credentials)
90228f9214952db05e7bfb09826fd7bb56b14f12
63,090
def getrevstofix(ui, repo, opts): """Returns the set of revision numbers that should be fixed""" if opts[b'all']: revs = repo.revs(b'(not public() and not obsolete()) or wdir()') elif opts[b'source']: source_revs = scmutil.revrange(repo, opts[b'source']) revs = set(repo.revs(b'(%ld::...
5cad3f34b2665eb12f01cce824589ad33af1963e
63,091
def mpin_server_1(mpin_id, date): """Calculate HID and HTOD.""" HID = mpin.ffi.new("octet*") HIDval = mpin.ffi.new("char []", mpin.G1) HID[0].val = HIDval HID[0].max = mpin.G1 HID[0].len = mpin.G1 # H(T|H(ID)) HTID = mpin.ffi.new("octet*") HTIDval = mpin.ffi.new("char []", mpin.G1) ...
a7be876896683f397bf1e002cdb06a2adbcf99d9
63,092
def plot_curve_metric(x, y, auc, curve_type, title=None, labels=None): """ Plot ROC or PRC curves per output channel. Args: - x (dict) - Dict of numpy arrays for values to plot on x axis. - y (dict) - Dict of numpy arrays for values to plot on x axis. - auc (dict) - Dict of numpy arrays for...
587cfe2d7298e0e726fd02078a8ec1416e2f82e3
63,093
def get_coordinate_dimensions(geometry): """Returns the dimensionality of the coordinates in a geometry (2 or 3). Returns -1 for not-a-geometry values. Parameters ---------- geometry : Geometry or array_like Examples -------- >>> get_coordinate_dimensions(Geometry("POINT (0 0)")) ...
12daf75dd668f57c332349ba7b19d15e0f6c4f95
63,094
def task_name(task): """ Compute the task name for an Eliot task. If we can't find a ``message_type`` or an ``action_type`` field to use to derive the name, then return ``None``. """ if task is None: raise ValueError('Cannot compute task name', task) level = u','.join(map(unicode, t...
9183e91dd898ae71c66a7d2c3bd44d8c7ef5f775
63,095
def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" ...
5bf4561d16a50965fc32fe19df71e7072f24e551
63,096
def get_backend(project_type = None, project = None, logger = None): """ project_type is a string, like 'svn' project is a Project """ if project_type is None: project_type = project.project_type pass klass = backend_registry.get(proj...
18a2c2f5843616a50523706fff1f6e57a0d844ac
63,097
def create_entity(entity_name): """Add an entry to an array-type entity .. :quickref: Model; Add an entry to an array-type entity :param entity_name: Name of the entity """ model = read_model() new_entity = request.get_json() key_field = get_key_field(new_entity) entities = model['inp...
56695fd0996f5a2c8ea09d7b52376211bbabff0e
63,098
import scipy import sys def calc_performance_all(performance, csv_lines): """ Calculate model performance over all sections. """ csv_lines.append(["", "", "AUC", "pAUC", "precision", "recall", "F1 score"]) amean_performance = np.mean(np.array(performance, dtype=float), axis=0) csv_lines.append...
3dea955bac63d4296d6ae3f813ce255fbc4ee3cf
63,099