content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def merge_schemas(a, b, path=None): """Recursively zip schemas together """ path = path if path is not None else [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge_schemas(a[key], b[key], path + [str(key)]) elif ...
8915f5e6fa0c352379852b088a9fe111fc27a719
35,847
def resample_dataarray2d_to_vertex_grid(da_in, gridprops=None, xyi=None, cid=None, method='nearest', **kwargs): """resample a 2d dataarray (xarray) from a structured grid to a new dataaraay of...
f2dacc6cad1fa10ee9014668b4aab853ab60f01f
35,848
def an_capabilities(b: bytes) -> list: """ Decode autonegotiation capabilities Args: b: coded *** Returns: human readable *** """ cap: list = [] i: int = (b[0] << 8) + b[1] cap_list = ['1000BASE-T (full duplex mode)', '1000BASE-T (half duplex mode)', ...
1e8b60582ad27ab6c1feafaac3992c4dc0550bbf
35,851
def peer_count(interface_name: str) -> int: """Number of peers in the mesh""" with mesh_client() as client: return len(client.getPeers(interface_name))
1caa3f916344a6fc919dbe18559e6f4606f53316
35,852
def german_words(): """Provides same known words list as used by the main script.""" return get_dictionary(language="de")
4a87fed3c451fa481373c209b788d1032e3bf7c0
35,853
def result(): """Get results when ready regarding a previously submitted task.""" # Retrieve JSON parameters data. data = request.get_json() or {} data.update(dict(request.values)) tid = data.get("tid") if not tid: raise abort(400, "missing 'tid' data") # Get the result (if exists a...
809ac8bc762fee45e4fcfb237085a4b998b328e9
35,855
def pushWPStoArray(aln, halfWPSwindow, start, end, tssWindow, isize, wpsWindow): """ for a given alignment, compute the regions that can be fully aligned and not e.g. [-1, -1 , -1, 1 , 1, 1, 1, 1, 1, -1, -1, -1] for a wps window -f 6 (halfwindow 3 ) this will be added to the defined transcription start ...
2f94dfa762f9997793a9a0d11bc47a375a06283f
35,856
def usgs_lithium_parse(*, df_list, source, year, **_): """ Combine, parse, and format the provided dataframes :param df_list: list of dataframes to concat and format :param source: source :param year: year :return: df, parsed and partially formatted to flowbyactivity specifications "...
17da5e3f8f25b2a2477f6eea4656ad28c307b760
35,858
import collections def convert_keys_to_string(dictionary): """ Recursively converts dictionary keys to strings. Utility to help deal with unicode keys in dictionaries created from json requests. In order to pass dict to function as **kwarg we should transform key/value to str. """ if isins...
01f15be1419d21758e215216b41819e5c4dbcf0f
35,859
def detectron2_available() -> bool: """ Returns True if Detectron2 is installed """ return bool(_DETECTRON2_AVAILABLE)
16531363e7728b02fb5639d93d66f82cc7647b8b
35,860
from operator import or_ def delete_user_by_id_and_name(id): """ username ๆˆ–่€…id ๅˆ ้™ค็”จๆˆท """ user = User.query.filter(or_(User.id.like(id), User.username.like(id))).first_or_404() user.delete() return user
d23485963e1b2b54957532aa8ea3ccb7575e0d07
35,861
def branch(default='master'): """used in the `git.latest` state for the `branch` attribute. If a specific revision exists DON'T USE THE BRANCH VALUE. There will always be a branch value, even if it's the 'master' default""" if cfg('project.revision'): return '' # results in a None value for git...
f1e1cbe73e27955c4e571115a72108aba9ba7b00
35,862
import requests def instance_types(gvar): """ List EC2 instance types for the specified cloud. """ mandatory = ['-cn'] required = [] optional = ['-CSEP', '-CSV', '-g', '-H', '-h', '-itc', '-itf', '-itmn', '-itmx', '-itos', '-itp', '-itpm', '-NV', '-ok', '-r', '-s', '-V', '-VC', '-v', '-v', '-...
676282fa68986a7545ff000f935714e3cae65dca
35,863
import math def math_logsumexp(data): """ achieve logsumexp by numpy Args: data: float array Returns: Float """ res = [] for i in data: res.append(math.exp(i)) return math.log(sum(res))
44a056d2aaa0298c62cc21ae2e224a974956ed8b
35,864
def only_numbers(iterable): """Returns whether the given iterable contains numbers (or strings that can be converted into numbers) only.""" return not any(lenient_float(item) is None for item in iterable)
d73735ed69aa85bd3982eade6a15de1bf76afcf4
35,865
def gaussian(birth, pers, mu=None, sigma=None): """ Optimized bivariate normal cumulative distribution function for computing persistence images using a Gaussian kernel. Parameters ---------- birth : (M,) numpy.ndarray Birth coordinate(s) of pixel corners. pers : (N,) numpy.ndarray ...
1c5321b31b7efdc501df72ee77fad17fbcc34056
35,866
def login(): """ TASKS: write the logic here to parse a json request and send the parsed parameters to the appropriate service. return a json response and an appropriate status code. """ data = request.get_json() user = User.objects(username=data.get('username')).first() ...
3a8e2c385d77705c5823e771c36311856bce2cae
35,867
def _process_rules_list(rules, match_rule): """Recursively walk a policy rule to extract a list of match entries.""" if isinstance(match_rule, policy.RuleCheck): rules.append(match_rule.match) elif isinstance(match_rule, policy.AndCheck): for rule in match_rule.rules: _process_ru...
67ffaac731e709e39b3120fd32ee3a0ad8dae299
35,869
def get_memoryview_and_address(data): """Get a memoryview for the given data and its memory address. The data object must support the buffer protocol. """ # To get the address from a memoryview, there are multiple options. # The most obvious is using ctypes: # # c_array = (ctypes.c_uint8 ...
7898bb5d79e8b839b1009ff549eb58ee8c2f71ed
35,870
def get_inv_dist_mat(node_list): """ Get pairwise distance matrix for specified nodes in node list. Args: node_list (list): Nodes for which to compute the pairwise distances Returns: (numpy.ndarray): Matrix of pairwise distances """ # Initialize array. dist_mat = np.ze...
27b600ef8ce03a0ea3a8c791e6cedcd7091e3a5b
35,871
import torch def stableSoftMax(x): """ stableSoftMax computes a normalized softmax :param x: Tensor List :return: Tensor List """ x = torch.exp(x - torch.max(x)) return x/torch.sum(x)
fa1e017812b7fd0c4e964eafb3fd59eae141203b
35,872
def is_item(var): """ is this a single item """ return is_str(var) or (not is_iterable(var))
3a56cb9832a77c77271087b5f653a9ef7b1a40a9
35,873
def _str_plot_fields(val, f, field_filter): """ get CSV representation of fields used by _str_plot :returns: list of fields as a CSV string, ``str`` """ s = _sub_str_plot_fields(val, f, field_filter) if s is not None: return "time,"+s else: return 'time,'
2d1be13fb801ea03ec34ef3810d6cc6dd11782b9
35,874
def cypher_repr(value, **kwargs): """ Return the Cypher representation of a value. This function attempts to convert the supplied value into a Cypher literal form, as used in expressions. """ encoder = CypherEncoder(**kwargs) return encoder.encode_value(value)
7e0a986206236399901c77d467c1c726573a1b33
35,875
def compareResultByTimeTupleRangesAndFlags(result, check, dateOnly=False): """ Ensures that flags are an exact match and time tuples a close match when given data in the format ((timetuple), (timetuple), flag) """ return (_compareTimeTuples(result[0], check[0], dateOnly) and _compareTime...
e2be1b7bdec5dcdaef8746349b4e7a56d54c8c19
35,876
def check_valid_title(title): """Checks if the title contains valid content""" title_issues = TitleIssues(title_contains_nsfw=title_contains_nsfw(title)) return title_issues
39bc77dce1a9136a7ab70c802bb90416655043b8
35,877
from typing import Any import typing from typing import Dict def ValueWidget(value: Any = None, on_value: typing.Callable[[Any], Any] = None) -> Element[ipywidgets.widgets.valuewidget.ValueWidget]: """Widget that can be used for the input of an interactive function :param value: The value of the widget. "...
6317cdb731902f9ae24435ad290e136f75680005
35,878
def list_all_volumes(): """Lists all available issues and volumes from the VA registry webpage. Only returns volumes that are available on HTML. Returns ------- volumes : dict A dictionary where the volumes are the keys and the issues are list entries. """ volumes = set() html =...
5dea8c7db1089a427282c7c76f780d37895f689f
35,879
def get_distribution(dist): """Return a PyMC distribution.""" if isinstance(dist, str): if hasattr(pm, dist): dist = getattr(pm, dist) else: raise ValueError(f"The Distribution '{dist}' was not found in PyMC") return dist
fe8f120be29690d3ae33dfb974369b9f068cb325
35,880
from datetime import datetime def login_required(f): """ Validates the JWT and ensures that is has not expired and the user is still active. :param f: :return: """ @wraps(f) def decorated_function(*args, **kwargs): if not request.headers.get("Authorization"): response...
e5582f78afa7acb0d2f7a8875d6f15bf2d9b73b1
35,882
from typing import List from typing import Dict def single__intent_topk_accuracy_score( intent_prediction: List[Dict[str, str]], y_true: List[str], k: int = 1, ) -> float: """Compute the Accuracy of a single utterance with multi-intents Accuracy of a single utterance is defined as...
c3a1c79692ef2031efc41cf6eb00c1e7139e0b20
35,883
def safeCellValue(cell, level=warning): """ ์…€ ๊ฐ์ฒด๋กœ๋ถ€ํ„ฐ ๊ฐ’์„ ์•ˆ์ „ํ•˜๊ฒŒ ์–ป๊ธฐ ์œ„ํ•œ ํ•จ์ˆ˜ - ์•ˆ์ „ํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ, ๊ณต๋ฐฑ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ """ cellType = type(cell) if cellType is openpyxl.cell.Cell or cellType is ReadOnlyCell: noneSpaceString = str(cell.value).strip() if noneSpaceString not in kIgnoreCharacters: return noneSpaceString else: #...
df7e636d269c29180faec548d7acf308fed4351d
35,884
def _get_port(config): """Get the server's port from configuration.""" if not config.has_option("server", "port"): return None port = config.getint("server", "port") return port
bee579fcfc82ea80c593dc7bd93ff3d39e63ef7b
35,885
def add_rectangular_plane( center_loc=(0, 0, 0), point_to=(0, 0, 1), size=(2, 2), name=None): """Adds a rectangular plane specified by its center location, dimensions, and where its +z points to. Args: center_loc (array_like, optional): Plane center location in world coordinates...
66d5410949d6702284e5b8027150129006691e86
35,886
def locations_3d_to_view(locations, extrinsic_matrix, intrinsic_matrix): """ Transforms 3D locations to 2D camera view.""" world_points = np.ones((4, len(locations))) for i in range(len(locations)): world_points[0][i] = locations[i].x world_points[1][i] = locations[i].y world_points...
fc5f3c781641366a840bcd1db72704ff804b17c2
35,887
def superkeyword_presence(document, superkeywords): """Return 1 if document contains any superkeywords, 0 if not.""" for word in superkeywords: if word in document.split(): return True return False
4b3223190651873d27562cc475ff623aa4cb5b47
35,888
def runTest(numClients, numServers, scripts, numFailures, runIndex): """ Run a single test of the Fault Tolerant SimpleFileLockService This takes numClients, numServers, and the test scripts to run. It SSHs into the requested number of servers and starts up the Fault Tolerant SimpleFileLockService o...
f8de155564d415e327589bd1d551e3353faca22c
35,889
def shuf_device_inclusive_scan(data, temp): """ Args ---- data: scalar input for tid temp: shared memory for temporary work, requires at least threadcount/wavesize storage """ tid = roc.get_local_id(0) lane = tid & (_WARPSIZE - 1) warpid = tid >> 6 roc.barrier() ...
a45d889202804493ebb653fce4cf66c3b58a941d
35,891
def chicago(return_X_y=True): """Chicago air pollution and death rate data Parameters ---------- return_X_y : bool, if True, returns a model-ready tuple of data (X, y) otherwise, returns a Pandas DataFrame Returns ------- model-ready tuple of data (X, y) OR Pand...
5e31c114f1e935927c052f7ff3fecee4222f33ab
35,892
def Normalize(normThisData: np.array,toThisData: np.array): """Normalize one dataset to another to produce a unitless output. Args: normThisData (np.array): toThisData (np.array): Returns: np.array: normalized_data Notes: Currently only works for 1D arrays shape=[m,] ?????true? and returns same shape 1D a...
2867d1835caf183b51e7c5dae0766cf6703312ea
35,893
def bbiboll(df, n=10, k=3): """ BBIๅคš็ฉบๅธƒๆž—็บฟ bbiboll(10,3) BBI={MA(3)+ MA(6)+ MA(12)+ MA(24)}/4 ๆ ‡ๅ‡†ๅทฎMD=ๆ นๅท[โˆ‘๏ผˆBBI-MA(BBI๏ผŒN)๏ผ‰^2/N] UPR= BBI๏ผ‹kร—MD DWN= BBI๏ผkร—MD """ # pd.set_option('display.max_rows', 1000) _bbiboll = pd.DataFrame() _bbiboll['date'] = df.date _bbiboll['bbi'] = (_ma(df....
26b6d83f50ebeecee0f7d671ba896dbc89df0a33
35,894
def calc_distance(y1, x1, y2, x2): """ Calculate distance between two locations using great circle distance. Notes: y1 = lat1, x1 = long1 y2 = lat2, x2 = long2 all assumed to be in decimal degrees if (and only if) the input is strings use the following conversions ...
6fbe2a02e1e3fa196e138bcbb28e676a55461cce
35,896
import unittest def suite(): """suite of unittest""" suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestDBManager)) return suite
9c0a313f137fc2c9530ea3f1a7ce8ad64d4f4a8f
35,897
def convert_size_string_to_bytes(size): """ Convert the given size string to bytes. """ units = [item.lower() for item in SIZE_UNITS] parts = size.strip().replace(' ', ' ').split(' ') amount = float(parts[0]) unit = parts[1] factor = units.index(unit.lower()) if not factor: ...
5763a4cc266a66e64f63d5bbe8d73f10edf0a397
35,898
def dumps(data, expires): """ๅŠ ๅฏ†""" # ๅˆ›ๅปบๅฏน่ฑก serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires) # ๅŠ ๅฏ† token = serializer.dumps(data).decode() return token
d38daca8895e544acea0de22e5e76926c21b34b5
35,899
def align_data(data): """Given dict with lists, creates aligned strings Args: data: (dict) data["x"] = ["I", "love", "you"] (dict) data["y"] = ["O", "O", "O"] Returns: data_aligned: (dict) data_align["x"] = "I love you" data_align["y"] = "O O O " """ spac...
6be0d9854cf73b4c44a91b2bbe6b4ac1bb76157e
35,900
def average_surface_distance(mflo, mref): """ average on points so not reliable if the sampling is unhomogeneous """ pd = polydata_distance(mflo, mref, do_signed=False) xv = pd.GetPointData().GetArray("Distance") xn = nps.vtk_to_numpy(xv) return xn.mean()
42e17183d58f05b1c4810f8d995b57e5b24a7bf8
35,901
def CleanUserUrl(user_url: str) -> str: """ๆธ…็† user_url๏ผŒๅŽป้™คๅ…ถไธญ็š„็ฉบๆ ผๅ’Œๆ— ็”จๅ‚ๆ•ฐ """ user_url = user_url.strip() return user_url.split("?")[0]
7c5c2cf5879d4ddfdbd1a60a679a747f162ebe35
35,902
def get_aqi_pb_24h(pb_24h: float) -> (int, str, str): """ Calculates Pb (24h) India AQI :param pb_24h: Pb average (24h), ppm :return: Pb India AQI, Effect message, Caution message """ cp = __round_down(pb_24h * 1000, 3) return __get_aqi_general_formula_texts(cp, IN_PB_24H, IN_AQI_EFFECTS, I...
dbd8beadaf57c5a14b1f91854cf004f877389ec4
35,903
def id_to_ec2_snap_id(snapshot_id): """Get or create an ec2 volume ID (vol-[base 16 number]) from uuid.""" if uuidutils.is_uuid_like(snapshot_id): ctxt = context.get_admin_context() int_id = get_int_id_from_snapshot_uuid(ctxt, snapshot_id) return id_to_ec2_id(int_id, 'snap-%08x') els...
d13a1a4c608c0baf8727a2b5c1d928b8722f71f7
35,905
def delete_nonestimator_parameters(parameters): """Delete non-estimator parameters. Delete all parameters in a parameter dictionary that are not used for the actual estimator. """ if 'Number' in parameters.keys(): del parameters['Number'] if 'UsePCA' in parameters.keys(): del p...
d84984d182a5945167b8e7880e493aa8fad832b7
35,906
from pathlib import Path def get_gene_sequence(gene_name: Path) -> str: """Okay, I don't understand how this is suppose to work. \f Parameters ---------- gene_name : Return ------ seq : `str` """ try: with open(gene_name, "r") as f: seq = f.read() ...
1ec4b9a2945b3e14dc87ce440734799c87560906
35,907
def get_service(credentials): """Get the service object corresponding to GMail.""" http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) user = service.users().getProfile(userId="me").execute() print("Authenticated user: {0}".format(user["emailAddress"])) ...
f59eaeb46a3f922855c9adc96a10ef2797ce8cbc
35,908
from typing import Optional from typing import Sequence def get_private_application_packages(display_name: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetPrivateApplicationPackagesFilterArgs']]] = None, package_types: Opt...
3dc97aa7d3fc27cc2cf12a797d7e7d364cffe210
35,909
def load_data(): """ :return: Data frame """ # load data engine = create_engine('sqlite:///data/disaster_response.db') df = pd.read_sql_table('disaster_response', engine) return df
231a0233d65717d4b171223d1870e2ba7c2822c4
35,910
def start_child_span( operation_name: str, tracer=None, parent=None, span_tag=None ): """ Start a new span as a child of parent_span. If parent_span is None, start a new root span. :param operation_name: operation name :param tracer: Tracer or None (defaults to opentracing.tracer) :param par...
e5465d45800560e601fde1d513c204d5ca1284de
35,911
def demslv08old(): """Nonlinear complementarity problem methods Solve nonlinear complementarity problem on R^2 using semismooth and minmax methods """ ''' function to be solved''' def f(z): x, y = z fval = np.array([200 * x * (y - x ** 2) + 1 - x, 100 * (x ...
4bf4b37ca8dbf7503443292996cfaf2a1ef4d368
35,912
from re import A import math def from_mercator(x, y): """Convert x,y coordinate from Spherical Mercator to lon, lat Ported from mercantile. Parameters ---------- x : float y : float Returns ------- (longitude, latitude) """ return (x * R2D / A, ((math.pi * 0.5) - 2.0 * ...
09a6a5ae85290fc230398de5ee0cfa28e8893366
35,913
def GetMaxIndex(tree): """get maximum node number.""" return tree.id
f443a9006765dface834aa9120c3ab38cd1d4369
35,914
def audit_name_starts_with(prefixes): """ Given a list of prefixes, returns a function that takes a folder and prints the folder path if the folder name does not start with one of the prefixes. """ def action(folder): if any(folder.name.startswith(prefix) for prefix in prefixes) == False: ...
886af28239aa989bed15d8f5a4462dd94cd1363b
35,915
def error_handler(error): """ Handle errors in views. """ return render('error.html'), 500
307846d8445f03ac8acb48585ccab5ffdbab972e
35,916
def save_work(work_id): """Save a work""" if not auth.session_user().can_manage_works: return Response('User not logged in or not authorized to manage works.', 401) if int(work_id) == -1: # New work work = Work() else: # Existing work work = Work.f...
296ed0eff93ea64b4541b4a84c62f8be673b6e89
35,917
def get_feedback_expertise_levels(): # noqa: E501 """Request a list of allowable expertise levels # noqa: E501 :rtype: ExpertiseLevels """ rtxFeedback = RTXFeedback() return rtxFeedback.getExpertiseLevels()
fc76ea2daf885159f4461ae694b7b68e203befdc
35,918
def get_coord_limits(coord): """get cooordinate limits""" lower_limit = float('.'.join([str(coord).split('.')[0], str(coord).split('.')[1][:2]])) if lower_limit > 0: upper_limit = lower_limit + 0.01 else: tmp = lower_limit - 0.01 upper_limit = lower_limit lower_limit = t...
803c0804e34a97d46a9555b4566be72949f55e8d
35,919
import torch def decode(loc, priors, use_yolo_regressors:bool=False): """ Decode predicted bbox coordinates using the same scheme employed by Yolov2: https://arxiv.org/pdf/1612.08242.pdf b_x = (sigmoid(pred_x) - .5) / conv_w + prior_x b_y = (sigmoid(pred_y) - .5) / conv_h + prior_y ...
8158b29c7557f1bde0e7873a6eace78d039c6d5d
35,920
def read_relative_file(filename): """Returns contents of the given file, whose path is supposed relative to this module.""" with open(join(dirname(abspath(__file__)), filename)) as f: return f.read()
b20d61e4ddc049c4beeacf106b04d30e3d0cc966
35,921
import torch import tqdm def get_activations(data_loader, model, device=None, batch_size=32, resize=False, n_samples=None): """Computes the activation of the given images Args: imgs: Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1] cuda: whether or not to run on GPU ...
2755bd34f05c3fb72f4c1da83bdb25d3df2f7662
35,922
from pathlib import Path def write( # Basic setup input_path, # preset_nickname=None, stream_name="", stream_description="", output_directory=None, output_mode="video", stream_name_file_output=False, max_cpu_cores=0, # Stream configurat...
f9b7335b5a4fe95d9f53631d78f2b1c9708d5eea
35,923
def shell_escape(string): """ Escape double quotes, backticks and dollar signs in given ``string``. For example:: >>> _shell_escape('abc$') 'abc\\\\$' >>> _shell_escape('"') '\\\\"' """ for char in ('"', '$', '`'): string = string.replace(char, '\\{}'.format...
03fcec5cdd99685e821fea11a69a234f3123fd9b
35,924
def boundary_and_obstacles(start, goal, top_vertex, bottom_vertex, obs_number): """ :param start: start coordinate :param goal: goal coordinate :param top_vertex: top right vertex coordinate of boundary :param bottom_vertex: bottom left vertex coordinate of boundary :param obs_number: number of ...
b0203b782e7655184c60d3a9e6c277ea880a2184
35,925
import logging import time def build_uncertain_table(args, scores, timestamp_list, image_path_list): """phase 3: build table from detection prediction""" logging.info('phase 3 start.') start = time.time() uncertain_scores = build_uncertain_table_fast(scores) save_uncertain_table(timestamp_list, u...
43edf61e10718dc6156060851fed3173ab47159f
35,926
def mvg_logpdf_fixedcov(x, mean, inv_cov): """ Log-pdf of the multivariate Gaussian where the determinant and inverse of the covariance matrix are precomputed and fixed. Note that this neglects the additive constant: -0.5 * (len(x) * log(2 * pi) + log_det_cov), because it is irrelevant when comparin...
3b2d256d58f9dce655d8aae9e04f3f4f87030981
35,928
def exec_flat_python_func(func, *args, **kwargs): """Execute a flat python function (defined with def funcname(args):...)""" # Prepare a small piece of python code which calls the requested function # To do this we need to prepare two things - a set of variables we can use to pass # the values of argume...
9c494daec2172fe59d65e625cc3a1b98656de5df
35,929
def robust_scale(df): """Return copy of `df` scaled by (df - df.median()) / MAD(df) where MAD is a function returning the median absolute deviation.""" median_subtracted = df - df.median() mad = median_subtracted.abs().median() return median_subtracted/mad
ba9ce747612c99997d890930e7ac7c582ba1af70
35,930
def generate_context_menu_mainmenu(menu_id): """Generate context menu items for a listitem""" items = [] if menu_id == 'myList': items.append(_ctx_item('force_update_mylist', None)) return items
d1cd169ec71a33c7bccf50b611d61b533ebcca54
35,931
def unroll_edges(domain, xgrid): """If necessary, "unroll" intervals that cross boundary of periodic domain. """ xA, xB = domain assert all(np.diff(xgrid) >= 0) assert xA < xB assert xA <= xgrid[0] assert xgrid[-1] <= xB if xgrid[0] == xA and xgrid[-1] == xB: return xgrid ...
274c446f60bb953e2b864bed06e23bb0153fac94
35,932
def create_correct_bias_pipe(params={}, name="correct_bias_pipe"): """ Description: Correct bias using T1 and T2 images Same as bash_regis.T1xT2BiasFieldCorrection Params: - smooth (see `MathsCommand <https://nipype.readthedocs.io/en/0.12.1/\ interfaces/generated/nipype.interfaces....
ec0be858a900f1b38ea6c61d9bcbcb8ac8535b85
35,933
def infer_gaps_in_tree(df_seq, tree, id_col='id', sequence_col='sequence'): """Adds a character matrix to DendroPy tree and infers gaps using Fitch's algorithm. Infer gaps in sequences at ancestral nodes. """ taxa = tree.taxon_namespace # Get alignment as fasta alignment = df_seq.phylo.to_...
ccd71b7b10977441a25a7d753f5a228287ed8d28
35,934
def _sklearn_booster_to_model(booster: GradientBoostingClassifier): """ Load a scikit-learn gradient boosting classifier as a Model instance. A multiclass booster gets turned into a one-vs-all representation inside the JSON. . Parameters ---------- booster : sklearn.ensemble.Grad...
0c1b0cb1eb396db707d22a1bb509f3592647ddb2
35,935
def encode_utf8_with_error_log(arg): """Return byte string encoded with UTF-8, but log and replace on error. The text is encoded, but if that fails, an error is logged, and the offending characters are replaced with "?". Parameters ---------- arg : str Text to be encoded. Returns ...
9a2ebc69f00220cfba92e0561b526ee3b5fd23d2
35,936
def gearys_c(adata, vals): """ Compute Geary's C statistics for an AnnData. Adopted from https://github.com/ivirshup/scanpy/blob/metrics/scanpy/metrics/_gearys_c.py :math:`C=\\frac{(N - 1)\\sum_{i,j} w_{i,j} (x_i - x_j)^2}{2W \\sum_i (x_i - \\bar{x})^2}` Parameters ---------- ...
ea5441619f0c893242b6d851781251b93a63b05d
35,937
def eq_kinematic_src(): """ Factory associated with EqKinSrc. """ return EqKinSrc()
be15e4169f90c28323dd881f67b325182547ad43
35,938
def generate_materials_string(materials, mtlfilename, basename): """Generate final materials string. """ if not materials: materials = { 'default': 0 } mtl = create_materials(materials, mtlfilename, basename) return generate_materials(mtl, materials)
e417a3a07576b61dd6b247251834e2c04ba0a947
35,939
def _mktyperef(obj): """Return a typeref dictionary. Used for references. >>> from jsonpickle import tags >>> _mktyperef(AssertionError)[tags.TYPE].rsplit('.', 1)[0] 'exceptions' >>> _mktyperef(AssertionError)[tags.TYPE].rsplit('.', 1)[-1] 'AssertionError' """ return {tags.TYPE: '%s.%...
0c89d3771c3531773e13475487b4466231e067e5
35,940
from typing import Tuple def colorize(img: np.ndarray, color: Tuple) -> np.ndarray: """colorize a single-channel (alpha) image into a 4-channel RGBA image""" # ensure color to RGBA if len(color) == 3: color = (color[0], color[1], color[2], 255) # created result image filled with solid "color...
88e79e7adc7785f1391db94c9a295b2a55943c7c
35,941
def prepare_template_stream(stream, base_url): """Prepares the stream to be stored in the DB""" document_tree = _get_document_tree(stream) _make_links_absolute(document_tree, base_url) return _serialize_stream(document_tree)
1072573ee0856725351a015f104e20604ef3b9c3
35,942
def _jsarr(x): """Return a string that would work for a javascript array""" return "[" + ", ".join(['"{}"'.format(i) for i in x]) + "]"
9c9b6df65bf4c01fa1c321445bbb7c86c6d28c5a
35,943
def PyApp_SetMacPreferencesMenuItemId(*args, **kwargs): """PyApp_SetMacPreferencesMenuItemId(long val)""" return _core_.PyApp_SetMacPreferencesMenuItemId(*args, **kwargs)
7704e544439e27f362fe703027af7d393e1ab647
35,945
def isnum(value): """ Check if a value is a type of number (decimal or integer) value: The value to check """ try: return bool(isinstance(value, (float, int))) except BaseException: return False
6116d0d4c61f5f3afefe311b06d9b23b03ab9bfc
35,946
import httpx import json async def _async_json_object(api_call): """async function to make a request to the wiki api and return a json object with article information Args: api_call (text): link to the api call Returns: dict: json content from the api call """ asy...
a047bbf16af314bd96c5d12c03ff8c2d0a16d17b
35,947
def yices_model_set_bv_int64(model, var, val): """Assign an integer value to a bitvector uninterpreted term. """ return libyices.yices_model_set_bv_int64(model, var, val)
5575adec31c297ff685884283bce7d1d9c47e386
35,948
def generate_histograms( num_users: int, counts_iid_param: float, avg_count: float, ref_distribution: np.ndarray, hist_iid_param: float, rng=np.random.default_rng()) -> np.ndarray: """Generate histograms with different total counts and distributions. Args: num_users: An integer indicati...
0e3c00a908cfe139dd273326d63a2c18cd0b1294
35,949
import requests def neo_create_bucket(**kwargs): """Create a bucket with headers. :param auth: Tuple, consists of auth object and endpoint string :param acl: Input for canned ACL, defaults to "private" :param policy_id: String represent `x-gmt-policyid` or determines how data in the bucket will be di...
52d5c6f3c49731c7fdfa95e85cdfc06c96a84f0a
35,951
def babi_handler(data_dir, task_number): """ Handle for bAbI task. Args: data_dir (string) : Path to bAbI data directory. task_number (int) : The task ID from the bAbI dataset (1-20). Returns: BABI : Handler for bAbI task. """ task = task_list[task_number - 1] retur...
12472b8b2430bf7d04e51e41f1b34124583935aa
35,952
def _full_ner(text_analyzer): """ Run complete NER. This includes extraction of different entity types and geotagging. :param class text_analyzer: the text_analyzer of nlp_components :return dict: json with persons, geotagged locations and metadata, readalbe by the viewer """ named...
e182e4d4bbc61ce9d7eca52b1a490d8705a81808
35,953
def frequency_impulse_response(magnitudes: tf.Tensor, window_size: int = 0) -> tf.Tensor: """Get windowed impulse responses using the frequency sampling method. Follows the approach in: https://ccrma.stanford.edu/~jos/sasp/Windowing_Desired_Impulse_Response.html Args: magnit...
9e307778511b7fb4b79caab338b016a1f7e91120
35,954
def parse_station_list_to_json(filepath_or_buffer) -> str: """ Return JSON-formatted data """ return _parse_station_list(filepath_or_buffer).to_json(orient="records")
32d3e6e122433692a1dd16bd3750cda528c70596
35,955
from typing import List from typing import Callable from typing import Set import numpy def get_minimal_intactness_ls_centralities( nodes: List[Node], definitions: Definitions, get_ill_behaved_weight: Callable[[Set[Node]], float], get_mu: Callable[[numpy.array], float] ) -> numpy.array...
ac2d01a8d5ba1842379044c77398c93292e8a4f9
35,956
def join_kwargs(**kwargs) -> str: """ Joins keyword arguments and their values in parenthesis. Example: key1{value1}_key2{value2} """ return "_".join(key + "{" + value + "}" for key, value in kwargs.items())
3054573ec51676bb8d93e2fcabd4cb5097e4b897
35,958
def zipped_lambda_function(): """Return a simple test lambda function, zipped.""" func_str = """ def lambda_handler(event, context): print("testing") return event """ zip_output = BytesIO() with ZipFile(zip_output, "w", ZIP_DEFLATED) as zip_file: zip_file.writestr("lambda_function.py", f...
38f2862c4e9401a32866ec54d5db420265bda2a1
35,959