content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import csv def snp2dict(snpfile): """Get settings of dict from .snp file exported from save&restore app. Parameters ---------- snpfile : str Filename of snp file exported from save&restore app. Returns ------- r : dict Dict of pairs of PV name and setpoint value. """ ...
cb902b3f8796685ed065bfeb8ed2d6d83c0fe80b
30,800
import numpy def _handle_zeros_in_scale(scale, copy=True, constant_mask=None): """ Set scales of near constant features to 1. The goal is to avoid division by very small or zero values. Near constant features are detected automatically by identifying scales close to machine precision unless t...
129f28dbf74f04929fcbccf8de42ee1c8dd5a09e
30,801
def ST_LineStringFromText(geos): """ Transform the representation of linestring from WKT to WKB. :type geos: WKT :param geos: Linestring in WKT form. :rtype: WKB :return: Linestring in WKB form. :example: >>> from pyspark.sql import SparkSession >>> from arctern_pyspark import...
7cb0a5f3f6d35b49d35765ad5b5992952fe58e18
30,802
def get_container_state(pod, name): """Get the state of container ``name`` from a pod. Returns one of ``waiting, running, terminated, unknown``. """ phase = pod["status"].get("phase", "Unknown") if phase == "Pending": return "waiting" cs = get_container_status(pod, name) if cs is no...
bad0143dbc2fb6998dce62665138d94f9542abc5
30,803
def implicit_ecp( objective, equality_constraints, initial_values, lr_func, max_iter=500, convergence_test=default_convergence_test, batched_iter_size=1, optimizer=optimizers.sgd, tol=1e-6): """Use implicit differentiation to solve a nonlinear equality-constrained program of the form: m...
98a753765dda4cbc09ee8b1bc6225c12d10eb996
30,804
from .modules import utils, concat def concatenate(input_files, output_file): """ Concatenates the input files into the single output file. In debug mode this function adds a comment with the filename before the contents of each file. """ if not isinstance(input_files, (list, tuple)): ...
0fcfb9e83bd300a383f037cfed14abf06cdc23ab
30,805
def get_detection_probability_Braun2008(filename, index, TS_threshold): """ Find the detection probability as a function of the expected number of source counts in a detector. Returns Nsrc_list and Pdet :param filename: Filename :param index: spectral index :param TS_threshold: TS <=>...
631195c6d0c264d9b8676929882048d39333f2d6
30,806
from datetime import datetime def device_create(db: Session, name: str, device_type: DeviceType, activation_token: str) -> Device: """ Create a new Device """ device = Device( name=name, device_type=device_type, activation_t...
f7c39a52ad43523cce895b223da85ec6f632ade2
30,807
def xy_potential(_): """ Potential for square XY model with periodic boundary conditions """ def potential(_, passive_rates): pot = -passive_rates.sum(dim=(-1, -2, -3)) # sum over all sites and directions return pot return potential
b809e57464a9cd893cd33cd7ad38dffdb0d12a40
30,808
def distribute_srcs_2D(X, Y, n_src, ext_x, ext_y, R_init): """Distribute n_src's in the given area evenly Parameters ---------- X, Y : np.arrays points at which CSD will be estimated n_src : int demanded number of sources to be included in the model ext_x, ext_y : floats ...
8c984c742e6e8d604332e51f39e057a46cad0076
30,809
def _setBlueprintNumberOfAxialMeshes(meshPoints, factor): """ Set the blueprint number of axial mesh based on the axial mesh refinement factor. """ if factor <= 0: raise ValueError( "A positive axial mesh refinement factor " f"must be provided. A value of {factor} is inva...
6c477b0e55e996009158fa34c06d3c642e4691c4
30,810
from typing import Mapping from typing import Any import os import logging import time def run_benchmark( execution_mode: str, params: config_definitions.ExperimentConfig, model_dir: str, distribution_strategy: tf.distribute.Strategy = None ) -> Mapping[str, Any]: """Runs benchmark for a specific ex...
d8c48c410f61ec2837683b1132321c21d4a2e1f3
30,811
def make_fun(f, *args, **kwargs): """ This function calls the function f while taking into account some of the limitations of the pandas UDF support: - support for keyword arguments - support for scalar values (as long as they are picklable) - support for type hints and input checks. :param ...
bc625453aa4913bcb70cea80f39f8edb8d4abbc7
30,812
def _get_filter_syntax(_filter_info, _prefix=True): """This function retrieves the proper filter syntax for an API call.""" if type(_filter_info) != tuple and type(_filter_info) != list: raise TypeError("Filter information must be provided as a tuple (element, criteria) or a list of tuples.") elif t...
b1817a2a3f004ba2bd44a8f8f272ad685e4d5ebe
30,813
import logging def pad_and_crop(ndarray, target_shape=(10, 10, 10)): """ Center pad and crop a np.ndarray with any shape to a given target shape Parameters In this implementation the pad and crop is invertible, ceil and round respects uneven shapes pad = floor(x),floor(x)+1 crop = floor(x)+1, ...
5362654de8c890560cb66c83f103b98b34462cfd
30,814
import math def pol2cart(r,theta): """ Translate from polar to cartesian coordinates. """ return (r*math.cos(float(theta)/180*math.pi), r*math.sin(float(theta)/180*math.pi))
69753e1cadd36ec70da1bf2cf94641d4c7f78179
30,815
import math def mass2mk_ben(m): """mass2mk_ben - mass to M_K, Benedict et al. (2016) double exponential. Usage: mk = mass2mk_ben(mass) Where mk is absolute 2MASS K magnitude and mass is in solar masses. This version is the original double-exponential "forward model" (for going from mass to absolute magnitude)...
3e9f20588f87db6bb9429b6c5d7135ad879158c3
30,816
def apply_and_concat_one_nb(n, apply_func_nb, *args): # numba doesn't accepts **kwargs """A Numba-compiled version of `apply_and_concat_one`. !!! note * `apply_func_nb` must be Numba-compiled * `*args` must be Numba-compatible * No support for `**kwargs` """ output_0 = to_2...
ed75920864a736aeafe9156b5bd6e456cd287226
30,817
def convertCovariance2Dto3D(covariance2d): """ convert the covariance from [x, y, theta] to [x, y, z, roll, pitch, yaw] :param covariance2d: covariance matrix in 3x3 format. each row and column corresponds to [x, y, theta] :return: covariance matrix in 6x6 format. each row and colu...
4c6ea8bb8475a705fb40181172bab2a761676e85
30,818
import torch import random def fit_gan_wasserstein(nb_epoch: int, x_LS: np.array, y_LS: np.array, x_VS: np.array, y_VS: np.array, x_TEST: np.array, y_TEST: np.array, gen, dis, opt_gen, opt_dis, n_discriminator:int, batch_size:int=100, wdb:bool=False, gpu:bool=True): """ Fit GAN with discriminator using the Wa...
64fc1625aa76ca09c14720ef3489657b8c28e671
30,819
def manifest_file_registration(workspace_id): """マニフェストテンプレートファイル登録 Args: workspace_id (int): ワークスペースID Returns: response: HTTP Respose """ globals.logger.debug("CALL manifest_file_registration:{}".format(workspace_id)) try: # 登録内容は基本的に、引数のJsonの値を使用する(追加項目があればここで記載) ...
2823d3c413f3635855c035fa4d3ba912c2285823
30,820
import math def pad(image_array, final_dims_in_pixels, zero_fill_mode=False): """ Pad image data to final_dim_in_pixels Attributes: image_array (float, np.array): 3D numpy array containing image data final_dim_in_pixels (list): Final number of pixels in xyz dimensions. Example: [256, 2...
8882ded9a01f98e9163807675cf7246527443d97
30,821
def save_and_plot(canddatalist): """ Converts a canddata list into a plots and a candcollection. Calculates candidate features from CandData instance(s). Returns structured numpy array of candidate features labels defined in st.search_dimensions. Generates png plot for peak cands, if so defined in p...
484b2bf099c31762e294ce40039f01f8ec00a273
30,822
def GetReviewers(host, change): """Gets information about all reviewers attached to a change.""" path = 'changes/%s/reviewers' % change return _SendGerritJsonRequest(host, path)
4e2d5bdf37993f76b42c0062dec042dc5a01aa87
30,823
def plot_single_points(xs, ys, color=dark_color, s=50, zorder=1e6, edgecolor='black', **kwargs): """Plot single points and return patch artist.""" if xs is None: xs = tuple(range(len(ys))) return plt.scatter(xs, ys, marker='o', s=s, color=color, zorder=zorder, edgecolor=edgecolor, **kwargs)
490c17dbb360bc06c7805dddb7af1c72b5ce5890
30,824
import _ast def find_imports(source: str, filename=constants.DEFAULT_FILENAME, mode='exec'): """return a list of all module names required by the given source code.""" # passing an AST is not supported because it doesn't make sense to. # either the AST is one that we made, in which case the imports have already be...
2ea91f6387e455fb1b4907e6a109fc3b987c8a9d
30,825
def generate_character_data(sentences_train, sentences_dev, sentences_test, max_sent_length, char_embedd_dim=30): """ generate data for charaters :param sentences_train: :param sentences_dev: :param sentences_test: :param max_sent_length: :return: C_train, C_dev, C_test, char_embedd_table ...
c53257e1d999edafc54b627a0687ae33aaebc487
30,826
def draw_pie_distribution_of_elements(Genome_EP, ChIP_EP, gprom=(1000, 2000, 3000), gdown=(1000, 2000, 3000), prom=(1000,2000,3000), down=(1000,2000,3000)): """Draw the pie charts of the overall distributions of ChIP regions and genome background """ # get the labels (legend) for the genome pie chart gn...
24a28a23e2929e20c77dd2389691235d51e1ba80
30,827
def get_neighborhood(leaflet, mdsys): """ Get neighborhood object for the give leaflet """ dist = distances.distance_array(leaflet.positions, leaflet.positions, mdsys.dimensions[:3]) nbrs = Neighborhood(leaflet.positions, dist, mdsys.dimensions[:3]) return nbrs
234193d36c957a0dd26a805f2fcbf5e97c0be2d6
30,828
def clean_title(title: str) -> str: """Strip unwanted additional text from title.""" for splitter in [" (", " [", " - ", " (", " [", "-"]: if splitter in title: title_parts = title.split(splitter) for title_part in title_parts: # look for the end splitter ...
5625c6c64b166560b1804b7048fd3d604536251a
30,829
def get_dates(): """ Query date in the tweets table :return: """ sql = "SELECT date FROM tweets" dates = cx.read_sql(db, sql) return dates
60704fa5fa625ffbd42b29b9cc22c95d01475026
30,830
def _convert_to_dict(best_param): """ Utiliy method for converting best_param string to dict Args: :best_param: the best_param string Returns: a dict with param->value """ best_param_dict = {} for hp in best_param: hp = hp.split('=') best_param_dict[hp[0]] ...
318ed529b0f411b1b671de34a4b0f4ecf3dc9780
30,831
import os def read_in(file_index, normalized, train, ratio): """ Reads in a file and can toggle between normalized and original files :param file_index: patient number as string :param normalized: binary that determines whether the files should be normalized or not :param train: int that determine...
c83c5033a291e99b45886a45e55cdd96af477cda
30,832
def _expand_currency(data: dict) -> str: """ Verbalizes currency tokens. Args: data: detected data Returns string """ currency = _currency_dict[data['currency']] quantity = data['integral'] + ('.' + data['fractional'] if data.get('fractional') else '') magnitude = data.get('magni...
491d175195f97126d65afec65c60f2e34ca09bc3
30,833
def getCampaignID(title): """ Returns the id of a campaign from a dm name and a title """ conn = connectToDB() cur = conn.cursor() print title query = cur.mogrify('select id from campaigns where title = %s;', (title,)) print query cur.execute(query) results = cur.fetchone() return re...
b3f6f3b50a97e25931754332ed864bdac9d5c639
30,834
import time def calculate_exe_time(input_function): """ This decorator method take in a function as argument and calulates its execution time. :param input_function: name of method to be executed. :return process_time: method that calls the input_function and calculates execution time. """ de...
bdbd4e20c8126e48d27031e46e5a91c83740a188
30,835
import torch def load_xyz_from_txt(file_name): """Load xyz poses from txt. Each line is: x,y,x Args: file_name (str): txt file path Returns: torch.Tensor: Trajectory in the form of homogenous transformation matrix. Shape [N,4,4] """ global device poses = np.genfromtxt...
f0d57aafa9e96a20c719a27dc8e0f2c18ebe0e7b
30,836
def category_add(): """ Route for category add """ # request Form data form = CategoryForm(request.form) if request.method == "POST" and form.validate(): # Set new category name variable category_name = form.name.data.lower() if category_check(category_name): ...
11a94b7b3600fcaad0848696dd63648d39988052
30,837
import requests def generate_text(input: TextGenerationInput) -> TextGenerationOutput: """Generate text based on a given prompt.""" payload = { "text": input.text, "temperature": input.temperature, "min_length": input.min_length, "max_length": input.max_length, "do_sam...
1c0eeff8b90b5246828a285f8c7a86bc4095c364
30,838
def file_content_hash(file_name, encoding, database=None): """ Returns the hash of the contents of the file Use the database to keep a persistent cache of the last content hash. """ _, content_hash = _file_content_hash(file_name, encoding, database) return content_hash
42962749e6bb5ec2d061ffcefd6ebf4aa34bbc29
30,839
import inspect def pass_multiallelic_sites(mqc): """ The number of PASS multiallelic sites. Source: count_variants.py (bcftools view) """ k = inspect.currentframe().f_code.co_name try: d = next(iter(mqc["multiqc_npm_count_variants"].values())) v = d["pass_multiallelic_sites"]...
cd91ff816e88fa29e4d3beed4d0baf740388428c
30,840
import json def read_dialog_file(json_filename: str) -> list[Message]: """ Read messages from the dialog file @return: list of Message objects (without intent) """ with open(json_filename, encoding="utf8") as dialog_json: return [ Message(is_bot=msg["is_bot"], text=msg["text"])...
9665c6bd708c66e66e24cb416d033730ef4f3909
30,841
def dtwavexfm3(X, nlevels=3, biort=DEFAULT_BIORT, qshift=DEFAULT_QSHIFT, include_scale=False, ext_mode=4, discard_level_1=False): """Perform a *n*-level DTCWT-3D decompostion on a 3D matrix *X*. :param X: 3D real array-like object :param nlevels: Number of levels of wavelet decomposition ...
d0adab48c51ade82fab55b416029a2291151e3b9
30,842
def character_regions(img, line_regs, bg_thresh=None, **kwargs): """ Find the characters in an image given the regions of lines if text in the image. Args: img (numpy.ndarray): Grayscaled image. line_regs (list[tuple[int, int]]): List of regions representing where the lines ...
2e1b182944a857b698886ed590295723909dcc7e
30,843
def cache_clear(request): """ Очищает директорию кеша. """ Core.get_instance().clear_cache() return { 'size': Core.get_instance().get_cache_size() }
039ddc6e400c1befe283b529ba239d9c7831a7ce
30,844
def sort_crp_tables(tables): """Sort cluster assignments by number""" keys = sorted(tables, key=lambda t: (len(tables[t]), min(tables[t])), reverse=True) items = [item for table in keys for item in tables[table]] dividers = [len(tables[table]) for table in keys] return (items, np.cum...
4147cb86ed672b7dd1503615ba759fdb36d74185
30,845
def sum_category_hours(day, now, timelog=TIMELOG, category_hours=False): """ Sum the hours by category. """ if not category_hours: category_hours = {} activities = get_rows(day, timelog) for activity in activities: category = activity.category duration = activity.get_duration(now...
5d8d77759c43f40c616bd394ed8ba169f4a58917
30,846
def run_factory( factory, # type: LazyFactory args=None, # type: Optional[Iterable[Any]] kwargs=None, # type: Optional[Mapping[str, Any]] ): # type: (...) -> Any """ Import and run factory. .. code:: python >>> from objetto.utils.factoring import run_factory >>> bool(ru...
3766555849bca15e568ffc41fb522a47c22c666c
30,847
def steps_smoother(steps, resolution): """ :param delta_steps: array of delta positions of 2 joints for each of the 4 feet :return: array of positions of 2 joints for each of the 4 feet """ smoothed_steps = [] for i in range(len(steps)): step = steps[i] next_step = steps[(i + 1) ...
a27e09af169e79438895d0e15c0b536213962429
30,848
from typing import Optional def get_instance_server(name: Optional[str] = None, server_id: Optional[str] = None, zone: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetInstanceServerResult: """ Gets inform...
aae211831c951d131a4cd21fab917da5b169f31b
30,849
def leaper(x, y, int1, int2): """sepcifically for the rook, permutes the values needed around a position for no_conflict tests""" return [(x+int1, y+int2), (x-int1, y+int2), (x+int1, y-int2), (x-int1, y-int2), (x+int2, y+int1), (x-int2, y+int1), (x+int2, y-int1), (x-int2, y-int1)]
6f7afc071c8adbc72a6391179e2df522574e5197
30,850
def calc_offsets(obj): """ The search "hit" should have a 'fullsnip' annotation which is a the entire text of the indexable resource, with <start_sel> and <end_sel> wrapping each highlighted word. Check if there's a selector on the indexable, and then if there's a box-selector use this to gener...
6af4827a57cf20f317ce2a40a669c14d3f6380f3
30,851
import argparse import sys def parse_args(): """ Parse command-line arguments Returns ------- Parser argument namespace """ parser = argparse.ArgumentParser(description="Fibermorph") parser.add_argument( "--output_directory", default=None, help="Required. Full path...
e788d4519b539ba52e99989653c7aa3091cd9a39
30,852
def spread(self, value="", **kwargs): """Turns on a dashed tolerance curve for the subsequent curve plots. APDL Command: SPREAD Parameters ---------- value Amount of tolerance. For example, 0.1 is ± 10%. """ return self.run("SPREAD,%s" % (str(value)), **kwargs)
a92c8e230eadd4e1fde498fa5650a403f419eaeb
30,853
def _ValidateCandidateImageVersionId(current_image_version_id, candidate_image_version_id): """Determines if candidate version is a valid upgrade from current version.""" if current_image_version_id == candidate_image_version_id: return False parsed_curr = _ImageVersionIt...
25d888645211fc21f7a21ee17f5aeeb04e83907e
30,854
import random def run_mc_sim(lattice, num_lattice_steps, data_dict, io_dict, simsetup, exosome_string=EXOSTRING, exosome_remove_ratio=0.0, ext_field_strength=FIELD_SIGNAL_STRENGTH, app_field=None, app_field_strength=FIELD_APPLIED_STRENGTH, beta=BETA, plot_period=LATTICE_PLOT_PERIOD, ...
bfd11100b37a2161cfaf32c10be0ba48dfdc0a84
30,855
def collisional_loss(electron_energy): """ Compute the energy dependant terms of the collisional energy loss rate for energetic electrons. Parameters ---------- electron_energy : `numpy.array` Array of electron energies at which to evaluate loss Returns ------- `numpy.array` ...
6edbb87a70dc033542c5dc3a113886ba26c87bc8
30,856
import re def getOrdererIPs(): """ returns list of ip addr """ client = docker.from_env() container_list = client.containers.list() orderer_ip_list = [] for container in container_list: if re.search("^orderer[1-9][0-9]*", container.name): out = container.exec_run("aw...
745c9635b03745c5e61d6cd56c0b1fcd58df1fa4
30,857
import re def repair_attribute_name(attr): """ Remove "weird" characters from attribute names """ return re.sub('[^a-zA-Z-_\/0-9\*]','',attr)
f653a5cb5ed5e43609bb334f631f518f73687853
30,858
def get_xsd_file(profile_name, profile_version): """Returns path to installed XSD, or local if no installed one exists.""" if profile_name.lower() not in XSD_LOOKUP_MAP: raise ValueError( 'Profile %s did not match a supported profile: %s.\n' % (profile_name, sorted(XSD_FILES.keys()))) # Ensur...
02d2c127fabd0a8f274211885e625f90d314036f
30,859
def get_response(url: str) -> HTMLResponse: """ 向指定url发起HTTP GET请求 返回Response :param url: 目标url :return: url响应 """ session = HTMLSession() return session.get(url)
f53c2a6a2066bbe76f3b9266d42ad014d5e4fcfa
30,860
def minutesBetween(date_1, date_2): """Calculates the number of whole minutes between two dates. Args: date_1 (Date): The first date to use. date_2 (Date): The second date to use. Returns: int: An integer that is representative of the difference between two dates. "...
1e75c3571bee3855183b7a51e661d8eaa0bf47a2
30,861
from typing import Dict import pkgutil import sys import importlib def find_whatrecord_submodules() -> Dict[str, ModuleType]: """Find all whatrecord submodules, as a dictionary of name to module.""" modules = {} package_root = str(MODULE_PATH.parent) for item in pkgutil.walk_packages(path=[package_roo...
9adfd236a64922d194493d10a9f5585b2e0eb208
30,862
import asyncio async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload FireServiceRota config entry.""" await hass.async_add_executor_job( hass.data[DOMAIN][entry.entry_id].websocket.stop_listener ) unload_ok = all( await asyncio.gather( *...
d6acb96f1f144868923b1cc65e99b4ee901caa56
30,863
def HasPositivePatterns(test_filter): """Returns True if test_filter contains a positive pattern, else False Args: test_filter: test-filter style string """ return bool(len(test_filter) > 0 and test_filter[0] != '-')
9038bf799efbe4008a83d2da0aba89c0197c16a1
30,864
import math def get_lr(lr_init, lr_end, lr_max, total_epochs, warmup_epochs, pretrain_epochs, steps_per_epoch, lr_decay_mode): """ generate learning rate array Args: lr_init(float): init learning rate lr_end(float): end learning rate lr_max(float): max learning rate ...
90091b35126bcf91166c498c396c831c3da1e7f6
30,865
def comptineN2(): """Generate the midi file of the comptine d'un autre été""" mid = MidiFile() trackl = MidiTrack() trackl.name = "Left hand" for i in range(8): trackl = comp_lh1(trackl) trackl = comp_lh1(trackl) trackl = comp_lh2(trackl) trackl = comp_lh2(trackl) ...
a7cd80b7ab483ef68be827c56e5f8b95967d8c08
30,866
from xenserver import tasks from xenserver.tests.helpers import XenServerHelper def xs_helper(monkeypatch): """ Provide a XenServerHelper instance and monkey-patch xenserver.tasks to use sessions from that instance instead of making real API calls. """ xshelper = XenServerHelper() monkeypatch....
d504aa6b651eb3777171187aceea7eb03fa7e46a
30,867
def highest_palindrome_product(digits): """Returns the highest palindrome number resulting from the multiplication of two numbers with the given amount of digits. """ def is_palindrome(target): """Returns True if target (str or int) is a palindrome. """ string = str(target) ...
e509de1c977c6e4ecf9ab8304ef1afe65a447188
30,868
def is_ladder(try_capture, game_state, candidate, ladder_stones=None, recursion_depth=50): """Ladders are played out in reversed roles, one player tries to capture, the other to escape. We determine the ladder status by recursively calling is_ladder in opposite roles, providing suitable captur...
755ed8c007d51034ec2f2a24958c3f4660795007
30,869
def instances(request, compute_id): """ :param request: :return: """ all_host_vms = {} error_messages = [] compute = get_object_or_404(Compute, pk=compute_id) if not request.user.is_superuser: all_user_vms = get_user_instances(request) else: try: all_host...
622336dfb836fbe4918f5d1331149aaaa3467a05
30,870
def seresnet101b_cub(classes=200, **kwargs): """ SE-ResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 200 Number of classification classes. ...
784e915704d244270ddf479eaaf5e279a7db437a
30,871
import os def get_template_dir(format): """ Given a format string return the corresponding standard template directory. """ return os.path.join(os.path.dirname(__file__), 'templates', format)
c204575b877c08700a7c236577016ed7e267f88b
30,872
from pathlib import Path import shutil def dst(request): """Return a real temporary folder path which is unique to each test function invocation. This folder is deleted after the test has finished. """ dst = Path(mkdtemp()).resolve() request.addfinalizer(lambda: shutil.rmtree(str(dst), ignore_erro...
7714ce85fbeedfed00b571d9d2ef31cd6d8898e9
30,873
import string def getSentencesFromReview(reviewContent): """ INPUT: a single review consist of serveral sentences OUTPUT: a list of single sentences """ sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') sentences = sent_detector.tokenize(reviewContent) # split agglomerated ...
2c074fac508994ad44edb0889a799ada22261c3c
30,874
import math def gamma_vector_neutrino(m_med, g_l=0.0): """Function to calculate the neutrino width of a vector mediator :param m_med: mediator mass :type m_med: float :param g_l: lepton coupling, defaults to 0.0 :type g_l: float, optional """ return 3 * g_l**2 / (24 * math.pi) * m_med
ebb0c913beee57cf9cdb605cc356949cea461882
30,875
from typing import Dict from typing import Callable import importlib import sys def load_debugtalk_functions() -> Dict[Text, Callable]: """ load project debugtalk.py module functions debugtalk.py should be located in project root directory. Returns: dict: debugtalk module functions mapping ...
8928d6e53985551e6375b8ff3ea94e86f690845a
30,876
def fifo_cdc(glbl, emesh_i, emesh_o): """ map the packet interfaces to the FIOF interface """ fifo_intf = FIFOBus(size=16, width=len(emesh_i.bits)) @always_comb def rtl_assign(): wr.next = emesh_i.access and not fifo_intf.full rd.next = not fifo_intf.empty and not emesh_i.wait ...
d30445dad18043c63e29e7a79ff3e02dad370964
30,877
def eudora_bong(update, context): #1.2.1 """Show new choice of buttons""" query = update.callback_query bot = context.bot keyboard = [ [InlineKeyboardButton("Yes", callback_data='0'), InlineKeyboardButton("No", callback_data='00')], [InlineKeyboardButton("Back",callback_data='1...
234d4324b384414fd6e2a6f52dbbccc51f0ff738
30,878
import os def get_wildcard_dir(path): """If given path is a dir, make it a wildcard so the JVM will include all JARs in the directory.""" ret = [] if os.path.isdir(path): ret = [(os.path.join(path, "*"))] elif os.path.exists(path): ret = [path] return ret
a2688463c02c9558140d52da567e8744ed775e99
30,879
def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if ...
33b9a4bfd44a70d93ae7b50df870d46765bf0cb7
30,880
def pattern(): """Start a pattern Expected arguments are: name, delay, pause """ if request.args.get('name') is None: return '' pattern = request.args.get('name') delay = float(request.args.get('delay', 0.1)) pause = float(request.args.get('pause', 0.5)) LightsController.start...
13d1ff59dbd4521b157ab28bae75fed30378f8c5
30,881
def smow(t): """ Density of Standard Mean Ocean Water (Pure Water) using EOS 1980. Parameters ---------- t : array_like temperature [℃ (ITS-90)] Returns ------- dens(t) : array_like density [kg m :sup:`3`] Examples -------- >>> # Data from UNESCO Tec...
1f7ae913a1f4c71493d7d94d04bf543e6ffff72b
30,882
from typing import Optional import os def get_asgi_handler(fast_api: FastAPI) -> Optional[Mangum]: """Initialize an AWS Lambda ASGI handler""" if os.getenv("AWS_EXECUTION_ENV"): return Mangum(fast_api, enable_lifespan=False) return None
acc6e37049bed84f58fd692df50016e18c04c714
30,883
from typing import Optional from typing import Tuple import torch def generate_change_image_given_dlatent( dlatent: np.ndarray, generator: networks.Generator, classifier: Optional[MobileNetV1], class_index: int, sindex: int, s_style_min: float, s_style_max: float, style_direction_index...
89ad94dd6f74c175ede27712046d3c46ba43143c
30,884
def count_nodes_of_type_on_path_of_type_to_label(source_name, source_label, target_label, node_label_list, relationship_label_list, node_of_interest_position, debug=False): """ This function will take a source node, look for paths along given node and relationship types to a certain target node, and then count the n...
27809f03b34d4f575d20cddb3780e55381cb6881
30,885
def _build_square(A, B, C, D): """Build a matrix from submatrices A B C D """ return np.vstack(( np.hstack((A, B)), np.hstack((C, D)) ))
510b39f433023339f977a665c055f60abe46a160
30,886
from typing import Sequence from typing import Optional import asyncio import sys import pkg_resources import logging def main( argv: Sequence[str] = sys.argv[1:], loop: Optional[asyncio.AbstractEventLoop] = None ) -> None: """Parse argument and setup main program loop.""" args = docopt( __doc__, ...
418251a015cfce97f028cc0f1be7e9e2f814f0e8
30,887
def DataFrame_to_AsciiDataTable(pandas_data_frame,**options): """Converts a pandas.DataFrame to an AsciiDataTable""" # Set up defaults and pass options defaults={} conversion_options={} for key,value in defaults.items(): conversion_options[key]=value for key,value in options.items(): ...
2864440528324e00e5d7389b5cc2b04aecbb833b
30,888
import logging async def update_product(product_id: int, product_update: schemas.ProductPartialUpdate, db: DatabaseManagerBase = Depends(get_db)): """ Patches a product, this endpoint allows to update single or multiple values of a product - **title**: Title of the product - **description**: Descrip...
a1104864e517df795b58b76020fef1e2dbdfe222
30,889
def TimeDist(times, cutoff, X, e, n1, k): """Translated from Rccp file ConleySE.cpp""" nrow = times.shape[0] assert n1 == nrow assert X.shape[1] == k dmat = np.ones((nrow, nrow)) v1 = np.empty(nrow) v2 = np.empty(nrow) for i in range(nrow): t_diff = times.copy() try: ...
89743d3585306907b1efa4aa3802a79e2627175f
30,890
def generate_fps_from_reaction_products(reaction_smiles, fp_data_configs): """ Generates specified fingerprints for the both reactive and non-reactive substructures of the reactant and product molecules that are the participating in the chemical reaction. """ # Generate the RDKit Mol representations of...
42c4777dcf9c306cd45f9e94bbf18c0d1768c59b
30,891
import torch def count_acc(logits, label): """The function to calculate the . Args: logits: input logits. label: ground truth labels. Return: The output accuracy. """ pred = F.softmax(logits, dim=1).argmax(dim=1) if torch.cuda.is_available(): return (pred == label).ty...
2f34be0cfb52a438c66b36d1d653ecbd72d559e2
30,892
def cuda_argmin(a, axis): """ Location of minimum GPUArray elements. Parameters: a (gpu): GPUArray with the elements to find minimum values. axis (int): The dimension to evaluate through. Returns: gpu: Location of minimum values. Examples: >>> a = cuda_argmin(cuda_give...
25231969616e5c14736757a7b13f058ee218b6aa
30,893
def _process_columns(validated_data, context): """Process the used_columns field of a serializer. Verifies if the column is new or not. If not new, it verifies that is compatible with the columns already existing in the workflow :param validated_data: Object with the parsed column items :param con...
cae79dda5e5121d4684e0995034050e9c6c45598
30,894
def module_of_callable(c): """Find name of module where callable is defined Arguments: c {Callable} -- Callable to inspect Returns: str -- Module name (as for x.__module__ attribute) """ # Ordinal function defined with def or lambda: if type(c).__name__ == 'function': ...
116e46a3e75fcd138e271a3413c62425a9fcec3b
30,895
def lung_seg(input_shape, num_filters=[16,32,128], padding='same') : """Generate CN-Net model to train on CT scan images for lung seg Arbitrary number of input channels and output classes are supported. Arguments: input_shape - (? (number of examples), input image height (pixe...
67cf286122c40e7fa2f87fc1e0a2f57e97777e32
30,896
def set_cluster_status(event, context): """Set the status of a cluster, ie active, inactive, maintainance_mode, etc""" try: cluster_status = event['queryStringParameters']['cluster_status'] except: return { "statusCode": 500, "body": {"message": f'Must provide a stat...
dbb4215c19b8a241d8d353f3567a19eca32190dc
30,897
import numpy def rep(x, n): """ interpolate """ z = numpy.zeros(len(x) * n) for i in range(len(x)): for j in range(n): z[i * n + j] = x[i] return z
97c2ba7e48ff365fb6b4cebcee3f753169cd4670
30,898
def insert_new_datamodel(database: Database, data_model): """Insert a new datamodel in the datamodels collection.""" if "_id" in data_model: del data_model["_id"] data_model["timestamp"] = iso_timestamp() return database.datamodels.insert_one(data_model)
b841e9e08e269cda60d261857bc8826b6a614814
30,899