content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Tuple from typing import List def sanitize(report: str) -> Tuple[str, str, List[str]]: """Returns a sanitized report, remarks, and elements ready for parsing""" clean = sanitization.sanitize_report_string(report) data, remark_str = get_remarks(clean) data = core.dedupe(data) dat...
ae4159bb8b947c4e74ae2c63f9e49233b6c85c83
50,662
def matfromrcell(astar, bstar=None, cstar=None, alphastar=None, betastar=None, gammastar=None): """Make standard-orientation reciprocal cell matrix from reciprocal cell. """ if isinstance(astar, CellParam): cell = astar else: cell = fillCellParam(astar, bstar, cstar, alp...
2c3d0545a14f9b6337e0b4cc0e5e606832bb4ea3
50,663
from typing import List def list_octicons() -> List[str]: """List available octicon names.""" return list(get_octicon_data().keys())
5a48163e34ec17e5c51c82f0d4b7f06f093bd258
50,664
def sampler_params(scope="function"): """Common parameters for sampler test""" params = { "tag_type": "ner", "query_number": 4, "label_names": ["O", "PER", "LOC"], "token_based": False, "tagger": MagicMock(), "embeddings": MagicMock(), "kmeans_params": {"n...
5e16ca4a223363a8cc637b58625a2f3aa650a260
50,665
def strip_xml(element): """ Recursively strip clean indentation from xml. Especially useful if you're using a template. For example, this is a bit of a mess: >>> xml_mess = ''' ... <help> How did ... ... <person>I ... </person> ... get to be so <cleanliness ...
e7938d19aa7202f1c8f4986b62a5556bb91fa6ac
50,667
import torch def add_gaussian(p, g_std): """add gaussian noise :param p: input tensor :param g_std: standard deviation of Gaussian :returns: tensor with added noise :rtype: tensor """ if g_std > 0: size = p.size() p += torch.normal(0, g_std, size=size) return p
025bfffca50463589619051f58b5d8e95341c0bd
50,668
def extension_supported(extension_name, request): """ this method will determine if nova supports a given extension name. example values for the extension_name include AdminActions, ConsoleOutput, etc. """ extensions = list_extensions(request) for extension in extensions: if extensio...
3087a0d9a5d9a64d4e4fc0b0f8b0c6ceafa577b6
50,669
from typing import OrderedDict import re def parse_interactions(input_file): """ Parse through the interactions input file. @param[in] input_file The name of the input file. """ # Three dictionaries of return variables. Systems = OrderedDict() Interactions = OrderedDict() Globals = ...
630b2ee0d4c7e7c39e78ce62a0678e3b60f5a3ab
50,671
def get_rates_above_threshold(y_vals, rec_bins): """ Gives the total number of interactions above every given threshold The input is expected to be integrated rates over time. Thus, the total rate returned is counts/kg/t_full Parameters ---------- y_vals : `array` ...
9af8cae3cf85223cec769f44c6be3358a5aab03f
50,672
def stormpath_login(request): """ Verify user login. It uses django_stormpath to check if user credentials are valid. """ if settings.USE_ID_SITE: return redirect('sample:stormpath_id_site_login') if request.user.is_authenticated(): return redirect('sample:home') form = Au...
c2394c957c7393f590173e71d8b4b15cab932b1e
50,673
def chain(_input, funcs): """Execute recursive function chain on input and return it. Side Effects: Mutates input, funcs. Args: _input: Input of any data type to be passed into functions. funcs: Ordered list of funcs to be applied to input. Returns: Recusive call if any functi...
3f2d1490044f0eb35656bd7601d1569fb6f8a553
50,674
def sample_circle(c, N=32): """ Sample points on a circle c Returns a 2D PointSet with N points """ assert len(c) == 3 # Get x, y and radius x, y, r = c # Sample N points, but add one to close the loop a = np.linspace(0,2*np.pi, N+1) # Prepare array pp = ...
357433b7d5fd228838c472b6132e282d95863c08
50,676
def turn_animation_into_updater2(animation, cycle=False, delay=0.0, **kwargs): """ Add an updater to the animation's mobject which applies the interpolation and update functions of the animation If cycle is True, this repeats over and over. Otherwise, the updater will be popped upon completion ...
7ce9e5a0ca6830b181de8503ed12e70e465f61e9
50,677
def all_levels(df, bucket_var, include_levels=None, ret_map=False): """ Assign each row of `df` to a bucket according to the unique values of `bucket_var`. bucket_var: Column name of the values to split on. Missing values will not be assigned to an interval. include_levels: Level value...
e16044f7a7cef4cade372938b29b48661dd2325c
50,678
import logging def loss_function(real, pred, loss_object): """ measure loss object in a logically consistent way :param real: :param pred: :param loss_object: :return: """ logging.info("loss_function") mask = tf.math.logical_not(tf.math.equal(real, 0)) loss_ = loss_object(real,...
1051ba1243698731131f9a42d1f10f2d6d19c475
50,679
def Z(theta=0, pulse_pars=None): """ Software Z-gate of arbitrary rotation. :param theta: rotation angle :param pulse_pars: pulse parameters (dict) :return: Pulse dict of the Z-gate """ if pulse_pars is None: raise ValueError('Pulse_pars is None.') else: ...
054133afad02dd15aceca4a5a60ad58c0d2783c5
50,680
def spend_separator_tx(tx_sep_tx, keys_for_sep_tx): """spends Transaction with scriptPubKey in form of: <pk1> OP_CHECKSIGVERIFY OP_CODESEPARATOR <pk2> OP_CHECKSIGVERIFY OP_CODESEPARATOR ... <pk N_signings> OP_CHECKSIG """ tx = CTransaction() tx.vin.append(CTxIn(COutPoint(tx_sep_tx.sha256, 0), b"",...
cb01f0ed7dc884fbc8dbb05a83a1748792f21b79
50,681
def get_nested_grid_bounds(land_cover_pth): """ Get the lat/lon bounds of the nested grid window (NA, EU, AS) for the inversion. The land cover file path specifies the window. """ if "NA" in land_cover_pth: if "GEOSFP" in land_cover_pth: minLat_allowed = 9.75 maxLat_...
49a2debbe5ee2cea9c74084d95a52f31313eb4b3
50,682
def get_resolution_HRF(): """Returns RIM_ONE_v2 resolution after post-processing.""" return (3504, 3504)
4d50b1a08a469f5790a7e59207fcde3956c4fa2d
50,683
import string import random def generate_password(size=4, chars=string.ascii_uppercase + string.digits): """Randomly generate a password with length `size`. Args: size (int): Length of the password. chars (str): The char appeared in this string will be considered as one of the choice....
bb0230810ddf6d4946146798ea304f321c8b3ae4
50,685
def overlaps_bool(pred_roi, bbox): """ :param rois: regions of interest in format (y1, x1, y2, x2) :return: Boolean Example: [[ 99,325,135,363], [ 54,229,88,264], [ 53,230,94,266], [ 93,321,132,361]] -> [1, 2, 2, 1] """ l_1_y1 = pred_roi[0] l_1_x1 = pred_roi[1] r_1_y2 = pre...
c186026967b7016aba7ce21cd9d710b51af74d91
50,686
def spec_exists(notification: Notification) -> bool: """ Check whether the spec exists. Args: notification: The SNS notification. Returns: Whether the spec file in the SNS notification exists. """ response = S3_CLIENT.list_objects_v2( Bucket=notification.bucket_name, P...
851a29189e63b8d727a1fd73a65c8970350fad51
50,688
def person(request, pk): """ Retrieve, update or delete a code snippet. """ try: person = Personnel.objects.get(pk=pk) except Personnel.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = PersonnelSerializer(person) return JsonResponse(serializer.data) elif request.me...
1bf25578ef1acc020b2aab91e825c642babb3815
50,689
import re def underline_to_hump(underline_str): """ Transfer underline to hump Args: underline_str(string): underline code string """ sub = re.sub(r'(_\w)', lambda x: x.group(1)[1].upper(), underline_str) return sub
dbc59ced8306088f08b6997c305c468370b4631d
50,691
def get_query_workload(duration_sec, rate): """ Returns an array of query tuples (see get_next_query()) for the given duration and rate """ cur_time = 0.0 workload = [] while cur_time < duration_sec: q = get_next_query(rate, duration_sec) cur_time += q["dt"] workload.appe...
86e4b9e7e71b74400ffccf60317be5ae1a060aae
50,692
def successor(node): """ 4.6 Successor: Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent. """ def get_min(node): if node.left != None: return get_min(node.left) ...
448342a8adcdf73ba73a5e6b4319cd299d1bc9a8
50,694
import traceback def get_length_audio(audiopath, extension): """ Returns length of audio in seconds. Returns None if format isn't supported or in case of error. """ try: audio = AudioSegment.from_file(audiopath, extension.replace(".", "")) except Exception: print(f"Error in get...
66408053a89a82b9ce9e0dc920ed91b990ac4158
50,695
import json def load_schema(data): """ Load Schema/Example data depending on its type (JSON, XML). If error in parsing as JSON and XML, just returns unloaded data. :param str data: schema/example data """ try: return json.loads(data) except Exception: # POKEMON! pass ...
13979ca2b649514524b12dc7a305c875a7140305
50,696
def netcdf_file_handler(index): """ Returns file info and phenomena information of a NETCDF file. """ fname = "file_%02d" % index fmeta = get_file_doc(fname) #fphen = get_file_phenomena() fphen = get_file_phenomena_i(index) return (fmeta, fphen)
b0a463a7cc6b6bcc8c80a3a47e248eb4dc637474
50,697
def calculate_transform(src, dst, model_class=AffineTransform): """Calculate transformation matrix from matched coordinate pairs. Parameters ---------- src : ndarray Matched row, column coordinates from source image. dst : ndarray Matched row, column coordinates from destination ima...
cbe4455d34753d6d7d0fb930a2b86a93d86dea1a
50,699
from typing import Iterable from typing import List from typing import Dict def after_attack_all(skills: Iterable[Skill], arena: ActiveArena, data: AfterAttackData) -> List[Dict]: """ Executes the after_attack_effect for all the given skills, if such exists, returning a list of their cumulative output, if...
3491d58d8b6412c3366e9fd902043cfe020754cb
50,700
from typing import Tuple from typing import Any def _get_laplace_matrix_2d(bcs) -> Tuple[Any, Any]: """get sparse matrix for laplace operator on a 2d Cartesian grid Args: bcs (:class:`~pde.grids.boundaries.axes.Boundaries`): {ARG_BOUNDARIES_INSTANCE} Returns: tuple: A sparse ...
2e2845ea64829d98b01484a0f5268ed352999cfc
50,701
def build_zooma_query(trait_name: str, filters: dict, zooma_host: str) -> str: """ Given a trait name, filters and hostname, create a url with which to query Zooma. Return this url. :param trait_name: A string containing a trait name from a ClinVar record. :param filters: A dictionary containing fi...
0fb22b1f44319c2fa8e87d8e720de248dd1a7eba
50,702
def _flatten_nested_jacobian(jacobian, state_shape): """Flattens a nested Jacobian into a matrix. The flattening and concatenation follows the interpretation of the structure as being a leading 'axis', meaning that if the input has 'shape': [input_structure, A, B], and the output has 'shape': [output_structu...
f03af541be656b3c21d088f561fa92d016372b17
50,703
def figletbulbhead(txt): """ FigletBulbLook Text """ f = Figlet(font='bulbhead') return f'{f.renderText(txt)}'
1eebc94b7f3ffa5c8f158533ccc9234b0a129e29
50,704
import struct def bytes_to_element(type, bytes, byteorder = 'little'): """Returns a python object parsed from bytes :param type: the type of the object to parse :param bytes: the bytes to read :param byteorder: little or big endian """ if type == 'char': return ord(struct.unpack('<b',...
02bfd7e6e5858fb265dfc9c3a2d57109e65f8e5e
50,705
def extract_predictions(data, predictions): """' Joins a dataframe containing match data with one containing predictions, returning a dataframe with team names, predicted values, and if available, the actual outcome (in points). """ probs = _team_test_prob(predictions) teams0 = [] teams1...
2fb6a99e5f1afbd5ebeecb7ffc20a26edf642ce5
50,707
def naturalnumber(value: int | float, *, caps: bool = True, digits=1) -> str: """ Makes a number to a human-readable string. Examples: naturalnumber(1000) -> "1k" naturalnumber(100000) -> "100k" naturalnumber(1000000) -> "1m" naturalnumber(1000000000) -> "1b" naturalnumber(1000000000, c...
9d2fbef692ff228ae1344ee78c16944afc82dd16
50,708
import inspect import pickle def request_analysis(user, analysis_func, subject, *other_args, **kwargs): """Request an analysis for a given user. :param user: User instance, user who want to see this analysis :param subject: instance which will be used as first argument to analysis function :param ana...
d49b8ed51641157051b47be6b76b1152db563992
50,709
def sequences_to_one_hot(sequences, chars='ACGTN'): """ :param sequences: :param chars: :return: """ seqlen = len(sequences[0]) char_to_int = dict((c, i) for i, c in enumerate(chars)) one_hot_encoded = [] for seq in sequences: onehot_seq = [] integer_encoded = [ch...
76af4e23d0dc4e6a0cd6098df4e5966aa79a8258
50,710
def __virtual__(): """Only load keystonev3 if requirements are available.""" if REQUIREMENTS_MET: return 'keystonev3' else: return False, ("The keystonev3 execution module cannot be loaded: " "os_client_config or keystoneauth are unavailable.")
08edf53888d9fe5adacff283d74ec6b3142b8776
50,711
def combined_equal_all_basic_types() -> tuple: """Combined tuple of all basic types""" combined_types: tuple = tuple( (value, value) for value in _ALL_BASIC_TYPES_1.values() ) return combined_types
e030e46e07a0481bd81338e51f14ef01c423c277
50,712
def n_cyber_object_to_node(graph): """ Initial function to create the blank nodes for each of the file's facet nodes :param graph: rdflib graph object for adding nodes to :return: The four blank nodes for each fo the other functions to fill """ cyber_object_facet = rdflib.BNode() n_raster_fa...
af401ef618fc00920505192face4e804470b5f0e
50,713
def freeze_module_until(module, name): """ Freeze all submodules inplace before and including `name`. If `isintance(name, list)`, submodules before and including every `name` will be frozen. Args: module (nn.Module): torch.nn.Module name (list(str)): submodule name """ def _is_c...
8d649f973f772f02f56594d365a05cb902734999
50,714
def pad_to_batch(dataset, batch_size): """Pad Tensors to specified batch size. Args: dataset: An instance of tf.data.Dataset. batch_size: The number of samples per batch of input requested. Returns: An instance of tf.data.Dataset that yields the same Tensors with the same structure as the origin...
e102abdc097f2983e01766444b728b3c6a76269d
50,715
import ast def apply_ast_transformations(source): """Used to convert the source code into an AST tree and applying all AST transformer specified in the source code. It returns a (potentially transformed) AST tree. "AST transformers" are modules which must contain a function trans...
b20fff4ad328bacb5bddfe7b7d106d621576ad96
50,716
def create_full_name_without_space_fields(romanize_method, given_name, family_name): """ Creates fields with the full name without white spaces. Returns: fullname fields, romanized_name_list: (for check) """ fields = [] romanized_name_list = [] ...
e57bf553e74f70faa425a48061218c6bd3f47c2c
50,717
import time import calendar def read_wdnr_monthly_water_use(wu_file, wu_points, model, active_area=None, drop_ids=None, minimum_layer_thickness=2 ): """Read water use data from a master ...
0eb8b0a55836fd85d76f5db227b178fbe871084e
50,718
import random import string import requests def create_coupon(auth_token: str, mavenseed_url: str, args: Args) -> None: """Creates a coupon with the given coupon code on the Mavenseed platform.""" def generate_random_coupon_code() -> str: """Generates a random coupon code with 8 characters.""" ...
8708f99e1de3f6b05fa0159e3c37d5ae29fd7cd3
50,719
def validate_clockwise_points(points): """ Validates that the points that the 4 points that dlimite a polygon are in clockwise order. """ if len(points) != 8: raise Exception("Points list not valid." + str(len(points))) point = [ [int(points[0]) , int(points[1])], ...
53a785fe6dfc9613200c4d5e05890340e3d6e910
50,720
def get_available_recipes(): """ Returns a dict of the available user-recipes """ recipes = {} for name, data in custom_recipes.items(): recipes[name] = { 'name': name, 'parameters': data['parameters'] } return recipes
3dd5525f199ecbf9ceb61b95c9abe2c4b8c64f6b
50,721
from datetime import datetime import time def wait_for_workflows(client, namespace, names, timeout=datetime.timedelta(minutes=30), polling_interval=datetime.timedelta(seconds=30), status_callback=None): """Wait for multiple workflows to finish. Ar...
e17da62443ab8e72d583f0c0169846747864c2f0
50,722
def _uncomment_magic(line): """Reverts the comments applied to magics (line level) """ if line.startswith(_PREFIX): return line[_PREFIX_LEN:] parts = _is_commented_line_magic(line) if parts: code, magic = parts return f'{magic} {code}' else: return line
e41a93fc763360d24bf5fec4cd948c97d631a730
50,723
import builtins import six def get_context(entity): """Returns the operating context of the given object. If the object is a subclass of Context, returns the top most context (or containing instance) of the object. If the object is a builtin object, returns the operating module (if available). ...
3eb1d6edb0c5c8136c10043968c18d273bae5ac9
50,724
from typing import Any def ret(d: dict, key: str) -> Any: """ Unwrap nested dictionaries in a recursive way. Parameters ---------- d: dict Python dictionary key: str or Any Key or chain of keys. See example below to access nested levels. Returns ---------- out...
86d07ba6dbe2610ceabb0bcee3099b5734c770ae
50,725
import types def _conical_frustum_to_gaussian(z_vals: f32['... num_samples 1'], rays: types.Rays): """Approximate a conical frustum as a Gaussian distribution (mean+cov). Assumes the ray is originating from the origin, and rays.base_radius is the radius at dist=1. Doesn't assum...
df48aabfac89372ce451b3190e59cc559246ca8d
50,728
import time def MLE_NQB_sim(n, measurements, paulis, variances, density_matrix, tolerance, random_initialization, max_iter_num, nlvl=2, plot_convergence=False, verbose=False, directory_path=""): """Maximum likelihood estimation for n_qubit n_level qubit state tomography. F...
ce8d6cb6bc915c1359c77272e999964346683e30
50,730
def portmap_portstat_route(port): """generate port statistics fragment""" stats = db.session.query(Service.proto, func.count(Service.id)).join(Host) \ .filter(Service.port == port) \ .group_by(Service.proto).order_by(Service.proto) infos = db.session.query(Service.info, func.count(Service....
03dda63f4ab8e91f903226688ca5994326081704
50,732
def authenticate(data): """Admin broadcast channel authentication""" if "token" in data: current_user = User.verify_auth_token(data["token"]) if current_user is not None and current_user.can(Permission.ADMIN): room = Channel.get_room() join_room(room) emit("au...
73b9eddff09d80a1d39171cc2dbb415c0c649ebb
50,733
def closet_common_manager(ceo: Employee, first_employee: Employee, second_employee: Employee)->Employee: """ 得到our boss :param ceo: 起始节点,Employee :param first_employee: 第一个雇员, Employee :param second_employee: 第二个雇员, Employee :return: 一般会返回一个正确的结果, 异常情况:Employee.EmployeeNotIn -> 雇员不在ceo管辖范围 ...
f2f4d119024d1b2f16bae9a027962e0162af64e9
50,735
def instance_destroy(context, instance_uuid, constraint=None, update_cells=True): """Destroy the instance or raise if it does not exist.""" rv = IMPL.instance_destroy(context, instance_uuid, constraint) if update_cells: try: cells_rpcapi.CellsAPI().instance_destroy_at_top(context...
0b2d78445561c1bf40321507bec58784a9cb969a
50,736
def group_excessive_points(gdf: gpd.geodataframe.GeoDataFrame, cell_size: float): """ Creates groupings of collocated points exceeding a threshold. By default, a grouping is defined as three times the average cell size of the input file. :param gdf: :param cell_size: :return: """...
68bdab8ae34e7ba7b8f3311a36509200a490ac8d
50,738
def local_conv2d(inputs, kernel, kernel_size, strides, output_shape, data_format="channels_last"): """Apply 2D conv with un-shared weights. Arguments: inputs: 4D tensor with shape: (batch_size, filters, new_rows...
7fe612725b16c157d9dda7eff28dd3126e583a68
50,739
def convex_hull(points, return_copy=False): """Computes the convex hull of a set of 2D points. Input: an iterable sequence of (x, y) pairs representing the points. Output: a list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically...
526f29fe04e84e68098015b2a8a5d2a82fb78940
50,740
def unit_to_altaz(x, y): """Convert coordinates on the projected skydome to alt,az coordinates Args: x, y: float coordinates, normalised to the unit circle Returns: Tuple[float, float]: alt, az coordinates in degrees """ R = min(sqrt(x**2 + y**2), 1) alt = degrees(a...
91d73fb997e3b0c020925213b2af7374c683ec6e
50,741
from typing import Any from pydantic import BaseModel # noqa: E0611 from datetime import datetime def fields_in_create(obj: Any): """Build dictionary for data insert by adding createdAt field""" if isinstance(obj, BaseModel): return { **obj.dict(), "createdAt": datetime.utcnow(), "updatedAt": None} ...
a7cdff857329f953b495b634942fa4e94b2baf74
50,742
def build_matrix(node, m, k, D, beta): """Compute k-tree algorithm matrices for each node of the tree. Args: node (KTreeNode): the top node of the tree. m (int): the alphabet size. k (int): the number of trees requested. D (int): the depth of the tree. Returns: int: t...
634fc4ff32c2fe24f450bad2505aed77e0100c97
50,743
import ast def mesh_select_face(mesh, message="Select a face."): """Select a single face of a mesh. Parameters ---------- mesh: :class:`compas.datastructures.Mesh` message: str, optional Returns ------- int or None """ guid = rs.GetObject(message, preselect=True, filter=rs.fi...
d2bae92384e445b0eba917a4b667fd1e5bc911ff
50,744
def simpleMergeMotifs(motifs, window=0): """ aggregates the motifs if they overlap, into one motif file Args: ---- motifs: df bed-like of motifs locations window: int maxsize around motif for which to still merge Returns: -------- df bedlike of merged motif: df bedlike of motifs that were not merged as ...
ff0735b293d8c26849bab79b9b7169c36236888f
50,745
def to_minutes(hour, minute): """ converts hours to minutes and adds extra minutes in the time... returns the sum """ return (hour * 60) + minute
05cc1cada49c7a2c84b3fa32cd9fb7bf805be751
50,746
import copy def _copy_to_tail_args(args: Namespace, as_router: bool = True) -> Namespace: """Set the incoming args of the tail router """ _tail_args = copy.deepcopy(args) _tail_args.port_in = random_port() _tail_args.port_ctrl = random_port() _tail_args.socket_in = SocketType.PULL_BIND _ta...
5146d68499a308ac07186a0e0a9f6bed55871746
50,748
import binascii def encodeAsMarket(data): """ Hide data inside a url commonly used for email personalization Parameters: data - the data to encode Returns: a dictionary with the key 'url' referencing a string holding the url and the key 'cookie' holding an array of 0 or more cookies. Note: Cookies ...
3792899bdbe1187ccd3ecb49b0c638ac1c4de02e
50,749
def is_identity(u): """Checks if the unit is equivalent to 1""" return u.unitSI == 1 and u.unitDimension == (0,0,0,0,0,0,0)
afc9029eeb44739a38869f06f84ba36b2a19da6f
50,750
def m_seq_inx_to_int(seq, args=0): """ 将列表中单个列表中元素转成int,返回新的列表 :param seq: 列表形成的列表 :param args: 列表的次序 :return: 转换后的列表 example: :seq [['30', 0], ['5', 1]] :args 0 :return [[30, 0], [5, 1]] """ for i in seq: ...
f6ba3c4060edffd704c53752df88b4dcfbdbef68
50,751
def convert_df_dates_to_str_or_none(df, cols): """Convert dataframe dates to str or None. Parameters: df (pd.DataFrame): The input dataframe cols (sqlalchemy table columns): The colums for the associated table Returns: df (pd.DataFrame): DataFrame with idntified date columns as str...
e8653c6017afe5844f6f7be36be28eede2ce9d62
50,752
def find_nearest(df, value, value_col="Insertion Loss (dB)", index_col="Frequency (Hz)"): """Given a pandas dataframe, find value corresponding to nearest index""" index = (np.abs(df[index_col]-value)).argmin() return df[value_col][index]
05ddf693cba3a63187a955a3d8f9356f9f2e8b2f
50,753
def source_df() -> pd.DataFrame: """ Produces a dataframe containing source coordinates for testing. Contains ra and dec. Returns: Dataframe with coordinates. """ source_df = pd.DataFrame( data={ 'ra': [ 12.59305887, 12.68310734, ...
4a04eea15119ee854cb4b87cc788ec738d136f55
50,754
from pathlib import Path def read_from_csv(path): """read data from csv""" if not Path(path).exists(): return None if not path.endswith('.csv'): return None with open(path, 'r') as file: data = pd.read_csv(file, header=0) return data
84e4b6ead3bfe18165aea5b69effd7c8c815c120
50,756
def compute_moments(features, input_channels=3): """ Computes means and standard deviation for 3 dimensional input for normalization. """ means = np.zeros(input_channels, dtype=np.float32) stddevs = np.zeros(input_channels, dtype=np.float32) for i in range(input_channels): # very specifi...
1701e63481241a6e3eb1d90ca289eed6dad54945
50,757
def _normalizeGlifContourFormat2(element): """ - Don't write unknown subelements. """ # INVALID DATA POSSIBILITY: unknown child element # INVALID DATA POSSIBILITY: unknown point type points = [] for subElement in element: tag = subElement.tag if tag != "point": co...
909b4027e379fa4d4576c90ab50d021c7ec8699e
50,758
def _compile_fragment_ast(schema, current_schema_type, ast, location, context): """Return a list of basic blocks corresponding to the inline fragment at this AST node. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the...
c4a87bbde57d26f51e03cc95be0a9db59a138d0c
50,759
def _parse_one_service_message(s): """ Parses one service message. :type s: str :rtype: service_message """ b1 = s.index('[') b2 = s.rindex(']', b1) inner = s[b1 + 1:b2].strip() space1 = inner.find(' ') if space1 >= 0: name_len = space1 else: name_len = inner....
78e70a3974b2302d10fdd00222423f8ee4fb4e61
50,760
def medidasChars(T): """Medidas de letras TTM formatar para passagem como dicionário""" nchars=len(T) # nspaces=T.count(" ") nletters=sum([t.isalpha() for t in T]) nuppercase=sum([t.isupper() for t in T]) nvowels=sum([t in ("a","e","i","o","u") for t in T]) npunctuations=sum([t in puncts for...
1a66b4535dc5b42b8c40512132c6010e44f13aa9
50,762
from datetime import datetime def read_chl(filename, field_names=None, additional_metadata=None, file_field_names=None, exclude_fields=None, use_file_field_attributes=True): """ Read a CSU-CHILL CHL file. Parameters ---------- filename : str Name of CHL file. ...
e6df2de26331eb72838b050d6050da6ca5eee70c
50,763
import pathlib def get_tree(tree_type, cfg, section, option): """Load a tree from file or parse a string. If the provided value is the name of an existing file, read the contents and treat it as a Newick tree specification. Otherwise, assume the provided value is a Newick tree specification. Trees c...
077ff497e32a9695ae146c381a29361187511bc6
50,764
def common(first_list, second_list): """Receives two lists, returns True if they have any common objects and false otherwise. Note that this implementation should theoretically work with any container-like object for which the in operator doesn't have a different meaning.""" # iterate over the elements ...
da48a3a559bc26a79bc5aa06ca6efa15053e1cd4
50,765
def base_download_namespace(api_keypath, path_fixtures_base, tmp_path): """Base namespace for the pyani download subcommand.""" return Namespace( outdir=tmp_path / "C_blochmannia", taxon="203804", email="my.email@my.domain", retries=20, batchsize=10000, timeout=10...
e1487b8295edd27e1b04f8cebd42c81126325b87
50,766
def Correct_Surface_Temp(Surface_temp,Temp_lapse_rate,DEM_resh,Pair,dr,Transm_corr,cos_zn,Sun_elevation,deg2rad,ClipLandsat): """ Function to correct the surface temperature based on the DEM map """ #constants: Gsc = 1367 # Solar constant (W / m2) cos_zenith_flat = np.cos((90...
bd98e5d211ad6203793078a74396852c177b90c9
50,767
from typing import Dict from typing import Tuple from typing import Collection from typing import Any from typing import Set def aggregate_unique_objects(edges: Dict[str, Dict[Tuple[str, str], Collection[Any]]]) -> Dict[ str, Dict[Tuple[str, str], Set[Any]]]: """ Performs an aggregation of the occurrences...
a89fb6a1e4203610ee00756d1486cd147ddee49e
50,768
import logging def receive(conn): """Receive a message conn has to be the socket which receive the message A message has to end with the bytestring b'\xDE\xAD\xE1\x1D' """ ip, port = conn.getpeername() logging.info('Receiving a message from '+ip+':'+str(port)) data = b'' while...
0b6f4e9c6fd3a38a33f625fe6b736020a044ca61
50,769
def lstm(token_embeddings, hid_dim=128, hid_dim2=96): """ LSTM network. """ # lstm layer fc0 = fluid.layers.fc(input=token_embeddings, size=hid_dim * 4) lstm_h, c = fluid.layers.dynamic_lstm( input=fc0, size=hid_dim * 4, is_reverse=False) # max pooling layer lstm_max = fluid.lay...
6e398cebf01f47800c45c46832ef7fc7b82d1c1f
50,771
def SetVPNClusterPath(ref, args, request): """Sets the vpnConnection.cluster field with a relative resource path. Args: ref: reference to the cluster object. args: command line arguments. request: API request to be issued Returns: modified request """ # Skips if full path of the cluster res...
629bafca1da8a479b72c936c352ade9fe53d27b7
50,772
def list_nmmr_option_bitfield(fp, child, sfrname, offset): """ Format a single bitfield of NMMR OPTION pseudo register Input: - index in .pic - register node Notes: - Expected to be used with 12Fs only """ if (child.nodeType == Node.ELEMENT_NODE): if (child.nodeName == "edc:Adjust...
834e3f16f00fc6ff2324f908a0ec0f95a5571956
50,773
from typing import Sequence from typing import List def qubit_pairs_to_qubit_order(qubit_pairs: Sequence[Sequence['cirq.Qid']]) -> List['cirq.Qid']: """Takes a sequence of qubit pairs and returns a sequence in which every pair is at distance two. Specifically, given pairs (1a, 1b), (2a, 2b), etc. returns...
7bb23f99266d5cfab4b587831d6ae5a182a0cbb7
50,774
def calculate_carryover_vector(model, car, last_10_rows): """ calculates carryover vector by iterating over each channel, and running carryover on each channel given the sampled car value """ cv = [] post = model.trace.posterior for idx, channel in enumerate(model.feature_names_in_): ...
6d23ff7654efc41cd635756a0116f61cb76d6781
50,775
from typing import Callable import click def config_path_option(exists: bool = True) -> Callable: """ A convenience decorator As we'll probably want to be able to specify the config in pretty much every console command """ def decorator(f: Callable) -> Callable: option = click.option( ...
b3e62578b6a2c6e16d5e0f622fd07130c4e7b079
50,778
import itertools def gabor_filter_parallel(image, mask, parameters=dict(), n_jobs=1, backend='threading'): """ Apply gabor filters to image, done in parallel. Note: on a cluster, where parallelisation of the gabor filters is not possible, use backend="threading" """ ...
4352d086371523eec922e49055207930864abb38
50,779
def from_numpy_array(A, create_using=Graph): """ Initializes the graph from numpy array containing adjacency matrix. Parameters ---------- A : numpy.array A Numpy array that contains adjacency information create_using: cugraph.Graph (instance or class), optional (default=Graph) ...
2fb0c48a32b31abaa21e9878f752244624e73649
50,780
def success_centroid_error(gt_poly, res_poly, thresholds, n_frame): """ :param gt_poly: [Nx8] :param result_bb: :param n_frame: :return: """ success = np.zeros(len(thresholds)) centroids_gt = [] centroids_res = [] for i in range(gt_poly.shape[0]): poly1 = res_poly[i].r...
a15175cc2813be15f554eb362735bcfffc2c161a
50,782
def is_path_head(path: str) -> bool: """ Determin if a path string is a path head. >>> is_path_head('path.ext') True >>> is_path_head('/dir/path.ext') False Args: path (str): Path string. Returns: bool: If the path string is a path head. """ return path_head(p...
93530bbd51413dfc14ca992a7243f961e4f22ec1
50,783