content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def extract_command(text): """ Extracts the command from `text` (minus the '/') if `text` is a command (see is_command). If `text` is not a command, this function returns None. Examples: extract_command('/help'): 'help' extract_command('/help@BotName'): 'help' extract_command('/search black...
f73e3a01b22ef8bf612c8a06fd2d3636657cba16
62,400
def get_files_array(path): """ get files as array """ files = [] for file in files_collect(path): files.append(file) return files
48a8b5b8f89fcf51b8e751f48fa39b8111c7afbb
62,401
def complete_tree_pair(aidx, bidx, adoc, bdoc, ops, adoc_range=None, bdoc_range=None): """this function extend the subphrases to their matching subtrees. Returns: [Span, Span]: the extended aspan, and bspan """ if is_punct_phrase(aidx, adoc) and is_punct_phrase(bidx, bdoc): return a...
b97cd5623f13c0891b64b33c1858186cdf6a71cf
62,402
import re def decompose_molecule(molecule, n=1): """ Returns the chemical constituents of the molecule, and their number. Parameters ---------- molecule : str A molecule in standard chemical notation, e.g. 'CO2', 'HCO3' or 'B(OH)4'. Returns ------- All elements i...
a332f40d5d20c349abe97569ce0129c7e9d03543
62,403
def sign_metadata(role: str, metadata_proto): """Signs a serialized metadata for a given role""" signed = getattr(tuf_pb2, f'Signed{role.capitalize()}Metadata')() serialized = metadata_proto.SerializeToString() setattr(signed, f'serialized_{role}_metadata', serialized) # TODO(pwbug:456): Generate si...
9ad59759e1e3eb76fabd9c20536a0cae5dcc424b
62,404
from typing import Union from typing import Optional def set_chat_description(token: str, chat_id: Union[int, str], description: Optional[str] = None ) -> bool: """Use this method to change the description of a group, a supergroup or a...
b47a1fb2374b73cde21d9a8eece47f2611fd7bc8
62,405
def converte_int_char(inteiro): """Converte um inteiro para um caractere segundo a tabela ASCII com correção do valor do inteiro, segundo enunciado e uso da função chr(), para que: 0 = '_' = , 1 = 'a' = , 2 = 'b', ..., 26 = 'z' e 27 = '.' Args: inteiro (int): inteiro a ser convertido em carac...
e7550dec4aa3e4a82729728befcb566e9d8315d0
62,406
def create_iterable_dataset(torch_transforms_module, pipeline_results): """ Create a PyTorch iterable dataset that loads samples from pipeline results. :param torch_transforms_module: The imported torch.transforms module. :param pipeline_results: Pipeline results iterator. :return: Dataset that has...
1de2f8be910da07e1a63e177f59d9bf0467edbe1
62,407
import json def add_flow(req): """ :param req: :return: """ r = {} post_args=req.POST f = flowgroup() f.name = post_args.get('title') try: r['msg'] = '%s saved.' % (f.name) r['status'] = '200' f.save() return HttpResponse(json.dumps(r, ensure_ascii...
6ea4ed871b2b5363fcca519eb0fbc27c4886da5a
62,408
def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None, ridx=None, cidx=None, exclude_rid=None, exclude_cid=None): """ Extract a subset of data from a GCToo object in a variety of ways. The order of rows and columns will be preserved. Args: gctoo (GCToo object) ...
2513c5449ac294ea9e79ac69f09b58ec9579d154
62,409
def dtype(request, device): """Run a test case in single and double precision.""" return request.param
8196d76b2edd4bd66253b675f4636b77208f7617
62,410
import ipdb def reduce(*event_lists): """ intersect all events of multiple sources to one dict of date: summary """ result = {} for cal_items in event_lists: for item in cal_items: try: ref = item['start'].get('date', None) or item['start'].get('dateTime') ...
f247481bb193aebbe8cb9b038347af2b409c2ae4
62,411
from typing import Dict from typing import Callable def is_current_builder() -> Dict[str, Callable]: """Inject a function to evaluate whether or not a result is current.""" def is_current(result: dict) -> bool: """Determine whether the result is the current version.""" if result['submitted_dat...
35b44ee27a24ecb09f6e76245aab4619971dc17e
62,412
from io import StringIO def download_image(session, url): """" dumps image into memory """ dl = session.get(url, stream=True) img = StringIO() img.write(dl.content) img.seek(0) # rewind to beginning return img
ed3ab31b0eb3419e34085585aeb742252713be51
62,413
def scale_alpha(range=None, name=None, breaks=None, labels=None, limits=None, na_value=None, guide=None, trans=None, format=None): """ Scale for alpha. Parameters ---------- range : list The range of the mapped aesthetics result. name : str The name of the scale ...
02626c2f8c347e4cf757a5c08da5bd88674531ed
62,414
def formation_energy_table( defect_phase_diagram: DefectPhaseDiagram, chempot_limits: dict = None, fermi_level: float = 0, hide_cols: list = None, show_key: bool = True, pd_facets: list = None, ): """ Prints the formation energy tables for either a single chemical potential limit (i....
9ecec1588f3367a8a33241562d1aa9d34da717ba
62,415
def get_attr_info(key, convention, normalized): """Get information about the MMD fields. Input ===== key: str MMD element to check convention: str e.g., acdd or acdd_ext normalized: dict a normalized version of the mmd_elements dict (keys are, e.g., 'personnel>or...
53e6d389935fead65173c3fd66d3608daa9c7ebc
62,416
def unpad(x, pad_width): """ func to unpad slice (FOR LINUX) ---------- x : ndarray image array pad_width : tuple tuple fed to np.pad Returns ------- ndarray unpadded img """ slices = [] for c in pad_width: e = None if c[1] == 0 else -c[1] ...
bedab5694f287d1ccd84f4240306c9d18cb38b8a
62,417
def hello_world(): """...""" jsn = request.json c = conn.cursor() c.execute("insert into User values ({},{},{},{},{},{})".format(jsn['user_id'], jsn['email_address'], j...
d6187a1fd0a73cff75523ce3d4f45e9987e0c59d
62,418
import os def ensurePath(root, dir_names): """Creates hierarchy of nested folders starting from root, if they did not exist. Returns resulting path. """ path = root for dir_name in dir_names: path += str(dir_name) + "/" if not os.path.exists(path): os.makedirs(path) ...
3829c4f17e0b72c06d0130df7ef2d1b35a3dd8db
62,419
from pkg_resources import resource_filename def get_ffxml_path(): """ Return the path where OpenMM ffxml forcefield files are stored in this package. Returns ------- path : str The absolute path where OpenMM ffxml forcefield files are stored in this package """ filename = resource...
29b9d3de56560ce6ddd690ffe944fe890c80f0ed
62,420
def evaluate_semeval_monolingual(vectors, lang): """ Get a semeval score for a single monolingual test set. """ spearman_score = measure_correlation(spearmanr, vectors, read_semeval_monolingual(lang)) pearson_score = measure_correlation(pearsonr, vectors, read_semeval_monolingual(lang)) score = ...
a529d58ad064f84683f1afcc4a6d4a6ca24c5f25
62,421
def exists_type(curs: Cursor, type_name: str) -> int: """Does type exists?""" schema, name = fq_name_parts(type_name) q = """select count(1) from pg_namespace n, pg_type t where t.typnamespace = n.oid and n.nspname = %s and t.typname = %s""" curs.execute(q, [schema, name]) re...
fdbfd1670db81ff9317e9ea04d4e4ac4b3db7230
62,422
import torch def get_batch(data): """ Get a batch of data from the data loader, which automatically batches the individual examples Concatenates necessary data (lm_labels, loss_mask, tgs_mask), which is required for FS/QT variant tasks Puts data into tensors, and places them onto CUDA """ ...
b9f1750e348916526015df576e2969abaa51fb5f
62,423
def override(args, overrides): """override optional arguments with arguments from the config file""" args_dict = vars(args) for key, value in overrides['args'].items(): if key == 'config': raise utils.FatalException('argument "%s" specified in the config ' 'override could...
4ec582bf506a82852496756bf8e67ee3997ad92a
62,424
def _infer_decision_threshold(y_proba: np.ndarray, y_true: np.ndarray, default_dt: float, results_at_recall: float=None) -> float: """infer decision threshold based on given recall value, """ if results_at_recall: ...
f64f1f433c9b74420601961ad69ed2c1bdc17bd5
62,425
def toggle_doors(doors, skip): """Toggle every skip door in doors. doors is an array of elements where a false value represents a closed door and a true value represents an open door. If skip is 1, toggle door #1, #2, #3... If skip is 2, toggle door #2, #4, #6... Returns doors """ for...
7631bbc860c4bfa9a7c236a07ebfdb1092bd351c
62,426
def has_year(line): """ :type line: FrekiLine :rtype: bool """ return bool(line.search(year_str))
b24ca4cc25174a62733f49c026f501d1832fac11
62,427
import math def presion_vapor_tmed(tmed): """ calcula la presión del vapor en saturación a la temperatura media kPa param: tmed : temperatura media """ return 0.6108*math.exp(17.27*tmed/(tmed+237.3))
968fc144037e57d688a8f0f5e19a0d7779e5bc9b
62,428
import os def process_tfr(input_path, data_dir, extract_1_of_N=1): """ Process a Waymo tfrecord file by extracting only every N-th frame of the front video camera images and labels and converting the extracted data items into a tfrecord file using tf object detection api format. The processed tfrecor...
df5e19a0aaf5112e6a40144d14373c93ca6fe714
62,429
import subprocess def dmenu(options, dmenu): """Call dmenu with a list of options.""" cmd = subprocess.Popen(dmenu, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ...
be627e15dbb62b017dee2cf707d7810d38d4854e
62,430
from typing import Tuple def double(user: str, num: int = 0) -> Tuple[str, str, str]: """Return JSON Object.""" return ("OK", "text/plain", f"{user}-{num}")
57a540ff9cd021847dff39f6ee02960c527f0b36
62,431
def reward_fixture(): """ Reward for 4 state MDP, reward of 1 for single state, 0 elsewhere """ return np.array([0, 0, 0, 1])
9cb33d03137d3921da7e8b82403d98f52db020d1
62,432
import re def find_first_arg_pos(bracket_offset, curr_line, args=None): """ find_first_arg_pos(bracket_offset : int, curr_line : str) -> [int, int] Arguments: bracket_offset - The position of the bracket in the current line e.g " ( list 'timey 'wimey )" --> 4 " ( list 'timey 'wimey ...
33732d7c0141b4d1c5e9942a299e2be9c64f4813
62,433
def get_col_dim(col): """ Get the physical dimension of a column by its name. Args: col (str): the name of the column. Returns: str: the physical dimensions of the given column. """ for dim in DIM_COL.keys(): if col in DIM_COL[dim]: return dim
ede5df4189caa156a40708292f0c2d838712792c
62,434
def prerank(rnk, gene_sets, outdir='GSEA_Prerank', pheno_pos='Pos', pheno_neg='Neg', min_size=15, max_size=500, permutation_num=1000, weighted_score_type=1, ascending=False, processes=1, figsize=(6.5,6), format='pdf', graph_num=20, no_plot=False, seed=None, verbose=False): """ Ru...
5b94e1d52b87671aea9a8090010f1a8040d044c3
62,435
def metade(valor=0, formatc=False): """ -> Dá a metade de um valor. Parâmetros opcionais :param valor: Valor que será dobrado. :param formatc: Booleano que indica se a formatação no valor será feita :return: Valor dividido em dois com a formatação ou não. """ res = valor / 2 return r...
83b25300b2b476fa0ec7b78ed5390d223b431376
62,436
import os import json from datetime import datetime import re def find_comment(anchor, store=None, raise_errors=False, get_time=False): """Find the comment in the specified store or any store""" # Remove anchor hook if it exists if anchor.startswith(ANCHOR_HOOK): anchor = anchor[len(ANCHOR_HOOK):] nth_s...
ebb99c731a1337aebb7b3f05efb1e7603b7f4c87
62,437
def get_repo_url(mead_tag, nexus_base_url, prefix="hudson-", suffix=""): """ Creates repository Nexus group URL composed of: <nexus_base_url>/content/groups/<prefix><mead_tag><suffix> :param mead_tag: name of the MEAD tag used to create the proxy URL in settings.xml :param nexus_base_url: the b...
b422b46da7c039575c9dbfd5ce5bf7157e64f9b4
62,438
def remove_false_deletes(tokenized, text): """ Sometimes a statement like 'Removing the 'x' from the end of paragraph can be confused as removing the paragraph. Ensure that doesn't happen here. Likely this method needs a little more work. """ contains_delete = bool(matching(tokenized, tokens.Verb, verb=...
16c7b479ad2d98a15ac9cd9d9f4f678af24dffa4
62,439
import functools import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" @functools.wraps(func) def new_func(*args, **kwargs): warnings.simplefilter('always', D...
7886ce0db1e81b3856222fb1ea3f6b2080b18474
62,440
def get_manufacturer(metadata): """Extract scanner manufacturer from DICOM tags.""" if [0x8, 0x70] in list(metadata.keys()): manufacturer = metadata[0x8, 0x70].value if 'Siemens' in manufacturer or 'SIEMENS' in manufacturer: manufacturer = 0.0 elif 'Philips' in manufacturer ...
9814f026d1ce6c8c83dbcd2b6132a80d5ea7fdac
62,441
def count_times(func): """ Checks how many times a function repeats. :param func: dictionary in the format (k, v): (name of brodmann area, name of the functions) """ times = dict() for val in func.values(): for v in val: inc = 1 v = v.split("\t\t")[1] ...
0080eaf022f1de61cc9e4a06ffec1a87c5cc8980
62,442
import itertools def GetBoundingBoxOfCoordinates(coordinates): """Returns smallest box containing all lat/long coordinates in given list. Args: coordinates: list of (lat, lon) 2-tuples. Returns: BoundingBox object. """ # Latitude is easy north = max(x[0] for x in coordinates) south = min(x[0] f...
ff5d556831c650c7178a703200d2ea3620b1cf53
62,443
def trunc_sequence(df: pd.DataFrame, max_len: int = -1) -> pd.DataFrame: """ Truncate the length of the passed in dataframe to the max length. :param df: pd.DataFrame, The dataframe to truncate. :param max_len: int, The length to truncate the df to. :return: pd.DataFrame """ return df.truncate(after=(max_len...
16466e4fef170cd10171d327cc7903862b1deaca
62,444
import typing async def wait_for_component( client: discord.Client, component: typing.Union[str, dict, list] = None, message: typing.Union[discord.Message, int, list] = None, check=None, timeout=None, ) -> ComponentContext: """ Helper function - wrapper around 'client.wait_for("component",...
bec60ec84d7ad03318272be30b459eb3e83f9703
62,445
def max_eigenvalue_constraint(x_vec, max_eigenvalue): """ This function defines an inequality constraint on the maximum eigenvalue of a SPD matrix. The value returned by the function is positive if the inequality constraints is satisfied. Parameters ---------- :param x_vec: SPD matrix in Mandel...
02810dbe9f57a11548de123d5278d896002f021f
62,446
def guess_timezone_by_ip(ip, only_name=False): """Given an `ip` with guess timezone using geoip2. Returns a tuple of (tz_offets, tz_name, tz_formated). `None` is returned if it can't guess a timezone. For this to work you need to set tz_utils.GEOIP_DATA_LOCATION You can get this database from http:...
d2be11536a06f5f9b6770b546404bc58e0ba762c
62,447
def get_insert_cmd(insert_fields, table, update_cmd=None): """ Creates the insert command to use with an insertion to a PostgreSQL database, given the table and the fields to be inserted Parameters ---------- insert_fields: list of strs Fields of data that will be inserted table: st...
d026911c0574bc2f8a52ede5bbb72b48d81272f8
62,448
def XCAFDoc_LayerTool_GetID(*args): """ :rtype: Standard_GUID """ return _XCAFDoc.XCAFDoc_LayerTool_GetID(*args)
6afb65fdc6c6da71181a57fb9bc1e34c5abd07f4
62,449
import os def get_labels(split='test'): """ Gets label files of specified dataset split """ label_paths = get_files_from_folder( os.path.join(dataset_constants.LABELS, split), '.json') return label_paths
b21cd5587000dd1e825cf14920dad71f0efb76a6
62,450
def kojak(kojak_txt: str, perc_inter: str, perc_intra: str, out_file: str, version: str = "2.0-dev", max_charge: int = 8, decoy_prefix: str = "decoy_", to_pin: bool = False) -> None: """ Convert Kojak search results to xenith tab-delimited format. For conversion, the Kojak searches must...
df709826dbe8e702ae2b362120638d16623caddb
62,451
import logging def extract_df(dic=input, file=None): """ :param dic: global input parameters that can be altered in the config.py file :param file: str: name of the file containing a sieving sample :return: dataframe of sieving sample """ df = pd.read_excel(file, engine="openpyxl", header=Non...
5c491074eaac0886313304f14457730495926b28
62,452
from typing import Dict from typing import Any def generate_artificial_data(params_dict: Dict[str, Any]): """Generate artificial biomarker data. Args: params_dict: Parameters for the data to generate (see parameters of :func:`generate_artificial_classification_data`). Returns: ...
e6779756a7d61234dd6b464743bec90e8b1c3f40
62,453
def serialize(gtp_command, gtp_response): """Serialize a GTP response as a string. Needs the command we are responding to so we can match the sequence number. """ return '%s%s %s\n\n' % ( '=' if gtp_response.success else '?', '' if gtp_command.sequence is None else str(gtp_command.s...
32412766b3d1db92a8aae653dbf8b11a761e35b1
62,454
def create_entry(request): """Creates a new entry or shows the create form""" if request.method == 'POST': new_entry = EntryForm(request.POST) if new_entry.is_valid(): # create the entry util.save_entry(new_entry.cleaned_data['title'], new_entry.cleaned_data['entry']) ...
0562bbc939e6bdcc5c3fb1bef4a572fc0439bc50
62,455
import pathlib import sys import subprocess import io import collections def shellcmd(bin, args, printOutput=True, returnOut=False): """Run the shell command with specified arguments for skopeo/docker args -- A tuple of arguments. printOutput -- If True, the output of the command will be send to t...
e9a84bda21e2f77c77b15179992a9af02585b360
62,456
def after(f, chain=False): """Runs f with the result of the decorated function.""" def decorator(g): @wraps(g) def h(*args, **kargs): if chain: return f(g(*args, **kargs)) else: r = g(*args, **kargs) f(*args, **kargs) ...
b4897684320927a86915335084f3da7ae126dec5
62,457
def fill_template(template_pack, predictions, eoa_id, pad_id, eos_id): """ :param template: [batch_size, max_seq_len] :param mask: [batch_size, max_seq_len] :param predictions: a list of tensors :return: """ def _transpose(a): """ :param a: mask_num * batch_size * undefined_l...
2d0ff6a31688608755188772ed6b87cac05fa620
62,458
from kotti.resources import get_root def root(db_session): """returns Kotti's 'root' node.""" return get_root()
165f71869534832541b292b33512abf70e035f1f
62,459
from typing import Optional from typing import Dict from typing import List from typing import Any from typing import cast def call_service( ctx: Configuration, domain: str, service: str, service_data: Optional[Dict] = None, ) -> List[Dict[str, Any]]: """Call a service.""" try: req = r...
8eb97e1be3efcddac5f6b982c1bed29f84259c9c
62,460
def list_entries(): """Return entries to be displayed in rofi.""" return([''])
76223be8cc86d9b9592edd1849ac1a8862c4d01c
62,461
import os import re def cprnc(model, file1, file2, case, rundir, multiinst_driver_compare=False, outfile_suffix="", ignore_fieldlist_diffs=False, cprnc_exe=None): """ Run cprnc to compare two individual nc files file1 - the full or relative path of the first file file2 - the full or relativ...
a2fa6fefcceae55767ad1e34b0b902a74e3e3b79
62,462
def eval(y_true, y_pred, normalize=False, verbose=3): """Evaluate the results in a two-class model. Parameters ---------- y_true : array-like True labels of the classes. y_pred : array-like Predicted labels. normalize : bool, optional Normalize the values in the confusio...
dd26ee9b70af25a11323fa420d5ac4709afa0fd2
62,463
import copy def add_missing_fields(og_layout, tab): """ Adds missing fields to the layout. """ layout = copy.deepcopy(og_layout) missing_fields = tab.get_missing_fields(layout.get("content")) if not missing_fields: return og_layout tab_data = tab.get_from_tabs(layout.get("content")...
040f47606c5b89a52ed9defc4a9dbdda56c4cb2a
62,464
def collate_effect_size(counts, powers, alpha): """Calculates the effects for power values Parameters ---------- counts : array the number of samples used to calculate the power powers : {list, ndarray} list of arrays of power values. If there are multiple power arrays, each...
f8171545e5b7a11a42da081a070be8232dd81199
62,465
def sample_dirichlet_multinomial(dirichlet_alphas:np.ndarray, num_samples:int) -> np.ndarray: """ Sample from a Dirichlet-multinomial distribution Parameters ---------- dirichlet_alphas : numpy.ndarray The concentration parameters for the Dirichlet distribution num_samples : int Th...
8cfe8a5fd8465d82612e176973c3a23d45eebd04
62,466
import os import logging import pickle from re import T def load_data(data_id, path, remove=True, do_pickle=True, silent=False): """ Read data from disk file """ path = os.path.join(path, data_id) if not os.path.exists(path): logging.info("[%s] %s missing", misc.caller_name(), path) retur...
6e13a37590fee08999d7ee706abf889de752a00d
62,467
def lift_hand(env_lift, tot_reward): """ Lift hand with set action velocities env_lift: Mujoco environment tot_reward: Total cumulative reward """ # action only used to move hand, not recorded in replay buffer and is NOT used to update policy action = np.array([wrist_lift_velocity, finger_lift_v...
ccba8cee7a92bb60672d4ca09b351cc0666c6083
62,468
import torch def get_autoencode_minibatch( lines, word2ind, index, batch_size, max_len, add_start=True, add_end=True ): """Prepare minibatch.""" if add_start and add_end: lines = [ ['<s>'] + line + ['</s>'] for line in lines[index:index + batch_size] ] elif ...
953785f3042e4800e7343c886d84218e6be5b171
62,469
def read_file(path): """ Return the contents of a file Arguments: - path: path to the file Returns: - contents of the file """ with open(path, 'r') as file: return file.read().rstrip()
85d64985da7c9ea15b314d25b42ad2bc6491a111
62,470
def build_scaler_train_and_test_datasets( label, train_features, test_feature, df, test_size, seed, scaler_cast_to_type="float32", min_feature_range=-1, max_feature_range=1): """build_scaler_train_and_test_datasets :param label: log label ...
da94aa27d78c22dfaaa03e441f83519d0c4b179d
62,471
def _entitlements(ctx): """Returns the entitlement file to be used for codesigning.""" # Use the entitlements from the internal provider if it's present (to support # rules that manipulate them before passing them to the bundler); otherwise, # use the file that was provided instead. if getattr(ctx....
d177c53a4d74319203d197fbe3561b5d4de3a6bf
62,472
def dwconv_block( in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 1, dilation: int = 1, bias: bool = False, use_bn: bool = True, bn_eps: float = 1e-5, activation=(lambda: nn.ReLU(inplace=True)) ): ...
4cf99e00f04a4d8e6fbb2ba75601fd4879898409
62,473
def test_db(): """Provide an in-memory database for testing.""" return SqliteDatabase(':memory:')
97c13d2a6bd3c8cc49349f480be1983b1aa29147
62,474
def get_venv_packages(venv_path): # type: (str) -> Set[str] """ Returns the packages installed in the virtual environment using the package index file. """ with open(get_index_filename(venv_path)) as reader: return set(p.strip() for p in reader.read().split('\n') if p.strip())
6aae4c5bd8d663a25b41205fd6ae4e3a2b02368d
62,475
def get_roi_ious(rois, gt_boxes): """ Get IoU per Reion Proposals (Column 1 == GT Box1, Column 2 == GT Box2 ...) """ roi_ious = np.zeros([len(rois), len(gt_boxes)]) for i in range(len(rois)): for j in range(len(gt_boxes)): roi_ious[i, j] = get_iou(boxA_pts=rois[i], boxB_pts=...
0a6b67e18efd16e58b3ae1428cc7bca227d6e5d7
62,476
import tempfile import base64 def _setup_conn(**kwargs): """ Setup kubernetes API connection singleton """ kubeconfig = kwargs.get("kubeconfig") or __salt__["config.option"]( "kubernetes.kubeconfig") kubeconfig_data = kwargs.get("kubeconfig_data") or __salt__[ "config.option"]("kub...
95635f66ae1df336c9f725bd281fb8bccac057cb
62,477
from datetime import datetime import json def get_co2_latest(): """ Returns the co2 values for the most recent day. """ if request.method == 'GET': try: session = co2DB.create_session() date = datetime.now().replace(hour=0, minute=0) if date == None: ...
7e40218227024f7f9e7a53134502361b642cd428
62,478
def common_options(f): """ Common CLI options used by all commands. Ex: --debug :param f: Callback function passed by Click :return: Callback function """ f = debug_option(f) return f
63dc4d1a294f34c1abdd08a96a733d812e309b91
62,479
def get_default_db_file(): """Returns default location of db file""" return DEFAULT_DB_LOCATION
25f374ea1392a63d7ad557800241ee1ff8b74e7f
62,480
def dashboard_post(request, status='all', category='all', page=1): """Dashboard""" list_count = settings.DASHBOARD_LIST_COUNT if int(page) < 1: return redirect('blogs:dashboard_post', status, category, 1) current_page = int(page) - 1 start_at = current_page * list_count end_at = start_...
91620494da8ca1ee766888d78fe04a1a2451dd90
62,481
import sys def addMenuItem(caption, link, icon=None, thumbnail=None, folder=False, fanart=None): """ Add a menu item to the xbmc GUI Parameters: caption: the caption for the menu item icon: the icon for the menu item, displayed if the thumbnail is not accessible thumbail: the thumbnail for th...
f2d51b9046e255196c4048aa66a9ecd07f2326e1
62,482
def next_power_2(x: int) -> int: """Return the smallest power of 2 greater than or equal to x""" return 1 << (x-1).bit_length()
f5361250c1a6ef8228adcfd0aeab478484e7239b
62,483
def ismir2015_evaluate(niter=0, **kwargs): """ inputs: niter - number of permutation test iterations to run [0=none] **kwargs - key-word arguments for tsne analysis function {harmonic_}tsne_all() ref_idx - reference audio file, all audio warped to this [9] dfun - distance function to use [bregma...
737814eb30bd97fa679134d63e97869893125fb1
62,484
def create_new_pet( obj_in: PetCreationForm, current_user=Depends(get_current_user) ): """ Add a new pet to DB """ if obj_in.owner != current_user["id"]: raise HTTPException( status.HTTP_403_FORBIDDEN, "You are not authorised for this operation." ) n...
e48d134f8e8e77fe4abd827dcab65d9af6af0492
62,485
def get_rnai_essentiality(symbol: str) -> float: """Get essentiality of the gene in the RNAi experiments.""" return _get_essentiality(symbol, "rnai")
fde9f7f748c79cb85b15fb649848a574057d5e5a
62,486
def security_group_exists(self, sg_id=None, name=None): """ Checks if a security group already exists on this connection, by name or by ID. :param boto.ec2.EC2Connection self: Current connection. :param string sg_id: ID of the security group to check. Default : None. :param string name: Name of the...
042cd05a550b139b3441613269f59a27ad028ea1
62,487
def FCS2CorrSplit(data, dwellTime, listOfG=['central', 'sum3', 'sum5', 'chessboard', 'ullr'], accuracy=50, split=10): """ Chunk SPAD-FCS trace into different parts and calculate correlation curves ========== =============================================================== Input Meaning -------...
346f0ee5be3f825e593a40276f2228569ff3bfc7
62,488
import json import os def _setup_hparams(args): """ Wrapper function to get hyperparameters from input args. """ print("Args:") for k, v in sorted(vars(args).items()): print("\t{}: {}".format(k, v)) if args.hparams_seed == 0: hparams = hparams_registry.default_hparams(args.algorithm, ...
1f6710f7bb397c20e473c77f04002dde772a0293
62,489
from typing import Optional from typing import Sequence def get_log_saved_searches(compartment_id: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetLogSavedSearchesFilterArgs']]] = None, log_saved_search_id: Optional[str] = None, ...
d4d8b0b8f8cc38f85fdd8d31e9f596e60a9d1ce8
62,490
def repeat(x, nTimes, assertAtLeastOneRep=False): """ Repeat x nTimes times. Parameters ---------- x : tuple or Circuit the operation sequence to repeat nTimes : int the number of times to repeat x assertAtLeastOneRep : bool, optional if True, assert that nTimes > 0. ...
fd03fa160625d9690aeda6bc5313f5af5999bc4a
62,491
import json import torch def load_model(directory, model_version=None): """ Returns model, data_loader and mask_descriptor of trained model. Parameters ---------- directory : string Directory where experiment was saved. For example './experiment_1'. model_version : int or None ...
af6799f2b43e666638c44c89a5550ff8357d0b2a
62,492
def load_data(file_name: str) -> dict: """Reads all data in h5 file ``file_name`` and returns them as a `dict`.""" with h5py.File(file_name, 'r') as data_file: q_values = np.array(data_file.get('q_values')) reflectivity = np.array(data_file.get('reflectivity')) labels = pd.read_hdf(fil...
f5fc95a47eb7edd039fab3040a18b37d3c8641dc
62,493
def pixel_scale(y): """Function (from WFC3 paper), to determine max and min scale for given ycen""" # Add or subtract 150 from y to account for impact # of vertical scan on y position. min = 0.0028*(y-150) + 44.68 max = 0.0026*(150+y) + 45.112 out = np.asarray([min,max]) return out
27845ec93ea212a12df680faba02e515bde048ba
62,494
def image_detail(request): """ post: Post an image. """ if request.method == 'POST' and request.FILES: print(request.FILES['image']) myfile = request.FILES['image'] # Future TODO: Possibly add it to the DB, but don't have too. try: Photo.object...
b3b8dd725507c089384ed463c6a5039189acf0fa
62,495
import os def get_config(argv, use_argparse=True, cwd=None): """ Read sys.argv and parse out repository of migrations and database url. >>> import os >>> from configparser import ConfigParser >>> from shutil import rmtree >>> from tempfile import mkdtemp >>> config_dir = mkdtemp() >>>...
d9decefb76d3775bec5c7d07b07194cf614f6950
62,496
def sbe43(calib, P, K, T, S, V): """NOT TESTED IS THIS IN ITS-90? DOES IT MATTER? SBE equation for converting SBE43 engineering units to oxygen (ml/l). SensorID: 38 Parameters ---------- calib : dictionary calib is a dict holding Soc, Voffset, Tau20, A, B, C, E P : array-like ...
30bc9b73bcef840e045b22dcc67d402a3dca61f7
62,497
def get_approximate_cloud_underside(qc, z_tol=100.0): """ Using 3D condensate field `qc` create a 2D array representing the underside height of the lowest cloudy point per column """ z_cloud_underside = qc.zt.where(qc > 0.0).min(dim="zt") m = z_cloud_underside < z_tol + z_cloud_underside.min() ...
5605531095b47e9552ca00b852188f4189bf43fe
62,498
def getDivisionByID(xStarts: [int], yStarts: [int], idDivision: int, divisionSize=1024): """ Return x and y starting and ending coordinates for a specific division :param xStarts: the x-axis starting coordinates :param yStarts: the y-axis starting coordinates :param idDivision: the ID of the divisio...
f82fd932eefd2560567117f96fdb7fc165a9bda7
62,499