content
stringlengths
22
815k
id
int64
0
4.91M
def get_sha3_calculator(input_bytes): """ Returns object that can be used to calculate sha3 hash :param input_bytes: input bytes :return: object that can calculate sha3 256 hash """ if input_bytes is None: raise ValueError("Input is required") return keccak.new(digest_bits=eth_comm...
5,309,300
def validate_json_payload(payload): """Validates input data against a predefined JSON schema""" try: validate(payload, payload_schema) except ValidationError: raise InvalidUsage('JSON schema mismatch: please review your input data')
5,309,301
def gen_train_data(): """ Generate aligned training data to train a patch similarity function. Given some original images, generate lots of encoded versions. """ global encoded_train, original_train encoded_train = [] original_train = [] args = Xray(True) C = 100 for i in rang...
5,309,302
def Exec(content, global_scope, local_scope, filename='<unknown>'): """Safely execs a set of assignments. Mutates |local_scope|.""" node_or_string = ast.parse(content, filename=filename, mode='exec') if isinstance(node_or_string, ast.Expression): node_or_string = node_or_string.body def _visit_in_module(no...
5,309,303
def make_lf_ending(file): """Converts all crlf line endings to lf""" with open(file, 'rb') as in_file: content = in_file.read() content = content.replace(WINDOWS_LINE_ENDING, UNIX_LINE_ENDING) with open(file, 'wb') as out_file: out_file.write(content)
5,309,304
def alerts(): """ Endpoint to return and alerts we have :returns result: dict with array of dicts containing alert data """ result = dict() result['alerts'] = [] alert_list = Alert.query.all() for alert in alert_list: result['alerts'].append(alert.message) return jsonify(re...
5,309,305
def blast_search(queryfile: str, run: Fast5run, outfile=None): """ Search in a run by blast :param queryfile: path to fasta file with a query sequence :param run: Fast5run object, where to search :param outfile: path to file, where the output should be written """ blastn_cmd = 'blastn -out ...
5,309,306
def ff_multiplicative_inverse(a, modulus=0x11b): """ Based on extended Euclidean algorithm >>> hex(ff_multiplicative_inverse(0x53)) '0xca' """ b = modulus x0, x1 = 0, 1 while a: (q, a), b = ff_divmod(b, a), a x0, x1 = x1, x0 ^ ff_multiply(q, x1, modulus) _, r = ff_divmod(x0, modulus) return r
5,309,307
def list_own_groups(cm_id, caller_id): """ Method returns list of the groups caller is leader of. @clmview_user @response{list(dict)} dicts describing groups led by caller """ user = User.get(caller_id) # returns all the groups where the user is the leader return [g.dict for g in user...
5,309,308
def _oned_intFunc(x,twodfunc,gfun,hfun,tol,args): """Internal function for bovy_dblquad""" thisargs= copy.deepcopy(args) thisargs.insert(0,x) return integrate.romberg(twodfunc,gfun(x),hfun(x),args=thisargs,tol=tol)
5,309,309
def main(): """ONNX evaluation""" config = get_config() generator, (image_input_name, domain_input_name) = create_session(config.export_file_name, config.device_target) if not os.path.exists(config.result_dir): os.mkdir(config.result_dir) # Define Dataset data_path = config.celeba_imag...
5,309,310
def get_category(category_string, model=Category): """ Convert a string, including a path, and return the Category object """ model_class = get_cat_model(model) category = str(category_string).strip("'\"") category = category.strip('/') cat_list = category.split('/') if len(cat_list) ==...
5,309,311
def genselect(arr, inds): """Select some elements along the inds.ndim-th axis of arr. Takes arr of shape shape (a1, a2, …, am), and inds of shape (a1, a2, …, a(k-1), bk), where k <= m. The elements of inds index into the kth axis of a, allowing you to keep only a subset of "supercolumns" along a given a...
5,309,312
def move_agrd_filter_results(successes_info_by_depth_bound, timeouts_info_by_depth_bound): """Moves successes to new directory, but only if all instances at the relevant depth bound succeeded""" # loop through timeouts first to purge successes dict meta_files_by_out = dict() for depth_bound, timeout...
5,309,313
def info(_: Request) -> Response: """ Definition of the /info endpoint, in accordance with SEP-0038. See: https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0038.md#response """ info_data = {"assets": []} for asset in Asset.objects.filter(sep38_enabled=True): info_data...
5,309,314
def remove_nan(*args): """ *args: 1d arrays of the same length """ # Check input arrays have the same wavelegth # ... # Find bad pixels: nan, null or negative wavelengths mask = [] mask = np.ones_like(args[0], dtype=bool) for a in args: for i in np.arange(len(a)): ...
5,309,315
def test_simple_pub_single_handler(nsproxy, server): """ SYNC_PUB should work just like a normal PUB. This test checks normal behavior when using a single handler (i.e.: no filtering). When clients connect to a SYNC_PUB server, as long as they do not make requests, this communication pattern should...
5,309,316
def periodize_filter_fourier(h_f, nperiods=1, aggregation='sum'): """ Computes a periodization of a filter provided in the Fourier domain. Parameters ---------- h_f : array_like complex numpy array of shape (N*n_periods,) n_periods: int, optional Number of periods which should be...
5,309,317
def bounding_box_crop(x, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100): """Generates cropped_image using a one of the bboxes randomly distorted.""" ...
5,309,318
def store_data_to_sqlite(df, database_name, table_name): """ Store `df` to a sqlite DB. :param: df: `pandas.DataFrame` object :param: database_name: `str` object to name the database :param: table_name: `str` object naming the table :return: None """ # Load engine = create_engine(f'...
5,309,319
def create_backup_fixture(): """Mock create backup.""" with patch( "homeassistant.components.zwave_js.addon.async_create_backup" ) as create_backup: yield create_backup
5,309,320
def gen_lines(problem): """ Define three line probes in axial directions. Parameters ---------- problem : ProblemDefinition instance The current ProblemDefinition instance. Returns ------- probes : list The list of the probes. labels : list The list of p...
5,309,321
def authenticated_http_request(service_account, *args, **kwargs): """Sends an OAuth2-authenticated HTTP request. Args: service_account: Service account to use. For GCE, the name of the service account, otherwise the path to the service account JSON file. Raises: AuthenticatedHttpRequestFailure "...
5,309,322
def load_config(config_path): """ load a config from the given path """ conf = os.path.expanduser(config_path) if not os.path.exists(conf): print("No config file at location: %s. Add --config to specify\ location or run from dir containing config.py." % conf) return...
5,309,323
def _test_std_logging(): """Tests logs from std logging.""" std_logging.debug('std debug log') std_logging.info('std info log') std_logging.warning('std warning log') std_logging.error('std error log')
5,309,324
def add_extra_columns(df, datatype='sim'): """ Function to add to new columns to DataFrame that are commonly used Parameters ---------- df : pandas.DataFrame Input DataFrame datatype : str, optional Specify whether this is a DataFrame based on simulation or data (default is ...
5,309,325
def write_fit_summary(parameters, outfile): """Store fit results with uncertainties""" fit_results_dict = {} for parameter in parameters: value = parameter.value error = parameters.error(parameter) unit = parameter.unit name = parameter.name string = "{0:.2e} +- {1:.2...
5,309,326
def debug(message: str): """ Just an alias for `dogelog.log` with the DEBUG level. Note that this doesn't get written to stdout or the logfile if it is below filter level, which is the case when initialized with `dogelog.init` or `dogelog.init_colorless`. """ log(message, DEBUG)
5,309,327
def main(): """ Main function. """ urllib3.disable_warnings() args = parse_args() config_file = args.config_file with open(args.config_file, 'r') as fp: config_root = yaml.safe_load(fp) config_this = config_root.get(MYNAME, None) if config_this is None: raise Config...
5,309,328
def _search(json_, query): """Search for matching packages. :param json_: output json if True :type json_: bool :param query: The search term :type query: str :returns: Process status :rtype: int """ if not query: query = '' config = util.get_config() results = [ind...
5,309,329
def decode_image(uri: str) -> np.array: """ Translates image from base64 string to numpy array. """ data = uri.split(",")[1] data = BytesIO(base64.b64decode(data)) image = Image.open(data).convert("RGB") return np.array(image)
5,309,330
def solve_for_map(ds, m0, obs_mean, obs_std, m_packer, obs_packer, mask3D, mds, n_small=None,xdalike=None,dsim=None,dirs=None): """Solve for m_MAP $m_{MAP} = m_0 + H^{-1}F^T R^{-1}(d - F m_0)$ Parameters ---------- ds : xarray Dataset containing the EVD ...
5,309,331
def _is2darray(var, description): """checks if the array is 2D""" _isarray(var, description) if np.array(var).ndim != 2: raise TypeError("{} must be 2D array and not {}" .format(description, var))
5,309,332
def main(algo): """ main routine. """ container_tmp = json.load(open('data/container.json')) container = json_graph.node_link_graph(container_tmp, directed=True) request_tmp = json.load(open('data/request.json')) request = json_graph.node_link_graph(request_tmp, directed=True) rels = jso...
5,309,333
def str_q2b(ustring, skip_cn_punc=False): """ 全角转半角 """ return ''.join([q2b(uchar, skip_cn_punc) for uchar in ustring])
5,309,334
def quick_sort(data): """To sort data as an increase order by divide and conquer method.""" def q_sort(left_index, right_index): """Do quicksort recursively.""" if right_index <= left_index: return # Sort sub partition. part = partition(left_index, right_index) ...
5,309,335
def test_partition_lattice(size, true): """ """ lattice = partition_lattice(range(size)) assert len(lattice._lattice) == true assert lattice.top == {frozenset(range(size))} assert lattice.bottom == {frozenset({i}) for i in range(size)}
5,309,336
def test_zero_loss(): """check sparsemax-loss proposition 5""" # construct z and q, such that z_k >= 1 + max_{j!=k} z_k holds for # delta_0 = 1. z = np.random.uniform(low=-3, high=3, size=(100, 10)) z[:, 0] = np.max(z, axis=1) + 1.05 q = np.zeros((100, 10)) q[:, 0] = 1 np.testing.asser...
5,309,337
def downloadNotInSet(setPath): """Downloads all images that are not part of a set. Keyword arguments: setPath -- the name of the directory in which the images will be saved """ getNextPage = True page = 1 while getNextPage: photos = flickr.photos.getNotInSet(page=page, per_page=50...
5,309,338
def monitor(event, context): """ This method looks for security groups and reports any found groups to a json file in s3. """ groups = getAllSecurityGroups() if len(groups) is 0: logger.warning("no security groups found") return # get s3 key and body key = S3_MONITORING...
5,309,339
def load_8_color_data(shot, frames=range(5,12), remove_edges=True, data=False, start_n = 13, end_n = 46, ignore=[22]): """ This function automatically loads data from the tree and passes it on to the load_8_color function. When loading data this is generally the preferred method. """ MST_data = load...
5,309,340
def error(mixed): """Show error page for HTTP and form errors. :param mixed: String or actual catched exception. """ status = 400 trace = None if isinstance(mixed, string_types): page, error = mixed.split(':') message = ERRORS[page][error] else: message = mixed ...
5,309,341
def load_mnist(final = False, flatten = True): """ Load the MNIST data :param final: If true, return the canonical test/train split. If false, split some validation data from the training data and keep the test data hidden. :param flatten: :return: """ if not os.path.isfile('./data/mnist...
5,309,342
def get_connection_params(config): """ Creates instances of DatasetParams, SystemParams, DatasetToSystemParams, and CollectionParams for connection generation from config. """ dataset_params = DatasetParams( dataset_count=config["dataset"]["dataset_count"], dataset_env_count_map=proc...
5,309,343
def slope_id(csv_name): """ Extract an integer slope parameter from the filename. :param csv_name: The name of a csv file of the form NWS-<SLP>-0.5.csv :return: int(<SLP>) """ return int(csv_name.split("-")[1])
5,309,344
def onPlayerLogin(game, player): """ Event Hook: onPlayerLogin Print a little message when a player connects """ print(player.name + ' joined the server.') # Sync the inventory to the player pp = game.getModInstance('ServerMod').packetPipeline pp.sendToPlayer(SendInventoryPacket(player....
5,309,345
def log(message, level=logging.DEBUG, use_header=True): """Logs a message with a header.""" global log_header global logger header = (log_header or "") if use_header else "" logger.log(level, header + message)
5,309,346
def full_path_to_points(path): """ Find the corners of the path :param path: a list containing, a list of the x coordinates and a list of the y coordinates of the path :return:a list containing, a list of the x coordinates and a list of the y coordinates of the corners of the path """ points_x =...
5,309,347
def sample_architectures(mini: MiniNASParsedTabularBenchmark, n=10): """ sample some random architectures to train """ for i in range(n): print(i, '\t\t', mini.get_value_space().random_sample())
5,309,348
def check_parent_login(username, dob): """Checks if user input for their credentials is correct for parent's portal. :param username: student's PID (format: XXXNameXXXX) where X - integers :type username: str :param dob: User's Date of Birth :type dob: str :return...
5,309,349
def within_duration(date: dt, start: dt, end: dt, is_break: bool, term: int) -> bool: """ Check if the date is within the current duration If it is, print out the date as what week of the term or break it is and return True """ if not start <= date <= end: return False week = ((date...
5,309,350
def joblib(function, argument_list, num_cores=None): """Apply a univariate function to a list of arguments in a parallel fashion. Uses Joblib's delayed() function with a parallel executor that starts multiple processes. Args: function: A callable object that accepts one argument argume...
5,309,351
def read_input(filename): """read input file and return list of raw intcodes.""" with open(args.input, "r") as infile: raw_intcodes = infile.readlines()[0].strip().split(",") return raw_intcodes
5,309,352
def marketYesterday(token="", version="stable", filter="", format="json"): """This returns previous day adjusted price data for whole market https://iexcloud.io/docs/api/#previous-day-prices Available after 4am ET Tue-Sat Args: token (str): Access token version (str): API version ...
5,309,353
def r2_glmnet(cv_out, y): """calculate r2 using the lambda_1se. This value is for the most regularized model whose mean squared error is within one standard error of the minimal.""" # https://stackoverflow.com/questions/50610895/how-to-calculate-r-squared-value-for-lasso-regression-using-glmnet-in-r be...
5,309,354
def shift_x(x, shift_amt): """ Shifts (registers) the raster plot x by shift_amt """ shifted = np.zeros_like(x) for t in range(x.shape[1]): col = x[:,t] sh = shift_amt[t] shifted[:,t] = shift(col, sh) return shifted
5,309,355
def get_start_sig(line: dict, sched_line: m_sched.LineSchedule, i_stop): """select start signal from branching data and target signals of last stop""" i_prev = (i_stop - 1) % len(line["stops"]) target_signals = list(line["routing"][i_prev].values())[0]["next"] start_signal_str: str = target_signals[sch...
5,309,356
def minbox(points): """Returns the minimal bounding box necessary to contain points Args: points (tuple, list, set): ((0,0), (40, 55), (66, 22)) Returns: dict: {ulx, uly, lrx, lry} Example: >>> minbox((0, 0), (40, 55), (66,22)) {'ulx': 0, 'uly': 55, 'lrx': 66, 'lry': 0...
5,309,357
def update_workspace_acl(namespace, workspace, acl_updates, invite_users_not_found=False): """Update workspace access control list. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name acl_updates (list(dict)): Acl updates as dicts with two keys: ...
5,309,358
def resolve_cname(hostname): """Resolve a CNAME record to the original hostname. This is required for AWS where the hostname of the RDS instance is part of the signing request. """ try: answers = dns.resolver.query(hostname, "CNAME") for answer in answers: if answer.rdt...
5,309,359
def eye(num_rows, num_columns=None, batch_shape=None, dtype='float32'): """ :alias_main: paddle.eye :alias: paddle.eye,paddle.tensor.eye,paddle.tensor.creation.eye :old_api: paddle.fluid.layers.eye **eye** This function constructs an identity tensor, or a batch of tensor. Args: num_rows...
5,309,360
def check_by_selector(self, selector): """Check the checkbox matching the CSS selector.""" elem = find_element_by_jquery(world.browser, selector) if not elem.is_selected(): elem.click()
5,309,361
def _IsRetriableHTTPError(ret_value: Tuple[httplib2.Response, Text]) -> bool: """Determines whether the given HTTP exception is retriable. Args: ret_value: The return Tuple returned from the request method. Returns: Whether the exception can be retried. """ retriable_http_errors = (_TOO_MANY_REQUEST...
5,309,362
def write_csv(history, filename): """ Write Letterboxd format CSV """ if history: with open(filename, 'w', encoding='utf8') as fil: writer = csv.DictWriter(fil, list(history[0].keys())) writer.writeheader() writer.writerows(history) return True return Fal...
5,309,363
def apply_regression(df, w): """ Apply regression for different classifiers. @param df pandas dataframe; @param w dict[classifier: list of weights]; @return df with appended result. """ # get input if 'state' in df.columns: x = df.drop('state', axis=1).to_numpy(dtype='float64') ...
5,309,364
async def asset(request): """ Browse a particular asset for which we have recorded readings and return a readings with timestamps for the asset. The number of readings return is defaulted to a small number (20), this may be changed by supplying the query parameter ?limit=xx&skip=xx and it will not respe...
5,309,365
def get_geopandas_df(path): """ Creates geopandas dataframe from geeojson file at "path" filepath """ open_json = open_geojson(path) gdf = gpd.GeoDataFrame.from_features((open_json)) return gdf
5,309,366
def _drop_table_if_exists(table_name): """Drop the provided table if it already exists.""" print('Dropping {} (if such a table exists).'.format(table_name)) engine = connect.create_db_engine() engine.execute('DROP TABLE IF EXISTS {};'.format(table_name))
5,309,367
def plot_profile_curves(rot_dir_list, profile_file_name_list, output_fname, profile='rotation', ring_crop_list=[2], inner_ring_crop=0, label_list=['?'], color_list=[None]): """...
5,309,368
def fabs(x: DNDarray, out: Optional[DNDarray] = None) -> DNDarray: """ Calculate the absolute value element-wise and return floating-point class:`~heat.core.dndarray.DNDarray`. This function exists besides ``abs==absolute`` since it will be needed in case complex numbers will be introduced in the future...
5,309,369
def main(): """ takes a sdf file (can be gzipped) and converts it to a Schroedinger maestro (mae) file. """ parser = argparse.ArgumentParser() parser.add_argument("--input", help="input filename, type: .sdf.gz or .sdf") parser.add_argument("--output", help="output filename, type: .mae.gz or .mae...
5,309,370
def parse_acc_table(infile): """Parsing tab-delim accession table (genome_name<tab>accession) """ if infile == '-': inF = sys.stdin else: inF = open(infile) tbl = [] for line in inF: line = line.rstrip().split('\t') tbl.append(line) return tbl
5,309,371
def _parse_meme_motif(motif_line, f): """ Parse the next meme motif from the file. Parameters ---------- motif_line: string the motif name line f: file the open file, which should be pointing to the line immediately after the motif name line Returns ------- mot...
5,309,372
def get_lambda_cloud_watch_func_name(stackname, asg_name, instanceId): """ Generate the name of the cloud watch metrics as a function of the ASG name and the instance id. :param stackname: :param asg_name: :param instanceId: :return: str """ name = asg_name + '-cwm-' + str(instan...
5,309,373
def secondary_training_status_changed(current_job_description, prev_job_description): """Returns true if training job's secondary status message has changed. Args: current_job_description: Current job description, returned from DescribeTrainingJob call. prev_job_description: Previous job descri...
5,309,374
def request_movie_info(movie): """ Request movie information. :param movie: A movie object in Model. :return: Request json or None :type movie: Movie """ url = 'https://api.themoviedb.org/3/movie/' + str(movie.tmdb_id) query = { 'api_key': TMDB_APIKEY, 'language': 'ja-JP...
5,309,375
def event_source( handler: Callable[[Any, LambdaContext], Any], event: Dict[str, Any], context: LambdaContext, data_class: Type[DictWrapper], ): """Middleware to create an instance of the passed in event source data class Parameters ---------- handler: Callable Lambda's handler ...
5,309,376
def get_placeholders(arg, check_duplicates=False): """ Get all the placeholders' names in order. Use the regex below to locate all the opening ({{) and closing brackets (}}). After that, extract "stuff" inside the brackets. Args: arg: The word which this function performs searching on. ...
5,309,377
def safe_sleep(secs): """ Sleeps, even in the presence of signals. """ start = time.time() end = start + secs while start < end: time.sleep(end - start) start = time.time()
5,309,378
def rank_2d_int64(*args, **kwargs): # real signature unknown """ Fast NaN-friendly version of scipy.stats.rankdata """ pass
5,309,379
def test_vs_less_than_100_weight(kiali_client, openshift_client): """ VirtualService has only weight < 100 """ tests = ValidationsTest( kiali_client=kiali_client, openshift_client=openshift_client, objects_path=istio_objects_validation_path.strpath) tests.test_istio_objects( ...
5,309,380
def string_concat(str1, str2): """Concatenates two strings.""" return str1 + str2
5,309,381
def run_webserver(port=8080, hierarchy=False): """ Post a job to run a basic webserver to the job board :param int port: The port to use for the webserver :param bool hierarchy: Print the execution graph of the flow that would be posted :return None: """ post_job( simple_http_ser...
5,309,382
def _determine_upstream_ids( fid: str, df: pd.DataFrame, basin_field: str = None, downstream_field: str = None, basin_family: Optional[str] = None, ) -> pd.Series: """Return a list of upstream features by evaluating the downstream networks. Parameters ---------- fid : str feat...
5,309,383
def copy_binaries_and_libs(chroot, binarieslist, force_overwrite=0, be_verbose=0, check_libs=1, try_hardlink=1, allow_suid=0, retain_owner=0, try_glob_matching=0, handledfiles=[]): """copies a list of executables and their libraries to the chroot""" if (chroot[-1] == '/'): chroot = chroot[:-1] for file in binaries...
5,309,384
def remove_spaces(input_text, main_rnd_generator=None, settings=None): """Removes spaces. main_rnd_generator argument is listed only for compatibility purposes. >>> remove_spaces("I love carrots") 'Ilovecarrots' """ return input_text.replace(" ", "")
5,309,385
def length_vector(vector): """ Calculates the norm of a vector. """ return np.linalg.norm(vector)
5,309,386
def get(conanfile, url, md5='', sha1='', sha256='', destination=".", filename="", keep_permissions=False, pattern=None, verify=True, retry=None, retry_wait=None, auth=None, headers=None, strip_root=False): """ high level downloader + unzipper + (optional hash checker) + delete temporary zip """ ...
5,309,387
def get_vrf(arg = None, opts = None, abort = False): """ Returns VRF to work in Returns a pynipap.VRF object representing the VRF we are working in. If there is a VRF set globally, return this. If not, fetch the VRF named 'arg'. If 'arg' is None, fetch the default_vrf attribute from...
5,309,388
def init_calendar(): """ init calendar. The calendar initialization function is called to generate the calendar id when the system starts. :return: calendar id """ calendar_id = create_calendar() if calendar_id is None: raise Exception("init calendar failed.") return calenda...
5,309,389
def get_db(): """Opens a new database connection if there is none yet for the current application context. """ #if not hasattr(g, 'sqlite_db'): #g.sqlite_db = connect_db() con = connect_db() #return g.sqlite_db return con
5,309,390
def top_k_frequent_pq(nums: List[int], k: int) -> List[int]: """Given a list of numbers, return the the top k most frequent numbers. Solved using priority queue approach. Example: nums: [1, 1, 1, 2, 2, 3], k=2 output: [1, 2] 1. Get the counts of each items, and turn them into tuples. ...
5,309,391
def get_db_instance(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDBInstanceResult: """ Resource Type definition for AWS::Neptune::DBInstance """ __args__ = dict() __args__['id'] = id if opts is None: opts = pulumi.InvokeOptions...
5,309,392
def add(x, y): """Add 2 numbers together""" return x+y
5,309,393
def create_engine(*args, **kwargs): """Create a new Engine instance. The standard method of specifying the engine is via URL as the first positional argument, to indicate the appropriate database dialect and connection arguments, with additional keyword arguments sent as options to the dialect and ...
5,309,394
def rename_nonunique(windows): """Rename all windows which share a name by appending an index.""" window_names = [window.get("name") for window in windows] for name in window_names: count = window_names.count(name) if count > 1: for i in range(count): index = wind...
5,309,395
def init(): # pragma: no cover # type: () -> AnnotatorConfig """Combines passed arguments to create Annotator config.""" parser = create_argparser() args = parser.parse_args() config = AnnotatorConfig(args.config, os.environ, vars(args)) return config
5,309,396
def splitData(X, Y=None, train_fraction=0.80): """ Split data into training and test data. Parameters ---------- X : MxN numpy array of data to split Y : Mx1 numpy array of associated target values train_fraction : float, fraction of data used for training (default 80%) Returns ---...
5,309,397
def _lamb_next_mv_tbe(): """LambNextMV TBE register""" return
5,309,398
def wrap_cleverhans(model, attack_fn): """This should return (newmodel, (x,y,loss)) where newmodel has input connected x """ class Dummy(cleverhans.model.Model): def __init__(self, model): self.model = model def predict(self, x): return self.model(x) def fpro...
5,309,399