content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_empath_scores(text): """ Obtains empath analysis on the text. Takes the dictionary mapping categories to scores, which is produced by passing the text to empath, and returns the scores. Args: text: string containing text to perform empath analysis on Returns: A list of empa...
f68a55a2dc4ba98696e9df3f88aaacf73d81ff2d
3,369
import json import logging def sqlite_insert(engine, table_name, data): """ Inserts data into a table - either one row or in bulk. Create the table if not exists. Parameters ---------- engine: sqlalchemy engine for sqlite uri: string data: dict Returns ------- bool "...
430e3109d233119043bc6c5f10ba966aa08992c1
3,371
def _fit_solver(solver): """ Call ``fit`` on the solver. Needed for multiprocessing. """ return solver.fit()
7007752777445d2cc6d476d7af1f83d6cdfe236b
3,372
import types def flatten(l): """ recursively turns any nested list into a regular list (using a DFS) """ res = [] for x in l: if (isinstance(x, types.ListType)): res += flatten(x) else: res.append(x) return res
5947566b7dfd1d03204c2a39f1e853ce812e18fe
3,373
def build_column_hierarchy(param_list, level_names, ts_columns, hide_levels=[]): """For each parameter in `param_list`, create a new column level with parameter values. Combine this level with columns `ts_columns` using Cartesian product.""" checks.assert_same_shape(param_list, level_names, axis=0) pa...
f19d4f93a0cfbc6ebe700285c8761c78ca5f9b1a
3,374
def gradient_descent(f, xk, delta = 0.01, plot=False, F = None, axlim = 10): """ f: multivariable function with 1 array as parameter xk : a vector to start descent delta : precision of search plot : option to plot the results or not F : the function f expressed with 2 arrays in argument (X,Y) re...
99b8da92c6df296c2d02b2f0d14f38b94ea87aef
3,375
def _get_cells(obj): """Extract cells and cell_data from a vtkDataSet and sort it by types.""" cells, cell_data = {}, {} data = _get_data(obj.GetCellData()) arr = vtk2np(obj.GetCells().GetData()) loc = vtk2np(obj.GetCellLocationsArray()) types = vtk2np(obj.GetCellTypesArray()) for typ in VT...
84f603d92e1548b6d9ebe33b31ac4277bed49281
3,376
def check_X(X, enforce_univariate=False, enforce_min_instances=1): """Validate input data. Parameters ---------- X : pd.DataFrame enforce_univariate : bool, optional (default=False) Enforce that X is univariate. enforce_min_instances : int, optional (default=1) Enforce minimum n...
2022cbccfaec72cc68e2d9692d96fb3241d9991a
3,377
def parse_amount(value: int) -> Decimal: """Return a scaled down amount.""" return Decimal(value) / Decimal(AMOUNT_SCALE_FACTOR)
66e7668ed5da3d451644de00dc98bfb2bf8745f0
3,378
def svn_ra_do_update2(*args): """ svn_ra_do_update2(svn_ra_session_t session, svn_ra_reporter3_t reporter, void report_baton, svn_revnum_t revision_to_update_to, char update_target, svn_depth_t depth, svn_boolean_t send_copyfrom_args, svn_delta_editor_t update_editor, void upda...
139fd5b8ea5b86ad70f056d5b53a86cc01ce3952
3,379
from ._sentiwords import tag def sentiwords_tag(doc, output="bag"): """Tag doc with SentiWords polarity priors. Performs left-to-right, longest-match annotation of token spans with polarities from SentiWords. Uses no part-of-speech information; when a span has multiple possible taggings in Senti...
c4769e82d9b9aff55f7d6e3de08188f5ba6501bb
3,381
def _GetCommandTaskIds(command): """Get a command's task ids.""" # A task count is the number of tasks we put in the command queue for this # command. We cap this number to avoid a single command with large run count # dominating an entire cluster. If a task count is smaller than a run count, # completed task...
98d6ac89e4f5569968740475eba924840170464f
3,382
import uuid import json def save_orchestrator_response(url, jsonresponse, dryrun): """Given a URL and JSON response create/update the corresponding mockfile.""" endpoint = url.split("/api/")[1].rstrip("/") try: path, identifier = endpoint.rsplit("/", maxsplit=1) except ValueError: path...
aab7d3e925d7b4d695832ba7aa45bd93b3824fb1
3,383
import math def compute_bleu(reference_corpus, translation_corpus, max_order=4, use_bp=True): """Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of references for each translation. Each reference should be tokenized into a list ...
e0978e3b05513c32ac55f72b298e8752eb887fb1
3,385
def flip(inputDirection: direction) -> direction: """ Chooses what part of the general pointer to flip, by DP%2 == CC rule, providing the following flow: (0,0) -> (0,1) (0,1) -> (1,1) (1,1) -> (1,0) (1,0) -> (2,0) (2,0) -> (2,1) (2,1) -> (3,1) (3,1) -> (3,0) (3,0) -> (0,0) :p...
44797849c14736de7380c5169e29bc9095f11a45
3,386
def save(request): """Update the column levels in campaign_tree table with the user's input from the data warehouse frontend.""" if any(request["changes"]): query = 'UPDATE campaign_tree SET ' query += ', '.join([f"""levels[{index + 1}] = trim(regexp_replace(%s, '\s+', ' ', 'g'))""" ...
7cc75024db3de8596bc685439d02a1023bfbae25
3,387
def _print_model(server, user_key, device_type_model): """ Print the model for a given device type :param device_type_model: Device type ID to print the model for """ name = None model = [] parameters = _get_parameters(server, user_key) parameters = parameters['deviceParams'] try: ...
b901cb21d39ac0fce1d8a60c3926d8b274ce5189
3,388
def parse_ipv6_addresses(text): """.""" addresses = ioc_grammars.ipv6_address.searchString(text) return _listify(addresses)
6177bc5fcb3b6613e945a7c63931d88a12d372cd
3,390
def as_jenks_caspall_sampled(*args, **kwargs): """ Generate Jenks-Caspall Sampled classes from the provided queryset. If the queryset is empty, no class breaks are returned. For more information on the Jenks Caspall Sampled classifier, please visit: U{http://pysal.geodacenter.org/1.2/library/esda/m...
7a271d3c48b6d813cacc9502f214d2045d8accfe
3,391
def positive_dice_parse(dice: str) -> str: """ :param dice: Formatted string, where each line is blank or matches t: [(t, )*t] t = (0|T|2A|SA|2S|S|A) (note: T stands for Triumph here) :return: Formatted string matching above, except tokens are ...
5b266a4025706bfc8f4deabe67735a32f4b0785d
3,392
def fmt_title(text): """Article title formatter. Except functional words, first letter uppercase. Example: "Google Killing Annoying Browsing Feature" **中文文档** 文章标题的格式, 除了虚词, 每个英文单词的第一个字母大写。 """ text = text.strip() if len(text) == 0: # if empty string, return it return text ...
44474f8f92888904a56f63bdcf1031f2d7c472e1
3,393
def insn_add_off_drefs(*args): """ insn_add_off_drefs(insn, x, type, outf) -> ea_t """ return _ida_ua.insn_add_off_drefs(*args)
684af1cea2deafffc33b007f064a67fb89ffd54f
3,394
def lambda_handler(event, context): """Lambda function that responds to changes in labeling job status, updating the corresponding dynamo db tables and publishing to sns after a job is cancelled. Parameters ---------- event: dict, required API gateway request with an input SQS arn, output SQS arn ...
3640bded7316a573d0740084e8006a876bb7300c
3,395
from typing import Union def get_answer(question: Union[dns.message.Message, bytes], server: Union[IPv4Address, IPv6Address], port: int = 53, tcp: bool = False, timeout: int = pydnstest.mock_client.SOCKET_OPERATION_TIMEOUT) -> dns.message.Message: """Get...
95493396393ce09e4610fb32c063d0d9676b14ea
3,396
def intersectionPoint(line1, line2): """ Determining intersection point b/w two lines of the form r = xcos(R) + ysin(R) """ y = (line2[0][0]*np.cos(line1[0][1]) - line1[0][0]*np.cos(line2[0][1]))/(np.sin(line2[0][1])*np.cos(line1[0][1]) - np.sin(line1[0][1])*np.cos(line2[0][1])) x = (line1[0][0] - ...
f23ec1960de85b72724388747ec8157925eefae1
3,397
def _remove_keywords(d): """ copy the dict, filter_keywords Parameters ---------- d : dict """ return { k:v for k, v in iteritems(d) if k not in RESERVED }
0eb7ed59898c3ec323574d0068af745250aef63b
3,398
def build_trib_exp(trib_identifier, trib_key_field): """Establishes a SQL query expresion associating a given tributary id""" return '"{0}"'.format(trib_key_field) + " LIKE '%{0}%'".format(trib_identifier)
792d5e4237268410f050323ff1748246a5cdee5d
3,399
import torch def train_epoch(loader, vae, optimizer, device, epoch_idx, log_interval, loss_weights, stats_logger, clip_gradients=None): """Train VAE for an epoch""" vae.train() train_losses = {} train_total_loss = 0 for batch_idx, data in enumerate(loader): data = data.to(...
e846987844933359a67f7b6581a8429ef88bfb0b
3,400
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost def phased_multi_axes(times, data, std, ephemeris, thin=1, colours='midnightblue', ylim_shrink=0.8, subplot_kw=None, gridspec_kw=None, **kws): """ Parameters ---------- times data std ...
32d2da62acde2a2424c310e1bd0196dbac9309cf
3,401
def get_delta(K): """This function returns the delta matrix needed calculting Pj = delta*S + (1-delta)*(1-S) Args: inputs: K: Integers below 2^K will be considered outputs: delta: Matrix containing binary codes of numbers (1, 2^K) each one arranged ro...
84e72790024c7294e715dd5efc03f001a7ab887d
3,402
def string_split_readable(inp, length): """ Convenience function to chunk a string into parts of a certain length, whilst being wary of spaces. This means that chunks will only be split on spaces, which means some chunks will be shorter, but it also means that the resulting list will only conta...
1f1d3641cc293754c174d32d397dab252c009eca
3,403
import torch def get_similarity_transform_matrix( from_pts: torch.Tensor, to_pts: torch.Tensor) -> torch.Tensor: """ Args: from_pts, to_pts: b x n x 2 Returns: torch.Tensor: b x 3 x 3 """ mfrom = from_pts.mean(dim=1, keepdim=True) # b x 1 x 2 mto = to_pts.mean(dim=1, ...
76524a1f85644cfedfda9dd60497768614a058b0
3,404
def get_current_daily_puzzle(**kwargs) -> ChessDotComResponse: """ :returns: ``ChessDotComResponse`` object containing information about the daily puzzle found in www.chess.com. """ return Resource( uri = "/puzzle", top_level_attr = "puzzle", **kwargs )
733ce2eaa45b773cdfc04395ceb4dbe101ae8b78
3,405
def stroke_negative(): """ render template if user is predicted negative for stroke """ return render_template("negative.html")
2f1a07b57b19143e6755f3067c4923bb7231fb89
3,406
import sirepo.sim_data def default_data(sim_type): """New simulation base data Args: sim_type (str): simulation type Returns: dict: simulation data """ return open_json_file( sim_type, path=sirepo.sim_data.get_class(sim_type).resource_path(f'default-data{sirepo.c...
47791f63a6b6c636d8e0a5513e47ab10bd2db209
3,407
def get_instance_name_to_id_map(instance_info): """ generate instance_name to instance_id map. Every instance without a name will be given a key 'unknownx', where x is an incrementing number of instances without a key. """ instance_name_to_id = {} unknown_instance_count = 0 for instance_id ...
293923476a19362fbbc2b3bb0b34bc35523bdfa1
3,408
def log_get_stdio_record(log): """ Returns a darshan log record for STDIO. Args: log: handle returned by darshan.open Returns: dict: log record """ return log_get_generic_record(log, "STDIO", "struct darshan_stdio_file **")
6438d1ca88357cb3928492ddb89c4beab643f9fb
3,409
def generate_spiral2d(nspiral=1000, ntotal=500, nsample=100, start=0., stop=1, # approximately equal to 6pi noise_std=.1, a=0., b=1., savefig=T...
4d5129f651fd3a817c9be3beb9c2358895dd3654
3,411
import math def AUC_confidence(auc_value, num, interval=0.95): """ Calculate upper and lower 95% CI for area under the roc curve Inspired by https://stats.stackexchange.com/questions/18887 :param r: spearman's rho :param num: number of data points :param interval: confidence interval (0-1.0) ...
5beab0e62171d49dcfb0fbd126243e4906787273
3,412
def add_data(data): """ This adds data """ item = data db.insert(data) return 'chain updated'
52efd328097c95768de7f049335dbad9761e5715
3,413
from typing import Counter def build_node_to_name_map(head): """ :type head: DecisionGraphNode :return: """ node_to_name_map = {} name_to_next_idx_map = Counter() def add_node_name(node): assert node not in node_to_name_map node_type_name = node.get_node_type_name() ...
9d4b21317030c30539a5ec5947e574e3bd4fdd60
3,415
def ReduceFloat(f, op=None): """Reduce a single float value over MPI""" if not hasMPI: raise Exception("mpi4py required for Reduce operations: not found") if op is None: op = MPI.SUM fa = np.array([f]) # can only reduce over numpy arrays MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE, ...
12ca088e19a20eed145e1a90d8d88941f5d249ac
3,416
def GetVerificationStepsKeyName(name): """Returns a str used to uniquely identify a verification steps.""" return 'VerificationSteps_' + name
e50e9bd7b586d8bbfaf8902ce343d35d752948a4
3,417
def annotate_ms1_peaks(ms1_data, ms2_data, analyte_list): """Interpolate MS1 intensities for the time points for the MS2 scans for the largest mass peak in each analyte. Use relative changes in intensity between interpolated MS1 data and real MS2 data to find MS2 peaks that go with each analyte. """ ms2...
32e0712ed27d802d99290cf01ba1f5f0dc07bae2
3,418
def split_tblastn_hits_into_separate_genes(query_res_obj, max_gap): """Take a SearchIO QueryResult object and return a new object with hits split into groups of HSPs that represent distinct genes. This is important, because there may be multiple paralogous genes present in a single nucleotide subject se...
f33bc8ed36343cb4e0c00c186546d6f979885c92
3,419
def to_entity_values(entity_group): """ Parse current entity group content into a CreateEntity[] """ values = [] for _, row in entity_group.iterrows(): value = row[ENTITY_VALUE_COLUMN] if not value: # Handle reserved entities continue synonyms = [] patterns ...
278f9d5a7c8294338d83ba025c67fe23f36a8ac2
3,420
import codecs import logging def read_file(file_path): """ Read the contents of a file using utf-8 encoding, or return an empty string if it does not exist :param file_path: str: path to the file to read :return: str: contents of file """ try: with codecs.open(file_path, 'r', encod...
13a72bc939021e3046243ed9afc7014cb403652a
3,421
def scrub(data): """ Reads a CSV file and organizes it neatly into a DataFrame. Arguments: data {.csv} -- the csv file to be read and scrubbed Returns: DataFrame -- the logarithmic returns of selected ticker symbols """ df = pd.read_csv(data, header=0, index_col=0, parse_dates=...
cce082da1d1f4c4308b4f30df918750f91de3f3f
3,422
def _get_lto_level(): """ Returns the user-specific LTO parallelism level. """ default = 32 if config.get_lto_type() else 0 return read_int("cxx", "lto", default)
1d0279d363aaa02dcf820f3a064e9b2023ae36a4
3,424
from typing import List from typing import Any def slice_label_rows(labeldf: pd.DataFrame, label: str, sample_list: List[str], row_mask: NDArray[Any]) -> NDArray[Any]: """ Selects rows from the Pandas DataFrame of labels corresponding to the samples in a particular sample_block. Args...
859bac2e577b534592a3428cd163f123608c9d72
3,425
def rollback(var_list, ckpt_folder, ckpt_file=None): """ This function provides a shortcut for reloading a model and calculating a list of variables :param var_list: :param ckpt_folder: :param ckpt_file: in case an older ckpt file is needed, provide it here, e.g. 'cifar.ckpt-6284' :return: """ ...
e434ba292b842ee29ca5e61e33b24089a34b52a8
3,426
import numpy def read_interaction_file_mat(file): """ Renvoie la matrice d'adjacence associée au graph d'intéraction entre protéines ainsi que la liste ordonnée des sommets :param file: tableau contenant un graphe :type file: dataframe :return: une matrice d'adjascence de ce graphe et une list...
de62b45810ada6a69b779f42c39b589092d95428
3,427
def load_figures(fig_names): """ Uses a list of the figure names to load them into a list @param fig_names: @type fig_names: @return: A list containing all the figures @rtype: list """ fig_list = [] for i, name in enumerate(fig_names): fig_list.append(pl.load(open(f"{name}.pi...
6e90a2c9c7fbbbb89d793b8e0c8e7b521f797f64
3,428
def define_mimonet_layers(input_shape, classes, regularized=False): """ Use the functional API to define the model https://keras.io/getting-started/functional-api-guide/ params: input_shape (h,w,channels) """ layers = { 'inputs' : None, 'down_path' : {}, 'bottle_...
e3151f29590cbd523063e13fffc29290a19d071a
3,429
def _list_subclasses(cls): """ Recursively lists all subclasses of `cls`. """ subclasses = cls.__subclasses__() for subclass in cls.__subclasses__(): subclasses += _list_subclasses(subclass) return subclasses
4cebf48916c64f32fcd5dfff28ecde7a155edb90
3,431
import logging def main(from_json: bool = True, filename: str = DEFAULT_ARGS['pipeline_config_save_path']): """ Calls the specified pipeline. :param filename: json filename :param from_json: whether to run pipeline from json file or not :return: pipeline call function """ # Parsing argum...
ccd975889d639f3a642e820e4d7ce5e2ef583609
3,432
def put(url, **kwargs): """PUT to a URL.""" return session.put(url, **kwargs)
64618fc239164a73fa90f2348de8402c5a593394
3,433
def cod_records(mocker, cod_records_json): """Fixture for COD records metric instance.""" mocker.patch.object(RecordsMetric, 'collect', new=records_collect(cod_records_json)) return metrics.records('cod_records', 'http://www.google.com')
d4ac73421f3fcef9b175aa42c02354ff437581ad
3,434
def get_lite_addons(): """Load the lite addons file as a set.""" return set_from_file('validations/lite-addons.txt')
68f26084b5e7e13492f61fc65fe504d1b5d53384
3,436
def GetApexPlayerStatus_TRN(api_key, platform, playerName): """ Get the status of a player on Apex Legends. :param api_key: The API key to use. :param platform: The platform to use. :param playerName: The player name to use. """ platform = _fixplatform(platform) if _checkplatform(platfo...
296f9900e3e95afa24a0e643ed45563b57fb172a
3,437
def subFactoryGet(fixture, **kwargs): """ To be used in fixture definition (or in the kwargs of the fixture constructor) to reference a other fixture using the :meth:`.BaseFix.get` method. :param fixture: Desired fixture :param kwargs: *Optional:* key words to overwrite properties of this fixture ...
480db102897a3edd682acef6ee95a42b6f937b03
3,438
def hello(): """Return the dashboard homepage.""" return render_template('index.html')
adac182b3c8dd2ae0f17425205203c5493499f19
3,439
from pathlib import Path def test_data_dir(): """ Returns path of test datas like excel Used for test or notebook """ path = Path(__file__).parent.parent / 'testdata' return path
f410f26276797204dd100d884b162f893b5ce4aa
3,441
def is_leap_year(year: int) -> bool: """Returns whether the given year is a leap year""" if year % 100 == 0: return year % 400 == 0 else: return year % 4 == 0
fccaa3de6378e62b937748c671a21aa5427781e8
3,443
def is_valid_distribution(qk: np.ndarray, axis: int) -> bool: """valid is e.g.: [], [1.0], [0.5, 0.5]""" """not valid is e.g.: [-1.0], [0.6, 0.6], [np.nan], [np.nan, 0.6], [1.2]""" assert 0 <= axis < len(qk.shape) if qk.shape[axis] == 0: return True if np.any(qk < 0.0): return False if np.any(qk > 1...
fdbb1ac82f2d5cf93843f3d8d1f4f4d02a3ab408
3,445
def srt(data, cube, **kwargs): """ Define Solar Rotational Tomography model with optional masking of data and map areas. Can also define priors. Parameters ---------- data: InfoArray data cube cube: FitsArray map cube obj_rmin: float Object minimal radius. Ar...
e0af1f5d0d00e8651c3668091165beaf0aaa6f55
3,446
def get(status_id): """Fetches a status of previously submitted PushFunds request. Returns a status of :func:`~pyvdp.visadirect.fundstransfer.MultiPushFundsTransactionsModel` request by transaction identifier, returned with 202 response. :param str status_id: **Required**. Transaction status identifi...
fb8951355f342405e93f44747e670afcaf094322
3,447
def eval_pop_thread(args): """ Evaluates solutions, returns a list of floats, between 0 and 1 (probabilities of survival and reproduction). """ m_solutions, m_state_hash_table, id_mi = args[0], args[1], args[2] step = int(N_POP/N_PROC) prob_surv = np.zeros(step) for index_sol in range(le...
8acdb0acae737a8bf48578ec48c3dcc1b66c7adb
3,449
def _mini_batch_convergence(model, iteration_idx, n_iter, tol, n_samples, centers_squared_diff, batch_inertia, context, verbose=0): """Helper function to encapsulate the early stopping logic""" # Normalize inertia to be able to compare values when # ba...
701488e530913bfc2e5d382a544679315dc1f013
3,450
def rho_MC(delta, rhoeq=4.39e-38): """ returns the characteristic density of an axion minicluster in [solar masses/km^3] forming from an overdensity with overdensity parameter delta. rhoeq is the matter density at matter radiation equality in [solar masses/km^3] """ return 140 * (1 + del...
f28e382cfcf661199728363b3ebe86f25e92760c
3,451
from typing import Dict from typing import Union from typing import List from typing import Optional def _parse_parameter_from_value( string: str, parameter_to_wordlist_mapping: Dict[Union[TimeResolution, PeriodType, Parameter], List[List[str]]] ) -> Optional[Union[TimeResolution, PeriodType, Paramete...
0fa1e2f7edf5e6be31e0e2ae514ecc22a512e8f7
3,452
def render(scene): """ :param scene: Scene description :return: [H, W, 3] image """ # Construct rays from the camera's eye position through the screen coordinates camera = scene['camera'] eye, ray_dir, H, W = generate_rays(camera) # Ray-object intersections scene_objects = scene['ob...
35f8cf34fea266034a76f3857213fcb83e334174
3,454
def state_fidelity(state1, state2): """Return the state fidelity between two quantum states. Either input may be a state vector, or a density matrix. The state fidelity (F) for two density matrices is defined as:: F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2 For a pure state and m...
9df10584ce9376df5690ebaccaa07046778b097c
3,455
def process_state(request): """Procesa una request GET o POST para consultar datos de provincias. En caso de ocurrir un error de parseo, se retorna una respuesta HTTP 400. Args: request (flask.Request): Request GET o POST de flask. Returns: flask.Response: respuesta HTTP """ r...
8e748dd73845438f768ecd34730a94c2e8696387
3,456
def is_ascii(string): """Return True is string contains only is us-ascii encoded characters.""" def is_ascii_char(char): return 0 <= ord(char) <= 127 return all(is_ascii_char(char) for char in string)
cd3aeddcad7610de83af6ec5a67ecbac95f11fd8
3,457
from typing import Union from typing import Tuple from typing import Optional from typing import List def _get_predictions_from_data( model: Union[Model, SKLEARN_MODELS], data: Union[ tf.data.Dataset, Tuple[Inputs, Outputs], Tuple[Inputs, Outputs, Paths], ], batch_size: Optiona...
29a91481989d283ac1dddd831a9746ada5971a5a
3,458
import pickle def get_data(data, frame_nos, dataset, topic, usernum, fps, milisec, width, height, view_width, view_height): """ Read and return the viewport data """ VIEW_PATH = '../../Viewport/' view_info = pickle.load(open(VIEW_PATH + 'ds{}/viewport_ds{}_topic{}_user{}'.format(dataset, dataset, topic, usernum...
f78f3b7505b3ca5ab2cac67f2634b71cfa383707
3,459
import copy def call(args, version): """Converts callList into functionString.""" # Find keyword keywords = [i for i in args if i in Variables.keywords(version)] # Too many keywords is a syntax error. if len(keywords) > 1: raise UdebsSyntaxError("CallList contains to many keywords '{}'".f...
0f5be8582903973ec3ae4077e51a11e084bcc2f8
3,461
from typing import List from typing import Dict from typing import Any import ray def get_object_locations(obj_refs: List[ObjectRef], timeout_ms: int = -1 ) -> Dict[ObjectRef, Dict[str, Any]]: """Lookup the locations for a list of objects. It returns a dict maps from an object to its...
c7b4aa6761024853468e09f846af0ada8f7ebbba
3,462
from conf.hosts import getPlateformObject from core.exceptions import EnvironmentDoesNotExist def remove_host(plateform=None, name=None, environment=None): """ Remove Host Object from Platform Object attribute hosts and return updated Platform Object. :param: plateform: host's plateform (same as type yam...
bc8e8681718f763c382230297087b9ce27a37e20
3,463
def convert_to_float_if_possible(x, elsevalue=MISSING): """ Return float version of value x, else elsevalue (MISSING or other specified value if conversion fails """ if isnonnumeric(x): return elsevalue else: return float(x)
74b1ca5d4ed63758ef9d56fb2be94cbbdec00b56
3,466
from typing import Union import requests def resolve( names: Union[list, pd.Series, str], data_source_ids: list = None, resolve_once: bool = False, best_match_only: bool = False, with_context: bool = False, with_vernaculars: bool = False, with_canonical_ranks: bool = False ) -> pd.DataFram...
a25bd275e8222058e5926bf9a8b53de7a1cb3ccc
3,467
import numpy def polarisation_frame_from_wcs(wcs, shape) -> PolarisationFrame: """Convert wcs to polarisation_frame See FITS definition in Table 29 of https://fits.gsfc.nasa.gov/standard40/fits_standard40draft1.pdf or subsequent revision 1 I Standard Stokes unpolarized 2 Q Standard Stoke...
a2ed057be23add9a6c2041a243286bf06519306f
3,468
import random import json import logging def _update_traffic_class(class_name, class_type, **kwargs): """ Perform a PUT call to version-up a traffic class. This is required whenever entries of a traffic class are changed in any way. :param class_name: Alphanumeric name of the traffic class :param...
8a19fedcce20a94a3e5c8f06f7fb1ee901dcc6dd
3,469
def eff_w_error(n_before, n_after): """ n_before = entries before n_after = entries after """ eff = n_after/n_before eff_error = np.sqrt(eff*(1-eff)/n_before) return (eff, eff_error)
307945af0acc2eb04686b5453f2905be1111944a
3,470
import scipy def hurst(x): """Estimate Hurst exponent on a timeseries. The estimation is based on the second order discrete derivative. Parameters ---------- x : 1D numpy array The timeseries to estimate the Hurst exponent for. Returns ------- h : float The estimatio...
0632f0e4c5912410568c25774c1da66c160ff78e
3,471
import yaml def explode_on_matched_columns(df, safe_columns, other_columns): """Given the name of multiple columns where each entry is a string encoding a list, and where for each row the lists in all columns are the same length, return a dataframe where the each row is transformed into len(list) rows...
4f38310e563c8081ee7297ec2af2211ca8084504
3,472
import networkx def plot_time_series_graph(val_matrix, var_names=None, fig_ax=None, figsize=None, sig_thres=None, link_matrix=None, link_colorbar_label='MCI', save_name=None, link_width=None, arrow_linewidth=20., vmin_edges=-1, vm...
e4acb78dbb8809f3b1604b4a44437c775c0cdfb7
3,473
def get_configuration_docname(doctype=None, txt=None, searchfield=None, start=None, page_len=None, filters=None): """get relevant fields of the configuration doctype""" return frappe.db.sql("""select soi.configuration_docname, so.name, so.customer from `tabSales Order Item` soi inner join `tabSales Order` so on ...
fb9494aacfbff6ec77f0e512daab35ffcd9c7fb9
3,474
import requests import re def skymapper_search(searchrad,waveband,targetra,targetdec): """ Search for stars within search radius of target in Skymapper catalogue """ # set up arrays and url star_ra = [] star_dec = [] star_mag = [] star_magerr = [] sky_ra = [] sky_dec = [] sky_u_petro = [] sky_u_petro_e...
3ebed23f2ec73f6a8e859e645a2c3b5f936ac674
3,476
import random def Decimal_to_Hexadecimal(x : str) -> str: """ It Converts the Given Decimal Number into Hexadecimal Number System of Base `16` and takes input in `str` form Args: x `(str)` : It is the Positional Argument by order which stores the Decimal Input from User. Returns ...
ffe5050a834a9111a50f28c425f1bd21f60605ff
3,477
def hardcorenas_d(pretrained=False, **kwargs): """ hardcorenas_D """ arch_def = [['ds_r1_k3_s1_e1_c16_nre'], ['ir_r1_k5_s2_e3_c24_nre_se0.25', 'ir_r1_k5_s1_e3_c24_nre_se0.25'], ['ir_r1_k5_s2_e3_c40_nre_se0.25', 'ir_r1_k5_s1_e4_c40_nre_se0.25', 'ir_r1_k3_s1_e3_c40_nre_se0.25'], ['...
ff9be560a0061101fd672bd115fbfd8920537177
3,478
import tqdm def refine(weights, trees, X, Y, epochs, lr, batch_size, optimizer, verbose): """Performs SGD using the MSE loss over the leaf nodes of the given trees on the given data. The weights of each tree are respected during optimization but not optimized. Args: weights (np.array): The weights o...
6704e36b61ac9bda65ba0e118590aa2b627c8e2a
3,479
from typing import ClassVar from typing import Any from typing import Dict def fetch_db_object(cls: ClassVar, body: Any): """Fetch a database object via SQLAlchemy. :param cls: the class of object to fetch. :param body: the body of the object. If the body is None then None is returned (for the case where...
ae4a96ac9875d5b936df1d9c05f8a022a9a4b51e
3,480
def should_skip_cred_test(): """ Returns `True` if a test requiring credentials should be skipped. Otherwise returns `False` """ if username is None or password is None: return True return False
c5f45a20f7febc100a2f2eb950697c91837e0281
3,481
from typing import List from pathlib import Path def list_input_images(img_dir_or_csv: str, bucket_name: str = None, glob_patterns: List = None): """ Create list of images from given directory or csv file. :param img_dir_or_csv: (str) directory containing input...
0dccd2d0356b8f89991a1ab1f8a621e696918ab5
3,482
def get_insta_links(L: Instaloader, url: str) -> tuple: """ Return list of shortcodes :param url: URL :return: success status and list of shortcodes """ try: shortcode = get_insta_shortcode(url) post = Post.from_shortcode(L.context, shortcode) return True, post exc...
6ee9eac712d4603d1b7cffedd11cf07e4345ec0a
3,483
async def http_request_callback(_request: HttpRequest) -> HttpResponse: """A response handler which returns some text""" with open(__file__, 'rb') as file_pointer: buf = file_pointer.read() headers = [ (b'content-type', b'text/plain'), (b'content-length', str(len(buf)).encode('ascii...
2c5bdf2e4617c7780fe9c8d0b4a65b363e05babc
3,485
from typing import Tuple from typing import List from typing import Union def item_coverage( possible_users_items: Tuple[List[Union[int, str]], List[Union[int, str]]], recommendations: List[Tuple[Union[int, str], Union[int, str]]], ) -> float: """ Calculates the coverage value for items in possible_us...
f3eb59e0146561c8a18f74c548539b8cc9dcbb5b
3,487
def calc_area(img_it, contours, conv_sq, list_save): """ Summary Parameters ---------- yearstr : TYPE DESCRIPTION. Returns ------- TYPE DESCRIPTION. """ # Calculate areas sum_file = 0 for c in contours: M = cv2.moments(c) area = M['m00']...
f3bdba8892041edfe5ba0497c927f846fd8110d9
3,488