content
stringlengths
22
815k
id
int64
0
4.91M
def LastAge(): """Age at which mortality becomes 1""" x = 0 while True: if BaseMortRate(x) == 1: return x x += 1
5,302,600
def putmask(a, mask, values): #, mode='raise'): """Set a.flat[n] = values[n] for each n where mask.flat[n] is true. If values is not the same size of a and mask then it will repeat as necessary. This gives different behavior than a[mask] = values. Note: Using a masked array as values will NOT tra...
5,302,601
def extensionName(path): """ Function responsible for returning the extension of a file. """ extension = os.path.splitext(path)[1][1:] return extension
5,302,602
def create_kubeconfig_for_ssh_tunnel(kubeconfig_file, kubeconfig_target_file): """ Creates a kubeconfig in which the Server URL is modified to use a locally set up SSH tunnel. (using 127.0.0.1 as an address) Returns a tuple consisting of: - the original IP/Servername of the K8s API ...
5,302,603
def binomial_distance(left: pandas.Series, right: pandas.Series) -> float: """ Based on the binomial calculations present in the original matlab scripts.""" # Find the mean frequency of each timepoint # index is timepoints, values are frequencies not_detected_fixed_df = pandas.concat([left, right], axis = 1) mean...
5,302,604
def sse_pack(d): """ Format a map with Server-Sent-Event-meaningful keys into a string for transport. Happily borrowed from: http://taoofmac.com/space/blog/2014/11/16/1940 For reading on web usage: http://www.html5rocks.com/en/tutorials/eventsource/basics For reading on the format: https://...
5,302,605
def parse_arguments(): """ Create command-line interface """ desc = "Compute dG, stdDG for different lengths and number of trajectories" parser = argparse.ArgumentParser(description=desc) parser.add_argument("-l", "--lagtime", type=int, default=100, help="Lagtimes to use, default 100") p...
5,302,606
def generate_upstream_solar(year): """ Generate the annual emissions. For solar panel construction for each plant in EIA923. The emissions inventory file has already allocated the total emissions to construct panels and balance of system for the entire power plant over the assumed 30 year l...
5,302,607
def handle_dns(packet, server_addr: str): """ Handle a captured DNS packet. :param packet: captured packet :param server_addr: address of server the packet originated from or was destined for :return: None """ print('Handling DNS packet') print_message(packet.summary())
5,302,608
def test_expected_param_behavior3(): """ Verify that we get the correct behavior when increasing the exponential power """ for model in (ZuMandelbaum16QuenchingCens(), ZuMandelbaum16QuenchingSats()): key = 'quenching_mass_' + model.gal_type testmass = np.copy(model.param_dict[key])*5 ...
5,302,609
def bootstrap_binom_err(k, n, CL=[0.025, 0.975], B=10000, type='percentile'): """ Bootstrap based binomial proportion confidence interval estimator. """ phat = k/n # Special case must be treated separately if k == 0: lower = 0 upper = 1 - (1-CL[1])**(1/n) # Special case must ...
5,302,610
def get_polar(img, msk, cent, r_max, r_min = 0, dr = 1, nPhi = None, dPhi = 1, msk_a = None, msk_w = None, plot = 0): """Returns cartesian images img & msk in polar coordinates pcimg[r,Phi] & pcmsk[r,Phi] @img Image in cartesian coordinates [nx,ny] @msk Mask in cartesian coor...
5,302,611
def aggregateTestSuite(doc, testsuite): """ Aggregate results for a particular test suite. """ # Iterate over all <testcase> tags. testcases = testsuite.getElementsByTagName('testcase') # This will hold a single instance of 'testcase' which will # represent multiple testcases within the inpu...
5,302,612
def get_logger(name=None): """Get a module for a submodule or the root logger if no name is provided""" return logging.getLogger(domain+'.'+name) if name else logging.getLogger(domain)
5,302,613
def smoke_test(): """ Simple smoke test """ #print "I am what I am and I am passing" parser = Parser() clouseau = Clouseau() ok_(True)
5,302,614
def AddAzureNodePoolResourceArg(parser, verb, positional=True): """Adds a resource argument for an Azure node pool. Args: parser: The argparse.parser to add the resource arg to. verb: str, the verb to describe the resource, such as 'to update'. positional: bool, whether the argument is positional or no...
5,302,615
def parse_rttm(rttm_path): """Parse audio and query pairs from *.rttm.""" # e.g. "LEXEME sws2013_12345 ... 3.50 1.00 sws2013_dev_123 ..." pattern = re.compile( r"LEXEME\s+(sws2013_[0-9]+).*?([0-9]\.[0-9]+)\s+([0-9]\.[0-9]+)" r"\s+(sws2013_(dev|eval)_[0-9]+)" ) query2audios = defaul...
5,302,616
def get_default_is_leaf_method(): """ returns default method for checking whether a tree should branch further or not ---- Returns ---- result : callable default method to check whether a tree node is a leaf or not """ return pure
5,302,617
def _separation_angles(katpt_catalogue, target, observer): """Calculate the separation angle between a target. and all the calibrators in the provided catalogue Parameters ---------- katpt_catalogue: katpoint.Catalogue target: ephem.FixedBody observer: ephem.Observer Returns -----...
5,302,618
def count(message): """Report on the current connections count. Slack has a limit on the number of concurrent Bot connections. Max: 17 Reference: https://github.com/slackapi/node-slack-sdk/issues/166 """ if (os.environ['TARGET_DEVICE'] != 'all' and os.environ['TARGET_DEVICE'] != device_...
5,302,619
def check_proto(host): """ Checks if port 22 or 23 is open, and returns open port number. """ check = socket.socket() response = check.connect_ex((host, 22)) if response == 0: return {'port': 22, 'name': 'ssh'} else: response = check.connect_ex((host, 23)) if response == 0: ...
5,302,620
def _touint64(num): """ This is required to convert signed json integers to unsigned. """ return num & 0xffffffffffffffff
5,302,621
def shuffle(images, targets, global_targets): """ A trick for CAN training """ sample_num = images.shape[1] for i in range(4): indices = torch.randperm(sample_num).to(images.device) images = images.index_select(1, indices) targets = targets.index_select(1, indices) gl...
5,302,622
def test_api_route(): """Simple test fixture that creates an ApiRoute object.""" ar = ApiRoute() yield ar
5,302,623
def _init_logging(level: str = 'INFO'): """" Initializes the Python logging Parameters: level (int): Optional - The level to which the logger will be initialized. Use any of the available logging.LEVEL values. If not specified, the default level will be set to logging.INFO """ ...
5,302,624
def update_signoffs(contact_id,signoffs,signoffs_ids_by_name): #pp.pprint(get_contacts_signoffs_by_email('bob@cogwheel.com')) """ how we do it in js wa_put_data = { 'Id' : this_contact_id , 'FieldValues' : [{ 'FieldName' : 'EquipmentSignoffs', ...
5,302,625
def test_expand_2d_short_array(): """ One of several _expand_?D tests. """ ary = np.array([[1., 2., 3.]]) val = np.array([1., 2., 3.]) exp2 = np.array([val * math.pow(1.02, i) for i in range(1, 5)]) exp1 = np.array([1., 2., 3.]) exp = np.zeros((5, 3)) exp[:1] = exp1 exp[1:] = exp...
5,302,626
def getValidTests(sourceTree): """ get the list of tests and make sure that the tests have all the required parameters. The returned list contains only those that have valid data """ tests = getSections() newTests = tests[:] # [main] is reserved for test suite parameters newTests....
5,302,627
def read_coords(file_name, base, prefix=""): """Read Ossian's input files with prefix indicating type""" res = {} with open(Path(base, file_name), 'r') as fid: nline = 0 for line in fid: nline += 1 if "=" in line: k, v = line.strip('\n').split("=") ...
5,302,628
def group_by_min_key(input_list): """ This function takes a list with tuples of length two inside: [(1,'a'),(1,'b'),('c',True),('d','x')] And return a dict with a list as value: {1:['a','b'], 'c': [True], 'd':['x']} The good thing about this function is that it will find the min key, a...
5,302,629
def get_mean_mask_location(mask): """ Args: - mask Returns: - coordinate of mean pixel location as (x,y) """ coords = np.vstack(np.where(mask == 1)).T return np.mean(coords, axis=0).astype(np.int32)
5,302,630
def get_base_path(base): """returns the path of a base URL if it contains one. >>> get_base_path('http://some.site') == '/' True >>> get_base_path('http://some.site/') == '/' True >>> get_base_path('http://some.site/some/sub-path') == '/some/sub-path/' True >>> get_base_path('http://som...
5,302,631
def debug_function(request): """ Minimal debug interface for the websocket :param request: current webservers reqquest :return: dict() """ LOG.debug("Preparing debug information for websocket") ui_locales = get_language_from_cookie(request) extras_dict = DictionaryHelper(ui_locales).pr...
5,302,632
def binomial_model_dynamicstrikes(T, S0, sigma, rf, custos, nome="teste", dpi=600, imagem=False, tkWindow=None): """ T = number of binomial iterations S0 = initial stock price sigma = factor change of upstate rf = risk free interest rate per annum K = exercise price """ global df glo...
5,302,633
def test_merge_sort_list_duplicates(): """Can sort list utilizing insertion sort method""" nums = [23, 1, 5, -69, 808, 808, -420, 33, 33, 1986] actual = merge_sort(nums) expected = [-420, -69, 1, 5, 23, 33, 33, 808, 808, 1986] assert actual == expected
5,302,634
def _make_annotation_lookup(db_links): """Make a lookup dictionary from a list of flat external DB links""" lookup = defaultdict(lambda: defaultdict(set)) for res in db_links: # skip old_bigg_id because it will be in notes if res[0] not in ['old_bigg_id', 'deprecated']: lookup[re...
5,302,635
def uniform(shape, dtype=None, min=-1.0, max=1.0, seed=0, name=None): """ This OP returns a Tensor filled with random values sampled from a uniform distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``. Examples: .. code-block:: text Input: shape = [1, 2] ...
5,302,636
def main(): """Main loop""" # initialize Arg-parser parser = argparse.ArgumentParser() # setup Arg-parser parser.add_argument( '-d', '--debug', type=int, help='Enable debug mode') parser.add_argument( '-r', '--raw', action="append", type=str, help='RAW Message') parser.add_a...
5,302,637
def get_lines_from_file(loc): """Reads the file and returns a list with every line. Parameters: loc (str): location of the file. Returns: list: list containing each of the lines of the file. """ f = open(loc) result= [line.replace("\n", "") for line in f] f.clo...
5,302,638
def get_path_from_request(request, path: str = None) -> str: """ Return current path from request, excluding language code """ if path is None: path = request.get_full_path() regex_match = language_code_prefix_re.match(path) if regex_match: lang_code = regex_match.group(1) ...
5,302,639
def test_rdf_detected_in_name(): """ The crawler should also detect rdf files if it encounters a file ending in the URL matching a known type. """ sys.stdout = open(os.devnull, 'w') expected_result = {'url': 'http://127.0.0.1:8080/mammals.rdf', 'opcode': 3, ...
5,302,640
def launch(service_id, project_id, every=EVERY): """ Initialize the module. """ return TutorialPrimitives(service_id=service_id, project_id=project_id, every=every)
5,302,641
def draw_keypoints(img_l, top_uvz, color=(255, 0, 0), idx=0): """Draw keypoints on an image""" vis_xyd = top_uvz.permute(0, 2, 1)[idx].detach().cpu().clone().numpy() vis = img_l.copy() cnt = 0 for pt in vis_xyd[:,:2].astype(np.int32): x, y = int(pt[0]), int(pt[1]) # cv2.circle(vis, (...
5,302,642
def polar_angle( snap: Union[SnapLike, Sinks], origin: Quantity = None, ignore_accreted: bool = False ) -> Quantity: """Calculate the polar angle. Parameters ---------- snap The Snap object. origin : optional The origin around which to compute the polar angle as a Quanti...
5,302,643
def fstring(c): """Pass the coefficients and return a string corresponding to the ploynomial""" order = len(c) fx = "$f(x) = x^%d" %(order) for n in xrange(order-1): nn = order - 1 - n fx += " + %1.3f x^%d" %(c[nn],nn) fx += " + %1.3f$" %(c[0]) return fx
5,302,644
def test_find_file_tmi(): """ Tests finding an TMI file for a given date. """ DATA_PATH = Path(__file__).parent / "data" l1c_path = DATA_PATH / "tmi" / "l1c" date = np.datetime64("2010-01-01T01:00:00") l1c_file = L1CFile.find_file(date, l1c_path, sensor=sensors.TMI) data = l1c_file.to_xa...
5,302,645
def build(input_reader_config, model_config, training, voxel_generator, target_assigner=None): """Build a dataset""" generate_bev = model_config['use_bev'] without_reflectivity = model_config['without_reflectivity'] num_point_features = model_config['num_point_fea...
5,302,646
def Rotation_EQJ_GAL(): """Calculates a rotation matrix from equatorial J2000 (EQJ) to galactic (GAL). This is one of the family of functions that returns a rotation matrix for converting from one orientation to another. Source: EQJ = equatorial system, using the equator at the J2000 epoch. Target:...
5,302,647
def query_copernicus_hub(aoi, username, password, hub, **kwargs): """Query Copernicus Open access Hub. :param aoi: (str) Geojson Area of interest url :param username: (str) Username to use for API connection :param password: (str) Password to use for API connection :param hub: (str) Url of hub to q...
5,302,648
def streaming_input_type_check(data: Iterable) -> None: """ Ensure input data is an iterable, but not a string or bytes. Raises `TypeError` if not. """ if not hasattr(data, '__iter__') or isinstance(data, (str, bytes)): raise TypeError("Input data must be a non-string iterable object.")
5,302,649
def delete_password(key): """Deletes the given password from the database. Returns True if the password was deleted.""" from saq.database import get_db_connection with get_db_connection() as db: c = db.cursor() c.execute("DELETE FROM `encrypted_passwords` WHERE `key` = %s", (key,)) d...
5,302,650
def _docker_compose_insecure( *, docker_compose_files: List[str], scale_factor: int, tmp_path_factory: TempPathFactory, ) -> Generator[List[Path], None, None]: """ Provides the location of the docker-compose configuration file containing the insecure docker GIT service. """ cache_key = _...
5,302,651
def StandardMols(mols, n_jobs=1): """ """ mols = mols if type(mols) is not Chem.rdchem.Mol else [mols] n_jobs = n_jobs if n_jobs>=1 else None pool = Pool(n_jobs) sm = pool.map_async(StandardMol, mols).get() pool.close() pool.join() return sm
5,302,652
def af_to_maf(af): """ Converts an allele frequency to a minor allele frequency Args: af (float or str) Returns: float """ # Sometimes AF == ".", in these cases, set to 0 try: af = float(af) except ValueError: af = 0.0 if af <= 0.5: return af ...
5,302,653
def test_non_issue2_bang(): """ Test issue """ inp = (b'if (Y) { ba=Math.max(ba, Math.round(W.minHeight/Y))}; ' b'bo.setKnobFactor((bp.width===0)? 0: br.width /bp.width);') exp = (b'if(Y){ba=Math.max(ba,Math.round(W.minHeight/Y))};' b'bo.setKnobFactor((bp.width===0)?0:br.width/bp.width...
5,302,654
def generate_nnet(feats): """Generate a neural network. Parameters ---------- feats : list with at least one feature vector Returns ------- Neural network object """ # Load it here to prevent crash of --help when it's not present from lasagne import layers from nolearn.lasa...
5,302,655
def sleep(retcode=0, time=SLEEP_TIME): """ Sleep for {time} seconds & return code {retcode} """ return [ sys.executable, '-c', 'import sys, time; time.sleep({}); sys.exit({})'.format(time, retcode) ]
5,302,656
def validate_auth(config: ConfigType) -> ConfigType: """Validate presence of CONF_ACCESS_TOKEN when CONF_DEVICE_CLASS=tv.""" token = config.get(CONF_ACCESS_TOKEN) if config[CONF_DEVICE_CLASS] == "tv" and not token: raise vol.Invalid( f"When '{CONF_DEVICE_CLASS}' is 'tv' then '{CONF_ACCES...
5,302,657
def print_table_migration_ddl(source_table, target_table): """ Prints DDL to migrate a table in one schema to the structure in another schema, including columns, constraints, indexes, triggers and permissions. N.B. The migration does not enforce identical column ordering. :param source_table: ...
5,302,658
def generateFile(data, filename): """Write all the passed in data to a file""" snOut = open(filename, "w") for i in range(0, len(data)): snOut.write(data[i]) snOut.close() # End generateFile()
5,302,659
def show_questions(player): """ Display available questions of player """ print(LINE) print(f"{' '*70}[HUMAN PLAYER'S AVAILABLE QUESTIONS]{' '*75}") print(LINE) for question in player.questions: print(f"[{question['id']}] {question['question']}") print(LINE)
5,302,660
def GetBuildShortBaseName(target_platform): """Returns the build base directory. Args: target_platform: Target platform. Returns: Build base directory. Raises: RuntimeError: if target_platform is not supported. """ platform_dict = { 'Windows': 'out_win', 'Mac': 'out_mac', 'Li...
5,302,661
def build_B_from_A(A, nodes=None): """ Create the numpy adjacency tensor of a networkX graph. Parameters ---------- A : list List of MultiDiGraph NetworkX objects. nodes : list List of nodes IDs. Returns ------- B : ndarra...
5,302,662
def get_sort_order(ds_spec): """ Find how quickly the spectroscopic values are changing in each row and the order of rows from fastest changing to slowest. Parameters ---------- ds_spec : 2D HDF5 dataset or numpy array Rows of indices to be sorted from fastest changing to slowest R...
5,302,663
def test_basic(norm): """ Test basic normalisation """ iplist = ('192.0.2.5', '198.51.100.128', '198.51.100.5', '2001:db8:fab::/64', '203.0.113.7') for ip in iplist: res = norm.normal(ip) assert res == ip
5,302,664
def generate_error(request, cls, e, tb, include_traceback=False): """ Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the last traceback and the request that was sent. """ import traceback if hasattr(cls, '_amf_code'): code = cls._amf_code else: code = ...
5,302,665
def reads(text, ext, format_name=None, rst2md=False, as_version=4, **kwargs): """Read a notebook from a string""" if ext == '.ipynb': return nbformat.reads(text, as_version, **kwargs) format_name = read_format_from_metadata(text, ext) or format_name if not format_name: format...
5,302,666
def test_dependencies_case_2(mocker, repo): """ Given - Content repo with the following items: -"foo" pack containing: - integration_foo which is a feed integration - "bar" pack containing: - mapper_in_bar - integration_foo using: ...
5,302,667
def make_wildcard(title, *exts): """Create wildcard string from a single wildcard tuple.""" return "{0} ({1})|{1}".format(title, ";".join(exts))
5,302,668
def extract_clear(field, tab, mag_lim=None): """ Extracts all sources given in tab from the given field. ** Step 3. of Interlace steps. ** Parameters ---------- field : string The GOODS field to process. tab : dictionary Values for each source read from catalog. mag_lim : ...
5,302,669
def _getFields(qset=None, model=None): """ returns a list of fields for specified QuerySet or Model """ if hasattr(qset, '_meta') and getattr(qset, '_meta') != None: fields = qset._meta.fields elif hasattr(qset, 'model') and getattr(qset, 'model') != None: fields = qset.model._meta.f...
5,302,670
def test_zone_delete_function(): """Zone delete function sends properly formated request.""" response = zone.delete(domain_name='example.com') assert response.success payload = response.payload assert payload['url'] == 'https://api.cloudns.net/dns/delete.json' assert payload['params']['domain-n...
5,302,671
def dir_files(path, pattern="*"): """ Returns all files in a directory """ if not isinstance(path, Path): raise TypeError("path must be an instance of pathlib.Path") return [f for f in path.glob(pattern) if f.is_file()]
5,302,672
def fix_while_loop(x): """Change Javascript for loop to Python for loop for(var i = 0fi < x.length;i++){" --> "for i in range(0,len(x),1): Args: x (str): A string with Javascript syntax. Returns: [str]: Python string Examples: >>> from ee_extra import fix_for_loop ...
5,302,673
def test_list_int_max_length_1_nistxml_sv_iv_list_int_max_length_2_4(mode, save_output, output_format): """ Type list/int is restricted by facet maxLength with value 6. """ assert_bindings( schema="nistData/list/int/Schema+Instance/NISTSchema-SV-IV-list-int-maxLength-2.xsd", instance="ni...
5,302,674
def io_connection_pattern(inputs, outputs): """Return the connection pattern of a subgraph defined by given inputs and outputs.""" inner_nodes = io_toposort(inputs, outputs) # Initialize 'connect_pattern_by_var' by establishing each input as # connected only to itself connect_pattern_by_var = {} ...
5,302,675
def parse_args(args=None): """Parse arguments from sys.argv""" parser = argparse.ArgumentParser() parser.add_argument( '-w', '--window', default="pyqt5", choices=find_window_classes(), help='Name for the window type to use', ) parser.add_argument( ...
5,302,676
def test_single_thread_single_trace(tracer): """ Ensure a simple trace doesn't leak span objects. """ wd = WeakValueDictionary() with trace(wd, tracer, "span1"): with trace(wd, tracer, "span2"): pass # Spans are serialized and unreferenced when traces are finished # so g...
5,302,677
def pool_forward(A_prev, hparameters, mode = "max"): """ Implements the forward pass of the pooling layer. Parameters: ----------- A_prev: tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) Input data. hparameters: dictionary Contains "f" and "stride". ...
5,302,678
def myDownsample(y, N) : """ yds = myDownsample(y,N) yds is y sampled at every Nth index, starting with yds[0]=y[0] with y[range(0,len(y),N)]. Implementing Matlab's downsample. Ted Golfinopoulos, 7 June 2012 """ return y[range(0,len(y),N)]
5,302,679
def compose (composite_property_s, component_properties_s): """ Sets the components of the given composite property. All parameters are <feature>value strings """ from . import property component_properties_s = to_seq (component_properties_s) composite_property = property.create_from_s...
5,302,680
def add_zip_file_contents_to_resource(pk, zip_file_path): """Add zip file to existing resource and remove tmp zip file.""" zfile = None resource = None try: resource = utils.get_resource_by_shortkey(pk, or_404=False) zfile = zipfile.ZipFile(zip_file_path) num_files = len(zfile.in...
5,302,681
def _norm_args(norm): """ Returns the proper normalization parameter values. Possible `norm` values are "backward" (alias of None), "ortho", "forward". This function is used by both the builders and the interfaces. """ if norm == "ortho": ortho = True normalise_idft = Fals...
5,302,682
def LoadConfigDict(config_paths, model_params): """Loads config dictionary from specified yaml files or command line yaml.""" # Ensure that no duplicate keys can be loaded (causing pain). yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, NoDuplicatesConstructor) # Han...
5,302,683
def get_next_point_in_trace(trace: LineString, point: Point) -> Point: """ Determine next coordinate point towards middle of LineString from point. """ coord_points = get_trace_coord_points(trace) assert point in coord_points if point == coord_points[-1]: return coord_points[-2] if p...
5,302,684
def reduced_quantity(a_quantity, b_quantity): """ Returns the reduced mass of two particles. Examples: ``` >>> reduced_quantity(1*u.kg, 1*u.kg) <Quantity(0.5, 'kilogram')> >>> reduced_quantity(1*u.kg, 20*u.kg).m 0.9523809523809523 >>> reduced_quantity(1, 200)...
5,302,685
def test_search_text_with_ambiguous_word_classes(): """ Results of all word classes should be searched when the query is ambiguous """ # pipon can be viewed as a Verb as well as a Noun results = search(query="pipon").presentation_results() assert { r.lemma_wordform.paradigm for r in resu...
5,302,686
def test_camera_fit_isometric(device_): """Test that fit works with the isometric option.""" scene = fresnel.Scene() fresnel.geometry.Sphere(scene, position=[[-9, -2, 0], [-5, -1, 0], [4, 0, 0], [2, 1, 0]], radius...
5,302,687
def expected_value(values, state, action, discount=0.9): """Calculate expected value for a given action :param state: state which value is updated :type state: tuple :param action: action taken in this state :type action: int :param discount: discount :type discount: float :return: new ...
5,302,688
def tf(*args, **kwargs): """ Create a transfer function model of a system. :param args: pass in num :type args: TransferFunction | List[numbers.Real] | numbers.Real :return: the transfer function of the system :rtype: TransferFunction :Example: >>> from tcontrol imp...
5,302,689
def _list_(): """\tlist installed packeges""" os.system('python -m pip list')
5,302,690
def all_pair_iou(boxes_a, boxes_b): """ Compute the IoU of all pairs. :param boxes_a: (n, 4) minmax form boxes :param boxes_b: (m, 4) minmax form boxes :return: (n, m) iou of all pairs of two set """ N = boxes_a.size(0) M = boxes_b.size(0) max_xy = torch.min(boxes_a[:, 2:].unsqueeze...
5,302,691
def nint(element): """Rounds the number to the nearest integer value. Passed element argument can be integer, real, Array, or list. Depends on the types of passed element, the return type may vary. """ raise TypeError(f"<nint> unhandled type: {type(element)}")
5,302,692
def get_matching_list_from_graph(graph): """ :param graph: nx.Graph(); each edge should have an attribute "color" :return: List of matching; each matching is an nx.Graph() representing a sub-graph of "graph" """ degree = get_graph_degree(graph) colors = [i for i in range(degree + 1)] ...
5,302,693
def remove_zeros(res_array): """ Erase all zeros in res_array and return (reduced) array without zeros. Parameters ---------- res_array : np.array Numpy results array Returns ------- res_no_zeros : np.array Numpy results array without zeros (shorter than res_array, if z...
5,302,694
def butter_lowpass(cutoff, fs, order=5): """ This is based on butter_bandpass """ nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = ssig.butter(order, normal_cutoff, btype="low", analog=False) return b, a
5,302,695
def instantaneous_phase_shift(analytic_sig, time_vect, carrier_frequency): """ For a signal $x(ray) = A * exp(i (2 pi f_0 ray + phi(ray)))$, returns phi(ray) in [-pi, pi[. Parameters ---------- analytic_sig: ndarray time_vect: ndarray carrier_frequency: float Returns ------- ph...
5,302,696
def run( config_path: Path = Argument( default="brood.yaml", metavar="config", exists=True, readable=True, show_default=True, envvar="BROOD_CONFIG", help="The path to the configuration file to execute.", ), verbosity: Verbosity = Option( Verbos...
5,302,697
def assert_lengths_equal(*args): """Throws a value error if input lists have different lengths""" if len({len(arg) for arg in args}) > 1: raise ValueError("Input lists must be same length")
5,302,698
def get_p0_gaussian(x, y): """Estimate (x0, dV, Tb) for the spectrum.""" if x.size != y.size: raise ValueError("Mismatch in array shapes.") Tb = np.max(y) x0 = x[y.argmax()] dV = np.trapz(y, x) / Tb / np.sqrt(2. * np.pi) return x0, dV, Tb
5,302,699