content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def show_cmaps(*args, **kwargs): """ Generate a table of the registered colormaps or the input colormaps categorized by source. Adapted from `this example \ <http://matplotlib.org/stable/gallery/color/colormap_reference.html>`__. Parameters ---------- *args : colormap-spec, optional Col...
c5b8fa3fa3cbb131250be5b813e10c4ff45e0752
50,000
import logging def Run(benchmark_spec): """Measure the boot time for all VMs. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects with individual machine boot times. """ vm = benchmark_spec.vms...
97176dc9e27d9f1f756769bef3966efa5c4e627c
50,001
import os def inputs(n_devices, dataset_name, data_dir=None, input_name=None, n_chunks=0, append_targets=False): """Make Inputs for built-in datasets. Args: n_devices: how many devices to build the inputs for. dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix w...
ab06140ec4a735c0e932a0d90d338a9d7242a1fe
50,002
def ansi_render_approx(s, width = 80, height = 2000): """ Does an approximated render of how a string would look on a vt100 terminal The string can contain ANSI escape sequences, which the :module:`pyte` engine can render so a string such as >>> s = '\x1b[23;08Hi\x1b[23;09H\x1b[23;09Hf\x1b[23;...
c6db54b85780137e75dcc04e43c04ef1f4abe873
50,003
def ycbcr2rgb(ycbcr, *, channel_axis=-1): """YCbCr to RGB color space conversion. Parameters ---------- ycbcr : (..., 3, ...) array_like The image in YCbCr format. By default, the final dimension denotes channels. channel_axis : int, optional This parameter indicates which a...
d5a27283f257c76c683426f5bb307c300756a464
50,004
import requests def confirm_licenses_package(access_token, resource_server, pickup_number): # type: (str, str, str) -> int """ Sends the confirmation to the server that the license package was retrieved. Returns the response code in case of success. """ response = requests.post( resour...
575e524efebcf4e89141362102488b087ca48fbf
50,005
def loss(logits, labels): """Calculates the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float. """ # Convert from sparse integer labels in the range [0, NUM_CL...
5e034179193ebb7343264a837f3dd3aeee151729
50,006
import os def import_data(directory, only_main_ipc): """Imports preprocessed patent files with patent text and ipcs from txt files in given hierarchical directory. Parameters ---------- directory : string Path of hierarchical directory with preprocessed patent txt files Returns ------- result_df : pandas...
5876193a9102bc14d569cf160423aba652af2306
50,007
def get_douban_url(detail_soup): """-""" detail_soup = detail_soup.find('a', title='豆瓣链接') if detail_soup: return detail_soup['href'] return ''
3f4cb56876da722883e3386d7af7ce41726456ac
50,008
import os import io def generate_gitlab_yaml_for_noop(rust_workspace: str) -> str: """Return a string with the Gitlab YAML pipeline config for no-op builds.""" rust_workspace = os.path.abspath(rust_workspace) gitlab_ci_config = load_gitlab_ci_config(rust_workspace) out = io.StringIO() generate_g...
df490acc8b8fcf5a7e00086bfb70c987aa96b645
50,009
import os def all_recording_days(path, day_format): """ Iterates through the provided directory path and returns an array of all day directories that match the provided format. """ dirpath, dirnames, filenames = next(os.walk(path)) return __dirnames_matching_format(dirnames, day_format)
08df38387205257ed79654188f3b52726fb4f0a3
50,010
def truncate_out_cert_raw(origin_raw_str: str): """truncate the original ssl certificate raw str like:\n -----BEGIN CERTIFICATE----- raw_str_data... -----END CERTIFICATE-----\n and split out the raw_str_data""" if not isinstance(origin_raw_str, str) or origin_raw_str == "": raise Excepti...
0513a927ab74ac8d6df4e379319eb3516c2f0c14
50,011
from datetime import datetime def addNewUser(db: Connection, userID: int) -> bool: """ Add new user to database :param db: database object instance :param userID: User ID :return: Boolean True if no error """ if db is None: return False now: datetime = datetime.utcnow() cur...
13ac827c703a30a96d416850b5380c2e89592a96
50,012
def dv_dlogdp(dp, n, gm, gsd): """The volume weighted PDF of a lognormal distribution as calculated using equation 8.20 from Seinfeld and Pandis. .. math:: n_V^o(log D_p)=log(10)*D_p n_V(D_p) Parameters ---------- dp : float or array of floats Particle diameter in microns. ...
88617ab744e86ef8a6d2b3b589c8620e87b80e61
50,013
def cmp_char(a, b): """Returns '<', '=', '>' depending on whether a < b, a = b, or a > b Examples -------- >>> from misc_utils import cmp_char >>> cmp_char(1, 2) '<' >>> print('%d %s %d' % (1, cmp_char(1,2), 2)) 1 < 2 Parameters ---------- a Value to be compare...
7e8183564f888df3cce65f2bbbeb659aec43928c
50,014
def retrieve_context_topology_node_owned_node_edge_point_available_capacity_bandwidth_profile_committed_burst_size_committed_burst_size(uuid, node_uuid, owned_node_edge_point_uuid): # noqa: E501 """Retrieve committed-burst-size Retrieve operation of resource: committed-burst-size # noqa: E501 :param uuid...
f299772ba3cab3ca0d508971d45d1ba0a5272b6e
50,015
def get_command_name(cmd, default=''): """Extracts command name.""" # Check if command object exists. # Return the expected name property or replace with default. if cmd: return cmd.name return default
f77a73d1ff24ec74b1c7cf10f89c45fab41fed20
50,016
import os def ref_ad_factory(path_to_refs): """ Read the reference file. Parameters ---------- path_to_refs : pytest.fixture Fixture containing the root path to the reference files. Returns ------- function : function that loads the reference file. """ def _reference...
451cc1603fa2390ff4e8487e20604629356d3d1a
50,017
def _getText(node): """ Obtains the text from the node provided. @param node Node to obtain the text from. @retval Text from the node provided. """ return " ".join(child.data.strip() for child in node.childNodes if child.nodeType == child.TEXT_NODE)
ebd23a28073104e81cd7a1d38323ac2a1c49355b
50,018
from typing import Union import sqlite3 def make_connection_plus_from(conn: Union[sqlite3.Connection, ConnectionPlus] ) -> ConnectionPlus: """ Makes a ConnectionPlus connection object out of a given argument. If the given connection is already a ConnectionPlus, then it is re...
b66ce558d9515d57ecfee066900a5b3150d90c81
50,019
from ._fine_cal import read_fine_calibration def _update_sensor_geometry(info, fine_cal, ignore_ref): """Replace sensor geometry information and reorder cal_chs.""" logger.info(' Using fine calibration %s' % op.basename(fine_cal)) fine_cal = read_fine_calibration(fine_cal) # filename -> dict ch_na...
7b22f9b42adff0f73a2a8b5fa71a9edbcf260eb2
50,020
def polygonOffsetWithMinimumDistanceToPoint(point, polygon, perpendicular=False): """Return the offset from the polygon start where the distance to the point is minimal""" return polygonOffsetAndDistanceToPoint(point, polygon, perpendicular)[0]
b84ca6bf40563c5663490d3c28806ee3b3226500
50,021
def get_package_versions(sha1, os_type, package_versions=None): """ Will retrieve the package versions for the given sha1 and os_type from gitbuilder. Optionally, a package_versions dict can be provided from previous calls to this function to avoid calling gitbuilder for information we've alrea...
24cdcf0641fd0a0bd16c39e7a79c0d2c69f6692f
50,022
from typing import List import os def get_configs_from_model_files(state: 'State', model_root = None, ignore_files: list = None) -> List[dict]: """ Assumes that all configs are defined within the model files: models/m_{name}.py and that each model file has a get_config() option which returns an a...
98d3026fe88b0f13c067071da948f36dbdebfb66
50,023
def get_arrdepth(arr): """ USAGE ----- arr_depths = get_arrdepth(arr) Determine number of nested levels in each element of an array of arrays of arrays... (or other array-like objects). """ arr = np.array(arr) # Make sure first level is an array. all_nlevs = [] for i in ran...
4d06fdf10f6b3bfb590da86c6627b546db29dbea
50,024
def get_ocid(prefix, tenderID): """greates unique contracting identifier""" return "{}-{}".format(prefix, tenderID)
309e8a07dcdf787fd2dd6a41abb4f4d26f1baa63
50,025
import hashlib def md5(fileName): """Compute md5 hash of the specified file""" m = hashlib.md5() try: fd = open(fileName,"rb") except IOError: print("Reading file has problem:", filename) return x = fd.read() fd.close() m.update(x) return m.hexdigest()
a502ada56c934e7b66155b261a23a283e9b65bf7
50,026
def Kernel(x,f,theta): """ build square kernel matrix for inputs x with kernel function f and parameters theta Inputs ------- x : vector values to evaluate the kenrel function at, pairwise f: kernel function function that accepts inputs as (x1,x2,theta) theta: vector ...
e0bb80f2c90e72bdbf2405f4d96dfaa0f6d3f03c
50,027
from typing import Union def drop_duplicated_indices(df: Union[pd.Series, pd.DataFrame]) -> Union[pd.Series, pd.DataFrame]: """If one concatenates dataframes there might be duplicated indices. This can lead to problems, e.g., in interpolation steps. One easy solution can be to just drop the duplicated row...
5f14965e5cbb7fa859db74588b5880d1b24e8bf3
50,028
import json def report_response(params, runner=None, cache=DEFAULT_CACHE): """ This frontend helper function is meant to be used in your request-processing code to handle all AJAX responses to the Blingalytics JavaScript frontend. In its most basic usage, you just pass in the request's GET parame...
7568ff0e80afcea319ceace1c9f10f807903ce3e
50,029
def median( y, mask): """Return the median of the array y, ignoring masked elements. Parameters ----------- y : ndarray array of values mask : ndarray array of (int32) ones or zeros (0 indicates a good value) Returns -------- med...
e5ff3c249f7246caa94b61aa3586c1e79b01f8fa
50,030
import torch import copy def train_model(x_train, y_train_e, x_val, y_val_e, num_epochs, learning_rate): """ Train the model using the data given, along with the parameters given. @param x_train is the training dataset. @param y_train_e is an np.array of the training labels. @param x_va...
96c8675816178362100082d5911b977ae192d14e
50,031
def polynomial(a0,a1,a2,a3,a4,x): """ Up to x4 """ return a0 + x*(a1+x*(a2+x*(a3+x*a4)))
81ad200df9b6e9d7cd00e1ced8bae8dacec303b1
50,032
def time_round(time, delta, epoch=None): """From https://stackoverflow.com/a/57877961/13775459""" mod = time_mod(time, delta, epoch) if mod < (delta / 2): return time - mod return time + (delta - mod)
a6d6a7e8beb60013c01d0512f5dc0ccf7c2fa0b2
50,033
def resnet(info, depth=28, width=1): """Resnets of varying width and depth.""" N = (depth - 4) // 6 inputs = Input(shape=info.features['image'].shape) x = Conv2D(16, (3, 3), padding='same')(inputs) x = BatchNormalization()(x) x = Activation('relu')(x) for _ in range(N): x = _residu...
7d8e0fc707549d39010db3f9cad2e92496b52d2e
50,034
import hashlib def get_str_md5(content): """ Calculate the MD5 for the str file :param content: :return: """ m = hashlib.md5(content) # 创建md5对象 return m.hexdigest()
c0e864288d8d6af2fe31b5cb5afe54bfe83e2fb3
50,035
def cv_personal_info(request): """Add information about person to CV requests""" return {'cv_personal_info': CV_PERSONAL_INFO}
8f7aa458747dcffc20247926b01ac36f536e6bd9
50,036
def make_test(row): """ Generate a test method """ def row_test(self): actual = row.get("_actual") if actual in ("P", "F"): if actual == "P": self.assertMeansTest("eligible", row) else: self.assertMeansTest("ineligible", row) ...
083117f44687c56a7a33cfa74776baea6b40048c
50,037
def replace_german_umlaute(unicode_string): """.""" utf8_string = unicode_string.encode("utf-8") print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") print("{}".format(utf8_string)) print(u"{}".format(utf8_string)) print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") for k in umlaute_dict.keys(): utf8_string ...
f1d88056b3166443a6cc4989d3b4f4106573cd65
50,038
import os import uuid import json def audio_conversion(): """Convert audio file to MP3 and update metadata on mp3. :return: Converted audio """ # For whatever reason temporary file was workable with subprocess. tmp_path = os.path.join("/tmp", "audio_" + uuid.uuid4().hex + ".mp3") try: ...
634706fef38f13ccf4d66e75ea5b954ac004f70f
50,039
import posixpath def populate(contents_mgr): """ Populate a test directory with a ContentsManager. """ dirs_nbs = [ ('', 'inroot.ipynb'), ('Directory with spaces in', 'inspace.ipynb'), ('unicodé', 'innonascii.ipynb'), ('foo', 'a.ipynb'), ('foo', 'name with space...
d2d3479e36c102d8d7d98819d2aeb5b40d1cca4c
50,040
def running_mean(clazz=None, batch_size=50, step_size=10, dim=None): """The :func:`running_mean` decorator is used to add a :class:`.RunningMean` to the :class:`.MetricTree`. If the inner class is not a :class:`.MetricTree` then one will be created. The :class:`.RunningMean` will be wrapped in a :class:`.To...
1dd99ce8a33bc66e3b69da5611bb6e405cb4b360
50,041
def min_value(state, depth, max_depth, alpha, beta, transposition_table): """ Acting as the minimizer for the min_max search with alpha beta """ state.depth = depth # checking entry in transposition table table_check = transposition_table.table_lookup(state) if(len(table_check) > 0): ...
ee28fcb8a18cf2aff60fdea3f963ce8a3404f9a0
50,042
def api_client(cluster_name: str, api_class: str) -> k8s.client.apis: """ Creates and returns a python k8s api client of the specified class and pointing to the specified cluster. Usage: Use this function whenever you want a python k8s api client. Python k8s api documentation: https://github.com/kubernetes-clie...
c9c857093dad701fa9a3a745da2c403137191e2d
50,043
def plot_intensity(tc, ax=None, figsize=(10,5), fontsize=15): """ Plot the intensity of the given TC. Parameters ---------- tc: TC A single TC. ax: Axe Axe for plotting figsize: tuple Figure size of (12, 6) fontsize: int Size of the font (title, label and...
6a76018f29de6e08b0715fe67bd94c30ee10e28e
50,044
import PIL.Image as Image def fig_2_Image(fig): """ Ref: https://panjinquan.blog.csdn.net/article/details/104179723 fig = plt.figure() image = fig2data(fig) @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a...
6dda76db1c976005bca0814fd512d747790ff45d
50,045
import math def binary_sigmoid(n: float, lmbda: float = 1.0) -> float: """ Binary Sigmoidal (Unipolar Continuous) Activation Function """ return 1 / (1 + (math.exp(-lmbda * n)))
dec3380311c5bb1130e8455254d55b44ab416d21
50,046
from .collections import store def user_is_valid(data): """user error handling""" resp = "The username you provided already exists" body = store.get_by_field(key='username', value=data.get('username')) is not None errors = {} if store.get_by_field(key='email', value=data.get('email')) is not None...
185e290afe74492d190c4adb336629a38c06c377
50,047
def create_new_ap_hostname(country_code, ap_macs: list(), mgmt_subnet: str) -> dict: """ "WAP<COUNTRY_CODE><2nd_OCTET>3rd_OCTET>_<ascending index starting from 001>" start index will be the lowest management IP address Args: mgmt_subnet: IP network portion (without prefix) ap_macs: list...
ad10091981a3f404d1e5805049e3bcf6e6d18899
50,048
def ldns_tsig_keydata_clone(*args): """LDNS buffer.""" return _ldns.ldns_tsig_keydata_clone(*args)
ccda3684f6611333fe0db77c4eacb325f6c6fa0a
50,049
def log_variance(locations): """ Compute location variance feature from location data. Logarithm of combined variance of latitude and longitude values. :param locations: dataframe of location data with columns latitude and longitude. :return: location variance. """ if len(locations) < 2: ...
d0fbf61ad8154d2ebf4f992682ebfcb1cc77472c
50,050
def client(app): """ Fixture to emulate client""" return app.test_client()
555e43501347e257ea9b0eeb95ba80e99e1a6ce9
50,051
def first_discoverable(targets, cat, kwargs): """A target chooser: the first target for which discover() succeeds This may be useful where some drivers are not importable, or some sources can be available only sometimes. """ for t in targets: try: if cat: s = cat...
592d738d943578929d69d4d98ca98cdda16f96b9
50,052
def _centralize(shape): """Create a shape which is just like the input, but aligned to origin. The origin is (0; 0) in 2D case. The input shape stays unchanged. It's expected to be a numpy.array. """ centroid = shape.mean(0) return shape - centroid
0c65ac55d3dbad9d540d73e2480c0d71ad703302
50,053
import torch import random def evaluate_model(Net, seeds, mini_batch_size=100, optimizer = optim.Adam, criterion = nn.CrossEntropyLoss(), n_epochs=40, eta = 1e-3, lambda_l2 = 0, alpha=0.5, beta=0.5, plot=True,statistics = True ,rotate = False,translate=False,swap_channel = False, ...
7a7e4438eaf81337894cd10454254e368060fb27
50,054
def factory(_context, request): """Return a AuthCookieService instance for the passed context and request.""" cookie = SignedCookieProfile( # This value is set in `h.auth` at the moment secret=request.registry.settings["h_auth_cookie_secret"], salt="authsanity", cookie_name="aut...
1d8191a1202c9493af47d947b5f95c7fc471624d
50,055
def get_fcn_resnet50_model_instance(num_classes): """ This method gets an instance of FCN-Resnet-50 model given num_classes. 0 < num_classes <= 21 :param num_classes: number of classes :return: instance of FCN-Resnet-50 model. """ # Checks constraint on num_classes if num_classes <= 0 ...
594c1f34822ba648a35392bcb4fe8e07bb7bb514
50,056
def projC(gamma,q): """return the KL projection on the column constrints """ return np.multiply(gamma,q/np.maximum(np.sum(gamma,axis=0),1e-10))
9199a9d746a4d1cb1cfb9c074f333289ac9365b1
50,057
def read_file(file_name, package_level=True): """Get file content given file path. :param: [package_level] - Wheather the file is in/out side the `gmail_api_wrapper` package """ file_path = get_absolute_path(file_name, package_level=package_level) with open(file_path) as file_descriptor: ...
2feac46a49acb7a804b7527512e1dfd9d7b98c04
50,058
def fit_vfa_nonlinear(s, fa_rad, tr): """Return T1 based on VFA signals using NLLS fitting. Parameters ---------- s: ndarray 1D array of signals. fa_rad: ndarray 1D array of flip angles (rad). tr: float Repetition time (s). Returns ---...
f8fccfd1e1e61a2da1c8be93eef6f241e8370a7f
50,059
import random def GenerateRandomName(): """Generates a random string. Returns: The returned string will be 12 characters long and will begin with a lowercase letter followed by 10 characters drawn from the set [-a-z0-9] and finally a character drawn from the set [a-z0-9]. """ buf = cStringIO.Stri...
96810577d5c12f97bf3854baee1ff66484b71782
50,060
from saq.database import get_db_connection import logging def get_restoration_targets(message_ids): """Given a list of message-ids, return a list of tuples of (message_id, recipient) suitable for the unremediate_emails command. The values are discovered by querying the remediation table in the data...
b6121a0c3daa39139ebda23930203a2a4775ac33
50,061
def _check_fit_params(x_data, fit_params, indices=None): """Check and validate the parameters passed during ``fit``.""" fit_params_validated = {} for param_key, param_value in fit_params.items(): if (not _is_arraylike(param_value) or _num_samples(param_value) != _num_samples(x_data))...
bcf7535af55662130b559b04970fabaa5b7e1ccf
50,062
def filter_wrong_poses( skel_ours_2d, skel_ours_3d, d_thresh=Conf.get().optimize_path.head_ank_dthresh, l_torso_thresh=Conf.get().optimize_path.torso_length_thresh, show=False): """Attempts to filter poses, where ankles are too close to the head. Remember, up is -y, so lower y coordinate means "higher" ...
ba4540a05992871c375513d452cafac10ccb1af1
50,063
def read_binary_file( bbseries, comps, station_names=None, wave_type=None, file_type=None, units="g" ): """ read all stations into a list of waveforms :param input_path: :param comp: :param station_names: :param wave_type: :param file_type: :return: [(waveform_acc, waveform_vel]) ...
142b8cef3fae056b26dd2ee81f87b4b37a10a852
50,064
def is_html_needed(user_agent): """ Basing on `user_agent`, return whether it needs HTML or ANSI """ plaintext_clients = ['curl', 'wget', 'fetch', 'httpie', 'lwp-request', 'python-requests'] if any([x in user_agent for x in plaintext_clients]): return False return True
67a75c34dca4672534058729875dc5ee98696590
50,065
def open_hansen_biomass_tile(tile_id, version): """ Open single tile from the Hansen 2020 dataset and then massage it into a format for use by the rest of the routines. Parameters ---------- tile_id : str The latitude/longitude of the northwest corner of the tile (e.g. 50N_130W) ver...
5f6bb87a90f9506af9e90d29ec11fda2f7c6b8c3
50,066
def process_entry(base_url, i, entry): """ Given a base URL, an index, and an entry dictionary, ensure that the entry is valid, and return an Apache RedirectMatch directive string. """ source = '' replacement = '' # Check entry data type if type(entry) is not dict: raise ValueError('Entry %d is n...
1dd3074fbca9d7c1f646ae348ceb992c027bb1fb
50,067
import unicodedata def _normalize(string_to_convert, normalize=False): """ a utility method for normalizing string """ try: return unicodedata.normalize('NFC', string_to_convert) if normalize else string_to_convert except TypeError: return string_to_convert
2c4edc31741d8b87165996339c8b9231f5ed6aa5
50,068
def pipe(*args, **kwargs): """An aggregator that eagerly sums fields of items in a stream. Note that this pipe is not lazy if `group_key` is specified. Args: items (Iter[dict]): The source. kwargs (dict): The keyword arguments passed to the wrapper Kwargs: conf (dict): The pipe...
dd0b6433793d40c1710cdf2ce72ff627af623279
50,069
def __xor_bytes(bytes1, bytes2): """xor of a list of bytes""" assert len(bytes1) == len(bytes2) return [bytes1[i] ^ bytes2[i] for i in range(len(bytes1))]
0b576cd877839cd2191fee57f6b5f270a37726de
50,070
def plugins_help() -> str: """ Gets the help text for the 'plugins' sub-command. """ return PluginsOptions.get_configured_parser(prog="wai-annotations plugins").format_help()
7d88e2e397fe6d1ddf6298901f7d7fece9a1e91b
50,071
def report_issue() -> str: # pragma: no cover """Used when errors are really f*cked up""" return ('Report an issue please? ' '( https://github.com/agamm/comeback/issues )')
9b6015a12f252341f63bb988d2bb5b46c3c66318
50,072
def get_distro(): """ factory to return the right Distro object """ return distro_instance
bd188dcb27c8f541988a3209453a92cfca34b59d
50,073
def compute_coefficients(temperature_resistance_pairs): """Computes Steinhart-Hart model coefficients. Equations taken from https://www.dataloggerinc.com/wp-content/uploads/2016/10/self-calibrate-thermistors.pdf. Args: temperature_resistance_pairs: sequence of three (temperature, resistance) tuples....
15e7a68281eb5a9b879c1bdd82522630b2d25846
50,074
from datetime import datetime import functools def timed_cache(**timed_cache_kwargs): """LRU cache decorator with timeout. Parameters ---------- days: int seconds: int microseconds: int milliseconds: int minutes: int hours: int weeks: int maxsise: int [default: 128] ty...
0cdad8fcb7f76303b73e883d71e0c055c136f453
50,075
def _get_orthologous_imodulons(M1, M2, method, cutoff): """ Given two M matrices, returns the dot graph and name links of the various connected ICA components Parameters ---------- M1 : ~pandas.DataFrame M matrix from the first organism M2 : ~pandas.DataFrame M matrix from t...
85aa4ba43b74b6b102f062a6aa131e7596ef9b69
50,076
def cont6(): """ 1 cluster (2 shared contours) with 2 subclusters (those from <cont4>). Contains 3 minima (subclusters contain 1 and 2, resp.). """ cont_min = [ cncc(5, (6.00, 3.00), 0.2, (1, 1)), cncc(2, (7.00, 4.00), 0.1, (4, 1), rmin=0.15), cncc(2, (6.25, 3.25), 0.3, (6, 1...
4ce2406b6bb6eb26341b64e853b3451003410a53
50,077
def _get_raw_parts_helper(response, http_response_type): """Helper for _get_raw_parts Assuming this body is multipart, return the iterator or parts. If parts are application/http use http_response_type or HttpClientTransportResponse as enveloppe. """ body_as_bytes = response.body() # In or...
755b33a9141e9ec62170f50e278f72fa20c7de2b
50,078
def mom2mag_nm(mom): """Converts moment to magnitude - newtonmetre""" return (np.log10(mom) - 9.05) / 1.5
83da75adb534f6e3e7ed6afa067c111f0688344b
50,079
def mergeWindows(data, dimOrder, maxWindowSize, overlapPercent, batchSize, transform, progressCallback=None): """ Generates sliding windows for the specified dataset and applies the specified transformation function to each window. Where multiple overlapping windows include an element of the input datas...
3775c7c4e5a49921af8ac8cd8a2b7cb37c5e3385
50,080
def UDPOS(*args, **kwargs): """ Universal Dependencies English Web Treebank Separately returns the training and test dataset Arguments: root: Directory where the datasets are saved. Default: ".data" Examples: >>> from torchtext.datasets.raw import UDPOS >>> train_dataset, vali...
cea4db2bba5e97fd6ecb34c4ceda89ee899e0c71
50,081
def _load_global_signal(confounds_raw, global_signal): """Load the regressors derived from the global signal.""" global_params = _add_suffix(["global_signal"], global_signal) _check_params(confounds_raw, global_params) return confounds_raw[global_params]
e904077af687083f0e2135744172a36b4ae38a41
50,082
from bifrostrpc.typing import DictTypeSpec, ScalarTypeSpec from typing import Callable from typing import Any def DictTester( value_test: Callable[[Any], bool], ) -> Callable[[Any], bool]: """ Return a callable that tests whether a given TypeSpec is a DictTypeSpec with the expected valueSpec. It ...
b7edca7701bce11b155c9c351a5eb0b5a8241810
50,083
def isHarmonic(field, sphericalMask, shellMask): """Checks if the extrema of the field are in the shell.""" fullField = np.multiply(field, sphericalMask) # [T] reducedField = np.multiply(field, shellMask) if int(ptpPPM(fullField)) > int(ptpPPM(reducedField)): print( "ptpPPM of field...
66170697c6a468e31d7badbd0a4cca277c74ca6c
50,084
def _as_list(arr): """Make sure input is a list of mxnet NDArray""" if not isinstance(arr, (list, tuple)): return [arr] return arr
be489c8d1be314c8b34df25546228f855c223b57
50,085
import random def random_number(): """Generate a random string of fixed length """ return random.randint(0, 9999)
f3d448b3118d82fd88946ddddadaa1941ffd7d41
50,086
def eh_posicao(pos): """ Verifica se um determinado valor e uma posicao valida Parametros: pos (universal): Possivel posicao. Retorna: (bool): True se for numero valido e False se nao for. """ return False if type(pos) != int or pos < 1 or pos > 9 else True
af0f73f8e4513a679b34795d7be43c26bbc6b586
50,087
def get_channel_row(*args, **kwargs): """ 获取信息 :param args: :param kwargs: :return: None/object """ return db_instance.get_row(Channel, *args, **kwargs)
40c66c1c633a92f9cad6d60f01206e82020483cd
50,088
import os def parse(filepath): """ Simple method for fully specified path which split the string into three parts: folders, filename without suffix and suffix e.g. for ./myfolder/myfile.ext method returns ./myfolder/, myfile, ext :param filepath: str any form of os.path (relative or absolu...
66fc5f1228361962687116d8c921e859ef03401f
50,089
def calc_hole(first_map, second_map, min_size=419430400): """ Calcul hole between 2 mappings. format of a Mapping Tuple: 2 integers : - physical_address - mapping_size formated as following ( physical_address, mapping_size ) Input : - first_map :...
c035d23eff6e73295d0421e1cfb63f992caf9673
50,090
def eval_ctx(*args, **kwargs) -> EmbeddingCtx: """Get the ``EmbeddingCtx`` with the ``PreprocessMode.EVAL`` mode.""" return EmbeddingCtx(PreprocessMode.EVAL, *args, **kwargs)
150847a06ae737deee18b45fd549c70b09d67232
50,091
def Snu_rescale_axion(ma, ga, ma_ref, ga_ref, source_input=default_source_input): """ Computes the rescale factor for different axion parameters. Parameters ---------- ma : axion mass [eV] ga : axion-photon coupling [GeV^-1] ma_ref : reference axion mass [eV] ga_ref : reference axion-ph...
63b2fa358c2eca3fcc0d8d6ac989410fe2893380
50,092
import json def _generate_screen_id_and_captions_pair(json_file_path): """Generates pair of screen id and MTurk labels for each screen.""" with tf.gfile.GFile(json_file_path) as f: screens = json.load(f) return list(screens.items())
041ea2f4f41b8a37d4877307341b6facbaffdc3f
50,093
def to_image(X, filters=2, n=None): """ 1x1 convolution layer to convert output to an image """ output = weighted_conv2d(inputs=X, filters=filters, kernel_size=[1, 1], activation=None, #tf.nn.tanh, ...
e8330805e42e131ffa183e77dac2ee8c8c763206
50,094
def summarize_ranges(addrlist): """ Convert a list like [1,2,3,5] to ["1-3", "5"], but with IP addresses """ ranges = [] start = None prev_range_class = None for addr in addrlist: if start is None: start = addr.ip end = addr.ip prev_range_class = addr.rang...
5c4183099b4be31ac73a80cba802cc2e942dc25e
50,095
def sphankel1(n, kr): """Spherical Hankel (first kind) of order n at kr. Parameters ---------- n : array_like Order kr: array_like Argument Returns ------- hn1 : complex float Spherical Hankel function hn (first kind) """ n, kr = scalar_broadcast_match(n...
b0951a744f50fa86ad419fecc7d06100dc53e309
50,096
import test def init_news_overview() -> OverviewDatabase: """ init the news overview Will store news overview -- number of hits, corresponding colour and other info :return: database.Database object """ if test() == 0: raise DatabaseError res = OverviewDatabase() init_db("publ...
a1f9b48915102b97c50e2a4b4a5cb784f20ba701
50,097
def get_obs_route(value): """ obs-route = obs-domain-list ":" obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain]) Returns an obs-route token with the appropriate sub-tokens (that is, there is no obs-domain-list in the parse tree). """ obs_route = ObsRoute() whi...
d1c319712dbf64c4aa48d70e8fc916dee4c3276d
50,098
def del_gloabls_var(key): """删除值""" try: GLOBALS_DICT.pop(key) return True except KeyError: return "Not Found"
5acb5ef300cceb2fe7ebe78e5b6dd2f0015267a0
50,099