content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def sizeof_fmt(num, suffix='B'): """Return human readable version of in-memory size. Code from Fred Cirera from Stack Overflow: https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: ...
1aeace0d5ad8ca712704a8ee58e1e206e5e61b56
3,643,500
def readFPs(filepath): """Reads a list of fingerprints from a file""" try: myfile = open(filepath, "r") except: raise IOError("file does not exist:", filepath) else: fps = [] for line in myfile: if line[0] != "#": # ignore comments line = line...
96d483360c411a27a3b570875f61344ef4dae573
3,643,501
def validate_take_with_convert(convert, args, kwargs): """ If this function is called via the 'numpy' library, the third parameter in its signature is 'axis', which takes either an ndarray or 'None', so check if the 'convert' parameter is either an instance of ndarray or is None """ if isinstanc...
dacaf4aa6fd5ff9fa577a217c0209d75785abbaf
3,643,502
from typing import List def load_operators_expr() -> List[str]: """Returns clip loads operators for std.Expr as a list of string.""" abcd = list(ascii_lowercase) return abcd[-3:] + abcd[:-3]
49ba476bebbb6b202b7021458e70e6b1fb927810
3,643,503
def findScanNumberString(s): """If s contains 'NNNN', where N stands for any digit, return the string beginning with 'NNNN' and extending to the end of s. If 'NNNN' is not found, return ''.""" n = 0 for i in range(len(s)): if s[i].isdigit(): n += 1 else: n = 0 if n == 4: return s[i-3:] return ''
fd5973383bcf8b74573408d95d4f0065dfbda32f
3,643,504
import urllib def parseWsUrl(url): """ Parses as WebSocket URL into it's components and returns a tuple (isSecure, host, port, resource, path, params). isSecure is a flag which is True for wss URLs. host is the hostname or IP from the URL. port is the port from the URL or standard port derived from sc...
149db7e862f832baf7591fb173cd53d5259cfbba
3,643,505
def load_image(filename): """Loads an image, reads it and returns image size, dimension and a numpy array of this image. filename: the name of the image """ try: img = cv2.imread(filename) print("(H, W, D) = (height, width, depth)") print("shape: ",img.shape) h, w...
2f27d15cd12fcdf4656291a7349883e8d63ff7cf
3,643,506
def add_manipulable(key, manipulable): """ add a ArchipackActiveManip into the stack if not already present setup reference to manipulable return manipulators stack """ global manips if key not in manips.keys(): # print("add_manipulable() key:%s not found create n...
3d3709758a96edec261141291950d28d2079ae19
3,643,507
def get_wave_data_type(sample_type_id): """Creates an SDS type definition for WaveData""" if sample_type_id is None or not isinstance(sample_type_id, str): raise TypeError('sample_type_id is not an instantiated string') int_type = SdsType('intType', SdsTypeCode.Int32) double_type = SdsType('do...
e86d693ac1405b7f440065cbc5eced33adcc666f
3,643,508
import random def _spec_augmentation(x, warp_for_time=False, num_t_mask=2, num_f_mask=2, max_t=50, max_f=10, max_w=80): """ Deep copy x and do spec augmentation then return it ...
caa4a9010254e13be36e2359d7437cd9f2ced084
3,643,509
def deg2rad(x, dtype=None): """ Converts angles from degrees to radians. Args: x (Tensor): Angles in degrees. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the output Tensor. Returns: Tensor, the corresponding angle in radians....
9e7ff9f5242e5b2eede27b06eb7eb64ba84bbc69
3,643,510
import math def point_in_ellipse(origin, point, a, b, pa_rad, verbose=False): """ Identify if the point is inside the ellipse. :param origin A SkyCoord defining the centre of the ellipse. :param point A SkyCoord defining the point to be checked. :param a The semi-major axis in arcsec of the ellip...
9c4b056c205b8d25e80211adb0eeb1cdfaf4c11c
3,643,511
def isNumberString(value): """ Checks if value is a string that has only digits - possibly with leading '+' or '-' """ if not value: return False sign = value[0] if (sign == '+') or (sign == '-'): if len(value) <= 1: return False absValue = value[1:] ...
06feaab112e184e6a01c2b300d0e4f1a88f2250e
3,643,512
def vaseline(tensor, shape, alpha=1.0, time=0.0, speed=1.0): """ """ return value.blend(tensor, center_mask(tensor, bloom(tensor, shape, 1.0), shape), alpha)
75e61b21e9ffc1f13a8958ee92d0940596ae116b
3,643,513
from typing import Union from typing import Dict from typing import Any from typing import List def _func_length(target_attr: Union[Dict[str, Any], List[Any]], *_: Any) -> int: """Function for returning the length of a dictionary or list.""" return len(target_attr)
b66a883c763c93d9a62a7c09324ab8671d325d05
3,643,514
from typing import Optional def import_places_from_swissnames3d( projection: str = "LV95", file: Optional[TextIOWrapper] = None ) -> str: """ import places from SwissNAMES3D :param projection: "LV03" or "LV95" see http://mapref.org/CoordinateReferenceFrameChangeLV03.LV95.html#Zweig1098 :param...
cc90f3da95bf84ff3dd854de310a6690a28fd750
3,643,515
import logging def create_file_handler(log_file, handler_level, formatter=logging.Formatter(LOG_FORMAT_STRING)): """ Creates file handler which logs even debug messages. """ if handler_level == 'debug': level = logging.DEBUG elif handler_level == 'info': level = logging.INFO elif handler_level == 'warnin...
0c294fe8d6c7e831a4a567dc101f8cef4fe980d2
3,643,516
def _generate_data(size): """ For testing reasons only """ # return FeatureSpec('dummy', name=None, data='x' * size) return PlotSpec(data='x' * size, mapping=None, scales=[], layers=[])
62cbbe947b4d20726f24503c38b9ba2c5d8bdc82
3,643,517
def configuration_filename(feature_dir, proposed_splits, split, generalized): """Calculates configuration specific filenames. Args: feature_dir (`str`): directory of features wrt to dataset directory. proposed_splits (`bool`): whether using proposed splits. split (`str`): tr...
a3fc2c23746be7ed17f91820dd30a8156f91940c
3,643,518
import array def gammaBGRbuf( buf: array, gamma: float) -> array: """Apply a gamma adjustment to a BGR buffer Args: buf: unsigned byte array holding BGR data gamma: float gamma adjust Returns: unsigned byte array holding gamma adjuste...
2d32f2ae0f1aae12f2ed8597f99b5cd5547ea108
3,643,519
def sentence_avg_word_length(df, new_col_name, col_with_lyrics): """ Count the average word length in a dataframe lyrics column, given a column name, process it, and save as new_col_name Parameters ---------- df : dataframe new_col_name : name of new column col_with_lyric: co...
50dd7cb7145f5c6b39d3e8199f294b788ca361c0
3,643,520
def to_sigmas(t,p,w_1,w_2,w_3): """Given t = sin(theta), p = sin(phi), and the stds this computes the covariance matrix and its inverse""" p2 = p*p t2 = t*t tc2 = 1-t2 pc2 = 1-p2 tc= np.sqrt(tc2) pc= np.sqrt(pc2) s1,s2,s3 = 1./(w_1*w_1),1./(w_2*w_2),1./(w_3*w_3) a = pc2*tc2*s1 + t2*s...
e6144c8d3313e25cd701f703703309820c60032e
3,643,521
def fetch_atlas_pauli_2017(version='prob', data_dir=None, verbose=1): """Download the Pauli et al. (2017) atlas with in total 12 subcortical nodes. Parameters ---------- version: str, optional (default='prob') Which version of the atlas should be download. This can be 'prob' for th...
c7dbf85de92c143a221d91c3dd6f452a4d79ee2f
3,643,522
import traceback def GeometricError(ref_point_1, ref_point_2): """Deprecation notice function. Please use indicated correct function""" print(GeometricError.__name__ + ' is deprecated, use ' + geometricError.__name__ + ' instead') traceback.print_stack(limit=2) return geometricError(ref_point_1, ref_p...
aefd3a21ffa7123401af7ac2b106bc4efde624b5
3,643,523
def svn_fs_open2(*args): """svn_fs_open2(char const * path, apr_hash_t fs_config, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t""" return _fs.svn_fs_open2(*args)
433e8fe01d5b6c3c7b66f8caa3c50e8386e99e92
3,643,524
def config(workspace): """Return a config object.""" return Config(workspace.root_uri, {})
6d02a61f4653742b90838a773458944a581f8ed4
3,643,525
from typing import List from typing import Optional def longest_sequence_index(sequences: List[List[XmonQubit]]) -> Optional[int]: """Gives the position of a longest sequence. Args: sequences: List of node sequences. Returns: Index of the longest sequence from the sequences list. If more...
32aafa324daea819e48bc14516a8532c110c0362
3,643,526
def subset_raster(rast, band=1, bbox=None, logger=None): """ :param rast: The rasterio raster object :param band: The band number you want to contour. Default: 1 :param bbox: The bounding box in which to generate contours. :param logger: The logger object to use for this tool :return: A dict wit...
62bb0bc292fa2a9d09dc746ce329394cf9dd2fcb
3,643,527
def extract_date_features(df): """Expand datetime values into individual features.""" for col in df.select_dtypes(include=['datetime64[ns]']): print(f"Now extracting features from column: '{col}'.") df[col + '_month'] = pd.DatetimeIndex(df[col]).month df[col + '_day'] = pd.DatetimeIndex(...
8726cf0d160de11dfbad701d6a0c7fb3113691f6
3,643,528
import copy def record_setitem(data, attr, value): """Implement `record_setitem`.""" data2 = copy(data) py_setattr(data2, attr, value) return data2
52af700d8d282a411e37de83a7ddfab7f3b9de82
3,643,529
from typing import Optional def get_git_branch() -> Optional[str]: """Get the git branch.""" return _run("git", "branch", "--show-current")
dee21ab7e6d9800160e161ae32fad3f9c6c6a8fb
3,643,530
def open_image(path, verbose=True, squeeze=False): """ Open a NIfTI-1 image at the given path. The image might have an arbitrary number of dimensions; however, its first three axes are assumed to hold its spatial dimensions. Parameters ---------- path : str The path of the file to be lo...
217522c5ea45b9c1cbff8053dc9668cf5473c709
3,643,531
def add_one_for_ordered_traversal(graph, node_idx, current_path=None): """ This recursive function returns an ordered traversal of a molecular graph. This traversal obeys the following rules: 1. Locations may...
1c923d07c6ca57d47c900fd2cc05470c4a0eef86
3,643,532
import subprocess def get_kubeseal_version() -> str: """Retrieve the kubeseal binary version.""" LOGGER.debug("Retrieving kubeseal binary version.") binary = current_app.config.get("KUBESEAL_BINARY") kubeseal_subprocess = subprocess.Popen( [binary, "--version"], stdout=subprocess.PIPE,...
3301c18d3bbdf0c0f5cc4a0a98dddf4d7a25ad26
3,643,533
import json def get_subject_guide_for_section_params( year, quarter, curriculum_abbr, course_number, section_id=None): """ Returns a SubjectGuide model for the passed section params: year: year for the section term (4-digits) quarter: quarter (AUT, WIN, SPR, or SUM) curriculum_abbr: curri...
fe22c43685eb36e3a0849c198e6e5621e763b7a3
3,643,534
def dense_reach_bonus(task_rew, b_pos, arm_pos, max_reach_bonus=1.5, reach_thresh=.02, reach_multiplier=all_rew_reach_multiplier): """ Convenience function for adding a conditional dense reach bonus to an aux task. If the task_rew is > 1, this indicates that the actual task is complete, a...
ac1b53836a2a1fd9a4cf7c725222f0e053d65ddb
3,643,535
import re def getAllNumbers(text): """ This function is a copy of systemtools.basics.getAllNumbers """ if text is None: return None allNumbers = [] if len(text) > 0: # Remove space between digits : spaceNumberExists = True while spaceNumberExists: ...
42d45d6bb7a5ae1b25d2da6eadb318c3388923d6
3,643,536
def optimal_string_alignment_distance(s1, s2): """ This is a variation of the Damerau-Levenshtein distance that returns the strings' edit distance taking into account deletion, insertion, substitution, and transposition, under the condition that no substring is edited more than once. ...
9c05cfd3217619e76dd1e6063aa1aa689dc1a0ef
3,643,537
def test_sanitize_callable_params(): """Callback function are not serializiable. Therefore, we get them a chance to return something and if the returned type is not accepted, return None. """ opt = "--max_epochs 1".split(" ") parser = ArgumentParser() parser = Trainer.add_argparse_args(parent_p...
d2a553a3c347d5ef0a2be10b21af6920a50697fb
3,643,538
import six def get_url(bucket_name, filename): """ Gets the uri to the object. """ client = storage.Client() bucket = client.bucket(bucket_name) blob = bucket.blob(filename) url = blob.public_url if isinstance(url, six.binary_type): url = url.decode('utf-8') return url
15e2d5ae5cfdfeb9794c9cfef1feecbc0f1e4183
3,643,539
def distance(): """ Return a random value of FRB distance, choosen from a range of observed FRB distances. - Args: None. - Returns: FRB distance in meters """ dist_m = np.random.uniform(6.4332967e24,1.6849561e26) return dist_m
c38cfa7878020bafd9fa1cafef962ed2b91bc804
3,643,540
def p10k(n, empty="-"): """ Write number as parts per ten thousand. """ if n is None or np.isnan(n): return empty elif n == 0: return "0.0‱" elif np.isinf(n): return _("inf") if n > 0 else _("-inf") return format_number(10000 * n) + "‱"
6d0ff6e5b48c62ad10207c0f8a72595201042ef4
3,643,541
from typing import Any def output_file(filename: str, *codecs: Codec, **kwargs: Any) -> Output: """ A shortcut to create proper output file. :param filename: output file name. :param codecs: codec list for this output. :param kwargs: output parameters. :return: configured ffmpeg output. ""...
c467331d5a2773a014f52326872b7999bf17547c
3,643,542
import pkg_resources def selftest_validate_resilient_circuits_installed(attr_dict, **_): """ selftest.py validation helper method. Validates that 'resilient-circuits' is installed in the env and confirms that the version is >= constants.RESILIENT_LIBRARIES_VERSION :param attr_dict: (required) dic...
d500d2bea15e5ff54fe7830cd7bfef75c5041cd8
3,643,543
import warnings def convert_topology(topology, model_name, doc_string, target_opset, channel_first_inputs=None, options=None, remove_identity=True, verbose=0): """ This function is used to convert our Topology object defined in _parser.py into...
139efc34473518b0403cd0bdbfc85b0b2715d576
3,643,544
def _get_intermediates(func_graph): """Returns all tensors in `func_graph` that should be accumulated.""" # We currently accumulate output tensors of most ops in the function and rely # on the pruning pass to get rid of the unused accumulators at runtime. # However, this can bloat the GraphDef and make debuggin...
c0ee4b51524e1b4bf912d8293cc5490c4ae2c3b9
3,643,545
def multivariate_logrank_test(event_durations, groups, event_observed=None, alpha=0.95, t_0=-1, suppress_print=False, **kwargs): """ This test is a generalization of the logrank_test: it can deal with n>2 populations (and should be equal when n=2): H_0: all event series ...
2d433c4651828cc962a94802eae72e0ab68e7f0b
3,643,546
def ae(y, p): """Absolute error. Absolute error can be defined as follows: .. math:: \sum_i^n abs(y_i - p_i) where :math:`n` is the number of provided records. Parameters ---------- y : :class:`ndarray` One dimensional array with ground truth values. p : :c...
6f08799429c561af37a941e0678ba0c147ba3a9c
3,643,547
def create_masks_from_plane(normal, dist, shape): """ Create a binary mask of given size based on a plane defined by its normal and a point on the plane (in voxel coordinates). Parameters ---------- dist: Distance of the plane to the origin (in voxel coordinates). normal: Normal of the plan...
c6f3995a12aa98f960364332195ac5caeb1d6fe4
3,643,548
from typing import List def untokenize(tokens: List[str], lang: str = "fr") -> str: """ Inputs a list of tokens output string. ["J'", 'ai'] >>> "J' ai" Parameters ---------- lang : string language code Returns ------- string text """ d = MosesDetokenizer(l...
551ecf233b0869c4912b47ff1dee765647b07acc
3,643,549
import os def RSS_LABEL_TO_DIR(label_, is_html_): """Return the directory path to store URLs and HTML downloaded from RSS @param label_: the RSS label being crawled @param is_html_: True to return HTML directory and FALSE to return URLs directory """ bottom_dir_ = '/'.join(label_.split('-')...
099c91177c6cfcca50782009b2c99542410eff06
3,643,550
def unwrap_cachable(func): """ Converts any HashableNodes in the argument list of a function into their standard node counterparts. """ def inner(*args, **kwargs): args, kwargs = _transform_by_type(lambda hashable: hashable.node, HashableNode, *args,...
40b8f4b62045808815c67f0a22b4d8b97c9fbb1e
3,643,551
def tuples_to_full_paths(tuples): """ For a set of tuples of possible end-to-end path [format is: (up_seg, core_seg, down_seg)], return a list of fullpaths. """ res = [] for up_segment, core_segment, down_segment in tuples: if not up_segment and not core_segment and not down_segment: ...
f5b15e0e2483d194f6cf6c3eb8ec318aadd7b960
3,643,552
def _fileobj_to_fd(fileobj): """Return a file descriptor from a file object. Parameters: fileobj -- file object or file descriptor Returns: corresponding file descriptor Raises: ValueError if the object is invalid """ if isinstance(fileobj, int): fd = fileobj else: ...
8b1bea4083c0ecf481c712c8b06c76257cea43db
3,643,553
def request_changes_pull_request(pull_request=None, body_or_reason=None): """ :param pull_request: :param body_or_reason: :return: """ if not pull_request: raise ValueError("you must provide pull request") if not body_or_reason: raise ValueError("you must provide request ch...
6487b8b47a8a33882010083e97ebbd57b464311b
3,643,554
from typing import Callable from typing import Union from typing import Type from typing import Tuple def handle( func: Callable, exception_type: Union[Type[Exception], Tuple[Type[Exception]]], *args, **kwargs ): """ Call function with errors handled in cfpm's way. Before using this funct...
d290fa4353a6e608b21464c33adc6f72675d9e6c
3,643,555
def hrnetv2_w32(**kwargs): """ HRNetV2-W32 model from 'Deep High-Resolution Representation Learning for Visual Recognition,' https://arxiv.org/abs/1908.07919. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, defaul...
859642b2631457fd3fd8389370d2618666269ebe
3,643,556
from .utils.globalcache import c def medicare_program_engagement(): """ Produces a wide dataset at the NPI level that shows when a provider entered and exited the three different medicare databases: Part B, Part D, and Physician Compare """ partd = part_d_files(summary=True, ...
3a4bd0545473f229c8452680fc38c6ded2cb14bf
3,643,557
def _is_bumf(value): """ Return true if this value is filler, en route to skipping over empty lines :param value: value to check :type value: object :return: whether the value is filler :rtype: bool """ if type(value) in (unicode, str): return value.strip() == '' return val...
1812e82036ed4bdbdee4e2e032886ac2c788a5ff
3,643,558
from .perceptron import tag as tag_ from artagger import Tagger from .unigram import tag as tag_ def pos_tag(words, engine="unigram", corpus="orchid"): """ Part of Speech tagging function. :param list words: a list of tokenized words :param str engine: * unigram - unigram tagger (default) ...
8c8328950fba9082220d9c6be3b9fc8f9e6c3332
3,643,559
import warnings def derive(control): """ gui.derive will be removed after mGui 2.2; for now it's going to issue a deprecation warning and call `wrap()` """ warnings.warn("gui.derive() should be replaced by gui.wrap()", PendingDeprecationWarning) return wrap(control)
a2f463c9a66425e5066c504803b5754c2260cbc9
3,643,560
import base64 def hex_to_base64(hex_): """ Converts hex string to base64 """ return base64.b64encode(bytes.fromhex(hex_))
26f42b25c9e804bc1b786aadab033db104882f4b
3,643,561
def dt2iso(orig_dt): """datetime to is8601 format.""" return timeutils.isotime(orig_dt)
9887db04c4b3703a4f0c43c874c8d907cc744ea5
3,643,562
def catalog(access_token, user_id, query=None): # noqa: E501 """Query the list of all the RDF graphs&#x27; names (URIs) and the response will be JSON format. # noqa: E501 :param access_token: Authorization access token string :type access_token: dict | bytes :param user_id: the ID of the organiz...
f3819e76be5a1559f60140542d151de1f1b50b0e
3,643,563
import json def _make_chrome_policy_json(): """Generates the json string of chrome policy based on values in the db. This policy string has the following form: { "validProxyServers": {"Value": map_of_proxy_server_ips_to_public_key}, "enforceProxyServerValidity": {"Value": boolean} } Returns: ...
629450bc9bb0c2c0ce61b25568a4689b20c89766
3,643,564
def get_rgb_color(party_id): """Get RGB color of party.""" if party_id not in PARTY_TO_COLOR_OR_PARTY: return UNKNOWN_PARTY_COLOR color_or_party = PARTY_TO_COLOR_OR_PARTY[party_id] if isinstance(color_or_party, tuple): return color_or_party return get_rgb_color(color_or_party)
18585d46551e1a1646e28d4371d68537e94975ac
3,643,565
from datetime import datetime def view_application(application_id): """Views an application with ID. Args: application_id (int): ID of the application. Returns: str: redirect to the appropriate url. """ # Get user application. application = ApplicationModel.query.filter_by(i...
dda04250b45a1a166c254b48039155e85ca62ea3
3,643,566
import logging def build_save_containers(platforms, bucket) -> int: """ Entry point to build and upload all built dockerimages in parallel :param platforms: List of platforms :param bucket: S3 bucket name :return: 1 if error occurred, 0 otherwise """ if len(platforms) == 0: return ...
9744577efabbd800c16e9c7f57c9c7b31654cec1
3,643,567
def get_object_record(obj_key): """ Query the object's record. Args: obj_key: (string) The key of the object. Returns: The object's data record. """ record = None model_names = OBJECT_KEY_HANDLER.get_models(obj_key) for model_name in model_names: try: ...
c32bd3f12babc4f7c30567d6f2529dd037e3e563
3,643,568
def diff_cars(c1, c2): """ diffs two cars returns a DiffSet containing DiffItems that tell what's missing in c1 as compared to c2 :param c1: old Booking object :param c2: new Booking object :return: DiffSet (c1-c2) """ strategy = Differ.get_strategy(CAR_DIFF_STRATEGY) return str...
fda0e12bea0fd70fbed1a0e2c445941dc44f8cb7
3,643,569
import os def dist_env(): """ Return a dict of all variable that distributed training may use. NOTE: you may rewrite this function to suit your cluster environments. """ trainer_id = int(os.getenv("PADDLE_TRAINER_ID", "0")) num_trainers = 1 training_role = os.getenv("PADDLE_TRAINING_ROLE",...
1a7af4fbbea2e0d7e4e90bad770a5c68426689e9
3,643,570
import json def main(request, response): """Helper handler for Beacon tests. It handles two forms of requests: STORE: A URL with a query string of the form 'cmd=store&sid=<token>&tidx=<test_index>&tid=<test_name>'. Stores the receipt of a sendBeacon() request along with its validation r...
5d970bb10d689bb55f70cd841bd01501d88428c7
3,643,571
def calc_chi2(model, dof=None): """ Calculate chi-square statistic. Parameters ---------- model : Model Model. dof : int, optional Degrees of freedom statistic. The default is None. Returns ------- tuple chi2 statistic and p-value. """ if dof is Non...
46ed27fca1f36fdc8a044136da1ea4a032be1554
3,643,572
def QuadraticCommandAddControl(builder, control): """This method is deprecated. Please switch to AddControl.""" return AddControl(builder, control)
9b775f34400a0deeea93fd58a211915462735fed
3,643,573
def authenticated_api(username, api_root=None, parser=None): """Return an oauthenticated tweety API object.""" auth = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET) try: user = User.objects.get(username__iexact=username) sa...
82237d40b89ad860720ae3830fa37de76439a2be
3,643,574
def get_model_header(fpath): """ :param fpath: :return: """ with gz.open(fpath, 'rt') as modelfile: header = modelfile.readline().strip().strip('#').split() return header
bd3600d831d212821c160b994ea73c24ee04ce6d
3,643,575
def _parse_vertex(vertex_row): """Parses a line in a PLY file which encodes a vertex coordinates. Args: vertex_row: string with vertex coordinates and color. Returns: 2-tuple containing a length-3 array of vertex coordinates (as floats) and a length-3 array of RGB color values (as ints between 0 ...
cc8d7d59762464cf03f9caa8d057c690055c939c
3,643,576
def clean_tag(tag): """clean up tag.""" if tag is None: return None t = tag if isinstance(t, list): t = t[0] if isinstance(t, tuple): t = t[0] if t.startswith('#'): t = t[1:] t = t.strip() t = t.upper() t = t.replace('O', '0') t = t.replace('B', '8...
1d2709323c4d80f290701d5cdc3a993b4bac25d4
3,643,577
def massM2(param): """ Mass term in the neutrino mass basis. @type param : PhysicsConstants @param param : set of physical parameters to be used. @rtype : numpy array @return : mass matrix in mass basis. """ M2 = np.zeros([param.numneu,param.numneu],complex)...
38997454d308b4730e4eac5a764977fc72a6b373
3,643,578
import json def get_input_data(train_file_path='train.json', train=True): """Retrieves training (X) and label (y) matrices. Note that this can take a few seconds to run. Args: train_file_path is the path of the file containing training data. Returns: A tuple containing the X training mat...
5b42339917f0ec97ae584a03ba415881221e639c
3,643,579
def dice_coef(y_true, y_pred): """ :param y_true: the labeled mask corresponding to a mammogram scan :param y_pred: the predicted mask of the scan :return: A metric that accounts for precision and recall on the scale from 0 - 1. The closer to 1, the better. Dice = 2 * (...
e0f24abe29771f384e640e9e2f2420add040492f
3,643,580
def linmsg(x, end_pts_msg=None, max_msg=None, fill_value=1.e20): """ Linearly interpolates to fill in missing values. x = Ngl.linmsg(x,end_pts_msg=None,max_msg=None,fill_value=1.e20) x -- A numpy or masked array of any dimensionality that contains missing values. end_pts_msg -- how missing beginning and end points...
342abdc7536d8a1866c156cdc238e06338a20398
3,643,581
def get_or_create_actor_by_name(name): """ Return the actor corresponding to name if it does not exist, otherwise create actor with name. :param name: String """ return ta.ActorSystem().createActor(MyClass, globalName=name)
cc1ad620bc29139d6230e5a134ff72c3639a2bb1
3,643,582
def client(): """Client to call tests against""" options = { 'bind': '%s:%s' % ('0.0.0.0', '8080'), 'workers': str(number_of_workers()), } return testing.TestClient(falcon.API(), options)
3c075eb528e88a51a8f2c13e1197da6b2831197a
3,643,583
import math def hard_negative_mining(loss, labels, neg_pos_ratio=3): """ 用于训练过程中正负例比例的限制.默认在训练时,负例数量是正例数量的三倍 Args: loss (N, num_priors): the loss for each example. labels (N, num_priors): the labels. neg_pos_ratio: 正负例比例: 负例数量/正例数量 """ pos_mask = labels > 0 num_pos = p...
3b2e38ab2b0bbd9732fceafdfd023ea220b3c5eb
3,643,584
def groups(): """ Return groups """ return _clist(getAddressBook().groups())
16db4befa0863b15055fd7b557ecfefa8da55e20
3,643,585
def round_temp(value): """Round temperature for publishing.""" return round(value, dev_fan.round_temp)
39f7d5e55d0ba444b675b8ae612f5f38350af050
3,643,586
def get_key_from_property(prop, key, css_dict=None, include_commented=False): """Returns the entry from the dictionary using the given key""" if css_dict is None: css_dict = get_css_dict()[0] cur = css_dict.get(prop) or css_dict.get(prop[1:-1]) if cur is None: return None value = cu...
169a4369a8fc5cc9cfde18b302a308bafa1d4def
3,643,587
def bbox_area(gt_boxes): """ gt_boxes: (K, 4) ndarray of float area: (k) """ K = gt_boxes.size(0) gt_boxes_area = ((gt_boxes[:,2] - gt_boxes[:,0] + 1) * (gt_boxes[:,3] - gt_boxes[:,1] + 1)).view(K) return gt_boxes_area
57ad16b8b339e4515dcd7e7126b9c6b35b6c3d8b
3,643,588
def DecodedMessage(tG,x): """ Let G be a coding matrix. tG its transposed matrix. x a n-vector received after decoding. DecodedMessage Solves the equation on k-bits message v: x = v.G => G'v'= x' by applying GaussElimination on G'. ------------------------------------- Parameters: ...
47968c4feed23a32abbbf34da1bed4521689f3d2
3,643,589
def get_ttp_card_info(ttp_number): """ Get information from the specified transport card number. The number is the concatenation of the last 3 numbers of the first row and all the numbers of the second row. See this image: https://tarjetatransportepublico.crtm.es/CRTM-ABONOS/archivos/img/TTP.jpg :...
fc8fb31ae5daf17173567d53a9a122c3d8e11ca5
3,643,590
import re def tag_matches(tag, impl_version='trunk', client_version='trunk'): """Test if specified versions match the tag. Args: tag: skew test expectation tag, e.g. 'impl_lte_5' or 'client_lte_2'. impl_version: WebLayer implementation version number or 'trunk'. client_version: WebLayer implementatio...
dab3494063cd382615648d12d5dae03a47963af6
3,643,591
def split_params(param_string): """ Splits a parameter string into its key-value pairs >>> d = split_params('alpha-0.5_gamma-0.9') >>> d['alpha'] 0.5 >>> d['gamma'] 0.9 >>> d = split_params('depth-15_features-a-b-c') >>> d['depth'] 15 >>> d['features'] ['a', 'b', 'c'] >>> d = split_params('alpha-0.1_l-...
d6b1c8b381abe94c1022e1a474b353423e844f55
3,643,592
def load_suites_from_directory(dir, recursive=True): # type: (str, bool) -> List[Suite] """ Load a list of suites from a directory. If the recursive argument is set to True, sub suites will be searched in a directory named from the suite module: if the suite module is "foo.py" then the sub suites ...
5bb0c83ee39537b0bb38a663b110f5ef6225833e
3,643,593
def deep_parameters_back(param, back_node, function_params, count, file_path, lineno=0, vul_function=None, isback=False): """ 深层递归分析外层逻辑,主要是部分初始化条件和新递归的确定 :param isback: :param lineno: :param vul_function: :param param: :param back_node: :param function_para...
5cc5669a3c071d14b5d4898f60315da27e397a8b
3,643,594
from typing import Optional import re def get_latest_runtime(dotnet_dir: Optional[str] = None, version_major: Optional[int] = 5, version_minor: Optional[int] = 0, version_build: Optional[int] = 0) -> Optional[str]: """ Search and select the latest installed .NET Core runtime directory. ...
46db4e55163e6110d48264ed5ad4394662ade336
3,643,595
def choose_action(state, mdp_data): """ Choose the next action (0 or 1) that is optimal according to your current mdp_data. When there is no optimal action, return a random action. Args: state: The current state in the MDP mdp_data: The parameters for your MDP. See initialize_mdp_data. ...
2cb1f50a62ec006367fb61d8e57eb95005670e31
3,643,596
def get_formatted_reproduction_help(testcase): """Return url to reproduce the bug.""" help_format = get_value_from_job_definition_or_environment( testcase.job_type, 'HELP_FORMAT') if not help_format: return None # Since this value may be in a job definition, it's non-trivial for it to # include new...
c1cef28ae82e81e8c1814285dbe32e5d7ebe1ef6
3,643,597
import inspect def specialize_on(names, maxsize=None): """ A decorator that wraps a function, partially evaluating it with the parameters defined by ``names`` (can be a string or an iterable of strings) being fixed. The partially evaluated versions are cached based on the values of these parameters ...
218cb169661507124acf1dae8076fa47eb313f1a
3,643,598
def parse_docstring(docstring: str, signature) -> str: """ Parse a docstring! Note: to try notes. Args: docstring: this is the docstring to parse. Raises: OSError: no it doesn't lol. Returns: markdown: the docstring converted to a nice markdown text. """ ...
f831cda6046853312f6b0afe28683d3fc81dc874
3,643,599