content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import tqdm def get_all_mask_volumes(): """ Purpose: Returns all masks for dataset in a single numpy array of 32 bit floats. Shape will be 259x240x240x155x1 """ all_patient_paths = get_each_hgg_folder() # preallocate empty np array to hold all the masks # dim 0 ...
661e64bdd550f98ae4861384da558981bb2e887e
3,614,100
def prepare_training_data(sessions): """ Convert extracted session into training data :param sessions: list of sessions :return: """ purchase_sessions = [] abandon_sessions = [] for s in sessions: # check that purchase action occurs after add action if Actions.purchase...
41ae799dcc815a1da5b89d6718bad7c0f84b375c
3,614,101
import torch def nx_to_graph_data_obj_simple(G, partial_charge=False): """ Converts nx graph to pytorch geometric Data object. Assume node indices are numbered from 0 to num_nodes - 1. NB: Uses simplified atom and bond features, and represent as indices. NB: possible issues with recapitulating rel...
e080aec34468e4948ca38dd162d864e8dc5dd4ba
3,614,102
def after_replace(func, target=None): """Request `func` be invoked as `func(self, old)` when `model` is about to replace an older version of itself. Alternatively when applied to a collection, request `func(key, old, new)` be invoked. :: @acid.events.after_replace def after_replace(sel...
a1c84c1c6a9cc04bd46c04b68410f33d5a26dd13
3,614,103
import os def add_prefix_to_fname(original_fname, prefix): """Add a prefix to a given filename. Examples: >>> add_prefix_to_fname("data.tif", "London") "London_data.tif" """ file_dir = os.path.dirname(original_fname) file_basename = os.path.basename(original_fname) new_basenam...
307385941159b38925cd935f381d5b337d345eeb
3,614,104
def construct_sequence(seq_dict): """Construct RnaSequence from dict of {pos:residue}. seq_dict -- dictionary of {position: residue} Checks whether the first residue is 0. Checks whether all residues between min and max index are present. No checking on validity of residue symbols. """ ...
cb150f3400807dd22ca1044a68f4a62faa279c1c
3,614,105
def _cauchy_ ( self , mu , gamma ) : """Generate Cauchy random numbers - rely on the distribution of the ratio for two Gaussian variables - see https://en.wikipedia.org/wiki/Cauchy_distribution """ g1 = self.gauss ( 0.0 , 1.0 ) while abs ( g1 ) < _fmin : g1 = self.gauss ( 0.0 , 1.0 ) g2 = ...
724afa6a7bf733227ae1fa03614785ba6f622b8c
3,614,106
def get_group_cpu_name(ifamily, category, device): """ Abstract layer to group i3, i5, i7 families. :param ifamily: which series of cpu we want to group :param category: category to make sure the input is processor :param device: device to check :return: grouped device name """ ifamily_...
46b3bf00540e9147f6e4bab3a1431bd8497009a6
3,614,107
def median(values): """Return median value for the list of values. @param values: list of values for processing. @return: median value. """ values.sort() n = int(len(values) / 2) return values[n]
c40b9e0b2cdd2b00ae6692aed2cfe9787bc8f9df
3,614,108
def remove_default_create_options(options): """ Return only non default create options """ _options = options.copy() for opt in IPSET_DEFAULT_CREATE_OPTIONS: if opt in _options and \ IPSET_DEFAULT_CREATE_OPTIONS[opt] == _options[opt]: del _options[opt] return _options
cbfdbbfab149cea698e912db0d3271ddcb97a20e
3,614,109
import numpy def _grid_3d(dx, dy, dz, order): """Generate 3D structured grid.""" # Internal functions def meshgrid(x, y, z, indexing="ij", order=order): X, Y, Z = numpy.meshgrid(x, y, z, indexing=indexing) return X.ravel(order), Y.ravel(order), Z.ravel(order) def mesh_vertices(i, j, k...
4204f54c0629fa17d4f8ffff997cfce735e4307c
3,614,110
def title_keywords(title): """Given a title, returns every author assigned keyword""" q = """ SELECT GROUP_CONCAT(keyword) FROM OriginalKeywords WHERE ArticleID='{t}'""".format(t=title) curr.execute(q) return curr.fetchall()[0][0].split(',')
2560ca23e91f3347c6bbb77c285b5f9a6fac7a75
3,614,111
import torch def collate_fn(batch, transforms): """Collate function to be passed to the PyTorch dataloader. Parameters ---------- batch : list Uncollated batch of size `batch_size`. device : str or torch.device Current working device. transforms : callable Transformati...
89daebd2f58d9a7b83c7bd7c14cdde2ed16d8b3d
3,614,112
def persistence_function_from_model(model, G_interlayer, layer_vec=None, N=None, T=None, Nt=None): """ Returns a function to calculate persistence according to a given multilayer model :param model: network layer topology (temporal, multilevel, multiplex) :param G_interlayer: input graph containing all...
9e3998ac4beb0ed653f6482a550fbde5e6c75eeb
3,614,113
def sanitizer(name): """ Sanitizes a string supposed to be an entity name. That is, invalid characters like slashes are substituted with underscores. :param name: A string representing the name. :returns: The sanitized name. :rtype: str """ return name.replace("/", "_")
f59aa75a40067068c711a4ca01b643c69d43cd0c
3,614,114
def fget_wcs(fitsfile_path): """Get the World coordinate system (wcs) from the fits header for plotting. Parameters ========== fitsfile_path: str The input fits path Return ====== wcs: `astropy.wcs.wcs.WCS` Image coordinates in WCS format """ hdu = fits.getheade...
e85e903a0dc3ff624fa2e1d053f7225932601c8d
3,614,115
def is_repository_setup(): """Indicates if base repository is setup or not. """ return repository_cache.get_value() is not None
0ab19dba941fe5af6359a3ed6b725a751dca3b41
3,614,116
def ISURL(value): """ Checks whether a value is a valid URL. It does not need to be fully qualified, or to include "http://" and "www". It does not follow a standard, but attempts to work similarly to ISURL in Google Sheets, and to return True for text that is likely a URL. Valid protocols include ftp, http,...
e1362d9cfe97b35e935d072da1aa1791acd24371
3,614,117
def transaction_class(cls): """ Return the associated transaction class for given versioned SQLAlchemy declarative class or version class. :: from sqlalchemy_continuum import transaction_class transaction_class(Article) # Transaction class :param cls: SQLAlchemy versioned decla...
054bf2e31b7c4132928192c21317ad898ed13dde
3,614,118
def get_comp_choice(): """ This function randomly generates a number between 1 up to and including the max number of options. If base, it should be 3. If expanded, it will depend on the number of options and logic you have created. Returns the integer "chosen" by the computer/randomizer. """ ...
941df6616d82d663d90c3484a6d3aa00e25269c3
3,614,119
def _GenerateRootGradle(jinja_processor): """Returns the data for the root project's build.gradle.""" variables = {'template_type': 'root'} return jinja_processor.Render(_JINJA_TEMPLATE_PATH, variables)
cfb28ff7fe2dffb1e451bce9e94b51ef17286209
3,614,120
def measure_display_label(src_type): """update label upon modification of Radio Items""" source_label, measure_label = get_source_labels(src_type) source_unit, measure_unit = get_source_units(src_type) return 'Measured %s (%s)' % (measure_label, measure_unit)
70e7ffc3dddc7b92cce79d66985b283d088759f3
3,614,121
def only_choice(values): """Apply the only choice strategy to a Sudoku puzzle The only choice strategy says that if only one box in a unit allows a certain digit, then that box must be assigned that digit. Parameters ---------- values(dict) a dictionary of the form {'box_name': '123456...
c8760594858a48aaa97e62ffbbb2f290bcff4e1f
3,614,122
def get_xml_storage_model(): """ Return the configured xml storage model class using apps.get_model() """ app, model = acs_settings.XML_STORAGE_MODEL.split(".") return apps.get_model( app_label=app, model_name=model )
03285f7c8ad7f781c4a82ac22d86cbbe0291c96b
3,614,123
def _get_deployments_digest_by_uid(uid): """ Get list of deployments for a reference designator; return digests. (See also event_tools.py, get_deployment_events. Supports asset management Deployment tab.) """ results = [] try: # Get vocabulary dictionary once. vocab_dict = get_vocab(...
ab3b689e9b6d47b0bb10a06cfc105f03493a15f4
3,614,124
def layout_arc_with_drc_exclude( cell, layer, drc_layer, center, r, w, theta_start, theta_end, ex=None, **kwargs ): """ Layout arc with drc exclude squares on sharp corners""" dpoly = layout_arc(cell, layer, center, r, w, theta_start, theta_end, ex, **kwargs) dpoly.layout_drc_exclude(cell, drc_layer, ex...
38bfe0f29f0a9e2a4ea3b7ad0ca43fdb5ee6ce5e
3,614,125
def create_fake_user(): """ Generate new user and saves to database """ user = User.objects.create(username=faker.first_name_male()) return user
71e141e6b2f34f4cc1453dffee113117125ce782
3,614,126
def control_brightness(how, level): """Control brightness level.""" _change_brightness(how, level) _send_notification() return 0
624e69d94c4d763699aff93d46482ecaa5c664df
3,614,127
def has_negative_control(cmd): """Return whether a command has negatively controlled qubits.""" return get_control_count(cmd) > 0 and '0' in cmd.control_state
94c5ab2773f946dc6c598e64c91ea7d90ec83b08
3,614,128
def qg8_graph_load(filename: str): """" Load a QG8 graph from file chunk by chunk """ f = qg8_file_open(filename, QG8_MODE_READ) if f is None: return None graph = qg8_graph([]) # create empty graph object i = qg8_file_iterator(f) while qg8_file_has_next(i): # EOF check ...
6c6b2ab78131fb9454c782aade283f59e223400a
3,614,129
def all_reduce(tensor, op=dist.ReduceOp.SUM, group=dist.group.WORLD): """ Reduces the tensor data across all machines in such a way that all get the final result. After the call the returned tensor is going to be bitwise identical in all processes. Arguments: tensor (Tensor): Input of ...
ecdd395272ff314a77b8e765d0f825cf7329fad2
3,614,130
def _get_stock_ledger_entries(filters): """ Get data from Stock Ledger Entries with the following fields: (1) date, (2) item_code, (3) actual_qty, (4) qty_after_transaction, (5) project, (6) stock_uom, (7) item_name :param filters: :return: Stock Ledger Entries """ item_code = filters.ge...
6ed2ce915876b1232c695619c4823db789be0a61
3,614,131
def parse(tokens): """Parses the infix permission ``tokens`` into a postfix instruction list. :param tokens: The token list produced by :func:`~pwh_permissions.tokenise` :type tokens: ``list`` :return: The token list in postfix notation :rtype: ``list`` """ result = [] stack = [] bu...
1e4bc897ec205112004aca56d49606e0726de27a
3,614,132
def roots_legendre_interval(n, a, b): """ Computes the sample points and weights for Gauss-Legendre quadrature on interval `[a, b]`. The sample points are the roots of the n-th degree Legendre polynomial `P_n(x)`. These sample points and weights correctly integrate polynomials of degree `2n - 1...
2e0e09785ec9557dbe4cc1c368d7401c581f947e
3,614,133
from typing import Optional from typing import List from typing import Tuple from pathlib import Path def get_physical_dependencies(obj: str, lib: str, include_self: bool, job: Optional[IBMJob]=None, verbose: bool=False) -> List[Tuple[str, str, str]]: """Get the dependencies for a given physical file object ...
8e358ef3a2b0210668ce1a4c88235c7975005138
3,614,134
import subprocess def git_uncommited_changes(): """ Returns True if the current git branch has uncommitted changes. """ p = subprocess.Popen( ['git', 'status'], ) returncode = p.wait() return (returncode is not 0)
0e72aa04afabc0dd8a014dbfb30a08cdf22eed01
3,614,135
def compute_counters(data): """ Returns the number of times a separator is in each line. """ counters = np.zeros((len(data), len(SEPARATORS))) for i, line in enumerate(data): counters[i] = [get_character_count(line, sep) for sep in SEPARATORS] return counters
9c115cad6a543939ca6601183bf31d976abd7a80
3,614,136
def mishActivation(x): """ Mish Activation Function """ return x * tf.math.tanh(tf.math.softplus(x))
d66dd5a2ee371e7937aa69ddf00ffc7481dc0d32
3,614,137
import warnings def MagneticDipoleWholeSpace( XYZ, srcLoc, sig, f, moment, fieldType="b", mu_r=1, eps_r=1, **kwargs ): """ Analytical solution for a dipole in a whole-space. The analytical expression is given in Equation 2.57 in Ward and Hohmann, 1988, and the example reproduces their Figure 2.2....
d8517f93bfa3f1f341e3c45ce6cd567cbda9aa3c
3,614,138
from clawpack.geoclaw import topotools from numpy import array import netCDF4 import xarray def read_netcdf(path, zvar=None, extent='all', coarsen=1, return_topo=True, return_xarray=False, verbose=False): """ :Input: - *path* (str) - Path to the file to read, or url to remote file, ...
9f28f25e7c7f9be856825843421f42a2f37027bf
3,614,139
def quantize(v, unit): """Quantize value `v` to a multiple of `unit`. When `unit` is an integer, the return value will be integer as well, otherwise the function will return a float. Parameters ---------- v : ndarray or number Number to be quantized unit : number The quantiz...
55f3b88d28dc94430cd7741f6f1e2603b208054e
3,614,140
def next(dist, median, d1, d2, p, N): """ INPUT dist: distance matrix median: list of integers for selected vertices d1: list of nearest facility for each vertex d2: list of second nearest facility p: number of facilities to locate N: number of vertices on the nextwork OU...
00bb21f286b29659358c91144567940ba4cbf758
3,614,141
def stop(): """ Stop the currently running recipe. :return: object response One of: ok error message Only present if response is "error" and there is a message to present to the user. """ recipes.stop() return jsonify({...
2c7dd7ff86d373877c9493b2027d0134624428f1
3,614,142
import textwrap def loadings_histograms( pca, feature_labels, n_components='all', bins=50, n_features_to_label=10, max_text_len=35, text_kws={'color': 'white', 'bbox': {'facecolor': 'k', 'alpha': 0.7, 'pad': 1}}, save_fig=None): """Plot histograms of the loadings ...
70e0248b76f543100704445467be7c52f760e16a
3,614,143
import re def password_string(value): """密码输入类型""" if len(value) < 8 or len(value) > 20 or re.match(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$', value) is None: raise ValueError('密码至少包含 数字和英文,长度6-20,不能出现非法字符') return value
e6bfcc473c164cd06e3acd65165f6fb9dcd251cf
3,614,144
import traceback def get_axes_texts(img, axis_entities): """The function for getting the texts in the axis""" try: data = [] # No axes in the image if img is None or axis_entities is None: return data (img_height, img_width) = img.shape[:2] for axis_id, axis...
1f1bd3f7b5a6561df27c57bf95ccdf3e8700deee
3,614,145
import typing import torch def mixture_component_selection_embedding_(subset_embeds: typing.Mapping[str, Tensor], s_key: str, flags, weight_joint: bool = True) -> Tensor: """ For each element in batch select an expert from subset. subset_embeds: embeddings of eac...
970d3413356ffeb45be6c96cc31f137a2ce160d6
3,614,146
import os def build_engine(onnx_file_path, engine_file_path, mode='fp32', verbose=False): """Takes an ONNX file and creates a TensorRT engine.""" TRT_LOGGER = trt.Logger(trt.Logger.VERBOSE) if verbose else trt.Logger() with trt.Builder(TRT_LOGGER) as builder, builder.create_network(*EXPLICIT_BATCH) as net...
ef72a6caacfcdf9f55e09a5561634246ee7fe84d
3,614,147
def filter_same_smiles(dset): """ Filter out species whose conformers don't all have the same SMILES. Can happen because, for example, CREST simulations can be reactive. This won't happen if conformers are generated using RDKit. Args: dset (nff.data.dataset): NFF dataset Returns: ...
968ffa6de9c3dd4c09620b4aa6bd94ac2f191b27
3,614,148
import logging def user_popup(request): """/user_popup - Pop up to show the user info.""" try: return _user_popup(request) except Exception as err: logging.exception('Exception in user_popup processing:') # Return HttpResponse because the JS part expects a 200 status code. return HttpHtmlRespons...
0daa09fb4f6b173af0794e37b7276638f732fa0e
3,614,149
from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer def tokenize_word(text, normalise_case=True, keep_numerics=False, shortwords=3, remove_stopwords=True, l...
83790a61a2d17cb3442d9388c58e13f3b8339b66
3,614,150
def read_video(fname): """ Parameters ---------- fname Returns ------- """ cap = cv2.VideoCapture(fname) frames = [] it = 0 while True: retval, image = cap.read() if image is not None: frames.append(image) it += 1 if no...
3a857ee51a5e04a3159a550c6652214203aef8ee
3,614,151
def build_bankruptcy_definition(years): """Build a bankruptcy definition Notes: This function is set according to a line of best fit from Year 0 at -10% ROI to 10% ROI by Year 7. Args: years (int): No. of years for analysis Returns: Bankruptcy definitio...
c2364bd97eec587e57bc0d701d83b304631a8bd2
3,614,152
import textwrap def run_pylint(source, msg_ids, *cmd_args): """Run pylint on some source, collecting specific messages. `source` is the literal text of the program to check. It is dedented and written to a temp file for pylint to read. `msg_ids` is a comma-separated string of msgids we are intereste...
b7dd29571b85f607d36b4986e798de6dcda85e31
3,614,153
import nipype.pipeline.engine as pe import nipype.interfaces.io as nio import os def resting_datagrab(c,name="resting_datagrabber"): """Returns a datagrabber nipype node. The datagrabber looks for the following files: * reg_file : bbregister file * mean_image : mean image after motion correction * mask : mask im...
3da8886de02bc7bed4a80ca1c32dcafde67235c7
3,614,154
import datasets import os import torch import time def create_and_train(data_folder, training_subfolder = '/train/', validation_subfolder = '/valid/', batch_size = 64, arch = 'densenet121', hidden_units = [], dropout = 0, bn = False, ...
ad62428b6c6ee115312bc10fc4ea63dcc88fe840
3,614,155
def compute_rot_scale_skew(lazAC, i=0, scaleFactor=1.): """ same as displayRotScaleSkew but without text output """ xshift = lazAC.Alm[i, 0] * scaleFactor yshift = lazAC.Alm[i, lazAC.Nalm] * scaleFactor if lazAC.k > 2: idx_forXterm = np.where(lazAC.polynomialTermOrder == 'x')[0] ...
4e3fa5ac0d3b1a0402cbebf7994eb0fb5acb286a
3,614,156
import tempfile import struct import zlib def readsav(file_name, idict=None, python_dict=False, uncompressed_file_name=None, verbose=False): """ Read an IDL .sav file Parameters ---------- file_name : str Name of the IDL save file. idict : dict, optional Dictionary...
1f056375d04bf8adddca86569c98f7d18708c351
3,614,157
import pickle def top_results_overall(databases= 'all', n_entries= 10): """ Creates a table summarizing the overall performances Args: databases (str): 'all'/'high_ir'/'low_ir'/'high_n_min'/'low_n_min'/'high_n_attr'/'low_n_attr' n_entries (int): number of entries to show """ result...
04feeeef502b4b01c12574351aaa3b83d17c1066
3,614,158
def clean_data(data): """ Clean data from Kobo :param data: Pandas DataFrame containing data from Kobo :return: Pandas DataFrame """ # Remove unnecessary columns drop_cols = ['subscriberid', 'deviceid', '_uuid', '_submission_time', '_validation_status', '_id', 'start', 'end', ...
3defebabca1fdcd8bef96c1bec830d13cd63a571
3,614,159
def ignore_sparse_panel_future_warning(func): """ decorator to ignore FutureWarning if we have a SparsePanel can be removed when SparsePanel is fully removed """ @wraps(func) def wrapper(self, *args, **kwargs): if isinstance(self.panel, SparsePanel): with assert_produces_w...
01d946c958f887008cdced6b62015b847393de2e
3,614,160
def bad_unpacking(): """ one return isn't unpackable """ if True: return None return [1, 2]
dd241b5aa49b58300fd883d61b5eb41b1eb92aa1
3,614,161
def build_slices_from_list_of_arrays(list_of_arrays, n_his, n_feat, verbose=0): """ This function creates a list of slices of shape (n_his + 1, n_feat) """ assert list_of_arrays[0].shape[1] == n_feat, "list_of_arrays[0].shape[1]={} but n_feat={}".format( list_of_arrays[0].shape[1], n_feat) X_sl...
bfec73928e84a07eab9fc00f2cf9c8b1d5ca31cb
3,614,162
def most_similar(text, topn=10): """检索最相近的topn个句子 """ token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen) vec = encoder.predict([[token_ids], [segment_ids]])[0] vec /= (vec**2).sum()**0.5 sims = np.dot(a_vecs, vec) return [(kkk_all[i], sims[i]) for i in sims.argsort()[::-1][:topn]...
1368a3f0c05fe8761be226c3a696e98bbaadf034
3,614,163
import types def orient_by_rois(streamlines, roi1, roi2, in_place=False, as_generator=False, affine=None): """Orient a set of streamlines according to a pair of ROIs Parameters ---------- streamlines : list or generator List or generator of 2d arrays of 3d coordinates. Each...
b0c3a25528d2f2a6a325161f9621e604541e9176
3,614,164
def luhn_checksum(check_number): """http://en.wikipedia.org/wiki/Luhn_algorithm .""" def digits_of(n): return [int(d) for d in str(n)] digits = digits_of(check_number) odd_digits = digits[-1::-2] even_digits = digits[-2::-2] checksum = 0 checksum += sum(odd_digits) for d in even_...
4209fd2f77acb240e7e2adfca63d638bb6f79187
3,614,165
import importlib def _data_api(): """Returns a Data API. This relies on Django settings to find the appropriate data API. """ # We retrieve the settings in-line here (rather than using the # top-level constant), so that @override_settings will work # in the test suite. api_path = getattr(...
7a5b7bb3be6d86bd8bb3872a6bc0a9934b84f001
3,614,166
import os import logging import time def setup_log_file_handler(config, logfile, fmt): """Setup file debug logging.""" log_file_path = os.path.join(config.logs_dir, logfile) try: handler = logging.handlers.RotatingFileHandler( log_file_path, maxBytes=2 ** 20, backupCount=1000) exce...
bfc32fa4f43a8c3f61ceb3e8d9d2783d7c7f7849
3,614,167
def get_system_log_queue(): """ Json格式为: {'alias':'w01' 'host':'192.168.1.100' 'timestamp':123213123 'type': 'reboot' or 'shutdown' or 'power' 三个值中其中一个 } """ system__log_queue ='ztq:queue:system_log' return get_limit_queue(system__log_queue, 200)
46329d3f5765b7fc07add5b2cec7b0978b8b6873
3,614,168
def blockchain_timeframe_summary(final_df, config) -> dict: """ Get summary statistics :param final_df: The full dataframe of address information from the blockchain :param config: configuration file for including start/end times in output dataframe """ print("Getting summary counts of analysi...
eedbb4e33bfdb937426ace26eba10427694356ec
3,614,169
def user_has_custom_top_menu(domain_name, couch_user): """ This is currently used for a one-off custom case (ewsghana, ilsgateway) that required to be a toggle instead of a custom domain module setting """ return (toggles.CUSTOM_MENU_BAR.enabled(domain_name) and not couch_user.is_superus...
735d119a5875cbf96b3f753fac334a51583f7477
3,614,170
import binascii def b2x(b): """Convert bytes to a hex string""" return binascii.hexlify(b).decode('utf8')
fded3635120d44436159908ed04e4384be1e5b47
3,614,171
import itertools import logging def get_size_k_subgraphs(graph, min_region_count, k=1, keep_grammars=[]): """for size k, get all unique subgraphs """ total = 0 subgraphs = [] current_subgraph_len = 0 for node_subset in itertools.combinations(graph, k): subgraph = graph.subgraph(node_su...
28b2df2256d0e337f0905c183c6a0a41dc68bf1b
3,614,172
import numbers def list_to_blackbird(A, var_name): """Converts a Python nested list to a Blackbird script array type. Args: A (list[list]): 2-dimensional nested list var_name (str): the array variable name Returns: list[str]: list containing each line representing the ...
80babac6cb03dfe0b0ef396e4dba45fb2fb4692a
3,614,173
def CreateOptim(parameters, lr=0.001, betas=(0.5, 0.999), weight_decay=0, factor=0.2, patience=5, threshold=1e-03, eps=1e-08): """ Creates optimizer and associated learning rate scheduler for a model Paramaters ---------- parameters : torch parameters Pytorch network parameters ...
95041c17f613d98dfbadb063c7117b4202e59ee3
3,614,174
import os import re import platform def find_path_by_regexp(default_dir, search_regexp, allow_environment_path=True) -> list: """ Search regexp or path in default directory and directory by environment path. Args: default_dir (str): Default directory to search application search_regexp (s...
d9c87d40bb11c1064aa35c368a8dffcbfcdab791
3,614,175
import sys def try_decorator(error_ret=None): """ Decorator that tries something, OR returns a safe_value if failure happens (and continues) usage: @try_or_return_none def foo(): if rand() > 0.9: raise Error else: return rand() """ def real_decorator(funct...
25f54168b9b0940e054d2ad75379de295ba7ed05
3,614,176
def prepare_images_tensorflow(images: np.ndarray) -> np.ndarray: """ Prepares an image ndarray to fit into the tensorflow NHWC Args: images: The images in an nxmxm format Returns: The images in the NHWC tensorflow format. """ return images.reshape(*images.shape, 1)
b8be86bc6efb9ad076a61779a35e9bda98aa3f24
3,614,177
import click def line_width_option(**kwargs): """Get line width option for the plots""" def custom_line_width_option(func): def callback(ctx, param, value): ctx.meta["line_width"] = value return value return click.option( "--line-width", type=F...
ef846fc4c8ba54891aac166aaf09d31816d83934
3,614,178
import ctypes def make_array_ctype(ndim): """Create a ctypes representation of an array_type. Parameters ----------- ndim: int number of dimensions of array Returns ----------- a ctypes array structure for an array with the given number of dimensions """ c_int...
c83ab386d40043d49d1b86c21c2789c461999fc5
3,614,179
def get_popular_article(): """Get top 3 most popular articles""" query_command = "SELECT * from popular_posts LIMIT 3" query_data = run_query(query_command) return query_data
1a2416746f8a74e5fa1028266a5bdf619f97aff8
3,614,180
def get_json_request_header(): """ Return the header for JSON request :return: """ return {'Accept': 'application/json', 'Authorization': 'Token sessionTokenHere==', 'Accept-Language': 'en'}
9767910ae8e4c1fe8993ab45fa2331e9ea6efad1
3,614,181
def diffraction_limited_mtf(fno, wavelength, frequencies=None, samples=128): """Give the diffraction limited MTF for a circular pupil and the given parameters. Parameters ---------- fno : `float` f/# of the lens. wavelength : `float` wavelength of light, in microns. frequencies ...
003c578ff0a19b98e4d7658515f53eecd8a87f82
3,614,182
def warrior2_label_csv(pose_df, side='right'): """ takes averages of all rows (2d_points) OLD order: head_front, sholders, arms, torso forward, torso backward hips, knee acute, knee obtuse, step wider 1 - needs to be adjusted 0 - good Order for 9 digit labeling: 1. arms 2. front_knee...
b9e8cfbd974607fb25ec5e27054674680f8c8ca1
3,614,183
import logging def ddmin(c, n, test): """ The original delta debugging algorithm :param c: Current input :param n: Current granularity :param test: Test function used to determine if a particular input leads to a fault, a return value of True indicates a failure :return: Minimal subse...
b26edff1492ca5b5a54d364efc37ee5c2206b135
3,614,184
from unittest.mock import Mock import json def check_client_method(): """ Helper to test an API method -- returns a tuple of (test_api_client, check_assertions) where check_assertions will verify that the API method returned the data from http.request, and that http.request was called with the cor...
20c49495861a509c97c007009423a3ecabeabfb5
3,614,185
def CMDdiff(parser, args): """Displays local diff for every dependencies.""" parser.add_option('--deps', dest='deps_os', metavar='OS_LIST', help='override deps for the specified (comma-separated) ' 'platform(s); \'all\' will process all deps_os ' ...
7fd2c16e3ed63d4b39f1a35d969f6da76bf6a868
3,614,186
def remove_accessory(): """ Remove the accessory from the database. Inform user if it was successful or not. """ add_accessory_form = AddAccessoryLiftForm() remove_accessory_form = RemoveAccessoryLiftForm() accessory_lifts = AccessoryLift.query.filter_by(lifter=current_user) remove_accessor...
02fdaf80590999a1ee37ad9438d38cb776a0aba0
3,614,187
def Pwr(a, b): """ a to the power of b :param a the base :param b the power value :return a^b """ c = 0 if a == 0: c = 0 elif b == 0: c = 1 else: i = 0 c = 1 while i < b: c = Mul(c, a) i = i + 1 return c
fc560d6ec568f5297dc9d8fdfae2e938ecaee98f
3,614,188
def random(pages : int = 1, wiki : str = WIKI, language : str = LANG): """ Get a list of random fandom article titles. Returns the results as tuples with the title and page id. .. note:: Random only gets articles from namespace 0, meaning only articles :param pages: the number of random pages returned (max...
785aa1179113367c6f1e565c8a2ef1f092898f60
3,614,189
def xilogxi(x): """ x: scalar """ if 0 == x: return 0 else: return x*np.log(x)
3baf0e2165c7d8b290d46705f1f333c47227d573
3,614,190
import requests import logging def remove_ipfs(ipfs_hash): """ Removes pin from IPFS hash in Blockfrost """ ipfs_remove_url = f"https://ipfs.blockfrost.io/api/v0/ipfs/pin/remove/{ipfs_hash}" headers = {"project_id": f"{config.BLOCKFROST_IPFS}"} res = requests.post(ipfs_remove_url, headers=headers) ...
28b148b91a3943041d549bec7fa7ae590c40a4ab
3,614,191
import os def migrate_system_connections(src_sc: str, dest_sc: str) -> bool: """ Migrate the contents of a system-connections dir :param dest_sc: The system-connections to copy to. Will be created if it does not exist :param src_sc: The system-connections to copy from :return: Tru...
e8fbd5088d36d94f6c9ddb1cc571fb0049d8f3d6
3,614,192
def solution_list(request, cc_biz_id): """ 套餐列表 """ solution_list = Solution.objects.filter(cc_biz_id=cc_biz_id, ).order_by('-id') solution_types = dict(fta_std.SOLUTION_TYPE_CHOICES) now = timezone.now() last_week = now - timedelta(days=7) date_range = '%s to %s' % (last_week.strftime...
c18032502e268af54be0c3c8c408d9e33ce0f106
3,614,193
import sys def fasta2ids(faf, verbose=False): """ Extract IDs from a fasta file :param faf: fasta file :param verbose: more output :return: a set of IDS """ if verbose: sys.stderr.write(f"{bcolors.GREEN} Reading IDs from fasta file: {faf}{bcolors.ENDC}") f = read_fasta(faf, wh...
332259ef43a68fab408468dc300df1b7e0d7ec54
3,614,194
import platform def get_uname(): """Get uname.""" # Preferable to running a system command uname = " ".join(platform.uname()) return uname
18b7fc9ae6c51c0c5087ed67586a7fc358697405
3,614,195
import re def find_run_tap_log_file(stdout, sync_engine=None): """Pipelinewise creates log file per running tap instances in a dynamically created directory: ~/.pipelinewise/<TARGET_ID>/<TAP_ID>/log Every log file matches the pattern: <TARGET_ID>-<TAP_ID>-<DATE>_<TIME>.<SYNC_ENGINE>.log.<...
e6ddad6fc64574e9306188285d91033d28eae442
3,614,196
def _kim_cnn_model(params, args, nb_classes, embedding_matrix): """ fully functional API style so that we can see all model details. params will obtain model related parameters :param params: :param args: :param nb_classes: # of labels to classify :param embedding_matrix: :return: a com...
2cf777d0dfd9e6900776f0cf281010bc7d1d8bdf
3,614,197
def everything_except(excluded_types): """hypothesis utility to generate everything but the types in excluded_types""" return everything().filter(lambda x: not isinstance(x, tuple(excluded_types)))
e0b789cb8637e6bed2669f17cf33b4327a20d22c
3,614,198
def get_country_names() -> list[str]: """Return country names.""" return [country.name for country in get_countries()]
a3118df56f3fd18ca74a7047a4e91448e07a06db
3,614,199