content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import eazy.igm def simulate_eazy_sed_from_coeffs( eazycoeffs, eazytemplatedata, z, returnfluxunit='', returnwaveunit='A', limitwaverange=True, savetofile='', **outfile_kwargs): """ Generate a simulated SED from a given set of input eazy-py coefficients and eazypy templat...
41c975efa4136e9958c2b5680db2e6f9a67a4291
3,656,100
def get_timezones_all(): """Dump the list of timezones from ptyz into a format suitable for use with the Django Forms API's ChoiceField """ # TODO: Find a more user-friendly way of managing 500+ timezones output = [] for tz in all_timezones: output.append( (tz, tz) ) return output
e00bd0bc3321b9ab91526e67200ce3ef3629014a
3,656,101
def create_logistic_vector(input_vector, cutoff): """ Creates a vector of 0s and 1s based on an input vector of numbers with a cut-off point. """ output_vector = np.zeros(len(input_vector)) n = 0 for i in range(len(input_vector)): if input_vector[i] > cutoff: output_vector[i...
bb4756f745f56fae7d8d4f0b1a1758ef6d70fb5a
3,656,102
def profile(username): """ user profile """ user = User.query.filter_by(username=username).first_or_404() return render_template("user/profile.jinja.html", user=user)
31e2a1b108c0652356cea92f32e9077105733726
3,656,103
def action_rescale(action): """Rescale Distribution actions to exp one""" return np.array([0 if abs(a) < 0.5 else 10 ** (a-3) if a > 0 else -(10 ** (-a - 3)) for a in action * 3])
534509b76410eaeadee599e1ac510def8243e7ba
3,656,104
def multi_knee(points: np.ndarray, t1: float = 0.99, t2: int = 3) -> np.ndarray: """ Recursive knee point detection based on the curvature equations. It returns the knee points on the curve. Args: points (np.ndarray): numpy array with the points (x, y) t1 (float): coefficient of determ...
ee44d9f51c843a0fb8e18f10057b5c6510dd8f3a
3,656,105
def parse_dotted_path(path): """ Extracts attribute name from dotted path. """ try: objects, attr = path.rsplit('.', 1) except ValueError: objects = None attr = path return objects, attr
4685fad6461286b957a8d0056df2146fdd0f2e55
3,656,106
def resource_media_fields(document, resource): """ Returns a list of media fields defined in the resource schema. :param document: the document eventually containing the media files. :param resource: the resource being consumed by the request. .. versionadded:: 0.3 """ media_fields = app.confi...
b54bc5f7fd35626866d70ce6d46bf0b84b9cf1b8
3,656,107
import os import logging def read_config_file(f): """Read a config file.""" if isinstance(f, basestring): f = os.path.expanduser(f) try: config = ConfigObj(f, interpolation=False, encoding='utf8') except ConfigObjError as e: log(LOGGER, logging.ERROR, "Unable to parse line {0...
7dd67233c8ab1a09568b0cca143a96e27ba15722
3,656,108
from typing import List from typing import Tuple def _parse_moving(message: List[str]) -> Tuple[Actions, str]: """Parses the incoming message list to determine if movement is found. Args: message: list of words in the player message Returns: a tuple of the action and direction """ short...
9785cbeb39dbc9ba980f605b648fb77855fe863d
3,656,109
def _Net_forward_all(self, blobs=None, **kwargs): """ Run net forward in batches. Take blobs: list of blobs to extract as in forward() kwargs: Keys are input blob names and values are blob ndarrays. Refer to forward(). Give all_outs: {blob name: list of blobs} dict. """ ...
f5b6acf347e4fb85e0148d2d176042559f93b6a1
3,656,110
def email_members_old(request, course_prefix, course_suffix): """ Displays the email form and handles email actions Right now this is blocking and does not do any batching. Will have to make it better """ error_msg="" success_msg="" form = EmailForm() if request.metho...
eeafa4d9c4ca0b0ad1b7ffaecceb03c188e02813
3,656,111
def Padding_op(Image, strides, offset_x, offset_y): """ Takes an image, offset required to fit output image dimensions with given strides and calculates the padding it needs for perfect fit. :param Image: :param strides: :param offset_x: :param offset_y: :return: Padded image """ ...
d3f046069a597f2d7e3204b543f1f60c8e1e5b23
3,656,112
def area_triangle(point_a: array_like, point_b: array_like, point_c: array_like) -> np.float64: """ Return the area of a triangle defined by three points. The points are the vertices of the triangle. They must be 3D or less. Parameters ---------- point_a, point_b, point_c : array_like ...
0c21ca96f8a6fd4d088cf0fa47a260b3bc582966
3,656,113
import os def file_exists(target, parse=False): """Checks if a file exists""" if parse: target = envar_parser(target) if os.path.isfile(target): return True else: return False
99332f2fd2d434a19372b453a6235f4f2d7f5ab3
3,656,114
def test_valid(line): """Test for 40 character hex strings Print error on failure""" base_error = '*** WARNING *** line in torrent list' if len(line) != 40: print(base_error, 'incorrect length:', line) elif any(char not in HEX for char in line): print(base_error, 'has non-hex digits...
ca6517a8dd622b07703b30af7842685b9b6d5865
3,656,115
def readIMAGCDF(filename, headonly=False, **kwargs): """ Reading Intermagnet CDF format (1.0,1.1,1.2) """ debug = kwargs.get('debug') cdfdat = cdf.CDF(filename) if debug: logger.info("readIMAGCDF: FOUND IMAGCDF file created with version {}".format(cdfdat.version())) if debug: ...
9d87de2c650b140cf42cab4814659cf842f4b5a5
3,656,116
def custom_formatter(code, msg): """ 自定义结果格式化函数 :param code: 响应码 :param msg: 响应消息 """ return { "code": code, "msg": "hello", "sss": "tt", }
59a7e3f9f03f9afc42b8faec6ebe23f5373d0bf0
3,656,117
def get_sampler_callback(rank, num_replicas, noniid=0, longtail=0): """ noniid: noniid controls the noniidness. - noniid = 1 refers to completely noniid - noniid = 0 refers to iid. longtail: longtail controls the long-tailness. - Class i takes (1-longtail) ** i percent of data. ...
05e526ba903ebd834f248d965253344136e8a8a8
3,656,118
def alloc_bitrate(frame_nos, chunk_frames, pref_bitrate, nrow_tiles, ncol_tiles): """ Allocates equal bitrate to all the tiles """ vid_bitrate = [] for i in range(len(chunk_frames)): chunk = chunk_frames[i] chunk_bitrate = [[-1 for x in range(ncol_tiles)] for y in range(nrow_tiles)] chunk_weight = [[1. for ...
1883f480852d49e63c0408c9ef0daeba9e50db6b
3,656,119
from typing import Collection from typing import Any def file_filter(extensions: Collection[str]) -> Any: """Register a page content filter for file extensions.""" def wrapper(f): for ext in extensions: _file_filters[ext] = f return f return wrapper
bef1a304497ffaac3f294607d8a393e505c1eb19
3,656,120
def epc_calc_img_size(reg_dict): """ Calcalute the output image size from the EPC660 sensor Parameters ---------- reg_dict : dict Returns ---------- int The number of rows int The number of columns in the image """ col_start, col_end, row_start, row_end ...
698b6ae6a99f8f9621c40ffaee2ab5ea5e584ce1
3,656,121
def simple_url_formatter(endpoint, url): """ A simple URL formatter to use when no application context is available. :param str endpoint: the endpoint to use. :param str url: the URL to format """ return u"/{}".format(url)
74f3e68fe10f7cc6bf8bfe81a7349a995bb79fa3
3,656,122
from typing import List def generate_service( name: str, image: str, ports: List[str] = [], volumes: List[str] = [], dependsOn: List[str] = [], ) -> str: """ Creates a string with docker compose service specification. Arguments are a list of values that need to be added to each section...
581e37e69d73ab5b6c0ac533bd91e7b5cb5187d9
3,656,123
def read_integer(msg=None, error_msg=None): """ Asks the user for an integer value (int or long) :param msg: The message, displayed to the user. :param error_msg: The message, displayed to the user, in case he did not entered a valid int or long. :return: An int or a long from the user. """ ...
c3067b436f57583b89ca02bff5e01802845ebf69
3,656,124
def set_async_call_stack_depth(maxDepth: int) -> dict: """Enables or disables async call stacks tracking. Parameters ---------- maxDepth: int Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async call stacks (default). """ return { ...
f3767d85dc12913b11c6b13bb66f866460198672
3,656,125
def percError(predicted, observed): """Percentage Error Parameters ========== predicted : array-like Array-like (list, numpy array, etc.) of predictions observed : array-like Array-like (list, numpy array, etc.) of observed values of scalar quantity Returns ======= ...
168affcb5af47563c15d27c6e662b0cf6411eca2
3,656,126
def _dict_eq(a, b): """ Compare dictionaries using their items iterators and loading as much as half of each into a local temporary store. For comparisons of ordered dicts, memory usage is nil. For comparisons of dicts whose iterators differ in sequence maximally, memory consumption is O(N). Exec...
68292489e4f6f8f213f4d17cf799052cb99ece37
3,656,127
from typing import Dict from typing import List def avoid_snakes(my_head: Dict[str, int], snakes: List[dict], possible_moves: List[str]) -> List[str]: """ my_head: Dictionary of x/y coordinates of the Battlesnake head. e.g. {"x": 0, "y": 0} snakes: List of dictionaries of x/y coordinates for e...
dcdd80522486ec1c6001aa8990f2bfaf88235ec1
3,656,128
from django.core.servers.basehttp import FileWrapper import zipfile import logging import os import tarfile import traceback def getChipZip(request, path): """Download the AutoPH file, converted to zip compression""" logger = logging.getLogger(__name__) path = os.path.join("/", path) try: nam...
af836e47967e830e1a36ade074bca655efc8fcbc
3,656,129
def m_unicom_online_time2_0(seq): """ 获取联通手机在网时长所对应的code :param seq: 联通在网时长区间 :return: code example: :seq: [0-1] :return 1 """ if not seq: return [] if seq[0] in ["[0-1]", "(1-2]", "[3-6]"]: seq = ["(0_6)"] elif seq...
4a242d76f3d2708b5ad590830156a44fd22e7267
3,656,130
def convert_config_gui_structure(config_gui_structure, port, instance_id, is_port_in_database, conf): """ Converts the internal data structure to a dictionary which follows the "Configuration file structure", see setup.rst :param config_gui_structure: Data structure used...
3f46a621261ba097918fb5b5d27bd7611910a623
3,656,131
def message_similarity_hard(m1, m2): """ Inputs: One dimension various length numpy array. """ return int(np.all(m1==m2))
8f649a295853c34d692fb96a0a7facbc82d67ddb
3,656,132
def identity_block(input_tensor, kernel_size, filters, stage, block): """ The identity_block is the block that has no conv layer at shortcut Arguments input_tensor: input tensor kernel_size: defualt 3, the kernel size of middle conv layer at main path filters: list of integers, the n...
38a898a3b52f12490584206dfa6ea6b9819a1240
3,656,133
def convert_to_squad(story_summary_content, question_content, set_type): """ :param story_summary_content: :param question_content: :param category_content: :param set_type: :return: formatted SQUAD data At initial version, we are just focusing on the context and question, nothing more, ...
5b884ef521af4d5835fef25f01cb1f11d68cfafb
3,656,134
import select import time import sys import os def push_output(process, primary_fd, out_buffer: TextBuffer, process_state: ProcessState, is_interactive_session: bool, on_error: callable): """ Receive output from running process and forward to streams, capture :param process: :param p...
accb4fa66d8746766b4552c09d22b3d2fd3502c0
3,656,135
def check_conditions(conditions, variable_dict, domain_dict, domain_list): """A function that checks if the generated variables pass the conditions and generates new ones until they do. :param conditions: The conditions of the template. :param variable_dict: List of variables. :param domain_dict: the do...
fffd9889d3c149f56041753522aee245135cf0ee
3,656,136
def set_pin_on_teaching_page(request, section_label, pin=True): """ if pin=True, pin the section on teaching page if pin=False, unpin the section from teaching page @except InvalidSectionID @except NotSectionInstructorException @except Us...
385940e3adc286a923a94a3205b56c3817ee6284
3,656,137
from typing import Any def inject_python_resources() -> dict[str, Any]: """ Inject common resources to be used in Jinja templates. """ return dict( isinstance=isinstance, zip=zip, enumerate=enumerate, len=len, str=str, bool=bool, int=int, ...
98fb7fbf39f20b9972ef5c0d35ae12b2864580b2
3,656,138
def get_feature_subsets_options(study, data_types): """Given a study and list of data types, get the relevant feature subsets """ feature_subsets = ['custom'] if 'expression' in data_types: try: feature_subsets.extend(study.expression.feature_subsets.keys()) except Attrib...
d9310f00ff001f5ddc643998c7544df6ba5382b5
3,656,139
import json def possibilities(q=0, *num): """ :param q: Número de quadrados a considerar :param num: Em quantos quadrados a soma do nº de bombas é 1 :return: pos -> Possibilidade de distribuição das bombas tot -> Número de quadrados nos quais só há uma bomba i -> Início da contagem dos qua...
94c126a1bacf5bb242ad2935f949ab146f847001
3,656,140
import re def parse_page_options(text): """ Parses special fields in page header. The header is separated by a line with 3 dashes. It contains lines of the "key: value" form, which define page options. Returns a dictionary with such options. Page text is available as option named "text". ...
b90b1adb7d5d6f8716b9d4e00b0e4b533393f725
3,656,141
def _read_16_bit_message(prefix, payload_base, prefix_type, is_time, data, offset, eieio_header): """ Return a packet containing 16 bit elements """ if payload_base is None: if prefix is None: return EIEIO16BitDataMessage(eieio_header.count, data, offset) ...
b552d06b314d47ee3ae928ebcee678c65bd24f84
3,656,142
def test_linear(): """ Tests that KernelExplainer returns the correct result when the model is linear. (as per corollary 1 of https://arxiv.org/abs/1705.07874) """ np.random.seed(2) x = np.random.normal(size=(200, 3), scale=1) # a linear model def f(x): return x[:, 0] + 2.0*x[:, 1...
6e716d6505162aa49507b026672455d357ab7c2b
3,656,143
def csm_shape(csm): """ Return the shape field of the sparse variable. """ return csm_properties(csm)[3]
a74357086a9d7233cabed1c6ddc14fdbdbe0b41f
3,656,144
def hyperlist_to_labellist(hyperlist): """ :param hyperlist: :return: labellist, labels to use for plotting """ return [hyper_to_label(hyper) for hyper in hyperlist]
9587694d783ccbd122b58894a2d80ee5e58dc900
3,656,145
import json def _pretty_print_dict(dictionary): """Generates a pretty-print formatted version of the input JSON. Args: dictionary (dict): the JSON string to format. Returns: str: pretty-print formatted string. """ return json.dumps(_ascii_encode_dict(dictionary), indent=2, sort_k...
17e94d18f824253540fd968c726721542f25a95e
3,656,146
def _bivariate_kdeplot(x, y, filled, fill_lowest, kernel, bw, gridsize, cut, clip, axlabel, cbar, cbar_ax, cbar_kws, ax, **kwargs): """Plot a joint KDE estimate as a bivariate contour plot.""" # Determine the clipping if clip is None: clip = [(-np.inf, n...
ecb60ec3ffdc746f40b89158ef3c5b3a03e85bfc
3,656,147
import os import scipy def load_file(path): """ Load single cell dataset from file """ if os.path.exists(DATA_PATH+path+'.h5ad'): adata = sc.read_h5ad(DATA_PATH+path+'.h5ad') elif os.path.isdir(path): # mtx format adata = read_mtx(path) elif os.path.isfile(path): if p...
bed61b35bf6bf6777f3350d34e754cd80acca327
3,656,148
def unified_load(namespace, subclasses=None, recurse=False): """Provides a unified interface to both the module and class loaders, finding modules by default or classes if given a ``subclasses`` parameter. """ if subclasses is not None: return ClassLoader(recurse=recurse).load(namespace, subcla...
62f5f4e17d3d232bfa72090a836f89f782068b53
3,656,149
def generate_free_rooms(room_times: dict) -> dict: """ Generates data structure for getting free rooms for each time. """ # create data format free_rooms = {'M': {}, 'Tu': {}, 'W': {}, 'Th': {}, 'F': {} } #...
e60df355acd84e60c08ba34a45a2131d8d4519b4
3,656,150
def code_parse_line(li, pattern_type="import/import_externa"): """ External Packages """ ### Import pattern if pattern_type == "import": if li.find("from") > -1: l = li[li.find("from") + 4 : li.find("import")].strip().split(",") else: l = li.strip().split("impor...
347b3d0c3192978beb4c26a1950d86482812310b
3,656,151
def get_high(pair, path="https://api.kraken.com/0/public"): """ Get the last 24h high price of `pair`. Parameters ---------- pair : str Code of the requested pair(s). Comma delimited if several pair. path : str Path of the exchange to request. Returns ------- float or d...
8443ad24450e8f7bd2b6fac339e5e2b9149685c1
3,656,152
def SIx(): """ Reads in future LENS SI-x data Returns ---------- leafmean : array leaf indices (ens x year x lat x lon) latmean : array last freeze indices (ens x year x lat x lon) lat : array of latitudes lon : array of longitudes lstfrz : list last freeze indices """ ...
0ac033577d73c6567ebef10437a7e44e51bf5c79
3,656,153
import scipy def make_truncnorm_gen_with_bounds(mean, std, low_bound, hi_bound): """ low_bound and hi_bound are in the same units as mean and std """ assert hi_bound > low_bound clipped_mean = min(max(mean, low_bound), hi_bound) if clipped_mean == low_bound: low_sigma = -0.01 * std ...
8e957d99141a56f804bebf931098fa147d066bb8
3,656,154
from invenio_app_ils.ill.api import BORROWING_REQUEST_PID_TYPE from invenio_app_ils.ill.proxies import current_ils_ill from invenio_app_ils.items.api import ITEM_PID_TYPE from invenio_app_ils.proxies import current_app_ils from invenio_app_ils.errors import UnknownItemPidTypeError def resolve_item_from_loan(item_pid)...
f58ea857a445f2e6e01f426656f87a2032ea8306
3,656,155
import os def lascolor(strPathInLAS, strPathOutLAS, strPathTif, strAdlSwitches = None): """ Function lascolor args: strPathInLAS = input LAS file strPathOutLAS = output LAS file strPathTif = Tif source of RGB values strAdlSwitches = optional additional switc...
59400923bd0148a3659f7988596b1b7b2d4a70b6
3,656,156
def delta(s1, s2): """ Find the difference in characters between s1 and s2. Complexity: O(n), n - length of s1 or s2 (they have the same length). Returns: dict, format {extra:[], missing:[]} extra: list, letters in s2 but not in s1 missing: list, letters in s1 but not in s2...
e439b5a4cf634f5e53fbf845b5774342cedeb404
3,656,157
def mean_predictive_value(targets, preds, cm=None, w=None, adjusted=False): """ :purpose: Calculates the mean predictive value between a discrete target and pred array :params: targets, preds : discrete input arrays, both of shape (n,) cm : if you have previously calculated a confus...
9e7b7047d0dcf79509e544ca8bb0d621d1ce283d
3,656,158
def delta(phase,inc, ecc = 0, omega=0): """ Compute the distance center-to-center between planet and host star. ___ INPUT: phase: orbital phase in radian inc: inclination of the system in radian OPTIONAL INPUT: ecc: omega: // OUTPUT: distance center-to-center, doubl...
797d84618ade3e84b63a1a40e7728de77d5465ca
3,656,159
def theoritical_spectrum(peptide_sequence): """Returns the theoritical spectrum of a given amino acid sequence. INPUT : peptide_sequence: string. The peptide sequence to get its theoritical spectrum OUTPUT: .: List. The theoritical spectrum of the given peptide sequence. """ linear_...
1808daed80b553fe3a5a2b38e178956e4a0d7de0
3,656,160
def is_amazon(source_code): """ Method checks whether a given book is a physical book or a ebook giveaway for a linked Amazon account. :param source_code: :return: """ for line in source_code: if "Your Amazon Account" in line: return True return False
31c50622b4bb97a05d8cabb94c58f6e0a8f58971
3,656,161
import os import sys import subprocess def transdecodeToPeptide(sample_name, output_dir, rerun_rules, sample_dir, mets_or_mags = "mets", transdecoder_orf_size = 100, nt_ext = ".fasta", pep_ext = ".faa", run_transdecoder = False): """ Use TransDecoder to conve...
b22f520808104e4fc471c4af5a2288a5f23b84ae
3,656,162
def data_dim(p): """ Return the dimensionality of the dataset """ dataset_class = DATASETS[p.dataset] return dataset_class(p).get_in_dim()
25e32039733e8599c22d696f28bfffbf8b97cf02
3,656,163
import torch def create_supervised_evaluator(model, metrics=None, device=None, non_blocking=False, prepare_batch=_prepare_batch, output_transform= lambda x, y, y_pred: (y_pred, y,)): """...
2af4cc7b12a76c3c12940353a072d8b715fec8c1
3,656,164
import typing def historical_earning_calendar( apikey: str, symbol: str, limit: int = DEFAULT_LIMIT ) -> typing.Optional[typing.List[typing.Dict]]: """ Query FMP /historical/earning_calendar/ API. Note: Between the "from" and "to" parameters the maximum time interval can be 3 months. :param apike...
7f231b253ef4f462ab89826d58546a3259bdd3d2
3,656,165
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_query_tor_network] base_url = https://onionoo.torproject.org/details #The Flag can be 'Running','Exit' for more information on flag sett...
239436c9b2141e17f6158aab20d7951d79359fcd
3,656,166
def show_object_id_by_date( move_data, create_features=True, kind=None, figsize=(21, 9), return_fig=True, save_fig=True, name='shot_points_by_date.png', ): """ Generates four visualizations based on datetime feature: - Bar chart trajectories by day periods - Bar char...
18bbd54adfba6ecfd0959904d99698cfaac4b198
3,656,167
def raw_escape(pattern, unix=None, raw_chars=True): """Apply raw character transform before applying escape.""" return _wcparse.escape(util.norm_pattern(pattern, False, raw_chars, True), unix=unix, pathname=True, raw=True)
e4df84b21b737f199a7314818cc7f892f93be1b8
3,656,168
def interpolate_effective_area_per_energy_and_fov( effective_area, grid_points, target_point, min_effective_area=1. * u.Unit('m2'), method='linear', ): """ Takes a grid of effective areas for a bunch of different parameters and interpolates (log) effective areas to given value of those p...
58c32f49c96ed7ceb14e734f1386ef0015920204
3,656,169
def extract_edge(stats:np.ndarray, idxs_upper:np.ndarray, runner:int, max_index:int, maximum_offset:float, iso_charge_min:int = 1, iso_charge_max:int = 6, iso_mass_range:int=5)->list: """Extract edges. Args: stats (np.ndarray): Stats array that contains summary statistics of hills. idxs_upper ...
8101a024c20d169f470d4e6632272e0ad00c484b
3,656,170
def _neq_attr(node, attr, gens, container): """ Calcs fitness based on the fact that node's target shall not have an attr with a certain value. """ trg_nd = container.nodes[gens[node]] if attr[0] in trg_nd and attr[1] == trg_nd[attr[0]]: return 10.1 return 0.0
adfa39aa60d0777b2b05f174a9cf61a847e55b1d
3,656,171
def getItem( user, list, itempk ): """ Get a single item from a list. :param user: user who owns list :param list: list containing item :param itempk: private key of item :return: item or None """ itemType = list.itemType item = None if itemType == 'Item': ite...
f0d2c3a6d1881e0e1288aae451a556ebe856242e
3,656,172
def metric_divergence(neighborhood_vectors: np.ndarray, dL: float, polarity: int) -> float: """ Calculates the divergence of a sampling volume neighborhood. Note: For JIT to work, this must be declared at the top level. @param neighborhood_vectors: Sampling volume neighborhood vectors (six 3D vectors)...
87dd2b19c654143ed54f3783059ece50eb32ec71
3,656,173
import argparse def parse_args(): """ Parse command line arguments. Parameters: None Returns: parser arguments """ parser = argparse.ArgumentParser(description='LeNet model') optional = parser._action_groups.pop() required = parser.add_argument_group('required arguments') required.add_argument('--datase...
6a93e1083ebc8fad5f0698b2e0a4eb125af2806f
3,656,174
def tag(request): """ Add/Remove tag to email """ if request.is_ajax(): mail = request.POST.get("mail") tag = request.POST.get("tag") op = request.POST.get("op") mail = get_object_or_404(Mail, pk=mail) if op == "ADD": mail.tags.add(tag) elif op...
b1f5c2e65393be1d68a03b01c522214413e5b321
3,656,175
def sid_to_smiles(sid): """Takes an SID and prints the associated SMILES string.""" substance = pc.Substance.from_sid(sid) cid = substance.standardized_cid compound = pc.get_compounds(cid)[0] return compound.isomeric_smiles
e243e201a8ac4e4ee63332454a8b8c64f0f43692
3,656,176
def view_static(request, **kwargs): """Outputs static page.""" template = kwargs.get('template', None) if not template: raise Http404 template = '.'.join([template, 'html']) title = kwargs.get('title', 'static page') img = kwargs.get('img', 'bgag.jpg') return render_to_response(temp...
b6997e86175688f9b1293b0888faeb337bb5f3b6
3,656,177
def start_call(called_ident, skicall): """When a call is initially received this function is called. Unless you want to divert to another page, this function should return called_ident which would typically be the ident of a Responder or Template page dealing with the call. If a ServeFile excep...
0353d81273ea6638858bf18271f4480895ca1db1
3,656,178
def getmemory(): """ Returns the memory limit for data arrays (in MB). """ return NX_MEMORY
f6850ac2ad5854f9798ef480e9ca105bf31644ed
3,656,179
import this def get_object_syncing_state(): """ Get a dictionary mapping which object trackers are active. The dictionary contains name:bool pairs that can be fed back into the func:`set_object_syncing_state()` function. """ states = { "selection": bool(this._on_selection_changed_cb_id), ...
c6fa40e7945b8186db06cc00b461fc2fe6a16c36
3,656,180
def determine_nohit_score(cons, invert): """ Determine the value in the matrix assigned to nohit given SeqFindr options :param cons: whether the Seqfindr run is using mapping consensus data or not :param invert: whether the Seqfindr run is inverting (missing hits to ...
d0539b5ac4dda8b4a15c6800fb4a821cb305b319
3,656,181
def estimate_csd(lfp, coord_electrode, sigma, method='standard', diam=None, h=None, sigma_top=None, tol=1E-6, num_steps=200, f_type='identity', f_order=None): """ Estimates current source density (CSD) from local field potential (LFP) recordings from multiple depths of the ...
eefe158dc93d9d2be23f7754b658c1f812cd8524
3,656,182
def library_get_monomer_desc(res_name): """Loads/caches/returns the monomer description objec MonomerDesc for the given monomer residue name. """ assert isinstance(res_name, str) try: return MONOMER_RES_NAME_CACHE[res_name] except KeyError: pass mon_desc = library_construct...
98b4790995bd1d2eba96775e99826fae7b7cfc8a
3,656,183
def parse_single_sequence_example( serialized, context_features=None, sequence_features=None, example_name=None, name=None): # pylint: disable=line-too-long """Parses a single `SequenceExample` proto. Parses a single serialized [`SequenceExample`](https://www.tensorflow.org/code/tensorflow/core/example/e...
89309aab313b89224a87cb3cf7f4d56356981885
3,656,184
import scipy import os def getBase64PNGImage(pD, cmapstr, logfloor_quantile=0): """ Get an image as a base64 string """ D = np.array(pD) if logfloor_quantile > 0: floor = np.quantile(pD.flatten(), logfloor_quantile) D = np.log(D + floor) c = plt.get_cmap(cmapstr) D = D-np.m...
9fa7a41624d14943e48221e9277320324f575d33
3,656,185
import sys def method_dispatcher(*args, **kwargs): """Try to dispatch to the right HTTP method handler. If an HTTP method isn't on the approved list, defer to the error handler. Otherwise, the HTTP Method is processed by the appropriate handler. :param args: Expect arguments in format (http_metho...
7c680aae25de4b158db0befa0963923ddb903f8a
3,656,186
def _seqfix(ref_seq, seq, comp_len, rev): """ Fill or trim a portion of the beginning of a sequence relative to a reference sequence Args: ref_seq (str): reference sequence e.g. germline gene seq (str): sequence to compare to reference comp_len (int): length of s...
222ba3a8e2c4bced8ebcde6662890c10a0b41cf8
3,656,187
import torch from typing import Tuple def get_dedup_tokens(logits_batch: torch.Tensor) \ -> Tuple[torch.Tensor, torch.Tensor]: """Converts a batch of logits into the batch most probable tokens and their probabilities. Args: logits_batch (Tensor): Batch of logits (N x T x V). Returns: ...
885048842e6d1b50cd5b98c5b455aeb71e49c191
3,656,188
def com(im): """ Compute the center of mass of im. Expects that im is leveled (ie zero-centered). Ie, a pure noise image should have zero mean. Sometimes this is improved if you square the im first com(im**2) Returns: y, x in array form. """ im = np.nan_to_num(im) mass = np.sum(i...
5e1a7c20075df3fe5804213e5fdddd4f46d276c6
3,656,189
def get_fitting_custom_pipeline(): """ Pipeline looking like this lagged -> custom -> ridge """ lagged_node = PrimaryNode('lagged') lagged_node.custom_params = {'window_size': 50} # For custom model params as initial approximation and model as function is necessary custom_node =...
3ed78dc2f83110b0ac7dd4622a76511d0316404f
3,656,190
def get_regularizable_variables(scope): """ Get *all* regularizable variables in the scope. :param scope: scope to filter variables by :return: """ return tf.get_collection(REGULARIZABLE_VARS, scope)
67a6673be12af47128a453e413778f18f4344eaa
3,656,191
import glob def load(midi_path: str, config: dict): """ returns a 3-tuple of `tf.Dataset` each returning `(input_seq, target_seq)`, representing train, validation, and test portions of the overall dataset. `input_seq` represents the `inp_split` portion of each midi sequence in `midi_path`. """ batch...
38d890a78cf85ce43cbdb783246ef1a5e7e2cd06
3,656,192
import re def _parse_docstring(doc): """Extract documentation from a function's docstring.""" if doc is None: return _Doc('', '', {}, []) # Convert Google- or Numpy-style docstrings to RST. # (Should do nothing if not in either style.) # use_ivar avoids generating an unhandled .. attribut...
ff4e3ce300748c32c2e65129c381f1e74912f4a1
3,656,193
def extract_remove_outward_edges_filter(exceptions_from_removal): """ This creates a closure that goes through the list of tuples to explicitly state which edges are leaving from the first argument of each tuple. Each tuple that is passed in has two members. The first member is a string representing a sing...
543e5823b8375cbdec200988ea5dd0c4f2d23d05
3,656,194
import torch def ln_addTH(x : torch.Tensor, beta : torch.Tensor) -> torch.Tensor: """ out = x + beta[None, :, None] """ return x + beta[None, :, None]
77e556c41a33a8c941826604b4b595ea7d456f9a
3,656,195
def drude2(tags, e, p): """dielectric function according to Drude theory for fitting""" return drude(e, p[0], p[1], p[2], p[3])
8032c61df099f6c1ac671f2b81c3bb93d1f81317
3,656,196
def ParseFile(path): """Parse function names and comments from a .h path. Returns mapping from function name to comment. """ result = {} with open(path, 'r') as fp: lines = fp.readlines() i = 0 n = len(lines) while i < n: line = lines[i] m = MCRE.match(line) if m and not m.g...
6319137de084aaf366b28e76af52cc1911298d8b
3,656,197
from typing import Dict def get_records(data: Dict[_Expr, Dict], column_order): """Output data as a list of records""" def cell_callback(expr, i, val, spreadsheet_data): spreadsheet_data[-1].append(val) return spreadsheet_data def row_callback(spreadsheet_data): spreadsheet_data[-1...
8a8eb0e69c9dabe6dfc59c9b5637fdf4ee2d2dd1
3,656,198
import torch def support_mask_to_label(support_masks, n_way, k_shot, num_points): """ Args: support_masks: binary (foreground/background) masks with shape (n_way, k_shot, num_points) """ support_masks = support_masks.view(n_way, k_shot*num_points) support_labels = [] for n in range(sup...
e6d73dc93e1e0b54d805d9c8b69785168dd2621e
3,656,199