content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def notebook(request, id=0): """ :param request: :param id: :return: """ get_notebook = JupyterNotebooks.objects.get(id=id) return render(request, "customdashboard/notebook.html", {'get_notebook': get_notebook})
3d1e3880182f6c8d507391fc66a9c0b41f18e3bc
8,200
def encrypt_decrypt(data_string, password, mode='encrypt'): """Encrypts OR Decrypts data_string w.r.t password based on mode specified Parameters: data_string: Text that needs to be encoded. passed in string format password: a string to encrypt data before encoding into an image. mo...
c0ecdf2009fe1b40cb9ed86e12904e241eb5ea86
8,201
def compute_alphabet(sequences): """ Returns the alphabet used in a set of sequences. """ alphabet = set() for s in sequences: alphabet = alphabet.union(set(s)) return alphabet
cf8f7dc1e31a28fe0910d806d18189aae7d7a85b
8,202
import argparse def numpy_dtype_arg_type(string: str) -> np.dtype: """argument type for string reps of numpy dtypes""" try: ret = np.dtype(string) except TypeError as error: raise argparse.ArgumentTypeError(error.message) return ret
e1d9fa61c6c6d954007e63e61c49a8564c8f6c5d
8,203
def Diff(a, b): """Returns the number of different elements between 2 interables. Args: a(iterable): first iterable. b(iterable): second iterable. Returns: int: the number of different elements. """ return sum(map(lambda x, y: bool(x-y), a, b))
0885bd224f956f138e80a4b681ebc581c733cc51
8,204
def load_description(model): """Load description of the <model>.""" desc = get_available_pkgyaml(model) entry = read_mlhubyaml(desc) return entry
2a97ee446d0693af704c6b0ebd14376d3e6dea37
8,205
import math def generate_star(rect: RectType, line_count: int = 20) -> vp.LineCollection: """Generate a set of line from a random point.""" orig_x = np.random.uniform(rect[0], rect[0] + rect[2]) orig_y = np.random.uniform(rect[1], rect[1] + rect[3]) r = math.hypot(rect[2], rect[3]) angles = np.li...
a430b486af8606d949a057b4578fdddd9968386b
8,206
def failure(request): """Display failure message""" return HttpResponse(f"Failure! {request.session['failure message'] if request.session['failure message'] is not None else ''}")
c9eee874106fce87d6816e3216e3a86d6eef5fab
8,207
import torch def visualize_image(cam, rgb_img, target_category): """ Visualize output for given image """ input_tensor = preprocess_image(rgb_img) grayscale_cam = cam(input_tensor=input_tensor, target_category=target_category) grayscale_cam = grayscale_cam[0, :] output = cam.activations...
2644eca6cd50078a167b7d791a625ecb13fef17d
8,208
import logging def read_csr_matrix(f): """Read A in compressed sparse row format from file f. Return dense ndarray. Text file format: - one number per line - First number is m = number of rows - Second number is n = number of columns - Next m+1 numbers are the row pointers (int, zero-based) ...
c9f1201217ca7c6ca45d0b3d258fc1828c5ab36c
8,209
import random def _get_random_hangul(count=(0xd7a4 - 0xac00)): """Generate a sequence of random, unique, valid Hangul characters. Returns all possible modern Hangul characters by default. """ valid_hangul = [chr(_) for _ in range(0xac00, 0xd7a4)] return random.sample(valid_hangul, count)
3a41edd36cd2aac05e51a121743bcfb61455bd9b
8,210
def build(dir, **kwargs): """run cmake to generate a project buildsystem Parameters: ---------- dir str: Location of the CMake build directory Keyword Args: ---------- parallel int: The maximum number of concurrent processes to use when building. Default: 1 less than ...
2f21fc901d7c95d3b1a2b37d6ba3584d6cb96efb
8,211
def is_builtin_model(target: type) -> bool: """returns ``True`` if the given type is a model subclass""" return is_builtin_class_except(target, ["MetaModel", "Model", "DataBag"])
6b1cf3b0fdd0db50c0dde6a2ca3f3bcb8e8328cf
8,212
def runQ(qparsed, params=dict(), nbcircuits=1, nbqubits = None): """ qparsed: qlang circuit (already parsed) params:{x:np.array, t:np.array} """ #*** verify if parameters are ok for qparsed circuit **** _ , vector_parameters = parseqlang.parameters_from_gates(qparsed) for pname, dimension i...
d6ca4afd14e56961920033e9e7ab40f4fc4a9ae6
8,213
def add_CNNB_loss_v2(true_labels, hidden, embed_model, bsz=512, dataset='imagenet2012', hidden_norm=True, temperature=1.0, strategy=None, loss...
117af71c6f84ad1d2553cd3a18001b93af8539c6
8,214
def simulation_wells(self): """Get a list of all simulation wells for a case Returns: :class:`rips.generated.generated_classes.SimulationWell` """ wells = self.descendants(SimulationWell) return wells
ecf13fc524f12be21593c49d8d22c365564716e9
8,215
from typing import Optional def getSmartMeter() -> Optional[str]: """Return smartmeter name used in recording.""" mapping = getDeviceMapping() # Identifier for smartmeter is meter with phase 0 try: return next(key for key in mapping if mapping[key]["phase"] == 0) except StopIteration: return None
8e947d5d9078886f9bc2b662162304eb2fb6474b
8,216
def olbp(array, point): """Perform simple local binary pattern calculation with a fixed 3x3 neighbourhood. Thanks to: http://www.bytefish.de/blog/local_binary_patterns/ for a really nice explanation of LBP. Won't return correct results around the image boundaries. Because it's on...
0db7058515ef435fe744a3b304e6532ec56b5f63
8,217
import http from typing import Optional def view_index( request: http.HttpRequest, workflow: Optional[models.Workflow] = None, ) -> http.HttpResponse: """Render the list of views attached to a workflow. :param request: Http request received. :param workflow: Workflow being processed :return: ...
2dca3e42a3d2b855d795fc0c61b41c2a2f449724
8,218
def inverseLPSB(data, mu, g): """Compute regularized L-PSB step.""" mUpd = data.mUpd gamma = data.gamma gammah = data.gamma + mu Q22 = np.tril(data.STY[:mUpd, :mUpd], -1) + np.tril(data.STY[:mUpd, :mUpd], -1).T + \ np.diag(np.diag(data.STY[:mUpd, :mUpd])) + \ gamma * np.diag(np.diag...
500705d0fd5cb5ccae7fa8dfeaa1548a65fa2203
8,219
import json def canPlay(request): """ Endpoint qui retourne la liste des cartes qui peuvent être jouées ( pour le Player ) rq : { "cards_played" : [ { "card_name": "As", "value_non_atout": 0, "value_atout": 0, ...
b579e0e99eebed68fa55f8eeb287cb2cdf283de6
8,220
async def async_setup(hass: HomeAssistant, config: dict): """Set up the Genie Aladdin component.""" return True
22f6c6126d8d7b3ce7df124b144b9ccfb4fc30c2
8,221
import importlib def _module_available(module_path: str) -> bool: """Testing if given module is avalaible in your env >>> _module_available('os') True >>> _module_available('bla.bla') False """ mods = module_path.split('.') assert mods, 'nothing given to test' # it has to be teste...
6673bf25845af6c12494ffbec0dc8bb8ab950ff2
8,222
def _GetPathBeforeFinalDir(uri): """ Returns the part of the path before the final directory component for the given URI, handling cases for file system directories, bucket, and bucket subdirectories. Example: for gs://bucket/dir/ we'll return 'gs://bucket', and for file://dir we'll return file:// Args: ...
20cad56a858e8feccfd7154ecff33d9508a7ec80
8,223
import toml def load_page_details(data, filename=None): """ # Raises ValueError of (filename, error) """ try: options = toml.loads(data) except toml.TomlDecodeError as exc: raise ValueError(filename, exc) if not isinstance(options, dict): raise ValueError(filename, 'page details could not b...
117bb7d84625475745a30522fda7dccf1bc5a487
8,224
def nested_render(cfg, fully_rendered_cfgs, replacements): """ Template render the provided cfg by recurisevly replacing {{var}}'s which values from the current "namespace". The nested config is treated like nested namespaces where the inner variables are only available in current block and further...
9958e792ef09aa7c88e4c8b7d29a61a8713927a2
8,225
from operator import sub import warnings def element_by_atomic_number(atomic_number): """Search for an element by its atomic number Look up an element from a list of known elements by atomic number. Return None if no match found. Parameters ---------- atomic_number : int Element atom...
42a23d0bd2ce1391a74ee8b5d5f97aa5fc8b2d3f
8,226
import tqdm def get_data_from_db(cursor): """ Get data from the database given a query-instantiated cursor :param cursor: query-instantiated database cursor :return: tuple of labels and training data """ training_data, labels = [], [] cols = [desc[0] for desc in cursor.description] fo...
a3db9af7912fd38e9966f0c95639613cb4dac087
8,227
def parse(input_str, file_path=True): """ Parse a GLM into an omf.feeder tree. This is so we can walk the tree, change things in bulk, etc. Input can be a file path or GLM string. """ tokens = _tokenize_glm(input_str, file_path) return _parse_token_list(tokens)
2e53a6870baae3fa9bfb511b28baf73e697b44a0
8,228
def pred(model, x_pred_scaled, scaler_y): """ Predict :param model: model for prediction :param x_pred_scaled: scaled x values we need to predict for :param scaler_y: scaler for y values :return: """ MAX_PREDICT_SIZE = 10000 g_mean_full = g_std_full = None start = 0 while s...
7a43020a2b4817b3287c849bc0059027346bf5a5
8,229
def metadataAbstractElementEmptyValuesTest3(): """ Empty value for unknown attribute. >>> doctestMetadataAbstractElementFunction( ... testMetadataAbstractElementEmptyValue, ... metadataAbstractElementEmptyValuesTest3(), ... requiredAttributes=["required1"], ... optionalAttri...
4f9e0d33948a9ac1ab35bc9cf0c5c3274cfc9d41
8,230
def orthonormal_initializer(input_size, output_size): """from https://github.com/patverga/bran/blob/32378da8ac339393d9faa2ff2d50ccb3b379e9a2/src/tf_utils.py#L154""" I = np.eye(output_size) lr = .1 eps = .05/(output_size + input_size) success = False tries = 0 while not success and tries < 10...
11cc28d6342ed20699c96051a36199c3b8941381
8,231
def stick_figure (ax, type, num, start, end, prev_end, scale, linewidth, opts): """ General function for drawing stick based parts (e.g., ribozyme and protease sites). """ # Default options color = (0,0,0) start_pad = 2.0 end_pad = 2.0 x_extent = 5.0 y_extent = 10.0 linestyle = '-' linetype = ""; shapetyp...
68ae3194ad1dd38e0e18f8da3b0b5f1b0e22071a
8,232
def display_datetime(datetime_str, time_zone=None, verbose=True): """Returns a formatted datetime with TZ (if provided) or 'Error (Missing)""" """ >>> print(datetime.datetime.utcnow().strftime("%Y/%m/%d %a %I:%M %p")) 2019/05/19 Sun 01:10 AM """ if datetime_str: # and type(datetime_str) =...
45caa488688e790ae19f8f3f2cda2cb0f250b1fd
8,233
import torch def mask_channels(mask_type, in_channels, out_channels, data_channels=3): """ Creates an autoregressive channel mask. Input: mask_type: str Either 'A' or 'B'. 'A' for first layer of network, 'B' for all others. in_channels: int Number of input channels...
772fa71f63d2f31c80966db0b0eb43a70ac5e9a9
8,234
import textwrap def dedent(text): """ Remove all common indentation from every line but the 0th. This will avoid getting <code> blocks when rendering text via markdown. Ignoring the 0th line will also allow the 0th line not to be aligned. Args: text: A string of text to dedent. Returns: String d...
b450a873c4c2b667d10c66985d19f8057aa205f9
8,235
from sys import stderr def open_text_file_for_write(output_directory:str, file_name:str, verbose=False) -> TextIOWrapper: """Open a text file for writing""" if verbose: print(f"opening text file for write: {output_directory}/{file_name}", file=stderr) return open(f"{output_directory}/{file_name}",...
e6e2a379f95c54ebec3f2e1d3a4c446ee169d2e7
8,236
def dpsplit(n,k, sig): """ Perform the dynamic programming optimal segmentation, using the sig function to determine the cost of a segment sig(i,j) is the cost of the i,j segment. These are then added together """ # Set up the tracking tables K = k + 1 N = n segtable = np.zeros((n,K)) ...
db1513ae0a4725b63e62b102dc2c5fdd77fd4ceb
8,237
from typing import List def get_wind_tiles() -> List[Tile]: """return a list of four wind tiles """ return [Tile(Suit.JIHAI.value, Jihai.TON.value), Tile(Suit.JIHAI.value, Jihai.NAN.value), Tile(Suit.JIHAI.value, Jihai.SHAA.value), Tile(Suit.JIHAI.value, Jihai.PEI.value...
469ec29795291bb8345fa3beccbbf2c6d4bb3101
8,238
import torch import os def train_mnist_classifier(lr=0.001, epochs=50, model_dir='.'): """train mnist classifier for inception score""" device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("Using device {0!s}".format(device)) train_loader = load_mnist(batchSize=100, train=True)...
91dbfaeae5e4ef5f34435c7034a7a06f980b1b3b
8,239
from datetime import datetime def datetime_now_filename_string(): """create a string representation for now() for use as part of the MHL filename""" return datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d_%H%M%S")
37a733ddd93ca1bc4eed82e920222c644c494fcd
8,240
from pathlib import Path import inspect import tqdm def generate_simulation_dataset(path, runs, **kawrgs): """Generate and save a simulation dataset. Parameters ---------- path : str Root path where simulation data will be stored. runs : int, array If int then number of runs to us...
8383f42cfe2604e5f82761bb351b6cf4f16f33aa
8,241
def num_sites(sequence, rule, **kwargs): """Count the number of sites where `sequence` can be cleaved using the given `rule` (e.g. number of miscleavages for a peptide). Parameters ---------- sequence : str The sequence of a polypeptide. rule : str or compiled regex A regular ex...
dc0840e33206c9db7058a7257a60c59bee0403f8
8,242
def get_packages(code: str) -> defaultdict: """Extracts the packages that were included in the file being inspected. Source for this code: https://stackoverflow.com/questions/2572582/ Example: input: 'from collections import Counter\n import kivy\n from stats import median as stats_median...
977f20e2d3c12993ef26ff8b199f943fb153c79b
8,243
def beam_name(): """Session level fixture for beam path.""" return str(beam_path)
a702d91c62024685d14125123ead41a2a4e38942
8,244
import itertools def get_mv_sandwich(a_blade_indices, b_blade_indices, signature, prod="gp"): """a b ~a""" out_indices = [] out_blade_indices = [] out_signs = [] out_indices = [] indices_a = [] indices_b = [] indices_a_r = [] blade_to_index = {} for (i_a, index_a), (i_b, inde...
8e30f31de944bd6aa19e60fe7a93aceb8ccb73ef
8,245
def ldns_dnssec_create_nsec3(*args): """LDNS buffer.""" return _ldns.ldns_dnssec_create_nsec3(*args)
653d899f7d30e1e272c0a7026e4383e191b3e78f
8,246
def S_difference_values(_data_lista, _data_listb): """ Returns new data samples where values are transformed by transformer values. """ d_data = [] dsa = len(_data_lista) dsb = len(_data_listb) if dsa != dsb: return [] for i in range(dsa): d_data.append(_data_lista[i] ...
40ec82cb7ef53d5e227b3287a9c1d08e78112e09
8,247
def parseFixedZone(s): """Convert a +hhmm or -hhmm zone suffix. [ s is a string -> if s is a time zone suffix of the form "+hhmm" or "-hhmm" -> return that zone information as an instance of a class that inherits from datetime.tzinfo else -> raise SyntaxError ] ...
681b5ad02f228ee40b099a461131de42309e58f0
8,248
def tica_eigenvalues_plot(tica, num=12, plot_file=None): """ Plots the highest eigenvalues over the number of the time-lagged independent components. Parameters ---------- tica : TICA obj Time-lagged independent components information. num : int, default = 12 ...
707ebbacf0dc90e96760ae26d316da4c27bdd997
8,249
from lxml import etree import random, string import os import subprocess import shlex import re def latex2svg(code, params=default_params, working_directory=None): """Convert LaTeX to SVG using dvisvgm and scour (or svgo). Parameters ---------- code : str LaTeX code to render. params : di...
5bfc425d206d0d0ee61e6ef2bff7db061d5750c0
8,250
def _split_train_test(features, labels, train_set, random_seed): """Split the dataset into training and test sets. Parameters ---------- features : pandas.DataFrame Features of the dataset events. labels : pandas.DataFrame Labels of the dataset events. train_set : {float, list-l...
67210e0462cdd4be58f5446b6220f921aa8c4ea0
8,251
from sideboard.lib._services import _register_rpc_services import os def parse_config(requesting_file_path, is_plugin=True): """ Parse the config files for a given sideboard plugin, or sideboard itself. It's expected that this function is called from one of the files in the top-level of your module (...
d8cfd06356d8f20040646b48da7c236e71db90fa
8,252
def generate_enc_keypair(): """ Generate Curve25519 keypair :returns tuple: A byte pair containing the encryption key and decryption key. """ private_key = PrivateKey.generate() return private_key.public_key.encode(), private_key.encode()
c2ba00b6463d7ab1708dcc43d9cafba2d11af0c6
8,253
from typing import List from typing import Tuple def filter_molecular_components( components: List[Component], ) -> Tuple[List[Component], List[Component]]: """Separate list of components into molecular and non-molecular components. Args: components: A list of structure components, generated usin...
72a43a5195ef3d35ca8216225dcae7f699c7bbd5
8,254
import types def argument(name, type): """ Set the type of a command argument at runtime. This is useful for more specific types such as mitmproxy.types.Choice, which we cannot annotate directly as mypy does not like that. """ def decorator(f: types.FunctionType) -> types.Function...
8f93c8e8cd4289d2b4747feb93ecfe3df74350f7
8,255
async def async_google_actions_request_sync(cloud): """Request a Google Actions sync request.""" return await cloud.websession.post( f"{cloud.google_actions_report_state_url}/request_sync", headers={AUTHORIZATION: f"Bearer {cloud.id_token}"}, )
5d75e4b67bc04878108066660b0f43939a1eab4e
8,256
def convert_time_string_to_secs(string: str) -> int: """ Takes a string in the format '1h30m25s' and converts it to an integer in seconds. This functions uses the regular expression RE_CONVERT_TIME above for matching the string. """ match = regexp_time.match(string) if not match: rai...
b520fde06640cd3d22a6c619031633bf21383687
8,257
def polar_cube(c, index, n=512, interp='cubic'): """VIMS cube polar projected. Parameters ---------- c: pyvims.VIMS Cube to interpolate. index: int, float, str, list, tuple VIMS band or wavelength to plot. n: int, optional Number of pixel for the grid interpolation. ...
6a02932e8685a1cdd43e6831b2a3544bd903a40b
8,258
from nibabel.gifti.parse_gifti_fast import ParserCreate, Outputter import gzip def _load_surf_files_gifti_gzip(surf_file): """Load surface data Gifti files which are gzipped. This function is used by load_surf_mesh and load_surf_data for extracting gzipped files. Part of the code can be removed while...
2fdc083a208f1a288b7d99bd3863bff22d36bf50
8,259
import platform def get_platform_system(): """return platform.system platform module has many regexp, so importing it is slow... import only if required """ return platform.system()
2531f1883d5acd0c192c0061d7cbf29637197706
8,260
def populate_sql( sql: sqlparse.sql.Statement, example: NLToSQLExample, anonymize_values: bool ) -> bool: """ Creates a sequence of output / decoder actions from a raw SQL query. Args: sql: The SQL query to convert. example: The NLToSQLExample object to add output actions. anony...
54aaa9465eebdad55e04ec6c840ee760de4e79ee
8,261
import sympy def factorial(n): """Stop sympy blindly calculating factorials no matter how large. If 'n' is a number of some description, ensure that it is smaller than a cutoff, otherwise sympy will simply evaluate it, no matter how long that may take to complete! - 'n' should be a sy...
73dc223df2b23a93aafb0ec2b897f1668869e07a
8,262
import re def getSupplier(num): """" get the supplier for a card number Attributes: @num: card number """ supplier = str() for key, value in suppliers.items(): if bool(re.match(value, num)): supplier = key break if supplier == "": suppl...
2572a0595d03cc3056b1155f8a3f0b007ec65b9e
8,263
from typing import Optional import torch def load_torch_hub_model(repo: str, model: str, *args, **kwargs): """Tries to load a torch hub model and handles different exceptions that could be raised. Args: repo: The GitHub repository containing the models. model: The model name to download. ...
3cc928f1026d276290ed97360a0cfebbcde82bb8
8,264
def compute_medoid(data): """ Get medoid of data Parameters ---------- data: ndarray Data points Returns ------ medoid: ndarray Medoid """ dist_mat = pairwise_distances(data) return data[np.argmin(dist_mat.sum(axis=0))]
3fd071cd6c48566caa3a52ead26f06621682703d
8,265
def int_sphere(fx, xgrid): """ Computes integrals over the sphere defined by the logarithmic grid provided as input Parameters ---------- fx : array_like The function (array) to be integrated xgrid : ndarray The logarithmic radial grid Returns ------- I_sph : fl...
d92962cde5200f0c25d8bd0e1011c969e2287125
8,266
import os def run( func, args=[], kwargs={}, service="lambda", capture_response=False, remote_aws_lambda_function_name=None, remote_aws_region=None, **task_kwargs ): """ Instead of decorating a function with @task, you can just run it directly. If you were going to do func(...
fdf1c4b8f654c27c2ac04a945b44e54b19e1b00f
8,267
def run_webserver(destination_root_dir): """ Run a local """ destination_root_dir = destination_root_dir if destination_root_dir.startswith('/'): destination_root_dir = destination_root_dir[1:] if destination_root_dir.endswith('/'): destination_root_dir = destination_root_dir[:-1] ...
df5d26ae754009135061abb4a1a2d1cad0937e97
8,268
from typing import Union from typing import List def sym_to_elm(symbols: Union[str, List, np.ndarray], order: Union[np.ndarray, List[str]]): """Transform symbols to elements.""" if not isinstance(order, list): order = order.tolist() if not isinstance(symbols, (str, list)): s...
16e2a88b353556068e8c1a3fa7c831264fd9f3c5
8,269
def set_custom_field( custom_field_id: str = None, person_id: str = None, owner_id: str = None, term_id: str = None, value: str = None, option_index: str = None): """ Sets a custom field value for a particular person, organization, or donation. :param custom_...
3d9471c62644e8e19f7b6faa03f3b503d5db7673
8,270
def ixn_is_increases_activity(ixn: ChemGeneIxn): """Checks if the interaction results in the decrease of the activity of the protein of the gene :param pyctd.manager.models.ChemGeneIxn ixn: A chemical-gene interaction :rtype: bool """ return _ixn_is_changes_protein(ixn, 'increases^activity')
0b324a953ed2a90a9a357965ad4e5ef4a635c2df
8,271
def load(csv, sep=';'): """ Load data into dataframe :param csv: :param sep: :return: """ data = pd.read_csv(csv, sep=sep) return data
da988e31601b13a767178b4d6613d948100ddfc9
8,272
import os import json def get_docs(request): """ вернуть список [ {doc_id, doc_name}, {doc_id, doc_name}, ] """ doc_set_id = request.GET["doc_set_id"] docs = Document.objects.filter(doc_set_id=doc_set_id) response_data = [] for doc in docs: ...
86d395b5a391a25b141d9d7f2139cf40ead94d41
8,273
def count_lost_norm4(matrix): """calculate 4th lost points: Proportion of dark modules in entire symbol: 50 + (5 + k) or 50 - (5 + k), return k * 10 Args: matrix ([type]): [description] Returns: [int]: [description] """ dark_sum = np.sum(matrix) modules_num = matrix.size ...
ad05892952af5cfc5dbd8273bbc1357d31b1a295
8,274
def sumaDigits(s): """assumes s is a string and returns the sum of the decimal digits in s. For example if s is 'a2b3c' it returns 5""" suma = 0 for c in s: try: suma+=int(c) except ValueError: continue return suma
47b09476925d45741d97eca5362e736f83a8185d
8,275
def f5_list_policy_file_types_command(client: Client, policy_md5: str) -> CommandResults: """ Get a list of all policy file types. Args: client (Client): f5 client. policy_md5 (str): MD5 hash of the policy. """ result = client.list_policy_file_types(policy_md5) table_name = 'f5...
b2b57d281b0cc3ea0ff7430d2033255071761a46
8,276
def recurrent_layer(input, act=None, bias_attr=None, param_attr=None, name=None, reverse=False, layer_attr=None): """ Simple recurrent unit layer. It is just a fully connect layer through both...
b616d372a9324c11aa1bb524d96844ce1e8c47e5
8,277
def mean_center(X): """ @param X: 2-dimensional matrix of number data @type X: numpy array @return: Mean centered X (always has same dimensions as X) """ (rows, cols) = shape(X) new_X = zeros((rows, cols), float) _averages = average(X, 0) for row in rang...
54885596c95856b0ce0f7fe68d2922641e7a830a
8,278
import collections import csv def csv_to_json(order_sentence_file: str, order_comment_file: str, os_filter_file: str=None) -> dict: """ Conversion of CSV to dictionary/JSON for sequenced PowerPlans and clinical category :param order_sentence_file: :param order_comment_file: :return: """ ...
9a4021168624773233dbea5eb6a5e6f0b7eacee5
8,279
import csv from io import StringIO def process_xlsform(xls, default_name): """ Process XLSForm file and return the survey dictionary for the XLSForm. """ # FLOW Results package is a JSON file. file_object = None if xls.name.endswith('csv'): # a csv file gets closed in pyxform, make a ...
af695bef6f063b2bfa7862e856e16ab42be2db96
8,280
def unflatten(X: np.ndarray, Y: np.ndarray, shape: tuple): """ Unflattens images with shape defined by list of tuples s X is an array (1D), unflattened to 2D Y is an array (1D) of flattened mask (flattened 2D label) array Not that X and Y are not compatible dimensions s denotes dimensions ...
7a1a79b165d44efd55c2e66936e072298cd5d648
8,281
from typing import Dict from typing import Any from typing import List import logging from pathlib import Path def collate_features(model_config: Dict[str, Any], dummy_features: List[str]) -> List[str]: """Saves and returns final list of simple and dummy features.""" simple_features = list(model_config.get("s...
e66e3aceb0b5bf093a4fc3165a30694875903b73
8,282
from typing import Type def new_dga(*, key_mo=None, pred=None, deg_diff=None) -> Type[DgaGb]: """Return a dynamically created subclass of GbDga. When key_mo=None, use revlex ordering by default.""" class_name = f"GbDga_{DgaGb._index_subclass}" DgaGb._index_subclass += 1 if deg_diff is not None: ...
32cfa58eec7512dd7b39b2298608df538a232ef9
8,283
def is_xarray(array): """Return True if array is a xarray.DataArray Parameters ---------- array : array-like Returns ------- test : bool """ return isinstance(array,xr.DataArray)
edf14a0c87e6590e6a583425ec830e51defe5fa1
8,284
from typing import Counter def _check_duplicate_gnames(block_id, block_dict, extra_args): """ Return False if any duplicate group names exist in /etc/group file, else return True """ gnames = _execute_shell_command("cat /etc/group | cut -f1 -d\":\"", python_shell=True).strip() gnames = gnames.spli...
2a181ca67f87f0f90eb97c1df0e7ae8db6ee2206
8,285
def join_nonempty(l): """ Join all of the nonempty string with a plus sign. >>> join_nonempty(('x1 + x2 + x1:x2', 'x3 + x4')) 'x1 + x2 + x1:x2 + x3 + x4' >>> join_nonempty(('abc', '', '123', '')) 'abc + 123' """ return ' + '.join(s for s in l if s != '')
041948f95caaef14cb96e761f08b4a84fba37d6e
8,286
import torch def correct_msa_restypes(protein): """Correct MSA restype to have the same order as rc.""" new_order_list = rc.MAP_HHBLITS_AATYPE_TO_OUR_AATYPE new_order = torch.tensor( [new_order_list] * protein["msa"].shape[1], device=protein["msa"].device, ).transpose(0, 1) protei...
881736333e3153c9c7713f7a54252eba705b7bb8
8,287
def plot_bootstrap_lr_grp(dfboot, df, grp='grp', prm='premium', clm='claim', title_add='', force_xlim=None): """ Plot bootstrapped loss ratio, grouped by grp """ count_txt_h_kws, mean_txt_kws, pest_mean_point_kws, mean_point_kws = _get_kws_styling() if dfboot[grp].dtypes != 'objec...
11a0276ab1eac233db537943b5af67f0452f89db
8,288
def ajax_user_search(request): """ returns the user search result. currently this is not used since search user feature changed to form post. """ if request.method=='POST': username=request.POST.get('username','') users=User.objects.filter(username__contains=username) try: ...
8318b881280e47ff28ea8db259df607b1e5bf7fb
8,289
def shortest_path(start, end): """ Using 2-way BFS, finds the shortest path from start_position to end_position. Returns a list of moves. You can use the rubik.quarter_twists move set. Each move can be applied using rubik.perm_apply """ if start == (7, 8, 6, 20, 18, 19, 3, 4, 5, 16, 17, 15...
c75b54b434c09f6d570f79c40453bd465a2a439b
8,290
import torch def prep_param_lists(model, flat_master=False): """ Creates a list of FP32 master parameters for a given model, as in `Training Neural Networks with Mixed Precision: Real Examples`_. Args: model (torch.nn.Module): Existing Pytorch model flat_master (bool, optional, defau...
36ec1b264af2b05c4fc13a295d007e0ac830b821
8,291
def to_matrix_vector(transform): """ Code from nilearn module, available at: https://github.com/nilearn/nilearn/blob/master/nilearn/image/resampling.py Split an homogeneous transform into its matrix and vector components. The transformation must be represented in homogeneous coordinates. It is ...
b971f3b53199a16bbf2343ed544389cbc21f1644
8,292
def sieveEr(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. """ # precondition assert isinstance(N,int) and (N > 2), "'N' must been...
8d48d2a491341d5302307597ad64ac4a37b1abb8
8,293
def validate_fields(item, fields=None): """ Check that all requested fields were returned :param item: comment or submission :param fields: list[str] :return: list[str] """ actual_fields = item.d_.keys() if fields is None: requested_fields = actual_fields else: requ...
88bd6d20ba1cc04f8478128f7f32192ef680762b
8,294
import warnings def _parallel_build_trees(tree, forest, X, y, sample_weight, tree_idx, n_trees, verbose=0, class_weight=None, target_imbalance_ratio=None): """Private function used to fit a single tree in parallel.""" if verbose > 1: print("building tree %d of %d" % (tree_idx...
a5c027d96bd96522544e56bd427ae39a5075e6b8
8,295
from typing import Iterable def remove_nones(sequence: Iterable) -> list: """Removes elements where bool(x) evaluates to False. Examples -------- Normal usage:: remove_nones(['m', '', 'l', 0, 42, False, True]) # ['m', 'l', 42, True] """ # Note this is redundant with it.chain ...
975c0104b3cc05bb82fa211c1b85b49c7d3cb174
8,296
import glob import os def writeSConscript(dirpath, profile, pkeys): """ Create a SConscript file in dirpath. """ # Activate modules mods, defines = collectModules(dirpath, pkeys) if validKey('CONFIG', pkeys) and isComplicated(pkeys['CONFIG'][0]): return False qrcname = "" if ...
36766bcb0f1e7d88b4df6500cb758b70c7c63600
8,297
from typing import List import pathlib def retrieve(passed: List[str]) -> List[str]: """ Retrieves all items that are able to be converted, recursively, from the passed list. Parameters ---------- passed: List[str] The items to search. Returns ------- List[str]: A...
6789255e302caf9dc6e481df532acec20dfc6b3c
8,298
from typing import List from typing import Optional from typing import Dict from typing import Tuple from typing import Any def get_out_of_sample_best_point_acqf( model: Model, Xs: List[Tensor], X_observed: Tensor, objective_weights: Tensor, mc_samples: int = 512, fixed_features: Optional[Dict...
a6331759833b4715275fdb3ca7d19c237c2c7e55
8,299