content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def vmag(v: list[float]) -> float: """Compute the Magnitude or length of a vector v of arbitrary dimension n equal to len(v) Args: v: list of ints or floats Returns: float """ s = sum(i * i for i in v) return sqrt(s)
c83b8e06c2a3a5efdb07b8d15d06bd52e853556d
73,300
def multi_win_eliminate(func, data, numwin=1, **kwargs): """Convert single winner method to multi-winner method, using candidate elimination.""" winners = [] num_left = numwin data = data.copy() outputs = [] ties = [] while num_left > 0: winners_ii, ties_ii, out...
cc3d7eec890058a1ef7d34615f4765ea89c5a058
73,301
def number_components(root, vertex_status): """ Number the components to the right of SOURCE vertex in the forest input to the assembly phase INPUT: - ``root`` -- the forest which contains the components and cocomponents - ``vertex_status`` -- dictionary which stores the position of vertex ...
38282f305bec3eb3e28a4132ad0c094ea98f5d0d
73,302
import time import os import shutil def load_data(config): """ :param config: config :return: batch data iterator and alphabet """ print("load data for process or pkl data") alphabet=None start_time = time.time() if(config.train is True)and(config.process is True): print('PROC...
8873040f65774d58ec573e7d84e1f7c156948dcb
73,303
def compute_score_of_segmentation(reference, segments_in_time, window_length = 0.5): """ Computes precision, recall and f measure from estimated segments and the reference, both in seconds. Scores are computed from the mir_eval toolbox. Parameters ---------- reference : list of tuples ...
2227d1d8d6e120bca1a54d0a204847406db73296
73,304
def get_countries(): """ The endpoint is for now publicly available. Returns: JSON of all countries. """ countries = Country.query # no need to order countries_data = [country.to_dict() for country in countries.all()] return jsonify(countries=countries_data)
2a1a9aeac95a6cd768534603ac7643cea06c02bc
73,305
def calc_reference_target(*args): """calc_reference_target(ea_t from, refinfo_t ri, adiff_t opval) -> ea_t""" return _idaapi.calc_reference_target(*args)
967af2f9f1851dffe132d427caefbedaa1f545c7
73,306
from typing import Any import numbers def _is_metric_diffable(metric_value: Any): """Check whether a metric value is a number or an ndarray of numbers.""" return (isinstance(metric_value, numbers.Number) or (isinstance(metric_value, np.ndarray) and np.issubdtype(metric_value.dtype, np.number)...
d5ce9122324c7902865ee6d5c3e70a00c462c568
73,307
def add_one(x: int) -> int: """ Returns input value added one :param x: value greater than or equal to 0 :return: x + 1 :except x less than 0: """ assert x >= 0 return x + 1
eaf60652a9dc210b3f4174c18873be1973c4f99e
73,308
def get_xdg_home(config_id: ConfigID) -> str: """ Returns the value specified in the XDG_CONFIG_HOME environment variable or the appropriate default. See :ref:`xdg-spec` for details. """ log, _ = prefixed_logger(config_id) config_home = getenv('XDG_CONFIG_HOME', '') if config_home: l...
66351b614e44e4146f1625334163116be3d10ff5
73,309
from sys import version_info def aes_raw_pad(raw): """ Return padded raw string that will be encrypted by AES encrypt function. :param raw: Raw string that will be padded. :return: Padded raw string. """ if version_info >= (3, 0): return py3_aes_raw_pad(raw) else: return ...
6d2c2235880756cb5bdaeb8e3921a186f8c0f787
73,310
def svn_fs_get_uuid(*args): """svn_fs_get_uuid(svn_fs_t * fs, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_get_uuid(*args)
d3d0316a8abb622a07ae69137376fc804bce9f6a
73,311
def listify(iterable): """Returns a flattened list of iterable if not already a list Parameters ---------- iterable : iter-like An iterable object that will be wrapped within a list Returns ------- list An enclosing 1-D list of iterable if not already a list """ a...
845428c8a7d4d431fd2fb94e338b004a5ac06ceb
73,312
async def text_to_pic(text: str, css_path: str = None, width: int = 500) -> bytes: """多行文本转图片 Args: text (str): 纯文本, 可多行 css_path (str, optional): css文件 width (int, optional): 图片宽度,默认为 500 Returns: bytes: 图片, 可直接发送 """ template = env.get_template("text.html") r...
9af7b461af684b9f71d14edf39be3bb0cd770215
73,313
def LU_nopivotv(A): """ % Fattorizzazione PA=LU senza pivot versione vettorizzata intermedia In output: L matrice triangolare inferiore U matrice triangolare superiore P matrice identità tali che LU=PA=A """ # Test dimensione m,n=A.shape flag=0; if n!=m: prin...
4ae8a22f9790c6433e2263d237696e66b4b25678
73,314
import os def download_repo(repo_name, sha): """ Download and validate the repository from a specific sha. Args: repo_name (str): The repository full name. (e.g iliapolo/pyci) sha (str): The sha of the commit to download. Raises: exceptions.NotPythonProjectException: Raised ...
b1fa7a693a34a91b25c1192901f886b7aa9023c4
73,315
def r2_metric(y_true, y_pred): """ Compute r2 metric. Args: y_true (tf.tensor): True y-values. y_pred (tf.tensor): Predicted y-values. Returns: tf.tensor: r2 metric. """ SS_res = ks.backend.sum(ks.backend.square(y_true - y_pred)) SS_tot = ks.backend.sum(ks.backen...
2b3e4e26a7eedf67722667727ec198c5ef211240
73,316
from typing import List from typing import Callable def post(route: str, additional_methods: List[str]=[]) -> Callable: """ States that a function will be executed when a POST request is sent to the server. """ return lambda func: (route, 'POST', func, additional_methods)
e162eb98ae612081a1eb54229b965deb7457c62f
73,317
def get_K(M, R, xi, theta, dthetaXdxi, xi1, dthetaXdxi1, n): """ The proportionality constant for the polytropic equation of state Positional Arguments: M -> Stellar Mass in g R -> Stellar Radius in cm xi -> dimensionless radius theta -> solution to theta from integration ...
67dd9c8bc8e79b1d45d2fda5053b150ae46e80e4
73,318
def FileClassify(diri, log): """ Classifies all files in a directory and writes a night log of science images """ # define output lists sim_sci = [] flats = [] ThAr_ref = [] ThAr_ref_dates = [] flat_ref_dates = [] obnames = [] exptimes ...
d812785fb8476243fa9cdff014acc8ec14c5bec1
73,319
import json def read_config(path_to_config): """Parses and returns configuration from чfile.""" data = json.load(open(path_to_config)) deploy = data['deploy']['monique'] queue_host = deploy['queue_host'] queue_port = deploy['queue_port'] return JobcontrolConfig(queue_host, queue_port)
db94cc797743775d80bf2fa47289db0e6321a096
73,320
def open_rmf_file_read_only(*args): """open_rmf_file_read_only(std::string path) -> FileConstHandle""" return _RMF.open_rmf_file_read_only(*args)
ea6c3054cc1061c1cf741f0fcd98be5f385869bd
73,321
def fetch_image(client, name): """ Fetch an image if it isn't already present. This works like ``docker pull`` and will pull the tag ``latest`` if no tag is specified in the image name. """ try: image = client.images.get(name) except docker.errors.ImageNotFound: name, tag = ...
f6d3e972bc196eb644b1029a6f0b23c8a37dfb70
73,322
import numpy def launch(cfg): """ Runs a GPATH job Parameters ---------- cfg : gpath.parse.Settings Parsed YAML dict with attribute-like access """ gpath.plugin.import_plugins(*cfg.genes) gpath.plugin.import_plugins(*cfg.objectives) import_module(cfg.similarity.module.rspl...
fd26c42ec926645f427e24620fa3c0b487d35a4b
73,323
def compile_extra(typingctx, targetctx, func, args, return_type, flags, locals, library=None, pipeline_class=Compiler): """Compiler entry point Parameter --------- typingctx : typing context targetctx : target context func : function the python function...
c0a8e7335b3ca6a8fe70c52cd841a7f1947e1ee8
73,324
from matplotlib.legend import Legend def setup_legend(all_axes, legend_handles, legend_labels, options): """Sets all the relevant legend properties using the options given in `options`.""" if not options.legend or not legend_labels: return legend_axis = all_axes[-1] if options.twin and o...
2166e31dffa624a886a467f6119f6b103c601793
73,325
def run_dark_zone(B_cells, cycle_number, nb_rounds = 2): """ B cells proliferate and undergo SHM in the dark zone. """ for i in range(nb_rounds): ftrack2.write('division/mutation round = %d' %(i+1)) ftrack2.write('\n') ftrack2.flush() new_cells = [] for b in B_cells:...
5eab738d9e0a5c5e69a5e639bfd877bd0be89b20
73,326
import itertools def rvps_from_bed(file_path, chrom_col = 0, region_cols = (1,2), value_col = None, ID_col = None, value_fill = 1, header = None, allowed_chroms = None, sep =...
8500fd6e77b0537852d1d351babebf3404e5a113
73,327
def select_imregions(ptype, full_im1, full_im2, overlap_pixels): """Select image regions to extract keypoints from.""" if ptype == 'z': im1 = full_im1 im2 = full_im2 elif ptype in 'y': y1 = full_im1.shape[0] - overlap_pixels[0] y2 = overlap_pixels[0] im1 = full_im1[y...
5c4b3caae4216bd84ad975603e8196c6061ce007
73,328
def plume_model_demo(dt=0.01, t_max=100, steps_per_frame=200, seed=DEFAULT_SEED): """Set up plume model and animate puffs overlayed over velocity field. Puff positions displayed using Matplotlib `scatter` plot function and velocity field displayed using `quiver` plot function. plot...
56d21108d5795674e8fa19719540b99255c61c74
73,329
def edit(*args, **kwargs): """ Checks out a file for editing. All file paths should be supplied as arguments! :rtype: dict """ # Create repository # p4 = createAdapter(**kwargs) try: # Check out files # p4.connect() results = p4.run('edit', '-c', k...
40fe17e8f7f9464b01b123c6323deadebbc425a5
73,330
import time def pytest_runtest_protocol(item, nextitem): """ Run the test protocol. Note: when teardown fails, two reports are generated for the case, one for the test case and the other for the teardown error. """ reruns = get_reruns_count(item) if reruns is None: # global settin...
ea0dd5408aec89c07be13123c62a7d6521cf9f92
73,331
from typing import Iterable from re import T def uniq(iterable: Iterable[T]) -> Iterable[T]: """Imitate the Unix tool uniq, dedup adjacent items This function guarantees overall uniqueness of its elements if and only if the iterable argument is sorted first. """ return map(itemgetter(0), groupby...
d0a370caa3b4067da37e2a7348fb672315c76f1e
73,332
def pitch(ra, dec, time): """Calculate sun pitch angle for the given spacecraft attitude ``ra``, ``dec`` at ``time``. Example:: >>> Ska.Sun.pitch(10., 20., '2009:001:00:01:02') 96.256434327840864 :param ra: right ascension :param dec: declination :param time: time (any Chandra.Time ...
52f07cd9b26493f408621795f5d8f171ba178787
73,333
import tqdm def adjust_contrast_with_mask(img, img_mask=None, contrast=-1, mu=-1, img_min=0, img_max=255, force=True, verbose=False, mu_steps=500, gain_steps=500): """ A version of the contrast adjustment that is mindful of the mask Performs contrast adjustment of the image,...
3980737a222d8618d42fe1e2add4f4af78289091
73,334
def get_minimum_n_cores_for_only_LSNN_placement_no_ws(LSNN_size, input_dim, n_relay_copies, use_cores_for_input=False): """ Unlike the function get_minimum_n_cores_for_LSNN_placement_no_ws, this function only calculates the parameters for the placement of the input and LSNN layers given the number of re...
c51eec344ecaa579c882c6b24a10fede2842bc65
73,335
def attack(url): """Implement timing attack on given url.""" guess = '' found = True while found: c, found = next_guess(url, guess) guess += c if found else '' valid = check_valid(url, gen_params(guess)) return valid, guess
c21de994600de346024950b0a8bb9d551c65836f
73,336
from typing import List def get_macro_recall(executions: List[RevisionResults]) -> float: """ Calculate macro-averaged recall for a list of tool executions. :param executions: list of RevisionResults objects :return: macro-recall value """ red_tests_recall = [ res.score[1] / res.score...
7ad1a564f3e1ebe674dbf52e193c48943848741a
73,337
import types import keyword def invalidPythonNames(): """ Creates a list of valid Java identifiers that are invalid in Python. """ ts = [getattr(types, n) for n in dir(types) if not n.startswith('_')] ns = [t.__name__ for t in ts if isinstance(t, type)] return ['None', 'True', 'False', ] + ns + keywor...
0eaf0f7188d3e821bb37faa5e5f698cbcdc9e0e0
73,338
def return_obs_RA_DEC(): """ Return OM10's lensed system's position """ return SkyCoord('03h 32m 30s', '10d 00m 24s')
8b19ee8f1f83816246918284033bc98670223894
73,339
def delete_object_property(object_type, property_name): """ Delete a property from Hubspot Args: object_type (str): The object type of the property (ie "deals") property_name (str): The property name Returns: dict: the result of the delete request in JSON format """ re...
29f5b8d83e45ae052d1946abbf21d21a8b96f3f6
73,340
def populate_table(parsed_header, parsed_line, file, data_dict): """Appends parsed sample metadata to a nested dictionary where dictionary['Sample_Name']['QC_Attribute'] = QC_Metadata. Returns an updated dictionary containing new information for N-th line.""" sample_index = parsed_header.index('Sample'...
fe12a867bf2a6893580eb05f1e8d6bdb284786ae
73,341
def get_report(query, page_len): """ Extract user's reports from the website based on query and page number. Here, we want to extract reports from user, institute destination, and category of the reports. In the HTML code, the reports element is in the <p> (paragraph) tag with class attribute `readmore`...
bdf8141c9bed1e85c49a00bcddbbc926bc589a4a
73,342
def get_object_id(path): """Read, if present an object_id if not available -- would simply raise a corresponding exception """ with h5py.File(path, "r") as f: return f.attrs["object_id"]
b1457dcd5d3e7bc393a78e0bd1cdf47a40fbacd1
73,343
def split_sql(sql): """Splits given SQL into list of statements, stripping comments.""" sql = sqlparse.format(sql, strip_comments=True) return sqlparse.split(sql)
d6627568afb28fb27b5f43d8635ea1d764a2990a
73,344
def generalised_dice_loss(prediction, ground_truth, weight_map=None, type_weight='Square'): """ Function to calculate the Generalised Dice Loss defined in Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning ...
05adfcaf5e86b8fa6861d4a29e1d2cb89680d92b
73,345
def calc_best_fit_n_param_fast(ndim,flatchain_path,output_file_path=None): """Description: -Input : -Output : a numpy array with [best params, chi2] Plots and txt files: txt files: pdf files: Tested : ? By : Maayane T. Soumagnac Nov 2016 URL :...
f922ac74527e03087d3522623528ad9a661cce4b
73,346
def maximum_leja(next_point, z, lower_bound, upper_bound, weight=lambda x : 1): """ the maximums function for the leja points the next leja point is the input so that this function returns its maximum """ if (next_point[0] < lower_bound or next_point[0] > upper_bound): return -100 pr...
079c312787a0d0e8704985f0f8ffd146754b2c59
73,347
def submit_metadata(metadata_modal, name, description=None, version=None, load_workspace=False): """ Submits metadata for a project Returns ``(projects_page, data)`` """ metadata_modal.submit_metadata(name, description, version) workspace_page = WorkspacePage.verify(metadata_modal.browser, TEST...
7e49169c8ede637b060f7c59e8feba03bed9d281
73,348
def calculate_individual_geo_mean(lines, index, geo_mean, num): """ Calculate an individual line of parse results goe_mean """ previous_value = None for line in lines: line = line.split("\t")[4:] current_value = line[index] try: if float(current_value) > 0: ...
765b03379d11d2622d07086e1858ee51807bc293
73,349
def sendDataToMDB(): """ Parses array of items from frontend, sends to mongoDB :input: array of json objs - name, price, need vs want """ feData = request.get_json() for i in feData: post = { "_id" : dataIndex.count_documents({}) + 1 , "ItemName" : i['name'], ...
b937303ff45a33911b78e289e794555e572c4003
73,350
def regenerated_pyconfig_h_in(file_paths): """Check if pyconfig.h.in has been regenerated.""" if 'configure.ac' in file_paths: return "yes" if 'pyconfig.h.in' in file_paths else "no" else: return "not needed"
d5d180a5a9d149cbbcdccb3d72ef69647908678f
73,351
import traceback def get_highest_priority(): """Get the highest Rules priority""" try: rules_count = get_geofence_rules_count() rules_objs = get_geofence_rules(rules_count - 1) if len(rules_objs['rules']) > 0: highest_priority = rules_objs['rules'][0]['priority'] el...
e3732d735693d890f7a7c0716463ae447dbf4bcf
73,352
def not_equal(a,b): """ return 1 if True, else 0 """ if(a != b): return 1 else: return 0
a37ae9177a450b11412c82898e1dade68b97416f
73,353
import uuid import subprocess import os def start(pname='ovs-vswitchd', lg=None, interval_ms=250): """ Start a monitor for the target process. :param pname: Name of the process for pgrep. :param lg: The logger object. :param interval_ms: Time, in ms, between two polling of resource usage info. ...
a4e296160b0c4b45b396049033e5850b326a338f
73,354
def check_square(): """ Checks the square of the board the mouse is currently over, selecting a piece if there is one Returns: selection: The object that was under the mouse at the time of checking """ x, y = pygame.mouse.get_pos() selection = the_board.board_[y // 100][x // 100] ...
900ced25a99a2a65b3b2914b602b3a386f94778e
73,355
from operator import and_ def view_codec_list(): """ admin: codec list not admin: query by productID """ if g.tenant_uid is None: query = Codec.query \ .join(Tenant, Tenant.tenantID == Codec.tenantID) \ .join(Product, Product.productID == Codec.productID) \ ...
f3913555025434a74579e7f434fc0b7bd171911b
73,356
from datetime import datetime def get_latest_one_piece_chapter_jb(): """Retrieves the latest chapter number on Jaimini's box.""" today = datetime.date.today() jb_page = "https://jaiminisbox.com/reader/series/one-piece-2" jb_request = urllib2.Request(jb_page, headers=get_headers()) jb_response = ur...
9937346367b65b55b3908c432c6e8fa56458aa88
73,357
def active_view(): """Return currently active view""" return sublime.active_window().active_view()
e19348dc249b63aab1350b8a2362ee24db9f930d
73,358
import pathlib import shutil def cache_audio_local(path, max_audio_length, cache_dir=pathlib.Path('./audio')): """ Copies the file specified by `path` to cache_dir in the same folder structure that is present at the source. The file should be in an audio format readable by `nt.io.audioread.load_audio`...
07b2eb61e842b8c603416313f3c1c2a472d8ab66
73,359
def centerdc_2_twosided(data): """Convert a center-dc PSD to a twosided PSD""" N = len(data) newpsd = np.concatenate((data[N//2:], (cshift(data[0:N//2], -1)))) return newpsd
28d712a16f5118e73081ef857194f39488fcd027
73,360
def getCount(board): """gets counts for all pieces and empty moves present on the board""" #For fast counting Implemented this Idea #https://stackoverflow.com/questions/10741346/numpy-most-efficient-frequency-counts-for-unique-values-in-an-array unique, counts = np.unique(np.array(board), return_counts...
274d5cfe6a593a78752d775a08a0bb27ea638eaf
73,361
def src_gauss(l, m, sigma_lm, A=1., i=0., pa=0., l0=0., m0=0.): """ A 2D Gaussian model on the source emission. Parameters ---------- l : array like The l axis coordinate. m : array like The m axis coordinate. sigma_lm : float The sigma of a Gaussian profile of the s...
8ca8f5f7521ec605f3bb6db1ef3cdeed4a2241ce
73,362
def sort_hsvs(hsv_list): """ Sort the list of HSV values :param hsv_list: List of HSV tuples :return: List of indexes, sorted by hue, then saturation, then value """ bars_with_indexes = [] for index, hsv_val in enumerate(hsv_list): bars_with_indexes.append((index, hsv_val[0], hsv_val...
49a0936a04156ef1d785dea7efc95d5fffb368e0
73,363
import json import urllib async def create(conf: json.Data, server: hat.monitor.server.server.Server ) -> 'WebServer': """Create user interface Args: conf: configuration defined by ``hat://monitor/main.yaml#/definitions/ui`` path: web ui directory...
fc7a69be148b5ec81b01c8d4a6a233cd5e7df91e
73,364
import matplotlib.pyplot as plt def variance_explained(adata, threshold=0.002, n_pcs=None, figsize=(4, 3), save_show_or_return='show', save_kwargs={}, ): """Plot the accumulati...
aef31ad477784de3784f599c1b3e7805cf1ff337
73,365
def GetCcIds(issue): """Get the Cc's of an issue, whether they are explicit or derived.""" return issue.cc_ids + issue.derived_cc_ids
c5d558c4bfac4da5e501bc834e6218a44c49fbd9
73,366
import cmd def kill_remote_process(pids, instance): """Kill processes in remote device (`instance`) Parameters ---------- pids : list A list of process id's to kill instance : instance.Instance Instance object corresponding to remote device Returns ------- str Result of `kill` command ...
81b272a099ffa9f0815526abbad66647ababf13e
73,367
def sortedArrayToBST(nums): """ :type nums: List[int] :rtype: TreeNode """ if len(nums) == 0: return None mid_idx = int(len(nums) / 2) root = TreeNode(nums[mid_idx]) root.left = sortedArrayToBST(nums[:mid_idx]) root.right = sortedArrayToBST(nums[mid_idx + 1 :]) return root
9f842a9818da7bc5de6c136d4ea46c099ce79711
73,368
def render_md(full_path, format): """ Render a given markdown file """ with open(full_path, encoding="utf-8") as file_handle: text = file_handle.read() html = markdown.markdown(text) return Response(html, mimetype="text/html")
f65ea879c1c501b28c27d2c369645a60c323fffa
73,369
import urllib def extract_params(qs, known_params, object_type, object_name): """ Extract parameters from a query string to a dict while ensuring there is no unknown parameter qs: the query string known_params: a list of known parameters, any unknown parameter found will fail an "ensure" check object_type: stri...
2b836ebb1a826c9d0ab17dbb472acb7ca5690fcc
73,370
import torch from typing import Sequence from typing import Any def clamp_n(tensor: torch.Tensor, min_values: Sequence[Any], max_values: Sequence[Any]) -> torch.Tensor: """ Clamp a tensor with axis dependent values. Args: tensor: a N-d torch.Tensor min_values: a 1D torch.Tensor. Min value...
bc3f486d04c55d92b001239d1f9e2496a7d201d0
73,371
import numpy as np import vtool_ibeis as vt import six def draw_feat_row(chip, fx, kp, sift, fnum, nRows, nCols=None, px=None, prevsift=None, origsift=None, aid=None, info='', type_=None, shape_labels=False, vecfield=False, multicolored_arms=False, draw_chip=False...
db36ebd7c41bf57f5b9298fe333df2bc1b294049
73,372
import time def login(): """ A form (GET) and the assocaited handler (POST) for validation of user credentials. It is possible to put the application in testing mode, so that password checks are not enforced and the user only need supply a username. This should never be enabled in production....
447610c550da1fed231577d7819574548d408605
73,373
import shlex import click def parse_parameters(_filter): """Return parsed filter parameters.""" try: parsed_filters = [] filters = ' '.join(_filter).replace(',', ' ') for item in shlex.split(filters): if '=' in item: filter_item = { 'colu...
174841c52303dc73a3ef0b598c025d8b97760461
73,374
def admin_auth(f): """Creates the admin guard decorator""" @wraps(f) def decorated(*args, **kwargs): data, status = Auth.get_logged_in_user(get_jwt_identity()) user = data.get('data') if not user: return data, status if not user['admin'] == store.is_admin(): ...
80ccaea73fc168b1bdc5e6d84ea160e29508c4f3
73,375
def load(test=False, cols=None): """Loads data from FTEST if *test* is True, otherwise from FTRAIN. Pass a list of *cols* if you're only interested in a subset of the target columns. """ f_name = FTEST if test else FTRAIN df = pd.read_csv(f_name) df['Image'] = df['Image'].apply(lambda im: np...
eb92ac8ee57b961118c37788915ca90b02a40cc9
73,376
import types def do(f): """ A decorator which allows you to use ``do`` notation in your functions, for imperative-looking code:: @do def foo(): thing = yield Effect(Constant(1)) return 'the result was %r' % (thing,) eff = foo() return eff.on(...) ...
c2408d4d546047098eb92979729b33395b41adca
73,377
def check_data_id(data_id): """检查DataId是否合法 :param dataId: :return: """ return check_param_isvalid(data_id)
1101c7f4a2bffd7bb1342640dd5fc22cbfadd080
73,378
from typing import List def BruteCollinearPoints(points: List[Point2D]): """ Examines 4 points at at a time Checks whether all 4 points lie on the same line, returning all such line segments """ segments = [] for p in range(0, len(points)): pp = points[p] for q in range(p +...
e6cd0099af7fe314eb1be1ba0693bfa357945d6b
73,379
import os import torch import socket def setup_cfg_gpu(cfg): """ Setup params for CUDA, GPU & distributed training """ logger.info("args.local_rank %s", cfg.local_rank) ws = os.environ.get("WORLD_SIZE") cfg.distributed_world_size = int(ws) if ws else 1 logger.info("WORLD_SIZE %s", ws) ...
784030171a8c1d7dca97fda3ff0f69681d6f33c2
73,380
def cleanupFilename( fname ): """: Make the filename usable. = INPUT VARIABLES - fname Given a filename, clean-it up to make sure we can use it with the file system. = RETURN VALUE - Returns a cleaned up form of the input file name. """ fname = fname.replace( ' ', '_' ) fname = ...
25f727172ed9438c49510fd6703d2d56c61f85f2
73,381
from paraview.modules.vtkPVVTKExtensionsFiltersGeneral import vtkCellIntegrator def IntegrateCell(dataset, cellId): """ This functions uses vtkCellIntegrator's Integrate method that calculates the length/area/volume of a 1D/2D/3D cell. The calculation is exact for lines, polylines, triangles, triangle...
a2eeb687d48fbab73aeb4de39726e93fdb0be6bd
73,382
def get_PS_embeddings(_files, params): """ Computes the Patchy-San embeddings for all functions in _files """ CNN_input = {} for function, acfgs in _files.items(): CNN_input[function] = list(map(lambda acfg: get_CNN_input(np.array(acfg['A']), np.array(acfg['X']), params),acfgs)) return C...
0b1d447d9176bb77261d40f6dd456b49dc60dcd1
73,383
import json import ast def parseJsonDatum(js): """Parse a JSON string, return parsed object or None :rtype: :param js A valid JSON string :return parsed JSON as a dict """ if isinstance(js, dict): return js if not isinstance(js, str): return None try: # prin...
29d334038b9275fc822576f9670966768d02060e
73,384
def randomly_resort(x, sigma, seed=None): """ Function randomizes the entries of ``x`` with an input level of stochasticity ``sigma``. Parameters ----------- x : ndarray Input array of shape (npts, ) that will be randomly reordered sigma : float Input level of stochasticity in ...
ea73a296cdcaa7ec28c7f8b6106ba2e95092b12f
73,385
def FullCopy(obj): """ * Return full copy of passed object. Inputs: * obj: Any object. """ if hasattr(obj, '__enum__'): if isinstance(obj, dict): copyObj = {} for key in obj: copyObj[deepcopy(key)] = FullCopy(obj) else: copyObj ...
717e70e28b1cdd803225c774304010a87a3ece3c
73,386
def model_from_sklearn(sk_model, name, accuracy): """Loads a model from the given sklearn data structure. Args: sk_model: A model previously fitted via scikit-learn. name (str): The name of the model. This name will later be used during code-generation for naming functions. accuracy (fl...
8f2904b471234bf65ffc947208166526649e9966
73,387
def tokenizer_encode(texts, tokenizer, maxlen=512): """ Let Transformers Tokenizer API prepare the input data and encode, precisely tokenizing Parameters: ------------ texts : list of str A list of string to be encoded by the tokenizer. tokenizer : Transformers AutoTokenizer ...
c28ee490a8d2e8efd473d25ed9b58b3b209dafa3
73,388
def is_tlog(filename): """Boolean specifying if filename is a Trajectory log file.""" return _is_log(filename, ('VOSTL',))
707a4b62bb9cb85fc279662b3910bafe382e48df
73,389
def continue_or_stop(question): """ n or y is parsed from inputs first character so it's the only part that matters """ while "answer not y or n": reply = str(input(question + " (y/n): " )).lower().strip() if reply[:1] == 'y': return True elif reply[:1] == 'n': return False else: print("ERROR: Not ...
3447a3b205e71270ccede9fa5608c823afa10062
73,390
import os def data_dir_check(dir_list, woid, date): """Create and return transfer directory if 'model' found in dir path.""" # return NA if no transfer dir found transfer_dir = 'NA' # iterate over data dirs for directory in dir_list: # if model found, create transfer dir and return path ...
424f0c36e6768328532676d429d690c50fbc6bd8
73,391
def get_default_if(): """ Returns the default interface """ f = open('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if int(dest) == 0: interf = words[0] break except ValueError: pass ...
b9c046aa02cd5e7df4f1ca7506c1d01ebf93f19e
73,392
def _get_mro(obj): """Get the method resolution order for an object. In other words, get the list of classes what are used to look up methods on the given object, in the order in which they'll be consulted. """ try: return obj.__class__.__mro__ except AttributeError: return _get...
3e7dbd7d4210726e5834c8a95a9b9086e16aad7d
73,393
import json def jsonify(val): """Perform a naive JSON dump.""" return json.dumps(val)
0b52203062c031ad10fd660c96daa0459f81d367
73,394
def linregress(x, y, weights=None): """ fit a line to y(x) using least squares. """ if weights is None: weights = np.ones(x.shape) weights /= np.sum(weights) μx = np.sum(weights*x) μy = np.sum(weights*y) m = np.sum(weights*(x - μx)*(y - μy))/np.sum(weights*(x - μx)**2) b = μy - m*μx return m, b
934a9734c92a2052ff038578781902a51378bdf2
73,395
import math def opacMg1(numDeps, temp, lambda2, logGroundPops): """//c****************************************************************************** //c This routine computes the bound-free absorption due to Mg I. //c******************************************************************************""" #//...
c97da4bf667163bc73c95da43b6300a4be9a38be
73,396
import requests import logging from datetime import datetime import json def get_strava_activities(config, access_token, after_date): """ Executes REST call to Strava's API to retrieve user's activities data. Prints one JSON object per activity to stdout. Returns True if retreival of activitites data ...
0c51f27363b8ec9665377b602410e040537f932b
73,397
def find_road_building_relations(voronoi, pts_line, pts_left, pts_right, road_crds): """ Find all road IDs facing the current road segment. Makes use of the indices of the points between which a voronoi ridge lies. This can be used to check if a road and building are facing each other. """ r_fi...
4c023d6a93bb8a6fbdcd7565e4b191fe2b63a66a
73,398
def create_sqlalchemy_url(drivername, username=None, password=None, host=None, port=None, database=None, **kwargs): """ 输出一个 sqlalchemy的 url,有一些额外的优化。 :param drivername: :param username: :param password: :param host: :param port: :param database: :param kwa...
1516d6c97ba8272dd3d2fe3829e64b8beb668e15
73,399