content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def seqlib_type(cfg): """ Get the type of :py:class:`~enrich2.seqlib.SeqLib` derived object specified by the configuration object. Args: cfg (dict): decoded JSON object Returns: str: The class name of the :py:class:`~seqlib.seqlib.SeqLib` derived object specified by `cfg`...
e48661f00eb6d0cb707fbb96d77b3a9ee3e798d6
42,900
from typing import Any from sys import path import posixpath def fetch_inventory(app: Sphinx, uri: str, inv: Any) -> Any: """Fetch, parse and return an intersphinx inventory file.""" # both *uri* (base URI of the links to generate) and *inv* (actual # location of the inventory file) can be local or remote...
f34f070708d5c775991c17090b7049db3c5a24c5
42,901
def ids(probabilities): """Turn a 1-hot encoding or a probability distribution over the possible characters back into its (most likely) character representation.""" return [str(c) for c in np.argmax(probabilities, 1)]
c51b64311c298f48219e35c67bbd50db43778ad2
42,902
import logging def scrape(start=None, end=None, silent=False): """Returns a pandas DataFrame of school information extracted from the website CollegeData.com, with each row corresponding to a successfully scraped schoolId in the range [start, stop], inclusive, with each column corresponding to labeled...
3dc93b5c043715aa6ef1f6833146e002205ca1a2
42,903
def clean_pdb(traj,neighbour_cutoff=5.0,Nsigma=1): """ pdb_clean """ print("Initial number of atoms ",traj.n_atoms) traj.superpose(traj, 0) atom_indices = pdb_clean_get_atom_indices(traj,neighbour_cutoff=neighbour_cutoff,Nsigma=Nsigma) traj.atom_slice(atom_indices,inplace=True) traj.superpos...
2931996bbf71af0fb31c534f2f5e722d93ff4fb3
42,904
from . import palette_tools from typing import Iterable from typing import Optional from typing import Literal def modules( adata: AnnData, root_milestone: str, milestones: Iterable, layer: Optional[str] = None, module: Literal["early", "late", "all"] = "all", ): """\ Extract mean expressi...
33bfbed8d816d4c3eb7085ba227480b1e1131c6f
42,905
import argparse def parse_args(): """ define and parse command line arguments. """ desc = 'Compare the performance of the C version of libexpat to Rust port.' parser = argparse.ArgumentParser(description=desc) # parser.add_argument('-c', '--clean-all', default=False, # ...
2ded405492b029c97601d4bb7f2befae107843bf
42,906
def largest_pandigital_multiples(): """ This function returns the largest pandigital number which is a multiple of an integer and a sequence of integer (1,2,3,..n) """ largest_number = 0 for i in range(1, 50000): j = 1 number = i*j while len(str(number)) < 9: ...
844ab07aca7d7d44805f893f849f5d63018797f4
42,907
import torch def train(unimodal_files, rep_size, classes, sub_sizes, train_data, valid_data, surrogate, max_labels, batch_size=32, epochs=3, search_iter=3, num_samples=15, epoch_surrogate=50, eta_max=0.001, eta_min=0.000001, Ti=1, Tm=2, temperature_init=10.0, temperature_final=...
51ee41222ee72f8afaad9f2a6ba20b0927219e40
42,908
import os def parentdir(p, n=1): """Return the ancestor of p from n levels up.""" d = p while n: d = os.path.dirname(d) if not d or d == '.': d = os.getcwd() n -= 1 return d
826a52937c491404afaa254acb40827eec36f1b1
42,909
def plot_kdeplot(data, ylabel, title, log_scaling=True): """ Args: data: Dict of list of numbers. """ fig, ax = plt.subplots(1, 1, figsize=(8, 6), dpi=300) plt.xticks(rotation=90) d = [] for k, v in data.items(): for i in v: d.append((k, i)) df = pd.DataFrame...
b41bb8283354f66d53feeecbd406dd3ad4ce11bb
42,910
import requests from bs4 import BeautifulSoup def get_sector_symbol_name_url(): """ 获取期货所对应板块的 URL :return: dict {'能源': '/commodities/energy', '金属': '/commodities/metals', '农业': '/commodities/softs', '商品指数': '/indices/commodities-indices'} """ url = "https://cn.investing.com/commod...
e9cec1bc28cdcc2b90fea5f25b326ad613284470
42,911
def visualize(mesh, vector_field, colors=None, params=None): """ Visualize a mesh and a vector field over it :param mesh: a mesh with n points :param vector_field: (n,3) array :param colors: (n,3) array :param params: params[0] is the length of the quivers :return: """ n = mesh.verti...
672f665563ece4b0356f880df18b573720865a79
42,912
def log__OperationsEvent( ctx, event_type_id, event_payload_dict=None, dbOperationsEvent_child_of=None, timestamp_event=None, ): """ creates a OperationsEvent instance if needed, registers it into the ctx """ # defaults # timestamp overwrite? timestamp_event = timestamp_e...
fed5d85d1ea009b79391f4a74ff6326649119995
42,913
def bare_rate_theta(k, kp, Ntheta, N_z): """ Calculate phonon scattering rate matrix element (scattering rate without thermal factors NQ of NQ+1) vs scattering angle theta ***for a given pair*** of k and k'. k magnitude of initial vector kp magnitude of scattering vector k' Ntheta number ...
1bbc2b4af2ccdb99fd1c6461f000ccd395cd93a2
42,914
def ingest_data(args): """ Ingest and wrangle data from BLS """ conf = get_config() opts = dict(vars(args)) del opts['func'] opts['startyear'] = opts.pop('start_year') or conf.STARTYEAR opts['endyear'] = opts.pop('end_year') or conf.ENDYEAR record = ingest(**opts) return ( ...
93edf5593262526a92be6ea8d4207d6e4454bd92
42,915
import torch def decode(loc, priors, variances=[0.1, 0.2]): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior b...
3394fb7d3e2a7874047689f2211bab6b618b43c2
42,916
def conv2dconv2d( shape_input, pad1, stride1, dilation1, shape_filter1, pad2, stride2, dilation2, shape_filter2, k_split_factor, h_split_factor, dtype, storage_scope="global", ): """ Conv2d -> Conv2d wherein the input activation is defined by its logical N...
3ace02c76aa7b1a0d2af670a646f2b255a8f49dd
42,917
def form(title='', text='', cancel_text='Cancel', inputs=[], buttons=[], style=None, async_=False): """ Display a text input box. Return the given text, or None when cancelled. """ #def accept(): # get_app().layout.focus(ok_button) input_objects = [] button_objects = [] def creat...
5f190323a16e533e20baa13a78301581d083fda1
42,918
def process_file(filepath): """ decides to either call process_openxml or process_ole """ if olefile.isOleFile(filepath): return process_ole(filepath) else: return process_openxml(filepath)
2d434135b42213a92083b6b1cd1bca40c2e6e93d
42,919
def run(*args): """ Create admin using this command. If the email already is registered, just return the email and no need to create new users. """ if args and "email" in args[0]: email = args[0].split("=")[1] admin = User.objects.get_user(email=email) if admin: prin...
8e8b370cf21a8cc51d9ba92a7be26bf05c11b6b7
42,920
import csv def read_data(data_path): """Read real-world trial data from given folder Arguments: data_path (string): path to folder containing measurements.csv and transforms.csv files to be read in Returns: (tuple of arrays): measurements array and transforms array populated with ...
572cdebd0034813ae11b5c8789e1816dd5fe49f9
42,921
def get_rms(y): """ Compute the root mean square of an array, usually a Y array. Parameters ---------- y (vector array): Array of values where the variance needs to be computes. Returns ------- RMS (value): The RMS value. """ return np.sqrt(np.mean(y ** 2.0))
7bd1bd827e1329011c9588818b6e72f3541a6fa6
42,922
def symmetric_phase_corr(I1, I2): """ match two imagery through symmetric phase only correlation (SPOF) also known as Smoothed Coherence Transform (SCOT) Parameters ---------- I1 : numpy.array, size=(m,n), ndim={2,3} array with intensities I2 : numpy.array, size=(m,n), ndim={2,3} ...
6df7f7dd5a5424d2bb7843151af3f8d370c15144
42,923
import os import errno def splitImage (newDir, imgToSplit, imgToSplitDir, oldMatchLocations): """ :type newDir: The name of the new directory. :type imgToSplit: The name of the image that needs to be cropped. :type imgToSplitDir: The name of the directory of the image that needs to be cropped. :type oldMatchLoc...
67963b608e9b2089227f204bd46dd36fd478a659
42,924
def saturated_oxygen(t,s,gsw=False): """Compute oxygen saturation from temperature and salinity Oxygen saturation value is the volume of oxygen gas absorbed from humidity-saturated air at a total pressure of one atmosphere, per unit volume of the liquid at the temperature of measurement (ml/l) """ ...
195b5beb6077e8ede563da188ab37384e1a1136e
42,925
def get_cpe_version(cpe): """ Determine if the given CPE name is following version 2.2 or 2.3 of the standard. :param cpe: CPE name. :type cpe: str :returns: CPE standard version ("2.2" or "2.3"). :rtype: str """ if not isinstance(cpe, basestring): raise TypeError("Expected...
c92299bcbf672ebf9140de663160853c77d9111e
42,926
def PaddingMask(pad=0): """Returns a layer that maps integer sequences to padding masks. The layer expects as input a batch of integer sequences. The layer output is a tensor that marks for each sequence position whether the integer (e.g., a token ID) in that position represents padding -- value `pad` -- versu...
d6f538042e260d38f2d62c4535e36e78cf032f7f
42,927
def read_local_rib(G, curr, prefix, port=0): """ Read local rib and return the next hop of a prefix. Return None if it doesn't have hop. """ # FIXME: This function is duplicate with default_routing_policy() in route.py local_rib = G.node[curr]['rib'] ribs_in = G.node[curr]['adj-ribs-in'] if ...
68d0dfe333a2a9d870261dd23c7dedd79ccba0e3
42,928
def parseXML(user, fname): """ Read 1 XML file via remote client and parse the content. """ data = localFs.read_user_file(user, fname) try: return etree.fromstring(data) except Exception as e: logError('Error parsing file `{}`, for user `{}`: `{}`!'.format(fname, user, e)) ...
46550b9c2f4b294ad8dbc9a819533f18caa64fd5
42,929
from sys import path def get_libraries_names(): """ Returns names of elements, for which are installed packages from PMDK library. """ rpm_packages_path = path.join(PMDK_PATH, 'rpm', SYSTEM_ARCHITECTURE) libraries_names = [elem.split('-')[0] for elem in listdir(rpm_packages_path) ...
2cb12a4ccd7d2f803179fff48493428645bcea9c
42,930
def rfactorial(n: int) -> int: """Recursive factorial function :param n: .. docstring::python >>> from math import factorial >>> rfactorial(1) == factorial(1) True >>> rfactorial(2) == factorial(2) True >>> rfactorial(3) == factorial(3) True ...
c8455ce7d0e7e781c0c745287c2aef3c9a776a48
42,931
import time def vassign(configuration, threads = 0): """ Loads network configuration (user characteristics, network capacity, representations, etc. from a scenario file and solves the ILP. """ # num users N = len(configuration["users"]) # Capacity in terms of pRBs capacity = configuration["nprb"] # ...
dac335283ccb24788baa634fdd7cfa2ff7c5b596
42,932
import re def extract_port_vlan(strValue): """处理show port vlan得到的数据 Args: strValue (str): show port vlan得到的数据 Returns: list: 元组列表。形式如,[(startVlan, endVlan, "U"), [(startVlan, endVlan, "T"),...]。 """ # port 9:2, # vlan(optin): # 1000(U) . # 1251 ~ 1254(T). # 3049 ...
e2aefb9dd5225410637904e6efb67010606243a2
42,933
import os import subprocess import json def construct_version_info(): """Make version info using git. Parameters ---------- None Returns ------- version_info : dict Dictionary containing version information as key-value pairs. """ hera_opm_dir = os.path.dirname(os.path.r...
9b56bb0e85555a6bb0989210d3d840d47cfecd42
42,934
def augment_dim(x3: Array, w: Array) -> Array: """(x,y,z) -> (x,y,z,w)""" d4 = np.expand_dims(w, axis=-1) x4 = np.concatenate((x3, d4), axis=1) assert len(x4) == len(x3) assert x4.shape[1] == 4 return x4
a0b7ff372e2e1698040dde11d60c5c05851d9580
42,935
def shorten_reference_string(reference_string): """Shorten a reference string Returns the minimum necessary string to unambigiously list references: E.g. `Genesis 1, Genesis 2` -> `Genesis 1, 2` """ range_list = parse_reference_string(reference_string) if len(range_list) == 0: return ""...
ad8564e3409b025fd1909d53d38ed291381d793a
42,936
def many2many_dicts(m2mlist): """ Maps objects from one list to the other list and vice versa. Args: m2mlist: list of 2lists [list1i, list2i] where list1i, list2i represent a many to many mapping Returns: (one2two, two2one) : one2two, two2one dictionaries from elements o...
edce4101213941dc08d2b32f4c4624ece02bf79c
42,937
def can_read_members(user: QfcUser, organization: Organization) -> bool: """Return True if the `user` can list members (incl. teams) of `organization`. Return False otherwise.""" if not organization.is_organization: return False return True
d754de80cd242431c57cfaa598a3da2485a0d261
42,938
def total_variation_loss(x, img_size): """ This function computes the total variation loss as an additional loss to the content and style loss from the paper "A Neural Algorithm of Artistic Style". Args: x [numpy.ndarray] generated image with index axis as first dimension. Returns: tota...
f8a46b183f4a09768100190c396dee0b973377aa
42,939
def test_get_annotations_data_returned( pandas_series, coordination_args, monkeypatch ): """Test coordination of annotation retrieval for a given protein.""" def mock_get_anno(*args, **kwargs): annotations = [["NA", "NA", "NA", "NA", "NA"]] return annotations monkeypatch.setattr(get_ge...
b0dab14bc6d2598a72b9f8b62c0a442f4aa3256c
42,940
import codecs import os def _readfile(dirpath, filename): """ Read a complete file and return content as a unicode string, or empty string if file not found """ try: with codecs.open(os.path.join(dirpath, filename), "r", "utf-8") as f: return f.read() except IOError: ...
e4fb96aaccc4a3bc7837c182bf25796c724f3c5b
42,941
def args_readfactors(lst): """Parse the factor arguments.""" factors = dict() if lst: for s in lst: res = s.partition('=') if not res[0]: raise CGBadArg("Factor has no key.") if not res[2]: raise CGBadArg("Factor has no value.") factors[res[0]] = float(res[2]) return factors
abb5e9eee08963bc7971c96cbfc8e7ad2304ccc1
42,942
def Adimensional_to_Asquare(SII,Z_jct,Te): """ Converts a SII with no unit to A**2/Hz """ return (2.0*_kb*Te)*SII/Z_jct
cebed8d98e434b33f2f092b762946c4bb4682d81
42,943
def coordinate_search(mni_coordinates, img_shape, inverse_affine, store_path): """ Return a list of patients whose masks have damage at the specified location. Parameters ---------- coordinates : tuple MNI coordinates (x,y,z) img_shape : tuple Voxel dimensions of the 3D MNI-...
4085d5d093f2d388bd4e056fc12898e4aa8d29ea
42,944
import tempfile def prepare_floppy_image(task, params=None): """Prepares the floppy image for passing the parameters. This method prepares a temporary VFAT filesystem image and adds a file into the image which contains parameters to be passed to the ramdisk. Then this method uploads built image to Sw...
c8702a316fa7e10d2f7a26ac08aa546077ee3cb3
42,945
def array_relative_error(a1, a2): """Return the elementwise absolute difference between the inputs, scaled by the maximum value that occurs in the input.""" denom = max(np.amax(np.absolute(a1)), np.amax(np.absolute(a2))) difference = np.amax(np.absolute(a1 - a2)) if denom < 1e-15: # Both input a...
523460101774f7667c0b0557bbb71133555c75be
42,946
import math def calculate_inverse_log_density(cluster): """Calculate the log of inverse of Density of a cluster. inverse of density-log = log-volume - ln(size) Args: cluster (): Returns: float: inverse of density-log -inf if log-volume = -inf """ inverse_log_...
e6d6a77d078b080cd01d9fce47f9715562132864
42,947
def reload_api_v1_integrator(func): """ Reload a model for each quest """ @wraps(func) def wrapper(*args, **kwargs): global COVID_API_V1, dt, ts COVID_API_V1 = CovidAPIv1() dt, ts = COVID_API_V1.datetime_raw, COVID_API_V1.timestamp return func(*args, **kwargs) return wrap...
7ad7072174c4201adda47ea3d9269006f653a404
42,948
def _prepare_errcheck(): """ This function sets the errcheck attribute of all ctypes wrapped functions to evaluate the _exc_info_from_callback global variable and re-raise any exceptions that might have been raised in callbacks. It also modifies all callback types to automatically wrap the function ...
8b707f3f400354853e53c885018522bf7b98e1e6
42,949
def _es_primo(n: int) -> bool: """ >>> _es_primo(7) True >>> _es_primo(8) False """ for i in range(2, n): if n % i == 0: return False return True
11a45986b68a3e05250a549356f536680ca282d1
42,950
import tarfile import time from contextlib import closing from io import BytesIO from base64 import b64encode def tarball64_factory(): """Provides a factor for creating base64 encoded contents of a tarball. """ def tarball_(input_dir): """Creates a base64 encoded tarball fro input_dir. ...
b9e2a8a1dd526afc597053c7b9d09fb08e89c6ac
42,951
import sys def safe_encode(text, incoming=None, encoding='utf-8', errors='strict'): """ Encodes incoming str/unicode using `encoding`. If incoming is not specified, text is expected to be encoded with current python's default encoding. (`sys.getdefaultencoding`) :param incomin...
a67fd51f114836894e6d16493da5886beb9ff4d2
42,952
from typing import List def study_with_records( complete_study: castor_study.CastorStudy, records: List[castor_record.CastorRecord] ) -> castor_study.CastorStudy: """Creates a CastorStudy with linked records for use in tests.""" return link_study_with_records(complete_study, records)
e1e5ba241b13f036d56425933b84bac47d52da8f
42,953
def expires(plugin): """ Returns the number of seconds after which to expire a pending plugin task Args: plugin (PanoptesPluginInfo): The plugin for which to return the expiry time Returns: int: The number of seconds after which to consider the task expired """ assert isinstanc...
5b004fe6c03cf93f5a25c000f37c29853e0bfa27
42,954
def exp_map(x, r, tangent_point=None): """ Let \(\mathcal{M}\) be a CCM of radius `r`, and \(T_{p}\mathcal{M}\) the tangent plane of the CCM at point \(p\) (`tangent_point`). This function maps a point `x` on the tangent plane to the CCM, using the Riemannian exponential map. :param x: np.array,...
798ee0a7016e84a454d2786b9a58c9bce23b8f62
42,955
def count_media_packages(distribution_artefacts): """ Count media packages in nested list. :param distribution_artefacts: Nested list containing distribution artefacts mapped to media packages and tenants :type distribution_artefacts: dict :return: Amount of media packages :rtype: int """ ...
715fb6e1fc1791051265a21021884a201ff08485
42,956
def get_eos_df(df,order,volpp_name='volpp',epp_name='Epp',with_error=False): """ obtain eos_df for df Args: df (pd.DataFrame): raw data, must have columns [volpp,epp] order (int): polynomial order, must be one of 1,2,3 """ data = [] snamel = df.sname.unique() for sname in snamel: sel = df.sname...
81a2859490edadde316f5e6649145e78b89a0193
42,957
def value_at_risk_1d_nb(returns, cutoff=0.05): """See `empyrical.value_at_risk`.""" returns = returns[~np.isnan(returns)] if len(returns) < 1: return np.nan return np.percentile(returns, 100 * cutoff)
86ab8bf763a79f868a57f5d0fcfe913d5e1fa151
42,958
def read_last_processed(): """Read last processed build number.""" with open("last_processed", "r") as fin: return int(fin.readline())
4362696222c0469c0150632650f07feb0f1a3273
42,959
import os import stat def load_config(filename): """ load config file or all the config files if filename represents a directory. """ s = os.stat(filename).st_mode if stat.S_ISREG(s): return load_one_config(filename) elif stat.S_ISDIR(s): return load_all_config(filename) el...
99748fac819b349304b8ad54e721e5c1fcccf6d2
42,960
def best_model_from_trials(trials): """Extract and return the best model object from trails.""" valid_trial_list = [trial for trial in trials if STATUS_OK == trial['result']['status']] losses = [float(trial['result']['loss']) for trial in valid_trial_list] index_having_minimum_lo...
f5e6e2ce339d418614510cb5645b9e8eff0e7a11
42,961
def get_region_keys(options): """ Extract the region name and credentials, from the options. :param options: options returned from OptionParser().parse_args() :type options: optparse.Values :rtype: k.aws.config.RegionAwsCreds """ region_name = options.region if not region_name: region_name = DEFAULT_REGION_...
a19fecefe11bef8cdc2242595c0bd6d92c4b63c4
42,962
def dirac(t, n, freq, pulse_delay): """ :param t: time sequence (s). :type t: list of floats :param n: time iteration index :type n: int :param freq: frequency of the sinusoid (Hz) :type freq: float :param pulse_delay: number of iteration for the delay of the signal defined in the i...
280234938eed8818666368d66b815ccb967b6dbb
42,963
import pickle import time def video_classify(video_name): """ extract_feature """ logger.info('predict ... ') logger.info(video_name) imgs_path = video_name.replace(".mp4", "").replace("mp4", "frames") pcm_path = video_name.replace(".mp4", ".pcm").replace("mp4", "pcm") # step 1: extra...
68276bcff8dd7d15c645a9d9daa2515486865785
42,964
def make_mag_column_names(instrument, filters): """ Given as input the instrument name and the list of filters needed, this routine generates the list of output header values for the Mirage input file. Parameters ---------- instrument : str 'NIRCam', 'NIRISS', or 'Guider" filte...
e003b1afb3ea2dccc4d7a29971779821e0d67361
42,965
def update(request, tid): """Update a PAF.""" return render(request, 'transaction/update.html', {})
24bac9561c0cad412218191d49eb1dbf5895279f
42,966
def get_student_sessions(): """ This api returns the student's sessions within a time frame. """ student_id = request.json.get('student_id', None) start_time = request.json.get('start_time', None) end_time = request.json.get('end_time', None) start_time_utc = datetime_string_to_utc(start_ti...
7cd360eb77bc91af69598dceb733aebb6d059671
42,967
import platform def get_macos_version(): """returns a tuple with the (major,minor,revision) numbers""" # OS X Yosemite return 10.10, so we will be happy with len(...) == 2, then add 0 for last number try: mac_ver = tuple(int(n) for n in platform.mac_ver()[0].split('.')) assert 2 <= len(mac...
982ae4be358fbfbda02a8b184f51c7f097353a58
42,968
def RunModel(num_parameters, num_training_samples): """ Creates a logistic regression model of size num_parameters by initializing the parameters randomly. Generates ground truth for the model and adds the specified amount of noise to the labels. Then uses gradient decent to train the model and determines the...
6df51d24091589d78199da9212d01cef7ed35ea7
42,969
import torch def DeterminePeople(tensor, classes): """ Input: Tensor of all objects detected on screen Output: Tensor of only 'people' detected on screen """ PersonIndexes = [] #Index of 'person' in tensor CurrentIndex = 0 for t in tensor: cls = int(t[-1]) ObjectDetected = "{0...
37f0875fe4fbb5e636e5f63795b5634072fb80a7
42,970
def get_query_date_index(timeframe="today 5-y"): """Queries Google trends to have a valid index for query results that returned an empty dataframe Args: timeframe (string): Returns: pd.Series: date index of Google trend's interest_over_time() """ # init pytrends with query that ALW...
a23b08f56348d5f6b9d9812b9934bb72bd0b33dc
42,971
def _l2t_section(label, include_section, include_marker): """Helper function converting section labels to text. Assumes _l2t_subterp, _l2t_interp, and _l2t_appendix failed""" if include_marker: marker = u'§ ' else: marker = '' if include_section: # Regulation Text with secti...
01052effeba4f00fb1024d91c954aa6031153973
42,972
def extract_scores_from_outlist_file(outlist): """ :param outlist: :return: """ scores = {'SEED': [], 'FULL': [], 'OTHER': []} outlist_fp = open(outlist, 'r') for line in outlist_fp: if line[0] != '#': line = [x for x in line.strip().split(' ') if x!=''] s...
cdaf7dca6784e6b7c5d9afd31b207d651824371e
42,973
def init_services(service_definitions, client_get, client_authn_factory=None): """ Initiates a set of services :param service_definitions: A dictionary containing service definitions :param client_get: A function that returns different things from the base entity. :param client_authn_factory: A lis...
9e2184e2e0fd755a44c8bdcd74b979793ea36945
42,974
import os def integration_url(scope="session"): """ returns an url """ test_url = os.getenv('TEST_URL_INTEGRATION', 'http://127.0.0.1') port = os.getenv('TEST_PORT_INTEGRATION', 5000) return f"{test_url}:{port}"
7857f252ed82af027c93e991f0b079786ce0f6fc
42,975
import os def list_downloaded_zoo_datasets(base_dir=None): """Returns information about the zoo datasets that have been downloaded. Args: base_dir (None): the base directory to search for downloaded datasets. By default, ``fo.config.dataset_zoo_dir`` is used Returns: a dict m...
a19680fd6fa76cee73ba78dc2770ccfedebacf27
42,976
def get_clients(units=None, cacert=None): """Create a list of clients, one per vault server. :param units: List of IP addresses of vault endpoints :type units: [str, str, ...] :param cacert: Path to CA cert used for vaults api cert. :type cacert: str :returns: List of CharmVaultClients :rty...
b324e54e4468b5d518f3beeba8d916bb50a36509
42,977
def var_to_np(var): """Convenience function to transform `torch.Tensor` to numpy array. Should work both for CPU and GPU.""" return var.cpu().data.numpy()
5c68a839f4d9c4dfbcf3ec7d695ebacf402470ae
42,978
def is_aaai_url(url): """determines whether the server from url @param url : parsed url """ return 'aaai.org' in url.netloc
36a5a71de9c40ad287e44f064aa85053ed13eef9
42,979
import ssl import ctypes def ModExp(a, b, c): """Uses openssl, if available, to do a^b mod c where a,b,c are longs.""" if not _FOUND_SSL: return pow(a, b, c) # convert arbitrary long args to bytes bytes_a = number.LongToBytes(a) bytes_b = number.LongToBytes(b) bytes_c = number.LongToBytes(c) # conv...
2cb6c47b33a0ede55df72cce2e6d960f80bd00bc
42,980
import glob import os def read_batch_of_files(DIR): """Reads in an entire batch of text files as a list of strings""" files = glob.glob(os.path.join(DIR,'*.txt')) texts = [] for f in files: with open(f,'r') as f: texts.append(f.read()) return texts
84068898e918cc6e4a073e6b6a11e7edc5b8cd75
42,981
def get_words_label(words_data: list) -> list: """ 得到当前数据集下的词汇表 :param words_data: 读取到的词语数据 :return: 词汇表 """ # 使用 set 去重 words_label = set({}) for words in words_data: words_label.update(words[1]) res = list(words_label) res.sort() return res
d9ce0701c3c1baff1067d5c96a7730dc42b027f9
42,982
def home(request): """ Controller for the app home page. """ # Get the options for the GLDAS Variables variables = gldas_variables() variable_opts = [] for key in sorted(variables.keys()): variable_opts.append((key, variables[key])) del variables date_opts = available_dates()...
45a4d19c90f0b91c79b72da9e930144408a10992
42,983
import json def add_identifier(request): """ Create an Actor Identifier. Should be an AJAX POST. :param request: Django request. :type request: :class:`django.http.HttpRequest` :returns: :class:`django.http.HttpResponseRedirect` """ if request.method == "POST" and request.is_ajax(): ...
e366c33c1960fe0e505cf427ce4a1c4a42bd6760
42,984
import os def locate_file(filename, default=''): """Locate command path according to OS environment""" for path in ENV_PATH: path = os.path.join(path, filename) if os.path.isfile(path): return path if default != '': return os.path.join(default, filename) else: return filename
82b065747dcf6625e1d72f5588361326bde6e5ee
42,985
def alias_(expression, alias, table=False, dialect=None, quoted=None, **opts): """ Create an Alias expression. Expample: >>> alias_('foo', 'bar').sql() 'foo AS bar' Args: expression (str or Expression): the SQL code strings to parse. If an Expression instance is pass...
2f82256913d610c28ba500773717679e8cbaff8e
42,986
async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" device_registry = await hass.helpers.device_registry.async_get_registry() device = device_registry.async_get(config[CONF_DEVICE_ID]) trigger = (config[CONF_TYPE], config[CONF_SU...
a2b9ee295d648c689f9f6e8d6e55f9d568cd940e
42,987
import functools def forward_errors(func): """ Transforms ``func`` in order to forward any ``grpc.RPCError`` returned by the upstream grpc as the result of the current grpc call. """ @functools.wraps(func) def wrapper(self, request, context, *args, **kwargs): try: return f...
4c33fa2ac5ec0241a5c783de78da7dcb7d9690b9
42,988
import decimal def add_graph_data(graph, dataset, value, cluster=None, horiz_value=None, pval=None, val_min=None, val_max=None): """Add a graph datapoint. Return the newly created GraphData object on success. Raise a LoaderException on error, or if the provided arguments are not valid for the graph. """ if ...
0a3e6be86174433de140cad4d2a2e5870e8a1acf
42,989
def run_sim(systems, trades, edge=0.1, pnl=0.01): """ 模拟多个参数组合的资金曲线,策略的胜率从-edge ~ edge :param systems: 参数数量 :param trades: 交易次数 :param edge: 最优参数的额外胜率 :param pnl: 每次交易盈亏百分比的标准差 :return: 实际最优参数的排名,回测结果最好参数的实际edge """ # 参数1~N的盈利笔数 win_rate_list = 0.5 + np.linspace(-1 * edge, edge,...
67db3b4c9ce90c9316049eb9246c443cc904b2a3
42,990
def verify_ldp_database_session( device, interface=None, expected_interface=None, label_type='input', local_label=None, max_time=60, check_interval=10, ): """Verifies ldp session exists Args: device (obj): device object interface (str): Interface to use in show comma...
4173d56992468542e2d56ffb5be9a97ea341891a
42,991
from typing import Union from pathlib import Path import asyncio import os import aiohttp async def _download_image( url: str, filename: Union[Path, str], semaphore: asyncio.Semaphore, timeout: float ) -> bool: """Download an image from a given url to a given path. Args: url: A url fr...
3e1b456be67573af77079b1c7a93beedfc95e7af
42,992
def get_exptype_counts(exposures, calibs, width=300, height=300, min_border_left=50, min_border_right=50): """ Generate a horizontal bar plot showing the counts for each type of exposure grouped by whether they have FLAVOR='science' or PROGRAM='calib' ARGS: exposures : a table of exposures whic...
ed1378b9749ce188b70933768c54078a270db613
42,993
def map(**kwargs): """Returns a dictionary of the given keyword arguments mapped to their values from the environment. """ d = {} e = lower_dict(environ.copy()) for k, v in kwargs.iteritems(): d[k] = e.get(v) return d
4bd95e2575fa6262c5635fbf805c4dbe1272b01c
42,994
import os import inspect def ReadXml(filename): """读取xml""" def set_to_field(cls): sep = os.sep file_path = inspect.getfile(cls) file_path = file_path[:file_path.rfind(sep)] path = os.path.join(file_path, filename) setattr(cls, '_xml_file', path) xml = Aestat...
677d68e964ef68aa13a0ebc874fc407f71c345a3
42,995
def login_ui(): """ Login to OpenShift Console return: driver (Selenium WebDriver) """ logger.info("Get URL of OCP console") console_url = config.UI_SELENIUM.get("url") browser = config.UI_SELENIUM.get("browser_type") if browser == "chrome": logger.info("chrome browser...
280278c3db9eac33c6f49f85c58c8cd4388f8591
42,996
def hover_over(spell: str, stopcast: bool = False, dismount: bool = True, ) -> str: """ Hover over target. """ macro = f'#showtooltip {spell}\n' if stopcast: macro += '/stopcast\n' if dismount: macro += '/dismount\n' macro += f'/use [@mous...
74586c97b971cbfab169c1777b6c82921015e8ba
42,997
def read_story_file(filename): """read story file, return three lists, one of titles, one of keywords, one of stories""" title_list, kw_list, story_list = [], [], [] with open(filename, 'r') as infile: for line in infile: title, rest = line.strip().split('<EOT>') kw, story = ...
f354618f57eef3f8c842f2802044bc0fea0666f7
42,998
def rotate_points(points, width=600, height=300): """180 degree rotation of points of bbox Parameters ---------- points: list or array Coordinates of top-left, top-right, bottom-left and bottom-right points width, height: int Width/height of perspective transformed module image Return...
ca15ebb21d9c34ba69049831395ce48de44c70a7
42,999