content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def core_rotd(sym_factor, flux_file_name, stoich): """ Writes the string that defines the `Core` section for a variational reaction-coordinate transition-state theory model of a transition state for a MESS input file by formatting input information into strings a filling Mako template. ...
6213ec9da79340738142ccd76ffbab3d30470d36
29,200
def last_gen(genobj): """ 迭代一个生成器对象,返回最后一个元素 :param genobj: :return: """ for i in genobj: last_e = i return last_e
04e7cc57bf6406832cacaa04aa01b2ec877307df
29,201
def get_section_name_mapping(lattice): """.""" lat = lattice[:] section_map = ['' for i in range(len(lat))] # find where the nomenclature starts counting and shift the lattice: start = _pyaccel.lattice.find_indices(lat, 'fam_name', 'start')[0] b1 = _pyaccel.lattice.find_indices(lat, 'fam_name',...
52a8352f6e8747ee6f6f9a1c85b34f551fd04dad
29,202
import math def from_quaternion(quaternions, name=None): """Converts quaternions to Euler angles. Args: quaternions: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "euler_from_quaternion". Returns: ...
4f00f734599699aaadf5c66a1f8e1457321bd689
29,203
def is_polygonal(n, num): """ Predicate for if num is a n-gonal number. Works for all n >= 3 and num >= 1. """ if n < 3 or num < 1: return False t = int((sqrt(8*num*(n-2) + (n-4)**2) + (n-4)) / (2 * (n-2))) return poly(n, t) == num
f3abde644544c05da17faeb9891916428b265602
29,204
def map2pix(geoTransform, x, y): """ transform map coordinates to local image coordinates Parameters ---------- geoTransform : tuple, size=(6,1) georeference transform of an image. x : np.array, size=(m), ndim={1,2,3}, dtype=float horizontal map coordinate. y : np.array, size=(m...
bd044a4ec6d1b97f304086c21d18485b70afbee2
29,205
def fk_plaintext_dict_from_db_record(session,element,db_record,excluded=None): """Return a dictionary of <name>:<value> for any <name>_Id that is a foreign key in the <element> table, excluding any foreign key in the list <excluded>""" fk_dict = {} fk_df = dbr.get_foreign_key_df(session,element) if ...
8edb1a4a30e7d1cb712690d5a0b01673b73ca4b5
29,206
def checkmarkers(tubemarker, tubechecker): """Check for required markers in each tube The tube-specific markers that are to be merged are desceribed in constants.py Args: tubemarker: required markers for that tube tubechecker: markers in the given tube that needs to be validated Retu...
5004a9158db93164dbcf024d6e06d832bf35cf30
29,207
def _in_Kexp(z): """ Returns true if z is in the exponential cone """ alpha, beta, delta = z if ((beta > 0) and (delta > 0) and (np.log(delta) >= np.log(beta) + alpha / beta)) \ or ((alpha <= 0) and (np.abs(beta) < 1e-12) and (delta >= 0)): return True else: retur...
19e57dbb10e420ead5ce02e9801cd1e087f3afad
29,208
def split_blocks(bytestring, block_size): """Splits bytestring in block_size-sized blocks. Raises an error if len(string) % blocksize != 0. """ if block_size == 1: return map(b_chr, bytearray(bytestring)) rest_size = len(bytestring) % block_size if rest_size: raise ValueError(...
f85caf419de35c75d5d920d531519b2f641cc7b3
29,209
def put_newest_oldest_files(f, author, path_earliest_latest, n_files, is_newest): """Write a report of files that were least recently changed by `author` (`is_newest` is False), or was first most least recently changed by `author` in current revision. f: file handle to write to path_earlies...
19aa6a9f45d41f04d72b5699ac1599a2b8c2aa28
29,210
def pearson_correlation(trajectory_data): """ Calculates the Pearson Correlation Matrix for node pairs Usage: node_correlation, node_variance, node_average = pearson_correlation(trajectory_data) Arguments: trajectory_data: multidimensional numpy array; first index (rows) correspond to ti...
c12f4a4fd0959424e6ccfd66c55046a0bcc93cdb
29,211
import random def dglstep(q,maxf=10000,replfunc=None): """returns: next dgl step, function that was replaced, with what""" #choose rnd func to replace allfunc=q.listfunc() f=random.choice(list(allfunc)) par=q.findparamforfunc(f) #choose replacement function global pdgl r=None shallreplace=True ...
83d10ac23261cfe5803ff732c698879dc0829c9d
29,212
import time import re import sys def main(): """ifstat main loop""" f_netdev = open("/proc/net/dev", "r") # We just care about ethN interfaces. We specifically # want to avoid bond interfaces, because interface # stats are still kept on the child interfaces when # you bond. By skipping bon...
1cdc6b7dfb3dd7dc0cd391a206317f8bdb126d8b
29,213
from typing import Optional def upper_band(df: 'Dataframe', metric_col: str, rolling_window: Optional[int] = 20) -> pd.DataFrame: """Calculates the lower bound of a stock's price movements. Args: df: the dataframe to append a column onto metric_col: the column to calculate over (usually the '...
f831e95ca2027ccedf787178dc630e7e60403ce3
29,214
import torch def reparametisation_trick(mu, log_var, device): """ :param mu: The mean of the latent variable to be formed (nbatch, n_z) :param log_var: The log variance of the latent variable to be formed (nbatch, n_z) :param device: CPU or GPU :return: latent variable (nbatch, n_z) """ n...
9cb646132f49fa79b6a8690d10fd188968931978
29,215
import re def process_gaf_input(gaf_file_path, gaf_file_cache, ignore_cache, node_lengths, edge_lengths, num_jobs): """ The current implementation only works if the GAF file has an informative MAPQ column """ segment_re = re.compile(SEGMENT_ORIENTATION_SYMBOLS) process_read_aln = fnt.partial(proce...
7a7bb52641840ab5b4bf09bcd95d7ca23227725d
29,216
async def prefix_wrapper_async_callable(prefix_factory, re_flags, message): """ Function to execute asynchronous callable prefix. This function is a coroutine. Parameters ---------- prefix_factory : `async-callable` Async callable returning the prefix. re_flags : `int` ...
d09499b4808a24bb643ae904a46049e89c77b7f3
29,217
def draw_mask(img0, img1, mask, size=14, downscale_ratio=1): """ Args: img: color image. mask: 14x28 mask data. size: mask size. Returns: display: image with mask. """ resize_imgs = [] resize_imgs.append(cv2.resize( img0, (int(img0.shape[1] * downscale_rat...
82149bd4fb9a313f76e029fb3234e6aff32cad2e
29,218
def serialize( obj: object, worker: AbstractWorker = None, simplified: bool = False, force_full_simplification: bool = False, ) -> bin: """This method can serialize any object PySyft needs to send or store. This is the high level function for serializing any object or collection of objects ...
b76fedee6e27e14db5ac07f8723eae01ec056457
29,219
def sine_data_generation(no, seq_len, dim): """Sine data generation. Args: - no: the number of samples - seq_len: sequence length of the time-series - dim: feature dimensions Returns: - data: generated data """ # Initialize the output data = list() # Generate sine ...
1d363cce8788b62f84ab3fd05b11ff98cf5719a3
29,220
def apply_wilcoxon_test(wide_optimal, dep_var, OVRS_NAMES, alpha): """Performs a Wilcoxon signed-rank test""" pvalues = [] for ovr in OVRS_NAMES: mask = np.repeat(True, len(wide_optimal)) pvalues.append( wilcoxon( wide_optimal.loc[mask, ovr], wide_optimal.loc[mas...
a1a219c7b1bb6f917da11e5fe35c6992ccc60a8c
29,221
import torch def get_accuracy(targets, outputs, k=1, ignore_index=None): """ Get the accuracy top-k accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or ...
df7f60f37abd9e85b63ca616fb086b84a6ae17d9
29,222
def cameraPs2Ts(cameraPOs): """ convert multiple POs to Ts. ---------- input: cameraPOs: list / numpy output: cameraTs: list / numpy """ if type(cameraPOs) is list: N = len(cameraPOs) else: N = cameraPOs.shape[0] cameraT_list = [] for _cameraPO in ...
10d6fb11a244eded26b4c9b989e88c131832357b
29,223
def dimerization_worker(primer_1, primer_2): """ Returns the total number of complementary bases and the longest run of complementary bases (weighted by HYBRID_SCORES), the median length of all runs and the array of complementary bases. """ p1 = [set(AMB[i]) for i in primer_1] p2 = [set(AMB[i])...
6bd1fd8a990c35f8cd0cde134714c9d4a19cfdb1
29,224
from skimage import img_as_ubyte def load_dataset(ds, elsize=[], axlab='', outlayout='', dtype='', dataslices=None, uint8conv=False): """Load data from a proxy and select/transpose/convert/....""" slices = get_slice_objects(dataslices, ds.shape) data = slice_dataset(ds,...
8ccbc4d3c42bcf0861daec23b7b2410b91b89c5c
29,225
import copy def _interpret_err_lines(err_specs, ncols, names=None): """Give list of column names from the READ SERR and TERR commands Parameters ---------- err_specs : dict ``{'serr': [n0, n1, ...], 'terr': [n2, n3, ...]}`` Error specifications for symmetric and two-sided errors n...
a3ba0960a3711b30c46e8fc75237786d5297f5eb
29,226
def mro_hasattr(cls: type, attr: str) -> bool: """Check if an attribute exists in a type's class hierarchy Args: cls (type): The type attr (str): The attribute Returns: bool: True if has the attribute. Raises: TypeError: Not called on a type """ if not isinsta...
cfc41693e3d3321bcb63dae079abf2e768f97905
29,227
def get_channel_number_from_frequency(frequency): """gets the 802.11 channel for a corresponding frequency in units of kilohertz (kHz). does not support FHSS.""" try: return _20MHZ_CHANNEL_LIST.get(frequency, "Unknown") except KeyError: return "Unknown"
0867a458e98a5a97b3d8925aeeee14f6f5af58a5
29,228
import sys def diurnal_cycle(data, var, stat, stat_config): """ Calculate diurnal cycle """ # Type of diurnal cycle; amount or frequency dcycle_stat = stat_config[stat]['dcycle stat'] # Threshold; must be defined for frequency in_thr = stat_config[stat]['thr'] if in_thr is not None: ...
6cbec0a8ab3dc9487c5e6e59b231e88f70a8f1e6
29,229
def fetch_single_minutely_equity(code, start, end): """ 从本地数据库读取单个股票期间分钟级别交易明细数据 **注意** 交易日历分钟自9:31~11:30 13:01~15:00 在数据库中,分钟级别成交数据分日期存储 Parameters ---------- code : str 要获取数据的股票代码 start_date : datetime-like 自开始日期(包含该日) end_date : datetime-like ...
cc125997fe2f0313295732235b1df2e886d3fcad
29,230
import os def aggregate_components_from_owners(root): """Traverses the given dir and parse OWNERS files for team and component tags. Args: root (str): the path to the src directory. Returns: A pair (data, warnings) where data is a dict of the form {'component-to-team': {'Component1': 'team1@chr....
870cda558bb30173ead1b1158631baeb900397a9
29,231
def method2(): """Provide an examples of doc strings that are too long. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. """ # noqa W505: doc line too long (127 > 100 characters) (auto-generated noqa) return 7
689c50c2cfb62d39cd35eec125813830c6068fdb
29,232
def get_parent_compartment_ocid(teamname): """ Retrieves the OCID for the compartment based on the team name (assuming the model of root -- team -- individual structure of compartments. Args: teamname (str): name of the team level compartment Returns: str: The OCId or None - None is only returne...
bec0bb1d98bb8da0c4e670efebcaa6adcfb8d494
29,233
import os def list_files_path(path): """ List files from a path. :param path: Folder path :type path: str :return: A list containing all files in the folder :rtype: List """ return sorted_alphanumeric([path + f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
84ec5263ca4549075341c90c9b84b330af455393
29,234
def set_recommended_watch_points(session_id): """Set recommended watch points.""" body = _read_post_request(request) request_body = body.get('requestBody') if request_body is None: raise ParamMissError('requestBody') set_recommended = request_body.get('set_recommended') reply = _wrap_re...
81f37e60ba108c2b59c79271342153ea8879697a
29,235
def epochJulian2JD(Jepoch): """ ---------------------------------------------------------------------- Purpose: Convert a Julian epoch to a Julian date Input: Julian epoch (nnnn.nn) Returns: Julian date Reference: See JD2epochJulian Notes: e.g. 1983.99863107 converts into 2445700.5 Inverse of ...
2738940ad390f979317177984c9120b34fa7d2af
29,236
import os def _isfile(path): """Variant of os.path.isfile that is somewhat type-resilient.""" if not path: return False return os.path.isfile(path)
1e5c6e993008b7256c22fe38af174fe87fd01d20
29,237
def GetHighlightColour(): """ Gets the default highlight color. :rtype: :class:`wx.Colour` """ if wx.Platform == '__WXMAC__': if CARBON: if wx.VERSION < (2, 9, 0, 0, ''): # kThemeBrushButtonPressedLightHighlight brush = wx.Brush(wx.BLACK) ...
1654393d9b5f3d5ea610c9dae9706d04d7f37d54
29,238
import os def video_to_frames(width, height, video_path, frames_dir, overwrite=False, every=1): """ Extracts the frames from a video :param width: width of input video :param height: height of input video :param video_path: path to the video :param frames_dir: directory to save the frames ...
9462aa8eb07bf9bd5cace8af29305dd080cc0846
29,239
import configparser def ignores(path): """Pull the flake8 ignores out of the tox file""" toxini = path + "/tox.ini" LOG.debug("Tox %s\n" % toxini) config = configparser.ConfigParser() config.read(toxini) options = {} for option in ('ignore', 'import-order-style', 'applic...
c3a7556cc55fb0215384d946744c8c3b9c8069e0
29,240
import inspect def get_classes(mod): """Return a list of all classes in module 'mod'""" return [ key for key, _ in inspect.getmembers(mod, inspect.isclass) if key[0].isupper() ]
be04546650a6243a3abfe4053a4dcaa9d71f85d7
29,241
import struct def ustring_to_string(ptr, length=None): """Convert a pointer to UTF-16 data into a Python string encoded with utf-8. ptr and length are both gdb.Value objects. If length is unspecified, will guess at the length.""" error_message = '' if length is None: length, error_message...
9981d15eb26816fbc7f2cb0e3cac99b4d738c25a
29,242
import logging def handle_outgoing(msg): """ Should return a requeue flag, so if it returns True, the message will be requeued and processed again immediately, and if it returns False, it will not be queued again. """ def onerror(): logging.exception("Exception while processing SMS %s"...
4b189ef37965ff5725a77af615b52bc019df5910
29,243
def add_entry(ynew: float, s: float, s2: float, n: int, calc_var: bool): """Adds an entry to the metrics, s, s2, and n. s: previous value of sum of y[] s2: previous value of sum of y[]*y[] n: previous number of entries in the metric """ n = n + 1 s = s + ynew s2 = s2 + ynew * ynew ...
8aed2d9f5acb85273b1a152b0747156e49f1ebdc
29,244
def get_conversion_dict(conversion_name): """Retrieves a hard-coded label conversion dictionary. When coarsening the label set of a task based on a predefined conversion scheme like Penn Treebank tags to Universal PoS tags, this function provides the map, out of a fixed list of known maps addressed by a keyw...
9137a50e2f9900abf6d60b51c8bc44e67f13df86
29,245
import scipy def discount_cumsum(x, discount): """ magic from rllab for computing discounted cumulative sums of vectors. input: vector x, [x0, x1, x2] output: [x0 + discount * x1 + discount^2 * x2, x1 + discount * x2, x2] """ return...
82bcb686840191b7cef650b30e14308393331fa2
29,246
def compute_rgb_scales(alpha_thres=0.9): """Computes RGB scales that match predicted albedo to ground truth, using just the first validation view. """ config_ini = configutil.get_config_ini(FLAGS.ckpt) config = ioutil.read_config(config_ini) # First validation view vali_dir = join(config_in...
44341b8c878ca02179ded0a3cc1c173f1eaea009
29,247
def pick_pareto_front(points, keep_equal=False): """Returns the Pareto-optimal points from a set of points, assuming all objectives are minimisation objectives. The n points in d-dimensional objective space are given in an ndarray of shape (n,d), and the return value is of shape (m,d) where m is the ...
4dbd528bb2731dafd8a6f82cbd9dd53a83bd1c4c
29,248
import csv def get_market_conditions(filename): """ Creates the market condition table from the scenario file and risk factors """ market_conditions = [] print("Generate conditions") #open the csv file to be read with open(filename) as csvfile: readCSV = csv.reader(csvfile, delimi...
f7876a8cf4b2d6399e1fd12f2e8a4f7614892874
29,249
def PaperSize(s): """Return a tuple (width, height) for a given paper format string. 'A4-L' will return (842, 595), the values for A4 landscape. Suffix '-P' and no suffix returns portrait.""" size = s.lower() f = "p" if size.endswith("-l"): f = "l" size = size[:-2] if size.en...
e0439e7535bba1b7f4bd5309b8f934b689f1b67f
29,250
def clean_detections(npts, on_off): """Removes spurious seismic detections that occur within a window following a detection. Parameters ---------- npts : int Length of window in data samples. on_off : array On/off indexes for detections. Returns ------- array ...
539ce2b53ee42f8038f4d1b8c35af55247e13204
29,251
def register_validator(fn): """ collect validator functions into ckanext.scheming.all_helpers dict """ all_validators[fn.__name__] = fn return fn
e1dc4c4a9294400d1916b6308192c85702d3fe69
29,252
def save_config(): """ :return: Completed save. """ global host_id_start # Save start and end to file. cfgfile = open("config.ini",'w') try: Config.add_section('Host ID') except ConfigParser.DuplicateSectionError, e: # File already exists. pass Config.set('Hos...
ba15a2d61e153fc251c5b6c9ebc6b48b5f34066e
29,253
def encode_data_image_to_16bit(data_image: np.ndarray, max_data_value: int = 120) -> np.ndarray: """ this method sets all data values above max_data_value to zero, scales it by the max_data_value and rescales the depth image to the uint16 range. :param data_image: :param max_data_value: :return...
fef90a4664ce851f2ace61c4b739c320f6cef3e8
29,254
from typing import Optional from typing import Mapping def get_database(name: Optional[str] = None, resource_group_name: Optional[str] = None, server_name: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, opts: Optional[pulumi.InvokeOp...
1f4afe29ce88d1a85bdb8cee93cf731a6c37b301
29,255
import yaml def read_status_yaml(path: str, year: int = None): """Reads a yaml file containing categories and date ranges for each categories.""" with open(path, "rt") as f: data = yaml.load(f, Loader=yaml.Loader) categories = [] for category, datestrlist in data.items(): status = Sta...
51765d53264c52a3817c48b125ddad6254fca816
29,256
import numpy import math def S_inv_eulerZYX_body_deriv(euler_coordinates, omega): """ Compute dE(euler_coordinates)*omega/deuler_coordinates cfo, 2015/08/13 """ y = euler_coordinates[1] z = euler_coordinates[2] """ w1 = omega[0]; w2 = omega[1]; w3 = omega[2] ...
f7688b61084b0421288be002042b7299a7f8e867
29,257
def _mini_batch_step(X, sample_weight, x_squared_norms, centers, weight_sums, old_center_buffer, compute_squared_diff, distances, random_reassign=False, random_state=None, reassignment_ratio=.01, verbose=False): """Incremental updat...
68bd702efc61a95721d25d6fd89dd5cb54fc41fa
29,258
def get_user_ida_projects(): """ List IDA projects for current user without the prefix. Returns: list(str) -- List of projects. """ user_ida_groups = get_user_ida_groups() if user_ida_groups is None: log.error('Could not get user IDA projects.\n') return None try: ...
d94888849dd1c3c170e99d7ba57a7ec641c5ee39
29,259
def bf_get_issue_config(major, minor): # type: (str, str) -> IssueConfig """Returns the issue config for the active network.""" return IssueConfig.from_dict( restv2helper.get_issue_config(bf_session, major, minor) )
fd8b20c28cac7b8535d7f5045b7fbbaca89f6e71
29,260
import torch def normalize_rotmat(mat: torch.Tensor) -> torch.Tensor: """Normalizes rotation matrix to a valid one""" u, _, v = torch.svd(mat) s = torch.zeros_like(mat) s[..., 0, 0] = 1.0 s[..., 1, 1] = 1.0 s[..., 2, 2] = torch.det(u) * torch.det(v) return u @ s @ v.transpose(-1, -2)
1ba33c73a943392d6fe06448e81c346a5e7dc9f6
29,261
def responder(): """Responder fixture.""" return MockResponder()
097e90423a19c7d1ca231daf717afc15a1597fc1
29,262
def ortho(U, V, A, X=1, G=None, Z=0): """ U is NxL array of cell factors V is JxL array of loadings onto genes X is NxKo array of cell specific covariates A is JxKo array of coefficients of X Z is JxKf array of gene specific covariates G is NxKf array of coefficients of Z assume the data Y is of dimen...
843d895d7d88717859cf73da939266a335214518
29,263
def get_all_users_projects(is_authenticated): """Pull every assigned project for all users from Users_Projects table""" if is_authenticated and auth0.is_admin(): app.logger.info( f"Received request at {const.INTERMEDIATE_API_ALL_USERS_PROJECTS_ENDPOINT}" ) auth0_users, _ = au...
cf33a581d9dcea988af8640b98cb816b61640c3d
29,264
import requests def get_status_code(ep): """Function that gets an endpoint and returns its HTTP status code""" req = requests.get(ep) return req.status_code
bd15853ac4615e96306c2b259c6945a4c46dd17b
29,265
def process_repository(repo_dict): """ Takes a dictionary containing keys: path, branches and revisions and returns a Repository object. This method should only be called by read_yaml. """ path = repo_dict[REPOSITORY_PATH] revisions = {} if REPOSITORY_REVISIONS in repo_dict: for revisi...
3a1122edf7ce42b268a8e735bf060844b7a7fc5d
29,266
import re def hash_algorithm(alg, allow_raw=False): """Parse an hash algorithm""" # canonical name: only alphanumeric uppercase characters alg = re.sub(r'[^0-9A-Z]', '', alg.upper()) if alg in DIGEST_ASN1_PREFIXES: return alg elif allow_raw and alg == 'RAW': return alg raise Va...
dc9287d7c2be76c9b2417a367e8c4e0653c4b515
29,267
def fista(gradient_op, linear_op, prox_op, cost_op, kspace_generator=None, estimate_call_period=None, lambda_init=1.0, max_nb_of_iter=300, x_init=None, metric_call_period=5, metrics={}, verbose=0, **lambda_update_params): """FISTA sparse reconstruction. Parameters ---------- ...
b05c2e860ce3423724f9385dc6f654b98dfdafd3
29,268
def get_entry_from_args(): """ Handle finding the file entry using the user supplied arguments return the entry or quits script entirely. :rtype: object containing the entry of the found file and the entry_id or error & exit """ # Get the pcap file from arguments entry_id = None if 'pca...
5d7ea26bf17d8a8fc54ece069b05cb1918fc746f
29,269
def GetGerritFetchUrl(host): """Given a gerrit host name returns URL of a gerrit instance to fetch from.""" return 'https://%s/' % host
caf5c9015a4cd863e407fb889d473ddebd7bbabc
29,270
import re import os from datetime import datetime import logging def _source() -> Source: """ checks HTTP header source is present and points to an available resource :return: parsed HTTP headers, transformed into a Source object """ source_header = request.headers.get("source") if not source...
5617e92a455f4b1546c5efe484045afc156063ca
29,271
def deep_copy(pcollection): """Create a deep copy of a PCollection up to materialization boundaries.""" if not isinstance(pcollection, pvalue.PCollection): raise ValueError('Input to deep_copy must be a PCollection.') # AppliedPTransform.update_input_refcounts() is a vestigial method that # uses an incorre...
7cfaa902d8e4ea5ce45f779decfeaaf54da2a435
29,272
def compute_lm_accuracy(eval_preds): """Compute the accuracy given the predictions and labels, contained in `eval_preds`. It assumes the logits have been reduced with argmax(-1) by `preprocess_logits_for_accuracy`. """ preds, labels = eval_preds # preds have the same shape as the labels, after ...
fc095cf1662b9cc2e164a8d9bf5e32eb30327460
29,273
import os def is_folder(dir_path): """Determines if a given local directory should map to a SmugMug Folder or Gallery by presence of a .smfolder file""" if os.path.isfile(dir_path + "/.smfolder"): return True else: return False
1825f4bbe328fc7dd2b79cdb55468ad75732e8ef
29,274
from pathlib import Path def fix_path(path): """Fix a path and convert to an absolute location. Parameters ---------- path : str Path to fix. Returns ------- str Absolute path. """ if THIS_PLATFORM == 'Windows': path = PureWindowsPath(path) return st...
a8b648f6bb9859412f347649fd93cf9c264d22b9
29,275
import numpy def partition_skymodel_by_flux(sc, model, flux_threshold=-numpy.inf): """ :param sc: :param model: :param flux_threshold: :return: """ brightsc = filter_skycomponents_by_flux(sc, flux_min=flux_threshold) weaksc = filter_skycomponents_by_flux(sc, flux_max=flux_threshol...
305b18621a3313cdf3ef1cdb14a855bbe4608276
29,276
def getNumberOfDaysBetween(d1, d2, tz_str='UTC'): """ d1 and d2 are datetime objects in UTC """ d1_date = utcInTz(d1, tz_str) d2_date = utcInTz(d2, tz_str) d1_date = deepcopy(d1_date).replace(hour = 0, minute = 0, second = 0, microsecond = 0) d2_date = deepcopy(d2_date).replace(hour = 0, minute = 0, second = 0, m...
c4cdf2febef6fe7c7bf0695c1fa0dcdc3bc6caeb
29,277
def get_language_specifics() -> BaseLanguage: """Gets the language specific actions.""" return PluginLoader().languageSpecifics
8959bce727b6c068d5fc08041d74820fd3738ef5
29,278
from .model_store import get_model_file import os def get_darknet53(model_name=None, pretrained=False, ctx=cpu(), root=os.path.join('~', '.mxnet', 'models'), **kwargs): """ Create DarkNet model with specific parameters. Parameters: ...
38771bab3d48bfef17f0c3453ce661e92f764b48
29,279
def add_item(): """Create a new item. This will list all login uuser created """ if 'username' not in log_session: flash("Please login in to continue.") return redirect(url_for('login')) elif request.method == 'POST': item = session.query(Item).filter_by(name=request.form['name'])....
31cc94f58a01f473731fcd689769b688bcb97f72
29,280
def SGLD(nburnin, nsample, gradU, p, batch, eta=0.0001, L=100, V=3): """ Function to get posterior samples given parameters with SGLD """ n = nburnin + nsample if type(p) != "np.array": d = 1 else: d = len(p) samples = np.zeros((n,d)) for i in range(n): ...
04d49230cb71c83561726939213e2bdc74edaf54
29,281
from typing import List def create_commands(device_ids: List[str], file_path: str) -> List[CommandRunner.Command]: """ Create a list of `Command` of the remove file command to `Cortex XDR` and `CrowdstrikeFalcon` :param device_ids: The device id's to run on :param file_path: The file_path to delete ...
2a27c69bcaaf91984c853bd37eb260cc7d27a720
29,282
from datetime import datetime def compiler(stats_set): """ Processes the API data into a clean dataframe for analysis and predictions. Parameters ---------- stats_set: list Incoming data on all previous games from the balldontlie API request. Returns ---------- final: pan...
a4edcd41cfd770e82aa368e3e6232f51d6cecec8
29,283
def generate_cpda_eligible_lists(request): """ Function retrieves the eligible user information and related unreviewed,approved and archived CPDA applications. """ active_apps = (Cpda_application.objects .select_related('applicant') .filter(applicant=request.u...
b6cda540dd94ea07d3e4a400a8dfa19c8cec1e0a
29,284
def get_points_on_sphere(n_points, r=1): """ Find n evenly spaced points on a sphere using the "How to generate equidistributed points on the surface of a sphere" by Markus Deserno, 2004. Arguments: n_points (int): number of points to generate r (float): radius of the sphere Return...
575b7aa98c08942dbe24389bf18bde36cd0f9c0e
29,285
def bottleneck_block(x, filters, kernel_size=(3, 3), padding="same", strides=1): """ bottleneck_block(x, filters, kernel_size=(3, 3), padding="same", strides=1) This function creates a bottleneck block layer, which is the addition of a convolution block and a batch normalized/activated block INPUTS: ...
a0a37478013feb4702fa18b5143d7f0c33506119
29,286
import logging def ClusterAndFindSplit(values, rand=None): """Finds a list of indices where we can detect significant changes. This algorithm looks for the point at which clusterings of the "left" and "right" datapoints show a significant difference. We understand that this algorithm is working on potentiall...
fb89eca16806042ef23f81d611741c4c77577071
29,287
def list_nodelets(): """ List all nodelets in all packages. """ nodelets = [] for p in rospkg.RosPack().get_depends_on('nodelet', implicit=False): nodelets += Package(p).list_nodelets() return nodelets
367aeb784bc3282e1e37d279591ddb00aa698b0b
29,288
import os def install_openwhisk_action_in_path(packaging_params, action_params_to_env, path): """ This performs the equivalent of the command line: wsk action create fetch_aws_keys --docker tleyden5iwx/openwhisk-dockerskeleton --param AwsAccessKeyId "$AWS_ACCESS_KEY_ID" --param AwsSecretAccessKey "$AWS_...
8a3e201b258341ff02d51b8b53a97f3fea96ab6a
29,289
import logging import sys def checkMysql(checkOptions, options, required=False): """ Used in functions that may use the DB interface either that this is required or that functionality may be degraded. <condition> = mysql is not used or pymysql is available arguments: optio...
1e5a77a4c578b99d36e7a27d901a4226a21e47fe
29,290
def predict(): """Predict route""" audio_id = request.args.get('id') db.download(audio_id) y = detector.predict("data//audio.wav") state = {"status": str(y)} return jsonify(state)
a0e7011499e6c387532172750cbaa4163c509736
29,291
def colorize(text, color, bold=False): """Colorize some text using ANSI color codes. Note that while ANSI color codes look good in a terminal they look like noise in log files unless viewed in an ANSI color capable viewer (such as 'less -R'). Args: text: The text to colorize. color: One of the color...
8231b5f7c58f940820a7f0ef0846d663ec146366
29,292
def _create_log_entry(class_, message, author, created_at=None, **kwargs): """ This method will create a new LogEntry of the given type with the given arguments. :param type type: A subclass of LogEntry which should be created. :param unicode message: the log message text :param User author: us...
ec0ad487b4aa6580555d0e58fcd3eadb8e4c3941
29,293
def avg_stimpos(band, eclipse): """ Define the mean detector stim positions. :param band: The band to return the average stim positions for, either 'FUV' or 'NUV'. :type band: str :param eclipse: The eclipse number to return the average stim positions for. :type eclipse: int :re...
59d748b99c621f6dbcbbc05ba77c54178b57533d
29,294
def multiclass_positive_predictive_value(confusion_matrix: np.ndarray, label_index: int) -> Number: """ Gets the "positive predictive value" for a multi-class confusion matrix. The positive predictive value is also known as *precision*. See the documentation of...
51822f7a75eb48301121fc52ef5e6f8fa661fe2f
29,295
def get_matching_cost_swap_bf(election_1: OrdinalElection, election_2: OrdinalElection, mapping): """ Return: Cost table """ cost_table = np.zeros([election_1.num_voters, election_1.num_voters]) for v1 in range(election_1.num_voters): for v2 in range(election_2.num_vot...
38b7857686caa60212ffdd4578097658dd9ba2e3
29,296
def auditable(event_type, msg_on_success): """ Makes the result of an endpoint audit loggable - passes an AuditLogger object to the handler so that it can set extra data to be logged. """ def decorator(f): @wraps(f) def _(self, request, *args, **kwargs): audit_logger ...
e422fcb8892da5dc26299a437238e3a815492f9e
29,297
def rec_pow(a, b): """Compute a**b recursively""" if b == 0: return 1 if b == 1: return a return (rec_pow(a,b//2)**2) * (a if b % 2 else 1)
42972acab57b3e217dbd10fa32a38125c5eab44d
29,298
def omega_d(m, bvectors, bweights, idx=None): # Eq. 36 """ Compute the diagonal contribution to the spread functional Parameters ---------- m: ndarray, shape (nkpts, nntot, nbnds, nbnds) the overlap matrix bvectors: ndarray, shape (nkpts, nntot, 3) bweights: ndarray, shape (nntot,...
30136552c53b3fd18ebb56b666cf9bafa7baf926
29,299