content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def bell_sigmoid(ds, a=None, bc=None, d=None, inplace=True): """ Apply a fuzzy membership function to data using bell-shaped sigmoidal function. Requires a low left inflection (a), a mid-point (bc), and a low right inflection (d) point to set the bounds in which to rescale all values to. Value...
3e0476a4df3d2c63646aedbc4a64e8ee3656bc43
30,651
def get_composite(name, error=DontCatchError, error_message=None, identifier=None, component_category='unknown'): """ Gets a Composite Singleton :param: - `name`: name to register singleton (clients that want same singleton, use same name) - `error`: exception to catch (``DontC...
39bfe67a1482c7c157e655c3f1accb308fa211b0
30,653
def is_list_of_float(value): """ Check if an object is a liat of floats :param value: :return: """ return bool(value) and isinstance(value, list) and all(isinstance(elem, float) for elem in value)
35ec9531bcddc33166e0f17d3fc59a08341d2d95
30,654
def get_example_params(example_index): """ Gets used variables for almost all visualizations, like the image, model etc. Args: example_index (int): Image id to use from examples returns: original_image (numpy arr): Original image read from the file prep_img (numpy_arr): Proce...
6e2760e4d91d888ce9f1443787b9bfa864fe7118
30,655
from geometrylab.geometry import Polyline def bezier_curve(points, nTimes=500, is_poly=False, is_crv=False): """ Given a set of control points, return the bezier curve defined by the control points. points should be a list of lists, or list of tuples such as [ [1,1], ...
0b60554a2b8697c665822ecf408a089b89df7107
30,656
import functools def decorator_with_keywords(func=None, **dkws): # NOTE: ONLY ACCEPTS KW ARGS """ A decorator that can handle optional keyword arguments. When the decorator is called with no optional arguments like this: @decorator def function ... The function is passed as the first a...
64c4ddd26cc04a43cbf559600652113db81b79ae
30,657
from datetime import datetime def parse_line(line): """ Extract all the data we want from each line. :param line: A line from our log files. :return: The data we have extracted. """ time = line.split()[0].strip() response = line.split(' :') message = response[len(response) - 1].strip...
72b4362b7628d31996075941be00e4ddcbd5edbc
30,658
def semi_lagrangian(field: GridType, velocity: Field, dt: float, integrator=euler) -> GridType: """ Semi-Lagrangian advection with simple backward lookup. This method samples the `velocity` at the grid points of `field` to determine the lo...
b265e660100a9855a99e03f3c03cbd4bad0f79c8
30,659
def pptx_to_bbox(left, top, width, height): """ Convert matplotlib bounding box format to pptx format Parameters ---------- left : float top : float width : float height : float Returns ------- bottom, left, width, height """ return top-height, left, width, height
3cdc186301d7e6e97ea44923ca6859e2e51f0774
30,660
from typing import Counter def reindex(labels): """ Given a list of labels, reindex them as integers from 1 to n_labels Also orders them in nonincreasing order of prevalence """ old2new = {} j = 1 for i, _ in Counter(labels).most_common(): old2new[i] = j j += 1 old2newf...
c12afd3b6431f10ccc43cce858e71bc504088a6e
30,661
def _validate_vg(module, vg): """ Check the current state of volume group. :param module: Ansible module argument spec. :param vg: Volume Group name. :return: True (VG in varyon state) or False (VG in varyoff state) or None (VG does not exist), message. """ lsvg_cmd = module.ge...
c5d68f69243f1ca24140f09c7047269b7012ed6c
30,662
from typing import List def news_items(news_index_page) -> List[News]: """Fixture providing 10 News objects attached to news_index_page """ rv = [] for _ in range(0, 10): p = _create_news_page(f"Test News Page {_}", news_index_page) rv.append(p) return rv
e7e8f417cefd713b9d79e6e28b654df9dd0ca0da
30,663
def is_annotated(procedure): """Return True if procedure is annotated.""" procedure = annotatable(procedure) try: ann = procedure.func_annotations return ann.are_for(procedure) and bool(ann) except AttributeError: return False
70eccace122462584e3c536fafe272b5397ac659
30,664
def _enable_disable_pim_config(tgen, topo, input_dict, router, build=False): """ Helper API to enable or disable pim on interfaces Parameters ---------- * `tgen` : Topogen object * `topo` : json file data * `input_dict` : Input dict data, required when configuring from testcase * `route...
4408ac212126895ba161f834e7e076a0c14d864f
30,666
from typing import Union def linear_interpolation_formula( left: Union[float, np.array], right: Union[float, np.array], gamma: Union[float, np.array], ) -> Union[float, np.array]: """ Compute the linear interpolation weighted by gamma on each point of two same shape array. """ return gamma...
cdcb915f6bfc60db2f3754044ab5b67432d66370
30,667
def estimate_visib_mask_est(d_test, d_est, visib_gt, delta, visib_mode='bop19'): """Estimates a mask of the visible object surface in the estimated pose. For an explanation of why the visibility mask is calculated differently for the estimated and the ground-truth pose, see equation (14) and related text in Ho...
90f2de0a4e489207e128668510ba8b08a0bd361f
30,668
import itertools def combine_assertions(input_filename, output_filename): """ Take in a tab-separated, sorted "CSV" files, indicated by `input_filename`, that should be grouped together into assertions. Output a msgpack stream of assertions the file indicated by `output_filename`. The input f...
87e2e7df2484dcff7f315da91ef39472991c2351
30,669
def sanitize_mobile_number(number): """Add country code and strip leading zeroes from the phone number.""" return "254" + str(number).lstrip("0")
944e6e5baef92ee7c59249714a9ba3463ff5981f
30,671
def fakebaraxis(ticks, painter=fakebarpainter(),*args, **kwargs): """Return a PyX linear axis that can be used to make fake bar plots. Use "keyticks" to create the ticks expected by this function.""" return axis.linear( min=-0.75, max=len(ticks)-0.25, parter=None, manualtick...
99b30a9b76b9da8e4c8e1c937431aa509b47ab16
30,672
import csv def get_score_sent_pairs_from_tsv(tsv_filepath, encoding="ISO-8859-1"): """expects tokenized sentences in tsv file!""" with open(tsv_filepath, encoding=encoding) as tsvfile: reader = csv.reader(tsvfile, delimiter='\t') score_sent_pairs = [[float(row[0]), row[1]] for row in reader] return scor...
44f5c150d40b407b50a93cd0ad968658fd5ef431
30,673
def test_timings_trie(port, individual_test_timings): """Breaks a test name into chunks by directory and puts the test time as a value in the lowest part, e.g. foo/bar/baz.html: 1ms foo/bar/baz1.html: 3ms becomes foo: { bar: { baz.html: 1, baz1.html: 3 } ...
dfca4a92715063620b3a110df3ea29b2de3bb0b6
30,674
def prop_end(wf, **kwargs): """Set variables needed to properly conclude a propagation run. Parameters ---------- wf : obj The current WaveFront class object Returns ------- wf.wfarr : numpy ndarray Wavefront array sampling : float Sampling in meters Oth...
d294939f5e26df7672611ae6b58ac7039e8d22c0
30,675
def add_others_ta(df, close, fillna=False): """Add others analysis features to dataframe. Args: df (pandas.core.frame.DataFrame): Dataframe base. close (str): Name of 'close' column. fillna(bool): if True, fill nan values. Returns: pandas.core.frame.DataFrame: Dataframe wit...
97185202663cb83ed1dc5f4bd02320b0ce02c4aa
30,676
def _fixture_union(caller_module, name, fixtures, idstyle, scope="function", ids=fixture_alternative_to_str, unpack_into=None, autouse=False, **kwargs): """ Internal implementation for fixture_union :param caller_module: :param name: :param fixtures: :param idstyle: :para...
7063ab888b99cc0aa10890de9f4575f0ce758017
30,677
def service_class(cls): """ A class decorator enabling the instances of the class to be used as a ``services``-provider in `JSONRpc Objects`_ and `BSONRpc Objects`_. Use decorators ``request``, ``notification``, ``rpc_request`` and ``rpc_notification`` to expose methods for the RPC peer node. ...
7c146b1d04415cd494e62fb9ee310364c345c217
30,678
def lightcurveplain(request, tcs_transient_objects_id): """lightcurveplain. Args: request: tcs_transient_objects_id: """ transient = get_object_or_404(TcsTransientObjects, pk=tcs_transient_objects_id) mjdLimit = 55347.0 # Hard wired to 31st May 2010 # 2012-07-18 KWS Changed this...
0db9b5ccdb5df9c65fab971fe72d5cec6da84676
30,679
def locate_address(ip_list, ip_attack): """ for each line in the file pointer define the ip ranges and country codes if the attacking ip is in between the range then return country code :param ip_list - list of ip address ranges and country code: :param ip_attack - attacking ip as an int...
82a8f9ed0cf79a2ba39d21348779687c1f8c19a8
30,680
import scipy def invertnd(f, x, *other_vars, kind='linear', vectorized=False): """ Invert a multivariate function numerically Args: f: Function to invert x: Domain to invert the function on (range of inverted function) *other_vars: Domain to invert the function on (parameters of in...
bc2798e382a700755a1d6a5d59743b969d96a02d
30,681
def most_mentioned(msgs, limit=20): """Top mentions by '@' references """ mentions = {} for m in msgs: for at in preproc.extract_ats_from_text(m['text']): mentions[at] = mentions[at] + 1 if at in mentions else 1 return sorted(mentions.items(), key=lambda x: x[1]...
10aa70248d33325d585fb19875a13965f67896b5
30,682
import string def is_valid_matlab_field_label(label): """ Check that passed string is a valid MATLAB field label """ if not label.startswith(tuple(string.ascii_letters)): return False VALID_CHARS = set(string.ascii_letters + string.digits + "_") return set(label).issubset(VALID_CHARS)
ea1358e94f4fc936cb12b9cad5d7285ee39dba55
30,683
def identity(n, dtype=DEFAULT_FLOAT_DTYPE): """ Returns the identity tensor. Args: n (int): Number of rows and columns in the output, must be larger than 0. dtype (Union[mstype.dtype, str], optional): Designated tensor dtype, can be in format of np.float32, or `float32`. Default...
7ad0025b5fb5bc02b8f07039b8beb15e8c402c11
30,684
def _chain_connectivity(edges, chains): """Returns chain connectivity treated as clustered entities represented by nodes""" chain_connectivity = np.empty((len(edges), 2), dtype=np.int64) starts = defaultdict(list) for section_index, chain in enumerate(chains): starts[chain[0][0]].append(section...
5687b433a1c47a75641442aef1b8cff4c8cb4e17
30,685
def reading2celsius(self, reading): """ Converts sensor reading to celsius """ celsius = reading / 50 - 273.15 return celsius
72e6933002c9725165145451e10bbf98c162b625
30,686
import sqlite3 def evaluate_csp(website_id, test_weights): """ Checks: no fallback to default: base-uri form-action frame-ancestors report-to/uri sandbox upgrade-insecure-requests ...
a5c24968ad98790eb3361db8310416b977e4adc7
30,687
def get_analysis_alias_from_metadata(eload_cfg): """ Returns analysis alias only if we find a metadata spreadsheet and it has exactly one analysis. Otherwise provides an error message and raise an error. """ metadata_spreadsheet = eload_cfg.query('submission', 'metadata_spreadsheet') if metadata...
ac3ecc7aa14f37fa2a25f9b7995923013c68a5c3
30,688
from imcsdk.mometa.bios.BiosProfileManagement import BiosProfileManagement from imcsdk.mometa.bios.BiosProfileManagement import \ def bios_profile_backup_running(handle, server_id=1, **kwargs): """ Backups up the running configuration of various bios tokens to create a 'cisco_backup_profile'. Will ove...
e1c1a7b498df6af5238914522eae56e666df328f
30,689
def variantCombinations(items): """ Calculates variant combinations for given list of options. Each item in the items list represents unique value with it's variants. :param list items: list of values to be combined >>> c = variantCombinations([["1.1", "1.2"], ["2.1", "2.2"], ["3.1", "3.2"]]) >>> ...
72bfdb19db3cf692e4260a5f75d10324e562f20e
30,690
import regex def bm_regex(regex_string): """Compile best multiline regex.""" return regex.compile(regex_string, regex.B | regex.M)
9c6507708b1d04ef91783bfd04f4949a9dfc6b76
30,691
def test_enable_8021q_1(monkeypatch): """Verify that enable_802q_1 function return exception when 802.1q is not supported by current os. """ def mockreturn(command): return CmdStatus("", "", 0) # monkeypatch.setattr(CLISSHNetNS, 'exec_command', mockreturn) lh = GenericLinuxHost(LH_CFG, OPTS...
4c3261ef788b369d185c4caff0f02a67818c5cc8
30,692
def qlearning_dataset(env, dataset=None, terminate_on_end=False, **kwargs): """ Returns datasets formatted for use by standard Q-learning algorithms, with observations, actions, next_observations, rewards, and a terminal flag. Args: env: An OfflineEnv object. dataset: An optional da...
bcc59e159ada77d2b3acaed530f190d3fcf8a706
30,693
import torch def build_save_dataset(corpus_type, fields, opt): # corpus_type: train or valid """ Building and saving the dataset """ assert corpus_type in ["train", "valid"] # Judging whether it is train or valid if corpus_type == "train": src_corpus = opt.train_src # 获取...
85594737b15ff356da3dcb431bab9c648122f57a
30,694
def gaussian_filter(image, sigma): """Returns image filtered with a gaussian function of variance sigma**2""" i, j = np.meshgrid(np.arange(image.shape[0]), np.arange(image.shape[1]), indexing='ij') mu = (int(image.shape[0]/2.0), int(image.shape[1]/2....
18f8d59ebe82fbeb5cc6090c3c01460923cbbf08
30,695
def get_lattice_points(strand): """ 格子点の情報を取得 @param ストランドの格子点の対 @return ストランドの格子点の始点と終点 """ strand_list = eval(strand) strand_from = strand_list[0] strand_to = strand_list[1] return strand_from, strand_to
a69902c15b9d8ce9f518891f4dea55d9aca186cf
30,696
def while_(condition): """ A while loop that can be used in a workchain outline. Use as:: while_(cls.conditional)( cls.step1, cls.step2 ) Each step can, of course, also be any valid workchain step e.g. conditional. :param condition: The workchain method that will retu...
6594c6da24d6a27d674ddb18713a0e521f0dc2dd
30,697
def new(init=None): """Return a new Whirlpool object. An optional string argument may be provided; if present, this string will be automatically hashed.""" return Whirlpool(init)
2d6bc8ce41009d642c78d92b022b44a23f67c496
30,698
def extract_bcr(tab, rep_col='CDR3_aa'): """ Extract BCR repertorie for each patient Args: tab: data table from TRUST BCR outputs rep_col: 'CDR3_aa' or 'complete_CDR3_sequences' or a list of keys Output: a Series vector containing lists of BCR CDR3 sequences """ ta...
998a3cfd6619b2fa3ae791e523f258a5a82e584b
30,699
def filter_labels(a, min_size, max_size=None): """ Remove (set to 0) labeled connected components that are too small or too large. Note: Operates in-place. """ if min_size == 0 and (max_size is None or max_size > np.prod(a.shape)): # shortcut for efficiency return a try: compone...
5754959bd2f404fa0189aee406c08745f236c294
30,701
def mask(bigtiff,profile,out_mask): """ mask a 1 or 3 band image, band by band for memory saving """ if profile['count']==4: bigtiff1 = bigtiff[0,:,:] bigtiff1[out_mask==1] = profile['nodata'] bigtiff[0,:,:] = bigtiff1 del bigtiff1 bigtiff2 = bigtiff[1,:,:] ...
0e31612da8d80f5fb4d8f35a0664708294e98312
30,702
def quadratic_sum(n: int) -> int: """calculate the quadratic num from 1 ~ n""" sum = 0 for n in range(1, n + 1): sum += n ** 2 return sum
e47a3ee49888c85cc06c72c428d983885ed7009f
30,703
def dag_rules(rules, required_keys): """ Serializing dag parameters from variable. Checking for required fields using required_keys :return dict dag_rules. An example of how they should look, in ..._settings.json, "airflow_settings" """ is_exists_rule_keys = all(key in rules.keys() for key in requir...
319096f113ff82c783266d83d8e194badeb7ec7d
30,704
import socket def ip_address(value): """Get IPAddress""" return write_tv(ASN1_IPADDRESS, socket.inet_aton(value))
beb56177436f7a67abbd2627ebf681eef3ed6352
30,705
def _GetUpdatedMilestoneDict(master_bot_pairs, tests): """Gets the milestone_dict with the newest rev. Checks to see which milestone_dict to use (Clank/Chromium), and updates the 'None' to be the newest revision for one of the specified tests. """ masters = set([m.split('/')[0] for m in master_bot_pairs]) ...
d3f8f78bb6aed29d2a7a932b288a84adf22e323b
30,706
def _hrv_nonlinear_poincare_hra(rri, out): """Heart Rate Asymmetry Indices. - Asymmetry of Poincaré plot (or termed as heart rate asymmetry, HRA) - Yan (2017) - Asymmetric properties of long-term and total heart rate variability - Piskorski (2011) """ N = len(rri) - 1 x = rri[:-1] # rri_n, x...
fff7f5c071b64fb44f7e8155a5ddf350a4586517
30,707
def headers(sheet): """Returns the values of the sheet's header row (i.e., the first row).""" return [ stringify_value(h) for h in truncate_row(next(sheet.iter_rows(values_only=True))) ]
26160064a3f0509d343140e3018e96fb1f7b91b4
30,708
def internal_server_error(message='Internal server error'): """500 Internal server error response""" errors = { '_internal': message } return error(500, errors)
d4ed017f6720ae3e62e5d6e66eb4d2cabd2a0775
30,709
def get_model(args, test=False): """ Create computation graph and variables. """ nn_in_size = 513 image = nn.Variable([args.batch_size, 3, nn_in_size, nn_in_size]) label = nn.Variable([args.batch_size, 1, nn_in_size, nn_in_size]) mask = nn.Variable([args.batch_size, 1, nn_in_size, nn_in_si...
9199034f0776e6d291185d130aadd78d7bf11ea0
30,710
import random def post_config(opt): """post_config""" # init fixed parameters opt.noise_amp_init = opt.noise_amp opt.nfc_init = opt.nfc opt.min_nfc_init = opt.min_nfc opt.scale_factor_init = opt.scale_factor opt.out_ = 'TrainedModels/%s/scale_factor=%f/' % (opt.input_name[:-4], opt.scale_f...
b7b7127e560b24a0d8242dfb9912852e2cd33c7d
30,711
import collections def select_device_with_aspects(required_aspects, excluded_aspects=[]): """Selects the root :class:`dpctl.SyclDevice` that has the highest default selector score among devices that have all aspects in the `required_aspects` list, and do not have any aspects in `excluded_aspects` list...
3f34baff8aab39ef88d20c610b203723712823af
30,712
def plus(a:int,b:int)->int: """ plus operation :param a: first number :param b: second number :return: a+b """ return a+b
f54224b8f8c0b599b7cd799aba0d291f11c4c16f
30,714
def linear_upsample_3d(inputs, strides=(2, 2, 2), use_bias=False, trainable=False, name='linear_upsample_3d'): """Linear upsampling layer in 3D using strided transpose convolutions. The upsampling kernel size will be...
42613b0aa245f53cc381a1c0b29ee5de67441c5c
30,715
def sample_ingredient(user: User, name: str = "Cinnamon") -> Ingredient: """Create a sample ingredient""" return Ingredient.objects.create(user=user, name=name)
c3ca73ece2c015608f54dd372749364c6d63b595
30,716
def naive_sample_frequency_spectrum(ts, sample_sets, windows=None, mode="site"): """ Naive definition of the generalised site frequency spectrum. """ method_map = { # "site": naive_site_sample_frequency_spectrum, "branch": naive_branch_sample_frequency_spectrum} return method_map[mod...
0aeb561437a521757fe1c884a063592b8ca2eb2e
30,717
import six import requests import json def make_server_request(request, payload, endpoint, auth=None, method='post'): """ makes a json request to channelstream server endpoint signing the request and sending the payload :param request: :param payload: :param endpoint: :param auth: :return:...
99c1bac6c3f010692f6e4b94b93ea77b4b655fde
30,719
import numpy as np def nan_helpfcn(myarray): """ Helper function to return the locations of Nan values as a boolean array, plus a function to return the index of the array. Code inspired by: http://stackoverflow.com/questions/6518811/interpolate-nan-values-in-a-numpy-array Input: - myarray, 1d ...
b5770e6bdfda85bc71fd954aacc4c31dbbd47f13
30,720
def _get_norm_layer(normalization_type='no_norm', name=None): """Get normlization layer. Args: normalization_type: String. The type of normalization_type, only 'no_norm' and 'layer_norm' are supported. name: Name for the norm layer. Returns: layer norm class. """ if normalization_typ...
8aa307db8c1ea93905cc5adddcec4a04f8718195
30,721
def run_single_camera(cam): """ This function acts as the body of the example; please see NodeMapInfo example for more in-depth comments on setting up cameras. :param cam: Camera to setup and run on. :type cam: CameraPtr :return: True if successful, False otherwise. :rtype: bool """ ...
b7a3df5fb0e44ac4ce293d6ff89d4955d662f482
30,722
import six def all_strs_text(obj): """ PyYAML refuses to load strings as 'unicode' on Python 2 - recurse all over obj and convert every string. """ if isinstance(obj, six.binary_type): return obj.decode('utf-8') elif isinstance(obj, list): return [all_strs_text(x) for x in obj]...
20b27cf809ed7fbf12b30a357d6aecfeeed88461
30,723
async def login_user(credentials: OAuth2PasswordRequestForm = Depends()): """Endpoint for logging user in.""" user = services.authenticate_user(email=credentials.username, password=credentials.password) if not user: raise HTTPException(status_code=401, detail="I...
d8e304b7cf718afce7a61c74ab38769d5695e7f5
30,724
def fahrenheit2celsius(f: float) -> float: """Utility function to convert from Fahrenheit to Celsius.""" return (f - 32) * 5/9
5161b29998553ad6ff497e698058f330433d90b3
30,727
def loadFireTurnMap(): """load in hard-coded 11x11 fire turn map, then flip so that access is [x][y] to match Board access""" boardSize = 11 fireMapFile = open( "fireTurnMap.txt", "r" ) data = [[int(n) for n in line.split()] for line in fireMapFile] fireMapFile.close() rotated = [[None for j in ...
a22350cf8ab488d719cdbaa0e3900c446b59b6f3
30,728
import itertools def get_param_list(params, mode='grid', n_iter=25): """ Get a list with all the parameter combinations that will be tested for optimization. Parameters ---------- params: dictionary Each key corresponds to a parameter. The values correspond to a list of p...
ed99bdff2a27df05e81f04e0495b60fc845ec5c3
30,729
def _apple_universal_binary_rule_transition_impl(settings, attr): """Rule transition for `apple_universal_binary` supporting forced CPUs.""" forced_cpus = attr.forced_cpus platform_type = attr.platform_type new_settings = dict(settings) # If forced CPUs were given, first we overwrite the existing C...
e672473db5b117102a2147445c0416f3a22b2b2d
30,730
def xml_get_text(_node): """Helper function to get character data from an XML tree""" rc = list() for node in _node.childNodes: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return unquote(''.join(rc))
0b611c0a95707b4220a114c7fe76c4fefd9d1615
30,731
def volume_get_all(context, marker, limit, sort_keys=None, sort_dirs=None, filters=None, offset=None): """Retrieves all volumes. If no sort parameters are specified then the returned volumes are sorted first by the 'created_at' key and then by the 'id' key in descending order. :...
664807482b6e26c6e96f8ec697d7d70a5c53d087
30,732
def merge_multirnn_lstm_state(states, w, b): """ Given two multirnn lstm states, merge them into a new state of the same shape, merged by concatation and then projection Args: state1: the first state to mergem, of shape (s1, s2, s3, ...), each s is of shape LSTMStateTuple(c,...
7ccc6666fafd1e1b6e117dc257598d88777c3e40
30,733
def gen_iocs(indicator_list): """ Generates a list of IOCs from a list of Anomali indicators :param indicator_list: list of Anomali indicators, types ip_address, url, or domain :return: list of IOC objects """ ioc_list = list() for i in indicator_list: pp = process_pattern(i.get('pat...
48bb07cf726f9052abbfc7de59e78f49f4b111d3
30,734
import csv def parse_input_specifications() -> dict[str, InputFile]: """ Ingest the input specs file and return a dictionary of the data. """ with open(PATH_INPUT_SPECS, 'r') as f: reader = csv.reader(f) next(reader) input_files = {} for row in reader: if...
fddc4b3ff1e9a45f09a62981fc12e7da1fa4e25c
30,736
import base64 def image_base64(img): """Return image as base64.""" if isinstance(img, str): img = get_thumbnail(img) with BytesIO() as buffer: img.save(buffer, "jpeg") return base64.b64encode(buffer.getvalue()).decode()
9a7cbbf9fd973831875ea0643547fd5abff2aa69
30,737
def read_file(file): """This function reads the raw data file, gets the scanrate and stepsize and then reads the lines according to cycle number. Once it reads the data for one cycle, it calls read_cycle function to denerate a dataframe. It does the same thing for all the cycles and finally returns a di...
8eb59ad8f8b700a0d0c26386644be97aa2417bb7
30,738
def calculate_performance(data): """Calculates swarm performance using a performance function""" df = pd.DataFrame(data) prev_column = None V = 0 G = 0 C = 0 vcount = 0 gcount = 0 ccount = 0 for column in df: v = calculate_max_speed(df, column, prev_column) g = calculate_vertical_mse(df, column) c = c...
dbf060501991b5408f8d102f35dbe60b34fae0a9
30,740
def ipn(request): """ Webhook handling for Coinbase Commerce """ if request.method == 'POST': request_sig = request.META.get('HTTP_X_CC_WEBHOOK_SIGNATURE', None) ''' # this was done in flask = request.data.decode('utf-8') try: # signature verificatio...
774ad9ebe0f1be9b65c73e90627640f66fe16d4c
30,741
def get_decomposed_entries(structure_type, species): """ Get decomposed entries for mix types Args: structure_type(str): "garnet" or "perovskite" species (dict): species in dictionary. structure_type(str): garnet or perovskite Returns: decompose entries(list): ...
0db24d7be2cacc2c0aed180cf5d31ccde057e358
30,742
def closest_point(p1, p2, s): """closest point on line segment (p1,p2) to s; could be an endpoint or midspan""" #if the line is a single point, the closest point is the only point if p1==p2: return (0,p1) seg_vector = vector_diff(p2,p1) seg_mag = mag(seg_vector) #print( "seg_ve...
5fbce0ac5b2d87f15b6dd5a146e77b23dba3d743
30,744
def new_name(): """ Returns a new legal identifier in C each time it's called Note: Not thread-safe in its current incarnation >>> name1 = new_name() >>> name2 = new_name() >>> name1 != name2 True """ global _num_names _num_names += 1 return '_id_{}'.format(_num_names)
bd72bfdedc7ccd00e973d9677e116cf5afe07314
30,745
def pollard_brent_f(c, n, x): """Return f(x) = (x^2 + c)%n. Assume c < n. """ x1 = (x * x) % n + c if x1 >= n: x1 -= n assert x1 >= 0 and x1 < n return x1
5037b3feac2f131645fbe6ceb00f0d18417a7c04
30,746
def morphological_transformation(input_dir): """ Performs advanced morphological transformations. Args: input_dir: Input Picture Data Stream. Returns: Picture Data Stream after Rotation Correction Processing. """ raw_image = cv2.imread(input_dir) gray_image = cv2.cvtColor(raw_...
b5db242cd39a71aea570d3f61b4c7a217565aa5d
30,747
import this # noqa: F401 def import_this(**kwargs): """Print the Zen of Python""" # https://stackoverflow.com/a/23794519 zen = io.StringIO() with contextlib.redirect_stdout(zen): text = f"```{zen.getvalue()}```" return text
1a80b384154f4cfa8b71eeb57807b8e9e3fce322
30,749
def getCurrentPane(): """Retrieve the current pane index as an int.""" return int(tget("display-message -p '#P'"))
f7439d407ef618c7d516ad9eed5c925c49639533
30,750
def get_lcc_size(G,seed_nodes): """ return the lcc size """ # getting subgraph that only consists of the black_nodes g = nx.subgraph(G,list(seed_nodes)) if g.number_of_nodes() != 0: # get all components max_CC = max(nx.connected_component_subgraphs(g), key=len) return ...
6582ab76a5b7a178d22592305d134529b327a2ec
30,751
def IsParalogLink(link, cds1, cds2): """sort out ortholog relationships between transcripts of orthologous genes. """ map_a2b = alignlib_lite.makeAlignmentVector() alignlib_lite.AlignmentFormatEmissions( link.mQueryFrom, link.mQueryAli, link.mSbjctFrom, link.mSbjctAli).copy(map_a2b...
012ad1a195c42127a39cabee9f7380c7cb8f6f9b
30,752
from numpy import array, vstack from scipy.spatial import Voronoi def segments(points): """ Return the bounded segments of the Voronoi diagram of the given points. INPUT: - ``points`` -- a list of complex points OUTPUT: A list of pairs ``(p1, p2)``, where ``p1`` and ``p2`` are the endp...
5d4c62455a605dfb09c1009b44e12ecd726e4c84
30,753
def tpu_ordinal_fn(shard_index_in_host, replicas_per_worker): """Return the TPU ordinal associated with a shard.""" return shard_index_in_host % replicas_per_worker
773313750ce78cf5d32776752cb75201450416ba
30,754
import string def replace_example_chapter(path_to_documentation, chapter_lines): """func(path_to_doc._tx, [new_chapter]) -> [regenerated_documentation] Opens the documentation and searches for the text section separated through the global marks START_MARK/END_MARK. Returns the opened file with that secti...
c4bb2285a55b0235d44a2550a3bad5a9d83583ad
30,755
def terminal(board): """ Returns True if game is over, False otherwise. """ if(winner(board)): return True for i in range(3): for j in range(3): if(board[i][j]==EMPTY): return False return True
0dd194c8281539977596779209d59533022ad16c
30,756
from typing import OrderedDict def get_network(layers, phase): """Get structure of the network. Parameters ---------- layers : list list of layers parsed from network parameters phase : int 0 : train 1 : test """ num_layers = len(layers) network = OrderedDict()...
cfbbcc99195a4e81503a89ce80a6d2314c2deb30
30,757
def create_category_hiearchy(cats, categoryType): """A function that creates a dict of the root and subroot categories""" dict_out = {} for key in cats.keys(): name = cats[key]['name'] parent_name = cats[key]['parent']['name'] cat_type = cats[key]['categoryType'] if cat_typ...
f0b19f2a6f56e49855a019a18d9357a31cfaeb2a
30,758
import time def date(): """ Returns the current time formated with HTTP format. @return: `str` """ return time.strftime('%a, %d %b %Y %H:%M:%S GMT')
909f1f31c6c7f0ed03fe0b30785ff454f541a5fc
30,760
def _estimate_gaussian_covariances_tied(resp, X, nk, means, reg_covar): """Estimate the tied covariance matrix. Parameters ---------- resp : array-like of shape (n_samples, n_components) X : array-like of shape (n_samples, n_features) nk : array-like of shape (n_components,) means : arra...
3bf510982698643afd9377e64d8fe569d7626452
30,761
from re import A def rights(value_strategy: SearchStrategy[A] ) -> SearchStrategy[either.Right[A]]: """ Create a search strategy that produces `pfun.either.Right` values Args: value_strategy: search strategy to draw values from Example: >>> rights(integers()).example() ...
867db62f02955bf226109bf1cb8f04d4fb3f578c
30,762
def lpad(col, len, pad): """ Left-pad the string column to width `len` with `pad`. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(lpad(df.s, 6, '#').alias('s')).collect() [Row(s=u'##abcd')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.lp...
b2a8b01b06166b4fd4ec09b76b634c8b2e231d86
30,763