content
stringlengths
22
815k
id
int64
0
4.91M
def plot_validation_curves(df, root_path, result_path, dataset='standardized_MNIST_dataset', scenario=1, dataset_dimension=28, architecture='FC', epochs=50): """ Plot for same scenario and data dimensions. Each curve represents the model trained with differ...
5,341,700
def _whctrs(anchor): """return width, height, x center, and y center for an anchor (window).""" w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) return w, h, x_ctr, y_ctr
5,341,701
def filter_tiddlers(tiddlers, filters, environ=None): """ Return a generator of tiddlers resulting from filtering the provided iterator of tiddlers by the provided filters. If filters is a string, it will be parsed for filters. """ if isinstance(filters, basestring): filters, _ = parse_...
5,341,702
def apply_move(board_state, move, side): """Returns a copy of the given board_state with the desired move applied. Args: board_state (3x3 tuple of int): The given board_state we want to apply the move to. move (int, int): The position we want to make the move in. side (int): The side we...
5,341,703
def merge(dicts, overwrite=False, append=False, list_of_dicts=False): """ merge dicts, starting with dicts[1] into dicts[0] Parameters ---------- dicts : list[dict] list of dictionaries overwrite : bool if true allow overwriting of current data append : bool if true ...
5,341,704
def compute_delivery_period_index(frequency = None, delivery_begin_dt_local = None, delivery_end_date_local = None, tz_local = None, profile ...
5,341,705
def make_proxy(global_conf, address, allowed_request_methods="", suppress_http_headers=""): """ Make a WSGI application that proxies to another address: ``address`` the full URL ending with a trailing ``/`` ``allowed_request_methods``: a space seperated list of request m...
5,341,706
def test(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('eachday/tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
5,341,707
async def save_training_result(r: dependency.TrainingResultHttpBody): """ Saves the model training statistics to the database. This method is called only by registered dataset microservices. :param r: Training Result with updated fields sent by dataset microservice :return: {'status': 'success'} i...
5,341,708
def sort2nd(xs): """Returns a list containing the same elements as xs, but sorted by their second elements.""" xs.sort(cmp2nd) return xs
5,341,709
def is_one_of_type(val, types): """Returns whether the given value is one of the given types. :param val: The value to evaluate :param types: A sequence of types to check against. :return: Whether the given value is one of the given types. """ result = False val_type = type(val) for tt ...
5,341,710
def load_qadata(qa_dir): """ :param qa_dir: the file path of the provided QA dataset, eg: /data/preprocessed_data_10k/test; :return: the dictionary of the QA dataset, for instance QA_1_; """ print("begin_load_qadata") qa_set = {} # os.walk: generates the file names in a directory tree by wal...
5,341,711
def get_online(cheat_id): """Получение онлайна чита --- consumes: - application/json parameters: - in: path name: cheat_id type: string description: ObjectId чита в строковом формате responses: 200: desc...
5,341,712
def grpc_client_connection(svc: str = None, target: str = None, session: Session = None) -> Channel: """ Create a new GRPC client connection from a service name, target endpoint and session @param svc: The name of the service to which we're trying to connect (ex. blue) @param target: The endpoint, a...
5,341,713
def test_product_category_relation( db_session: Session, example_categories: List[Category], example_products_without_category: List[Product] ): """Check whether orm adds products along with category""" example_categories[0].products = example_products_without_category db_session.ad...
5,341,714
def aqi(pm25): """AQI Calculator Calculates AQI from PM2.5 using EPA formula and breakpoints from: https://www.airnow.gov/sites/default/files/2018-05/aqi-technical -assistance-document-may2016.pdf Args: - pm25 (int or float): PM2.5 in ug/m3 """ if pm25 < 0: raise ValueErr...
5,341,715
def projectionManip(*args, **kwargs): """ Various commands to set the manipulator to interesting positions. In query mode, return type is based on queried flag. Flags: - fitBBox : fb (bool) [create] Fit the projection manipulator size and po...
5,341,716
def get_fighters(url): """ Scrape fighter data """ response = simple_get(url) if response is not None: html = BeautifulSoup(response, 'html.parser') html_tr = html.find_all('tr') # html_td = html.find_all('td') # for fighter in html.find_all('div', class_ = 'odd') ...
5,341,717
def require_lock(model, lock='ACCESS EXCLUSIVE'): """ Decorator for PostgreSQL's table-level lock functionality Example: @transaction.commit_on_success @require_lock(MyModel, 'ACCESS EXCLUSIVE') def myview(request) ... PostgreSQL's LOCK Documentation: http://www...
5,341,718
def welcome(): """List all available api routes.""" # Set the app.route() decorator for the "/api/v1.0/precipitation" route return ( f"Available Routes:<br/>" f"/api/v1.0/names<br/>" f"/api/v1.0/precipitation" )
5,341,719
def train_filter_keras_model(config: Config) -> None: """Train a Filter model""" train_seq = FilterModelSequence(config, "training") valid_seq = FilterModelSequence(config, "validation") product_input_layer = Input(shape=(config["fingerprint_len"],)) product_dense_layer = Dense(config["model"]["hid...
5,341,720
def pbootstrap(data, R, fun, initval = None, ncpus = 1): """ :func pbootstrap: Calls boot method for R iteration in parallel and gets estimates of y-intercept and slope :param data: data - contains dataset :param R: number of iterations :param func: optim - function to get estimate of y-intercept and slo...
5,341,721
def _el_orb(string): """Parse the element and orbital argument strings. The presence of an element without any orbitals means that we want to plot all of its orbitals. Args: string (str): The element and orbitals as a string, in the form ``"C.s.p,O"``. Returns: dict: T...
5,341,722
def _prettify_xml(elem, level=0): """Adds indents. Code of this method was copied from http://effbot.org/zone/element-lib.htm#prettyprint """ i = "\n" + level * " " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail o...
5,341,723
def test_inverse_force(): """Testing that we can convert amounts of substance.""" E = Q_(1, "eV/angstrom") E2 = E.to("kcal/mol/angstrom") assert f"{E:~} = {E2:~.4}" == "1 eV / Å = 23.06 kcal / mol / Å"
5,341,724
def create_folders(path): """ create folders with class names 0 - 9 :param path: global path of the parent folder [str] :return: None """ for i in range(10): # 0 - 9 if not os.path.exists(os.path.join(path, str(i))): os.mkdir(os.path.join(path, str(i)))
5,341,725
def create_LOFAR_configuration(antfile: str, meta: dict = None) -> Configuration: """ Define from the LOFAR configuration file :param antfile: :param meta: :return: Configuration """ antxyz = numpy.genfromtxt(antfile, skip_header=2, usecols=[1, 2, 3], delimiter=",") nants = antxyz.shape[0] ...
5,341,726
def fmla_for_filt(filt): """ transform a set of column filters from a dictionary like { 'varX':['lv11','lvl2'],...} into an R selector expression like 'varX %in% c("lvl1","lvl2")' & ... """ return ' & '.join([ '{var} %in% c({lvls})'.format( var=k, ...
5,341,727
def sfen_board(ban): """Convert ban (nrow*nrow array) to sfen string """ s = '' num = 0 for iy in range(nrow): for ix in range(nrow): i = iy*nrow + ix if ban[i]: if num: s += str(num) num = 0 s +=...
5,341,728
def join_simple_tables(G_df_dict, G_data_info, G_hist, is_train, remain_time): """ 获得G_df_dict['BIG'] """ start = time.time() if is_train: if 'relations' in G_data_info: G_hist['join_simple_tables'] = [x for x in G_data_info['relations'] if ...
5,341,729
async def create_upload_file(file: UploadFile = File(default="")): """ Takes a csv file uploaded as multipart form data, downloads it. """ newpath = os.path.join(DATA_DIR_NAME, file.filename) with open(newpath, "wb") as buffer: shutil.copyfileobj(file.file, buffer)
5,341,730
def make_model(model_name: str, migration): """ Create model.\n :param model_name: model name in singular form.\n :param migration: if you would like to create migration as well\n :return: None """ if migration: call(['python', 'db.py', 'make:migration', model_name, '-p...
5,341,731
def create_epochs(data, events_onsets, sampling_rate=1000, duration=1, onset=0, index=None): """ Epoching a dataframe. Parameters ---------- data : pandas.DataFrame Data*time. events_onsets : list A list of event onsets indices. sampling_rate : int Sampling rate (sam...
5,341,732
def is_equal_limit_site( site: SiteToUse, limit_site: SiteToUse, site_class: Type[Site] ) -> None: """Check if site is a limit site.""" if site_class == Site: return site.point.x == limit_site.x and site.point.y == limit_site.y elif site_class == WeightedSite: return ( site.p...
5,341,733
def get_header(filename): """retrieves the header of an image Args: filename (str): file name Returns: (str): header """ im = fabio.open(filename) return im.header
5,341,734
def gaussian_ll_pdf(x, mu, sigma): """Evaluates the (unnormalized) log of the normal PDF at point x Parameters ---------- x : float or array-like point at which to evaluate the log pdf mu : float or array-like mean of the normal on a linear scale sigma : float or array-like ...
5,341,735
def _show_traceback(method): """decorator for showing tracebacks in IPython""" def m(self, *args, **kwargs): try: return(method(self, *args, **kwargs)) except Exception as e: ip = get_ipython() if ip is None: self.log.warn("Exception in widget ...
5,341,736
def ecdf(data): """Compute ECDF for a one-dimensional array of measurements.""" # Number of data points n = len(data) # x-data for the ECDF x = np.sort(data) # y-data for the ECDF y = np.arange(1, len(x)+1) / n return x, y
5,341,737
def import_module_part(request, pk): """Module part import. Use an .xlsx file to submit grades to a module part On GET the user is presented with a file upload form. On POST, the submitted .xlsx file is processed by the system, registering Grade object for each grade in the excel file. It dynamically ...
5,341,738
def ordered_pair(x: complex) -> Tuple[float, float]: """ Returns the tuple (a, b), like the ordered pair in the complex plane """ return (x.real, x.imag)
5,341,739
def find_fits_file(plate_dir_list, fits_partial_path): """ Returns a path :rtype : basestring """ for plate_dir in plate_dir_list: fits_path = os.path.join(plate_dir, fits_partial_path) if os.path.exists(fits_path): return fits_path return None
5,341,740
def HornFromDL(owlGraph, safety=DATALOG_SAFETY_NONE, derivedPreds=[], complSkip=[]): """ Takes an OWL RDF graph, an indication of what level of ruleset safety (see: http://code.google.com/p/fuxi/wiki/FuXiUserManual#Rule_Safety) to apply, and a list of derived predicates and returns a Ruleset instance co...
5,341,741
def _assembleMatrix(data, indices, indptr, shape): """ Generic assemble matrix function to create a CSR matrix Parameters ---------- data : array Data values for matrix indices : int array CSR type indices indptr : int array Row pointer shape : tuple-like ...
5,341,742
def quantize_model(): """ Create the Quantization Simulation and finetune the model. :return: """ tf.compat.v1.reset_default_graph() # load graph sess = graph_saver.load_model_from_meta('models/mnist_save.meta', 'models/mnist_save') # Create quantsim model to quantize the network using...
5,341,743
def mock_state_store(decoy: Decoy) -> StateStore: """Get a mocked out StateStore.""" return decoy.mock(cls=StateStore)
5,341,744
def beam_search_runner_range(output_series: str, decoder: BeamSearchDecoder, max_rank: int = None, postprocess: Callable[ [List[str]], List[str]]=None ) -> List[BeamSearchR...
5,341,745
def clone_provenance_history(provenance_history_data, ad): """ For a single input's provenance history, copy it into the output `AstroData` object as appropriate. This takes a dictionary with a source filename, md5 and both it's original provenance and provenance_history information. It duplicates...
5,341,746
def read_variants( pipeline, # type: beam.Pipeline all_patterns, # type: List[str] pipeline_mode, # type: PipelineModes allow_malformed_records, # type: bool representative_header_lines=None, # type: List[str] pre_infer_headers=False, # type: bool sample_name_encoding=SampleNameEncodin...
5,341,747
def carla_location_to_numpy_vector(carla_location): """ Convert a carla location to a icv vector3 Considers the conversion from left-handed system (unreal) to right-handed system (icv) :param carla_location: the carla location :type carla_location: carla.Location :return: a numpy.array wit...
5,341,748
def test_round_trip_masked_table_default(tmpdir): """Test round-trip of MaskedColumn through HDF5 using default serialization that writes a separate mask column. Note: >>> simple_table(masked=True) <Table masked=True length=3> a b c int64 float64 str1 ----- ------- ---- -...
5,341,749
def main(): """docstring for main""" import argparse distribution = pkg_resources.get_distribution('tldextract') parser = argparse.ArgumentParser( version='%(prog)s ' + distribution.version, description='Parse hostname from a url or fqdn') parser.add_argument('input', metavar='fqd...
5,341,750
async def test_abort_on_connection_error( mock_get_cases: MagicMock, hass: HomeAssistant ) -> None: """Test we abort on connection error.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": confi...
5,341,751
def prev_cur_next(lst): """ Returns list of tuples (prev, cur, next) for each item in list, where "prev" and "next" are the previous and next items in the list, respectively, or None if they do not exist. """ return zip([None] + lst[:-1], lst, lst[1:]) + [(lst[-2], lst[-1], None)]
5,341,752
def vet_input_path(filename): """ Check if the given input file exists. Returns a pathlib.Path object if everything is OK, raises InputFileException if not. """ putative_path = pathlib.Path(filename) if putative_path.exists(): if not putative_path.is_file(): msg = ('A ...
5,341,753
def check_for_updates(repo: str = REPO) -> str: """ Check for updates to the current version. """ message = "" url = f"https://api.github.com/repos/{repo}/releases/latest" response = requests.get(url) if response.status_code != 200: raise RuntimeError( f"Failed to get...
5,341,754
def _process_image(record, training): """Decodes the image and performs data augmentation if training.""" image = tf.io.decode_raw(record, tf.uint8) image = tf.cast(image, tf.float32) image = tf.reshape(image, [32, 32, 3]) image = image * (1. / 255) - 0.5 if training: padding = 4 image = tf.image.re...
5,341,755
def svn_diff_fns2_invoke_token_discard(*args): """svn_diff_fns2_invoke_token_discard(svn_diff_fns2_t _obj, void diff_baton, void token)""" return _diff.svn_diff_fns2_invoke_token_discard(*args)
5,341,756
def process_bb(model, I, bounding_boxes, image_size=(412, 412)): """ :param model: A binary model to create the bounding boxes :param I: PIL image :param bounding_boxes: Bounding boxes containing regions of interest :param image_size: Choose the size of the patches :return: Patches with the clas...
5,341,757
def roc( observations, forecasts, bin_edges="continuous", dim=None, drop_intermediate=False, return_results="area", ): """Computes the relative operating characteristic for a range of thresholds. Parameters ---------- observations : xarray.Dataset or xarray.DataArray Lab...
5,341,758
def print_forecast(forecast=None): """Print forecast to screen.""" if forecast == None: return print '-'*20 print time.strftime('%Y/%m/%d %H:%M:%S') print "LAT: {0} LON: {1}".format(LAT,LON) print '-'*20 for daily in forecast: print daily
5,341,759
def make_grammar(): """Creates the grammar to be used by a spec matcher.""" # This is apparently how pyparsing recommends to be used, # as http://pyparsing.wikispaces.com/share/view/644825 states that # it is not thread-safe to use a parser across threads. unary_ops = ( # Order matters here...
5,341,760
def _pull(keys): """helper method for implementing `client.pull` via `client.apply`""" if isinstance(keys, (list,tuple, set)): return [eval(key, globals()) for key in keys] else: return eval(keys, globals())
5,341,761
def position(df): """ 根据交易信号, 计算每天的仓位 :param df: :return: """ # 由 signal 计算出实际每天持有的股票仓位 df['pos'] = df['signal'].shift(1) df['pos'].fillna(method='ffill', inplace=True) # 将涨跌停时不得买卖股票考虑进来 # 找出开盘涨停的日期 cond_cannot_buy = df['开盘价'] > df['收盘价'].shift(1) * 1.097 # 今天的开盘价相对于昨天的收盘价上...
5,341,762
def prepare_data(data, preprocessed_data, args): """Prepare Data""" data = data.to_numpy() train_size = int(len(data) * args.train_split) test_size = len(data) - train_size train_X = preprocessed_data[0:train_size] train_Y = data[0:train_size] test_X = preprocessed_data[train_size:len(pre...
5,341,763
def svn_client_conflict_tree_get_victim_node_kind(conflict): """svn_client_conflict_tree_get_victim_node_kind(svn_client_conflict_t * conflict) -> svn_node_kind_t""" return _client.svn_client_conflict_tree_get_victim_node_kind(conflict)
5,341,764
def list(event, production): """ Store a file in the Store. """ click.echo(f"{'Resource':30} {'Hash':32} {'UUID':32}") click.echo("-"*96) for resource, details in this_store.manifest.list_resources(event, production).items(): click.echo(f"{resource:30} {details['hash']:32} {details['uuid...
5,341,765
def load_module(script_path: str, module_name: str): """ return a module spec.loader.exec_module(foo) foo.A() """ spec = importlib.util.spec_from_file_location(module_name, script_path) module = importlib.util.module_from_spec(spec) return spec, module
5,341,766
def readfile(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read()
5,341,767
def memory_func(func): """ декоратор для замера памяти занимаемой функцией в оперативной памяти. """ def wrapper(*args, **kwargs): proc = Process(getpid()) # получение идентификатора текущего процесса и объявление класса start_memory = proc.memory_info().rss # сохранение начального зна...
5,341,768
def read_data(datafile='sampling_data_2015.txt'): """Imports data from an ordered txt file and creates a list of samples.""" sample_list = [] with open(datafile, 'r') as file: for line in file: method, date, block, site, orders = line.split('|') new_sample = sample(method, da...
5,341,769
async def get_https(method: str = "all"): """Get https proxies from get_proxies_func() function.""" return await get_proxies_func("https", method)
5,341,770
def iam_analysis(obs_spec, model1_pars, model2_pars, rvs=None, gammas=None, verbose=False, norm=False, save_only=True, chip=None, prefix=None, errors=None, area_scale=False, wav_scale=True, norm_method="scalar", fudge=None): """Run two component model over all model combinations.""...
5,341,771
def _parse_archive_name(pathname): """Return the name of the project given the pathname of a project archive file. """ return os.path.basename(pathname).split('.')[0]
5,341,772
def download_har_dataset(): """ Download human activity recognition dataset from UCI ML Repository and store it at /tsfresh/notebooks/data. Examples ======== >>> from tsfresh.examples import har_dataset >>> har_dataset.download_har_dataset() """ zipurl = 'https://github.com/MaxBen...
5,341,773
def is_authenticated(user, password): """Check if ``user``/``password`` couple is valid.""" global IMAP_WARNED_UNENCRYPTED if not user or not password: return False log.LOGGER.debug( "Connecting to IMAP server %s:%s." % (IMAP_SERVER, IMAP_SERVER_PORT,)) connection_is_secure = Fals...
5,341,774
def apply_mask(input, mask): """Filter out an area of an image using a binary mask. Args: input: A three channel numpy.ndarray. mask: A black and white numpy.ndarray. Returns: A three channel numpy.ndarray. """ return cv2.bitwise_and(input, input, mask=mask)
5,341,775
def runUrllib2(urls, num): """Running benchmark for urllib2. Args: urls: List of URLs. num: Number of requests. """ results = [] for i in range(num): sys.stderr.write('.') start = time.time() for url in urls: urlopen(url) end = time.time()...
5,341,776
def fetch_track_lyrics(artist, title): """ Returns lyrics when found, None when not found """ MUSIXMATCH_KEY = get_musixmatch_key() api_query = 'https://api.musixmatch.com/ws/1.1/matcher.lyrics.get?' api_query += 'q_track=%s&' % title api_query += 'q_artist=%s&' % artist api_query += 'apikey=%s...
5,341,777
def string_avg(strings, binary=True): """ Takes a list of strings of equal length and returns a string containing the most common value from each index in the string. Optional argument: binary - a boolean indicating whether or not to treat strings as binary numbers (fill in leading zeros if lengths...
5,341,778
def refresh(): """Pull fresh data from Open AQ and replace existing data.""" DB.drop_all() DB.create_all() api = openaq.OpenAQ() status, body = api.measurements(city='Los Angeles', parameter='pm25') reading_list = [] for reading in body['results']: object = Record(datetime = reading[...
5,341,779
def personalize_patient_cellline(expression_data_flag="-e", expression_data=None, cnv_data_flag="-c", cnv_data=None, mutation_data_flag="-m", mutation_data=None, model_bnd_flag="-x", model_bnd=None, ...
5,341,780
def update_organization(current_user): """ Обновление информации об организации. """ try: if CmsUsers.can(current_user.id, "put", "contacts"): organization = CmsOrganization.query.first() update_data = request.get_json() for key in list(update_data.keys()): ...
5,341,781
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_sep] sep_base_path=/sepm/api/v1 sep_auth_path=/sepm/api/v1/identity/authenticate sep_host=<SEPM server dns name or ip address> sep_port=...
5,341,782
def create_users_table() -> None: """ SQL query that creates user table if it doesnt exist. Table order must match order defined on User class. """ sql = """CREATE TABLE IF NOT EXISTS users ( slack_id text UNIQUE NOT NULL PRIMARY KEY, slack_channel text UNIQUE, email text UNI...
5,341,783
def read_eieio_command_message(data, offset): """ Reads the content of an EIEIO command message and returns an object\ identifying the command which was contained in the packet, including\ any parameter, if required by the command :param data: data received from the network :type data: byte...
5,341,784
def test_outcomes_unwrap_raises_trio_error_over_qt_value(): """Unwrapping an Outcomes prioritizes a Trio error over a Qt value.""" class LocalUniqueException(Exception): pass this_outcome = qtrio.Outcomes( qt=outcome.Value(9), trio=outcome.Error(LocalUniqueException()), ) ...
5,341,785
def quote(): """Get stock quote.""" if request.method == "POST": # Get values get_symbol = request.form.get("symbol") stock = lookup(get_symbol) # Ensure symbol was submitted if not get_symbol: return apology("must provide symbol") # Ensure symbol ...
5,341,786
def counts_to_df(value_counts, colnames, n_points): """DO NOT USE IT! """ pdf = pd.DataFrame(value_counts .to_frame('count') .reset_index() .apply(lambda row: dict({'count': row['count']}, **d...
5,341,787
def make_pair_plot(samples, param_names=None, pair_plot_params=PairPlotParams()): """ Make a pair plot for the parameters from posterior destribution. Parameters ----------- samples : Panda's DataFrame Each column contains samples from posterior distribution. param...
5,341,788
def read_meta_soe(metafile): """read soe metadata.csv to get filename to meta mapping""" wavfiles = csv2dict(metafile) return {f['fid']:{k:v for (k,v) in f.items() if k!='fid'} for f in wavfiles}
5,341,789
def send_message(message, string, dm=False, user=None, format_content=True): """send_message Sends a message with string supplied by [lang]_STRING.txt files. :param message: MessageWrapper object with data for formatting. :param string: Name of the string to read. :param dm: Whether the message shou...
5,341,790
def calc_torque(beam, fforb, index=False): """ Calculates torque from a neutral beam (or beam component) torque = F * r_tan = (P/v) * r_tan = (P/sqrt(2E/m)) * r_tan = P * sqrt(m/(2E)) * r_tan :param fforb: :param index: :param beam: beam object with attributes z, m, a, en, pwr, rtan :return: t...
5,341,791
def test_sa_empty_commit(session): """Direct commit generates nothing """ session.commit() assert [t_writes, t_updates, t_deletes] == [[]] * 3
5,341,792
async def handle_token_job_transition(websocket): """Send several job status, and close with 4002.""" msg_out = WebsocketResponseMethod(type_="job-status", data={"status": "RUNNING"}) await websocket.send(msg_out.as_json().encode("utf8")) await asyncio.sleep(1) msg_out = WebsocketResponseMethod(typ...
5,341,793
def cli(ctx, user_id): """Create a new API key for a given user. Output: the API key for the user """ return ctx.gi.users.create_user_apikey(user_id)
5,341,794
def whitespace_tokenizer(text): """Tokenize on whitespace, keeping whitespace. Args: text: The text to tokenize. Returns: list: A list of pseudo-word tokens. """ return re.findall(r"\S+\s*", text)
5,341,795
def _u2i(number): """ Converts a 32 bit unsigned number to signed. If the number is negative it indicates an error. On error a pigpio exception will be raised if exceptions is True. """ v = u2i(number) if v < 0: if exceptions: raise error(error_text(v)) return v
5,341,796
def apply_once(func, arr, axes, keepdims=True): """ Similar to `numpy.apply_over_axes`, except this performs the operation over a flattened version of all the axes, meaning that the function will only be called once. This only makes a difference for non-linear functions. Parameters ---------- ...
5,341,797
def test_crop_all_returns_list(in_paths, output_dir, basic_geometry_gdf): """Test that crop all returns a list. """ img_list = es.crop_all( in_paths, output_dir, basic_geometry_gdf, overwrite=True ) assert type(img_list) == list
5,341,798
def _log_data(path, action_name, header, tag, log_metadata=False): """ Log data about a path or trajectory. @param path: trajectory after postprocessing @param action_name: name of Action that generated the trajectory @param header: one-letter header for logs @param tag: tag to filter trajector...
5,341,799