content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def transform_instance_annotations( annotation, transforms, image_size, *, keypoint_hflip_indices=None, bbox_key="bbox", ): """ NOTE: Adapted from detection_utils. Apply transforms to box, segmentation, keypoints, etc. of annotations of a single instance. It will use `transforms...
19227c58c314be7e388f26ea44d77ba7c6277a51
58,800
def strip_comments(contents): """Strips the comments from coq code in contents. The strings in contents are only preserved if there are no comment-like tokens inside of strings. Stripping should be successful and correct, regardless of whether or not there are comment-like tokens in strings. ...
2c7ddc9fb3e2981cf297ff37a4bb0b7019247a3a
58,801
def get_P_l(mol, configs, weights, epos_rot, l_list, e, at): """ Returns a nconf x naip x nl array, which is the legendre function values for each l channel. The factor (2l+1) and the quadrature weights are included. Parameters: l_list: [-1,0,1,...] list of given angular momenta weights: int...
51f82d9394e94790b93dde24f03ced5e71122850
58,802
async def async_rpc_set_tmux_window_visible(connection, tmux_connection_id, window_id, visible): """Hides/shows a tmux window (which is an iTerm2 tab)""" _assert_not_in_transaction() request = _alloc_request() request.tmux_request.SetInParent() request.tmux_request.set_window_visible.SetInParent() ...
69f8d7aa7a91dcf3daa0db8f772948b920739ac4
58,803
def localize_timestamp(timestamp, tz=None): """ Localizes timestamp to a given timezone If none of those have worked, localizes to settings.TIME_ZONE. """ if isinstance(timestamp, str): timestamp = get_parsed_datetime(timestamp) time_zone = get_tz(tz) try: local_time = timezo...
12d5cd68a68b3f40fed06874066d6461de2a4687
58,804
import os def read_error_ouput(exceldir, workbook, rowS=18, colS=1, colE=5): """ """ wb = openpyxl.load_workbook(os.path.join(exceldir, workbook), data_only=True) sheet = wb.get_sheet_by_name('summery') rowS = rowS colS = colS colE = colE mean_abs_error = sheet.rows[rowS][colS:colE] ...
96915db4421c5088c37f5fe3797135e1eed941ce
58,805
import yaml import textwrap def get_validated_configs(config_text: str, config_path: str, preset_target_definitions_text: str) -> "PlotmanConfig": """Return a validated instance of PlotmanConfig with data from plotman.yaml :raises ConfigurationException: Raised when plotman.yaml is either missing or malforme...
830c69aa24addde96876871eef55f99ffcf03296
58,806
def wrapsync(func): """Turns synchronous function into asynchronous.""" if iscoroutinefunction(func): return func async def inner(*args, **kwargs): return func(*args, **kwargs) return update_wrapper(inner, func)
4b8b490facf00f5f632b71f9c440dd90b96dbd70
58,807
def softmax(x): """Calculates the softmax for x(numpy array, matrix, vector, of any shape)""" return np.exp(x) / np.sum(np.exp(x), axis=1, keepdims=True)
059ccba8b3fb69e7d76814778469b457440bb3c4
58,808
def diff(x): """ Computes the approximate local derivative of `x` via finite differencing assuming unit spacing. Can be viewed as the opposite of trapz(). Args: x: The vector-like object (1D np.ndarray, cas.MX) to be integrated. Returns: A vector of length N-1 with each piece corresponding...
e7e21447f2c745ab8d05f05a9c6c50e24a9aec55
58,809
import random def random_sentence_swap(sentences, p): """Swaps sentences with probability p.""" def swap_sentence(s): idx_1 = random.randint(0, len(s) - 1) idx_2 = idx_1 counter = 0 while idx_2 == idx_1: idx_2 = random.randint(0, len(s) - 1) counter += 1 if counter > 3: ...
5a2fa1a7303dc6fe924803fe6fad2ef5da998733
58,810
import torch def multiclass_dice_threshold(logits, targets, threshold=0.5, iou=False, eps=1e-8): """ Dice coefficient metric for multiclass binary target. If iou=True, returns iou metric, classic for segmentation problems. """ n = targets.shape[0] #Batch size of 4 #Flatten logits ...
e6c1565532accde1debfbf2cf92939797d30b020
58,811
def process_not_implemented(**kwargs): """ default process function - return not implemented """ ret_dict = { 'function_return': 'not-implemented', 'slack_response': {} } return ret_dict
c78b7cda6e52471a5839d1231f45ba45d077888b
58,812
def Eval_point(state, data): """ External validity, where data is a multiset of points, to be used as point predicates""" vals = [state(*a) ** data(*a) for a in data.sp.iter_all()] val = _prod(vals) return val
0dc29e2c1d668e4b077efe55e2c3ec3243f77abc
58,813
import collections import itertools def WrapTypeDeclUnit(name, items): """Given a list (classes, functions, etc.), wrap a pytd around them. Args: name: The name attribute of the resulting TypeDeclUnit. items: A list of items. Can contain pytd.Class, pytd.Function and pytd.Constant. Returns: A...
49e5e1e8e962b8c9add3ec99fc63b9f5f3442022
58,814
def plot_decision_boundary(ax, clf, xx, yy, **params): """Plot the decision boundaries for a classifier. Parameters ---------- ax: matplotlib axes object clf: a classifier xx: meshgrid ndarray yy: meshgrid ndarray params: dictionary of params to pass to contourf, optional """ Z ...
99f8d9f42b8e9fba9ab6b5936ed5f3c24ab18789
58,815
def reassign_assignment(worker_id, assignment_id, staffing_request_inquiry=None): """ Return a given assignment after reassigning it to the specified worker. Args: worker_id (int): The ID of the worker to be assigned. assignment_id (int): ...
8be2e860203249ab4001170062db56edb2212806
58,816
from typing import Tuple import torch def draw_img_preds( img: Tensor, bboxes: Tensor, bbox_labels: LongTensor, img_size: Tuple[int], color: Tuple[int] = (0, 0, 255) ) -> np.ndarray: """ Args: img: bboxes: xyxy order, normalized img_size: (h, w) """ img = TF...
b576e151eb6641c76bf1cfb1ae6d1d8afd5537e0
58,817
def read_depot(df): """ reads the instance with the data, return the clietns data only :param dataframe: :return: a list of clients with their locations, demand """ #clients = df.loc[] depot = df.loc[df.demand.isna(), ["x_loc", "y_loc"]] return [depot.values[-1]]
baece330e54db024915f5ab6fd1ec724b687b5a0
58,818
def parse_human_activity_recog_data( data_path='https://raw.githubusercontent.com/ChicagoBoothML/MLClassData/master/HumanActivityRecognitionUsingSmartphones', X_names_file_name='features.txt', train_subfolder_name='train', X_train_file_name='X_train.txt', y_train_file_name='y_train.txt', ...
6ecb076308e5121262a07f836562791b7bf6c05e
58,819
def quaternions_to_euler_angles(quats, rotmode=EulerOrder.ZXY): """ See https://www.geometrictools.com/Documentation/EulerAngles.pdf """ if rotmode == EulerOrder.ZXY: return quaternions_to_ZXY_euler_angles(quats) elif rotmode == EulerOrder.YXZ: return quaternions_to_YXZ_euler_angles(...
92a0a17180fe451bb7d7968b01b9694e6ca6b7fa
58,820
def _expand_mock_imports(*mock_imports): """Returns an expanded set of mock imports. mock_imports is expected to be a dict which looks like: { "absolute.module.name": SomeObject, } The objects in this dictionary will be the ones returned in the eval-compatible env dict. Think of it as a fake sys...
78941ddde22dc750fac3904a5a0b3d0578f8b91e
58,821
import collections def duplicate_steps(name, value): """Argument validator to check template for duplicate steps""" # TODO(mgoddard): Determine the consequences of allowing duplicate # steps. # * What if one step has zero priority and another non-zero? # * What if a step that is enabled by default...
848f2540b8c55a4a851b458718787a948f3e2694
58,822
def insert_perform_labeling_job_metadata( parent_batch_id, batch_id, batch_status, batch_metadata_type, num_children_batches, ): """Creates a new record in the batch execution metadata table. Parameters ---------- batch_id: id to retrieve the associated batch_execution_metadata ...
e01d5c8b4fcea732ce1e9eec00fc352a8e2c5d18
58,823
def read_rosbag(bagfile, state_topic='/state_output'): """ Read states from a rosbag file """ states = [] time = [] with Bag(bagfile) as bag: start = bag.get_start_time() for topic, msg, t in bag: if topic == state_topic: states.append([ ms...
c0eccba042b24fbe6dccbcd7495dc4b316a861f9
58,824
def lazy_npgettext(context, singular, plural, num, **variables): """Like :func:`npgettext` but the string returned is lazy. The translation happens when it is used as an actual string. """ return _lazy_translate('npgettext', context, singular, plural, num, **variables)
94991ca1fc2a5050027d9120cb7b6429f4078b45
58,825
def is_complete_sentence(root_node): """ We'll use "complete sentence" to mean we've found a node tagged 'S' directly below a node tagged 'ROOT', i.e.: (ROOT (S ...)) """ return root_node.label() == 'ROOT' and \ len(root_node) == 1 and \ root_node[0].label() == 'S'
4bac130f2264b7dfabd66371031b5caa472017a7
58,826
from re import T def clamp(v: T, min_v: T, max_v: T) -> T: """ clamp関数 入力値を`[min_v, max_v]`の範囲に収める :param T v: 入力値 :param T min_v: 最小値 :param T max_v: 最大値 :return: `[min_v, max_v]`内に収めた値 """ return min(max_v, max(v, min_v))
4d90a11e7201cf449e82befa1a05d7a3cfb9ba3c
58,827
import base64 def base64url_encode(data): """ Url safe version of urlsafe_b64encode with stripped `=` sign at the end. :param data: input data :return: Base64 URL safe encoded string """ return to_string(base64.urlsafe_b64encode(to_bytes(data)))
002c975239fce8b64915ea4296d83e2f0be4b8e5
58,828
def _get_hub_by_entity_id(hass: HomeAssistant, entity_id: str) -> HmHub | None: """ Get ControlUnit by device address """ for control_unit in hass.data[DOMAIN].values(): if control_unit.hub.entity_id == entity_id: return control_unit.hub return None
b6503c060b54701dccf8ab2243c8a8cc8fa4fcd4
58,829
def pressure2dBSPL (p, pRef=20e-6): """ Convert sound pressure (p [Pa]) to sound pressure level (L [dB]). Parameters ---------- p : ndarray-like or scalar Array or scalar containing the sound pressure in Pa pRef : Sound pressure reference in the medium (air:20e-6 ...
3bdf675db331aab5e4b502a07b44238243f0ebd7
58,830
def info(): """Returns the challenge name and site.""" init() challenge = get_challenge() return "Challenge name : %s @ %s" % (challenge.name, challenge.domain)
d598fe046ab9de0d86f8188b9df0ddfb46a23377
58,831
import json def create_mapping_dict(total_parsed_results, type_field): """ Create a {'field_name': 'fields_properties'} dict to be used as mapping schemas. Args: total_parsed_results: list. the results from the splunk search query type_field: str. the field that represents the type of the ...
3dd29abbd986a42a2c3a2cab8cd5e40b0b6a65ca
58,832
def metric_fn(config, metrics, eval_fn_inputs): """Computes the loss and accuracy of the model.""" d = eval_fn_inputs metrics["masked_lm_accuracy"].update_state( y_true=tf.reshape(d["masked_lm_ids"], [-1]), y_pred=tf.reshape(d["masked_lm_preds"], [-1]), sample_weight=tf.reshape(d["ma...
450bb814c93b3eb260e81e0c10135cc5e3ed37fd
58,833
import csv import numpy def read_file(input_filename, parm): """ Read the given parameter from the given file and return array of data """ # print('Reading', input_filename) infile = open(input_filename) reader = csv.DictReader(infile) vals = [] for row in reader: vals.append(f...
af9417ae42a582aae69b5209d6bf73f7e890dc4a
58,834
def not_safe_gerone(a, b, c): """ Compute triangle area from valid sides lengths :param float a: first side length :param float b: second side length :param float c: third side length :return: float -- triangle area >>> not_safe_gerone(3, 4, 5) 6.0 """ p = (a+b+c)/2 return ...
499cf398158d170363ea22096b44ea16e402a23a
58,835
def shelf_pwlin(r): """ Ocean followed by continental slope, continental shelf, and beach. The ocean is flat, the slope, shelf, and beach are linear. """ z = z0_shore + slope_of_beach * r # beach z = where(r<x0_beach, z0_shelf + slope_of_shelf*(r-x0_shelf), z) z = where(r<x0_shelf, z0_ocea...
99bfff14129bd634376395bbe346b52eb169ec1f
58,836
def generate_symmetric_group(configuration, symmetry): """ For a particular configuration and list of sublattices with symmetry, generate all the symmetrically equivalent configurations. Parameters ---------- configuration : tuple Tuple of a sublattice configuration. symmetry : list...
12883715b424347468c638fe58d2b52f571ce48f
58,837
import sympy def r_per_amplitude(m, theta_i): """ Calculate the reflected amplitude for perpendicular polarized light. Args: m : complex index of refraction [-] theta_i : incidence angle from normal [radians] Returns: reflected fraction of perpendicular field [-]...
96a278c908282e16b29e724c2bfae954395f83b6
58,838
def is_iterable(an_object, include_strings=True): """ Returns True if an object is iterable, False otherwise. Iterable types include lists, tuples, dicts, strings, numpy arrays, etc. If include_strings is False, then strings are not considered iterable. This is useful because often we use is_iterable()...
7b9f531e3cf69d7fa90d8b9d17188c07f8d7e2da
58,839
from keras.applications.vgg19 import preprocess_input def preprocess_VGG19(img): """ Preprocess image for use with VGG19 Parameters ---------- img : ndarray Raw image as a numpy array Returns ------- img : ndarray Preprocessed image as a numpy array """ return...
aa18c5f92b82e8d7059b7060a67ca40a4326794d
58,840
def quote_text(text): """Quote text and normalize it in sonic protocol context. Arguments: text str -- text to quote/escape Returns: str -- quoted text """ if text is None: return "" return '"' + text.replace('"', '\\"').replace('\r\n', ' ').replace('\n', ' ') + '"'
530042874e8d7531ed14ef8d348211d8d5907902
58,841
def noiseReductionUsingGaussian(image, Kx = 5, Ky = 5) : """ Performs Gaussian Blurring Parameters ---------- image : (M,N) ndarray Input image Kx : Int Kernel size in X direction Ky : Int Kernel size in Y direction Returns ------- image : (M, N) ...
fde36d4ba0b1df67f9ae75fea630c04f0fbfc8bf
58,842
def compName(n1, n2): """ Compare names: n1 n2 strings, blankspace separated names return value between -1 (mismatch) and 1 (match) return None if any of n1, n2 is empty can be used on names, normalised names """ if (not n1) or (not n2): return None nn1 = n1.strip().split() n...
7a37261779f38040e0baa3bf99bbaf66569d6962
58,843
def add(cm_response, **data): """ Creates template of VM. Template has a name and some description. It defines VM's hardware parameters: CPU and memory. It also defines number of points utilized by VM created of it (per hour and overly). @clmview_admin_cm @cm_request_transparent{user.add()} ...
ff8b29ccb0fa288c018275d09208a0b3cfddfce0
58,844
def z_tf(u, H): """ discrete-time transfer function u - the input signal H - the transfer function """ def get_zm1_coeff(L): numcf = L.num[0][0] dencf = L.den[0][0] N = len(dencf)-1 M = len(numcf)-1 # convert to normalized z^...
8a87bce5f3968916d67706e1ac4ce4d137ab7927
58,845
def find_fixed_point(arr): """ Returns i such that arr[i] = i (or -1, if no such i exists). """ #--------------------------------------------------------------------------- # Easier Version: Assume that all integers are distinct (binary search). #-------------------------------------------------...
6697a83cb923e228bbf46c9da49f5f4da1732b4c
58,846
import os import time from datetime import datetime import tqdm import json def download_vn_data( url='http://enviinfo.cem.gov.vn/', save_folder='../data/vn_epa/'): """Download hourly data for all monitoring stations from Vietnamese EPA. All data are saved into the save files Args: ...
0d78a61b7c5bf2ce1657e6017d54fb3a03c8b822
58,847
def devices_action(module): """ Manage all actions related to devices. Action ordonancer and output bui Structure output: >>> devices_action(module) { "changed": "True", "data": { "tasks": [ { "workOrderId": "108", "name": "", ...
4bf09077987f449e4011338434207485bb07b947
58,848
def EventGrain(src_id_or_meta=None, flow_id_or_data=None, origin_timestamp=None, creation_timestamp=None, sync_timestamp=None, rate=Fraction(25, 1), duration=Fraction(1, 25), event_type='', topic='', ...
04207a6fb517e608450a0d40e31d9dcf60cf0c8a
58,849
from typing import Optional from typing import List def tall_info_card( box: str, name: str, title: str, caption: str, label: Optional[str] = None, icon: Optional[str] = None, image: Optional[str] = None, image_height: Optional[str] = None, categ...
2596b739df78b87b20d7cf236b41f087e6cf38d0
58,850
def _func(coeffs, *labels): """ Takes the dot product of coefficients vec & labels vector Parameters ---------- coeffs: np.ndarray the coefficients on each element of the label vector *labels: np.ndarray label vector Returns ------- dot product of coeffs vec and lab...
b445df24f1137f0c43de469cf9270f43115710c9
58,851
def make_object(n): """Take a list of pairs and create a dict NOTE: run through make_array to transform the results to an array """ return dict(make_array(n))
a96403a493809d3be6ed5391f41e2d431769d9cf
58,852
def load_image(test_data, shape): """Load calibration images.""" test_np = np.fromfile(test_data, dtype=np.float32) test_shape = (-1,) + tuple(shape[1:]) test_np = np.reshape(test_np, test_shape) calib_num = 32 if test_np.shape[0] > calib_num: return test_np[:calib_num] else: ...
c91ff785c8b466e573f990fd51a56665742db152
58,853
def ssl_loss_pi_model(labels_x, logits_x, logits_teacher, logits_student): """ Computes two cross entropy losses based on the labeled and unlabeled data. loss_x is referring to the labeled CE loss and loss_u to the unlabeled CE loss. Args: labels_x: tensor, contains labels corresponding t...
e1d013366d3e13ae13ec4fc5e7362ff36faa0f95
58,854
def ellipseCircleIntersections(s_circle, a, b, mx, my, x, y, minSep, maxSep, lminSep, lmaxSep, yrealAllRealInds, yrealImagInds, sma=None, e=None, W=None, w=None, inc=None): """ Calculates the intersections between a circle centered at x,y with radius s_circle and an ellipse centered at x=0, y=0 with semi-major axis...
b8f183e2892f1dfac52564f01aebf679857e34ec
58,855
from typing import Tuple from typing import Optional import urllib def parse_netloc(netloc: str) -> Tuple[str, Optional[int]]: """ Return the host-port pair from a netloc. """ url = build_url_from_netloc(netloc) parsed = urllib.parse.urlparse(url) return parsed.hostname, parsed.port
4f24482b60f38e880d9748d4e42361265d0b7964
58,856
def glcm_features(image, distances, orientations, properties): """ Compute properties of the Grey-Level Co-occurance Matrix for an image :param image: image to compute the GLCM for :param distances: distances to compute the GLCM across :param orientations: angles to computes the orientations over :...
63196a13f257aab56f43deb1156a2391b42f3089
58,857
def darknet53(**kwargs): """ DarkNet-53 'Reference' model from 'YOLOv3: An Incremental Improvement,' https://arxiv.org/abs/1804.02767. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' ...
8d88394ec127ac376df02d69ffb51af74649bc60
58,858
def triangulate_vertices(vertices): """ Built a triangular mesh from 3d points Uses the scipy Delaunay algorithm in a u,v parametrization see for more info about Delaunay: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html :param vertices: flatten 3D points used fo...
6371ccb1aca2f2d725d2240559e91f0c6c18c146
58,859
import numpy def draw_mandelbrot(width, height, left, right, top, bottom, iterations, z0): """Returns a PIL.Image representing the given portion of the set.""" x, y = numpy.meshgrid(numpy.linspace(left, right, width), numpy....
af01deddb80917bf577b757b6a5d552e148109aa
58,860
from typing import List def make_field_dimensions_cartesian(mask: List[int] = None) -> FieldDimensions: """ Create FieldDimensions of cartesian type :param mask: mask to identify which cartesian dimensions are legal (default is [1, 1, 1]) """ if mask is None: mask = [1, 1, 1] assert len...
618e158ac4e6052de42be76b916f51ff2a9006a4
58,861
def change_config(set_attr): """ 因为每次更改属性都要刷新托盘菜单,并且写到配置文件中, 所以定义一个装饰器,以简化代码 :param set_attr: 更改属性的函数 :return: 装饰过的函数 """ def wrapper(plugin, option_text): f = set_attr(plugin, option_text) plugin.save_config() plugin.root.refresh_menu() return f return w...
0f497fb83007dbcd353f44a684c5be995821b424
58,862
def matrix_determinant(M, check=True): """Calculates the determinant of a square matrix M. Parameters ---------- M : list[list[float]] A square matrix of any dimension. check : bool If True, checks if the matrix is square. Raises ------ ValueError If the matrix ...
fc9aa8222274cecb3e32c008c664348392351423
58,863
def get_kubeconfig_current_cluster_name(_kc_model=None): """ :param _kc_model: Internally used to cache kubeconfig info. :return: Returns the cluster associated with the current context. """ kc = _get_kubeconfig_model(_kc_model=_kc_model) current_context_name = get_kubeconfig_current_context_nam...
8198b0ed906fefc0ffaf1f0b67042f0d390accba
58,864
from pathlib import Path def find_artefacts(base_dir:str, type="models", target_file="model.py", target_string="mantraml"): """ Find a Mantra artefacts directory :param base_dir: Base directory to look at :param type: Can be `models`, `data`, `tasks` :param target_file: File use to identify the a...
520e2b18e27c20e4f1aa81a471ea940a9e2b6d8b
58,865
def make_allocation(patient,**kwargs): """ Allocation based on facility preference """ print('allocating',patient) if(patient.group.category == Group.FAMILY): family = patient.group.person_set.all() else: family = [patient] allocated = True for i in range(len(fami...
18bb76f802a79dc533f3d98cdb7320f55413ecc3
58,866
import argparse def _get_parser(): """ Returns an ArgumentParser for TensorFlow Lite Converter. """ parser = argparse.ArgumentParser( description=("Command line tool to run TensorFlow Lite Converter.")) # Converter version. converter_version = parser.add_mutually_exclusive_group(required=...
c4f30733852066362a9549856abaf367e1f0ca8d
58,867
def is_container_flag( df, watersource_col="mhm_WaterSourceType", bit_col="mhm_IsWaterSourceContainer", inplace=False, ): """ Creates a bit flag: `mhm_IsWaterSourceContainer` where 1 denotes if a watersource is a container (e.g. ovitrap, pots, tires, etc.) and 0 denotes the contrary. Parame...
bce47480feb0e3bbc2562d246c4796bc8a822b9b
58,868
from prettytable import PrettyTable def format_term_rankings( term_rankings, labels = None, top = 10 ): """ Format a list of multiple term rankings using PrettyTable. """ # add header header = ["Rank"] if labels is None: for i in range( len(term_rankings) ): header.append("C%02d" % (i+1) ) else: for la...
37682b3c8d8535e73181da4c8daaf4fb1ee79617
58,869
def get_request_user(request): """ 获取请求user (1)如果request里的user没有认证,那么则手动认证一次 :param request: :return: """ user: AbstractBaseUser = getattr(request, 'user', None) if user and user.is_authenticated: return user try: user, tokrn = JWTAuthentication().authenticate(request...
8dcb6d61821d8a546c0b36a1baa0829425d84cdc
58,870
def test_paper_page_end(root, printerror=False): """Verifies if the papers declared in the Lattes CV parsed in the argument root contain a declared end page. Args: root: the Lattes CV that has been parsed with the ElementTree language. flag: if 0, then all papers in the Lattes CV hav...
40b083fa8b2b38211e74e590033c4029cc57b09d
58,871
from sage.matrix.constructor import matrix def lfun_eta_quotient(scalings, exponents): """ Return the L-function of an eta-quotient. INPUT: - scalings -- a list of integers, the scaling factors - exponents -- a list of integers, the exponents EXAMPLES:: sage: from sage.lfunctions....
d77a37f0259d82f25263914a187f373bed6e4057
58,872
from typing import List def add_option(poll: Poll, text: str, added_options: List[str], is_date: bool): """Parse the incoming text and create a single option from it. We allow option descriptions after an `--` or `—` delimiter. `added_options` is a list of names of options that have already been a...
fbdbf35696c45938c2fc8e85bb27ec04a53f1c00
58,873
def test_gen_moving_timeseries_forecast_with_regressors(): """Test for `gen_moving_timeseries_forecast` with regressors""" data = generate_df_for_tests(freq="1H", periods=1000) df = data["df"] df["x"] = 40 # A simple train-forecast function which always uses last available # value, then adds th...
bb22353aa67e97c06d73160773af03f28895202b
58,874
import re from bs4 import BeautifulSoup import requests def mediafire(url: str) -> str: """ MediaFire direct link generator """ try: link = re.findall(r'\bhttps?://.*mediafire\.com\S+', url)[0] except IndexError: raise DirectDownloadLinkException("No MediaFire links found\n") page = Be...
3a79fc7c42a0531b1e3acc56252873b1d3ec7f21
58,875
from typing import List def _add_outputs_of_onnx_model(model, output_nodes: List[str]): """ Add output nodes of onnx model. Args: model (ModelProto): ONNX model. output_nodes (list[str]): Output nodes list. Returns: ModelProto, edited ONNX model. """ onnx = import_mod...
4170d36d9d18ee023a550a72209d769ca182c64d
58,876
def get_pane_working_directory(session: str, window: int, pane: int): """ Get the working directory of a given pane Parameters ---------- session : str Name of the session window : int Window number of pane pane : int Pane index in the window """ return get_t...
f5b469ddbd5efc483be944dc09ac539256cc9f93
58,877
def export_report(id: str, report: str, filename: str) -> bool: """Exports a report summary to a file. Args: id: An extension identifier string. report: A string of the report summary. filename: The chosen filename as a string. Returns: A boolean result for exporting the re...
682694ce9eb0bae2e7f56b4afcdad0d13f6d54ff
58,878
import pickle def simulation(*vars): """ Evaluate a dam hazard potential 'simulation' with a given set of spatial parameters and random forest hyperparameters :param vars: tuple A set of spatial and nonspatial parameters :return: tuple Objective values "...
e949876d60e7cc1fada727a7279ccff562b29d3b
58,879
def GetInfoForCountry(country_name_or_code): """Get code, name, lat and lon for a given country name or code.""" match = False partial_match = False if not country_name_or_code: return None if len(country_name_or_code) == 2: country_code = country_name_or_code.upper() country_name = False els...
db773274d73e210bac2ed237ff0704d923973562
58,880
def sqs_lookup_url(session, queue_name): """Lookup up SQS url given a name. Args: session (Session) : Boto3 session used to lookup information in AWS. queue_name (string) : Name of the queue to lookup. Returns: (string) : URL for the queue. Raises: (boto3.ClientError):...
4f7bfb98d10a372b3b07f270e2a25e3227732f41
58,881
def calcstat(iv, ev, base, level, nature_stat): """Calculate the battle stat of a Pokémon. Note that some stats may be off by one compared to the "official" PKM data. I've only found this to be true on a specific FAL2010 Mew file, but it's worth mentioning. If you would like to be safe, deposit the...
facaeeb2f054a1b091f7383b6342dc624317fed2
58,882
import typing def interpret_target(raw_target: str) -> tuple[typing.Callable, str]: """Determine saving function and target string from input target""" HELP = "Target must be u/username or r/subreddit" SAVERS = {"u": save_user, "r": save_subreddit} assert "/" in raw_target, HELP raw_target = raw...
370680104db88f1cecf66001ea31797efd32d146
58,883
import os import json import codecs def write_files(journal, path, format): """Turns your journal into separate files for each entry. Format should be either json, md or txt.""" make_filename = lambda entry: e.date.strftime("%Y-%m-%d_{0}.{1}".format(slugify(u(e.title)), format)) for e in journal.entri...
26ad732c0a087147578a0a9703ca312ef2f3673f
58,884
def split_dataset(data, keys, p=[ .6, .2, .2 ]): """ This procedure splits a dataset, with split_percentage, and filters it keeping only specified keys, :param data: dictionary with all datat in (key, sentences) format :param keys: list of required keys :param p: percentage of the test_set set, what is ...
d2775be2563d97f11d1f7f1a2e7466365e433ed5
58,885
def get_image_array(self, image_id=None, ann_id=None): """ Retrieves the array associated with the image_id or ann_id """ image_pil = self.get_image_pil(image_id=image_id, ann_id=ann_id) return np.asarray(image_pil)
ca7a6202b2c690790bfd94683ab64d8a13486301
58,886
import os import logging import hmac import hashlib import threading def generate_xferspec_download( blob_service, file_service, args, storage_in_queue, localfile, remoteresource, addfd, blobprop): """Generate an xferspec for download Parameters: blob_service - blob service fil...
e2ebda0aa9c5679d3a24d336055e230f67313d19
58,887
from datetime import datetime import traceback async def login_post(request): """ Server login page for the browser :param request: :return: """ try: try: post_data = await request.json() except Exception as _e: print(f'Cannot extract json() from req...
c873796744b944fdf033e94e3696db97da724470
58,888
def getMSDP(obdm): """ This function takes the time dependent obdm matrix and finds the time evolution of the momentum space density profile (MSDP) OUTPUTS: msdp[time idx][p idx] """ msdp = np.zeros((len(obdm), numpts), dtype=np.complex_) # to evaluate this integral we need...
35d01cd77dbca2cc6a36dbf39cb310a20c81ef68
58,889
def get_government_factions(electoral_term): """Get the government factions for the given electoral_term""" government_electoral_term = { 1: ["CDU/CSU", "FDP", "DP"], 2: ["CDU/CSU", "FDP", "DP"], 3: ["CDU/CSU", "DP"], 4: ["CDU/CSU", "FDP"], 5: ["CDU/CSU", "SPD"], ...
cfd502f81ebb0536432da4974ab9f25724dc83df
58,890
import os def load_cifar10(batches_data_folder): # language=rst """ Load a single batch of the cifar dataset :param filename: Where the batch is located """ # Load the cifar training data batches xs, ys = [], [] for batch_idx in range(1,6): filename = os.path.join(batches_data...
09d76b4bedd76d6dc2dea005dcc5f3b8d44d9226
58,891
def lognormal(mean=0.1, std=0.5, shape=1, z=0): """Draw burst from lognormal distribution. Args: shape (tuple): Required array shape z (array): Redshift of pulses Returns: type: Description of returned object. """ w_int = gd.lognormal(mean, std, shape).astype(np.float32) ...
26c1d6d06da01699fb6afa44824d98670d4ef86f
58,892
def krisciunas_schaefer_free(obs_zenith, moon_zenith, separation_angle, moon_phase, vband_extinction, C_R, C_M0, C_M1, M0, M1, M2): """Calculate the scattered moonlight surface brightness in V band. Based on Krisciunas and Schaefer, "A model of the brightness of moonlight", PASP, vo...
867b4b148e4e76b73aa02bfcc88f1b61bf7d87ae
58,893
from typing import List def _ipv6_address_validator(address: str, strict: bool = True) -> bool: """Validates the address part of an IPv6 address""" valid = True segments = [] empty_segment = f'{IPV6_MIN_SEGMENT_VALUE}' * IPV6_NUMBER_BIT_COUNT # Split on zero-skip, if any try: left, *...
91f6035b98e35fefd594af4b0e6d83b78f6da83c
58,894
def bam_read_count(bamfile, samtools_path="samtools"): """ Return a tuple of the number of mapped and unmapped reads in a BAM file """ p = Popen([samtools_path, 'idxstats', bamfile], stdout=PIPE) mapped = 0 unmapped = 0 for line in p.stdout: rname, rlen, nm, nu = line.rstrip().split() ...
914bf5ff14c7e267937f33b14cfaec563f7519b4
58,895
import logging import tqdm import gc def train_survci_info(model, x_train, y_train, e_train,W_train, x_valid, y_valid, e_valid,W_valid, n_iter=1, lr=1e-3, elbo=True, bs=100): #bs=100 """Function to train the torch instance of the model.""" #bs = 100 (ACTG-SYNT...
c0be3c0678c6671f187488c2070c13833007d287
58,896
def run_model(mod, params=None, opts=None): """Run model. Paramters --------- mod: Module The relay module. params: Parameters The model parameters. opts: Dict The compiler options. Returns ------- out: Data The output data. """ with transf...
f173fe3b2388177d53c25e6016b2f89e8cf382aa
58,897
def VectorVector_scalar(vectorA, vectorB): """ N diemnsional. Return a float as a scalar resulting from vectorA * vectorB""" result = 0 for i in range(0, len(vectorA)): result += vectorA[i] * vectorB[i] return result
c7f0448a05573b8ddba63ed7a8262072ffcda38f
58,898
def artifact_removal(X, n_components=None, check_result=True): """Remove artifacts from data. The artifacts are detected via Independent Component Analysis (ICA) and subsequently removed. To plot the results, use :func:`gumpy.plot.artifact_removal` Args: X (array_like): Data to remove arti...
59d15348ad3eb4744f3c364331d6d6e5f453f66e
58,899