content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def exponential(max_iteration=1.0, min_transition=1.0, initial_radius=1.0): """ Return an exponential radius neighborhood function. f(iteration) = initial_radius * (min_transition / initial_radius)^(iteration / max_iteration) Keyword arguments: max_iteration -- maximum count of itera...
8f3a8789547ddb93cb884da04c92ecfef9daf5ed
3,611,730
def cal_newpath(dis_mat, path_new, cityNum): """ 计算所有路径对应的距离 :param dis_mat: 城市距离矩阵 ndarray :param path_new: 路径矩阵 ndarray :param cityNum: 城市数量 int :return: 动态规划最优路径 list """ dis_list = [] for each in path_new: dis = 0 for j in range(cityNum - 1): dis = dis_mat[each[j]][each[j + 1]] + dis...
2a4d733e9633a44da3d66d74d54b75efc165d8bf
3,611,731
def load_input(source): """load the input""" if isinstance(source, str): # pragma: no cover with open(source, 'r', encoding='utf8') as stream: return stream.read() else: data = source.read() if isinstance(data, bytes): return data.decode("utf8") retur...
fa0a9aac1854af59f400bf2344638c8fb4bee96d
3,611,732
def _compute_dci(x_recon, x): """Computes score based on both training and testing codes and factors.""" scores = {} importance_matrix, train_err = compute_importance_gbt( x_recon, x) assert importance_matrix.shape[0] == x_recon.shape[0] assert importance_matrix.shape[1] == x.shape[0] informativeness_...
047745df93d73e26578c1d7b7b0bb5e4165a1434
3,611,734
from typing import Dict from typing import Any def sample_sac_params(trial: optuna.Trial, octree_observations: bool = True, octree_depth: int = 4, octree_full_depth: int = 2, octree_channels_in: int = 7, octr...
63d57c7a8de0eb12f01b410ed33ba5b5beb4a725
3,611,735
import random def split_vertex_labels(num_vertices, proportion_censored, rng=None): """ Adapts tensorflow dataset to produce another element in the labels dictionary corresponding to whether the vertex is in the training or testing set. Parameters ---------- num_vertices: The number of vertices i...
63a3419ca171ef006041e12f3cb61b9c368262af
3,611,736
def table(): """Display base and representative InChI.""" if request.method == "POST" and request.form.get("nmr-inchi-table-data"): nmr_experiment_type = request.form.get("select-nmr-experiment") generate_nmr( nmr_experiment_type=nmr_experiment_type, records=RECORDS ) ...
29d5552418f98b79036df37446ae940f85873ed6
3,611,737
def PSO( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2020-05-19", **kwargs ) -> Graph: """Ret...
02d9f25998aba2154e8d921ce4667c8803f286df
3,611,738
def se_resnet152(num_classes): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(SEBottleneck, [3, 8, 36, 3], num_classes=num_classes) model.avgpool = nn.AdaptiveAvgPool2d(1) return model
95984b592f695e9423263f8c3cf0edb7fb07e541
3,611,739
def is_integer(mark_string): """Function to check if a supposed pk is an integer.""" try: mark_id = int(mark_string) except ValueError: return False return mark_id
1df4842906452cf5672584e5781e0e8a2d3b367d
3,611,740
def getCoordsAndSearchRadius(inputString): """getCoordsAndSearchRadius. Args: inputString: """ coords = {} ra = None dec = None radius = None sex = COORDS_SEX_REGEX_COMPILED.search(inputString) decimal = COORDS_DEC_REGEX_COMPILED.search(inputString) if decimal: ...
289e6153908ec0553c4560b18d8afd4e57aeebbc
3,611,741
def _extract_command_with_args(cmd): """Parse input command with arguments. Parses the input command in such a way that the user may provide additional argument to the command. The format used is this: command=arg1,arg2,arg3,... all the additional arguments are passed as arguments to the target ...
3db8aebab04e32f292e2956412bd81e7a07a471e
3,611,742
def filtered_secondary_files(unfiltered_secondary_files: dict) -> list: """ Remove unprocessed secondary files. Interpolated strings and optional inputs in secondary files were added to CWL in version 1.1. The CWL libraries we call do successfully resolve the interpolated strings, but add the ...
89c0906984ca634b8afc3dd4bdf2e9ccbbad504c
3,611,743
def get_P_rtd_hs(q_rtd_hs, e_rtd): """定格消費電力 (4) Args: q_rtd_hs(float): 温水暖房用熱源機の定格能力 (W) e_rtd(float): 当該給湯機の効率 Returns: float: 定格消費電力 """ return q_rtd_hs / e_rtd
61d4a7c2f26b979891936efd6db0195ca3b083b0
3,611,744
def registration_success(request): """ This view is called when the registration succeeded """ rcontext = RequestContext(request, {}) return render_to_response('auth/registration_success.haml', rcontext)
6fe87ed1559b7d0a54a380d543eeab1a6a4fc63b
3,611,745
def match_attr( src1, src2, attrlist=None ): """ extension: check that attributes listed are the same for each src input: string <OR> dict, string <OR> dict, list output: bool notes: input sources can be either paths to netcdf files or dicts {attr_name : attr_val}. if attrlist is None t...
4a6eb511dc90c85bc38fa2bd0caef1a85e1c2446
3,611,746
def slash_validator( epochs_ctx: EpochsContext, state: BeaconState, slashed_index: ValidatorIndex, config: Eth2Config, whistleblower_index: ValidatorIndex = None, ) -> BeaconState: """ Slash the validator with index ``slashed_index``. """ epoch = epochs_ctx.current_shuffling.epoch ...
da36f061397c3909427abc47a30b68e56ac819de
3,611,747
def biot_savart(loop_list, fov_min, fov_max, fov_n, points=None): """ Creates coil profiles for arbitrary loops, for use in multichannel shim examples that do not match spherical harmonics Args: centers (list): List of 3D float center points for each loop in mm normals (list): List of 3D...
1a116e3299131911bc1a6c19106518c56427efe4
3,611,749
def heatmap(data, row_labels, col_labels, ax=None, cbar_kw={}, cbarlabel="", **kwargs): """ Create a heatmap from a numpy array and two lists of labels. Arguments: data : A 2D numpy array of shape (N,M) row_labels : A list or array of length N with the labels for ...
5465a92df4edbc94e194a140b0a81b105be68953
3,611,750
def get_request(): """Get the current request from anywhere.""" request = request_accessor.send(None) if request: return request[0][1] return None
92853938db8d7f90551c6ce4febbfedbaccfa6db
3,611,753
def get_aligned_face_and_landmarks( im, face_cache, aligned_face_size=256, padding=(0, 0) ): """ get all aligned faces and landmarks of all images :param imgs: origin images :param fa: face_alignment package :return: """ aligned_cur_shapes = [] aligned_cur_im = [] for mat, point...
cdb0989a377c609945058e2903fbec15b94c64ce
3,611,754
def items_per_cart(customers, orders, data): """Return customers dataframe with an extra column containing the average of items_per_cart for each customer.""" mapper = customers_mapper(data) customers = customers.copy() orders = orders.copy() orders['customer_unique_id'] = orders['customer_id']....
8fdbdba3bfaaeaeaf89cafcaee0597cf626856d6
3,611,755
def getParameterDefinitions(): """Return ParameterDefinitionCollections for each appropriate ArmiObject.""" return {Block: _getBlockParams()}
502c909754b80c4e0bf40dd74a77e6b2c2df55e1
3,611,756
def check_fake_image_dataset(method): """A wrapper that wraps a parameter checker around the original Dataset(FakeImageDataset).""" @wraps(method) def new_method(self, *args, **kwargs): _, param_dict = parse_user_args(method, *args, **kwargs) nreq_param_int = ['num_images', 'num_classes', ...
11b140ca35b5f3f232c1d410671010c9351dd220
3,611,757
async def validation_exception_handler(request: Request, exc: RequestValidationError): """ Handling error in validating requests """ return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=get_error_response(request, exc) )
a05629d0853b9aadceebda568450373718bd5912
3,611,758
def cpo(total_cost, total_transactions): """Return the CPT (Cost per Order). Args: total_cost (float): Total cost of marketing. total_transactions (int): Total number of transactions. Returns: cpt (float) as total cost per order """ return total_cost / total_transactions
aaaaf5a96fcbef65e59591954bded1afa13f8c47
3,611,760
def convert_seq2seq_golds(indices, lengths, rlut, subword_fix=lambda x: x): """Convert indices to words and format like a bleu reference corpus. :param indices: The indices of the gold sentence. Should be in the shape `[B, T]`. Iterating though axis=1 should yield ints. :param lengths: The length o...
152385efd2354486d2e069c9ac80f27032672c70
3,611,761
def advanced_raster_scan(ny=10, nx=10, fast_axis=1, mirror=[1, 1], theta=0, dy=1, dx=1): """ Generates as raster scan. Parameters ---------- ny, nx : int Number of steps in *y* (vertical) and *x* (horizontal) direction *x* is the fast axis dy, dx : float Step size (grid...
f3c54a605956c4373654fb466e6b0493048160a0
3,611,764
def command(func): """Decorator to register a fn as an available command.""" if func.__name__ not in COMMANDS: COMMANDS.append(func.__name__) return func
5ed35f6fe82751c95969cd43e5ef2fe3f6fc3dcf
3,611,765
def dendrogram( df, method='average', filter=None, n=0, p=0, orientation=None, figsize=None, fontsize=16, label_rotation=45, ax=None ): """ Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as a `scipy` dendrogram. The default vertica...
f2f8838547df8c0112e65ff1f6bfb0687f86730b
3,611,766
def intervalrecordlookup(table, start='start', stop='stop', include_stop=False): """ As :func:`petl.transform.intervals.intervallookup` but return records instead of tuples. """ tree = recordtree(table, start=start, stop=stop) return IntervalTreeLookup(tree, include_stop=include_stop)
cc1941e96a0affabcebabb2e39b34b65aa12cb10
3,611,767
def Convert2targetSeqView( sampleName, sampleBamName, sampleSplitBamName, vcfFile, outputDir, outputFileName): """This ``converts`` the Delly Vcf file having tumor normal, to tab-delimited format for input to targetSeqView :param str sampleName: str for the name...
c2d13107f0e142a17fb10d1933bbed17e17e24ea
3,611,768
def max_valued_dose_dependent_assertion_to_jtms(ev, s, a, ac): """ convert this continous valued DIKB assertion to a JTMS assertion that includes the dose used in the study/experiment @param ev:an instance of EvidenceBase containing Assertions instances @param s:string - representation of the assertion ty...
6e8312112fa9022d966aca0da6808df7393fa173
3,611,769
import re def create_user(): """注册新用户""" data = request.get_json() if not data: return bad_request('Please post json data.') message = {} if 'username' not in data or not data['username']: message['username'] = 'Please provide a valid username.' pattern = '^(([^<>()\[\]\\.,;:\...
97629ef053c298a679dd46f820f76ba49056620f
3,611,770
def rebin_1darray(a, shape, function='sum'): """Rebin an array into a new shape by making the sum or mean """ sh = shape,a.shape[0]//shape if function == 'mean': return a.reshape(sh).mean(-1) elif function == 'sum': return a.reshape(sh).sum(-1) else: print("WARNING: doing...
66de60326e081c27aae471281c79c5e86f5180e3
3,611,771
def affine(src, dst, rcond=1e-6): """Estimate the best affine matrix by least-squares in target space. The implementation is specific to 3-dimensional source and target spaces, but could be generalized easily. """ assert src.shape[1] == dst.shape[1] == 3 flat_dst = dst.flatten(order="C") # ord...
a9d59339813fd0e37e51262a8f13e7af7e4a7918
3,611,772
def get_ground_truth(obj, image, question): """ Get the ground truth value for the image/question combination in reader study obj. """ ground_truths = obj.statistics["ground_truths"] return ground_truths[image][question]
522b5550344891e0985bacb9c763c4c52686cb67
3,611,773
def eval_math(math, compiled_math, workspace): """ Compile a mathematical expression Args: math (:obj:`str`): mathematical expression compiled_math (:obj:`_ast.Expression`): compiled expression workspace (:obj:`dict`): values to use for the symbols in the expression Returns: ...
deeaefa52a048bf218874614062f8e6e43b9e389
3,611,776
def LF_CD_PARENTHETICAL_DESC(c): """ This label function looks for mentions that are in paranthesis. Some of the gene mentions are abbreviations rather than names of a gene. """ if ")" in c[1].get_span() and "(" in list(get_left_tokens(c[1], window=1)): if LF_CD_DISTANCE_SHORT(c): ...
d4cf44b27cf8ee2139173096a39328c2d841dd96
3,611,777
def _declare_clang_library_target_files( ctx, target, build_config_path, clang_custom_info): """Declares the outputs for a clang module and returns a struct value describing the clang module. Args: ctx: A `ctx` instance. target: A target `dict` from the package d...
faf39325495eadc5cb775c4ed97f28e871ac8598
3,611,778
def is_pandas_df(obj): """Check if an object is a Pandas dataframe The benefit here is that Pandas doesn't have to be included in the dependencies for pydeck The drawback of course is that the Pandas API might change and break this function """ return obj.__class__.__module__ == 'pandas.core.f...
aa226f86d8640903fef4e51121e285ba9c594a3c
3,611,779
def time(days=0, seconds=0, minutes=0, hours=0, **kwargs): """ Returns a Time that can be added to a Date object. Other parameters: microseconds, milliseconds, weeks, months, years. """ return Time(days=days, seconds=seconds, minutes=minutes, hours=hours, **kwargs)
3e39559a4f9d9a2da9bc97489a4c1a8582533883
3,611,782
def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) # output: [B, d] _, pred = output.topk(maxk, 1, True, True) pred = pred.t() # pred: [B, len(topk)] -> [len(topk), B] # target.reshape(1, -1)...
f8dd618922056eafb7aa1e856137c6a0ea7a3c6e
3,611,783
def password_login(request): """ 客户端用户使用密码登录 :param request: :return: """ print('api:password_login') if request.session.get(USER_SESSION_KEY): print("###api:password_login request.session.session_key已经存在: ", request.session.session_key) return fail(ResultCode.COMMONERR, "失败:...
f2e794d188d485385170d2e0ae8c5a192a384896
3,611,784
def gen_node_color_map(table_column, palette = {'d': palette_color_brewer_q_Set2(), 'c': (palette_color_brewer_s_GnBu(), palette_color_brewer_d_RdYlBu())}, mapping_type='c', default_color=None, ...
08fe825e3901cb21c39ea7c32ea6c023b9e50a0f
3,611,786
def unpack_qubit(qubit): """ Get a qubit from an object. :param qubit: An int or Qubit. :return: A Qubit instance """ if isinstance(qubit, integer_types): return Qubit(qubit) elif isinstance(qubit, Qubit): return qubit elif isinstance(qubit, QubitPlaceholder): re...
27f6dd2598bf2cc052849bbf032f4d1cdf545058
3,611,787
def solve(f, x0): """ Solve the equation f(x) = x using a fixed point iteration. x0 is the start value. """ x = x0 for n in range(10000): # at most 10000 iterations oldX = x; x = f(x); if abs(x - oldX) < 1.0e-15: return x;
d5f5409d689c842c1a8c70b95c621360c9ae7c8c
3,611,788
import datasets def mi_estimate(y_real, gen, enc, masks, k, batch_size, z_dim, s_dim, z_trans = None): """Estimates the MI of the encoder. Args: y_real: s_I gen: generator, (z -> x^) enc: encoder, (x^ -> dist(z^)) masks: for sampling z_\I from the prior k: number o...
68e0d902145ba1eec6d02b195a56413f9feebe4e
3,611,790
from application.plotlydash.dashboard import create_dashboard from application.assets import compile_assets import sqlite3 def create_app(): """Construct core Flask application with embedded Dash app.""" app = Flask(__name__, instance_relative_config=False) app.config.from_object('config.Config') wit...
fb1cd994477f7cddd1852edad3d28b685cc69892
3,611,791
def _transformer_configs(c: Configs): """ ### Transformer configurations """ # We use our # [configurable transformer implementation](../configs.html#TransformerConfigs) conf = TransformerConfigs() # Set the vocabulary sizes for embeddings and generating logits conf.n_src_vocab = c.n_to...
6cc7d72cef9a1f607b6f0e712f0a3792247892c2
3,611,792
def te_diff_template(ruletype): """ This is a template for the type_* diff functions. Parameters: ruletype The rule type, e.g. "type_transition". """ def diff(self): """Generate the difference in rules between the policies.""" self.log.info( "Generating {0} dif...
d2f5b2eca127be8c991ac0c49027bce9c01ee3a2
3,611,793
def normalize(v1, Rmin=1.0e-8, Rmax=1.0e15): """ Do not normalize in place. Not supported in autograd """ n = norm(v1) if n < Rmin or n > Rmax: print('vector:', v1) print('norm:', n) raise Exception("Could not normalize vector. Vector norm beyond tolerance") else: ...
dddc57693472e5a72ab3caed5e592fd859a4b64e
3,611,794
import re def find_version() -> str: """Only define version in one place.""" version_file = read_file("__init__.py") version_match = re.search(r'^__version__ = ["\']([^"\']*)["\']', version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find versi...
8bbd0c331eef2a1918f0fcf0ce63127396e40681
3,611,796
def p2_allocateByScore(CCA, nameCat, quota, rank, scorelist, final_dic, CCA_dic): """ Allocates students to cca where applicants exceed quota Returns the final dictionaries """ cat = "" for key, value in nameCat.items(): #theoretically it will all be the same anyway cat = value quot...
de0ec96eadf396319a7dfbb3942a6917afc6c84c
3,611,797
def _total_solves(color_info): """ Return total number of linear solves required based on the given coloring info. Parameters ---------- color_info : dict dict['fwd'] = (col_lists, row_maps) col_lists is a list of column lists, the first being a list of uncolored columns. ...
32031f2ba834f7d6ed310b0a71ab43884b424459
3,611,798
def generat_int_pop(n_particles,n_vars,low_bounds,up_bounds): """ Generate initial population function. Here, random values between the lower and the higer bounds are defined for the initial population: x1^j = rand[xlb^j, xub^j] Parameters: n_particles: int Number of partic...
27afd97b45b74135633d133ee7ff1163898bf1b8
3,611,799
def gettext(msg, domain='python-apt'): # real signature unknown; restored from __doc__ """ gettext(msg: str[, domain: str = 'python-apt']) -> str Translate the given string. This is much faster than Python's version and only does translations after setlocale() has been called. """ return ""
a6d83a79110ec233f86878fc6aa9f37f2b3e61fa
3,611,801
def as_sparse_or_tensor_variable(x, name=None): """ If we can't make a sparse variable, we try to make a tensor variable. """ try: return as_sparse_variable(x,name) except (ValueError, TypeError): return theano.tensor.as_tensor_variable(x,name)
4e9560dc48bd0388b376b9ee29b303850b8ad2e1
3,611,802
def freeze(slug): """ Prevent a builder from updating it's source code to a newer version. The software will still be re-built if it's dependants are upated. """ freeze_file = settings.get('install_path') + 'etc/build-freeze' return file_filter.AppendUnique(freeze_file, slug).run()
e08b0146fc5c4eafaeba689a3aaf1dff04c06192
3,611,803
def get_compressor(alg): """Return an instance of a compressor This function returns an object that can be used for data compression. """ return _cmp_compressors[alg]()
a40274f069b2fb7bf5afc05efb10b39d5cea5179
3,611,804
import json import uuid import time def confirm(self, speech, timeout): """ Start the view 'confirm' :param speech: the text that will be use by the Local Manager for tablet and vocal :type speech: dict :param timeout: maximum time to wait for a reaction from the local manager :type timeout: ...
41a1061879dc14f32a567bb4860195221385609a
3,611,805
def generateAdjMatrix(edgeJsonList, sent_len): """ Function to generate Adjacency matrix from Depedency Parse Tree """ sparseAdjMatrixPos = [[], [], []] sparseAdjMatrixValues = [] deptags = [] gov_words = [0] * sent_len adjMatrix = [0] * sent_len for i in range(sent_len): adjMa...
ca8af1991b072c334cab20c317a3cb2e00d8f67f
3,611,806
import operator def assert_no_duplicate_router_ids( snapshot=None, nodes=None, protocols=None, soft=False, session=None, df_format="table", ): # type: (Optional[str], Optional[str], Optional[List[str]], bool, Optional[Session], str) -> bool """Assert that there are no duplicate router ...
51d987ece746ea481fa39490aba364765512ce5f
3,611,807
from typing import Generator def de_bruijn(alphabet: bytes, n: int) -> Generator[str, None, None]: """De Bruijn sequence for alphabet and subsequences of length n (for compat. w/ pwnlib).""" k = len(alphabet) a = [0] * k * n def db(t: int, p: int) -> Generator[str, None, None]: if t > n: ...
bc647a3e140a81c47703eaa2216d49e0aa78f088
3,611,809
def writexl_alt_getsheetref(path_wbrels, path_wb): """ Takes a file path for '/xl/_rels/workbook.xml.rels' and '/xl/workbook.xml' files and returns a dictionary relationship between sheetID, name and xml worksheet file path rId: xml's indexing between files (workbook.xml.rels defined rID to xml work...
84852fc99897b471834ce3a9dc721e18b41047e1
3,611,810
import re def createPattern(string): """Cria um padrão de comandos de bot.""" return re.compile(f"/{string}|{string}")
b2b013dc71d5f49f041402ecf98db8b923f4d22a
3,611,811
def gnomad_filtered_func(raw_value): """ We use FILTER in Gnomad3 (GRCh38 only) - need to convert back to bool """ return raw_value not in (None, "PASS")
6de1d4ef9395e89c11b08cdb43decb045656494b
3,611,813
from bs4 import BeautifulSoup def parse(html_bytes: bytes, *args, **kwargs) -> BeautifulSoup: """Convenience method for ``ZimHtmlParser(html_text).simplify()``.""" return ZimHtmlParser(html_bytes, *args, **kwargs).simplify()
2b1c711a9ead749e0e8b6279e4861c29b97aa968
3,611,814
def register(name): """Registers a new logs preprocessor function under the given name.""" def add_to_dict(func): _PREPROCESSORS[name] = func return func return add_to_dict
a07008f74ea4a93a6763d1062c78d50a64d9614e
3,611,815
import torch def _project_z(z, project_method='clip'): """To be used for projected gradient descent over z.""" if project_method == 'norm': z_p = torch.nn.functional.normalize(z, p=2, dim=-1) #elif project_method == 'clip': #not reimplemented yet # z_p = tf.clip_by_value(z, -1, 1) else: raise Value...
6cabb462dcbfff7ffdc065601f4a68671822f93f
3,611,817
from datetime import datetime def __dirnames_matching_format(dirnames, format): """ Iterates through dirnames and returns a sorted array of directory names that match the provided format. """ matching_dates = [] for dirname in dirnames: try: dt = datetime.strptime(dirname, ...
52349f0992a0ac0366d75f5328f674ab179246be
3,611,818
import re def solve(s): """doc""" return "".join([w.capitalize() for w in re.split(r"(\W+)", s)])
28f075dd47c3ec57d6bb2a1675ae77815378786e
3,611,819
import requests def marco_china_hk_trade_diff_ratio() -> pd.DataFrame: """ 东方财富-经济数据一览-中国香港-香港商品贸易差额年率 https://data.eastmoney.com/cjsj/foreign_8_7.html :return: 香港商品贸易差额年率 :rtype: pandas.DataFrame """ url = "https://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { ...
7d60526def9c00944638b80311dbbd6913a11ca2
3,611,820
from typing import Optional def make_default_sim_env( interface: Optional[GymTrainedInterface] = None, ) -> CustomSimEnv: """ A simulator environment with the following characteristics: The action and observation spaces are continuous. An action in this environment is a pilot signal for each EVSE, ...
e023dc37fc81fb8d5e17f87d66b3035e9909a3aa
3,611,821
from iris.cube import Cube from iris.coords import DimCoord def make_dummy_1d_cube(job_n=0): """ Makes a dummy 1d cube filled with dummy data. It has a scalar job coordinate to make ensemble stacking convenient """ x = np.arange(100) y = np.sin(x) * np.cos(x + 0.3) obs = DimCoord(x, var_...
992251299f13bbfa7581f647602a349b98547635
3,611,822
def edit_delivery(request, delivery): """Edit a delivery as a full network admin: act upon its lifecycle, control which subgroups have been validated, change the products characteristics, change other users' orders.""" dv = m.Delivery.objects.get(id=delivery) if dv.network.staff.filter(id=request.user.i...
7d807af78d2b063555a529a525295352513af919
3,611,823
def get_fields_by_name(model_cls, *field_names): """Return a dict of `models.Field` instances for named fields. Supports wildcard fetches using `'*'`. >>> get_fields_by_name(User, 'username', 'password') {'username': <django.db.models.fields.CharField: username>, 'password': <django.d...
8ce9c845adbff9bb53da50c7d7e208aa8077e718
3,611,824
def pyramidnet110_a84_svhn(num_classes=10, **kwargs): """ PyramidNet-110 (a=84) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- num_classes : int, default 10 Number of classification classes. pretrained : bool, default Fal...
085571ae5ab102de5e1bdeab100d6244608f899a
3,611,825
def list_of_comments(fname) : """Returns list of str objects - comment records from file. - fname - file name for text file. """ #if not os.path.lexists(fname) : raise IOError('File %s is not available' % fname) f=open(fname,'r') cmts = [] for rec in f : if rec.isspace() : conti...
5aea0668c006b4a4615cab01acd07db8dc1fb2b5
3,611,826
def publish_branch(branch): """Publishes given branch.""" repo_check() return repo.git.execute([git, 'push', '-u', remote.name, branch])
7335704d94efdc5dfba65dab914ab75a70bc24d9
3,611,827
import base64 def pil_to_base64(pilimage): # pragma: no cover """Returns base64 encoded image given a PIL Image""" buffer = BytesIO() pilimage.save(buffer, "png") return base64.b64encode(buffer.getvalue()).decode()
9c2673b97a86544c5281cbd43ff6dfdad31a4253
3,611,828
def save_result(x,time,lev,copy_from_source,dflt_units='k'): """Saves results from projection in netcdf output format. Input parameters: x: projection indices (2dim array with time,mode) time: coordinates from input netcdf file lev: level coordinates (PCA modes) copy_from_s...
704eb922bf8ccb4f8669df5ee0cf6b134ed4b55c
3,611,829
def linkcode_resolve(domain, info, author, package): """Determine the URL corresponding to a Python object.""" try: module = import_module(info["module"]) except ModuleNotFoundError: # No URL is returned when the object is not in # any module, or the module cannot be imported ...
ec849260610890510f0686ab4b1150eb30efe99c
3,611,831
def _max(self, dim=None, keepdim=False): """Map of 'max' pytorch method.""" x = self dim_orig = dim if dim is None: dim = _build_fwd_tuple(x.shape) elif isinstance(dim, int): dim = (dim,) dim = _dim_tuple_explicit(x.shape, dim) ret_max = P.array_max(x, dim) ret_argmax =...
ecf96de331d24b0b692c12fa24269fb9863121bb
3,611,832
import re def minify(source): """ Removes comments from the source code """ multiline = re.compile("(/\*.*?\*/)", re.DOTALL) singleline = re.compile("//.*?\n") remove_multiline = lambda f: re.sub(multiline, "", f) remove_singleline = lambda f: re.sub(singleline, "", f) return map(remove_multiline, ...
3743e4071485d1ae085037a4bf4cd492f4f81d29
3,611,834
def configmap_data_keys(): """ Build keys for the ``data`` mapping of a ``ConfigMap``. """ return builds( lambda labels, dot: dot + u".".join(labels), labels=lists(object_name(), average_size=2, min_size=1, max_size=253//2), dot=sampled_from([u"", u"."]), ).filter( la...
4c88839707f37cfb334f6bedce080b4f97a84c58
3,611,835
from typing import Callable from typing import Any def handler_assertions( handler_name: str, test_case: str, error_name: str = None, ) -> Callable: """Configurable decorator for testing assertions for a given handler""" def decorator_function( decorated_function: Callable...
7abb8776e029c330c0ad4b060bdf8e0c1ea3af35
3,611,836
import random def create_bitmap_dataset(bitmap_data, output_dir, output_name, classnames, output_shards): """ Writes the provided bitmap_data as tf.Example in tf.Record :param bitmap_data: tuple of lists containing (x_train, y_train, x_test, y_test) :param output_dir: path where to write the outp...
050fe1ed5a66cf49741d24e21062fadba08a0c7c
3,611,837
import logging def with_logger(cls): """Class decorator to add a logger to a class.""" attr_name = '_logger' cls_name = cls.__qualname__ module = cls.__module__ if module is not None: cls_name = module + '.' + cls_name else: raise AssertionError setattr(cls, attr_name, logg...
77f854ac6d1cbe95ff7804184a1a67a513ac81ae
3,611,838
import itertools def _generate_mesh_simplices( *, limits, mesh_size, periodic=False, skip_origin=False ): """ Generate the starting simplices for given limits and mesh size. """ dim = len(limits) if len(mesh_size) != dim: raise ValueError( "Inconsistent dimensions: ...
7b2008906aaafb411c22128ffcdd4f2ce1c13471
3,611,839
def write_tfrecords(data_path,video_paths,action_labels, n_vids_per_batch,subset, n_frames_batch = 16, n_frames_chunk = 512): """Function to write tfrecords. :param data_path: name of tfrecords file to write :param video_paths: list contain...
4c6e27a2cc9a2079a8f2828d288ea65542b8e56a
3,611,840
def _set_up_thermo_mets(base_df: pd.DataFrame, mets_list: list, mets_conc_df: pd.DataFrame) -> tuple: """ Given the base excel input file, the list of metabolites in the model and a dataframe with metabolite concentrations averages and respective stdev, fills in the thermoMets sheet. First fills in conc...
c048a6c220de7055f5cb5ce0a65f969b3d0a9be7
3,611,841
def setup_constant(prefix, **kwargs): """ Set up a simple constant function model. :param prefix: Model prefix :type prefix: string :param kwargs: Keyword arguments :return: LMFIT model and parameters :rtype: (lmfit.Model, lmfit.Parameters) """ amplitude = kwargs.pop('amplitude', 5) ...
3d0c24887e81c34b499190a79185822fef641bd8
3,611,842
def subapp_css_static(filename): """ set css files. :param filename: css file name. :return: static path. """ return static_file(filename, root='kokemomo/plugins/subapp/view/resource/css')
bf29bc7a7f9cbab9e2db3da0841eab018c57d96b
3,611,843
def graph1D(n: int, pbc: bool = True) -> Graph: """ 1D PBC chain with n sites :param n: :return: """ g = nx.Graph() for i in range(n): g.add_node(i) for i in range(n - 1): g.add_edge(i, i + 1, weight=1.0) if pbc is True: g.add_edge(n - 1, 0, weight=1.0) ...
fdb809ee46c7b9d7ebdd241175e199db747f9227
3,611,844
def _solve_triangular_right(a, b, left_side, lower, trans_a): """An unrolled right-looking triangular solve on (blocked) LapaxMatrices.""" n = a.shape[-1] def solve(a, b): return _solve_triangular_left(a, b, left_side, lower, trans_a) if n == 1: return solve(a.bview(1), b.bview(1)) out = full_like(...
1dc6826bfb717a8b162bd2a5d997368276ae0b47
3,611,845
from numpy import linspace, meshgrid def _get_latlons(nlat, nlon): """Short summary. Parameters ---------- nlat : type Description of parameter `nlat`. nlon : type Description of parameter `nlon`. Returns ------- type Description of returned object. """ ...
f43553b4f758ac2a060f609e2781645b79466cb4
3,611,846
def abs(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.abs <numpy.abs>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in abs") return Array._new(np.abs(x._array))
cb37d3486fd82535de77f4df56a30c7e713127b9
3,611,847
def challenge_hash(peer_challenge, auth_challenge, user_name): """ RFC 2759 section 8.2 ChallengeHash :param peer_challenge: :param auth_challenge: :param user_name: :return: challenge example peer_challenge = "\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x5F\x2B\x3A\x33\x7C\x7E" ...
153f33509e09ea140433d6ef46aab2225bbb5808
3,611,848
def var_historic(r, level=5): """ Returns the historic Value at Risk at a specified level i.e. returns the number such that "level" percent of the returns fall below that number, and the (100-level) percent are above """ if isinstance(r, pd.DataFrame): return r.aggregate(var_historic, le...
dd2b23c15b7aee470886621ba8d64bee571488f9
3,611,849