content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Union def euclidean_distance(p1: Union[Vector, np.array], p2: Union[Vector, np.array]) -> float: """Euclidean distance between two 3D points. Support {Vector} and {np.array} as data types. Arguments: p1 {Union[Vector, np.array]} -- first 3D point p2 {Union[Vector, np.array]...
4ebad943fbb46f34ffbceb43a7b8ec90c8340f6f
3,608,838
def suffix(pattern, k): """we define SUFFIX(Pattern) as the last (k-1)-mers in a k-mer Pattern""" return pattern[-(k - 1):]
d6cec61ba024f551071a6ba9d6409963ff2ffe7d
3,608,839
import time def wait_for_reload(ctx): """ Wait for system to come up with max timeout as 25 Minutes """ begin = time.time() pattern_to_match = r"RP\/0\/RP0\/CPU0\:ios(\([^()]*\))?#|RP\/[0-3]\/RS?P[0-1](?:\/CPU[0-3])?:ios#|rommon \d+ >|XML>" if not ctx.is_console: ctx.disconnect() ...
9e20631997fa89f6b483bf692b7a3cdee0951b59
3,608,840
def get_api(alias=None): """ Returns global API object and if present, otherwise raise MissingConfiguration exception. :param alias: Alias of the API to retrieve :type alias: str :returns: An API object :rtype: :class:`infermedica_api.webservice.API` :raises: :class:`infermedica_api.ex...
0f7575ea49591f31c123f4acfaa9582fe8386477
3,608,841
def mol_to_smiles(molecule, isomeric=True, explicit_hydrogen=True, mapped=True): """ Generate canonical SMILES with OpenEye. Parameters ---------- molecule: oechem.OEMol isomeric: bool If True, SMILES will include chirality and stereo bonds explicit_hydrogen: bool If True, S...
8e58b5941d81f426114c65a7cc14b05c84fd776f
3,608,844
import torch def conj(x): """ Computes the complex conjugate of complex-valued input tensor (x). ``conj(a + ib)`` = :math:`\\bar{a + ib} = a - ib` Args: x (torch.Tensor): A tensor. Returns: torch.Tensor: The conjugate. """ assert is_complex_as_real(x) or is_complex(x) ...
2eb4768d90c3c683f6e4513de3ea3fccfffbcdc7
3,608,845
def runSingleThreaded(runFunction, arguments): """ Small overhead-function to iteratively run a function with a pre-determined input arguments :param runFunction: The (``partial``) function to run, accepting ``arguments`` :param arguments: The arguments to passed to ``runFunction``, one r...
9cdc34f5e44751667ec5a3bddcf2958b3302f4d1
3,608,848
def clean_year(year): """ Cleaning up year column """ if len(year) > 3 and year[0].isnumeric() and year[3].isnumeric() and year[1].isnumeric() and year[2].isnumeric(): return year[:4] else: return np.nan
4bda1034e921bb450a6052b056fa46688e1203d0
3,608,849
def init_residual_weights_matrix(dim_in, dim_out, borrow=True): """Partial isometry initialization.""" if dim_out == dim_in: weights = np.identity(dim_in) else: d = max(dim_in, dim_out) weights = np.linalg.qr(np.random.randn(d,d))[0][:dim_in,:dim_out] return theano.shared(np.asar...
acef4bac45b198655be4eb53204e8f4019ce7565
3,608,850
def calc_velocity(STRIDE_LENGTH, LEG_LENGTH, grav_const): """Calculate velocity of the dinossaur """ return ((STRIDE_LENGTH / LEG_LENGTH) - 1) * sqrt(LEG_LENGTH * grav_const)
22b2b047a347ee256adf293d9548e2860ce65b35
3,608,852
import time def velocidade(funcao): """ Função decoradora: Verifica o tempo que uma função leva para executar """ def envolve(*args, **kwargs): """ Função que envolve e executa outra função """ # Tempo inicial start = time() # Pega o tempo atual # Executa a função ...
2784eed306b4c2c90423bbb1eb05f54ee9cc4ace
3,608,853
def comp(*args) -> bool: """Compare string lengths.""" return len(set([len(arg) for arg in args])) == 1
c3bf069c723b37030531ffbbb84a0a91488a7345
3,608,855
def DC_LC(z): """Method for comoving distance in Linear Coasting model""" return np.log(1.0+z)
52d28730a7f8a69bb5aed1cf342608fe3e18ce82
3,608,857
def clip(num, num_min=None, num_max=None): """Clip to max and/or min values. To not use limit, give argument None Args: num (float): input number num_min (float): minimum value, if less than this return this num Use None to designate no minimum value. num_max (float): maxim...
fe46f5a200ab24d517c57c5e1d93d4bf86192e13
3,608,858
def Singleton(name, bases, dict): """Use this metaclass on Converter subclasses to create a instance.""" return type(name, bases, dict)()
d7a196f0a645dac8150d9fba46b426882358a9a6
3,608,859
import collections def build_model_metrics_aggregator( model: model_lib.Model, metrics_type: computation_types.Type ) -> computation_impl.ConcreteComputation: """Creates a stateless aggregator for client metrics.""" @computations.federated_computation( computation_types.at_clients(metrics_type)) def ...
35b55d2808a7bc02659a564b9ca11c9cef108494
3,608,861
def sparse_std(a, axis=None): """Standard deviation of sparse matrix a std = sqrt(var(a)) """ return np.sqrt(vars(a, axis))
2bc56bbe70da190ccbb0234a7a9b61281058431c
3,608,862
def reduce_with_mantid(ws, data_set, apply_db=False, apply_scaling_factor=False): """ @param ws: Mantid workspace @param data_set: template object """ kwargs = { "InputWorkspace": ws, "NormalizationRunNumber": str(data_set.norm_file), "SignalPeakPixelRange": data_set....
dd1494074b9754c5e85fec1dfebc66489af1367a
3,608,863
def calculate_fraction_of_sn_discovered( log, surveyCadenceSettings, snSurveyDiscoveryTimes, redshifts, peakAppMagList, snCampaignLengthList, extraSurveyConstraints, zmin, zmax): """ *Given a list of the snSurveyDiscoveryTimes calculate the...
70409bba2f7dd2601ed073ad140d75c8ec863942
3,608,864
def create_model_info(config, loss_func, accuracy): """Create a dictionary of relevant model info. Parameters ---------- param : dict Any parameter relevant for logging. accuracy_log : dict A dictionary containing accuracies. Returns ------- type Description of ...
25cd8f49a0c7c7fd9b52f3d33c8a8ac24167fbff
3,608,866
def grid_coordinates(roi, x_divisions, y_divisions, position): """ Function that returns the grid coordinates of a given position. To do so it computes, for a given area and taking into account the number of x and y divisions which is the total amount of cells. After that it maps the given position to the cell it ...
1db6e8ed8b1c0abde965e3a5536867ae32ac2228
3,608,867
def splitmessage(message): """Returns a tuple containing the command and arguments from a message. Returns None if there is no firstword found """ assert isinstance(message, str) words = message.split() if words: return (words[0], words[1:])
d8db56ef55097f9f8858de95ee3d7799c0dc127e
3,608,868
def methods_of(obj): """Get all callable methods of an object that don't start with underscore. returns a list of tuples of the form (method_name, method) """ result = [] for i in dir(obj): if callable(getattr(obj, i)) and not i.startswith('_'): result.append((i, getattr(obj, i)...
ca22a91b5c60749e7a6b700cb029baab6b64eeb7
3,608,869
import typing def implement_insulation_widths(delphin_dict: dict, system: pd.DataFrame) -> typing.List[dict]: """Permutate width of system applied materials""" # look up current material assume system db_material = get_material_info(system.loc['insulation' + '_00', 'ID']) insulation_select = ['insula...
41fcf75890f09cb1568509d20dca0803dbef0db3
3,608,870
def make_moment_matcher(config): """make_moment_matcher(config: dict) -> (MM, dict) Initialize an MM given `config` and return unconsumed part of `config`. """ return _make_mm_from_kwargs(**dict(DEFAULT_PARAMS, **config))
10704127ada70d70629c989bd39bb8306032d3ca
3,608,871
def get_reddit_instance(refresh_token=None): """Get the interface to talk to Reddit :param refresh_token: The refresh token given on a previous authentication, which we can use to continue their session. """ user_agent = ('Dust. Giving users the power to remove their content.' ...
110f17f4406a185e30185fd0eb482af95d3fc94f
3,608,872
def num_allowed_shape_input(): """ This function receives input from the user - The total number of matchsticks for division It returns the user's input """ while True: num_allowed_s = raw_input("ENTER THE NUMBER OF MATCHSTICKS FOR DIVISION: ") if num_...
251b26e33671fa26ff5a63b880a7072e619454ce
3,608,873
from textwrap import dedent async def query(conn: pg.Connection, timestamp) -> Record: """ Returns current P2PK address counts by minimal balance. Assumes snapshots are up to date. """ qry = dedent( """ select count(*) as total , count(*) filter (where value >= 0.001 *...
daa5ef5c08c2ca94e3d8bf7486431ee039ef3c7c
3,608,874
from typing import Dict from bs4 import BeautifulSoup def check_html_doc( html_path: str, all_links: bool = False, top_root: str = None, checked_links: Dict[str, UrlResult] = None, ) -> Dict[str, UrlResult]: """ Check links in an html document (file). Parameters ---------- html_pa...
58c7cb71b67859821bbf5fde38dab85fe5fe2007
3,608,875
def dec_to_str(total): """Converts decimals to strings for more natural speech.""" if total == 0.125: return "an eighth" elif total == 0.25: return "a quarter" elif total == 0.5: return "a half" elif total == 0.75: return "three quarters" else: if total % ...
05e170eb21f5f0b188a32a634b5c617536c64a11
3,608,876
from typing import Iterable def make_location_trees(tables: Iterable[Table]) -> list[LocationTreeNode]: """ Return a graph representation of the origins for given tables Graph is a collection of trees: B LocationFile L LocationBlock # table B LocationBlock # include ...
a67701963170c7b61a8149ac3ccaca89741dd0e3
3,608,877
def _order_logging_keys(logger, method_name, event_dict): # pylint: disable=unused-argument """ Returns an OrderedDict with a spesific key order. Unnamed keys are alphabetically sorted at the end. """ keys = len(SORT_ORDER) return dict(sorted(event_dict.items(), key=lambda i: SORT_ORDER.get(i[0...
cf0b9f379f9f5a97b8578e5ac5a1a7ba10c2fa37
3,608,878
def maybe_cast_list(value, types): """ Try to coerce list values into more specific list subclasses in types. """ if not isinstance(value, list): return value if type(types) not in (list, tuple): types = (types,) for list_type in types: if issubclass(list_type, list): ...
c3078c42087103ee8b0a8b3257d345e7d73c0fd7
3,608,879
def bilinear(image, warp): """ Bilinear interpolation. Parameters ---------- array: nd-array Input array for sampling. warp: nd-array Deformation coordinates. Returns ------- sample: nd-array Sampled array data. """ result = n...
80fe5bde81f878b91418898d26d628f18e152899
3,608,880
def forxml(uri): """ Escape XML nasties in a URI """ return xmlutils.cleanxml(uri)
aefc461d7f9d2be53f4ef4fb0a10f9551b0eb334
3,608,881
def dh_noConv(value, pattern, limit): """Helper for decoding a single integer value, no conversion, no rounding.""" return dh(value, pattern, encNoConv, decSinglVal, limit)
1107ca20edf660d66818bb9e3922cf36c34cefe3
3,608,883
import re from typing import OrderedDict def CustomExtension(observable=None, type='x-custom-observable', properties=None): """Decorator for custom extensions to STIX Cyber Observables. """ if not observable or not issubclass(observable, _Observable): raise ValueError("'observable' must be a vali...
6cbc0adb9191b710abca60804ab9b56ce79556f7
3,608,884
def read_wi_table(wi_file, wi_column): """ Reads in the relative adaptiveness file """ tmp_wi_dict = {} line_number = 0 with open(wi_file, 'r') as infile: for line in infile: line_number += 1 if line_number == 1: continue # skip header ...
89a1b38e375678b8d221b7386dd742fe6745223c
3,608,885
def uri_encode(data): """ Return URI encoding of the passed string. Args: data (str): String to encode Raises: None Returns: TYPE: str """ return quote(str(data))
3c0b7274f2661a4ba4939404669f51e16f98b11c
3,608,886
def get_accuracy_by_dtype(predictions): """ Calculates model accuracy w/r to available data types. Parameters: predictions (pandas.Series): model predictions for each sample Returns: accuracies (pandas.Series): model accuracy w/r to data types """ d_types = list(set(predictions...
e4eb37cdcf6273b6daa3cf0431c88a892a544e25
3,608,887
def run_retina(params): """Run the retina using the specified parameters.""" tmpdir = tempfile.mkdtemp() print "Setting up simulation" pyNN.Timer.start() # start timer on construction pyNN.setup(timestep=params['dt'],max_delay=params['syn_delay']) pyNN.pynest.setDict([0],{'threads' : params['...
6180c6e233cdb67cf2109f53611a9736e0393297
3,608,888
def detect_cycle(init_progs, compiled_moves): """Find a cycle length by repeating a list of compiled moves""" progs = fastdance(list(init_progs), compiled_moves) cycle = 1 while progs != init_progs: progs = fastdance(progs, compiled_moves) cycle += 1 return cycle
782771b4e218bbe0c352cb503cff4de4b8a0d070
3,608,890
def get_thickness(system, axis): """Get the thickness of an atomic system along a basis vector direction. Args: system(ase.Atoms): The system from which the thickness is evaluated. axis(int): The index of the unit cell basis in which direction the thickness is evaluated. Return...
64e57ba302cc7f64ba45f16b32744522938c92e9
3,608,891
def affilation_wks(short_name, graph_df): """ Find wich wks to use by postfix at command :param short_name: command last word like Basketball_FF1 :param graph_df: pandas df of graph :return: node_id and link_id """ row = get_row_by_keys(graph_df, key_value=[short_name]...
bb5a63248d45c37275314972f36bcee12877ec31
3,608,893
def healthcheck(): """Returns health information""" return jsonify({ "message": "I feel good." })
0bc6e43fcbb5c15771be417a0831822e9ef34971
3,608,895
def get_msg_fileslug(msg): """ for a given message, which file/foia is this? checks entire message thread for category labels """ convo = get_conversation(msg['conversationId']) for msg in convo: for cat in msg['categories']: if 'file' in cat: return cat
aa177140a15c3b26bbb307414be173e4ac7ea12c
3,608,897
import numpy def empty_like_pinned(a, dtype=None, order='K', subok=None, shape=None): """Returns a new, uninitialized NumPy array with the same shape and dtype as those of the given array. This is a convenience function which is just :func:`numpy.empty_like`, except that the underlying memory is pinn...
f2a03e31ea8adbfecf81943b37dd7dc32606cfc7
3,608,899
from typing import List import collections import heapq def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int: """ >>> Dijkstra's Algorithm Variation The differences are: 1. Also track the number of stops so far; 2. Now since ...
27a06b0ebce16e3b2389ce28d9a6548bfd1bdf8c
3,608,900
def get_row_col(i, axes): """Get the ith element of axes """ if isinstance(axes, np.ndarray): # it contains subplots if len(axes.shape) == 1: return axes[i] elif len(axes.shape) == 2: nrow = axes.shape[0] ncol = axes.shape[1] row_i = i ...
20c3af7e27072225699d61e16ed7968850205a28
3,608,901
from typing import Match from typing import Optional from typing import Union async def rise_score_data(payload: dict, match: Match, nickname: Optional[str] = None) -> Union[MessageSegment, str]: """ 上分数据 - `payload` : 传递给查分器的数据 - `match` : 正则结果 - `nickname` : 用户昵称 """ dx_ra_lowest = 999 ...
b6d6bba6b75779aafcd0ce8cc530c0e086ff43da
3,608,902
from ecdsa import numbertheory, ellipticcurve, util import base64 def verify_message(address, signature, message): """ See http://www.secg.org/download/aid-780/sec1-v2.pdf for the math """ curve = curve_secp256k1 G = generator_secp256k1 order = G.order() # extract r,s from signature sig = base...
d4d37d5aa93cb2e02ae956204bcb850e14bb649a
3,608,903
from typing import Iterable from re import T from typing import Tuple def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]: """s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ...""" return zip(*[iter(iterable)] * n)
38caab13c4e26cb504e3155765316da9235e2a3a
3,608,904
import requests import json def get_cards_done(board_id, app_key, user_token, board_name): """Fetches and returns the number of cards in the Trello list under the passed name""" # Constructing GET request to get all lists on the board url = "https://api.trello.com/1/boards/%s/lists?cards=all&key=%s&token...
e957313ac72fdfc3b1499a09496bece614ba7a6f
3,608,905
import numpy def w_conj_kernel_fn(kernel_fn): """Wrap a kernel function for which we know that kernel_fn(w) = conj(kernel_fn(-w)) Such that we only evaluate the function for positive w. This is benificial when the underlying kernel function does caching, as it improves the cache hit rate. ...
c5ba5bb741e9e696a94535c4373e84268a7ab95d
3,608,906
def loadWorld(worldName, store): """ Load an imaginary world from a file. The specified file should be a Python file defining a global callable named C{world}, taking an axiom L{Store} object and returning an L{ImaginaryWorld}. This world (and its attendant L{Store}) should contain only a sing...
801c98b5be82e9d5c9ca19db9adbe3078f500674
3,608,907
def _cosine_dist(u, v, w=None): """ :purpose: Computes the cosine similarity between two 1D arrays Unlike scipy's cosine distance, this returns similarity, which is 1 - distance :params: u, v : input arrays, both of shape (n,) w : weights at each index of u and v. array of shape (n,)...
d4252f6d79e4b1254bf79d1933ef123ff8fadc16
3,608,908
import torch def full(*args, **kwargs): """ In ``treetensor``, you can use ``ones`` to create a tree of tensors with the same value. Example:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.full((2, 3), 2.3) # the same as torch.full((2, 3), 2.3) tensor...
8c6df708b76a799c27a45979e9a43b3d3678ac8d
3,608,910
def funnel(base, test): """Tests string against the base string to determine if it can be constructed by removing one character from the base string str, str -> bool >>> funnel("leave", "eave") True >>> funnel("eave", "leave") False """ return test in get_shortened_string_list(base)
03e0b0e223ed9c1fabdf4411eb3ea3a938917d08
3,608,911
from bs4 import BeautifulSoup from typing import Dict from typing import List def extract_back_matter_from_tei_xml( sp: BeautifulSoup, bib_dict: Dict, ref_dict: Dict, cleanup_bracket: bool ) -> List[Dict]: """ Parse back matter from soup :param sp: :param bib_dict: ...
7f830bcd4588a29281ea96e90fdba5d00f4c75c4
3,608,912
def kearsley_rotation(reference_sites, other_sites): """ Kearsley, S.K. (1989). Acta Cryst. A45, 208-210. On the orthogonal transformation used for structural comparison Added by Peter H. Zwart, Nov 3rd, 2006. Converted to C++ by Gabor Bunkoczi, Apr 2008. """ return matrix.sqr(superpose_kearsley_rotation...
2833704e69a380d1c91c2448cb39a37e49bdb941
3,608,913
def lc_virus(playing_field): """ From https://leetcode.com/contest/weekly-contest-63/problems/contain-virus/ A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as a 2-D array of cells, where 0 represents uninfected cells, and 1 repre...
fb3991a8c19d7cbc3599231fd7fa6a9bf0c5b7e0
3,608,914
import math def tan(x): """Get tan(x)""" return math.tan(x)
112b52faee2f08262515086fe59b2ff978001200
3,608,915
def gelu_ad_custom(head, in_data, target="cce"): """ Automatic differentiation of gelu with customize function. In order to achieve higher precision, we could also self-define tanh part differentiate with simplify calculation. """ dtype = in_data.dtype const1 = akg.tvm.const(0.044715, dtype) ...
aec594eed9954e79cf16a36a4e50911c9a7991f1
3,608,916
def ParticleFactory(variables, name="SamplingParticle", BaseClass=parcels.JITParticle): """Create a Particle class that samples the specified variables. The variables that should be sampled will be prepended by ``var_`` as class attributes, in case there are any namespace clashes with existing variable...
5c09acf1cc4a1ce3a3fdad7cbaf026cb5533a467
3,608,917
def piece_placed(x, y, player, board): """This function determines the piece played. It takes the coordinates of the piece, the player number, and the board. The pieces are zeros or ones and the function returns the piece on the board based on the number.""" if player == 0: board[x][y] = 1 e...
ffcd46e11c3e5b0704ed66d6010dfc227106c752
3,608,918
def get_max_unsecured_debt_ratio(income): """Return the maximum unsecured-debt-to-income ratio, based on income.""" if not isinstance(income, (int, float)): raise TypeError("Expected a real number.") # Below this income, you should not have any unsecured debt. min_income = 40000 if income <...
ffff63807842197e2f60ebfd29b54ecf895f6279
3,608,919
import glob import shutil def merger(): """ Function to combine all results csv into a single file. """ #import csv files from folders path = r'C:/Users/luxon/OneDrive/Research/McQuade/Projects/NSF/OKN/phase1/Work/ml-hte-results-20200207' # Adam's tablet. will vary by OS, computer # path = r'C:/Use...
8b96d569cef54636cc009df797061b45c31c264b
3,608,920
def calc_other_bias(probs): """ :param probs: list of negative log likelihoods for a corpus :return: gender bias in corpus """ bias = 0 for idx in range(0, len(probs), 16): bias -= probs[idx + 1] + probs[idx + 3] + probs[idx + 5] + probs[idx + 7] bias += probs[idx + 8] + probs[id...
2ceb6788e22277192475218db6e3175f259dc9ba
3,608,921
def pubkey_to_merkletree(key, hashfunction, salt, prefix=""): """Convert a full signing-key pubkey into a merkletree dictionary""" drval = dict() part1 = key[0] part2 = key[1] if len(key) > 2: breakpoint = int(len(key)/2) part1, dpart1 = pubkey_to_merkletree(key[:breakpoint], hashfun...
50e5283a7189aa0202e93201d70f7343719f1f13
3,608,922
def generate_test_case(num_nodes=500, num_edges=1000, num_communities=5, connecting_strength_among_communities=0.01, random_state=None): """ :param num_nodes: int :param num_edges: int :param num_communities: int :param connecting_strength_among_communities: float :param r...
417f4bf0a4c2089796dcdd2de749225c86bdb7b0
3,608,924
def deprocess_image(x): """normalize tensor: center on 0., ensure std is 0.1""" x -= x.mean() x /= (x.std() + K.epsilon()) x *= 0.1 # clip to [0, 1] x += 0.5 x = np.clip(x, 0, 1) # convert to RGB array x *= 255 if K.image_data_format() == 'channels_first': x = x.transpo...
3ecf94411855e3a212fc0ebe2b60ff76bf30efd3
3,608,925
def DFFN_3tower_5depth(x_dict, dropout, reuse, is_training, n_classes): """Three towers. Each depth 5. This is the train_paviaU network when input is 23. 20 steps/second. 94.5% on PaviaU 2%, lr 5e-5, within 10k """ with tf.variable_scope('DFFN', reuse=reuse): x = x_dict['s...
9945092ba2c983b218c0c8d9351aaede6f807a80
3,608,926
def build_list_all_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """List scan rulesets in Data catalog. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an :class:`~azure.purview.scanning.core.res...
4b2cbf297ec89855f794bd0bb9046f525f23a7fa
3,608,927
from typing import Any import json def is_jsonable(x: Any): """ Check if an object is json serializable. Source: https://stackoverflow.com/a/53112659 """ try: json.dumps(x) return True except (TypeError, OverflowError): return False
3735de8bd1940d84c185142c0a4387366d7cd9c2
3,608,928
def plot_cumvar_pca(data,title): """Plots the cumulative variance explained by PCA for different number of components""" fig,axes = plt.subplots(nrows=2,ncols=2,figsize=(10,8)) pca = PCA().fit(data) axes[0,0].plot(np.cumsum(pca.explained_variance_ratio_),'bx',alpha=0.6) axes[0,1].plot(np.cumsu...
e2e6758af3bc203df76f12d60be0b83ad8163036
3,608,929
def add_number_of_different_roles(dev_type: str) -> int: """ INPUT dev_type - dev_type answer (separeted by ';') OUTPUT numeric value - number of different dev types """ try: return len(dev_type.split(';')) except: return 0
78872b9101b128cc107a0194fc85b353f1d2f836
3,608,930
import time def try_models(models, X_train, y_train, preprocessor): """ Fits different regression models on the given dataset and evaluates the mean absolute error. ​ Parameters ---------- models : dict Dictionary of various regression models to try. X_train : DataFrame Traini...
4d7c1acd19ef425ebb7185cb805ddf805af55619
3,608,931
def FormatCommentWithAnnotations(comment, type_name=''): """Format a comment string with additional RST for annotations. Args: comment: comment string. type_name: optional, 'message' or 'enum' may be specified for additional message/enum specific annotations. Returns: A string with additional ...
accf33ab834e9aeada2c3edfbd83427935e5e130
3,608,932
def _todict(matobj): """ A recursive function which constructs from matobjects nested dictionaries. """ dict = {} for strg in matobj._fieldnames: elem = matobj.__dict__[strg] if isinstance(elem, spio.matlab.mio5_params.mat_struct): dict[strg] = _todict(elem) else:...
cc5c594cecdb88183b36ce4be5b8c01424847936
3,608,933
def create_network_with_bn(): """Creates a network contains both QConv2D and QDepthwiseConv2D layers.""" xi = Input((28, 28, 1)) x = Conv2D(32, (3, 3))(xi) x = BatchNormalization()(x) x = Activation("relu")(x) x = DepthwiseConv2D((3, 3), activation="relu")(x) x = BatchNormalization()(x) x = Activation(...
22a167a15326cc6d8830c6498402b45c91587c02
3,608,934
def GetBigQueryTableID(tag): """Returns the ID of the BigQuery table associated with tag. This ID is appended at the end of the table name. """ # BigQuery table names can contain only alpha numeric characters and # underscores. return ''.join(c for c in tag if c.isalnum() or c == '_')
0fe659fd3c7ca3df5f061289dad5635841146901
3,608,935
import timeit from typing import DefaultDict def dnscl_rpz(ip_address: str) -> str: """Return RPZ names queried by a client IP address. Args: ip_address (str): IP address to search. Returns: str: Search results found. """ start_time = timeit.default_timer() rpz_dict: Default...
0916933d64f5fca1145f3c1d31bbc6e8ae82c139
3,608,937
def rf_local_unequal_int(tile_col, scalar): """Return a Tile with values equal 1 if the cell is not equal to a scalar, otherwise 0""" return _apply_scalar_to_tile('rf_local_unequal_int', tile_col, scalar)
ca9200dd94b786ae258ec2f91dca9934f280dd01
3,608,938
def get_process_list(node: Node): """Analyse the process description and return the Actinia process chain and the name of the processing result :param node: The process node :return: (output_objects, actinia_process_list) """ input_objects, process_list = check_node_parents(node=node) output_o...
e14ecb3d43c1329cf707a21bb11c933e84875712
3,608,939
def run_text(query_string): """Run a query that should only return string contents.""" contents, types, result = run(query_string) assert types is None assert result is None return contents
6201bdde6a5fb42603b3d9a7e67629bb368dfc72
3,608,940
def Value_getNullValue(): """Value_getNullValue() -> Value""" return _yarp.Value_getNullValue()
efae2c7810f2ae277e10d68c0e6640e7d760982b
3,608,941
def transform_landmark(landmark, t): """ Function applies transformation t to a single landmark represented by its coordinates in space. It first creates poly data from its positions and then applies given transformation. :param landmark: (x, y, z) coordinates of landmark to be transformed :param t...
f058ba9060ba1e7f718c8c9d87e7cf332592ce27
3,608,942
import requests def find_location(location): """ Takes a location as a string, and returns a dict of data :param location: string :return: dict """ params = {"address": location, "key": dev_key} if bias: params['region'] = bias json = requests.get(geocode_api, params=params).j...
44381de26b3db10e00b0f03be2a5b2da14dcf812
3,608,943
import token import time def sign_url_path(url, secret_key, expire_in=None, digest=None): # type: (str, bytes, int, Callable) -> str """ Sign a URL (excluding the domain and scheme). :param url: URL to sign :param secret_key: Secret key :param expire_in: Expiry time. :param digest: Specif...
946d0ae6d704d5a6b9da8517f1b37563471761cb
3,608,944
from typing import Dict from typing import List def get_label_colour_map() -> Dict[str, str]: """converts a comma seperated list of organizations/repositories into a list of tuples. """ def _preproc(label_colour: str) -> List[str]: return label_colour.lower().split(sep="/") return { ...
440092d8f31fab679761453ec7abc8fb37b5f5d8
3,608,945
def log_modulo(a, b, m): """Computes discrete logarithm i.e. finds x such that a^x = b (mod m) Uses Shanks algorithms which takes O(sqrt(m)) time """ # find x in form x = np - q for some (n, p) # => a^x = b ~ a^np = a^q * b a, b = a % m, b % m n = isqrt(m) + 1 # compute all a^q * b ...
6f2c2afd9858ba7d3baaaa2e871cc336396d2042
3,608,946
def _linear_transform(src, dst): """ Parameters of a linear transform from range specifications """ (s0, s1), (d0,d1) = src, dst w = (d1 - d0) / (s1 - s0) b = d0 - w*s0 return w, b
7f55a2617721fdefcc724bcb8ce9f880d7bcd846
3,608,948
def feature_within_s(annolayer, list_of_s): """Extracts all <annolayer> from all sentence-elements in list_of_s; returns a flat list of <annolayer>-elements; """ list_of_lists_of_feature = [s.findall('.//' + annolayer) for s in list_of_s] list_of_feature = [element for sublist in list_of_lists_of_fe...
df6ed3603381a4b8d2ea12fc483fa37ea3068372
3,608,949
def _permute_facets(facets, ori, ori_map): """ Return a copy of `facets` array with vertices sorted lexicographically. """ assert_((in1d(nm.unique(ori), ori_map.keys())).all()) permuted_facets = facets.copy() for key, ori_map in ori_map.iteritems(): perm = ori_map[1] ip = nm.wh...
0e09ad2b7555be8e77e564266e3920e5413d851e
3,608,950
def showname(keyvalue): """filter koji za neku od prosledjenih kljuceva vraca vrednost""" key_dict ={'P':'Accepted','C': 'Created','Z': 'Closed','O': 'On Wait'} return key_dict[keyvalue]
59453d5e0dd31696b99d01c8b927297adddec10c
3,608,951
def findDomainRanges(r,r_surf_index,W,oldMiddleRange): """ Because the islands grow and shrink, the location of the boundaries are in constant flux. This code figures out the boundaries and returns the indices associates with all three regions. """ innerBCIndex=findNearest(r,r[r_surf_index]-W/2) if innerB...
db213209e4bed1daf9d3e18ceb8f0e30db5d875e
3,608,952
def create_taperedvia(AR, dr, Nseg): """Return the areas and view factor of a rectangular trench, where the vertical wall is divided into identical sections. Parameters ---------- AR : float Aspect ratio, defined as the width to top diameter ratio dr : Float Ratio between the bo...
408077ec50272236da497b93ec897213ae6b30eb
3,608,953
import torchvision import torch def get_train_val_loaders(train_dir, collate_fn, height, width, no_data_augmentation=False, max_trainset_size=np.infty, seed=0, ...
675be081fa34ad2c282674dbb59a9e81cb36581d
3,608,954
def adjust_learning_rate(optimizer, epoch, gammas, schedule): """Sets the learning rate to the initial LR decayed by 10 at 600 and 900 epochs""" lr = args.lr_ assert len(gammas) == len(schedule), "length of gammas and schedule should be equal" for (gamma, step) in zip(gammas, schedule): if (epoc...
5fb413f4403aa9606758134929f684d2dd03a621
3,608,955
def get_organizations_from_ckan(portal_url, verify_ssl=False, requests_timeout=REQUESTS_TIMEOUT): """Toma la url de un portal y devuelve su árbol de organizaciones. Args: portal_url (str): La URL del portal CKAN de origen. verify_ssl(bool)...
fd280b3106d84b66c893877657f5ec0b3b2dc635
3,608,956