content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_worker_list(AnnotationSet): """ return a list of worker IDs """ return list(AnnotationSet.dataframe.columns)[1:]
0f18afa4bb70360e03a1a65c1ab3a5b4bbba7e38
3,634,703
def is_string(data): """ Check property string validity """ if not len(data): return None if data[-1] != 0: return None pos = 0 while pos < len(data): posi = pos while pos < len(data) and \ data[pos] != 0 and \ data[pos] in printable.encode...
06232bae72c49a8ee50545c3fb8b0f6aed6102d9
3,634,704
import json def create_hdfs_metadata_pipeline(pipeline_builder, pipeline_title, hdfs_directory, hdfs_metadata): """Helper function to create and return a pipeline with HDFS File Metadata The Deduplicator assures there is only one ingest to HDFS. The pipeline looks like: dev_raw_data_source >> record_d...
fcf6d41365347a67e40a22ee01baceadb191d7e8
3,634,707
def dqpar_interpol(xfit, dqpars, ipkey='temperature'): """return interpolated parameters at temperature or exc_current Arguments: xfit -- temperature or exc_current to fit dqpars dqpars -- list of dict with id, iq (or i1, beta), Psid and Psiq values ipkey -- key (string) to interpolate ""...
5ddea416732e4c5602e07ab2e5e6067a05a2530e
3,634,708
def visflow_par_str(direc, size, str_type="file"): """ visflow_par_str() Returns a string with stim type, as well as size (e.g., 128, 256) and direction (e.g., "right", "left") parameters, unless all possible visual flow parameters values are passed. Required args: - direc (str or li...
f214dd87c6eece8ce7fec3bdd846c0ad969de139
3,634,709
import math as m from math import sin, cos, atan, asin, floor def equ2gal(equ): """Convert single Equatorial J2000d to Galactic coordinates.""" ra, dec = equ OB = m.radians(23.4333334); dec = m.radians(dec) ra = m.radians(ra) a = 27.128251 # The RA of the North Galactic Pole d = 192.8...
a7a007ad64595c72f80b02736fba8307d6c668b2
3,634,710
import torch def pre_residual_correlation(labels, model_out, label_idx, **trash): """Generates the initial labels used for residual correlation""" # what happened: # z = model_out; y = labels # it take inputs of BOTH model_out and labels # then, assign (y-z) at indexed locs, and 0 els...
11bda13c8046788ad5b78943bd47c06ebbe63b93
3,634,711
def trimesh2Panda(trimesh, name = "auto"): """ cvt trimesh models to panda models :param trimesh: :return: """ return packpandanp_fn(trimesh.vertices, trimesh.face_normals, trimesh.faces)
6afbbf9cc5bfeed4dbd1aa94985b246921e2aac9
3,634,712
from sklearn.feature_extraction.text import TfidfVectorizer from nltk import snowball, word_tokenize def compute_similarity(left, right, tokenize=False, stop_words=None, **kwds): """Compute cosine similarity from tfidf-weighted matrix consisting of two vectors (left and right). """ def tokenize_and_s...
b895e3921eecc3a14481279073250b3c99a20e5e
3,634,714
def hr_max_sqi(nn_intervals): """ Function returning the max heart rate . The input nn_interval in ms is converted into heart rate bpm (beat per minute) unit Parameters --------- nn_intervals : list Normal to Normal Interval Returns --------- : float The maximum...
abc1e3b5385049fd5ab991a3ae92b3a2b0da5e9e
3,634,717
import torch def fft(x): """ Layer that performs a fast Fourier-Transformation. """ img_size = x.size(1) // 2 # sort the incoming tensor in real and imaginary part arr_real = x[:, 0:img_size].reshape(-1, int(sqrt(img_size)), int(sqrt(img_size))) arr_imag = x[:, img_size:].reshape(-1, int(s...
e63143c79ef2446736384c243b36ea3b09a76279
3,634,718
def generate_elgamal_auxiliary_key_pair( owner_id: GUARDIAN_ID, sequence_order: int ) -> AuxiliaryKeyPair: """ Generate auxiliary key pair using elgamal :return: Auxiliary key pair """ elgamal_key_pair = elgamal_keypair_random() return AuxiliaryKeyPair( owner_id, sequence_ord...
18cd4fe4908181f4d38d8e31d2b3392cc7e6ce6d
3,634,719
def benchmark_random(backtest, random_strategy, nsim=100): """ Given a backtest and a random strategy, compare backtest to a number of random portfolios. The idea here is to benchmark your strategy vs a bunch of random strategies that have a similar structure but execute some part of the logic ...
4c0bea5e3d434940102180c1f6caf5d685dc7ee6
3,634,721
def detachStatement(request): """ ํ•˜๋‚˜์˜ ์ „์ž๋ช…์„ธ์„œ์— ์ฒจ๋ถ€๋œ ๋‹ค๋ฅธ ์ „์ž๋ช…์„ธ์„œ๋ฅผ ํ•ด์ œํ•ฉ๋‹ˆ๋‹ค. - https://docs.popbill.com/statement/python/api#DetachStatement """ try: # ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ CorpNum = settings.testCorpNum # ํŒ๋นŒํšŒ์› ์•„์ด๋”” UserID = settings.testUserID # ์ „์ž๋ช…์„ธ์„œ ์ข…๋ฅ˜์ฝ”๋“œ, 121-๋ช…์„ธ์„œ, 122-์ฒญ๊ตฌ์„œ, 123...
cff3d9f3e9ac3a22beaff8630f2494bb3643bab3
3,634,722
def this(func, cache_obj=CACHE_OBJ, key=None, ttl=None, *args, **kwargs): """ Store the output from the decorated function in the cache and pull it from the cache on future invocations without rerunning. Normally, the value will be stored under a key which takes into account all of the parameters t...
a60d4c74198dd6435a9b67bba0f53eba8fc33225
3,634,723
def get_data(table,cid,fields=None,date=None): """ table = name of database table fields = list of database fields to return key = dict with unique identifier and value """ status = False sql = "SELECT " if fields: sql += ','.join(fields) else: sql += "*" s...
4ab5a3dbeb3ecaab5abdb97e3030c09c20ac64ba
3,634,724
from typing import List from typing import Callable from typing import Tuple def jwt_perm_required(perms: List[str]) -> Callable: """ Receives a list of permissions and only process the inner function if the jwt token available in the input request have the required permissions. """ def process_fu...
19eb006696de38c011b9c0ad33ed3804664f2e78
3,634,725
def get_park1_function_caller(**kwargs): """ Returns the park1 function caller. """ opt_val = 25.5872304 opt_pt = None func = lambda x: park1(x, opt_val) domain_bounds = [[0, 1]] * 4 return get_euc_function_caller_from_function(func, domain_bounds, vectorised=False, opt_val=opt_val, opt_pt=opt_pt...
8cf82bb083df8eeefb83630918bf048b7fed1989
3,634,726
def univariate_analysis(groups): """Mean, median, variance""" groups_to_analyze = [] basic = {} central_tendencies = {} dispersion = {} all_vals = np.array([]) for group in groups: all_vals = np.concatenate((all_vals, group['vals']), axis=0) groups_to_analyze.append(group) ...
0e5806d06e252a230eed60672d2e6ba63e9cd9c7
3,634,727
from typing import Callable def smape(actual_series: TimeSeries, pred_series: TimeSeries, intersect: bool = True, reduction: Callable[[np.ndarray], float] = np.mean) -> float: """ symmetric Mean Absolute Percentage Error (sMAPE). Given a time series of actual values :math:`y_t` ...
96c1fc712ded84830b086264ef3a78bc12ddb937
3,634,730
def func_two(x): """ Harder function for testing on. """ return np.sin(4 * (x - 1/4)) + x + x**20 - 1
eca62a1aea260029329fdaa360989d15d0070d91
3,634,731
def random(samples, key=(0, 0), counter=(0, 0), sampler="gaussian", threads=False): """Generate random samples from a distribution for one stream. This returns values from a single stream drawn from the specified distribution. The starting state is specified by the two key values and the two counter v...
332c1ff48463a6c904f2cb75a80c0e9d0fa81afd
3,634,732
def random_effect_2level_model(dataframe): """ Multi-level model_1_sci includes intercept, variable as fixed and the interaction term random on country level. :param dataframe: a data frame with student ID, school ID, country ID, science, math, reading, and other five selected variables...
9184a6a513b1e0a24e747de4bc5811f7a724edc9
3,634,733
def get_model_data(model_name: str): """ Return model data saved in demisto (string of encoded base 64) :param model_name: name of the model to load from demisto :return: str, str """ res_model = demisto.executeCommand("getMLModel", {"modelName": model_name})[0] if is_error(res_model): ...
042f39ca2028ed6986ebe0a5573bb16baa27bd04
3,634,735
def get_bprop_batch_norm(self): """Grad definition for `BatchNorm` operation.""" is_training = self.is_training input_grad = G.BatchNormGrad(is_training, self.epsilon, self.data_format) def bprop(x, scale, b, mean, variance, out, dout): if is_training: saved_reserve_1 = out[3] ...
4454d514b5b3b7f7ba96370c5e35e8c63b29828f
3,634,736
def deg_to_num(lat_deg, lon_deg, zoom): """ degree to num """ lat_rad = radians(lat_deg) n = 2.0 ** zoom xtile_f = (lon_deg + 180.0) / 360.0 * n ytile_f = (1.0 - log(tan(lat_rad) + (1 / cos(lat_rad))) / pi) / 2.0 * n xtile = int(xtile_f) ytile = int(ytile_f) pos_x = int((xtile_f ...
0459645ee4965a7226cc4e3167e86ca7eaa28108
3,634,737
def parse_cmdline(): """ Parse command-line arguments """ parser = ArgumentParser(prog=__file__) parser.add_argument("-i", "--indir", dest="indirname", action="store", default='multiplexed_data', type=str, help="Parent directory for multiplexed subfolders"...
3c8f4b44df9697a019fa093a70027e76c89ea7a2
3,634,738
import requests def get_google_api_books(query_dict: dict, params: dict = None, page: int = 1) -> tuple: """Get books from google api from given page.""" query = google_api_query(query_dict) if not params: params = {} params.update(GOOGLE_API_QUERY_PARAMS) start_index = (page - 1) * PAGIN...
c23e3ff5aa55b03dc6f9d8eb88bb4cbed49459d9
3,634,739
def get_messages(): """ Query the data base for messages and returns a container of database message objects. """ return Messages.select(Messages, MediaType).join(MediaType)
4df5018217edb7051af79150b162c1b2e590b07a
3,634,740
def create_db(x, y, train_size=0.8, bs=96, random_state=42): """ Take dataframe and convert to Fastai databunch """ X_train, X_test, y_train, y_test = train_test_split(x, y, train_size=train_size) train_ds = TrainData(X_train, y_train) val_ds = TrainData(X_test, y_test) bs = min(bs, len(tr...
006ee0c4d3e5f43f1b60c22324c03cef5be564eb
3,634,741
def bootstrap(resolver): """Lookup the root nameserver addresses using the given resolver Return a Resolver which will eventually become a C{root.Resolver} instance that has references to all the root servers that we were able to look up. """ domains = [chr(ord('a') + i) for i in range(13)] ...
4fd2287276a97e84b5433912c63d71f995282881
3,634,742
def estimate_prior_limits(param_space, prior_limit_estimation_points, objective_weights): """ Estimate the limits for the priors provided. Limits are used to normalize the priors, if prior normalization is required. :param param_space: Space object for the optimization problem :param prior_limit_estimat...
98b41f3882c11d941d5b771021f823971ab393d4
3,634,743
def rotate_by_point_and_angle(vector, origin, angle): """ Rotate vector at origin to angle :param vector: DB.XYZ :param origin: DB.XYZ of origin :param angle: Angle to rotate :type angle: float :return: DB.XYZ """ transform = DB.Transform.CreateRotationAtPoint(DB.XYZ.BasisZ, angle,...
f69d6485da9c22e7d9b2533f87fb285be01b8f21
3,634,744
def load_xviii_bayer_from_binary(binary_data, image_height, image_width): """Read XVIII binary images into bayer array Parameters ----------- binary_data : numpy.ndarray binary image data from XVIII image_height : int image height image_width : int image width Retur...
28495c2480e128109f0852a21780bf900fb0d1b8
3,634,745
from typing import Union from typing import Iterable from typing import Optional import ast def apply_dialects( source: str, names: Union[str, Iterable[str]], filename: Optional[str] = None ) -> ast.AST: """Utility for applying dialect transpilers to source code.""" reducer = dialect_reducer(names, filena...
faeeb21d9e7325bac5ab55b7df3f1dac8d1e83fb
3,634,746
def get_atoms(smiles): """ Process a SMILES. SMILES string is processed to generate a sequence of atoms. Arguments: smiles (str): a SMILES representing a molecule. Returns: a list of atoms. """ tokens = process_smiles(smiles) return [ REVERSED_ATOM_MAPPING[t...
e352159d4bc5d33833a4276a4ef13fbd4f89713c
3,634,747
from typing import Optional from typing import List def wide_article_preview_card( box: str, persona: Component, image: str, title: str, name: Optional[str] = None, aux_value: Optional[str] = None, caption: Optional[str] = None, items: Optional[List[Comp...
0b6b68e39d5e379392aa8ee26abca69cf64181bc
3,634,749
def calc_water_year(df: pd.DataFrame): """Calculates the water year. Parameters ---------- df : pandas.DataFrame Flow timeseries with a DataTimeIndex. Returns ------- pandas.DataFrame.index A pandas.DataFrame index grouped by water year. """ return df.index.ye...
40badcaae1bbf50add3616b4f420f7f46efe6d48
3,634,750
def count_and_dissect_tlvs(buf): """ Count and dissect TLVs. Return length of LLDP layer buf -- buffer to dissect return -- parsed_bytes_total, [(clz, bts), ...] """ shift = 0 tlv_type, tlv_len = 1, 1 clz_bts_list = [] while (tlv_type | tlv_len) != 0: type_and_len = unpack_H(buf[shift:shift + TLV_HEADER_LE...
0c32e7f2b3be156d9c09965a60826bb877dd2fc2
3,634,751
import json def get_encoded_access_granter(): """Add REMS metadata as base64 encoded json. Uses data from user session.""" saml = session["samlUserdata"] metadata_provider_user = saml[SAML_ATTRIBUTES["CSC_username"]][0] email = saml[SAML_ATTRIBUTES["email"]][0] name = "{} {}".format( saml[...
29d83c01708195a058c5689541acac7a33ea3405
3,634,752
from typing import Dict def output(prim_data: Dict) -> Dict: """ Sort the dictionary so that key (score) in descending order, value (time) in ascending order Args: prim_data: The original data where key reps score, value reps time Returns: a "sorted" dictionary that has score in descendi...
ca8aed8905fb6cd4a57e180a6d4a06d8fbb8506e
3,634,753
def _create_dummy_graph(triples_count): """This creates test data of a given size.""" test_graph_input = rdflib.Graph() for triples_index in range(triples_count): test_graph_input.add(( rdflib.term.URIRef("subject:%d" % triples_index), rdflib.term.URIRef("predicate:%d" % trip...
8f99be0a68c0c0bf96e1412e1f4c6cf282b0fcef
3,634,754
from ansible.constants import MAGIC_VARIABLE_MAPPING def _get_magic_var(hostobj, varname, default=""): """Use Ansible coordination of inventory format versions :param hostobj: parsed Ansible host object :param varname: key of MAGIC_VARIABLE_MAPPING, representing variations of Ansible ...
0636a7cec6c879ea8b3df7ebf6ffd7265687bd49
3,634,755
from typing import Counter import math def sentence_bleu(hypothesis, reference, smoothing=True, order=4, **kwargs): """ Compute sentence-level BLEU score between a translation hypothesis and a reference. :param hypothesis: list of tokens or token ids :param reference: list of tokens or token ids ...
e3913cebdfe58ca55aa9c02d9faab4d8fc9ef3dd
3,634,756
import copy def generate_representation(coordinates, nuclear_charges, max_size=23, neighbors=23, cut_distance = 5.0, cell=None): """ Generates a representation for the FCHL kernel module. :param coordinates: Input coordinates. :type coordinates: numpy array :param nuclear_charges: List of nuc...
271ca6d7a66289a44e63452e64dca6a6b0e8da04
3,634,758
def standardize_selected_features(X_df, gene_features): """Standardize (take z-scores of) selected real-valued features. Note this should be done for train and test sets independently. Also note this doesn't necessarily preserve the order of features (this shouldn't matter in most cases). """ X...
2a88901534129e957d5d92158f812951ec2f4e19
3,634,759
def crop_and_align_one(image: Image.Image, polygon: np.array): """ Crop and warp image so that it only contains the word selected by the bounding polygon, horizontally aligned :param image: :param polygon: :return: """ polygon = np.array(polygon).astype(np.float32) rect = cv2.minAreaRec...
7fdde53a11b0fd28d9b92ce50a569de3e51a12f8
3,634,760
def get_ldap(): """connects to ldap and returns ldap connection""" # if not hasattr(g, 'ldap'): # g.ldap = ldap.initialize(app.config['LDAP_URL']) # return g.ldap return None
c2cebe614b269d8e68a320c3f6951ca5b5cf26d0
3,634,762
def _sqrt_l2_prox(ww, reg): """The proximal operator for reg * ||ww||_2 (not squared).""" backend = get_backend() norm_ww = backend.norm(ww, axis=0) mask = norm_ww == 0 ww[:, mask] = 0 ww[:, ~mask] = backend.clip(1 - reg[~mask] / norm_ww[~mask], 0, None)[None] *...
2888149411b016fd2995e0d972ec2174ed85c75b
3,634,763
def modify_content(request, page_id, content_type, language_id): """Modify the content of a page.""" page = get_object_or_404(Page, pk=page_id) perm = PagePermission(request.user).check('change', page=page, lang=language_id, method='POST') if perm and request.method == 'POST': conten...
024a98c20a1260eddf5714e702d4bb9054b8f182
3,634,764
def _extend_data_with_sampled_characteristics(df, optim_paras, options): """Sample initial observations from initial conditions. The function iterates over all state space dimensions and replaces NaNs with values sampled from initial conditions. In the case of an n-step-ahead simulation with sampling a...
a8849d345b57c1207c9ab56a157ea9b061835918
3,634,765
def needs_update(targ_capacity, curr_capacity, num_up_to_date): """Return whether there are more batch updates to do. Inputs are the target size for the group, the current size of the group, and the number of members that already have the latest definition. """ return not (num_up_to_date >= curr_ca...
77981f3fdb57296503f34b0ea955b68b9f98db4c
3,634,766
def build_get_array_item_empty_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Get an array of array of strings [['1', '2', '3'], [], ['7', '8', '9']]. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return...
7ff34d977f9cd50ee8ed29df90952f757f2c4796
3,634,767
def get_single_image_results(gt_boxes, pred_boxes, iou_thr): """Calculates number of true_pos, false_pos, false_neg from single batch of boxes. Args: gt_boxes (list of list of floats): list of locations of ground truth objects as [xmin, ymin, xmax, ymax] pred_boxes (dict): dict of di...
9990dcf989b1b76bc6cb7a4bbbedad5bb73fc132
3,634,768
def generate_test_experiments(n=2): """Make a test experiment list""" experiments = ExperimentList() exp_dict = { "__id__": "crystal", "real_space_a": [1.0, 0.0, 0.0], "real_space_b": [0.0, 1.0, 0.0], "real_space_c": [0.0, 0.0, 2.0], "space_group_hall_symbol": " C 2y"...
19644c834127e24f15e46657e1e131444861f2fc
3,634,769
def MakeProjectIssueConfig( project_id, well_known_statuses, statuses_offer_merge, well_known_labels, excl_label_prefixes, templates, col_spec): """Return a ProjectIssueConfig with the given values.""" # pylint: disable=multiple-statements if not well_known_statuses: well_known_statuses = [] if not stat...
4be0d3b01e7a7ba958ef6fa489559a237a535d77
3,634,770
import json import requests def moderate(request): """ View for moderation actions on a single item. """ microcosm_id = request.POST.get('microcosm_id') if request.method == 'POST': if request.POST.get('action') == 'move': if request.POST.get('item_type') == 'event': ...
151a3fe08653835ccb6fe3e54d729b73675c84ac
3,634,771
def private_invite_code(invite_code_key, invite_code): """ ๅ†…ๆต‹้‚€่ฏท็ ๆ ก้ชŒ :param invite_code_key: :param invite_code: :return: """ error_dict = 0 if not invite_code: error_dict = {'captcha_not_blank': ['ๅ†…ๆต‹้‚€่ฏท็ ไธ่ƒฝไธบ็ฉบ']} else: # if settings.ENABLE_VERIFY_CAPTCHA: # s...
1403c849670adc21501775003283d3dfd0c32019
3,634,773
def summary(state, figsize=(11, 7), hemisphere="both", center_lon=180, pv_cmap="viridis", pv_max=None, v_max=None): """4-panel plot showing the model state in terms of vorticity and wind.""" grid = state.grid roll, configure_lon_x = roll_lons(grid.lons, center_lon) # Scale PV to 10e-4 1/s pv...
789bd3942d8c7bad671d22e29882f12825b9da73
3,634,776
def features_to_matrix(features): """ features_to_matrix(features) This function takes a list of feature matrices as argument and returns a single concatenated feature matrix and the respective class labels. ARGUMENTS: - features: a list of feature matrices RETURNS: - f...
8f3ef18105aa2f6a427ac89582fb17a7e508990d
3,634,778
def union_all(*selects, **kwargs): """Return a ``UNION ALL`` of multiple selectables. The returned object is an instance of :class:`.CompoundSelect`. A similar :func:`union_all()` method is available on all :class:`.FromClause` subclasses. \*selects a list of :class:`.Select` instances....
f211193d7b0ee2b3de22e0d3ae086cc443209ece
3,634,779
from autode.species import Species from autode.calculation import Calculation from autode.exceptions import CouldNotGetProperty def run_autode(configuration, max_force=None, method=None, n_cores=1): """ Run an orca or xtb calculation -----------------------------------------------------------------------...
32d36a5e271c17922b0898f414ecfabf04a63d5a
3,634,780
def set_count_and_flavor_params(role, baremetal_client, compute_client): """Returns the parameters for role count and flavor. The parameter names are derived from the role name: <camel case role name, no hyphens>Count Overcloud<camel case role name, no hyphens>Flavor Exceptions from this ...
f635ae2cae259a3dc1da5734ffe1a062f5f5781c
3,634,781
from pathlib import Path def is_dir_exist(path): """Whether the directory exists""" path_info = Path(path) return path_info.is_dir()
8182e96399d2271bc8e3cd5c1a4201f3e2acd895
3,634,784
def m1m2count(data): """ Reads the counts of epitopes for -1 and -2 mutations by HLA in a dataset. """ hlas = list(data["HLA"].sort_values().unique()) mutations = list(data["ID"].sort_values().unique()) m_1 = [mut for mut in mutations if mut.endswith("_m1")] m_2 = [mut for mut in mutations if mut.endswith...
0e2b7d63e6ab2cb45d56ae3d3cc545b0b27d3349
3,634,785
def compute_permutation_sample(perm_num, all_conditions_power, trial_indices, permutation_indices, times, freqs, chs, config, comp, exp): """ Helper function to compute the permuted toi band power difference for a particular permutation of trials bet...
626a27f6cada79fa8a89223a4a3b64b9a0972e71
3,634,788
def get_users(): """ The endpoint is for now publicly available. Returns: JSON of all users """ users = User.query # no need to order users_data = [user.to_dict() for user in users.all()] return jsonify(users=users_data)
4231cf43f26d59501f386f5a5f661497ef488448
3,634,789
def _lower_neighbours(G, u): """Given a graph `G` and a vertex `u` in `G`, we return a list with the vertices in `G` that are lower than `u` and are connected to `u` by an edge in `G`. Parameters ---------- G : :obj:`Numpy Array(no. of edges, 2)` Matrix storing the edges of the graph. ...
c51b681a7c0361cd1768791dce4d7d63fb54ab44
3,634,790
def find_f_include_statement(line): """ Determine whether line contains a Fortran INCLUDE statement. If so, return the file name being INCLUDE'd. line is a line of code from the Fortran file being processed. If the INCLUDE'd file is in the exclude_finc_files set, then simply return None. We ...
cb381953f64ee03e4a42d20750562afecf3c1785
3,634,791
def get_phase_from_ephemeris_file(mjdstart, mjdstop, parfile, ntimes=1000, ephem="DE405", return_pint_model=False): """Get a correction for orbital motion from pulsar parameter file. Parameters ---------- mjdstart, mjdstop : float ...
29504e37159ce53dcbb52f868974601e07cec3e0
3,634,792
def create_hash(ls): """this function takes in the treecolor matrix and returns a tuple of the hash code and the hash vector that uniquely identifies a particular combination of colors""" index_vector = [x for x in range(20)] # creates a vector of the indexes hash_vector = matrixvector_multiply(modify_treecolorm...
0d46624a4e14e18696469f6b637d403714170a01
3,634,793
from typing import List from typing import Union def create_pruning_param_scorer( params: List[Parameter], score_type: Union[str, MFACOptions], ) -> PruningParamsScorer: """ :param params: List of Parameters for the created PruningParamsScorer to track :param score_type: String name of scoring typ...
db46dc4420575995c23565f31d0d28aba4d6d8a1
3,634,796
from datetime import datetime def calculate_new_age(table): """Calculates new age and adds it to the dataframe""" date_now = datetime.now() def get_age(birthday): if birthday: return relativedelta(date_now, birthday).years table['age'] = table.apply(lambda birthday: get_age) re...
d6b5fe19559022a175540eebc8f90c2f9371ab7e
3,634,797
def get_wl(full_dir): """ Get the NIR wavelength used for this Video session. :param full_dir: directory containing SVM/SVR files :return: a string containing the wavelength """ return channels[str(get_channel(full_dir))]
17bd7c312c3f91e8262e39f57052d1e987e8edaa
3,634,798
def calculate_v(nfs): """Calculates V(n+1/n) values. Useful for establishing the quality of your normalization regime. See Vandesompele 2002 for advice on interpretation. :param DataFrame nfs: A matrix of all normalization factors, produced by `calculate_all_nfs`. :return: a Series of values...
3fedc410ac21b01352985e518484b21afb45d71f
3,634,799
def export_ruptures_csv(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] if 'scenario' in oq.calculation_mode: return [] dest = dstore.export_path('ruptures.csv') header = ('rupid multiplicity ...
b23f6b9fea092822d9700017bf92aab322577da6
3,634,800
def get_google_auth(state=None, token=None): """Helper function to create OAuth2Session object.""" if token: return requests_oauthlib.OAuth2Session(Auth.CLIENT_ID, token=token) if state: return requests_oauthlib.OAuth2Session(Auth.CLIENT_ID, state=state, ...
70f60828f6ad7c6a7658a217f98a22cfd07067ae
3,634,802
def _normalize_dataframe(dataframe, index): """Take a pandas DataFrame and count the element present in the given columns, return a hierarchical index on those columns """ #groupby the given keys, extract the same columns and count the element # then collapse them with a mean data = dataframe[in...
fdc49912f538694048560f1c1453714791a7c6e4
3,634,803
def get_indicator_plugin_manager(): """ Import all Hook classes that are in the plugins package and make this availables for be called from master sources """ pm = pluggy.PluginManager("indicator") pm.add_hookspecs(IndicatorSpec) for class_imported in indicatorPluginClasses: # noqa: F405 ...
610d21bab6f58a0b43539b5b382233b71937e764
3,634,805
def run(command, **kwargs): """Run and return the output of a command. Raise CalledProcessError on error. Pass in any kind of shell-executable line you like, with one or more commands, pipes, etc. Any kwargs will be shell-escaped and then subbed into the command using ``format()``:: >>> r...
5022e5cb1fe4863e1bd2293385eb8f13fe763e58
3,634,806
from datetime import datetime def to_date(string, format="%d/%m/%Y"): """Converts a string to datetime :param string: String containing the date. :type string: str :param format: The date format. Use %Y for year, %m for months and %d for daus, defaults to "%d/%m/%Y" :type format: str, optional ...
83fa8e8a0cdfae9546c7a83e55ddcf84ec667646
3,634,807
def invert_apply_grouping2(grouped_items, groupxs, dtype=None): """use only when ungrouping will be complete""" maxval = _max(list(map(_max, groupxs))) ungrouped_items = np.zeros((maxval + 1,), dtype=dtype) for itemgroup, ix_list in zip(grouped_items, groupxs): ungrouped_items[ix_list] = itemgro...
c1e7d46ddf57bc7bf1f7123fbd18061b63fb8a8d
3,634,808
def make_aware_assuming_local(dt): """ Just a wrapper for Django's method, which will takes a naive datetime, and makes it timezone aware, assuming the current timezone if none is passed (which it isn't from this wrapper function). It will also raise an exception if the passed datetime is already timezo...
3b9f142f11bc918a7faebcb0309f43dc6e9a5d2b
3,634,809
def pad_word_array(word_array, MAX_SEQUENCE_LENGTH, padding='pre', truncating='pre'): """Return a word array that is of a length MAX_SEQUENCE_LENGTH by truncating the original array or padding it Args: word_array: MAX_SEQUENCE_LENGTH: padding: truncating: Returns: """ ...
33d33284eb347f9f4b242932c42b7b8b68219135
3,634,810
def nbconvert(code): """Create Jupyter Notebook code Return dict in ipynb format Arguments: code -- code string separated by \\n """ cells = [] for cell in code.split("\n# <codecell>\n"): cells.append({ "cell_type": "code", "execution_count": None, ...
f7e895e107f07850652e762a4b382ec299e6d352
3,634,811
def add_box(width, height, depth): """ This function takes inputs and returns vertex and face arrays. no actual mesh data creation is done here. """ verts = [ (+1.0, +1.0, 0.0), (+1.0, -1.0, 0.0), (-1.0, -1.0, 0.0), (-1.0, +1.0, 0.0), (+1.0, +1.0, +2.0), ...
930dedbba8a1c11999d4ffdb98b0032bae743498
3,634,812
import time def pixmap(randoms, targets, rand_density, nside=256, gaialoc=None): """HEALPix map of useful quantities for a Legacy Surveys Data Release Parameters ---------- randoms : :class:`~numpy.ndarray` or `str` Catalog or file of randoms as made by :func:`select_randoms()` or :fu...
cda21bb679c84d1842ca1de675db0daf3ed79534
3,634,813
from typing import Union from typing import Callable from typing import Sequence from typing import Tuple def filter_keys(data: dict, keys: Union[Callable, Sequence], return_popped=False) -> Union[dict, Tuple[dict, dict]]: """ Filters keys from a given data dict Args: data: the di...
ecfd6985242d802401c25046745afade16ceec24
3,634,814
def beta_ion(T_rad, species): """Case-B photoionization coefficient. Parameters ---------- T_rad : float The radiation temperature. species : {'HI', 'HeI_21s', 'HeI_23s'} The relevant species. Returns ------- float Case-B photoionization coefficient in s\ :sup:`...
d82b37fcfd4852722260a7b4f6c92e58e8588b11
3,634,815
from pathlib import Path def load_template(template_path, template_name): """Loads a Jinja template from a given path and name Arguments: template_file {PathToDir: Path/String} template_name {Filename: String} Raises: IOError: This path does not exist """ if isinstance(te...
8e935d2f0ab41174237d4b7c803d5e16687d3bd0
3,634,816
def html(string): """Return inline html element.""" return RawInline('html', string)
980b409f769a38102398c81006dfd220b8865715
3,634,817
def mock_user_moira_lists(mocker): """Return a fake moira client""" mocked = mocker.patch("ui.utils.user_moira_lists") mocked.return_value = set() return mocked
8dedab7071deae4f1e5fa3ffc7b79149fc49e795
3,634,818
def translateAllIndex(text): """ This is the translator API Call this api passing a piece of text and get back the Swedish translation --- tags: - Translation API parameters: - name: text in: path type: string required: true description: The text r...
e7740738d112c64a6dfa30be7825e4db9b89f6f0
3,634,819
def AIHT(x, A, AT, m, M, thresh, proximalProjection=None): """ Accelerated Iterative Hard thresholding algorithm that keeps exactly M elements in each iteration. This algorithm includes an additional double overrelaxation step that significantly improves convergence speed without destroying any of the theoretical...
a4eed242acddf61059d3a77367a89d6966b16c63
3,634,822
def permutate(array: list, permutation: list): """ permutate a fixed array with a given permutation list Args: array: An array of random elements permutation: The permutation of the given array Returns: """ _swapped_array = [] _counter = 0 for i in permutation: ...
5b4f603c030276dcd78b6334ec00c901ca003c63
3,634,823
def has_collided_with_wall( width: int, height: int, segments: list[SnakeSegment] ) -> bool: """Return True if the snake has collided with a wall.""" head = segments[0] return ( head.x <= 1 or head.x > width - 3 or head.y < 1 or head.y >= height - 2 )
54f96b2a28f56e440f647316fe9e9e0dac356c34
3,634,824
def plot_heatmap_max_val(env, value): """ Generate heatmap showing maximum value at each state (not for n-armed bandit). """ if env.name == 'n_armed_bandit': print("Heatmap can only be generated for grid worlds.") return None if value.ndim == 1: value_max = np.reshape(v...
b39c43aa87bbae78b519e5f1042a63359a0c9f48
3,634,825
def separate_lines(lines,imshape): """ separate_lines(lines) Classifies left and right lines based on slope --------------------------------------------------------------------------- INPUT: lines: line points [[x1,y1,x2,y2]] OUTPUT: right{}: right line dictionary with the follo...
3d7ee319456202cc7478a97afc78922761a9e86e
3,634,826
def p_climo_one_season( seasonname, datafilenames, omit_files, varnames, fileout_template, time_units, calendar, dt, force_scalar_avg1, input_global_attributes, filerank={}, filetag={}, outseasons=None, queue1=None, lock1=None, comm1=None ): """cli...
dfd41e9cce28fbca51a4a838df831aa95c62b3af
3,634,827
def two_view_reconstruction_rotation_only(p1, p2, camera1, camera2, threshold): """Find rotation between two views from point correspondences. Args: p1, p2: lists points in the images camera1, camera2: Camera models threshold: reprojection error threshold Returns: rotation ...
25bc0038970eae23cf8443f4de1a7f89e5ff4f34
3,634,828