content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import OrderedDict def apply_address_fixups(address: OrderedDict[str, str]) -> OrderedDict[str, str]: """Sometimes the usaddress parser makes mistakes. It's an imperfect world. This function applies transformations to the parsed address to correct specific known errors. """ # Fixup: At...
735f7e035b352b21b9b7998b8aa6f5ad7ac826d7
3,621,000
import logging def validate_args(args): """ Validate that arguments are valid. :param args: An arguments namespace. :type args: :py:class:`argparse.Namespace` :return: The validated namespace. :rtype: :py:class:`argparse.Namespace` """ level = V_LEVELS.get(args.verbose, logging.DEBUG)...
fb55ad24baac924d9a45ddcc760837f78ec23ec0
3,621,001
def get_slaves(): """Get the list of slave nodes""" slaves = range(mpi_comm.Get_size()) slaves.remove(mpi_master) return slaves
c255a0068b354ef6d385299ad581bb61999736f1
3,621,002
def _max(arr, axis = 0): """The max function. Args: arr -- The array. axis -- The axis (0 by default) Returns: The max value along the axis. """ return extrema(max, arr, axis)
fbe78449f945f22dc78cfff9ad2169e0f8029982
3,621,003
import socket def _get_results_socket(): """Instantiate the results socket for sending binary results.""" client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) sock = '/_abaco_results.sock' try: client.connect(sock) except (FileNotFoundError, ConnectionError) as e: msg = "Excep...
76cea0132285d44a4bc21fcea84a75e8acf408a7
3,621,004
import torch def mask_finished_scores(score, flag): """ If a sequence is finished, we only allow one alive branch. This function aims to give one branch a zero score and the rest -inf score. Args: score: A real value array with shape [batch_size * beam_size, beam_size]. flag: A bool ar...
87d5d8fb45a44c54cd690280ce0baf0c4fe8dab5
3,621,005
from typing import Dict from typing import Any def get_user(url: str, access_key: str) -> Dict[str, Any]: # pylint: disable=unused-argument """Execute the OpenAPI `GET /v1/users`. Arguments: url: The URL of the graviti website. access_key: User's access key. Returns: The respons...
7b54fb5950aa1c0d69305cd8e1a8b14b81c7bb99
3,621,006
def streamers_alter_workers(streamers): """ Alter the number of workers currently in a cluster RouteParams: """ streamers = int(streamers) account = request.form['account'] user = request.form['user'] spot = request.form.get('spot') is not None if streamers != 1 and streamers != ...
836c60e1d28a031abcdd50b4ff5c6af733e14292
3,621,007
def get_default_scaler(model_type): """ Get default values for scaler in and output for each model. Args: model_type (str): Model identifier. Returns: Dict: Scaling dictionary. """ if model_type == 'mlp_e': return EnergyStandardScaler() elif model_type == 'mlp_eg':...
da5a116db83e90687de5cf74bb346e87c7473c4a
3,621,008
from sys import path def read(file_name: str) -> str: """Helper to read README.""" this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, file_name), encoding="utf-8") as f: return f.read()
ba7db7ee74c5ae5ed0f77a9a9ce5a8249c19a4cf
3,621,009
import numbers def get_correlation(arg1,arg2=None): """Return correlation The input arguments may be a pair of uncertain numbers, or a single uncertain complex number. When a pair of uncertain real numbers is provided, the correlation between the arguments is returned as a real nu...
7ee642b247cf6b5daeb61f614ad503ef75c29224
3,621,010
from datetime import datetime def _extractDicomMetadata_old(dcmdata, water_suppressed=True): """ Extract information from the nibabel DICOM object to insert into the json header ext. Args: dcmdata: nibabel.nicom image object Returns: obj (hdr_ext): NIfTI MRS hdr ext object. """ #...
08816d5caac2a9c1043a499ac8b5ef1506bd32b4
3,621,011
def rotmat2d(theta: float) -> np.ndarray: """Convert angle `theta` (in radians) to a 2x2 rotation matrix.""" s = np.sin(theta) c = np.cos(theta) R = np.array([[c, -s], [s, c]]) return R
64550e94ef7c31263a0a4e453b14f6d17016dfd8
3,621,012
def Vector(size, dtype='float32', name=None): # pylint: disable=invalid-name """A block that converts its input to a vector.""" return Tensor(shape=[size], dtype=dtype, name=name).set_constructor_name( 'td.Vector')
63299f889274e68f3431fc59e451cc02c88bb7f0
3,621,013
from typing import Sequence from typing import List def render_correlation_single_heatmaps( itmdt: Intermediate, plot_width: int, plot_height: int, palette: Sequence[str] ) -> Tabs: """ Render correlation heatmaps, but with single column """ tabs: List[Panel] = [] tooltips = [("y", "@y"), ("co...
73c3704c0c05883a0354d33ea77cc28253e066fd
3,621,014
def get_blocks(text): """ Get a traversed README doctree Args: text: Text of the example's README Returns: Returns an iterable containing the README document structure See `traverse` implementation in docutils/nodes.py for more details. """ doctree = publish_doctree(text) ...
a5e193c6b3313a0951201b66bffa41f1210b5954
3,621,015
from pathlib import Path import os def get_feature_geojson(features): """convert input clip_features to list of clip_features in the geojson format. Parameters ---------- features : str (shapefile path) or list of clip_features If clip_features is a list, the clip_features can be in shape...
ff1c22a6649cafdf629ea37312a47145108bce0d
3,621,016
import itertools def args_combinations(*args, **kwargs): """ Given a bunch of arguments that are all a set of types, generate all possible possible combinations of argument type args is list of type or set of types kwargs is a dict whose values are types or set of types """ def asset(v): ...
8e90ce285322bd17a97e4bdb75e230f7015f4b2d
3,621,017
import copy def coordinate_tensor(dim): """ :param dim: list of lengths for each dimension :return: a list of every possible coordinate within the dimension system """ # recurrent function def recurrent_dim_filler(dim_current, dim_higher, coordinate_higher, coordinates): # processing...
8a5e2f11b5157cb2500748ea149305a21b562b77
3,621,018
from typing import Optional from typing import Collection def get_relation_injectivity_df( *, dataset: Dataset, parts: Optional[Collection[str]] = None, add_labels: bool = True, ) -> pd.DataFrame: """ Calculate "soft" injectivity scores for each relation. :param dataset: The datas...
01e37769d2c63f7c75d130e3bf825750e2580937
3,621,019
def vimeval(cmd, to_int=0): """ :to_int: 0 for original 1 for int 2 for float """ r = vim.eval(cmd) if to_int == 0: return r if to_int == 1: return int(r) return float(r)
9a4aa37c58f99261cea95e290f620885ae27d567
3,621,020
def RGBStringToList(rgb_string): """Convert string "rgb(red,green,blue)" into a list of ints. The purple air JSON returns a background color based on the air quality as a string. We want the actual values of the components. Args: rgb_string: A string of the form "rgb(0-255, 0-255, 0-255)". Returns: ...
f94650ed977b5a8d8bb85a37487faf7b665f2e76
3,621,021
def preprocessing(df, deduplicate=False): """ Split the `sen_tok` column into sentence ID (combined with note ID) and token ID. If the `deduplicate` parameter is True, duplicate notes are removed. """ if deduplicate: df = deduplicate_notes(df) return df.assign( sen_id = lambda df...
a59dbd42d10cd7a141084b0018006f9041a5dad0
3,621,022
def get_files_involved_in_pr(repo, pr_number): """ Return a list of file names modified/added in the PR """ headers = {"Accept": "application/vnd.github.VERSION.diff"} query = f"/repos/{repo}/pulls/{pr_number}" r = utils.query_request(query, headers=headers) patch = unidiff.PatchSet(r.cont...
01a051eed32ea3fb3c566eb7167f5628d698580b
3,621,023
def csv(file_path): """Read CSV file, return DataFrame""" return pd.read_csv(file_path)
5cdeb33eae908699d1ade6e5688e171236254d95
3,621,024
import six def _metric_value(value_str, metric_type): """ Return a Python-typed metric value from a metric value string. """ if metric_type in (int, float): try: return metric_type(value_str) except ValueError: raise ValueError("Invalid {} metric value: {!r}". ...
39a3b0e5bfe2180e1897dd87872f8e08925e8847
3,621,025
def point_sample_raster(gdf, rds, win_radius=0, stat_func=np.mean, col_names=None): """ Sample all bands of a raster data set `rds`, and attribute each point of a geopandas GeoDataFrame `gdf`. A radius value can be supplied to sample the mean of a square window rather than individual pixels. Parame...
7672bf4a9937c3d1955402e3a1cdd8caa8353ead
3,621,026
def vol_spherical_cap(height: float, radius: float) -> float: """ Calculate the Volume of the spherical cap. :return 1/3 pi * height ^ 2 * (3 * radius - height) >>> vol_spherical_cap(1, 2) 5.235987755982988 """ return 1 / 3 * pi * pow(height, 2) * (3 * radius - height)
cc07575f2f98cf21ecae5b6ca9a4dd669ff83722
3,621,027
def im2col(input_data, filter_h, filter_w, stride=1, pad=0): """ Parameters ---------- input_data : (データ数, チャンネル, 高さ, 幅)の4次元配列からなる入力データ filter_h : フィルターの高さ filter_w : フィルターの幅 stride : ストライド pad : パディング Returns ------- col : 2次元配列 """ N, C, H, W = input_data.shape ...
656b7ff1875cef679ea08a04f5df7cd644a06aaf
3,621,028
def generate_g(b, d, p, q): """Compute a generator of a subgroup of Z^*_n that has order b**d mod p and order b**d mod q""" rs = PRNG() b_to_the_d = b ** d while True: x = rs.random_Zsp(p) if gmpy2.powmod(x, mpz((p-1)/b), p) != 1: gp = gmpy2.powmod(x, mpz((p-1)/b_to_the_d...
29ff505e932e46075b35ce004a752ef572742914
3,621,029
def load_runner( tag: t.Union[str, Tag], name: t.Optional[str] = None, resource_quota: t.Optional[t.Dict[str, t.Any]] = None, batch_options: t.Optional[t.Dict[str, t.Any]] = None, model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> "_PyFuncRunner": """ Runner represents a...
2ac4f43a9be98327995e05fbee93a71464c476bc
3,621,030
def get_html(url): """抓取传入url页面并返回html""" try: with sync_playwright() as p: disable_warnings() # 禁用安全请求警告 browser = p.webkit.launch() # 启用webkit浏览器访问 page = browser.new_page() page.goto(url) page.wait_for_timeout(3000) # 等待网页加载 h...
79c57ef4f0e8f8e1c5711ff09f2eca2b35b26782
3,621,031
import threading def in_main_thread(): """ True when the current thread is the main thread. """ return threading.current_thread().__class__.__name__ == '_MainThread'
82da352928b2af3794a2ee608b2763b98b8a731e
3,621,032
import math def itmlogic_p2p(main_user_defined_parameters, surface_profile_m): """ Run itmlogic in point to point (p2p) prediction mode. Parameters ---------- main_user_defined_parameters : dict User defined parameters. surface_profile_m : list Contains surface profile measure...
8da9c1765112c58494bfd5cc0e139735ae79b93a
3,621,033
def get_commit_messages(starting_version: str, ending_version: str = "HEAD"): """Get the commit messages from the current git branch. Depends on `git`. Args: starting_version (str): Starting version number, not included in the results ending_version (str): Ending version number, defaults t...
d732ab3f0ee112cf443389485c7f3aa2cbb663e5
3,621,034
import os def compute_results(ann_inter, est_inter, ann_labels, est_labels, bins, est_file, weight=0.58): """Compute the results using all the available evaluations. Parameters ---------- ann_inter : np.array Annotated intervals in seconds. est_inter : np.array ...
12f5106ca5e089db8d18e47a40064d777a99f124
3,621,035
def gsl_blas_ssyrk(*args, **kwargs): """ gsl_blas_ssyrk(CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, float alpha, gsl_matrix_float A, float beta, gsl_matrix_float C) -> int """ return _gslwrap.gsl_blas_ssyrk(*args, **kwargs)
19940170fa090ce7fc642c975ea4b887f66e25e4
3,621,036
import os def get_ages(location, country, level, num_agebrackets=85): """ Get the age count for the synthetic population of the location. Args: location (str) : name of the location country (str) : name of the country level (str) : name of level (country o...
00461ac6d462848033b89b71147f9a84b019d415
3,621,037
def address_to_string(b): """Converts an IP address to its string representation. Takes a 4-byte string representing an IP address, and returns a dot-separated decimal representation on the form '123.123.123.123'. """ assert len(b) == 4 b = map(lambda x: str(_decode_byte(x)), b) return '.'...
b22ce9550d9cc7e8354409fc177af27bf87d6dfe
3,621,038
from ..description import WidgetDescription, CategoryDescription from .. import WidgetRegistry def small_testing_registry(): """Return a small registry with a few widgets for testing. """ registry = WidgetRegistry() data_desc = CategoryDescription.from_package("Orange.widgets.data") file_desc =...
99edfa086145e8500383c9b6cf151d8c748c19c2
3,621,039
def fixUnits(object, **kwargs): """Convert output pint units into a proper latex string.""" string = str(object) type = kwargs.get('type', None) unitColor = 'darkBlue' replacements = kwargs.get('replacements', None) if replacements: for old, new in replacements.items(): str...
a1922f296a7d55b989fe5455ed98eb166edeeee7
3,621,040
def get_schema_for_macro_definition(schema): """Return a schema with macro definition directives added in. Preconditions: 1. All compiler-supported and GraphQL-default directives have their default behavior. This returned schema can be used to validate macro definitions, and support GraphQL macro ...
d46d3d0bed4858110fee55e0afb2a058c4b1e0ee
3,621,041
def rect(r, w, deg=False): """ Convert from polar (r,w) to rectangular (x,y) x = r cos(w) y = r sin(w) """ # radian if deg=0; degree if deg=1 if deg: w = np.pi * w / 180.0 return r * np.cos(w), r * np.sin(w)
4b0fee6964dd5d5041a5719a370d77c4a4d7d1ee
3,621,042
from typing import Optional def get_account_ssh_key(name: Optional[str] = None, ssh_key_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAccountSshKeyResult: """ Use this data source to get SSH key information based on its ID...
6ffcef6079c5b72df1474e00149ee42b80fc3a04
3,621,043
def map_l2dist_sinhnormalmech_tCDP(sensitivity, scale, A): """map via the sinhnormal mechanism an L2 distance `sensitivity` with parameters `scale` and `A` to (rho, omega)-tCDP """ rho = (sensitivity / scale) ** 2 / 2 assert 1 < 1 / np.sqrt(rho) <= A / sensitivity return 16 * rho, A / (8 * sen...
8dd6ed4b2bfd6f37beb6ec759b849ab17a465a14
3,621,044
def getMDistance(plug): """ Gets the MDistance value from the supplied plug. :type plug: om.MPlug :rtype: om.MDistance """ return plug.asMDistance()
43cd8dfd2c698ad1cc88771c2c69f3b5e502f202
3,621,045
import torch def create_activation_stats_collectors(model, *phases): """Create objects that collect activation statistics. This is a utility function that creates two collectors: 1. Fine-grade sparsity levels of the activations 2. L1-magnitude of each of the activation channels Args: mod...
9fa705f8c728059e956949662a1aabf0f0cf4643
3,621,046
def get_fach_choices(item_container): """ liefert die Liste der moeglichen Faecher """ ret = [] ret.append((-1, '---')) faecher = get_fach_list(item_container) for fach in faecher: ret.append((fach.fach_id, fach.fach_name)) return ret
11706498d24af113292c2fceae60d2cb72a2d901
3,621,047
import re def isPositive(phrase): """ Returns True if the input phrase has a positive sentiment. Arguments: phrase -- the input phrase to-be evaluated """ return bool(re.search(r'\b(sure|yes|yeah|go)\b', phrase, re.IGNORECASE))
584aa6d03984fbfe0069d3acaa407045b5e86f48
3,621,048
def tree_of_size(size, root, *stops, with_data = True, loc_prefix = 'a', data_prefix = 'd'): """Return expression for a tree segment of size `size` rooted in `root`. If `stops` is non-empty, the given stop nodes are used as the first (but not necessarily left-most) leaves. Warning: Stop nodes are in f...
81f7e05aac561aa826d57b4e6d31f4e80c545977
3,621,049
from typing import Any import operator def less_than(value: Any) -> Matcher[Any]: """Matches if object is less than a given value. :param value: The value to compare against. """ return OrderingComparison(value, operator.lt, "less than")
18be406aac9c7746c0beb7ac4e1ed78de802e197
3,621,050
def get_time_size(rates): """ Get number of time intervals Parameters ---------- Returns ------- out : int Number of time intervals See Also -------- DataStruct """ wgname_keys = list(rates.keys()) mnemo_keys = list(rates[wgname_keys[0]].keys()) return...
c6c496992ef0fe557df302c3c88d9290895cd4a1
3,621,051
import argparse def arg_parser(): """ """ parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", type=str, dest='input_file', help="Input file with tweets summary information") parser.add_argument("-e", "--input-entities", type=str, dest='input_ent', ...
b0079ee9990229890f510e2679344256a4d32dc2
3,621,052
def to_pandas(summary, metrics=None, date_key="summary_date"): """ Creates a dataframe from a summary object :param summary: A summary object returned from API :type summary: dictionary of dictionaries. See https://cloud.ouraring.com/docs/readiness for an example :param metrics: The metrics to inc...
3c7a83ddd4cbb3fabd472a8509296187c0c5a79e
3,621,053
def custom_loss(y_true, y_pred, alpha1=1, alpha2=0.5, alpha3=1): """ The designed loss function consists of precision, recall and mean squared error as follows: loss = a1 * precision_loss + a2 * recall_loss + a3 * mae_loss where α 1 , α 2 and α3 are the balance parameters. """ prec, recall =...
2626f652ace99e168f3a2758ac849e4f1b5e1455
3,621,054
def networkx_to_data_dict(graph_nx, node_shape_hint=None, edge_shape_hint=None, data_type_hint=np.float32): """Returns a data dict of Numpy data from a networkx graph. The networkx graph should be set up such that, for fixed shapes `node...
5ceb403d6f6d6fc2b65942f87c051f20c2734808
3,621,055
def compute_attributes_record(service): """ compute the number of attributes needed by this service. """ attribute_records = 1 for characteristic in service.get_characteristics(): # add two attributes, one for the characteristic declaration # and the other for the characteristic value. ...
50f7b10ca13282b2843681605d8177cea84d70f2
3,621,056
def twoQ_clifford_error(ngates, gate_qubit, gate_err): """ The two qubit Clifford gate error given measured errors in the primitive gates used to construct the Clifford (see arxiv:1712.06550). Assumes the error in the underlying gates is depolarizing. Args: ngates: list of the number of gat...
f2e5ef34aa4b1c7363ec0ff2c348d886ed3e8b21
3,621,057
import os import glob def main(): """ The main entry point for adb_push_built_products. Parse arguments and kick off the script. Return zero to indicate success. Raises an exception otherwise. """ parser = argument_parser() args = parser.parse_args() for path in args.paths: i...
8e6e6ab2445f5a67e583e6aa2abbc91e6f78837c
3,621,058
import typing def gather_texture( blender_shader_sockets: typing.Tuple[bpy.types.NodeSocket], export_settings): """ Gather texture sampling information and image channels from a blender shader texture attached to a shader socket. :param blender_shader_sockets: The sockets of the material ...
77826f62db2e0ed998114f3162ad01cc37daf19b
3,621,059
def splitFragP(uriref, punct=0): """split a URI reference before the fragment Punctuation is kept. e.g. >>> splitFragP("abc#def") ('abc', '#def') >>> splitFragP("abcdef") ('abcdef', '') """ i = uriref.rfind("#") if i >= 0: return uriref[:i], uriref[i:] else: ...
cc179fd8f064f3e87f18a9968f6f98ff0d584eb6
3,621,060
from typing import Optional from typing import List def get_scopes_from_groups( config: Config, groups: Optional[List[TokenGroup]] ) -> Optional[List[str]]: """Get scopes from a list of groups. Used to determine the scope claim of a token issued based on an OpenID Connect authentication. Paramet...
c68872f2884b2ec7d169ff94a1868711f03982bd
3,621,061
from typing import List from typing import Dict def get_notifications(refresh: bool = True) -> List[Dict[str, str]]: """ Get a list of notifications. :params refresh: Whether to get new news. If false, the existing notifications will be returned :returns: The list of notifications """ if ref...
03ada7fc18d0e483b75796992be2cb54cf58796d
3,621,062
import ctypes def _convert_double_vector_out( dlist ): """ Convert python list to datum as PyCapsule. Possibly check type of input and handle arrays amd nparrays too. Convert to standard form for C translation to datum. """ _VCL = _find_converter_lib() func = _VCL.double_vector_to_datum ...
390090fa6ef6785c605400c78c42f7e711b4a8b5
3,621,063
def sanitize_name(name): """ Clean-up the given username.""" name = name.strip() # clean up group name = name.replace('- IE', ' -IE') name = name.replace('- MA', ' -MA') for l in [1,2,3,4,5,6,7,8,9]: for g in "AB": name = name.replace(f'IE{l}-{g}', f'IE-{l}{g}') ...
c0618737b0717e6e90c09ab8d2f4f969abb7d891
3,621,064
import yaml import os import logging def to_md(mmyaml, projdir, mddir, use_synopsis=False): """ Generates markdown files from Scrivener RTF sources. If `use_synopsis` is `True` the Scrivener synopsis text files for each chapter must contain valid yaml `key: value` pairs. These will be prepended t...
93c3e0c6d54ec668f805a99dc8527ac9c5276704
3,621,065
def _givens_rotation_matrix_entries(a, b): """ Compute matrix entries for Givens rotation. """ r = hypot(a, b) c = a/r s = -b/r return c, s
29bf3891bfdbadde82c9dffebdbba0f9828bc095
3,621,066
def LastAge(): """Age at which mortality becomes 1""" x = 0 while True: if BaseMortRate(x) == 1: return x x += 1
b7dd7f42087c340b1e8ab6f082e8ec33455cf886
3,621,067
import os def extensionName(path): """ Function responsible for returning the extension of a file. """ extension = os.path.splitext(path)[1][1:] return extension
e76f47164acc5d1c189b111b018690b7d2f039b4
3,621,068
import yaml import re 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/Serve...
39c85681486abda0008a040ad13a37032fc182b5
3,621,069
import pandas import math 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([l...
3d9a6c55f225f9360f52c80c11e084c42bc66e48
3,621,070
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://...
5e3f791fc5b2451ff5538c3463674e1e89b80e12
3,621,071
import argparse 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, d...
e464504557497ebcfabdefe99fec5069aa9c03a1
3,621,072
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...
2030ed46c66fd0ab9818c4b6b0ef42b435933ceb
3,621,073
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 ...
8f9267cd11e28ab4225db613a622a822306a896d
3,621,074
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...
0582be8a96fa7b4953dd91375f7a604ab4b00da7
3,621,075
import logging 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)
dca9fa413f10ed4f93c2233de65cbb72ce507b10
3,621,076
import re 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]+)" ) query2aud...
a0fead629b25a89e27d60e902ca93fa409dc3f4a
3,621,077
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
d962b3138ddba7660f4d59f7ed89fa21ca08f035
3,621,078
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 -----...
c7d71fbd2dc15e99fa5b0268f0d79398ef6177fe
3,621,079
import socket 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 ...
2b903cfdad1edab69ba1fcd564540fdbed1dd193
3,621,080
def _touint64(num): """ This is required to convert signed json integers to unsigned. """ return num & 0xffffffffffffffff
9edf75a0bd62ae2c6fb126a9ce1e1b283dfbd52c
3,621,081
import torch 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, indi...
0079304c05293fb68e3af45be7a2e3cbd9564184
3,621,082
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', ...
bbbada95e72c9da567c4168791cce813abf80f35
3,621,083
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....
61e06b764475a7b7c0346d3c82fc1bfc9f049e97
3,621,084
from pathlib import Path 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...
6a3e6bf5fe554a13c28a96ab97aa5e14f0cbff13
3,621,085
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...
e2d3964d1a1278613ee46e2207fca86a38aa443f
3,621,086
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)
2819a0b5051e8ebcb891d1c48284dd2105ab9a7f
3,621,087
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...
e678ec67157b3a117e14be5e5b4f42718564fb82
3,621,088
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...
a9c1ddb3ccf1be62bc5c269f18537d1f0f88b421
3,621,089
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...
2f08fc0022704b00f4e63b88614120afd2c76efd
3,621,090
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...
db8cfaff0b6c2d831b5078efc49d900f17632383
3,621,091
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] ...
faaa2959e1de1f5d43476e124a76bb53cc04c45b
3,621,092
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...
c05101b94e459346adae553e31d25d46a8475514
3,621,093
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) ...
f79baa5e1b5d252a36f231e0acef7d8ef5e680b1
3,621,094
def launch(service_id, project_id, every=EVERY): """ Initialize the module. """ return TutorialPrimitives(service_id=service_id, project_id=project_id, every=every)
81f098de352565fca9f4951e2623f3fa403dd7f1
3,621,095
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, (...
9b7a309b92ed72f5d489c1d208122d5353a961e3
3,621,096
from typing import Union 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 pola...
84b371acc07cfeef0eab1b57601589dcaf8c4b90
3,621,097
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
a5ef2323e69f45c02b5596027e2c871b0837859b
3,621,098
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...
1086168623fe40bbb5e18180a089506572cfd2b6
3,621,099