content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def lzo_stream(*, length: int = 4096): """ Compress a string of null bytes, the length being defined by the argument to this function. """ compressor = Popen(["lzop", "-c"], stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = compressor.communicate(input=b"\x00" * length) if stderr: ...
a44d8b37384ad29d19c35b8f28ddbcbc3f6308e3
48,200
async def buy(client, event, item: (ShopItem.item_choices(), "Buy cat items with your Neko coins (NC).")): """Buy cat items with your Neko coins (NC).""" neko_coins = await get_coins_helper(event.user.id) selected_item: ShopItem = ShopItem[item] new_balance = neko_coins - selected_item.price if new_...
d2d05f08f49cf873f4ef48dd98a10c1db593b061
48,201
import htcondor def config_val(attr): """Query HTCondor for the value of a configuration variable using the python bindings if available, condor_config_val otherwise """ try: # Necessary for checking config between different flavors of HTCondor htcondor.reload_config() try: ...
c9bff2321b615939c4a4dcffe01a19718782d882
48,202
def like(lhs: str, pattern: str, wildcard: str, singlechar: str, escapechar: str, not_: bool = False, ) -> 'elasticsearch_dsl.query.Query': """ Create a filter to filter elements according to a string attribute using wildcard expressions. :param...
31c23a2a255f8d39bef0ba9e9c2f33e04c5e94d1
48,203
def bug_to_response(bug, detailed=True): """Convert a Bug entity to a response object.""" response = osv.vulnerability_to_dict(bug.to_vulnerability()) response.update({ 'isFixed': bug.is_fixed, 'invalid': bug.status == osv.BugStatus.INVALID }) if detailed: add_links(response) add_source_i...
b250339d65db15a777f86f81ed44b4cb42e8b8fe
48,204
import sys from sys import path def get_current_path() -> str: """Get current path of script/executable""" application_path = "" if getattr(sys, "frozen", False): application_path = path.dirname(sys.executable) elif __file__: application_path = path.dirname(__file__) return appl...
e582f638d4f95ab57cb21dc154c11a94ec78488e
48,205
import os import json def get_pmc(uid, metadata_df, directory='data/cord-19/'): """ In: uid [str]: cord-uid of required file metadata_df: DataFrame containing metadata for file Returns: json of required file""" uid_df = metadata_df[metadata_df.cord_uid == uid] pmc = uid_df.il...
da8d0825272493dceb0ce26d98410f9a5481acf6
48,206
import ipaddress def parse_cidr(value): """Process cidr ranges.""" klass = IPv4Network if '/' not in value: klass = ipaddress.ip_address try: v = klass(str(value)) except (ipaddress.AddressValueError, ValueError): v = None return v
4bf2fbbf39558421b397be3d85719cb85bfecf46
48,207
def lab_mean_std(im_input, mask_out=None): """Compute the mean and standard deviation of the intensities. ... of each channel of the given RGB image in LAB color space. The outputs of this function is for reinhard normalization. Parameters ---------- im_input : array_like An RGB image ...
89a8f13882d4aabb41310182e52cad85dab2f6d8
48,208
import requests def sel(host, args, session): """ prints out the bmc alerts @param host: string, the hostname or IP address of the bmc @param args: contains additional arguments used by the sel sub command @param session: the active session to use @param ar...
3fb583d7f8ddbade281b5975b9f9a7dd21b0caef
48,209
import errno import csv def read_order_metrics(csvfile, required=False): """ Read oredred metrics. Routine to read in ordered list of metrics csv file. Not really csv but easily read in by csv package. This is a line by line ordered list of the metrics that will be plotted on a NAC plot. It shou...
c2ec2329459aad5c57b3feaa900aaf34e9927f8f
48,210
from django.contrib.auth.views import redirect_to_login def request_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the request passes the given test, redirecting to the log-in page if necessary. The test sho...
e7559e94dcb60dc436b931b27c9af641558650a8
48,211
def generate_dataset_code(id): # noqa: E501 """generate_dataset_code Generate sample code to use dataset in a pipeline # noqa: E501 :param id: :type id: str :rtype: ApiGenerateCodeResponse """ return util.invoke_controller_impl()
2acb572bf55a7edcd52bce682814e179f28e6bb5
48,212
import resource def GetManagedRelationalDbClass(cloud): """Get the ManagedRelationalDb class corresponding to 'cloud'. Args: cloud: name of cloud to get the class for """ return resource.GetResourceClass(BaseManagedRelationalDb, CLOUD=cloud)
562b17daab2c9b96548eecdb3154b59fe4c62b4a
48,213
import os def main(): """ Main route """ # Query logs query_logs = [] # Update params with user's settings params = get_params() # Get query default_user_query = "What do we know about Chloroquine to treat covid-19?" try: user_query = str( request.form["user_quer...
6698e46a080ea7e87ae0ce061223315de9d27422
48,214
import re def normalize_summary(summary): """Return normalized docstring summary.""" # Remove newlines summary = re.sub(r'\s*\n\s*', ' ', summary.rstrip()) # Add period at end of sentence if ( summary and (summary[-1].isalnum() or summary[-1] in ['"', "'"]) and (not summar...
002e72668e87d668c2d6df678092ac57fc2b1d37
48,215
import torch def compute_metrics(data , pred_transforms): """ Compute metrics required in the paper """ def square_distance(src, dst): return torch.sum((src[:, :, None, :] - dst[:, None, :, :]) ** 2, dim=-1) with torch.no_grad(): pred_transforms = pred_transforms gt_transf...
5c27279448542994560ecb0ee5d3b47b1fe079be
48,216
def get_datetime_timedelta_conversion(datetime_unit, timedelta_unit): """ Compute a possible conversion for combining *datetime_unit* and *timedelta_unit* (presumably for adding or subtracting). Return (result unit, integer datetime multiplier, integer timedelta multiplier). RuntimeError is raised i...
02ab9ecb182ed1cfcec4138cb9ac5f576411e8a9
48,217
def create_workflow_to_resample_baw_files(name="ResampleBAWOutputs"): """ This function... :param name: :return: """ workflow = Workflow(name) inputs_to_resample = ["t1_file", "t2_file", "hncma_file", "abc_file"] other_inputs = ["reference_file", "acpc_transform"] label_maps = ["hnc...
73146fee1f8acb6d31e3b804efde78e57ec6a617
48,218
def absorb(expression): """ A AND (A OR B) -> A A OR (A AND B) -> A A AND (NOT A OR B) -> A AND B A OR (NOT A AND B) -> A OR B """ if isinstance(expression, exp.And): return _absorb(expression, exp.Or) if isinstance(expression, exp.Or): return _absorb(expression, exp.And)...
fa6814aea142651f46fd0311df18130cf6d39653
48,219
def gen_data(shape_matrix, shape_diagonal, dtype): """generate valid data to test""" input_matrix = random_gaussian(shape_matrix, miu=10, sigma=0.3).astype(dtype) input_diagonal = random_gaussian(shape_diagonal, miu=5, sigma=0.3).astype(dtype) # make shape_diagonal can support broadcast if shape_mat...
69f97f0372a964d923bf584a8da6998b357ef03f
48,220
def pe_7(): """Return the 10,001st prime number.""" primes = list(lpe.prime_sieve(2_000_00)) primes.sort() return f'The 10,001st prime number is {primes[10_000]:,}.'
9b60be4d0e3d3f2502fee94bce5462e9bb3e93a4
48,221
def minimal_stat_test(agonists, antagonists, stat_test, start, stop, threshold=0.05, cache=None): """ Inputs a list of agonists and a list of antagonists and finds the most significant residues. We do not return the p_value but only the residue ids. .. note:: RMSF calculations are cached to a...
82b71dfedd2e8c9def77e969515aaa0827aee516
48,222
import torch def variance(values): """ Variance function. """ mean_value = mean(values) var = 0.0 for value in values: var = var + torch.sum(torch.sqrt(torch.pow(value-mean_value,2))).item()/len(values) return var
38be900320427475b30c40d9364649243b4c9752
48,223
import subprocess def task_lint(): """Check linting""" def run(args): args = args or [] subprocess.run( ['flake8', 'ruly', 'test', 'setup.py', 'dodo.py', *args]) return {'actions': [run], 'pos_arg': 'args'}
f152eecd3fa21e62502ebf0223046ce75807e098
48,224
def update_link(): """ This is a route for ALL NODES. When a new node is inserted in the RING (via the '/bootstrap/node/join' route), then the neighbors of that node must update their links, so that they point at that new node. """ prev_or_next = request.form['prev_or_next'] if prev_or_next...
71d5d2da5d7b61f65868f3b7c65f7133ba7ac8ff
48,225
from typing import Optional from typing import Sequence from typing import Tuple def instances_to_boxes_np( seg: np.ndarray, dim: int = None, instances: Optional[Sequence[int]] = None, ) -> Tuple[np.ndarray, np.ndarray]: """ Convert instance segmentation to bounding boxes (not batched) Ar...
c0a4aace311ac5b07a1168f94b89d3de6fa5f049
48,226
import argparse def parseargs(description: Text) -> argparse.ArgumentParser: """ Parse arguments """ parser = argparse.ArgumentParser( allow_abbrev=False, description=description ) parser.add_argument("--server", help="Mattermost Server") parser.add_argument("--user", help="Matter...
95c127bf73360afe7227f01ca9591864f1ccd614
48,227
import hashlib def md5_key(string): """ Use this to generate filenae keys """ m = hashlib.md5() m.update(string.encode('utf-8')) return m.hexdigest()
ffa2d26933b5a18f43d2c8ed696e880a38039ece
48,228
def run_all_gluon_nn_loss_operations_benchmarks(ctx, inputs): """Helper to run all Gluon Loss Layer benchmarks. Just runs the benchmarks with default input values. This is just a utility to run benchmarks with all default input values. :return: list[dict], list of dictionary of benchmark results. Each item...
7d3e1c6835292051277d35c3d13865985c257a31
48,229
def name_to_hash(name: str) -> int: """ given a name, generate a unique-ish number. cannot simply use hash(), since that is different each time we re-run the process... """ hash_v = sum([ord(c) for c in name]) print('hash_v', hash_v) return hash_v
e707d401911d7ca41b019e73d1afcd0c66fe045e
48,230
def attack_targets_by_country(country): """Returns the targets list with the corresponding number of attacks in descending order of the given country.""" cur = get_db().execute('SELECT targtype1_txt, num_attacks FROM (SELECT targtype1_txt, COUNT(targtype1_txt) num_attacks FROM Attacks WHERE iso_code="{}" GROUP ...
ded89ef143ad1db373fa495edc1f9a05859721dd
48,231
def calculate_average(list_of_nums): """Calculates the average of a list of numbers.""" average = calculate_sum(list_of_nums) / len(list_of_nums) return average
122fc06e55f5932c088712777691179047cce3eb
48,232
def query_introspection() -> str: """Retrieve available queries.""" return """query { __type(name: "Query") { kind name fields { name description args { name description defaultValue } ...
f01c4a79517b60a5c130805a673665b9bfae858e
48,233
def re_exp_matching_backward(s, p): """ :type s: str for match :type p: pattern str :rtype: match or not """ def is_match(chr_for_match, match_pattern): return match_pattern == '.' or match_pattern == chr_for_match def match_core(str, pattern): if pattern < 0: re...
03fb3bb85123435779b46086b1c2ef1705b686f3
48,234
def _batched_table_lookup(tbl, row, col): """Mapped 2D table lookup. Args: tbl: a `Tensor` of shape `[r, s, t]`. row: a `Tensor` of dtype `int32` with shape `[r]` and values in the range `[0, s - 1]`. col: a `Tensor` of dtype `int32` with shape `[r]` and values in the range `[0, t - 1]`. ...
048100b750a91afe2f6809950a0c97d2cc482fce
48,235
def avg_pool2d(inputs, kernel_size, scope, stride=[2, 2], padding='VALID'): """ 2D avg pooling. Args: inputs: no_dropout-D tensor BxHxWxC kernel_size: a list of 128 ints stride: a list of 128 ints Returns: Variable tensor ...
fe8c7825832b9b13f0f363036d82d0198ff913f3
48,236
import scipy def repressilator(): """Replaces the plot of the protein-only repressilator. Replaces Python code: def repressilator_rhs(x, t, beta, n): ''' Returns 3-array of (dx_1/dt, dx_2/dt, dx_3/dt) ''' x_1, x_2, x_3 = x return np.array( [ ...
f4446493d3552fc6f1006f65cccaea194bc56dd9
48,237
def date_list(start, end): """ :param start: year start; format: 2017, int :param end: year end; format: 2019, int :return: a list include all the month """ assert int(start / 1000) == 0 or type(start) is int, 'start error' assert int(end / 1000) == 0 or type(end) is int, 'end error' ...
4af977d47e611013ead4dd6538e7bdcbb87bf5be
48,238
def get_y_axis_max(x, chr=None, start=0, end=0, fix_end=True): """ Parameters ---------- x : list A list of bigwig files chr : str The name of chromosome start : int The start position end : int The end position, 0 indicate t...
4154ff99805321801c43bb2bdafaf8de983da066
48,239
def index(): """ Module's Home Page """ response.view = "mad/index.html" module_name = deployment_settings.modules[module].name_nice response.title = module_name return dict(module_name=module_name)
2e18da3d02bcae6b34f920dc0bb1a800e4d541c5
48,240
def reflect_coef(ip): """ Computes the reflection coefficient for a plane incident P-wave. Parameters ---------- ip : array P-impedance. Returns ------- rc : array The reflection coefficient """ rc=(ip[1:]-ip[:-1])/(ip[1:]+ip[:-1]) rc=np.append(rc,rc[-1]...
9ff8c8e103bca6b9cc79663daca8610adfdc954a
48,241
import torch def subsequent_mask(size: int) -> Tensor: """ Mask out subsequent positions (to prevent attending to future positions) Transformer helper function. :param size: size of mask (2nd and 3rd dim) :return: Tensor with 0s and 1s of shape (1, size, size) """ mask = np.triu(np.ones((...
7f4b11b7b62441991ae095b9a15b0111ad6e90e1
48,242
def list_reuters_codes(codes=None, report_types=None, statement_types=None): """ List available Chart of Account (COA) codes from the Reuters financials database and/or indicator codes from the Reuters estimates/actuals database Note: you must collect Reuters financials into the database before you can...
50854e075022aaaa31bb54fe4c034ac66904cf18
48,243
def waveletdec(s, wavelet, lvl, coord): """ Decompose . Args: s (list): list of numbers representing time-series signal wavelet (string): name of the wavelet; ex: 'sym2', 'bior1.3', etc. lvl (int): level of decomposition; length of coeffs will be lvl+1 coord (str): genomic coordi...
916cb3f11f176b4ef8c97cea9c3fbae8e6939ea1
48,244
def concatenate_datasets(current_images, current_labels, prev_images, prev_labels): """ Concatnates current dataset with the previous one. This will be used for adding important samples from the previous datasets Args: current_images Images of current dataset current_labels Lab...
b7183adf59bc0be95995db7764a826dec4926a18
48,245
def dot(v: Vector, w: Vector) -> float: """Returns v_1 * w_1 + ... + v_n * w_n""" assert len(v) == len(w), "vectors must be same length" return sum(v_i * w_i for v_i, w_i in zip(v, w))
da0744bc6cd838f6bcbb06479bed0bcdcbbb2836
48,246
def ww_sim(word, mat, topn=10): """Calculate topn most similar words to word""" index = tok2index[word] if isinstance(mat, sparse.csr_matrix): v1 = mat.getrow(index) else: v1 = mat[index:index+1, :] sims = cosine_similarity(mat, v1).flatten() sindexs = np.argsort(-sims) sim_w...
aee7528805ad069f921441c85cbfde655a7a92a9
48,247
import re def count_characters(text, whites=False): """ Get character count of a text Args: whites: If True, whitespaces are not counted """ if whites: return len(text) else: return len(re.sub(r"\s", "", text))
e4db9e873e800282cf7f2398272a8b4546fe171e
48,248
def get_posixtime_from_uuid(uuid1): """Convert the uuid1 timestamp to a standard posix timestamp """ assert uuid1.version == 1, ValueError('only applies to type 1') t = uuid1.time t = t - 0x01b21dd213814000 t = t / 1e7 return t
1e7751026aae6d0534403707d89fee8e99984137
48,249
import re def remove_html(raw_text): """ Remove html tags """ text = str(raw_text) cleaner = re.compile('<.*?>') text = re.sub(cleaner, '', text) return text
397b49c052e055a71876d9883ab259f871b5015e
48,250
def process_special_event(events_list: str) -> tuple: """Gets word list from parse events and turns into list""" in_key_dicts = [ x in shift_key_codes or x in modifier_codes or x in codes for x in events_list ] final_keys = [] if False not in in_key_dicts: for word in events_list: ...
89f9f976cf3f44383c8f0c4ef11574b5b9a957f9
48,251
def pull_words(words_file, word_length): """Compile set of words, converted to lower case and matching length of start and end words. Args: words_file: str, name of the file containing all words word_length: int, length of the start/end words Returns: words_set: set, all possible...
cbecb29bd93177cb14a208e7e3a7bcee14f7c010
48,252
def format_participants_packet(data: PacketParticipantsData, index: int, race: Race, lap: int): """ """ formatted_data = [] for key, value in data.to_dict().items(): if key == 'm_header': continue elif key.endswith('_participants'): ...
133a42779443ae4ad84891d56137bb97d0c11c3f
48,253
def classify_cells_majority(data, burnt_samples, table, cell_type_name2idx): """ This function is an extension of "classify_cells". It extends to the case when you need to ensemble a list of MP trees by majority. INPUT: data: N*D np.array burnt_samples: A list of MP trees table: a da...
4d932a4602a573196298b2c61fd350c7fa1b9585
48,254
def vertices_vector_to_matrix(vertices): """vertices_vector_to_matrix(vertices) -> List[List[float]] PyPRT outputs the GeneratedModel vertex coordinates as a list. The list contains the x, y, z coordinates of all the vertices. This function converts the vertex list into a list of N vertex coordinates ...
0d03a60f32ed722d089500840e1a2a2e645c20b4
48,255
import torch def random_well_conditioned_matrix(*shape, dtype, device, mean=1.0, sigma=0.001): """ Returns a random rectangular matrix (batch of matrices) with singular values sampled from a Gaussian with mean `mean` and standard deviation `sigma`. The smaller the `sigma`, the better conditioned ...
bd2d7e232ffcd2848b836e9187d32a00339477de
48,256
def get_index_str(n, i): """ To convert an int 'i' to a string. Parameters ---------- n : int Order to put 0 if necessary. i : int The number to convert. Returns ------- res : str The number as a string. Examples -------- ```python getI...
e7b3561a49b447d1edec22da8cc86d2a702ec039
48,257
def print_red(text): """" Prints a sentence in the color red. :param: text :return: Fore.RED + Style.BRIGHT + text + Style.NORMAL + Fore.WHITE """ return Fore.RED + Style.BRIGHT + text + Style.NORMAL + Fore.WHITE
87d805cd2c499d95d51da76d6b5ef2b6571679b1
48,258
def extract_metrics(postprocessors): """ Extract performance metrics from multiple runs. :param postprocessors: :param data_projection: :return: """ n_runs = len(postprocessors[0]) n_estimators = len(postprocessors) n_clusters = postprocessors[0][0].nclusters x_vals = np.arange(...
55548be2d5ed83dda94252877143cbdd9ffd71f8
48,259
import os import io def load_notebook(filename): """load a notebook object from a filename""" if not os.path.exists(filename) and not filename.endswith(".ipynb"): filename = filename + ".ipynb" with io.open(filename) as f: return nbf.read(f, as_version=4)
8de24bac73429ccbadb9e69a9f4af00cf8d485c6
48,260
import pandas def concat_gdf(*args): """ Concatenates an arbitrary number of GeoDataFrames """ return geopandas.GeoDataFrame(pandas.concat([*args], ignore_index=True))
4790545c2b3b2589e8f505574d0c35b64b2d0ebb
48,261
def match_stops_in_model(stops): """ Matches a list of bus stops with stops present in the model. The bus_station_ids provides a handling method for bus stations. Input all the ATCO codes associated with bus station stops into the array and ensure the Bus Terminal in Aimsun has the EID 'Bus Station'. Parameters ...
a5490b8e23776843bbd12d1f42bbf9725595e842
48,262
def sigma_at_error_rate_with_good_examples( model, sess, x, y, desired_error_rate, gaussian_samples_at_sigma_1, num_examples_wanted, distance_scale, initial_guess=0.1, tol=0.001, sample_batch_size=10): """The scale at which Gaussian noise produces the provided error rate. Args: model: A `Model`; th...
a98a32206469fe35f3fdb663451eba497cb95f95
48,263
def get_all_matching_models(cars=cars, grep='trail'): """return a list of all models containing the case insensitive 'grep' string which defaults to 'trail' for this exercise, sort the resulting sequence alphabetically""" matches = [] for mfg, modellist in cars.items(): for model in mo...
0d854fc3e934c3657cf27c3c9bddd2c895997776
48,264
from scipy import interpolate def psresp(t, y, dy, slopes, dt, df, percentile, oversampling=10, number_simulations=100): """ Compute power spectral density of a light curve assuming an unbroken power law with the PSRESP method. The artificial light curves are generated using the algorithm by Timmer and K...
d06b53c50f897be908d3b48378c556de2b9718ab
48,265
def gaussian_mixture(x: np.ndarray, params: np.ndarray ) -> np.ndarray: # pragma: no cover """ Mixture of gaussian curves. Parameters ---------- x : np.array params: np.ndarray parameter for each curve the shape of the array is n_curves by 3. Each row has ...
9a272c2f4394bff7f2741d8f77d8393f838dad86
48,266
import argparse def get_parser() -> argparse.ArgumentParser: """Create and return the argparser for undiscord flask/cheroot server""" parser = argparse.ArgumentParser( description="Start the UnDiscord flask/cheroot server", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) gro...
5f158f7fef854b67420573de0c1c671bd05259e4
48,267
def text(body: t.Any, status: int = 200, content_type: str = 'text/plain', headers: Headers = None) -> Response: """ Response object that contains prepared plain text :param body: dict object :param status: http status :param content_type: response content type (default text/plain) :param header...
54cd50e0fc58c745204566c008ee750690b3a36b
48,268
def risk_estimate(est, gt, loss_func='zero-one-loss'): """ est: cause x effect (indirect) boolean matrix""" if loss_func == 'zero-one-loss': return np.logical_xor(est.astype('bool'), gt.astype('bool')).sum() else: raise Exception('Specify correct loss function')
449aa52a6554ca411de71bc1c1b2022654928610
48,269
def mf_session(mf_engine): """Define a default fixture in for the session, in case the user defines only `mf_engine`. """ Session = sessionmaker(mf_engine) return Session()
e19458933e171614e0abc4d50363260ea7b4db31
48,270
def mafiaAlgorithm(transactions, min_support_count): """ Extract the MFIs (Maximal Frequent Itemsets) from transactions with min support count using MAFIA Algorithm Parameters ---------- transactions : list of sets The list of transactions min_support_count : int The minimum support count threshold Returns...
b2870ed93330df86f81d4b1c5c174027b63ffca3
48,271
import numpy from typing import Counter def train_test_apart_stratify(df, group, test_size=0.25, train_size=None, stratify=None, force=False, random_state=None, fLOG=None): """ This split is for a specific case where data is linked in one way. Le...
a5f82a39bc0a037785df0cb6de3d25006c47e8d9
48,272
def get_ipsec_udp_key_status( self, ) -> dict: """Get IPSEC UDP key status for all appliances .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - ikeless - GET - /ikeless/seedStatus :return: Returns dictionary ike...
db5ac6fee37574987a023183f8416d40234ac4e4
48,273
def compute_loss_sparse(logits, indices, weights=None): """Cross-entropy loss when only 1 label per example.""" losses = tf.nn.sparse_softmax_cross_entropy_with_logits( labels=indices, logits=logits) if weights is not None: row_sums = tf.squeeze(batch_gather(weights, tf.expand_dims(indices, 1)), 1) ...
1bb2de7c4cd6e8838e31ae5fd8f162ee86194ff7
48,274
def convert_poly(p, zoom, im_height): """Move a polygon to the correct zoom level and referential""" polygon = affine_transform(p, [powdiv(1, zoom), 0, 0, powdiv(1, zoom), 0, 0]) return affine_transform(polygon, [1, 0, 0, -1, 0, im_height])
3ec27e81f1c432ede8520f7f7918536d357e6c61
48,275
import time def get_volume_from_pod(volume_name, namespace, experiment_id): """ Get volume content zipped on base64. Parameters ---------- volume_name: str namespace: str experiment_id: str Returns ------- str Volume content in base64. """ load_kub...
2453e11543eaa3303ed00647ff72c770c4a57628
48,276
def PyOS_double_to_string(space, val, format_code, precision, flags, ptype): """Convert a double val to a string using supplied format_code, precision, and flags. format_code must be one of 'e', 'E', 'f', 'F', 'g', 'G' or 'r'. For 'r', the supplied precision must be 0 and is ignored. The 'r' form...
8d10031e7331a569a27919b25528363f693ca028
48,277
import typing def describe_services( ecs, cluster: str, services: typing.Set[str] ) -> typing.List[typing.Dict[str, typing.Any]]: """Wrap `ECS.Client.describe_services` to allow more then 10 services in one call. """ result: typing.List[typing.Dict[str, typing.Any]] = [] services_list = list(...
f585610480aa7c657974b6f3163888fe7e9b6a32
48,278
from datetime import datetime async def Custom(title:str, text:str) -> nextcord.Embed: """ Success Embed ------------- Input: `Text` Output: `nextcord.Embed` object """ # Start constructing the embed embed = nextcord.Embed( title = f"[ ■ ] {title}", descriptio...
0dcb35ff1e3005fd487716ae94f05bba0ddcf49e
48,279
from typing import Counter def _get_article_nb_links_and_scores(url, links_dict=None, score_counter=None, base_score=1, current_deep=1, max_deep=1, top_n=10): """Function to accumulate article neighborhood scores recursively.""" article, _ = get_or_create_article_by_url(url) # if article == None: ...
8082d41ff106a03c48b6344be629440364db990b
48,280
import warnings def handle_deprecated_data_source(data_collection, data_source, default=None): """ Joins parameters used to specify a data collection. In case data_source is given it raises a warning. In case both are given it raises an error. In case neither are given but there is a default collection it rai...
95067948dd49973895fd66fb8e00ae0ee239e57c
48,281
import re def extract_page_nr(some_string): """ extracts the page number from a string like `Seite 21` :param some_string: e.g. `Seite 21` :type some_string: str :return: The page number e.g. `21` :rtype: str """ page_nr = re.findall(r'\d+', some_string) if len(page_nr) > 0: ...
6d39314de89c8f4bf4d931f2dc329fe394a10091
48,282
def is_notification_center_valid(notification_center): """ Given notification_center determine if it is valid or not. Args: notification_center: Instance of notification_center.NotificationCenter Returns: Boolean denoting instance is valid or not. """ return isinstance(notification_center, Notifica...
30df9ea9d5bea4a048ec0a590c6dfd78bb79d8ce
48,283
def get_codec(module): """Creates and returns the codec defined in the given module path (ex: ``"myapp.mypackage.mymodule"``). The argument can also be an alias to a built-in codec, such as ``"json"``, ``"json_zlib"`` or ``"pickle"``. """ if module in CODECS: # The "_codec" suffix is to avoi...
975344688d64cc8efe226a493aff2391e41626d2
48,284
def zeros(shape, dtype=hl.tfloat64): """Creates a hail :class:`.NDArrayNumericExpression` full of zeros. Examples -------- Create a 5 by 7 NDArray of type `tfloat64` zeros. >>> hl._nd.zeros((5, 7)) It is possible to specify a type other than `tfloat64` with the `dtype` argumen...
91291485a857fb851ead8a3474aa6b8fb321e197
48,285
from datetime import datetime from operator import and_ def get_expenses_by_year(session, user_id, year): """ Function to get expenses by year :param session: current db session :param user_id: user id :param year: year :return: returns list of expenses """ date_begin = datetime(year=y...
d9e31f911f47995a459762ae750160b322949430
48,286
from operator import gt def get_graph_tool_from_adjacency(adjacency, directed=None): """Get graph-tool graph from adjacency matrix.""" idx = np.nonzero(np.triu(adjacency.todense(),1)) weights = adjacency[idx] if isinstance(weights, np.matrix): weights = weights.A1 g = gt.Graph(directed=dir...
420e7a77c42d81f1ddafdc760395f666109c027a
48,287
def embed_batch(X, Y, mask): """Embed a square matrix x with y where mask is true. Args: x <list<np.array>>: set of to be embedded matrices y <list<np.array>>: set of elements that are embedded into elements of X. Same size as X. mask <np.array<bool>>: marks where to embed....
3ba7956b4e0994567859981fe0c8c379ca24acb4
48,288
def ttgrange(*args, **kwargs): """ A shortcut for `tqdm.contrib.telegram.tqdm(xrange(*args), **kwargs)`. On Python3+, `range` is used instead of `xrange`. """ return tqdm_telegram(_range(*args), **kwargs)
9d10f380e6d267c189ab5292867cdd69a0e7cce4
48,289
def decode_lookup(key, dataset, description): """Convert a reference to a description to be used in data files""" if key in dataset: return dataset[key] else: decoded = input("Please enter {desc} for {key}: ".format(desc=description, key=key)) dataset[key] = decoded return de...
4df44c411ef4d1ffe76e489611c4a65888b0a3cd
48,290
def comp_conv2d(conv2d, X): """ # 定义一个函数来计算卷积层,它初始化卷积层权重,并对输入和输出做相应的升维和降维 (主要是增删批量大小和通道数两个维度的信息) """ conv2d.initialize() X = X.reshape((1, 1) + X.shape) # (1, 1)代表批量大小和通道数(“多输入通道和多输出通道”一节将介绍)均为1 Y = conv2d(X) return Y.reshape(Y.shape[2:])
1fa8bce8a7efc2f53ba0146b1dbf607140bdbef0
48,291
def get_axes(): """It returns the value set for the option 'axes' of the plot.""" return h.axes
3aecd917da341160bb4b15b9760436717332ccfe
48,292
def create_explicit_child_condition(parentage_tuple_list): """ This states for a parent node, what its explicit children are. """ def explicit_child_condition(G): return all( [sorted(G.out_edges(y[0])) == sorted([(y[0],x) for x in y[1]]) for y in parentage_tuple_list])...
81860f24e7538feb84e9205dc233d2bf7d1dd1b3
48,293
from typing import List def similar_in_backness(backness_1: UnmarkableBackness) -> List[Backness]: """ If the value is a wildcard value, return all possible backness values, otherwise return the single corresponding backness value. """ if isinstance(backness_1, MarkedBackness): return backness_1.backness ret...
0096ba9f8a2f4d0e5a851330da383caa77155bb6
48,294
def ajax_delete_comment(): """ Deletes a comment from the recipe document """ response = { "success" : False, "flash" : {"message" : "Deletion Failed!", "category" : "error"}, "response" : None } if "comment" in request.json and "recipe" in request.json: index = int(requ...
952c5405fd977e91b7cbbb8035dd393123e432ca
48,295
def line_job(): """ 每条线路的计划分配情况 :return: "data": [ { "choice_plan": "5e71dd0d3ae156497e114364", "device_id": "7WIZya2wsIKGuitNpHyIWjCq", "id": "5e6ee2ddc1094a4d94ed0264", "limit": 100.0, "line": 1, "line_name": "线路一", ...
54c95021add6c706a70ffc60fb9889598ceec054
48,296
import random def generate_random_GenericWindRoseVT(): """ Generate a random GenericWindRoseVT object Parameters ---------- N/A Returns ------- wind_rose GenericWindRoseVT A wind rose variable tree """ weibull_array = np.array([[ 0.00000000e+00, 3.59673...
42cd08447618b7710dd6e9c3a744feb9b8745cdb
48,297
def CMYK_to_CMY(CMYK): """ Converts from *CMYK* colourspace to *CMY* colourspace. Parameters ---------- CMYK : array_like, (4,) *CMYK* colourspace matrix. Returns ------- ndarray, (3,) *CMY* matrix. Notes ----- - Input *CMYK* colourspace matrix is in doma...
51f64dae0ed43439f958cfb7210a65ba91e4613b
48,298
def intDictToStringDict(dictionary): """ Converts dictionary keys into strings. :param dictionary: :return: """ result = {} for k in dictionary: result[str(k)] = dictionary[k] return result
65e519f04433a5dfcb4d7ace9bad91d8e06db4e5
48,299