content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import tqdm def calc_curve_bootstrap(curve, metric, y, preds, n_bootstrap, seed=12345, stratified=True, alpha=95): """ Parameters ---------- curve : function Function, which computes the curve. metric : fucntion Metric to compute, e.g. AUC for ROC curve or AP for PR curve y : n...
3ce7d2cacd9d09b8978db6514a112cfe5288ba6a
3,610,200
import os def connect(host=None, database=None, user=None, password=None, **kwargs): """Create a database connection.""" host = host or os.environ['PGHOST'] database = database or os.environ['PGDATABASE'] user = user or os.environ['PGUSER'] password = password or os.environ['PGPASSWORD'] ret...
a247940b8b18e69d85775d94bfee420ba32aad79
3,610,201
def to_b58_string(multihash): """ Convert the given multihash to a base58 encoded string :param bytes multihash: multihash to base58 encode :return: base58 encoded multihash string :rtype: str :raises: `TypeError`, if the `multihash` has incorrect type """ if not isinstance(multihash, b...
e85c83a622c3371b85f5dc716bbf1a415d03e349
3,610,202
import subprocess import os def run_in_docker( command: str, docker_options="", capture_output=False, text=None ) -> subprocess.CompletedProcess: """Run command in Docker.""" command = command.strip() print("+ ", command) env = os.environ.copy() env["PWD"] = cwd_for_docker_volume() return ...
5007dbcdd6de80ef6c2001521111b9f79305bdbf
3,610,203
import logging import os import yaml def get_logger(name, level=logging.INFO): """ Get a logger and load logging.yaml config file if exists """ # Set a basic level of logging logging.basicConfig(level=level) # Get the path to the logging config yaml dir_py_file = os.path.dirname(os.path.r...
09899272eff1ba937bb64cc2c1705c204147adea
3,610,204
import urllib def make_request(url: str) -> HTTPMessage: """ Send a get request to the url passed in and return the headers in the response Args: url (str): url to send GET request to Returns: HTTPMessage: http response object """ with urllib.request.urlopen(url, timeout=3...
11b628838b6cee5528761440e2b13de428f508e6
3,610,205
def poly0g_to_poly01(polygon, grid_side): """ [0, grid_side] coordinates to [0, 1]. Note: we add 0.5 to the vertices so that the points lie in the middle of the cell. """ result = (polygon.astype(np.float32) + 0.5) / grid_side return result
d3882be349bf09a5634de00ef12bef851d826075
3,610,206
def image_loader(path): """Image Loader helper function.""" return Image.open(path.rstrip("\n")).convert('RGB')
b6b989703771d6dd4ca8705044027fb71bcdcdb7
3,610,207
def retrieve_item(item_id): """ This is a stubbed method of retrieving a resource. It doesn't actually do anything. """ return { "id": item_id, "brand_name": "Clean Breathing", "name": "Air Purifier", "weight": 12.3, }
eedeca7580bd74244c62da798ac19d6b815ba445
3,610,208
def max_drop_in_simulated_observation( event_duration: int, observation_size: int, noise_sigma: float, corr_array: np.ndarray) -> float: """Returns the maximum drop from a simulated observation. An observation consisting only of correlated gaussian noise is created and exhau...
464f45adc3633ba87105f66dd4bc492c1241c500
3,610,209
def tau_of_N(microns, column, v0=0, temperature=20, width=1.0, velocity=0.0, orthopara=3): """ Return the optical depth of an H2 line as a function of wavelength... (absorption) """ grounden = h2level_energy(0,0) alllevelpop = np.sum([exp(-(h2level_energy(v,j)-grounden)/(k*temperature)) for v in...
2d8c84188c802554be79660874a5f7cafafbcf6c
3,610,210
def witness_dag_from_root(root, xsys, get_links=lambda y: map(lambda e: set({e}), y), strict=False): """Builds the witness DAG as in Englert (2014) from a sequence of 2-opt steps""" # add a node for each edge in the initial tour with arbitrary timestamp {1,..,n} _, y = xsys[root] links = [find_next_li...
20e7e905fadd383c8bf005bdd2b18a5ff32ca082
3,610,211
def create_instance(test_id, config, args): """ Invoked by TestExecutor class to create a test instance @test_id - test index number @config - test parameters from, config @args - command line args """ return TestPeerReachability(test_id, config, args)
5bfa04a20898fa2086656bd21a57a67d9d61a956
3,610,212
from typing import List def get_graphs_np(graphs: GraphsTuple, indices=List[int]) -> GraphsTuple: """Gets a new graphstuple (numpy) based on a list of indices.""" node_indices = np.insert(np.cumsum(graphs.n_node), 0, 0) node_slice = np.concatenate( [np.arange(node_indices[i], node_indices[i + 1]) ...
3b19af0f179749be6b3c1b3d743961baf616b4e9
3,610,213
def one_hot(Y, C): """ :param Y: -- shape of (1, number of examples) :param C: -- number of classes of Y :return: Y_oh -- shape of (C, number of examples) """ m = Y.shape[1] Y_oh = np.zeros((C, m)) for i in range(m): Y_oh[Y[0,i],i] = 1 return Y_oh
a88d145033c1995d36031a5d176d1333f861ca48
3,610,214
import six def parse_input_data(input_data, hdu_in=None): """ Parse input data to return a Numpy array and WCS object. """ if isinstance(input_data, six.string_types): return parse_input_data(fits.open(input_data), hdu_in=hdu_in) elif isinstance(input_data, HDUList): if len(input_...
5c1b4fc5dfa2b5a89242e62580f8d38b7c15952e
3,610,215
import plotly.express as px def _plotlyGraphCore(data: GraphData, title, legend): """Internal function for plotly graphing, users should call plotlyGraph() instead""" try: except ImportError: raise ImportError("Plotly is required to use this graph. Install with `pip install plotly`") sm =...
0f6cf8fb052bda60c9235f96a37a9b481fee2ece
3,610,216
def alg_to_song(algorithm, num_qubits=None, num_samples=40, mapping=maps.default_map, name="alg", tempo=100): """ Make a song from an algorithm. Markovian sample the algorithm, then map to a Song object. algorithm: list of Gate objects and/or string gates. Example:...
09d55312a57438834afcb8406b6683819854dc68
3,610,217
from typing import Optional from typing import Any def encode_categorical_data_with_vocabulary( train_data: np.ndarray, test_data: Optional[np.ndarray] = None, unknown_item_idx: int = 0, ) -> tuple[np.ndarray, Optional[np.ndarray], list[Any]]: """Encode the categorical data by using vocabulary mapping...
d89cb19df4bb1510e01db851caf865f947ce5fac
3,610,218
def filter_sides(segmentation): """Remove hedges on left and right hand side. Also remove anything from the edge of the hedge to the closest edge of the image. """ ydim, xdim = segmentation.shape mid_point = xdim // 2 for i in segmentation.identifiers: region = segmentation.region_b...
4d02903b4cadc39fb3461fdc13916cc7233ad39d
3,610,219
from datetime import datetime def log_file_name(extension): """ Create a file name in the logfiles directory, based on current data and time Requires the computer to have an RTC or synched clock """ now = datetime.now() # Linux file_name = '%0.4d%0.2d%0.2d-%0.2d%0.2d%0.2d' % (now.year, now...
795ab0623ee6a563cfc4e2531cd8745f0ff2fac3
3,610,220
def arc(data: bytes) -> int: """ Compute a CRC-16 checksum of data with the arc algorithm. :param bytes data: The data to be computed :return: The checksum :rtype: int :raises TypeError: if the data is not a bytes-like object """ _ensure_bytes(data) return _crc_16_arc(data)
1ce9de456d04b1a8b060a1cb83ffd1b457bdae86
3,610,221
def check_replication(master_vals, slave_vals, options): """Check replication among a master and a slave. master_vals[in] Master connection in form: user:passwd@host:port:socket or login-path:port:socket slave_vals[in] Slave connection in form user:passwd@host:port:socket ...
dde3878a9afde2bd12209da20da5681fd64ba77c
3,610,222
def _incremental_mean_and_var(X, last_mean, last_variance, last_sample_count): """ Note. Most of this script is taken from scikit-learn, except for the last line. --- Original doc --- Calculate mean update and a Youngs and Cramer variance update. last_mean and last_variance are statistics compute...
55eacfc7905eae1b2608314a651c25f2707a3ac7
3,610,223
def _calculate_expected_result( dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config ): """ Calculates the expected result given cell and aggregation probabilities. Args: dist_per_cell (`tfp.distributions.Bernoulli`): Cell selection distr...
b282c538b495989b6c4066b8f99d72fc4810845e
3,610,224
def fit_unbinned(f_likelihood, data, start_guess, min_method=None, bounds=None): """ unbinned max likelihood fit to data with given likelihood func """ if method is None: method="L-BFGS-B" # minimization method, see docs result = minimize( neg_log_like, # function to minimize ...
ac20d2fe30aae1922190fee7a38d204a1612a2ad
3,610,225
def load_data(n_pca=3): """Data Loader :param n_pca: number of pca components, defaults to 3 :type n_pca: int, optional """ path = f'../dataRBC/RBC_r28L_T100R100_pca{n_pca}_enc_data.txt.gz' traj_data = pd.read_csv(path, header=None).values traj_data = traj_data.reshape(-1, 200, n_pca) ...
e7e7c454da1aebb2af83f800e488cfab3296b110
3,610,226
import os import pickle def load_object(fname,zip=0,nofind=0,verbose=0): """Loads an object from disk. By default, this handles zipped files and searches in the usual places for OCRopus. It also handles some class names that have changed.""" if not nofind: fname = ocropus_find_file(fname) ...
10252b6c1348750b66c2a01a27df8f4e6aa9d660
3,610,227
def delete_attachment(self, request, form): """ Delete a notice attachment. """ layout = Layout(self, request) notice = self.linked_official_notices[0] if notice.state == 'accepted' or notice.state == 'published': if not request.is_secret(self): request.message( _("...
6715c1079dfabd4e43e97a88ff4b5c75c563b00c
3,610,228
def geoloc(ip_address: str) -> dict: """ Return {'lat':, 'lon':} values for {ip_address} """ ip_details = method_ipinfo(ip_address) return {'lat': ip_details['latitude'], 'lon': ip_details['longitude']}
1f98d69dd9d239f27c85e490cc69d5a27aac9184
3,610,229
def TreeImportanceArray(reg): """Get important array if `reg` is tree regression.""" return reg.feature_importances_
59f3b0bcc9a4c60af71b62163e3e087137c64f49
3,610,230
def _get_test_stats_with_mi(feature_names): """Get stats proto for MI test.""" result = statistics_pb2.DatasetFeatureStatistics() for feature_name in feature_names: feature_proto = text_format.Parse( """ custom_stats { name: "max_sklearn_adjusted_mutual_information" ...
d5ebdd6a55ca0af03b1076ecc5fd4741f296ec19
3,610,231
def ride(self: Client, riders_or_rides: str) -> RideProxy: """Delegates to a :py:class:`mcipc.rcon.be.commands.ride.RideProxy` """ return RideProxy(self, 'ride', riders_or_rides)
209f5804eaf7a6e566fd13acc484abf73802d47c
3,610,232
def process_data(event_id, st, sampling_rate, pre_filt=(1.2, 2, 8, 10), water_level=100, folder_name="default_folder", save_processed=True): """ Function to process the raw data stream Args: event_id (str): Event ID -> Ideally should be time stamp YYYY-MM-DDTHH:MM:SS.000 st ...
bf2b1f829bb0211d9d1729d8feb4534cb01b236e
3,610,233
from typing import Any from typing import Dict def _check_headers(headers: Any) -> Dict: """Check headers format an validate content type. :param headers: configured headers :return Dict: request headers """ if headers is None: headers = {} if 'Content-Type' not in headers.keys(): ...
f7dc965ffd740ea94ca3485f455cf6427ebc16d8
3,610,234
def average_test_disorder(data, test_classifier, target_classifier): """Given a list of points, a feature-test Classifier, and a Classifier for determining the true classification of each point, computes and returns the disorder of the feature-test stump.""" test_disorder = 0 test_classifications = ...
555b55c58cfa956642d6b4f53afca07a999a33b1
3,610,235
import os import glob def test_snippets() -> bool: """Test all code snippets in *.snip files.""" here = os.getcwd() fixture = CompilerFixture() fail = False for i in glob.glob(here + "/*.snip"): print("=" * 20) print(i) try: fixture.run_file(i) except Ex...
60c98bd13a1a24548493e5d1b39a07b7bb7a1b07
3,610,236
import signal def seed_initial_offsets_peaks(y, noise, rect_area=500, prominence_knockdown_factor=0.03): """ Generate the locations of the seeds for the initial fit. Place a seed at each of the peaks. Determine peak location from smoothed version of signal. Smooth signal by cross correlating it with rect....
e7b4f572cedf5ef37e5bc0c3a6f724704c212f16
3,610,237
def ReadNetString(fp): """Reads a net string from the File object fp, returning the string in unicode. A net string has the format <len>:<str>, where <len> is decimal of the length of <str>, and comma ends the string. Returns: The unicode string contained in the netstring, or '' if...
9805367388fea261df94209482f3d496ef6e749b
3,610,238
def to_str(obj): """Attempts to convert given object to a string object """ if not isinstance(obj, str) and PY3 and isinstance(obj, bytes): obj = obj.decode('utf-8') return obj if isinstance(obj, string_types) else str(obj)
1123f73fff9b0eebe3a6d29f2768f0459e0d83f2
3,610,239
def get_middle_value(my_list): """Return the middle value from a list after sorting. :param list my_list: List of sortable values""" return sorted(my_list)[len(my_list) // 2] """Convert an integer resolution in base-pairs to a nicely formatted string. :param int window_size: Integer resolution ...
53e8724f1709429707766db45c34ebd0db62a686
3,610,240
import math def ll2m(lat, lon): """Lat/lon to meters""" x = lon * 20037508.34 / 180.0 y = math.log(math.tan((90.0 + lat) * math.pi / 360.0)) / (math.pi / 180.0) y = y * 20037508.34 / 180 return (x, y)
f998cb7af707d56c9dd6e7a26b8d165f392e07f3
3,610,241
def bilinterp(x, y, nx_tuple, ny_tuple, x_tuple, y_tuple, fxy): """ Bilinear interpolation: Given nx-tuple + 1 x-points, ny-tuple + 1 y-points, x_tuple and y_tuple, routine finds f(x, y) = fxy at (x, y) in (x_tuple, y_tuple). Assumes x_tuple and y_tuple are increasing arrays. """...
ee6ffb312cb0a7af3cff524aa366e71f176158f8
3,610,242
def get_version(): """Return version of the dynamic link library. Wraps: int DWGetVersion();""" return _get_version()
a99b2c66124f14b04c476b888663ffd7b38a61ff
3,610,243
def edu_plotter(func): """Decorator to apply to all plotting functions in OGGM-Edu. Parameters ---------- func : function the function or method to decorate Returns ------- the decorated function """ @wraps(func) def context_wrapper( *args, sns_context=...
d44a63d1c62f5107eb9cbedd89b3c3634bc60a00
3,610,244
def load_sample_data(name): """ Load an example dataset from the GMT server. The data are downloaded to a cache directory (usually ``~/.gmt/cache``) the first time you invoke this function. Afterwards, it will load the data from the cache. So you'll need an internet connection the first time around...
73ffa2caa4106f97d88766214756fbf6347f4787
3,610,245
def rip_svgi(content: str, embed_styles: bool = False) -> str: """ Rips SVG content (single diagram) and scripts for interaction out of HTML :param content: HTML page content in text format :param embed_styles: If specified as True then mentioned styles would be downloaded and embedded into SVG ...
d5472b86be70e138128ff527f388a9b1ffa2602d
3,610,246
def get_info(request): """ Obtiene """ info = "Backend" if UserToken.get_headquar_id(request.session): try: sede = Headquar.objects.get( id=UserToken.get_headquar_id(request.session)) info = "%s-%s" % (sede.enterprise.name, sede.name) except:...
fbfdf8ce2a802af374b0004bb0e6029849c38b9d
3,610,247
from typing import Sequence def prune_by_lbh(seq_list: list, seq_length: int, q: Sequence, kim_reduction: float = 0.75, keogh_reduction: float = 0.25): """ Prune the sequences based on LB_Kim and LB_Keogh lower bound. First the sequences are pruned using LB_Kim reduction factor and then u...
c2ed7e88f9597e9f27ed1902fca858a35e028ff3
3,610,248
def keyDataIdsInit(): """ Initializes the key data klasses. This function is called from the init function and the application should not call it directly. Returns : 0 on success or a negative value if an error occurs. """ return xmlsecmod.keyDataIdsInit()
a2f254c8b0655cea68f6a91092ac0b7697f99df2
3,610,249
import os import click def cli(drivername, mfname, devicetype, author): """ Create sal driver staging from template """ templatedir = os.path.join(scriptdir, templates[devicetype][0]) destdir = os.path.join(scriptdir, "../../", templates[devicetype][1], drivername) destdir = os.path.abspath(destdir) ...
7321e77ad30472ed8b8420db132ced002cd3164b
3,610,250
import numpy def _image_to_ground_plane_perform(r_tgt_coa, r_dot_tgt_coa, arp_coa, varp_coa, gref, uZ): """ Parameters ---------- r_tgt_coa : numpy.ndarray r_dot_tgt_coa : numpy.ndarray arp_coa : numpy.ndarray varp_coa : numpy.ndarray gref : numpy.ndarray uZ : numpy.ndarray R...
d325471ce2f21562dfd38e536ce77eb215069349
3,610,251
def encode_string_text(text): """Replace special symbols with corresponding entities or magicwords.""" text = text.replace("<", "&lt;") text = text.replace(">", "&gt;") text = text.replace("[", "&#91;") text = text.replace("]", "&#93;") text = text.replace("{", "&#123;") text = text.replace(...
c7887934983efda3a0d1e06451ccd85cab529a30
3,610,252
def compute_input_planes(input_channels, merging_strategy, inputs, abs_nodes): """Compute the number of input planes.""" if len(inputs) == 0: # this is an input node return input_channels inplanes = 0 for i in inputs: if merging_strategy == EdgeMerge.CAT: inplanes += abs_nod...
a6f163a9891f77ba58e06905d3ed03fe9e7259eb
3,610,253
def test_01_setup(): """ sample init init attr, state, action space :return: """ names = ['gender', 'age'] vals = {'gender': ['M', 'F', 'U'], 'age': ['0-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-*']} attr_set = AttrSet(names, vals) state_set = StateSet(['date', '...
ce487a5287859ea1502aea0090df90f5a0769036
3,610,254
def make_aware(value, timezone=None): """ Make a naive datetime.datetime in a given time zone aware. :param value: datetime :param timezone: timezone :return: localized datetime in settings.TIMEZONE or timezone """ if timezone is None: timezone = TIMEZONE # Check that we won't...
8012d14a84bf44f14454f5bf02f4ec93d31668cf
3,610,255
from typing import Tuple def parse_reflections_array(array: np.array) -> Tuple: """ Helper method for parsing reflections without exporting to ".CSV" Parse an reflection array of GSASII defined as: index explanation 0,1,2 h,k,l (float) 3 (int) multiplicity 4 (float) d-space, Å 5 (floa...
a20e11499b6baba9c6c6631441cd457a88bac5b9
3,610,256
def get_dbconn(db_dsn): """Connects to the MongoDB server and returns a database handler.""" def _ensure_indexes(db): """ Ensures that an index exists on specified collections. Definitions: index_by_collection = { 'collection_name': [ ('field_name_1'...
f4b074547ce539865f17cee302feae0ca4bbd0d2
3,610,257
def _params_to_ints(qs): """Convert a (string) list of string ids to a list of integers""" return [int(str_id) for str_id in qs.split(',')]
7568eeb6cf28f1c8e696e2fab6e7a89dcbbc07fc
3,610,258
import typing import json def _prepare_hyperparams(free_hyperparams: typing.Sequence, hyperparameter_values: typing.Dict) -> typing.Tuple[typing.Sequence, typing.Set[str]]: """ Values in ``hyperparameter_values`` should be serialized as JSON, as obtained by JSON-serializing the output of hyper-parameter's...
90a42428d33c6931622258691d92e82642dfa49e
3,610,259
from typing import List def est_croissante2(l : List[float]) -> bool: """ ... cf. ci-dessus ... """ # Résultat b : bool = True # Indice courant i : int = 0 while (i < len(l) - 1) and b: b = l[i] < l[i + 1] i = i + 1 return b
74357fe91d42b3cb0d95e09346504b0701ab7164
3,610,260
def compose(f, g): """ Compose two filter f and g. :param f: Outer filter function. :type f: filter function. :param g: Inner filter function. :type g: filter function. :return: lambda x: f(g(x)) :rtype: filter function. """ def filter_fn(df): df = g(df) if len...
d90cda63eb365219ce5f454265036c7d977da216
3,610,261
def Device(device_name): """Returns the taurus device for the given device name It is a shortcut to:: import taurus.core.taurusmanager manager = taurus.core.taurusmanager.TaurusManager() factory = manager.getFactory() device = factory.getDevice(device_name) :param device_...
834baf071ab408e9150cc803a317f151554950cb
3,610,262
def load_data(self, name): """Load data given a data path. This is a low level method that will search through the various search paths until it's able to load a value. This is typically only needed to load *non* model files (such as _endpoints and _retry). If you need to load model files, you sho...
94e75787fa72b91ea5e27e8cd076b36037044962
3,610,263
def stop_list_to_link_list(stop_list): """ [a, b, c, d] -> [(a,b), (b,c), (c,d)] """ return list(zip(stop_list[:-1], stop_list[1:]))
49046e60664cd9c19ab55c1254684932d937531a
3,610,264
from typing import Union def compare(A: Mv, B: Mv) -> Union[Expr, int]: """ Determine if ``B = c*A`` where c is a scalar. If true return c otherwise return 0. """ if isinstance(A, Mv) and isinstance(B, Mv): Acoefs, Abases = metric.linear_expand(A.obj) Bcoefs, Bbases = metric.linea...
830dfaa97cf042278278b5c1aff8da77d5ee8f5a
3,610,265
def get_enum_size(*args): """get_enum_size(enum_t id) -> size_t""" return _idaapi.get_enum_size(*args)
58024506d567e6d07d420233a16c1bd1e2f7750e
3,610,266
def _martin_luther_king_holiday(year): """Martin Luther King's birthday (third Monday in January)""" if year < 1983: return None for day in range(15, 22): d = dt.date(year, 1, day) if d.weekday()==0: return d raise Exception('Should never get there')
06cfb37660a8b7034bad3cadc329bca84694acb6
3,610,267
def random_bivariate_anisotropic_Gaussian(kernel_size, sigma_x_range, sigma_y_range, rotation_range, noise_range=None, ...
add17263e4bc7c1b99bf55bf032e40cc093d7079
3,610,268
def validate_guess(number) -> str or None: """ :param number: the number to guess :return: the valid guessed number or None if user gives up """ number_size = len(number) while True: guess = easygui.enterbox(f"Please guess the {number_size}-digit number: ") if guess is None: ...
41cfc02f97f33365389bd27dcd42d65c31ccdb57
3,610,269
def excel_radiosonde(request, form): """ Reads the radiosonde form and converts the data into a excel file """ start = form.cleaned_data['start_date_radiosonde'] end = form.cleaned_data['end_date_radiosonde'] time = form.cleaned_data['time_radiosonde'] fields = form.cleaned_data['fields...
371736b8f6c0eb0b84a46bc4aa36060bf85b3db4
3,610,270
def compare_metrics(best_eval_result, current_eval_result): """Compares two evaluation results.""" return best_eval_result["exact_match"] < current_eval_result["exact_match"]
ce3880c2cc271d9c8c766a2dfbd95d31f5fb651c
3,610,271
import importlib def import_module(filename): """Import a module given a full path to the file.""" spec = importlib.util.spec_from_file_location("doc_filter", filename) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
924f19b96d98290dabfda1aef70cb7f67455f553
3,610,272
def set_target_bits(targs, sourcemask): """Apply bright source mask to targets, return desi_target array. Parameters ---------- targs : :class:`recarray` A recarray of targets as made by, e.g., :mod:`desitarget.cuts.select_targets`. sourcemask : :class:`recarray` A recarray containi...
156a45e5c79a02321a3de05081ec429f5a4c325d
3,610,273
def get_checksum_value(checksum): """ Return the checksum value. The given checksum might either be a standard ad32 or md5 string, or a dictionary with the format { checksum_type: value } as defined in the `FileSpec` class. This function extracts the checksum value from this dictionary (or immediate...
bc5a3a506a53970217a32fc0be79378e85787c18
3,610,274
def construct_bibfile_data(*paths): """ List of data corresponding to individual bib files :param pathlib.Path *paths: Path to file possibly containing BibTeX data. :rtype: list """ bibs = [reffile_factory(path) for path in paths] return bibs
7b0ddfd615e8cb54ce905d52a756e689824454a1
3,610,275
def check_shell_pipes(cmd): """ Determine whether a command appears to contain shell pipes. :param str cmd: Command to investigate. :return bool: Whether the command appears to contain shell pipes. """ return "|" in strip_braced_txt(cmd)
ad91661727e42fef6c95428b524c0178e23642ec
3,610,276
from typing import Dict import requests from bs4 import BeautifulSoup import re def scrap_allrecipes_recipe(url: str) -> Dict: """This function scraps a recipe of Allrecipes, given its URL, and prepare a JSON file to index in Elasticsearch. :param url: the URL of the recipe :return: the recipe as a J...
0c060ba40e784b7dad6ab2af40dd6f0aa4600173
3,610,277
def waitTargetUpdate(omni_robot, timeout): """ Wait for target updating :param omni_robot: (OmniRobot) :param timeout: (time to wait for updating) """ omni_robot.target_pos_changed = True time = 0.0 # second while time < timeout and not rospy.is_shutdown(): if not omni_robot.tar...
c9be8516640667a758ef1a3fc62b881fc4bedec3
3,610,278
def known_references(request): """ List all known references witht he option of removing the contact date """ user = request.user if 'remove_known_ref' in request.POST and \ request.POST['remove_known_ref'].isdigit(): try: application = CredentialApplication.objects.get( ...
e22424641306f0020006f233cfea2b169a4c17c6
3,610,279
def get_plugin(): """Return the filter.""" return IpynbFilter
991dead0a95e97526736e3cf06bd76138be46cf2
3,610,280
from typing import Collection from typing import Tuple import os import tempfile import logging import shutil import subprocess import shlex def run_gliph(fname: str, cutoff: int = 0) -> Collection[Tuple[str]]: """ Run gliph. Note that we copy the fname into the current directory to make working with GLIP...
b4411f809d12275219fbb24f200b57ff0aef0b7d
3,610,281
import sys def main_loop(snake_list, cherry_list): """ Main loop of the game. This function returns only if snake collision occured. """ while True: # capture events for event in pygame.event.get(): if event.type == pygame.QUIT: # happens when user tries to...
8f99e460b88616c34213e649485c2705bfc5a351
3,610,282
def __ensure_paragraphs(text): """ Checks if paragraph break in text else adds it and returns """ if "\n\n" in text: # Paragraph break detected just return it return text # If not detected add it ourselves new_text = "\n\n".join(__cut_text(text, length=500)) return new_text
5b79021021c4a89bc12901ac12c29257e16d3409
3,610,283
def main(path, task, representation): """ :param path: str specifying path to dataset. :param task: str specifying the task. Always e_iso_pi in the case of the human performance comparison :param representation: str specifying the molecular representation. One of ['fingerprints, 'fragments', 'fragprints...
732f96bc4697ce11f3665584799c608b8c0096ae
3,610,284
from typing import Any def vectorized_loss_and_aux(task_family: tasks_base.TaskFamily, learned_opt: lopt_base.LearnedOptimizer, theta: lopt_base.MetaParams, inner_opt_state: Any, task_param: Any, key: PRNGKey, ...
760366cc22a5b3c962f3598cc707771d284f3d66
3,610,285
def region_of_interest(img, vertices): """ 区域选择 Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. """ # defining a blank mask to start with mask = np.zeros_like(img) # defining a 3 channel or 1 channel color to fill...
a0b3741b135a9a9c2356b6b63061ee784c0a6b98
3,610,286
def segformer_b5(pretrained=False, progress=True, num_classes=150): """Create a SegFormer-B5 model. Args: pretrained: Download backbone weights pretrained on ImageNet data if true. progress: Display the download progress of pretrained weights if true. num_classes: Number of output class...
39bc9c36fd26a49856848d8ba08076a0a9205334
3,610,287
def expand_codes(df=None, codes=None, cols=None, sep=None, codebook=None, hyphen=True, star=True, colon=True, regex=None, del_dot=False, case_sensitiv...
e2e6132cf94a6b19c9d6294c36ffc8fa412401a0
3,610,288
import math def compute_roce(fpr, preds, real): """ Calculate the ROC enrichment (ROCE) score - i.e., the y value divided by the x value on an ROC curve, at a fixed predetermined x value (i.e. a fixed false positive rate). Args: fpr (float): pre-set false positive rate preds (np.ar...
89190c89b4faa0d2025da578b06ba94906e7bfe8
3,610,289
import os def create_local_path(*relative_path, cache=LOCAL_CACHE) -> str: """ Create path in local OS - if not exist, create make directory to the root :param relative_path: path relative to 'base_path' :param cache: initial part of local path to be be joined with :return: a full path in local ...
cb25184dd6911d1e88a168eefc4a2b75a4bf17d7
3,610,290
def segmentPlaneIntersection(s0 = "const Dim<3>::Vector&", s1 = "const Dim<3>::Vector&", point = "const Dim<3>::Vector&", normal = "const Dim<3>::Vector&", tol = ("const double", "1.0e-8")): """Inters...
eb68974937de575702069565fc3ee34dfadf89cc
3,610,291
def subplots(nrows=1, ncols=1, figsize=None, xlabel=None, ylabel=None): """ Creates subplots from matplotlib. Args: nrows (int): ncols (int): figsize (tuple[int, int]): xlabel (str): ylabel (str): Returns: fig (matplotlib.figure.Figure): the matplotlib f...
fa78a962364dc3cb7f9807e42a9c458a17e75f42
3,610,292
def get_host_data(root): """Traverses the xml tree and build lists of scan information and returns a list of lists. """ host_data = [] hosts = root.findall('host') for host in hosts: addr_info = [] # Ignore hosts that are not 'up' if not host.findall('status')[0].attrib[...
6f4967da12edd496df613b210083745c5c137578
3,610,293
import concurrent def with_progress_bar(target): """ Adapted from ipywidgets progress bar example :param target: Function to run. Function must take progress bar as argument. :return: None Try it out with:: a = [] def work(progress): total = 3 for i in ran...
0d814c035363c14cff98de798781129b42a2858a
3,610,294
def incident_beam(*, source_chopper: sc.Variable, sample_position: sc.Variable) -> sc.Variable: """ Compute the incident beam vector from the source chopper position vector, instead of the source_position vector. """ return sample_position - source_chopper.value['position'].data
2f6b5502e336ed02b4c733808bb446f5e0310689
3,610,295
import math def arrhenius (A: float, E: float, T: float, R: float = R) -> float: """ Args: A: Pre-exponential (frequency) factor. ValueError raised if not > 0. E: Activation energy. T: Temperature in Kelvins. ValueError raised if not >= 0. R: Universal g...
8f5d43bb659070fed34274db36fb9e5ec79343d1
3,610,296
def xoai_contributor(source, *args, **kwargs): """ CZ: EN: """ value = [] for person_role in source: role = person_role["@name"] field = person_role["element"]["field"] if isinstance(field, list): for person in field: value.append( ...
a17ab90aee1326c66cdc546b726666b86039cc3f
3,610,297
def http_endpoint( flask_entity, flask_rule, method: HttpMethod = HttpMethod.GET, returns_json_response: bool = True, ): """ Decorator factory used to easily register a Transiter HTTP endpoint. :param flask_entity: either the Flask app or a Flask blueprint :param flask_rule: the URL rel...
a33c4a24466ce8ebaa96e243714ae045ce1f22fa
3,610,298
from typing import Any from typing import List import torch def all_gather_cuda(data: Any) -> List[bytes]: """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = global_world_size() ...
763c64ee2f5efe129be1a292acb81461ba395bf5
3,610,299