content
stringlengths
22
815k
id
int64
0
4.91M
def cheat_interest_points(eval_file, scale_factor): """ This function is provided for development and debugging but cannot be used in the final handin. It 'cheats' by generating interest points from known correspondences. It will only work for the 3 image pairs with known correspondences. Args:...
60,400
def get_person_speech_pair(file_name): """ XML parser to get the person_ids from given XML file Args: file_name(str): file name Returns: person_id_speech_pair(dict): Dict[person_id(int) -> speech(str)] """ person_id_speech_dict = dict() with open(file_name, encoding='utf-8') ...
60,401
def decode_jpeg(image_string: tf.Tensor, channels: int = 0) -> tf.Tensor: """Decodes JPEG raw bytes string into a RGB uint8 Tensor. Args: image_string: A `tf.Tensor` of type strings with the raw JPEG bytes where the first dimension is timesteps. channels: Number of channels of the JPEG image. Allowed...
60,402
def get_df(a: int) -> pandas.DataFrame: """ Generate a sample dataframe """ return pandas.DataFrame(data={"col1": [a, 2], "col2": [a, 4]})
60,403
def log_softmax(x): """Perform log softmax activation on the data Parameters ---------- data : tvm.te.Tensor 2-D input data Returns ------- output : tvm.te.Tensor 2-D output with same shape """ assert len(x.shape) == 2, "only support 2-dim log softmax" m, n = x...
60,404
def hours(datetime: dt.datetime) -> int: """ Returns the hours component for the given datetime value, in local time. """ return datetime.hour
60,405
def Call_setattr(t, x): """Translate ``setattr(foo, bar, value)`` to ``foo[bar] = value``.""" if (isinstance(x.func, ast.Name) and x.func.id == 'setattr') and \ len(x.args) == 3: return JSExpressionStatement( JSAssignmentExpression( JSSubscript(x.args[0], x.args[1]), ...
60,406
def skip_check(): """ Check if an environment variable was used to skip this actor """ if os.getenv('LEAPP_SKIP_CHECK_OS_RELEASE'): reporting.create_report([ reporting.Title('Skipped OS release check'), reporting.Summary('Source RHEL release check skipped via LEAPP_SKIP_CHECK_OS_...
60,407
def get_excessive_pdf(): """ this function is a generator to be used by 'remove_excessive_pdf()' """ categories = ['battery', 'catalysis', 'cells', 'city', 'dssc', 'light', 'nano', 'neel', 'solar', 'super alloy'] for category in categories: path_xml = r'/Users/miao/Desktop/PDFDataExt...
60,408
def triagToNormal(triag, M): """Convert triangular matrix to a regular matrix""" ar = np.arange(M) mask = ar[:, None] <= ar[None, :] x, y = np.nonzero(mask) new = np.zeros((M, M), dtype=triag.dtype) new[x, y] = triag return new + new.T
60,409
def search_users_by_id(dataset_path: str, users: list): """ Searches the number of movies and genres that a given user or a group of users watched. The number of movies watched are calculated by counting the number of movies that the user rated. The number of genres watched are calculated by counting a...
60,410
def bosch_shc_mock_async_zeroconf(mock_async_zeroconf): """Auto mock zeroconf."""
60,411
def get_fsl_metrics(datadir, subject_list): """ Calculates both dice similarity coefficients between FNIRT masks and ground truth lesionmasks as well as SSIM between FNIRT and FLIRT images. Input: data directory, subjects to calculate DSC and SSIM Output: list of DSCs and SSIM for each slice of eac...
60,412
def execute_parallel_functions_in_threads(tasks_groups: Deque[List[ThreadedFunctionData]], max_workers, timeout=None)\ -> List[Tuple[Future, str, str]]: """ This function takes a Queue (tasks_groups: Deque[List[ThreadedFunctionData]]) of lists, when each queued item represents a list of functions th...
60,413
def plot_entropy(probabilities, models_entropy): """ Replicates figure 3 from A Tutorial for Information Theory in Neuroscience. Args: probabilities (list): Probabilities for each model. models_entropy (list): Entropy for each model. """ states_vector = range(1, probabilities[0].sha...
60,414
def _download(pep_number): """ Fetches PEP files as HTML from python.org. """ # PEP URLs look like https://www.python.org/dev/peps/pep-0123/ url = f'https://www.python.org/dev/peps/pep-{_format_pep_number(pep_number)}/' response = requests.get(url) if response.status_code == 200: re...
60,415
def kwargs_function(**kwargs): """test with kwargs :param kwargs: default para eg. x=1 ; kwargs is dictionary :return: none """ for i in kwargs: print(kwargs[i])
60,416
def stretched_flow_para_function( x, beta, relaxation_rate, alpha, flow_velocity, baseline=1 ): """ flow_velocity: q.v (q vector dot v vector = q*v*cos(angle) ) """ Diff_part = np.exp(-2 * (relaxation_rate * x) ** alpha) Flow_part = ( np.pi ** 2 / (16 * x * flow_velocity) ...
60,417
def svn_path_is_url(path): """svn_path_is_url(char const * path) -> svn_boolean_t""" return _core.svn_path_is_url(path)
60,418
def random_key_generator(key_length): """ Creates a random key with key_length written in hexadecimal as string Paramaters ---------- key_length : int Key length in bits Returns ------- key : string Key in hexadecimal as string """ return bytes.hex(os.uran...
60,419
def process_error(err): """Special handling for consent_required""" body = err.body.decode('utf8') if "consent_required" in body: consent_scopes = ' '.join(DsConfig.permission_scopes()) consent_url = f"{DsConfig.auth_server()}/oauth/auth?response_type=code&scope={consent_scopes}&client_id={D...
60,420
def get_sheet(sheet_id, gid=None, use_cache=True): """Returns a list of rows from a sheet.""" query_dict = get_query_dict() force_cache = RELOAD_ACL_QUERY_PARAM in query_dict cache_key = 'google_sheet:{}:{}'.format(sheet_id, gid) logging.info('Loading Google Sheet -> {}'.format(cache_key)) resul...
60,421
def _make_geometry_1_file(filename): """See n.comment for details.""" n = netCDF4.Dataset(filename, "w", format="NETCDF3_CLASSIC") n.Conventions = "CF-" + VN n.featureType = "timeSeries" n.comment = ( "Make a netCDF file with 2 node coordinates variables, each of " "which has a corr...
60,422
def bootstrap_classify(sample_list, fout, header=False, metrics=None, cutoff_t=0.07, cutoff_min=4, mad=7): """ Get cluster_distance, cluster_cutoff, and global_coverage for a sample """ # Skip header if header: sample_list.next() # header_fmt = "%s\t" * 4 + "%s\n...
60,423
def conv_forward_im2col(x, w, b, conv_param): """ A fast implementation of the forward pass for a convolutional layer based on im2col and col2im. """ N, C, H, W = x.shape num_filters, _, filter_height, filter_width = w.shape stride, pad = conv_param["stride"], conv_param["pad"] # Check ...
60,424
def get_model(pretrained=True): """Function to obtain a pytorch resnet50 model with modified final layer Args: pretrained (bool): whether to use pretrained weights of the resnet50 model Returns: model (pytorch model): a pytorch model with resnet50 architecture with ...
60,425
def dilation_dependent(input_tensor: torch.Tensor, structuring_element: torch.Tensor, origin: Optional[Union[tuple, List[int]]] = None, border_value: Union[int, float, str] = 'geodesic'): """ This type of dilation is needed when you want a structu...
60,426
def audio_process(songname: str) -> pd.DataFrame: """ :rtype: DataFrame of all the features """ y, sr = librosa.load(songname, mono=True, duration=30) rmse = librosa.feature.rms(y=y) chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr) spec_cent = librosa.feature.spectral_centroid(y=y, s...
60,427
def estimate_fundamental_matrix(points_a, points_b): """ Calculates the fundamental matrix. Try to implement this function as efficiently as possible. It will be called repeatedly in part 3. You must normalize your coordinates through linear transformations as described on the project webpage befor...
60,428
def insert_to_weekday_table(dbName: str, df: pd.DataFrame, table_name: str) -> None: """ Parameters ---------- dbName : str: df : pd.DataFrame: table_name : str: dbName : str: df : pd.DataFrame: table_name : str: dbName:str : ...
60,429
def main(video_dir, elan_dir, output_dir, padding_format=0.1, num_jobs=1, tmp_dir='/tmp/video_trim', check=False): """ The main function for cropping videos in a folder """ # Sanity check (if we have all files / folders) files = check_folders(video_dir, elan_dir, tmp_dir, output_d...
60,430
def maincgi(): """SWRC Fit to run as CGI""" import cgi from io import TextIOWrapper import unsatfit f = unsatfit.Fit() if DEBUG: import cgitb cgitb.enable() # Change encoding of stdout to utf-8 # It is required becaue CGI script runs as another user and may not # pr...
60,431
def qg8_chunk_get_type(chunk: qg8_chunk): """ Return the chunk type as an integer """ if not isinstance(chunk, qg8_chunk): raise TypeError("Argument is not a qg8_chunk") return chunk.type
60,432
def agg_func(data:pd.DataFrame, object_column:str, agg_list=['nunique', 'count'])->pd.DataFrame: """ Parameters ---------- data:pd.DataFrame : object_column:str : agg_list : (Default value = ['nunique', 'count'] : Returns ------- A dataframe with...
60,433
def update_top_config_in(top_config_in): """ Extra updates for build/Config.in """ contents = [] patten = re.compile(r".*(NULL|Null).*") with open (top_config_in, "r") as cf: for line in cf.readlines(): match = patten.match(line) if match: continue ...
60,434
def _process_triggers(buffers, out_file, draw_png, json_dict): """Save the buffers if necessary and report their averages.""" if out_file: csv_file = _replace_file_suffix(out_file, '.csv') if json_dict: json_dict['CSV_FILE'] = csv_file with open(csv_file, "w", newline='') as ...
60,435
async def test_kubernetes_score_failing_metrics_provider( aiohttp_server, config, db, loop ): """Test the error handling of the Scheduler in the case of fetching the value of a metric (referenced by a Cluster) from its provider, but the connection has an issue. """ routes = web.RouteTableDef() ...
60,436
def get_audits(): """Get OS hardening login.defs audits. :returns: dictionary of audits """ audits = [TemplatedFile('/etc/login.defs', LoginContext(), template_dir=TEMPLATES_DIR, user='root', group='root', mode=0o0444)] return audits
60,437
def test_init_default_values(): """Attrs get set to their default values""" c = CountStore() s = SendTimeData(c) assert s._countstore is c assert s._flushwait == 2 assert s._channel is stat.timedata
60,438
def do_load_list(cc, args): """List all loads.""" loads = cc.load.list() field_labels = ['id', 'state', 'software_version'] fields = ['id', 'state', 'software_version'] utils.print_list(loads, fields, field_labels, sortby=0)
60,439
def draw_component_loss_barchart_s3(ctype_resp_sorted, scenario_tag, hazard_type, output_path, fig_name): """ Plots bar charts of direct economic losses for components type...
60,440
def test_xpub_and_subaccount_search(mock_bitcoincore): """Test that the options --ga-xpub and --search-subaccounts are mutually exlcusive""" mock_bitcoincore.return_value = AuthServiceProxy('testnet_txs') estimate = {'blocks': 3, 'feerate': 1, } mock_bitcoincore.return_value.estimatesmartfee.return_valu...
60,441
def train(): """ train model, then construct post-processing network """ # load mnist data transform = Compose([Normalize(mean=[127.5], std=[127.5], data_format='CHW')]) train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform) test_dataset = paddle.vision.datasets.MNI...
60,442
def username_exists(username): """ Checks if a username aldready exists :param username: username to be checked :return: Boolean indicating whether the username exists or not :rtype: boolean """ return not User.query.filter_by( username=username).first() is None
60,443
def import_series_from_dump( sources, rectype, loader_class=CDSSeriesDumpLoader ): """Load serial records from given sources.""" if rectype == "serial": dojson_model = serial_marc21 elif rectype == "multipart": dojson_model = multipart_marc21 else: dojson_model = journal_marc...
60,444
def group_difference(shap_values, group_mask, feature_names=None, xlabel=None, xmin=None, xmax=None, max_display=None, sort=True, show=True): """ This plots the difference in mean SHAP values between two groups. It is useful to decompose many group level metrics about the model output...
60,445
def buy_ticket(email,price,name,quantity): """ Update user balance :param email: email of user :param price: price of ticket :param name: name of ticket :param quantity: quantity to buy """ user=User.query.filter_by(email=email).first() user.balance=int(float(user.balance)-float(pric...
60,446
def test_validators(): """Tests of validatorfuncs.py that aren't covered elsewhere""" # PercentageString with raises(Invalid, match="Not a valid percentage string"): validatorfuncs.PercentageString("mess%") # ListOfType testfunc = validatorfuncs.ListOfType(int) assert testfunc([1, 2, 3]...
60,447
def rand_precision_mat(lat_row, lat_col, max_neighbors=8, rho=1): """Generate a random spatial precision matrix. The spatial precision matrix is generated using a rectengular lattice of dimensions `lat_row` x `lat_col`, and thus the row and colum size of the matrix is (`lat_row` x `lat_col`). Para...
60,448
def generate_df(cols_to_keep: List[str]) -> pd.DataFrame: """Generates the cleaned dataframe.""" df = pd.read_csv(CSV_URL) for col in INTEGRAL_COLS: df[col] = df[col].astype('Int64') if col.endswith('_flag'): assert get_unique_values(df[col]) == [0, 1, pd.NA] df = pd.merge(d...
60,449
def scrape_attackdex( save_csv: bool = True, file_path: str = 'data/attackdex.csv' ) -> pd.DataFrame: """Return dataframe of scraped attack data from serebii.net""" gen_dict = { 1: '-rby', 2: '-gs', 3: '', 4: '-dp', 5: '-bw', 6: '-xy', 7: '...
60,450
def get_ppm_df(): """Get a pandas dataframe containing all PPM data. Returns: pd.DataFrame: PPM Pandas dataframe """ if app.mongo is None: return None docs = app.mongo.get("PPM") if docs is None: return None ppm_dict = { "date": [], "total": [], ...
60,451
def utc2local(utc_dtm): """ UTC 时间转本地时间( +8:00 ) :param utc_dtm: :return: """ local_tm = datetime.fromtimestamp(0) utc_tm = datetime.utcfromtimestamp(0) offset = local_tm - utc_tm return utc_dtm + offset
60,452
def add_base_args(parser: argparse.PARSER, exp='sandbox', dataset='shapes'): """base experiments arguments use across all exps""" parser.add_argument('--dataset', default=dataset, help='dataset [shapes | binmnist | omniglot | fashion | gmm-toy | gaussian-toy]') parser.add_argument('-...
60,453
def make_serviceitem_servicedll(servicedll, condition='contains', negate=False, preserve_case=False): """ Create a node for ServiceItem/serviceDLL :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/serviceDLL' content_type = 'strin...
60,454
def func6(): """ Get an item and predict with upload """
60,455
def main() -> None: """ Calculate and output the solutions based on the real puzzle input. """ data = aocd.get_data(year=2016, day=12) print(f'Part 1: {run_program(data).get("a")}') print(f'Part 2: {run_program(data, 1).get("a")}')
60,456
def load_dataset_with_augmentation(source_dir, augmentation=None, min_count=None): """ Wczytanie sampli z opcjonalną augmentacją. Użyć parametru augmentation albo min_count, nie obu na raz. :param source_dir: katalog źródłowy z plikami PNG. :param augmentation: krotność augmentacji. :param min_coun...
60,457
def test_list_unsigned_int_min_length_nistxml_sv_iv_list_unsigned_int_min_length_1_5(mode, save_output, output_format): """ Type list/unsignedInt is restricted by facet minLength with value 5. """ assert_bindings( schema="nistData/list/unsignedInt/Schema+Instance/NISTSchema-SV-IV-list-unsignedIn...
60,458
def get_mse(prices, predictions): """Get the mean squared error of a network by analysing actual price and the network's corresponding predictions. :rtype: float64 :param prices: the prices that the predictions aim to mimic :param predictions: the predictions :return: the mean-squared error of ...
60,459
def test_read_predictions( test_app, user_auth_headers, multiple_new_predictions ): """Test getting all predictions from predictions table.""" # Verify input with authentication returns all predictions in predictions # table endpoint = "/api/v1/topics/read_predictions" r = test_app.get(endpoint,...
60,460
def test_action_create_post_multipart_form_zero_files_fails( app: Flask, indieauthfix: IndieAuthActions, client: FlaskClient, testconstsfix: TestConsts, ): """Zero files should fail""" with app.app_context(): z2btd = indieauthfix.zero_to_bearer_with_test_data() headers = Headers(...
60,461
def find_k_neighbors(): """Receiving input and returning closest neighbors""" input_dict = json.loads(request.get_json()) # print(pd.json_normalize(input_dict).info()) result = KNN.kneighbors( TRANSFORMER.transform(pd.json_normalize(input_dict)), return_distance=False) return jsoni...
60,462
def get_databases(task=None): """Get list of databases Parameters ---------- task : str, optional Only returns databases providing protocols for this task. Defaults to returning every database. Returns ------- databases : list List of database, sorted in alphabetica...
60,463
def dimensions(image: np.ndarray, kernel: np.ndarray, padding:int, strides:int) -> np.ndarray: """ See https://medium.com/analytics-vidhya/2d-convolution-using-python-numpy-43442ff5f381 :param image: :param kernel: :param padding: :param strides: :return: """ x_kern_shape = kernel.sh...
60,464
def intcode_comp(puzzle_input, phase_setting, input_signal): """Compute based on the intcode instructions below # position mode: # 1: positional add # 2: positional multiply # 3: get input and save it at location of parameter # 4: output value located at parameter # immediat...
60,465
def watch_insert_queue(queue, queue_name, counter_name, engine, stop_event, sleep_time=5): """ A worker process to be launched in a thread that will asynchronously insert or update objects in the Session using dicts pulled from a redis queue. Using this queuing approach many cluster jobs are able to pu...
60,466
def copy(cell: SpiceCell) -> SpiceCell: """ Copy the contents of a SpiceCell of any data type to another cell of the same type. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/copy_c.html :param cell: Cell to be copied. :return: New cell """ assert isinstance(cell, stypes.Spic...
60,467
def get_list_of_audios(folder_path, audio_extension = 'wav', confirm_with_transcript = True, verbose = False): """ Confirm_with_transcript requires: file path in first column To-do: check if in csv file the header_none will throw count the header as the first ro...
60,468
def get_hash_hex(raw_hash): """Creates a nice hex representation of a raw req""" return raw_hash.encode('iso-8859-1').encode('hex')
60,469
def new_document(source_path: str, settings: Any = None) -> nodes.document: """Return a new empty document object. This is an alternative of docutils'. This is a simple wrapper for ``docutils.utils.new_document()``. It caches the result of docutils' and use it on second call for instanciation. This m...
60,470
def to(config, restart): """ Switch to specified configuration file """ userSystem = platform.system() if vlc_running(userSystem): click.echo('VLC is running, stopping it') if userSystem == 'Windows': subprocess.call('taskkill /F /IM vlc.exe', shell=True) elif userSystem =...
60,471
def guild_only() -> AC: """A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.ApplicationNoPrivateMessage` that is inherited from :exc:`.ApplicationC...
60,472
def importable_name(cls): """ >>> class Example(object): ... pass >>> ex = Example() >>> importable_name(ex.__class__) 'jsonpickle.util.Example' >>> importable_name(type(25)) '__builtin__.int' >>> importable_name(None.__class__) '__builtin__.NoneType' >>> importable_n...
60,473
def loadDictDDIs(path_file:str): """ load the ddi source if the pickle file already existe :param path_file: path of the picke file :type path_file: str :return: dictionary with the ddis sources ids :rtype: dict[(domain_id_a, domain_id_b)] : id sources """ dict_ddis_source_data = {}...
60,474
def print_and_log(msg, log_file, write_mode='a'): """ print `msg` (string) on stdout and also append ('a') or write ('w') (default 'a') it to `log_file` """ print(msg) with open(log_file, write_mode) as f: f.write(msg + '\n')
60,475
def gen_client(api_id: str, api_hash: str) -> Client: """Generates Client instance, nothing special Args: api_id (str): Telegram App API ID api_hash (str): Telegram App API Hash key Returns: Pyrogram::Client """ return Client( "tgresender", api_id=api_id, ...
60,476
def encode_argument_text_from_spans(arguments: Iterable[Argument], tokens: List[str]) -> str: """ Return a string for the CSV field 'answer' """ return SPAN_SEPARATOR.join([span_to_text(span, tokens) for span in arguments])
60,477
def get_folder_size_human(path, container: DockerContainer): """disk usage in human readable format (e.g. '2,1GB')""" cmd_folder_size = "du -sh {}".format(path) result = DockerUtils.run_cmd(cmd=cmd_folder_size, container=container) return result.split()[0].decode('utf-8')
60,478
def is_input_type(graphql_type: "GraphQLType") -> bool: """ Determines whether or not the "GraphQLType" is an input type. :param graphql_type: schema type to test :type graphql_type: GraphQLType :return: whether or not the "GraphQLType" is an input type. :rtype: bool """ return isinstanc...
60,479
def which_package(path): """ given the path (of a (presumably) conda installed file) iterate over the conda packages the file came from. Usually the iteration yields only one package. """ path = abspath(path) prefix = which_prefix(path) if prefix is None: from ..exceptions impor...
60,480
def update_counter(new_d_counter, new_a_counter): """ This function saves the counters of the amount of payload (data and audio) received in a file Args: new_d_counter (integer): The new data counter new_a_counter (integer): The new audio counter Returns: No returns """ ...
60,481
def shuffle(x): """ Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remain the same. Parameters ---------- x: _Symbol The array o...
60,482
def write_vector_binary(fn, X, dtype="int"): """ write 1darray to binary file @param @return """ with open(fn, "wb") as fo: outdata = "" if dtype == "int": fmt = "i" elif dtype == "short": fmt = "h" elif dtype == "float": fmt = "f" ...
60,483
def cartao_trello(request, pedido=None, desc=None): """Responsavel por enviar ao cartao trello.""" cliente = TrelloClient(api_key=API_KEY, api_secret=API_TOKEN) my_boards = cliente.get_board('kyL57xiF') lista = my_boards.all_lists() pedido = json.dumps(pedido, cls=UUIDEncoder) desc = serializer...
60,484
def modify_submit_scripts(filename, jobid, cores=8): """Modify the submission scripts to include the job and simulation type in the header.""" with open("submit.pbs", "r") as f: lines = f.readlines() lines[1] = "#PBS -N {}\n".format(jobid) with open("submit.pbs", "w") as f: f.writeli...
60,485
def flush_database(redis: Redis) -> None: """Flushes our database.""" redis.flushdb() print("Database flushed!")
60,486
def data_reorg_half_daily(instrument_type) -> pd.DataFrame: """ 将每一个交易日主次合约合约行情信息进行展示 :param instrument_type: :return: """ # engine = Config.get_db_engine(Config.DB_SCHEMA_PROD) engine = Config.get_db_engine(Config.DB_SCHEMA_DEFAULT) sql_str = r"select lower(instrument_id) instrument_i...
60,487
def assign_boxes_to_levels(boxlist, min_level, max_level, canonical_box_size, canonical_level): """ Map each box in `box_lists` to a feature map level index and return the assignment vector. Args:...
60,488
def spectral_maxpeaks(sign, FS): """Compute number of peaks along the specified axes. Parameters ---------- sig: ndarray input from histogram is computed. fs: int sampling frequency of the signal Returns ------- num_p: float total number of peaks """ f, ...
60,489
def get_calling_module(point=2): """ Return a module at a different point in the stack. :param point: the number of calls backwards in the stack. :return: """ frm = inspect.stack()[point] function = str(frm[3]) line = str(frm[2]) modulepath = str(frm[1]).split('/') module = str(...
60,490
def raises_on_dir_fd(dir_fd): """ Raise on use of dir_fd Args: dir_fd: Checks if None Raises: NotImplementedError: dir_fd is not None. """ if dir_fd is not None: raise ObjectNotImplementedError(feature="dir_fd")
60,491
def upgrade(ctx, revision="head", sql=False, tag=None): """Upgrade to a later version""" command.upgrade(ctx.obj["migrations"], revision, sql=sql, tag=tag)
60,492
def _pad_keys_tabular(data, sort): """Pad only the key fields in data (i.e. the strs) in a tabular way, such that they all take the same amount of characters Args: data: list of tuples. The first member of the tuple must be str, the rest can be anything. Returns: list with the strs padded with space cha...
60,493
def depth_based_median( X: FDataGrid, depth_method: Optional[Depth] = None, ) -> FDataGrid: """Compute the median based on a depth measure. The depth based median is the deepest curve given a certain depth measure. Args: X: Object containing different samples of a functiona...
60,494
def get_read_only_permission_name(model: str) -> str: """ Create read only permission human readable name. :param model: model name :type model: str :return: read only permission human readable name :rtype: str """ return f"{settings.READ_ONLY_ADMIN_PERMISSION_NAME_PREFIX.capitalize()}...
60,495
def _determine_colnums_to_yield(colnames, fname, dtype_fname): """Return a list of integers storing the column numbers of the ASCII history file corresponding to the ordered sequence determined by the input ``colnames``. """ colnames = np.atleast_1d(colnames) colnames = [s.lower() for s in colnames]...
60,496
def get_all_countries(): """Returns all countries""" url = BASE_URL + "all" return _get(url=url)
60,497
async def find_channel(ctx, userstr, interactive=False, collection=None, chan_type=None): """ Find a guild channel given a partial matching string, allowing custom channel collections and several behavioural switches. Parameters ---------- userstr: str String obtained from a user, expec...
60,498
def df_params_generator(number_of_facilities, number_of_tasks, seed=0): """ Generate instance parameters for the df problem set mentioned in [1]. Parameters ---------- number_of_facilities: int the number of facilities to schedule on number_of_tasks: int the number of tasks to a...
60,499