content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_mentornet_network_hyperparameter(checkpoint_path): """Get MentorNet network configuration from the checkpoint file. Args: checkpoint_path: the file path to restore MentorNet. Returns: a named tuple MentorNetNetHParams. """ if checkpoint_path and tf.gfile.IsDirectory(checkpoint_path): che...
3f7c8f056cec574e11027178b82652e5daa25989
46,500
def densenet(images, num_classes=1001, is_training=False, dropout_keep_prob=0.8, scope='densenet'): """Creates a variant of the densenet model. images: A batch of `Tensors` of size [batch_size, height, width, channels]. num_classes: the number of classes in the dataset. is_training: specifies whether or not ...
7b444de908bb13c0403082895451f87211c2793a
46,501
from typing import List from functools import reduce def product(li: List[int]) -> int: """Calculates the product of all the numbers in a list. doctests: >>> product([2, 1, 4]) 8 >>> product([3, 1, 4, 2, 5, 8]) 960 """ x = reduce(lambda a, b: a * b, li) return x
8afe00bb6056accc694ab955a48b6be85d8a30bf
46,502
def CDLDOJI(data: xr.DataArray) -> xr.DataArray: """ Doji (Pattern Recognition) Inputs: data:['open', 'high', 'low', 'close'] Outputs: double series (values are -1, 0 or 1) """ return multiple_series_call(talib.CDLDOJI, data, ds.TIME, ds.FIELD, [f.OPEN, f.HIGH, f.LOW, f.CLOSE], ...
73130fe5309c279b79e12738acee0433a4f78aee
46,503
def filename(N, epsilon, v0, D, Dr, phi, launch): """ Name of simulation output files. Parameters ---------- N : int Number of particles in the system. epsilon : float Coefficient parameter of potential. v0 : float Self-propulsion velocity. D : float Tran...
7fb6c9cfc081caaacc447c4e1869030ef2b00ff3
46,504
def g2c(coordinate:tuple, pixel_unit:int) -> tuple: """ Convert pygame coordinate to cartesian coordinate. x pixel unit refers to 1 unit in cartesian coordinate system. For example: if pixel unit is 100 then 100 pixel is one unit in cartesian system coordinate: game coordinate (x,...
16c93158145edf1454c31aaede426f99639f34a7
46,505
async def site_base(): """Return the configured site prefix. Useful for correct client-side routing.""" return conf().metador.site
729c72428baf914a91e5970f3d7c931283690986
46,506
from typing import Dict from typing import List def filter_labels( label_dict: Dict[str, np.ndarray], filter_dict: Dict[str, List[int]] ) -> Dict[str, np.ndarray]: """Filter out examples from arrays based on specified labels to filter. The most common use of this method is to remove examples whose gold l...
f5d0402bee3947d4c248320842750ec3613c5b30
46,507
from typing import Sequence from typing import Dict from typing import Any def get_view_report_fields_list(report: str) -> Sequence[Dict[str, Any]]: """Gets the fields in the report month view :param report: the kind of the report :returns: list of fields in this report's month view""" report_fields ...
af6d96acaec6d7b7d44f402b8edd09f354bdfa91
46,508
def parse_options() -> Namespace: """ Parse command line arguments and liftoff configuration. """ opt_parser = OptionParser( "liftoff-status", ["experiment", "all", "timestamp_fmt", "results_path"] ) return opt_parser.parse_args()
cff274096dd9a74bce62867f2519e93b11c4521b
46,509
def generate_betas_inertia(time_periods: int) -> np.ndarray: """ Generate an array of beta_inertia values for t time periods """ betas = np.empty(time_periods) taste_shocks = np.random.normal(loc=0, scale=src.const.taste_shock_std, size=time_periods) b0 = np.clip(np.random.normal(loc=src.const....
1bbc2a9f29206f7086874e9bb0992a8ee3ce7927
46,510
def create_graph_hac(env, n_layers, n_steps, subtask_specs, level_algo_kwargs_list): """Create and return HAC graph.""" # If buffer size not specified, set it such that all transitions will fit into buffer # (assuming that the episodes always last for env.max_episode_length which is not the # case in ...
c0b8ac527bc03d2b30c1eb0709985c2365528a78
46,511
def add_cartesian_dummy(odf: dc_dd) -> dc_dd: """create a dummy dataframe with a column "cartesian" with the value 0 to force a cartesian join using merge. Args: odf (dc_dd): original dask_cudf or dd Returns: dc_dd: dummy dask_cudf or dd """ odf["cartesian"] = 0 odf = du.sh...
406d58869b2a49b7cbcb6528b9746b2320e8a8e0
46,512
import os def parse_fname(fname): """ Returns dictionary of parameters encoded in file name. Assumes structure: der/<name1>-<unit1><val1>_<name2>-<unit2><val2>_<note1>_<note2>/trial_v<version>.txt No numbers are allowed in the name, unit, or note fields """ #assumes <path tail>/data/<date>...
ac3923653af311c85da28d52ff75b1c7cd41506e
46,513
def get_etl_pipeline_ids(client): """Return a dict mapping pipeline ids to their names, filtering on ETL pipelines.""" paginator = client.get_paginator("list_pipelines") response_iterator = paginator.paginate() filtered_iterator = response_iterator.search("pipelineIdList[?contains(@.name, 'ETL') == `tru...
10dcd1d933ed8adabd75740a55d567cf786fffbb
46,514
from typing import Optional from typing import Dict def GCBucket(bucket: str, prefix: Optional[str] = None, identifier: Optional[str] = None) -> Dict: """Get configuration object for Google Cloud storage volume. Parameters ---------- bucket: string Google Cloud Storage bucket identifier. ...
e93f2bab567a32a15b76278b18da3a7f001263cc
46,515
import tqdm def segment_threshold(eventfile,segment_length,demod,tbin_size,threshold,PI1,PI2,t1,t2): """ Using the .dat files, rebin them into 1s bins, to weed out the segments below some desired threshold. Will return a *list* of *indices*! This is so that I can filter out the *sorted* array of .dat ...
d9bbf34b6230df4257ed5a99d46292603d7f54f8
46,516
import tokenize def build_model(): """ Making a pipeline and using grid-search to optimize it. Input: None Output: Returns a model """ pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(RandomForestClassifier())) ]) para...
4e27d35ce612a5bdea6ff2175db956d121777362
46,517
import json def load_remote_settings_cache(): """Load cached remote skill settings. Returns: (dict) Loaded remote settings cache or None of none exists. """ remote_settings = {} if REMOTE_CACHE.exists(): try: with open(str(REMOTE_CACHE)) as cache: remot...
f2a58a5185a8b9d670489d6ad9eaa21abcb2e5d9
46,518
def get_blogroll(parser, token): """ {% get_blogroll %} """ return BlogRoll()
9ebd58021e048f1d9d4610daadba4f98d427b76f
46,519
def otsu(data, num=400): """ Generate threshold value based on Otsu. :param data: cluster data :param num: intensity number :return: selected threshold """ max_value = np.max(data) min_value = np.min(data) total_num = data.shape[1] best_threshold = min_value best_in...
1d3c264ff059b4205dc8bbe02e45b1f267ba52d4
46,520
import inspect def get_states(start=None, stop=None, state_keys=None, cmds=None, continuity=None, reduce=True, merge_identical=False, scenario=None): """ Get table of states corresponding to intervals when ``state_keys`` parameters are unchanged given the input commands ``cmds`` or ``start`...
f141f29f4e9f4d57a30a0869dd6043fdeedcbbad
46,521
import os import contextlib import wave def skip_long_utterance(wav_file, cut_off_len = 15): """ from "Text-Free Image-to-Speech Synthesis Using Learned Segmental Units" Appendix A: When computing duration statistics, we exclude utterances longer than 15s for SpokenCOCO... """ if os.path.isl...
9f2d81f30aaa0e5325b6ec88a116810f4c6c7ae9
46,522
import zipfile def read_data(filename): """Extract the first file enclosed in a zip file as a list of words.""" with zipfile.ZipFile(filename) as f: data = tf.compat.as_str(f.read(f.namelist()[0])).split() return data
e1b06f067cb22b71483033d32dddf454ce1c22ab
46,523
import logging def create_logger(name='', logging_config=logging_config): """Create a Logger object Args: name (str, optional): The name of the module.function logging_config (TYPE, optional): Logging config Returns: TYPE: Description """ dictConfig(logging_config) l...
f71bd7d96b50f2263c7b0175a89229d8c58abc92
46,524
def mark_all(request): """ Mark all notification as read or unread. """ action = request.data.get('action', None) success = True if action == 'read': request.user.notifications.read_all() msg = _("Marked all notifications as read") elif action == 'unread': request.us...
495a39c5f1229477704826ebaa4bdf86d8d67afe
46,525
import os def GetUniqueName(path, name): """Make a file name that will be unique in case a file of the same name already exists at that path. @param path: Root path to folder of files destination @param name: desired file name base @return: string """ tmpname = os.path.join(path, name) ...
c22b5d897fcec291f4e1e69fae8d85a9601ba15e
46,526
def _split_mime_type(mime_type): """Split MIME type into main type and subtype. Args: mime_type: The full MIME type string. Returns: (main, sub): main: Main part of MIME type (e.g., application, image, text, etc). sub: Subtype part of MIME type (e.g., pdf, png, html, etc). Raises: _In...
ce88fd75624060403aed44ddab9f044a577cfbd1
46,527
def handler_get_user_connections_from_id_from_event_id(userID, eventID): """Get the connections of the user with the given IDs (user and event). .. :quickref: Users; Get the connections of the user with the given IDs (user and event). :param int userID: The ID of the user to retrieve the collection fr...
506904c23a23fd94f5894d2ede08ed37a8ae5ff5
46,528
import requests def run(studata,cook): """获取处理后的数据 :param studatae:学生信息 :param cook:传入的cookie :return :打卡结果 """ # 读取个人提交信息 info = getinfo.data(studata, cook) if info == 0: print("今日打卡已完成,自动打卡取消\n") return "已完成" # 提交今日打卡 url = 'https://yq.weishao.com.cn/api/quest...
f7767bc6e0dfbf3d0c663eaed5ed1e9d7924ad34
46,529
def filter_label_2( context, label ): """Test Filter Label 2""" return False
a31337f18cbec6d5b8e556b21603635732d17ffd
46,530
def raise_404_if_no_object(fn): """ get_object_or_404 doesn't work with mongoengine, so this is needed for similar purpose """ def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: if not e.__class__.__name__ == "DoesNotExist": ...
b50a204a8cc0ab2cb2c05eabbe62f9d9ea6c751d
46,531
from typing import Tuple async def generate_keys() -> Tuple[bytes, str]: """A helper function to generate the private and public keys. backend - The value specified is default_backend(). This is because the cryptography library used to support different backends, but now only uses the default_backend...
13654fa051eeddaad6682ee0525199500dee67fd
46,532
import six def _is_named_tuple(instance): """Returns True iff `instance` is a `namedtuple`. Args: instance: An instance of a Python object. Returns: True if `instance` is a `namedtuple`. """ if not isinstance(instance, tuple): return False return (hasattr(instance, "_fields") and i...
8ee641d4fb64926b807d74eaf40115e8608af301
46,533
import os import joblib def load_trained_model(pipeline_str='BDT', config='IC86.2012', return_metadata=False): """ Function to load pre-trained model to avoid re-training Parameters ---------- pipeline_str : str, optional Name of model to load (default is 'BDT'). co...
92edd50dadf3741851218b0ecb6ffeb123d4b3a4
46,534
import urllib3 import json import sys def orsGetSnapToRoadLatLon(loc, APIkey): """ A function to get snapped latlng for one coordinate using ORS Parameters ---------- loc: list The location to be snapped to road Returns ------- list A snapped location in the format of [lat, lon]. Note that this function ...
6c770e59ce0fc5d76c1750e99bf3f087593989f2
46,535
def department_list_current(): """Returns a list of all Departments as of today's date. """ resp = _call_organisations_service("GetDepartmentListCurrent") return _parse_list_response(resp, "OrganisationsList", "Organisation")
dba40b7de228fdb196e46869499ed21db12fc569
46,536
def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, aggregate_size=None): """ Find the unique elements of a tensor. Returns the sorted unique elements of a tensor. There are three optional outputs in addition to the unique elements: * the indices of ...
fb97f22416a5558cb334396d07546aa2c98d89b2
46,537
def first(n, min_length, max_length, floor, ceiling, min_slope, max_slope): """ Return the lexicographically smallest valid composition of ``n`` satisfying the conditions. .. warning:: INTERNAL FUNCTION! DO NOT USE DIRECTLY! .. TODO:: Move this into Cython. Preconditions: ...
75a48ebd937dd8278f72b07954b1e97c73c45c16
46,538
from typing import Sequence from typing import Callable from typing import Optional from typing import Dict def load_with_native_transform( dss: Sequence[Dataset], bands: Sequence[str], geobox: GeoBox, native_transform: Callable[[xr.Dataset], xr.Dataset], basis: Optional[str] = None, groupby: ...
8625bf16a637c43169d57a775b9f5c293f9a41df
46,539
def post_to_dto(post: Post, href: str = None, links: list = None) -> PostDto: """ Converts post resource into data transfer object. :param post: Post resource to convert. :type post: Post :param href: Post resource href link. :type href: str :param links: Post resource links. :type link...
106d8b3dde351e52ed3df6b83eed3dd770e8f797
46,540
import logging def get_dual_coding_stop_stop_location( fs_coord, fs_type, strand, chr_seq, gencode): """Extend the starting coordinate (fs_coord) downstream until the stop-codon in the main frame, shift the frame (fs_type) at this stop-codon and then go upstream in the alternative until the second st...
cd5db26363585f93e234c36e158b0cd8046484ed
46,541
def delete_restaurant(restaurant_id): """V 0.0.0 POST Delete a restaurant: GET render Delete a restaurant form""" restaurant_to_delete = SESSION.query( Restaurant).filter_by(id=restaurant_id).one() if request.method == 'POST': SESSION.delete(restaurant_to_delete) SESSION.commit() ...
1380fa2159a90c536c94967a226453efedeaeafc
46,542
def get_clusters_from_file(path, ref_cluster_names=[]): """Get cluster names, labels, and cells from cluster file or metadata file """ clusters = {} with open(path) as f: lines = f.readlines() headers = [line.strip().split('\t') for line in lines[:2]] names = headers[0] types = hea...
cabf14c72b0467b0f2b15e3c0b8c8bd1846e92b5
46,543
import gzip def split_deltas(deltas_url): """Opens and decompress a gzipped text file and splits each line into two deltas""" left, right = [], [] with gzip.open(BytesIO(read_url(deltas_url))) as deltas: for line in deltas: line = line.decode().rsplit(" ", 1) left.app...
ff43daced54f1c18f837a525424e79dcd23d91d2
46,544
def transform(image, parameter_maps, verbose=False): """Transform an image according to some vector of parameter maps :param image: Image to be transformed :param parameter_maps: Vector of 3 parameter maps used to dictate the image transformation :type image: SimpleITK.Image ...
d2ac4b61f79f2a8275aa0f63feb49c87f12294ba
46,545
def put_lines(ax, cwaves, fluxes, ypos2, ypos3, labels, bars=None, bscale=None, edges=None, barskwargs=dict(), adjustkwargs=dict(), linekwargs=dict(), textkwargs=dict()): """ Automatic layout of labels for spectral lines in a plot. Parameters ---------- ax : Matplotlib A...
b8cf1918eeb77871e42e4bc9691ccaf227373ca8
46,546
import os def sip_to_pv(infile,outfile,tpv_format=True,preserve=False,extension=0,clobber=True): """ Function which wraps the sip_to_pv conversion Parameters: ----------- infile (string) : name of input FITS file with TAN-SIP projection outfile (string) : name of output FITS file with TAN-TPV p...
c13f4f7b7e1e1ddb2bed29365036d56d673789dd
46,547
def _tracking(fcn): """ Decorator to indicate the list has changed """ def new_fcn(self, *args): self.changed = True return fcn(self, *args) return new_fcn
3f6454190056f112134f01507b2bb353a8043790
46,548
def test(doorcount: int, switch: bool, trials: int) -> bool: """Returns a win rate for the Monty Hall problem with repeated trials.""" wins = sum(int(play(doorcount, switch) == CAR) for _ in range(trials)) return wins/trials
0e02834f54570867412eb2c25892377a388c9287
46,549
def getLastStepMeanSpeed(detID): """getLastStepMeanSpeed(string) -> double Returns the mean speed in m/s of vehicles that have been within the named multi-entry/multi-exit detector within the last simulation step. """ return _getUniversal(tc.LAST_STEP_MEAN_SPEED, detID)
dd0e79e0639ee6141ba2abb8f66398bc4cbe4341
46,550
def get_random_experiment_histories_from_file(experiment_path_prefix, net_number): """ Read history-arrays from the specified npz-file and return them as ExperimentHistories object. """ histories_file_path = generate_random_experiment_histories_file_path(experiment_path_prefix, net_number) with np.load(hist...
ec65f7bb1580f166218554a28fbe40b629d3bd11
46,551
import sys def caller_module(level=2, sys=sys): """This function is taken from Pyramid Web Framework - ``pyramid.path.caller_module``.""" module_globals = sys._getframe(level).f_globals module_name = module_globals.get('__name__') or '__main__' module = sys.modules[module_name] return module
4bc6d73f656c98be185f7b5aaa869d7fb6ca841c
46,552
def qr_householder(A): """Return a QR-decomposition of the matrix A using Householder reflection. The QR-decomposition decomposes the matrix A of shape (m, n) into an orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of shape (m, n). Note that the matrix A does not have to be square...
ce2e64c55e4476be1048c88b66bb89ce0c6697f5
46,553
def login(): """ Página de entrada de la app """ if 'email' in session: # Obtenemos el ID del user _id = elastic.getIDByMail(session['email']) return render_template('index_sup.html', random_num = WebScraper.getRandomNumber(), msg = session['user'] + ' is already online!',...
ea534c69727332958fe4fe7a32e0979f5a674d87
46,554
def load_data(database_filepath): """ Load data from database Arguments: database_filepath -> Path to SQLite destination database Output: X -> a dataframe containing features Y -> a dataframe containing labels category_names -> List of categories name """ # l...
142eed54d527225a7208a35b2631333ef842c934
46,555
def cholesteric_droplet_data(shape, radius, pitch, hand = "left", no = 1.5, ne = 1.6, nhost = 1.5): """Returns cholesteric droplet optical block. This function returns a thickness, material_eps, angles, info tuple of a cholesteric droplet, suitable for light propagation calculation tests. Pa...
3c478afad445066ade233461500b072bd756836f
46,556
def getInterpolatedFzeroPzero( f, g, p ): """ look at the points of f, g and p surrounding where g crosses zero and interpolate f and p at 0 """ ndx = getIndexZeroDbCrossover( g ) f_zero_db = None g_zero_db = None p_zero_db = None if ndx != None: f_zero_db = f[ndx] g_z...
7dbf5b0372e0c81c771c077b6badbe42d2c4eb55
46,557
from typing import Mapping def create_tag(entity: Entity, source_name: str, color: str) -> Mapping[str, str]: """Create a tag.""" value = entity.value if value is None: value = f"NO_VALUE_{entity.id}" return {"tag_type": source_name, "value": value, "color": color}
f510ddc698f9d6c491fda63e33a16fe2cfda1021
46,558
import re def javacode_to_tokens(code:str): """ Starting on method level, without javadocs returns a touple of ([code-tokens],code-string) """ code_tokens = re.findall(r"\w+(?:'\w+)*|[^\w\s]", code) #print("Javacode to tokens to be done!",code,code_tokens) return (code_tokens,code)
85c0dccb06936326929493edc5192ccf01bf59ea
46,559
def static(type='artist', artist_pick='song_hotttnesss-desc', variety=.5, artist_id=None, artist=None, \ song_id=None, description=None, results=15, max_tempo=None, min_tempo=None, max_duration=None, \ min_duration=None, max_loudness=None, min_loudness=None, max_danceability=None...
95961b0d4c865e86a636682bbb0f335a43e57a27
46,560
def floor_to(value: float, target: float) -> float: """ Similar to math.floor function, but to target float number. """ value: Decimal = Decimal(str(value)) target: Decimal = Decimal(str(target)) result: float = float(int(floor(value / target)) * target) return result
c58341913e294b68d38328fe42441e6942e94b8d
46,561
def registration(): """Processes registration when user provides email and password, or displays the form.""" if request.method == 'POST': email = request.form.get("email") password = request.form.get("password") # Create a possible user object to query if the user's email is in t...
e52fab05c05ad945b39d2f1e9d9f102efc5f395e
46,562
from typing import Dict def generate_meta(favicon: Dict[str, str]) -> str: """Generate metatag based on favicon data. Default behavior: - If favicon data contains no ``rel`` attribute, sets ``rel="icon"`` - If no ``size`` attribute is provided, ``size`` will be omitted - If no favicon MIME type i...
940e7f7ab7b2fb7207cba287f6f6ec7424749f98
46,563
import re def select_disk(prompt='Which disk?'): """Select a disk from the attached disks""" disks = get_attached_disk_info() # Build menu disk_options = [] for disk in disks: display_name = '{Size}\t[{Table}] ({Type}) {Name}'.format(**disk) if len(disk['Partitions']) > 0: ...
f5fd59ab6c45b1af303bfa453ecdde8c7df326a3
46,564
def imageToVTK( path, origin=(0.0, 0.0, 0.0), spacing=(1.0, 1.0, 1.0), cellData=None, pointData=None, fieldData=None, ): """ Export data values as a rectangular image. Parameters ---------- path : str name of the file without extension where data should be saved. ...
f263f1a7613e331fd46c336446be50d84e7110c6
46,565
def compute_capacities(n, demands_across_cuts): """ Computes the capacities as given in the paper. Takes O(n^2) time. :param n: ring size :param demands_across_cuts: SymmetricMatrix containing all demands across cuts. :return: np.array containing capacities """ c = np.zeros((n,), dtype=np.fl...
7a8936e057577473919302274b6c72c44d5b47fc
46,566
def needs_nibabel_data(subdir=None): """ Decorator for tests needing nibabel-data Parameters ---------- subdir : None or str Subdirectory we need in nibabel-data directory. If None, only require nibabel-data directory itself. Returns ------- skip_dec : decorator De...
2d45fe47fae9ac6e574d33e97c556c7dabac9215
46,567
def get_ranks_lsq(df_teams, df_schedule, year, week, B_w=30., B_r=35., dS_max=35., beta_w=2.2, show=False): """Calculate iterative LSQ rankings, and save plot :param df_teams: data frame wtih team_ids :param df_schedule: data frame with data for each matchup :param year: current year :param week: current wee...
3f2ba7d6aa1648b250a46cd0ecbcff9d6cb706df
46,568
def __create_pyramid_features(C3, C4, C5, feature_size=256): """ Creates the FPN layers on top of the backbone features. Args C3 : Feature stage C3 from the backbone. C4 : Feature stage C4 from the backbone. C5 : Feature stage C5 from the backbone. ...
754acc903e767179096c5e84ec43e6df54970c3e
46,569
import copy def parse_compare(*tests, justeq=False): """Decorate a function to run it against pure python. This will run and compare the function using all available backends. """ def decorate(fn): def test(backend_opt, args): if not isinstance(args, tuple): args =...
3e503ab27bdb5fedc62a82ddace9f12a4e9da3c2
46,570
def check_brand_parameters(request): """ Function to check if the parameters of a given brand are valid :param request: request object containing all the parameters :return: Error if exists, if not, None """ if not check_parameter(request.json, NAME, 2, 15) \ or not check_parameter(r...
c59b94c044d81fa29d338d51ff19a44beca0da6b
46,571
def command_exists(cmd): """ does the command exists in current system? """ path = which(cmd) if path is None: return False return True
d84a843cb478c7ae63f1ec3abba0621a794dabd5
46,572
from typing import Optional from typing import List def _convert_names( names, max_levels: Optional[int] = None, err_msg: Optional[str] = None ) -> List[str]: """Helper function that converts arguments of index, columns, values to list. Also performs check on number of levels. If it exceeds `max_levels`,...
d67fb93b039306e7dac973abffe1e08089993c0d
46,573
import time import pickle import json import csv import sys def importCandidatePairs(input_file, log): """ Import candidate pairs from a file. Supported filetypes: txt, json, pickle (python) and csv. """ tim = time.clock() logprint(log, True, "Importing candidate pairs...") candidatePairs = dict() # Input fil...
e531e86874971e8a29a3cde24e4999d263c8b507
46,574
from backend.caffe.path_loader import PathLoader def extractNetFromSolver(solverstring): """Read a protoxt string(!) of a solver and return the network protoxt string(!). This works only, if the solver specifies a network using the "net_param" parameter. A reference to a file using the "net" parameter ca...
a78e35798a48ef19272993183e73f314e5f7fd14
46,575
from datetime import datetime def expand_date_param(param, lower_upper): """ Expands a (possibly) incomplete date string to either the lowest or highest possible contained date and returns datetime.datetime for that string. 0753 (lower) => 0753-01-01 2012 (upper) => 2012-12-31 2012 (lower...
1a2c34a0abace3b521be093de361ddcae0006ea7
46,576
def appliedMediumData(modelFunction,cellSpace,initialPercentageInfected,states,n_iterations,n_simulations,theSystemHasAges = False, systemAges = None): """Aplica el modelo epidemiológico en n_simulations modelFunction => Función basica del modelo epidemiológico initialPercentageInfected => Porcentaje de inf...
2237c93fdd318db6dc3bcd77ed7b396041938f18
46,577
import glob import os import subprocess def HD_BET_bet(niix_root, first_level_code='PID*PNAME*', second_level_code='20*', filename_pattern='CTP_*_mc_ncct.nii.gz', out_ext='hdbet', low_thresh=-50, high_thresh=100, gpu='4'): """ """ # retrieving the study root ...
09d5b3c0e09b096726ed6cd06b230c483b4b8317
46,578
def make_id(ref: extmodule.Ref) -> Text: """Convert a ref to a string iddentifier.""" return "{}/{}".format(ref.type, ref.ident)
b3dd53a68dc98230576839f9ced28c220e044e80
46,579
import math def get_torch_datagens(data_dir, feature_len=300, num_video_per_person=1e4, num_audio_per_video=1e4, split_by='audio', split_size=0.2, txt_dirs=None, ratios=[1.0, 1.0]): """ Returns datagens for torch Params: data_dir: Parent directory for the pickle files. Assumed that each person has...
59fc414365d44551b32c262f6268161e7d462529
46,580
def create_grouped_df_adv(group_param, df, ticker_name='symbol', agg_func=np.count_nonzero, show_value_counts=False): """ Receive the `group_param`, `df`, `ticker_name`, `agg_func` and return grouped by group_param DataFrame with values aggregated by agg_func and Dict with ...
22fc6d243cb64df906c143bee1b3d4ff8f4cb376
46,581
import argparse def read_args(argv): """Print the splash screen, parse, and return the command-line arguments""" print(splash) help_formatter = lambda prog: argparse.HelpFormatter(prog, max_help_position=45, width=200) parser = argparse.ArgumentParser(description="", ...
45eccec5688079443316566df145891b20c89604
46,582
def query_history_to_json(query_history: QueryHistory): """ The function converts an object of QueryHistory to a json string. :param query_history: A QueryHistory object. :type query_history: ibmpairs.query.QueryHistory :rtype: str """ return QueryHi...
766d0918a7cea0868cdab6c672d14c7c5504dbd1
46,583
def is_MC(parcels): """ Dummy for Maricopa County. """ return (parcels.county == 'MC').astype(int)
6e8af2675f1ba40d642ada0d07e133aeb9dd0d70
46,584
import re def getMatchingCompetence(dictionary, lastmessage): """ Searches for a competence in a string """ allCompetences = getAllCompetences(dictionary) searchedCompetence = [] for word in re.split('[ .!?]', lastmessage): if stemmer.stem(word.strip().lower()) in [ ste...
2b6fbd95597db71a60a914443d2998ad093acb33
46,585
def objScale(obj,factor): """ Object scaling function, gets obj and scale factor, returns an array of the scaled size """ oldSize = obj.get_size() newSize = [] for i in oldSize: newSize.append(int(i/float(factor))) return newSize
3104fc4e126299400a5a119fff0d8bc9d3ea32f7
46,586
def tiny_shakespeare(c: NLPAutoRegressionConfigs): """ ### Tiny Shakespeare dataset It will download from the url if not present """ return TextFileDataset( lab.get_data_path() / 'tiny_shakespeare.txt', c.tokenizer, url='https://raw.githubusercontent.com/karpathy/char-rnn/ma...
7a22a359c5306e73e94701ce91645c31cf87c380
46,587
def preprocess_encoder_input(arr): """ Simple method to handle the complex MFCC coefs that are produced during preprocessing. This means: 1. (For now), discarding one of the channels of the MFCC coefs 2. Collapsing any empty dimensions :param arr: the array of MFCC coefficients. """ return a...
ccd754783377e9fe257e423f9099d6dbef21d11b
46,588
def findTreeRoute(observations, tree, startNodeID, startLayer, stopLayer, alternateLeafActivation = False): """Classifies the observations according to the tree.""" col = 0 treeRoute = [] for i in range(startLayer,stopLayer+2): if i == startLayer: currentNode = tree[startNodeID] ...
e206902c6edec2eff100f2ff77bb8a57d2a6c99f
46,589
def determineWinCardIndex(pile): """ @param list pile: pile of cards in center @return int: index of winning card - highest index of leading suit, or if there are spades, highest spades index """ bestCard = (pile[0], 0) for i in range(1, len(pile)): bestCardSuit = bestCard[0].ind...
c105ade59b79482de0f2d3e6b4d25c4353bb1dcf
46,590
import time def sagemaker_timestamp(): """Return a timestamp with millisecond precision.""" moment = time.time() moment_ms = repr(moment).split('.')[1][:3] return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_ms), time.gmtime(moment))
a0c09ed9f419ef519ca22b219e1bc0922f7f7f7c
46,591
def EmitEval(deque_graph, # type: collections.deque ctx, # type: Context ): """ Emit evaluation code(eval layers) """ ret = ''' bool NetworkForwardExecute(Buffer *buffer) { ''' for layer_name in deque_graph: node = ctx.graph[layer_name] if node["op"] == "N...
d2215da9db38d53e7a5fd1f6b3da01ef310cf357
46,592
from ._tornadoserver import TornadoServer # noqa - circular dependency from ._flaskserver import FlaskServer def create_server(host=None, port=None, loop=None, backend='tornado', **server_kwargs): """ Create a new server object. This is automatically called; users generally don't need t...
e4806cd389287c6aeab2e9ad824317fc34ec13e5
46,593
def build_dataset_info(cfg): """Build information struct about the dataset from a configuration. This performs type conversion to the expected types. Paths contained in cfg are expected to be alread expanded. That is, it should not contain global variables or other system dependent abbreviations. ...
576e71057bcaf38c1720d5b70f21557c608700e0
46,594
import os def is_database_available(name: str) -> bool: """ Basic check for available files, does not recognize if some files are missing. """ base_name = os.path.join(BLASTDB, name) # It may be from multiple files, so check for the first one. return are_database_files_available(base_name)...
2c9f281a3d35db1f3cbee8e51f228ce2f235a321
46,595
def hdr2srgb(im): """[Tonemap a linear image with quasi srgb (clip and gamma 1/2.2)] Args: im ([[hxwx3 ndarray]): [linear image] Returns: [hxwx3 ndarray]: [srgb image] """ return (np.clip(im,0,1) ** (1/2.2) * 255).astype(np.uint8)
ab932f0ea5061f549bbb5d85ab8e1cdbeabb4466
46,596
def greyList(n): """ 生成格雷编码序列 参考:https://www.jb51.net/article/133575.htm :param n: 长度 :return: 范围 2 ** n的格雷序列 """ def get_grace(list_grace, n): if n == 1: return list_grace list_before, list_after = [], [] for i in range(len(list_grace)): list...
eab1f00ec2cdd62fbbffbb78a2c69c6fe9177e66
46,597
from typing import Union def get_feature(feature: Union[str, Feature]) -> Feature: """Get feature from name. Args: name (str): Name of feature. Returns: Feature """ if isinstance(feature, str): feature = get_feature_class(feature)() elif not isinstance(feature, Featur...
92a0938ff426f66bc61e10e9f7b3f6cdc64ede33
46,598
from sys import path def format_seq_timing(txt_loc, edge_type=1): """format the hold and setup time as per .lib requirement """ attr_names = ['rise_hold', 'fall_hold', 'rise_setup', 'fall_setup'] lut_table_list = [] seq_timing_type = '' if edge_type == 1: clk_type = 'rising' else: ...
31d7f845b6dfc8e90579e80c68b800c6969d2aff
46,599