content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import argparse import os import torch def get_args(): """Expose different behaviors of the server to the user. Raises: AssertionError: If the combination of arguments are unsupported Returns: parsed arguments for the server, cached """ parser = argparse.ArgumentParser( f...
8febdd4cc0962dce57c8d50682dac5a35d8a189f
37,000
def pandas_read_xlsb_file(filepath): """ https://stackoverflow.com/questions/45019778/read-xlsb-file-in-pandas-python Accepts a filepath - pathlib.Path object Reads an xlsb file into a dataframe Returns the dataframe """ dfs = [] with open_xlsb(filepath) as wb: with wb.get_sheet(...
eb04c2eee736cca81b1e58a11090517b27bea879
37,001
from typing import List def join_batch_meshes_as_scene( meshes: List[ParametricMeshes], include_textures: bool = True) -> ParametricMeshes: """Join `meshes` as a scene each batch. For ParametricMeshes. The Meshes must share the same batch size, and topology could be different. They must al...
3758e6d3e47b20747669d8f89e3a146b1fe1bb0a
37,002
import pathlib def load_dxf(dxf_filepath: pathlib.Path): """ Import any-old-shape in dxf format for analysis. Code by aegis1980 and connorferster """ if not dxf_filepath.exists(): raise ValueError(f"The filepath does not exist: {dxf_filepath}") my_dxf = c2s.dxf.Dxf...
68af5d3a7c779b468c6235fb5e4534f1695850eb
37,003
def validate_cv_implementation(impl, bootstrap=False): """Validate a back end for computing variables, returning it. Raise an exception if it is invalid. The second argument is for internal use only. """ # Note that the very first call to this with a non-None argument, # and with bootstrap giv...
f87d6ce0b978cc44e82b5a0ad92dfc2b99e8300d
37,004
def accuracy_op(predictions, targets): """ accuracy_op. An op that calculates mean accuracy. Examples: ```python input_data = placeholder(shape=[None, 784]) y_pred = my_network(input_data) # Apply some ops y_true = placeholder(shape=[None, 10]) # Labels acc_op = acc...
b726b0e9a5089f53ed050a70b930ef4603c69cf4
37,005
import time def detect_image(image, yolo, all_classes): """Use yolo v3 to detect images. # Argument: image: original image. yolo: YOLO, yolo model. all_classes: all classes name. # Returns: image: processed image. """ pimage = process_image(image) start = tim...
c50b56f115a95ba2523231291ff1f1873b8bd5e7
37,006
def list_entry_factory(db): """ Fixture to get the factory used to create list entries. """ return factories.ListEntryFactory
a7ddaa90999f0ab5767f96b7abe6502cdb54e663
37,007
def fractals_tholins(wvln, rm, Df, N, db=Database(), **kwargs): """Fractals cross-sections and phase function for tholin aggregate. Use default tholins indexes and Tomasko et al. 2008. Parameters ---------- wvln: float Wavelength (m). rm: float Monomer radius (m). Df: float...
48e9cc54bfccd522333b8df08a7cdbfc814d73bb
37,008
def _apply_quat(quat, pts, move=True): """Apply MaxFilter-formatted head position parameters to points.""" trans = np.concatenate( (quat_to_rot(quat[:3]), quat[3:][:, np.newaxis]), axis=1) return(apply_trans(trans, pts, move=move))
3f43c2b925475e3a53775a3d004b8415e104248e
37,009
def spherical_to_vector(spherical): """ Convert a set of (n, 2) spherical vectors to (n, 3) vectors Parameters ------------ spherical : (n , 2) float Angles, in radians Returns ----------- vectors : (n, 3) float Unit vectors """ spherical = np.asanyarray(spherical,...
61c3140c377bb72e6b0e31b03d1d68c9a4eeca74
37,010
from typing import Mapping from typing import Any from typing import Tuple def split_config(config: Mapping[str, Any]) -> Tuple[dict, InternalConfig]: """ Break config map object into 2 instances: first is a dict with user defined configuration and second is internal config that contains private keys for ...
74775375cd4f7119b2f31ac31489a1d0509d7729
37,011
from scipy.interpolate import interp1d import numpy as np def klatt_bridge(f0, ff, bw, av, avs, ah, af, fs, dur, inv_samp=50): """ Processes/interpolates input parameters for Klatt synth, runs synth. Arguments: f0 (Track object) -- fundamental frequency contour ff (list, len n_form, T...
9b584479e229ea389eaa927342f3fe0d18975e5a
37,012
def create_dict(data: list): """ Cria um dicionário onde a chave é o tempo de duração da palestra e o valor é uma lista que contém as palestras com essa duração. """ data = lectures_ordered_by_duration(data) new_set = {} for item in data: if item[0] not in new_set: ...
ecd985e57ac7d3244c99e0daee4ba2d0a18b56d3
37,013
import os import sys import argparse def create_args_parser(): """ Create the program argument parser. Returns: An argparse parser object. """ prog_name = os.path.basename(os.path.dirname(sys.argv[0])) mesg = """ This script will (re)generate tests for recipes. It will OVERWRI...
4810f99abf4e29ecb990246d8e0d68ae8270aaa7
37,014
import os import argparse from pathlib import Path def adapt_environment() -> set[str]: """Update env vars and return CLI flags for compatibility with latest Semgrep.""" for old_var, new_var in ENV_TO_ENV.items(): if os.getenv(old_var): os.environ[new_var] = os.environ.pop(old_var) p...
c39307b393d17e8f1c85a515e47f1961476b33cb
37,015
def _kernel_cdf_gamma(x, sample, bw): """Gamma kernel for cdf, without boundary corrected part. drops `+ 1` in shape parameter It should be possible to use this if probability in neighborhood of zero boundary is small. """ return stats.gamma.sf(sample, x / bw, scale=bw)
02e50b8fe7e6b594d8d4e9236f3ac611916c98c2
37,016
def infer_type(node): """A method to infer the type of an intermediate node in the relay graph.""" mod = node if isinstance(node, _module.Module) else _module.Module.from_expr(node) mod = _transform.InferType()(mod) entry = mod["main"] return entry if isinstance(node, _expr.Function) else entry.body
d77a9e00562c68337129a020398b0e0359900aff
37,017
from typing import Counter def palindrome_from(letters): """ Forms a palindrome by rearranging :letters: if possible, throwing a :ValueError: otherwise. :param letters: a suitable iterable, usually a string :return: a string containing a palindrome """ counter = Counter(letters) sides ...
cbc4bab8e1ea9ce094007620314803a69f5ad330
37,018
def get_cloud(session, cloud_name, return_type=None, **kwargs): """ Retrieves details for a given cloud name :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type cloud_name: str :param cloud_name: Cloud Name: i.e: zadaraqa9 :typ...
fe524715a931504f3825240d404a0397fd595b54
37,019
def check_scopes(required_scopes, scopes): """Check that required_scope(s) are in scopes Returns the subset of scopes matching required_scopes, which is truthy if any scopes match any required scopes. Correctly resolves scope filters *except* for groups -> user, e.g. require: access:server!user=x,...
34cb956ee1cd3b4657005e3cd06b55b61b2906e4
37,020
def new_filter(filters=None): """ Returns the default lookup filters. :param filters: dict - The defaults are updated with this dict before being returned. :returns: dict """ out = dict(const.DEFAULT_FILTERS) if filters is not None: if not isinstance(filters, dict): ...
c38bd00d08ca10533c39d84753df4c7f1b135687
37,021
def addAssignment2D(initAssignments=None, odID=1, objectID=None, modelFile=None, startLoc=None, endLoc=None, startTimeSec=0.0, expDurationSec=None, routeType='euclidean2D', speedMPS=None, leafletColor=config['VRV_DEFAULT_LEAFLETARCCOLOR'], leafletWeight=config['VRV_DEFAULT_LEAFLETARCWEIGHT'], leafletStyle=config['VRV_D...
bca861213b8de4f2a7a0c5398feca35c4376ddc3
37,022
import re import math def load(filename): """load a 'TAMO'-formatted motif file""" FID = open(filename,'r') lines = FID.readlines() FID.close() motifs = [] seedD = {} seedfile = '' for i in range(len(lines)): if lines[i][0:10] == 'Log-odds matrix'[0:10]: w = le...
22a6d5796a9fa4b8e813d62fcf52cea05ee5f987
37,023
import uuid import os def _homogenize_linesep(line): """Enforce line separators to be the right one depending on platform.""" token = str(uuid.uuid4()) line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "") return line.replace(token, os.linesep)
f1808c46c44024d5d6adf419ebfefb31a14a64cb
37,024
def create_div_stats(Pi, a, b): """Return div element with text of distribution statistics.""" # Calculate mode and variance probability based on prior. if a == 1 and b == 1: mode_str = "any value" else: # str(round((a - 1.0) / (a + b - 2.0), 7)) mode_str = f"{(a - 1.0) / (a + b...
974c5fbf479a7cc44d7aee16f00e1e08964af259
37,025
def check_credentials(account): """ Function that check if a Credentials exists with that account name and return true or false """ return Credentials.if_credential_exist(account)
cc9724bd6bbc3059ac7610ebcc650d76ba93fcce
37,026
from typing import List from re import T def quicksort(args: List[T]) -> List[T]: """ >>> quicksort([4, 3, 2, 1]) [1, 2, 3, 4] >>> quicksort([4, 2, 3, 1]) [1, 2, 3, 4] >>> quicksort([1, 2, 4, 3]) [1, 2, 3, 4] >>> data = list(range(100)) >>> random.shuffle(data) >>> quicksort(da...
4a48608d10550f60a458337029e0ecbf94167a07
37,027
def vect3_bisector(v1, v2): """ Gives the bisector vector of v1, v2 v1, v2 (3-tuple): 3d vectors return (3-tuple): 3d vector """ return vect3_add(vect3_normalized(v1), vect3_normalized(v2))
9c7209e6850b59ecade9c263e47e9c178010af40
37,028
def check_intra_node_overlap(node_a, node_b): """ check if alignments of the same read hit overlapping parts of the same node (or node_a and _b are different) """ same_node = True if node_a.name != node_b.name: same_node = False same_orientation = False overlap_bp = 0 ...
13f019b552576cf57cf08363ff42f7e3067f659d
37,029
import tensorflow.keras as keras def load_model(filepath, custom_objects=None, compile=True): """ Loads a model saved via `save_model`. Arguments: filepath: One of the following: - String, path to the saved model - `h5py.File` object from which to load the model cu...
7b1dc2616cb81567bb178a33714580275cee0918
37,030
def read_guess_word(row): """ Read the specified row's results. """ guess_result = [read_guess_letter(row, ordinal) for ordinal in range(word_len)] return guess_result
fa86d12a90eefa7e3caa5483aabc379986025076
37,031
def teacher_data(num_train=100, num_test=300, num_feat=5, num_feat_teach=10, width=1.0): """Generate two Gaussians and then split features into normal features and teacher features """ (metadata, examples, labels) = cloudgen(num_train+num_test, num_feat+num_feat_teach, ...
d1adcd8efdcfbe187f5e058500fc3475fc72db16
37,032
def _transformer_mask(x, triu, mask, lengths, left_aligned): """Helper function to determine attention masks for the transformer Args: x (:py:class:`dynet.Expression`): Input (dimensions ``input_dim x L``) triu (bool): Upper triangular masking mask (:py:class:`dynet.Expressi...
d9b639437d95e6b0379016179ceedc328b7ffa2c
37,033
def inverse_alr(Y: np.ndarray, ind=-1, null_col=False): """ Inverse Centred Log Ratio transformation. Parameters --------------- Y : :class:`numpy.ndarray` Array on which to perform the inverse transformation, of shape :code:`(N, D-1)`. ind : :class:`int` Index of column used as...
9cdcf851edad0718cc47b016077cca949670152e
37,034
import os import subprocess def exec_potrace(filepath, line='', filename=None): """ Executes a subprocess call that executes imagemagick's convert :returns True if passed, False if failed """ if filename is None: return '', False line = line if line is True else '' name = filename.sp...
4d315aae034b34729b10f103dc63dd2d8ab22764
37,035
import re def content_insert_emotes(bot: Bot, string: str): """ Method that will attempt to turn the passed in string and replace emoji sequences with the appropriate emote Parameters ---------- bot: Bot pass in bot reference to find emotes string: str the string that may or m...
54b88baf8c093057a02d41b63bd5f7869606793f
37,036
def square(root): """This function calculates the square of the argument value""" # result = num * num return root * root
54049a92a0383c756911a4604161e092d496ce62
37,037
from typing import MutableSequence from typing import Any def quick_sort(seq: MutableSequence[Any]) -> MutableSequence[Any]: """Quicksort or Hoare's sort. Algorithm in-place, complexity: O(n*log(n)) for a totally unsorted seq. """ def _quick_sort( _seq: MutableSequence[Any], _...
b1003afbe9ddb812ba33a99187e1a7f91c31fcc7
37,038
import string from typing import Counter def letter_frequency(seq): """Returns a dictionary with the frequencies of letters in the sequence""" freq = filter(lambda x: x in string.ascii_letters, seq.lower()) freq = dict(Counter(freq).most_common()) freq.update(dict((x, 0) for x in filter(lambda x: x no...
bcbf61526c395bc8df36bf7b3a7a37b25dbe1aba
37,039
def ns_template(): """api.query.ns_template 获取[模板]命名空间中所有页面 Returns: List Of Response(py.Dict) Response: { 'pageid': 页面id, 'ns': 10, 'title': 标题, } """ return _abstract_ns_allpages(10)
db95dfa9ebe4c632666f02e68df0d478b0748b84
37,040
def custom_openMM_force_object(system, bond_list, bond_type_index_dict, bond_param_dict, angle_list=None, angle_type_index_dict=None, angle_param_dict=None): """ #todo: add argument allowing this custom function to be fed in as an input (more flexible used-designed ff) :param bond...
e1b9c9cfb9e010fa869d9fef75c30661cd93c7ff
37,041
from typing import Optional from datetime import datetime def test_collect_account_basic_account_metrics(target_datetime: Optional[datetime.datetime] = None) -> dict: """ Run the CostManager.collect_account_basic_account_metrics() function and retrieve the results. """ end, _, previous_month_start = _...
e53242e4fa8109988939de759cf44f3d57af59aa
37,042
def shadow_model(): """The architecture of the shadow model is same as target model, because the attack is white-box, hence the attacker is assumed to know this architecture too. :return: shadow model """ classifier = Sequential() classifier.add( Dense(1, input_dim=featur...
89ae1c17d7cc7d45cff3f28103929d76d4632a63
37,043
def get_codes(dikt, text): """ returns those elements in a dict where value contains the expressions listed in codes todo: more complicated star notations: starts with, contains, endswith alterative name: find_codes? get_codes? example get all codes that have "steroid" in the explanatory text ...
8cfba80b4dd97202d46c6f3034f31b4e7b924fd4
37,044
def is_kind_of_class(obj, a_class): """ Function that determine if a class is a specific class or an inherited class. Args: obj (object any type): The object to analyze. a_class (object any type): The reference object. Returns: Returns True if the obj is exactly an instanc...
3a31ad121ace5918e7f3f5d7620e5ab94a92501a
37,045
def get_candidate_type(candidate_tokens): """Returns the candidate's type: Table, Paragraph, List or Other.""" first_token = candidate_tokens[0] if first_token == "<Table>": return "Table" elif first_token == "<P>": return "Paragraph" elif first_token in ("<Ul>", "<Dl>", "<Ol>"): ...
298856aef02c44683af6bd32cb9284f62d0aabc9
37,046
def parse_file(input_file): """ Input: A file containing one binary-number string per line Output: A list of binary number strings Blank lines and lines starting with '#' are ignored """ strings = [] with open(input_file) as f: for line in f.readlines(): line = line.strip...
63b51ee15c264c8e0635053d80bf47f70687023e
37,047
import torch def from_numpy(x): """Creates a ComplexTensor from a numpy.ndarray. """ a = x.real.copy() b = x.imag.copy() return ComplexTensor(torch.from_numpy(a), torch.from_numpy(b))
e3cb1577e1d4b27bfacb0c8d93dedc4cfeb4f5f7
37,048
def classification_stats(ytrue, ypred, num_samples=1000): """ construct a dataframe that summarizes classification """ # compute aucs, prec, rec, f1 auc = roc_auc_score(ytrue, ypred) yp = ypred > .5 prec = precision_score(ytrue, yp) rec = recall_score(ytrue, yp) f1 = f1_score(ytrue, y...
7593e835499ad1e1acb5aa12b7556c7a2368d852
37,049
def process_map_input(input_lines): """ Find the dimensions of a map using the lines of input :param input_lines: List of string representing the map :return: (x: width, y: height) Tuple """ height = len(input_lines) - 1 width = len(input_lines[0]) return width, height
30662e1466d6d553ddee797c6252453c6f6f7f47
37,050
def total_loss(c_layer, s_layers, generated): """ Computes the total loss of a given iteration :param c_layer: The layer used to compute the content loss :param s_layers: The layer(s) used to compute the style loss :param generated: The generated image :return: The total loss """ conten...
1914f501873326c92bd28d938872f77df55d67a8
37,051
import random def weighted_choice(lst): """Choose element in integer list according to its value. E.g., in [1,10], the second element will be chosen 10 times as often as the first one. Returns the index of the chosen element. :ivar [int] lst: List of integers. :rtype: int """ total = ...
513ca734a7b96f08993bd03c47df9c60288ebe50
37,052
def git_connect(github_username, github_password, github_repo): """ Logs in to github with our creds, returns gh,repo,branch objects. """ gh = github3.login(username=github_username, password=github_password) # we login and get a session. repo = gh.repository(github_username,github_repo) # we create our...
4bcaf55bbbe3404fffea30c11c9a7f779f213252
37,053
def get_course(doc): """Returns the course name for given document of type Course, Chapter, Lesson or Exercise. """ if doc.doctype == "LMS Course": return doc.name elif doc.doctype == "Course Chapter": return doc.course elif doc.doctype == "Exercise": return doc.course el...
e69510c1d8055e08562c2fe6842ef209b93c5942
37,054
import argparse def _read_configuration(): """Get and return application settings. :return: """ parser = argparse.ArgumentParser( description='Compute PaDEL descriptors for given' 'molecules/fragments.') parser.add_argument('-i', type=str, dest='input', ...
97c46b9daea3645c2c96600b9b03092d3b98e198
37,055
def v_vorticity(u, v, dx, dy, dim_order='xy'): """Wrap vorticity for deprecated v_vorticity function.""" return vorticity(u, v, dx, dy, dim_order=dim_order)
13fa0cdc4be4df6ec98bd9646cbc33ad84a67c19
37,056
from typing import List def split_rgb(stack: Image, with_alpha=False) -> List[Image]: """Variant of stack_to_images that splits an RGB with predefined cmap.""" if not stack.rgb: raise ValueError( trans._('Image must be RGB to use split_rgb', deferred=True) ) images = stack_to_...
dd3b80bf36ba430a26a9ff5605b215b5d6a68524
37,057
def get_country(user): """ Returns the object the view is displaying. """ user_countries = ActivityUser.objects.all().filter( user__id=user.id).values('countries') get_countries = Country.objects.all().filter(id__in=user_countries) return get_countries
1abebfec315834aa00ef8f12b08cf6e64262169b
37,058
def isfirefox(session): """ bool: Whether the session is using Firefox. """ return getattr(session.driver, "_firefox", False)
ca7c5c217de308642e4ec0687c42a0dc71cfeecd
37,059
from typing import Dict from typing import Any from typing import cast def generate_readme(meta: Dict[str, Any]) -> str: """ Generate a Markdown-formatted README text from a model meta.json. Used within the GitHub release notes and as content for README.md file added to model packages. """ md ...
41b91b31d3c2fbeab1440a0ec82d06d857c98168
37,060
def origin_tag(parser, token): """Create a node indicating the path to the current template""" if hasattr(token, "source"): origin, source = token.source return OriginNode(origin) else: return OriginNode()
2ad166eaebcfd6cd6c00f76fdb339342e05ae100
37,061
def get_bucket_name(config, bucket_suffix=None): """ Return a bucket name of the form: ${account_id}-${project}-${suffix} Args: config: dictionary containing all variable settings required to run terraform with. bucket_suffix: string to add to the returned bucket name. ...
0d607f35e2beb6149e21da426dc73a1118ad1967
37,062
from typing import Optional import os def solve( instance: CVRPInstance, params: Optional[LKHParams] = None ) -> CVRPSolution: """Solve a CVRP instance using LKH-3""" params = params or LKHParams() logger.info("Converting instance into a TSPLIB file") convert_instance_file(instance, params) ...
66080f933b7ea663ba52f5bfe388b34426271fc3
37,063
def break_track(xy,waypoints,radius_min=400,radius_max=800,min_samples=10): """ xy: coordinate sequence of trackline waypoints: collection of waypoints return pairs of indices giving start/end of transects, split by waypoints. """ breaks=[] for waypt in waypoints: dists = mag( xy[:...
a56795deac8c41a0670a3f4d76d698f2cb54e2e0
37,064
def parse_string(s): """ Parse string containing Snowball code. Returns the corresponding AST. """ reset() return PROGRAM.parseString(s)[0]
b3298ddc2bba330e07cbe15078d2286b5250c95e
37,065
def list_to_multipolygon_df(list_of_inds, discretizer=DefaultSystem, split=True): """ Parameters ---------- split : object """ unique_h3 = list(set(list_of_inds)) polys = [discretizer.ind_to_boundary(cod) for cod in unique_h3] if split: polys = [shp_help.split_polys(poly) for po...
0a2ab86112324480a4e8f3a7a4f3275e7a8fe699
37,066
def Get_Data(filename, start, stop): """Takes output from txt file and converts to a np.array Argument: filename -- filename including end bit, enclosed in single inverted commas start, stop -- integers, lines to read if there's a header etc Returns: array -- np.array of file c...
9844606de755aa71e70df7f5bca67518df5dc595
37,067
import os from pathlib import Path import json def load_sample_weights(weights_dir, filename='.json', dtype=np.float): """Loads the sampled bnn weight sets from directory recursively into memory. """ weights_sets = [] # loop through json files, get weights, concatenate them # walk directory t...
ecc856c4ad50a2008ff26ab8d0c8dd2818b6e6ff
37,068
from datetime import datetime def get_es_index_name(project, meta): """ Get the name for the output ES index :param project: seqr project identifier :param meta: index metadata :return: index name """ return '{project}__structural_variants__{sample_type}__grch{genome_version}__{datestamp}...
fc1245287aed07ddd8d90f33cadc095c22f944a3
37,069
def triangle_coordinates(i, j, k): """ Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangles are parallel to the lower axis on the lower side. Parameters ---------- i,j,k: enumeration of the desired triangle Returns ------- A numpy ar...
ffdaf2c601cb4f25b15b67a97a9746a80dbcdd6b
37,070
def generate_lines(rects, room): """ Converts a list of rects each containing x, y, width, height, theta into a list of lines (each rect has 4 lines) room is (width, height) of surrounding room returns list of lines, each line is 2 points """ # x, y, w, h, angle rects.append([0, 0, room...
7d57a8dd892727bcda4be9c97cb5aa10509f3519
37,071
def generic_exception_json_response(code): """ Turns an unhandled exception into a JSON payload to respond to a service call """ payload = { "error": "TechnicalException", "message": "An unknown error occured", "code": code } resp = make_response(jsonify(payload), code) ...
ad891505aefa9dc261a00a3a50d0033b9932f113
37,072
def reference_col(tablename, unique=False, nullable=False, pk_name='id', **kwargs): """Column that adds primary key foreign key reference. Usage: :: category_id = reference_col('category') category = relationship('Category', backref='categories') """ return db.Column(...
d7400e6b1a9b65b1aa43e14442fa65ff01ef59c6
37,073
import cairosvg import StringIO def convertSvgToPng(svg_data): """ Converts the given svg data to PNG. This one is preferred over convertSvgTo(), because it simply returns the result instead of a file and does not have excessive white space. """ buffer = StringIO.StringIO() cairosvg.svg2png(by...
93bcc7c6657aee877ca032775903700c00b8617b
37,074
def RegexCheck(re, line_number, line, regex, msg): """Searches for |regex| in |line| to check for a particular style violation, returning a message like the one below if the regex matches. The |regex| must have exactly one capturing group so that the relevant part of |line| can be highlighted. If more ...
31e979570eb4e0b251f445555f24fadef8e6879d
37,075
import time import ast def load_graphml(filename, folder=None): """ Load a GraphML file from disk and convert the node/edge attributes to correct data types. Parameters ---------- filename : string, the name of the graphml file (including file extension) folder : string, the folder contai...
b0c2afff46e8e81d450a1fc32e7e169e04ce285b
37,076
def cosine_distances(test, support): """Computes pairwise cosine distances between provided tensors Parameters ---------- test: tf.Tensor Of shape (n_test, n_feat) support: tf.Tensor Of shape (n_support, n_feat) Returns ------- tf.Tensor: Of shape (n_test, n_support) """ rnorm_test = t...
06214a59cda12b78a2b8a520c3cf7fe02b7c8479
37,077
def read_table_file(file, element, sheet_name=0, n=0, sheet_type="Model"): """Instantiate one or more element objects using inputs from an Excel table. Parameters ---------- file: str Path to the file containing the shaft parameters. element: str Specify the type of element to be in...
a51387be0ada1f5d9307ce959ee476191305470b
37,078
def substring(column, pos=0, l=1): """ Substring starts at ``pos`` and is of length ``l`` when str is String type or returns the slice of byte array that starts at ``pos`` in byte and is of length ``l`` when ``column`` is Binary type # Arguments column: a ``Column`` object, or a column name ...
6922224fda5a72305f2d7158b28982d30de722fa
37,079
def _f2_div_ ( self , other ) : """Operator for ``2D-function / other''""" return _f2_op_ ( self , other , Ostap.MoreRooFit.Division , "Divide_" )
ecc5ce2cf3e423209f006f04b90953b423270be7
37,080
def usplit( uval ): """ Split Unicode string into a sequence of characters. \U sequences are considered to be a single character. You should assume you will get a sequence, and not assume anything about the type of sequence (i.e. list vs. tuple vs. string). """ # The commented code (below)...
39efcb9e9f87f7809ec5919e23617c860654bcb8
37,081
def aten_mean(mapper, graph, node): """ 构造求均值的PaddleLayer。 TorchScript示例: %x.28 : Tensor = aten::mean(%result.1, %4967, %3, %2) 参数含义: %x.28 (Tensor): 输出,求均值后的结果。 %result.1 (Tensor): 输入,需要求均值的Tensor。 %4967 (int/list): 求平均值运算的维度。 %3 (bool): 是否在输出Tensor中保留减小的维度。 ...
21eba8c745363e21d5e049100f06746fbef2c0e4
37,082
def get_partial_dict(prefix, dictionary, container_type=dict): """Given a dictionary and a prefix, return a Bunch, with just items that start with prefix The returned dictionary will have 'prefix.' stripped so:: get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}) would return...
a4450fe8930932c1568fba1dd42053e29eddc573
37,083
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add val...
2795730972837612d1b87bc6cba2e28a8047c457
37,084
async def add_user(user: NewUserPayload): """ Creates new user in database """ try: user_exists = await storage.driver.user.check_if_exists(user.email, user.id) except ElasticsearchException as e: raise HTTPException(status_code=500, detail=str(e)) if not user_exists: try...
72a2c63eaa335564f4ad385a573847cce5df1f23
37,085
import os def check_bsp_planetary(): """ Verifica se existe o arquivo BSP Planetary. """ bsp_planets_filename = os.getenv("BSP_PLANETARY") bsp_planets = os.path.join(os.getenv("DATA_DIR"), bsp_planets_filename) if not os.path.exists(bsp_planets): # Se nao existir no data, criar lin...
6b9f0a8e026e3cb7121db2e8d0ff1cc3128da6a5
37,086
async def _update_instance_async(filter, projection, update) -> dict: """Helper to update an instance async-style""" await moto.update_one(collection="system", filter=filter, update=update) return await _get_instance_async(filter, projection)
7d87e656304e2a28166a059fdda8252c197bed9a
37,087
from pathlib import Path from typing import Optional from typing import List def cryptominisat_solve(input_file: Path, docker_mode: bool = DEFAULT_DOCKER_MODE_ON) -> Optional[List[int]]: """Attempts to solve a CNF formula with CryptoMiniSAT and returns the result as a list of integers. Returns an empty l...
c601574773ca4a1bc2d1e21064e5b8c1e999ecba
37,088
import math def sen(x): """ El seno de un número. El ángulo debe estar expresado en radianes. .. math:: \sin(x) Args: x (float): Argumento. Returns: El seno. """ return math.sin(x)
26f7854e550cd0ac68123d3f2d5b3117aef282a6
37,089
def req_item_packs(): """ Called by S3OptionsFilter to provide the pack options for an Item Access via the .json representation to avoid work rendering menus, etc """ req_item_id = None args = request.args if len(args) == 1 and args[0].isdigit(): req_item_id = args[0] e...
22cf4c4884ef84b924c0e09e134bce8074455349
37,090
def create_board() -> t.List[t.List[int]]: """Initialize game board (road).""" board = [] # Create rows for _ in range(BLOCKS_AMOUNT_Y + 1): board.append( [Blocks.frame] + [Blocks.empty for _ in range(BLOCKS_AMOUNT_X - 2)] + [Blocks.frame] ) return...
d58d82e8b201b8a91a748559f5195cba7355ab3b
37,091
def SymDatToPath(symtext): """Convert a Cygwin style symlink data to a relative path.""" return ''.join([ch for ch in symtext[12:] if ch != '\x00'])
0d5104819678ca12d95b5f987a88726c5aef3f18
37,092
def n_bytes(count: int, name: str = ""): """ Create an instance of a byte string of ``count`` length. Setting ``count`` to ``-1`` will consume the entire remaining buffer. """ class BYTES(BytesDataType): size = count return BYTES(name)
a06668571b2b0c759361ce3bee74fa67af9b682e
37,093
from typing import Container def find_trait_and_value(obj, pathname): """Return a tuple of the form (trait, value) for the given dotted pathname. Raises an exception if the value indicated by the pathname is not found in obj. If the value is found but has no trait, then (None, value) is returned. ...
2a0851e433ceac57494718d38942147c25d2c07a
37,094
from sys import path def icon(name, extension=None, style=None, use_inheritance=True, allow_theme=True, _always_return=True): """ Find an icon with the given ``name`` and ``extension`` and return a :class:`PySide.QtGui.QIcon` for that icon. ================ =========== ============ Arg...
080b6e183b6cd480da53d86b7ad49ed4d28b3e6a
37,095
def bigbird_block_rand_mask(from_seq_length, to_seq_length, from_block_size, to_block_size, num_rand_blocks, last_idx=-1): """Create adjacency list of random attention. Args: ...
1d51a4eec884b6c38b58897ad245428b73f19f06
37,096
import json def list_(env=None, user=None): """ List the installed packages on an environment Returns ------- Dictionary: {package: {version: 1.0.0, build: 1 } ... } """ cmd = _create_conda_cmd('list', args=['--json'], env=env, user=user) ret = _execcmd(cmd, user=user) if ret[...
25a9f82afe94587b832ccf70a16949d1f400c089
37,097
def read_dir_key(fname='', existing_dict=None, delim=None): """ Read a directory mapping key. """ out_dict = read_nametoname_key(fname=fname, existing_dict=existing_dict, delim=delim) return(out_dict)
5c7a7620bd11e146f37b14129647a057ecd66099
37,098
def get_end_pair_index(s: str, i: int): """ This method takes a string and an integer as inputs. It searches for the opening brace'[' using the given integer as the index of the opening brace in the given string. It outputs the index of the closing pair ']' in the string. :param s: The input string...
bd0413aa2ff48df2bb76736a11fda40757f2d482
37,099