content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from .wrappers import Response import os import mimetypes import io import time def send_file(request, filepath_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=60 * 60 * 12, conditional=False, use_x_sendfile=False, response_class=None): """Sends t...
75255450998c77861e2f6460b9c95bf7bb3e726d
3,638,000
import json def getInfo(ID): """ get info from file :param ID: meter ID :return: info = { "distance": 10, "horizontal": 10, "vertical": 20, "name": "1_1", "type": SF6, "template": "template.jpg", "ROI": { ...
d0e415b547450a84d15c96b3800276f6f566e503
3,638,001
from typing import Union import os def DO_run(wb, args: Union[list, None] = None, external: bool = False) -> RET: """run shell_command lfn|alien: tagged lfns :: download lfn(s) as a temporary file and run shell command on the lfn(s)""" if args is None: args = [] if not args: return RET(1, '', 'No shell co...
904cc2e014410cb89a975af2e59119a99604b495
3,638,002
import os import subprocess import re def get_keychain_pass(account=None, server=None): """ Gets the password for a given account from Apple's keychain """ params = { 'user': os.environ['USER'], 'security': '/usr/bin/security', 'command': 'find-internet-password', '...
97aa11d196919438d0fcb6b149c73a539ccceed2
3,638,003
import tensorflow as tf def cast_tensor_by_spec(_input, spec): """ transform dtype & shape following spec """ try: except ImportError: raise MissingDependencyException( "Tensorflow package is required to use TfSavedModelArtifact" ) if not _isinstance_wrapper(spec, ...
3cea0851c5cc9d457a05b58b0d2cdde50b3ed1ba
3,638,004
def StopRequestHook(ref, args, request): """Declarative request hook for TPU Stop command.""" del ref del args stop_request = GetMessagesModule().StopNodeRequest() request.stopNodeRequest = stop_request return request
8eba140a8f9bf59fec293d8f33d4c10bb03c1a99
3,638,005
def get_bucket( storage_bucket_name: str, **kwargs, ) -> Bucket: """Get a storage bucket.""" client = get_client() return client.get_bucket(storage_bucket_name, **kwargs)
ad33ae43f9d8ff2fb087519733931efd3952df18
3,638,006
def furl_for(endpoint: str, filename: str=None, **kwargs: dict) -> str: """ Replacement for url_for. """ return URL() + (url_for(endpoint, filename=filename) if filename != None else ("/" if endpoint == "" else url_for(endpoint, **kwargs)))
2e518ce13bd01771a5daffc111c6adc5d60e40cd
3,638,007
def image_max_value(img, region=None, scale=None): """Retrieves the maximum value of an image. Args: img (object): The image to calculate the maximum value. region (object, optional): The region over which to reduce data. Defaults to the footprint of the image's first band. scale (float...
b7e9c4ece9639fbdad75146021fd16438567b9c7
3,638,008
def getblock(lst, limit): """Return first limit entries from list lst and remove them from the list""" r = lst[-limit:] del lst[-limit:] return r
8d230dec59fe00375d92b6c6a8b51f3e6e2d9126
3,638,009
def electrode_neighborhoods(mea='hidens', neighborhood_radius=HIDENS_NEIGHBORHOOD_RADIUS, x=None, y=None): """ Calculate neighbor matrix from distances between electrodes. :param mea: (optional) type of the micro electrode array, default: 'hidens' :param neighborhood_radius:(optional) depends on mea typ...
7595b8cbd43bd12db2cb8e8a14d1968152a34fc0
3,638,010
def lat_from_meta(meta): """ Obtains a latitude coordinates array from rasterio metadata. :param meta: dict rasterio metadata. :return: numpy array """ try: t, h = meta["transform"], meta["height"] except KeyError as e: raise e lat = np.arange(t[5], t[5] + (t[4] * h), t[4...
dd4624521071788e497dadabdbb3e7716c6132cc
3,638,011
def get_test_class(dbcase): """Return the implementation class of a TestCase, or None if not found. """ if dbcase.automated and dbcase.valid: impl = dbcase.testimplementation if impl: obj = module.get_object(impl) if type(obj) is type and issubclass(obj, core.Test): ...
0ddf0127f87308695fef83001424ce7fa94ca463
3,638,012
def calc_dp(t_c, rh): """Calculate the dew point in Celsius. Arguments: t_c - the temperature in °C. rh - the relative humidity as a percent, (0-100) Returns: The dew point in °C. """ sat_vp = vapor_pressure_liquid_water(t_c) vp = sat_vp * rh / 100.0 a = log(vp / 6.1037) / 17.6...
a183a11e6a61e536376802d18b939caa7c02dd28
3,638,013
from typing import Tuple def getSlackMetar(input: flask.Request) -> Tuple[str, int, dict]: """ Endpoint handler for the slack_metar HTTP function trigger """ global _baseUrl global _logger _logger.debug("Entered metar") station = _getStationName(input) txt = _requestData('METAR', stat...
902c68255c419f34e196886015102b7226ca527c
3,638,014
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)): """conv_block is the block that has a conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: defualt 3, the kernel size of middle conv layer at main path filters: list of integers, the f...
f54486729405eb1ae41b554842c5942f8ad9483a
3,638,015
from typing import List from typing import Optional import tokenize def _fake_before_lines(first_line: str) -> List[str]: """Construct the fake lines that should go before the text.""" fake_lines = [] indent_levels = _indent_levels(first_line) # Handle regular indent for i in range(indent_levels...
9d3a450dce45690e1650ad2f1c86eff5df5d8e36
3,638,016
def normal_logpdf(x, mu, cov): """ Multivariate normal logpdf, numpy native implementation :param x: :param mu: :param cov: :return: """ part1 = 1 / (((2 * np.pi) ** (len(mu) / 2)) * (np.linalg.det(cov) ** (1 / 2))) part2 = (-1 / 2) * ((x - mu).T.dot(np.linalg.inv(cov))).dot((x - mu)...
47672093235cdf23562a83eac28ad428c5d4db24
3,638,017
def criteriarr(criteria): """Validate if the iterable only contains MIN (or any alias) and MAX (or any alias) values. And also always returns an ndarray representation of the iterable. Parameters ---------- criteria : Array-like Iterable containing all the values to be validated by the...
3f00db0e4a41ab09650b7779819e243c25b6ca35
3,638,018
import random def integer_or_rational(entropy, signed, min_abs=0): """Returns a rational, with 50% probability of it being an integer.""" if random.choice([False, True]): return integer(entropy, signed, min_abs=min_abs) else: return non_integer_rational(entropy, signed)
03e11aa082dfdb613f0f1861ff8346b1087b4880
3,638,019
import functools import warnings def ignore_python_warnings(function): """ Decorator for ignoring *Python* warnings. Parameters ---------- function : object Function to decorate. Returns ------- object Examples -------- >>> @ignore_python_warnings ... def f()...
438e54fe927f787783175faacf4eb9608fd27cf0
3,638,020
def runMetrics( initWorkingSetName, stepName, requestInfo, jobId, outputFolder, referenceFolder, referencePrefix, dtmFile, dsmFile, clsFile, mtlFile, ): """ Run a Girder Worker job to compute metrics on output files. Requirements: - Danesfield Docker image is...
e908191b274e4d55dc77a5686dc462a2f8a43798
3,638,021
import os def terminal_bg(): """Returns the first argument if the terminal has a light background, the second if it has a dark background, and the third if it cannot determine.""" colorfgbg = os.environ.get('COLORFGBG', '') if colorfgbg == '0;15': return BGColor.LIGHT if colorfgbg == '15;0...
d86ffaac04dce16f47bf71f495a9e017f3805618
3,638,022
def matplotlib_kwarg_dealiaser(args, kind): """De-aliase the kwargs passed to plots.""" if args is None: return {} matplotlib_kwarg_dealiaser_dict = { "scatter": mpl.collections.PathCollection, "plot": mpl.lines.Line2D, "hist": mpl.patches.Patch, "bar": mpl.patches.Re...
9c267531bde5445d7024bee4860b882044359212
3,638,023
def volume(): """ Get volume number :return: """ return Scheduler.ret_volume
0a39ff47800d04055971e7687b240f0c1e1a2396
3,638,024
def grid_grad(input, grid, interpolation='linear', bound='zero', extrapolate=False): """Sample spatial gradients of an image with respect to a deformation field. Notes ----- {interpolation} {bound} Parameters ---------- input : ([batch], [channel], *inshape) tensor ...
4df566e4612252169f2fab721b62cbd9be8c85ac
3,638,025
def delete_cart_item(quote_id, item_code): """Delete given item_codes from Quote if all deleted then delete Quote""" try: response = frappe._dict() item_code = item_code.encode('utf-8') item_list= [ i.strip() for i in item_code.split(",")] if not isinstance(item_code, list): item_code = [item_code] if n...
f7a17cf74764322136bd3e3940a37399ec1ac53b
3,638,026
def list_methods(f): """Return a list of the multimethods currently registered to `f`. The multimethods are returned in the order they would be tested by the dispatcher when the generic function is called. The return value is a list, where each item is `(callable, type_signature)`. Each type signa...
97ac92d58ee1edd7c38a2b9c1bcd05f0b7468a24
3,638,027
import os def load_CIFAR10(file_dir): """ load all of cifar """ xs = [] ys = [] for filename in train_list: file_path = os.path.join(file_dir, filename) data, labels = load_CIFAR_batch(file_path) xs.append(data) ys.append(labels) x_train = np.concatenate(xs) y_t...
8074f373561503ecfee901220135211319110c9b
3,638,028
def get_requirements(extra=None): """ Load the requirements for the given extra from the appropriate requirements-extra.txt, or the main requirements.txt if no extra is specified. """ filename = f"requirements-{extra}.txt" if extra else "requirements.txt" with open(filename) as fp: ...
7ce9e348357925b7ff165ebd8f13300d849ea0ee
3,638,029
import os def count_image_files(directory, montage_mode=False): """Counts all image files inside the directory. If montage_mode, counts 1 level deep and returns the minimum count. Else, counts all child images of directory. Args: directory (str): directory to look for child image files ...
c6b085a04f5777d6d5a30c714eced453e831f02e
3,638,030
def _format_mojang_uuid(uuid): """ Formats a non-hyphenated UUID into a whitelist-compatible UUID :param str uuid: uuid to format :return str: formatted uuid Example: >>> _format_mojang_uuid('1449a8a244d940ebacf551b88ae95dee') '1449a8a2-44d9-40eb-acf5-51b88ae95dee' Must have 32 charac...
517071b28f1e747091e2a539cd5d0b8765bebeba
3,638,031
def generate_uri(graph_base, username): """ Args: graph_base (): username (): Returns: """ return "{}{}".format(graph_base, username)
5e3557d300ed1a706e7b5257719135063d8c44e6
3,638,032
from typing import Type from typing import Optional from typing import Dict from typing import Any def _combine_model_kwargs_and_state( generator_run: GeneratorRun, model_class: Type[Model], model_kwargs: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Produces a combined dict of model kwargs...
b646b1cd12cdba02e0495e0592790933adadd3c9
3,638,033
def quick_boxcar(s, M=4, centered=True): """Returns a boxcar-filtered version of the input signal Keyword arguments: M -- number of averaged samples (default 4) centered -- recenter the filtered signal to reduce lag (default False) """ # Sanity check on signal and filter window length = s.s...
64e0a847b05972f674394984fe8799738465b96b
3,638,034
import psutil async def info(request): """HTTP Method to retun node state to caller""" log.debug("info request") app = request.app answer = {} # copy relevant entries from state dictionary to response node = {} node['id'] = request.app['id'] node['type'] = request.app['node_type'] ...
5960b166c7c73335a09d3e4ece84ae63155b56d0
3,638,035
def read_file(file, assume_complete=False): """read_file(filename, assume_complete=False) -> Contest Read in a text file describing a contest, and construct a Contest object. This adds the ballots (by calling addballots()), but it doesn't do any further computation. If assume_complete is True, any...
2e57353c66b82e73fbc4caace2f2e2e54d486dac
3,638,036
import six def merge_dict(a, b): """ Recursively merges and returns dict a with dict b. Any list values will be combined and returned sorted. :param a: dictionary object :param b: dictionary object :return: merged dictionary object """ if not isinstance(b, dict): return b ...
5adddd784ff4facdefebecea3ce2ab5069058885
3,638,037
def send_message(oc_user,params): """留言 """ to_uid = params.get("to_uid") content = params.get("content",'') if not to_uid: return 1,{"msg":"please choose user"} if not content: return 2,{"msg":"please input content"} if len(content) > 40: return 3,{"msg":"c...
6e61bfd8bfd4b94584e093c2bd91e647c39f7f90
3,638,038
def BDD100K(path: str) -> Dataset: """`BDD100K <https://bdd-data.berkeley.edu>`_ dataset. The file structure should be like:: <path> bdd100k_images_100k/ images/ 100k/ test train val...
c154f57e09fac6b01004015bcbebdbd3929a9ac3
3,638,039
def is_utf8(string): """Check if argument encodes to UTF8 without error. Args: string(str): string of bytes Returns: True if string can be successfully encoded """ try: string.encode('utf-8') except UnicodeEncodeError: return False except UnicodeDecodeError:...
4ea0f8f9b93976017a8add574098d89f86f1345d
3,638,040
def fixedwidth_bins(delta, xmin, xmax): """Return bins of width `delta` that cover `xmin`, `xmax` (or a larger range). The bin parameters are computed such that the bin size `delta` is guaranteed. In order to achieve this, the range `[xmin, xmax]` can be increased. Bins can be calculated for 1D da...
5f9e8bc31f44d66323689a1a79d6a597d422fa57
3,638,041
def get_word(path): """ extract word name from json path """ return path.split('.')[0]
e749bcdaaf65de0299d35cdf2a2264568ad5051b
3,638,042
def produce_edge_image(thresh, img): """ Threshold the image and return the edges """ (thresh, alpha_img) = cv.threshold(img, thresh, 255, cv.THRESH_BINARY_INV) blur_img = cv.medianBlur(alpha_img, 9) blur_img = cv.morphologyEx(blur_img, cv.MORPH_OPEN, (5,5)) # find the edged return c...
e269f15f515e8c88da3761306430d4d49c445d3b
3,638,043
import json import logging def get(endpoint: str, encoding: str="utf-8", **params) -> (list, dict, None): """ Return requested data in JSON (empty list on fallback) Check request has correct schema. :param endpoint - endpoint for request. :param encoding - encodin...
7deb825098ea3ed7e26a8eecd1341ee07657dfff
3,638,044
def aggregate_dicts(dicts: t.Sequence[dict], agg: str = "mean") -> dict: """ Aggregates a list of dictionaries into a single dictionary. All dictionaries in ``dicts`` should have the same keys. All values for a given key are aggregated into a single value using ``agg``. Returns a single dictionary with the ...
c8a557e26c885fcef381eb21edd27a0fcb91a12e
3,638,045
def aggregation_most_frequent(logits): """This aggregation mechanism takes the softmax/logit output of several models resulting from inference on identical inputs and computes the most frequent label. It is deterministic (no noise injection like noisy_max() above. :param logits: logits or probabili...
28440569b918a2a58ca0ee1589884948809994c7
3,638,046
import os def sanitize_path(path): """ Ensure the local filesystem path we're supposed to write to is legit. """ if not path.startswith("/"): raise Exception("Path must be fully qualified.") os.chdir(path) return os.getcwd()
203cbf5cad2f252540bfa1cff74c68c236d4b105
3,638,047
def handle_led(req): """ In this function all the work is done :) """ # switch GPIO to HIGH, if '1' was sent if (req.state == 1): if hostname == 'minibot': GPIO.output(req.pin, GPIO.HIGH) else: # for all other values we set it to LOW # (LEDs are low active!) if hos...
d2ea7c703d9b1002901d68c35d576fedd1e61a9a
3,638,048
from typing import Dict def evaluate_submission_with_proto( submission: Submission, ground_truth: Submission, ) -> Dict[str, float]: """Calculates various motion prediction metrics given the submission and ground truth protobuf messages. Args: submission (Submission): Proto messag...
c777359e6385164a463318f089ceb330e7bad814
3,638,049
def build_optimizer(args, model): """ Build an optimizer based on the arguments given """ if args['optim'].lower() == 'sgd': optimizer = optim.SGD(model.parameters(), lr=args['learning_rate'], momentum=0.9, weight_decay=args['weight_decay']) elif args['optim'].lower() == 'adadelta': ...
09677cbd5dc13f0dbab227f64d7724ff653eb9ec
3,638,050
import re def decorator_matcher(func_names, keyword, fcreate=None): """Search pattern @[namespace]<func_name>("<skey>") Parameters ---------- func_names : list List of macro names to match. fcreate : Function (skey, path, range, func_name) -> result. """ decorator = r"@?(?P<deco...
62db3ae8bfaab36266cbe07f886531d60f47905e
3,638,051
def log_binomial(n, k, tol=0.): """ Computes log binomial coefficient. When ``tol >= 0.02`` this uses a shifted Stirling's approximation to the log Beta function via :func:`log_beta`. :param torch.Tensor n: A nonnegative integer tensor. :param torch.Tensor k: An integer tensor ranging in ``[0,...
6e61ac09020c65202a2ab32134cb0c2ff6ff7f80
3,638,052
def error_500(request, *args, **kwargs): """ Throws a JSON response for INTERNAL errors :param request: the request :return: response """ message = "An internal server error ocurred" response = JsonResponse(data={"message": message, "status_code": 500}) response.status_code = 500 ret...
59f31de52a0d77ca71b3176929cf3142858637cf
3,638,053
from datetime import datetime import warnings def datetimes_to_durations(start_times, end_times, fill_date=datetime.today(), freq="D", dayfirst=False, na_values=None): """ This is a very flexible function for transforming arrays of start_times and end_times to the proper format for lifelines: duration and...
f30f64ac90b92a8614e60119d93f14954e24e2ef
3,638,054
from datetime import datetime import calendar def offset_from_date(v, offset, gran='D', exact=False): """ Given a date string and some numeric offset, as well as a unit, then compute the offset from that value by offset gran's. Gran defaults to D. If exact is set to true, then the exact date is figure...
6b45b553df7926ee0e68ee0e2678d4da5304e9b9
3,638,055
def _strip(x): """remvoe tensor-hood from the input structure""" if isinstance(x, Tensor): x = x.item() elif isinstance(x, dict): x = {k: _strip(v) for k, v in x.items()} return x
74023594b2da6f58dea425411d72ca493fb80f61
3,638,056
def rank_array(a, descending=True): """Rank array counting from 1""" temp = np.argsort(a) if descending: temp = temp[::-1] ranks = np.empty_like(temp) ranks[temp] = np.arange(1,len(a)+1) return ranks
8f15ab7123aa7652fe5208ef96808791454b876c
3,638,057
import torch def create_board_game_mcts(observation_spec, action_spec, dirichlet_alpha: float, pb_c_init=1.25, num_simulations=800, debug_summaries=False): """Helper function for ...
5c4f25e5c8dcd360967d9af8fc9429d7b7dde8b4
3,638,058
def normalize(params, axis=0): """ Function normalizing the parameters vector params with respect to the Axis: axis :param params: array of parameters of shape [axis0, axis1, ..., axisp] p can be variable :return: params: array of same shape normalized """ return params / np.sum(params, axis=ax...
c11ee3ccab492769e8c60cf2057d010190c7362f
3,638,059
from re import DEBUG def product_soft_update(uuid): """ Product soft update route :return Endpoint with RESTful pattern # pylint: disable=line-too-long See https://madeiramadeira.atlassian.net/wiki/spaces/CAR/pages/2244149708/WIP+-+Guidelines+-+RESTful+e+HATEOS :rtype flask.Response ...
7100adb6cef03a6bad8c835afb2ede074f86e56f
3,638,060
from typing import Sequence from typing import Dict from typing import List def estimate_cv_regression( results: pd.DataFrame, critical_values: Sequence[float] ) -> Dict[float, List[float]]: """ Parameters ---------- results : DataFrame A dataframe with rows contaoning the quantiles and co...
22e163da18cb7a9707ebba16690788467a4132c9
3,638,061
def parse_field(field_info, op): """ Combines a field with the operation object field_info is a dictionary containing at least the key 'fields' op is an elasticObject returns an elasticObject """ fields = field_info["fields"] constraints = field_info["constraints"] _logger....
40c05cfcad903f739279b6c3e083803f14c6038c
3,638,062
def resize(image, size): """Resize multiband image to an image of size (h, w)""" n_channels = image.shape[2] if n_channels >= 4: return skimage.transform.resize( image, size, mode="constant", preserve_range=True ) else: return cv2.resize(image, size, interpolation=cv2...
6a67524552397f1b1c9cd315b2cbaccd624027fb
3,638,063
import os import yaml def get_configs(conf_file=None): """ Get configurations, like db_url """ if not conf_file: conf_file = os.path.join(os.path.dirname(__file__), os.pardir, 'config.yml') with open(conf_file, 'r') as fp: ...
0baee739a2fc8770e11c247d38ff486d194579c4
3,638,064
def version(): """Return the version of this cli tool""" return __version__
790059de16a48ea7dd5dbcc4470f2be851562146
3,638,065
def load_file_dangerous(file_path): """ Load a single-lined file. Using eval with no safety check! """ #TODO: Dangerous `eval`! Be aware of the content in the file with open(file_path, "r") as f: content = eval(f.read().strip()) return content
516fec3f96499cc59864ea4ddcf8a3b80234fc63
3,638,066
def ho2cu(ho): """ Homochoric vector to cubochoric vector. References ---------- D. Roşca et al., Modelling and Simulation in Materials Science and Engineering 22:075013, 2014 https://doi.org/10.1088/0965-0393/22/7/075013 """ rs = np.linalg.norm(ho,axis=-1,keepdims=True) xyz3 = np...
be55f70c27be789a51c9aee0ba94b36879755915
3,638,067
def apparent_resistivity( dc_survey, survey_type='dipole-dipole', space_type='half-space', dobs=None, eps=1e-10 ): """ Calculate apparent resistivity. Assuming that data are normalized voltages - Vmn/I (Potential difference [V] divided by injection current [A]). For fwd modelled ...
ec9cc774b2ae9484916da46083730156c64559d1
3,638,068
import json def readJsonFile(filePath): """read data from json file Args: filePath (str): location of the json file Returns: variable: data read form the json file """ result = None with open(filePath, 'r') as myfile: result = json.load(myfile) return result
cf15e358c52edcfb00d0ca5257cf2b5456c6e951
3,638,069
def _sort_torch(tensor): """Update handling of sort to return only values not indices.""" sorted_tensor = _i("torch").sort(tensor) return sorted_tensor.values
0480d397726f9cd97c9fa9b7e566db1d9266a75a
3,638,070
def lambda_handler(event, context): """ Route the incoming request based on type (LaunchRequest, IntentRequest, etc). The JSON body of the request is provided in the event parameter. """ print("event.session.application.applicationId=" + event['session']['application']['applicationId']) ...
cda1cecdde08ae0cb7c925a5f8b598efd1c47e16
3,638,071
def get_authorized_client(config): """Get an OAuth-authorized client Following http://requests-oauthlib.readthedocs.org/en/latest/examples/google.html """ client = requests_oauthlib.OAuth2Session( client_id=config['client']['id'], scope=SCOPE, redirect_uri=config['client']['...
00012be81fed9e29cfabcf81799d887259fa395c
3,638,072
from datetime import datetime def query_obs_4h(session, station_name: str, start: datetime, end: datetime) -> pd.DataFrame: """ SQLite 读取 & 解析数据. """ time_format = "%Y-%m-%d %H:00:00" resp = session.query( ObsDataQcLinear.time, ObsDataQcLinear.watertemp, ObsDataQcLinear.pH,...
35730e5de1b675dc14ef5771459e7cb9629d34e5
3,638,073
def get_valid_user_input(*, prompt='', strict=False): """Return a valid user input as Fraction.""" frac_converter = parse_fraction_strict if strict else Fraction while True: user_input = input(prompt) try: user_input_fraction = frac_converter(user_input) except (ValueErro...
7726df5b1a57ab9c9122a60e847be95161829a09
3,638,074
import os def get_rsync_pid_file_path(image_id): """Generate the path for an rsync pid file.""" return os.path.join(CONF.baremetal.rsync_pid_path, image_id)
475896fafc8423498694b2c82857df978f2fa3b7
3,638,075
def binary_irrev(t, kf, prod, major, minor, backend=None): """Analytic product transient of a irreversible 2-to-1 reaction. Product concentration vs time from second order irreversible kinetics. Parameters ---------- t : float, Symbol or array_like kf : number or Symbol Forward (bimole...
c399cb13bbe32a066b07e0aaa93fc40ddfd8c6ec
3,638,076
def adapted_rand_error(seg, gt, all_stats=False): """Compute Adapted Rand error as defined by the SNEMI3D contest [1] Formula is given as 1 - the maximal F-score of the Rand index (excluding the zero component of the original labels). Adapted from the SNEMI3D MATLAB script, hence the strange style. ...
0530fad7982e83aaf33e3f190b435bc7e216af00
3,638,077
from typing import List def get_knp_span(type_: str, span: Span) -> List[Span]: """Get knp tag or bunsetsu list""" assert type_ != MORPH knp_list = span.sent._.get(getattr(KNP_USER_KEYS, type_).list_) if not knp_list: return [] res = [] i = span.start_char doc = span.doc for ...
90c0f753a6dd4acdbdfebc550fa66b1e8c5f21eb
3,638,078
def get_namespace_leaf(namespace): """ From a provided namespace, return it's leaf. >>> get_namespace_leaf('foo.bar') 'bar' >>> get_namespace_leaf('foo') 'foo' :param namespace: :return: """ return namespace.rsplit(".", 1)[-1]
0cb21247f9d1ce5fa4dd8d313142c4b09a92fd7a
3,638,079
from typing import Tuple def fft_real_dB(sig: np.ndarray, sample_interval_s: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """ FFT, real frequencies only, magnitude in dB :param sig: array with input signal :param sample_interval_s: sample interval in seconds :r...
fc2aec1bad283aa7e1817e6d91c833e3d8c83f8f
3,638,080
from typing import Union from typing import List def get_ipv4_gateway_mac_address_over_ssh(connected_ssh_client: SSHClient, target_os: str = 'MacOS', gateway_ipv4_address: str = '192.168.0.254') -> Union[None, str]: """ Get MA...
5701aaec179d0d36f38df929d7838fc9e31ebe4f
3,638,081
def sort(list_): """ This function is a selection sort algorithm. It will put a list in numerical order. :param list_: a list :return: a list ordered by numerial order. """ for minimum in range(0, len(list_)): for c in range(minimum + 1, len(list_)): if list_[c] < list_[mini...
99007e4b72a616ae73a20358afc94c76e0011d3e
3,638,082
import requests import tqdm def stock_em_xgsglb(market: str = "沪市A股") -> pd.DataFrame: """ 新股申购与中签查询 http://data.eastmoney.com/xg/xg/default_2.html :param market: choice of {"全部股票", "沪市A股", "科创板", "深市A股", "创业板"} :type market: str :return: 新股申购与中签数据 :rtype: pandas.DataFrame """ mark...
2ea409c176e5a2b266866f5af7bbced291dbadca
3,638,083
def geomfill_Mults(*args): """ :param TypeConv: :type TypeConv: Convert_ParameterisationType :param TMults: :type TMults: TColStd_Array1OfInteger & :rtype: void """ return _GeomFill.geomfill_Mults(*args)
d79a857308bb796e08ce3e84f75963d473f37b76
3,638,084
import math def arcminutes(degrees=0, radians=0, arcseconds=0): # pylint: disable=W0621 """ TODO docs. """ if radians: degrees += math.degrees(radians) if arcseconds: degrees += arcseconds / arcsec(degrees=1.) return degrees * 60.
985e9dad40609d07d262f26ee69a638c0f873dfc
3,638,085
import ctypes def PCO_GetRecordingStruct(handle): """ Get the complete set of the recording function settings. Please fill in all wSize parameters, even in embedded structures. """ strRecording = PCO_Recording() f = pixelfly_dll.PCO_GetRecordingStruct f.argtypes = (ctypes.wintypes.HAN...
2d50968e9445f3937726583c00a61c8839b488b2
3,638,086
import random def auxiliar2(Letra, tabuleiro): """ Função auxiliar para jogada do computador, esta função compõe a estratégia e é responsável por realizar uma das jogadas do computador. Recebe como parâmetro o Simbolo do computador e retorna a jogada que será realizada. """ if Letra == "X": ...
1db9ca4a9a9e97a3b689efc4295b59ad553cfd7a
3,638,087
def create_task(): """ 处理创建根据相关抓取参数及抓取节点服务的名称,启动数据抓取. :return: """ payload = request.get_json() # 查找抓取节点信息 node = db.nodes.find_one({"name": payload["node"]}) # 未找到抓取节点返回404 if node is None: return abort(404) # 保存任务信息至数据库中 payload["task"] = "%s@%s" % (payload["node...
4963b66174f57687453a4a59b321d564cbec9225
3,638,088
def eco_hist_calcs(mass,bins,dlogM): """ Returns dictionaries with the counts for the upper and lower density portions; calculates the three different percentile cuts for each mass array given Parameters ---------- mass: array-like A 1D array with log stellar ma...
bf4e9ffeec76b2cf7a3e85db73dd1a7fc996ecd9
3,638,089
def avgSentenceLength(text): """Return the average length of a sentence.""" tokens = langtools.tokenize(text) return len(tokens) / sentenceCount(text)
4988c4fe945e2eada9abf01aebe0d454620cf565
3,638,090
def retrieve_context_topology_link_available_capacity_total_size_total_size(uuid, link_uuid): # noqa: E501 """Retrieve total-size Retrieve operation of resource: total-size # noqa: E501 :param uuid: ID of uuid :type uuid: str :param link_uuid: ID of link_uuid :type link_uuid: str :rtype:...
6c0ee9cbf2784b17a6d624530bdf94875b4e751f
3,638,091
import re def harmonize_geonames_id(uri): """checks if a geonames Url points to geonames' rdf expression""" if 'geonames' in uri: geo_id = "".join(re.findall(r'\d', uri)) return "http://sws.geonames.org/{}/".format(geo_id) else: return uri
acfb8cb4277363c6bee4844a0a95ed2ea464e741
3,638,092
import argparse def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Gashlycrumb', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('letter', metavar='letter', help='Lett...
b3b3eb5f3a85a82d9feee8e99e1ae16cd05d8f32
3,638,093
def get_apikey(api): """Return the API key.""" if api == "greynoise": return config.greynoise_key if api == "hybrid-analysis": return config.hybrid_analysis_apikey if api == "malshare": return config.malshare_apikey if api == "pulsedive": return config.pulsedive_apike...
bf52c5424c657dc9d2173c0fa7434040daf967f3
3,638,094
def create_admin_account(): """ Creates a new admin account """ try: original_api_key = generate_key() secret_key = generate_key() hashed_api_key = generate_password_hash(original_api_key) Interactions.insert(DEFAULT_ACCOUNTS_TABLE, **{'userna...
3d9d1c7fdfe0492080930855490eb8f050056c54
3,638,095
def _arg_wrap(func): """ Decorator to decorate decorators to support optional arguments. """ @wraps(func) def new_decorator(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): return func(args[0]) else: return lambda realf: func(realf, *ar...
a74f7cf363aab33d770c5f7a080b8796d27e91ec
3,638,096
def _point_as_tuple(input_string: str) -> _Tuple[float]: """ Attempts to parse a string as a tuple of floats. Checks that the number of elements corresponds to the specified dimensions. The purpose of this function more than anything else is to validate correct syntax of a CLI argument that is suppo...
f828c5ed9cbcf9b1820abaff07c0b646027e6ab9
3,638,097
import random def generate_id(): """Generate Hexadecimal 32 length id.""" return "%032x" % random.randrange(16 ** 32)
2f9a9eb7cc1808515fb7d71607899bb43d2ac682
3,638,098
def __charge_to_sdf(charge): """Translate RDkit charge to the SDF language. Args: charge (int): Numerical atom charge. Returns: str: Str representation of a charge in the sdf language """ if charge == -3: return "7" elif charge == -2: return "6" elif charge ...
1bfda86ee023e8c11991eaae2969b87a349b7f7e
3,638,099