content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def matplotlib_axes_from_gridspec_array(arr, figsize=None): """Returned axes layed out as indicated in the array Example: -------- >>> # Returns 3 axes layed out as indicated by the array >>> fig, axes = matplotlib_axes_from_gridspec_array([ >>> [1, 1, 3], >>> [2, 2, 3], >>> ...
e1048ea32a6c3c8ea87a82c5c32f7e009c1b5c19
10,386
def _fetch_gene_annotation(gene, gtf): """ Fetch gene annotation (feature boundaries) and the corresponding sequences. Parameters: ----------- gene gene name that should be found in the "gene_name" column of the GTF DataFrame. type: str gtf GTF annotation D...
d08307fd3e079e6de3bca702a0d9f41005a6d5f7
10,387
from django.core.servers.basehttp import AdminMediaHandler def deploy_static(): """ Deploy static (application) versioned media """ if not env.STATIC_URL or 'http://' in env.STATIC_URL: return remote_dir = '/'.join([deployment_root(),'env',env.project_fullname,'static']) m_prefix = len(en...
7c1c8d7ce725e285e08f5fa401f6e431a35fc77c
10,388
import array def randomPolicy(Ts): """ Each action is equally likely. """ numA = len(Ts) dim = len(Ts[0]) return ones((dim, numA)) / float(numA), mean(array(Ts), axis=0)
6c99ecfe141cb909bceb737e9d8525c9c773ea74
10,389
def calc_TiTiO2(P, T): """ Titanium-Titanium Oxide (Ti-TiO2) ================================ Define TiTiO2 buffer value at 1 bar Parameters ---------- P: float Pressure in GPa T: float or numpy array Temperature in degrees K Returns ------- float or numpy array log_fO2 References ---------- Bar...
c4f920db3ff6020eba896039228e7adbcdcd4234
10,390
def nlevenshtein_scoredistance(first_data, memento_data): """Calculates the Normalized Levenshtein Distance given the content in `first_data` and `memento_data`. """ score = compute_scores_on_distance_measure( first_data, memento_data, distance.nlevenshtein) return score
e85776c5ae95533c500a47d550ea848e6feceed7
10,391
def parameter_from_numpy(model, name, array): """ Create parameter with its value initialized according to a numpy tensor Parameters ---------- name : str parameter name array : np.ndarray initiation value Returns ------- mxnet.gluon.parameter a parameter object...
babf1a32e55d92bbe1ad2588167bd813836637e7
10,392
def execute_workflow_command(): """Command that executes a workflow.""" return ( Command().command(_execute_workflow).require_migration().require_clean().with_database(write=True).with_commit() )
f20b5be4d37f14179f0097986f2f75b1de699b79
10,393
import tqdm def fast_parse(python_class, parse_function, data_to_parse, number_of_workers=4, **kwargs): """ Util function to split any data set to the number of workers, Then return results using any give parsing function Note that when using dicts the Index of the Key will be passed to t...
ffbd377a53362cb532c84860f3b26ff2ed1234c6
10,394
import copy def create_plate(dim=DIMENSION, initial_position=-1): """ Returns a newly created plate which is a matrix of dictionnaries (a matrix of cells) and places the first crystal cell in it at the inital_pos The keys in a dictionnary represent the properties of the cell :Keys of the dictionn...
1f1b806035dc6dc24796840f7cb31c61cf7ec5a7
10,395
import unicodedata def CanonicalizeName(raw_name: Text): """Strips away all non-alphanumeric characters and converts to lowercase.""" unicode_norm = unicodedata.normalize('NFKC', raw_name).lower() # We only match Ll (lowercase letters) since alphanumeric filtering is done # after converting to lowercase. Nl a...
bd8d2d47dae4220e51dab8d44a0c6b603986ecff
10,396
from datetime import datetime import json def data_v1( request ): """ Handles all /v1/ urls. """ ( service_response, rq_now, rq_url ) = ( {}, datetime.datetime.now(), common.make_request_url(request) ) # initialization dump_param_handler = views_helper.DumpParamHandler( rq_now, rq_url ) if request.GE...
18e98f015cb92f0d0e2ac6bbe9627d4c6ab33fb0
10,397
def permutations(n, r=None): """Returns the number of ways of arranging r elements of a set of size n in a given order - the number of permuatations. :param int n: The size of the set containing the elements. :param int r: The number of elements to arange. If not given, it will be\ assumed to be eq...
7eab1c02ab0864f2abd9d224145938ab580ebd74
10,399
def cyk(word: str, cfg: CFG) -> bool: """ Checks whether grammar derive the word. This function is applicable to any CFG. Parameters ---------- word: str A word to derive in cfg cfg: CFG A CFG to derive a word Returns ------- bool: Whether grammar deriv...
08fd0790f01ab5ff968564f2b684b833d7cda355
10,400
def macd(df, ewa_short, ewa_long, ewa_signal, price_col="adj_close"): """Moving Average Convergence Divergence Parameters: ----------- df : DataFrame Input dataframe. ewa_short : int Exponentially weighted average time-window for a short time-span. A common choice for the sho...
3140f67371394244b66b9048d273e0d5fee5e471
10,402
from typing import Union from typing import Any from enum import Enum def make_annotation(field: ModelField): """ Convert a field annotation type to form data accepted type. The method convert structural field such as `BaseModel` and `Dict` to a str. Such as the model's value is supplied as a seriali...
9abba2c30302554d06c5a734ba13892ce5933811
10,403
def texture_symmetry_predict_patches(classifier, data=None, data_backup_file='FeaturesForPreds'): """Predict if symetric pairs of patches taken in a dermoscopic image are similar or not using features extracted with the `texture_symmetry_features()` function and stored in the "FeatureForPreds.csv" file. ...
87f5323b70b027992dc3ed56a536f43f0d8a8fd2
10,404
def instantiateSong(fileName): """Create an AudioSegment with the data from the given file""" ext = detectFormat(fileName) if(ext == "mp3"): return pd.AudioSegment.from_mp3(fileName) elif(ext == "wav"): return pd.AudioSegment.from_wav(fileName) elif(ext == "ogg"): return pd.A...
16d5daab7b4a8b0e62845339c5a7c51618e15cee
10,405
def get_href(link: bs4.element.Tag) -> str: """If a link has an href attribute, return it :param link: The link to be checked :returns: An href """ if (link.has_attr("href")): return (link["href"])
d9f9d9e9303cc6a7e57ca60f3f2b5582e99aa8a8
10,406
from typing import Dict import ast def get_contrib_requirements(filepath: str) -> Dict: """ Parse the python file from filepath to identify a "library_metadata" dictionary in any defined classes, and return a requirements_info object that includes a list of pip-installable requirements for each class that def...
3b25fa4c4185f0e77f1efeab40a1bfd199e950dd
10,407
def __zedwalther(kin): """ Calculate the z-parameter for the Walther equation (ASTM D341). Parameters ---------- kin: scalar The kinematic viscosity of the lubricant. Returns ------- zed: scalar The z-parameter. """ zed = kin + 0.7 + 10 ** (-1.47 - 1.84 * kin ...
d01a716da03230436c5f511cc65f9e7c96732d99
10,409
def o1_cosmologies_list(): """ Return the list of $\\sigma_8$ values used in training Q1 :return: A numpy array of 20 $\\sigma_8$ values """ return np.array([0.969, 0.654, 1.06, 0.703, 1.1615, 0.759, 0.885, 0.6295, 0.605, 0.7205, 1.1685, 1.179, ...
f7fae1d4301631c6ad33090a6c0bceed94380345
10,410
def chrelerr(fbest, stop): """ checks whether the required tolerance for a test function with known global minimum has already been achieved Input: fbest function value to be checked stop(0) relative error with which a global minimum with not too small absolute value ...
c90ad548ea9490cdb5a43cfb3559d7f26a0c57fc
10,411
from scipy.stats import binom def prop_test(df): """ Inspired from R package caret confusionMatrix.R """ x = np.diag(df).sum() n = df.sum().sum() p = (df.sum(axis=0) / df.sum().sum()).max() d = { "statistic": x, # number of successes "parameter": n, # number of trials ...
e2b584435cdcc25b091b0d0c17a04b07790a89cd
10,412
import time def time_and_log_query( fn ): """ Decorator to time operation of method From High Performance Python, p.27 """ @wraps( fn ) def measure_time( *args, **kwargs ): t1 = time.time() result = fn( *args, **kwargs ) t2 = time.time() elapsed = t2 - t1 ...
75d2bb057afd63c9abbfd0c392c533236238fe15
10,413
def parse_anchor_body(anchor_body): """ Given the body of an anchor, parse it to determine what topic ID it's anchored to and what text the anchor uses in the source help file. This always returns a 2-tuple, though based on the anchor body in the file it may end up thinking that the topic ID and th...
5e86ac489727ec4da69f7ca14152cb79da541f3a
10,414
def func_parameters(func_name): """ Generates function parameters for a particular function. Parameters ---------- func_name : string Name of function. Returns -------- d : integer Size of dimension. g : gradient of objective function. `g(x, *func_ar...
4bcd62167cae79c456754349e35209ba4c932caf
10,415
def range_overlap(range1, range2): """ determine range1 is within range2 (or is completely the same) :param range range1: a range :param range range2: another range :rtype: bool :return: True, range1 is subset of range2, False, not the case """ result = all([ range1.start >= ra...
3df4edf59ea473ad7b832256443a1e4e8c7e0ce9
10,416
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ user = User.query.filter(User.name==username and User.password_hash==encrypt_password(passsword)).first() if user == None: return False else: return True
e664f6885b68581d0f647a252db7b0176f54b8c8
10,419
def redirect_success(): """Save complete jsPsych dataset to disk.""" if request.is_json: ## Retrieve jsPsych data. JSON = request.get_json() ## Save jsPsch data to disk. write_data(session, JSON, method='pass') ## Flag experiment as complete. session['complete'] = 'su...
23e4a91df3ea1bedf99dfc59c94cff24d0dd9d45
10,420
import tempfile def fill_region(compound, n_compounds, region, overlap=0.2, seed=12345, edge=0.2, temp_file=None): """Fill a region of a box with a compound using packmol. Parameters ---------- compound : mb.Compound or list of mb.Compound Compound or list of compounds to be p...
dc125e905a8b6238d79724d66a4d19fa54d130bd
10,421
def morris_traversal(root): """ Morris(InOrder) travaersal is a tree traversal algorithm that does not employ the use of recursion or a stack. In this traversal, links are created as successors and nodes are printed using these links. Finally, the changes are reverted back to restore the original t...
1770e1df3811edb6bebb64729e2eddef34348dc4
10,422
def normalize_matrix_rows(A): """ Normalize the rows of an array. :param A: An array. :return: Array with rows normalized. """ return A / np.linalg.norm(A, axis=1)[:, None]
cd04f8a77954c53e97f9025d35c232b755577d6d
10,423
def clear_cache() -> int: """ Очистка локального кэша форматов, меню и прочих ресурсов, прочитанных с сервера. :return: код возврата """ return IC_clearresourse()
3e94b618dd988d477517e25f3e7cca23163596f4
10,424
def transform(shiftX=0.0, shiftY=0.0, rotate=0.0, skew=0.0, scale=1.0): """ Returns an NSAffineTransform object for transforming layers. Apply an NSAffineTransform t object like this: Layer.transform_checkForSelection_doComponents_(t,False,True) Access its transformation matrix like this: tMatrix = t.transformS...
fa6b0eb4a84ae7fa13bab1ebb12591abe5362373
10,426
def get_entity(text, tokens): """获取ner结果 """ # 如果text长度小于规定的max_len长度,则只保留text长度的tokens text_len = len(text) tokens = tokens[:text_len] entities = [] entity = "" for idx, char, token in zip(range(text_len), text, tokens): if token.startswith("O") or token.startswith(app.model_co...
ee261ceda4443b8c0f0c4663c23c0a422971f72b
10,427
def new_func(message): """ new func :param message: :return: """ def get_message(message): """ get message :param message: :return: """ print('Got a message:{}'.format(message)) return get_message(message)
c5f23b0cd3cebfdd2d36398a3ace18342d6de37c
10,428
import torch import numpy import random def process_midi(raw_mid, max_seq, random_seq, condition_token=False, interval = False, octave = False, fusion=False, absolute=False, logscale=False, label = 0): """ ---------- Author: Damon Gwinn ---------- Takes in pre-processed raw midi and returns the in...
ae90ddf6c5c18a22298eb1b863a7a90a3f4c6a9f
10,429
def _rack_models(): """ Models list (for racks) """ models = list(Rack.objects. \ values_list('rack_model', flat=True).distinct()) models.sort() return models
6192656d82bee5227c19cd1c3446077027457251
10,430
def confidence_ellipse(cov, means, ax, n_std=3.0, facecolor='none', **kwargs): """ Create a plot of the covariance confidence ellipse of *x* and *y*. Parameters ---------- cov : array-like, shape (2, 2) Covariance matrix means: array-like, shape (2, ) Means array ax : matp...
eb7ac51f6e24ca41855232b1c73f054e6538f4d4
10,431
def catalogResolveURI(URI): """Do a complete resolution lookup of an URI """ ret = libxml2mod.xmlCatalogResolveURI(URI) return ret
20eefbe64bde8a57e7ce56538c1fa0da45922bfa
10,432
def high_low_difference(dataframe: pd.DataFrame, scale: float = 1.0, constant: float = 0.0) -> pd.DataFrame: """ Returns an allocation based on the difference in high and low values. This has been added as an example with multiple series and parameters. parameters: scale: determines amplitude facto...
f821f5ed7d3bc714ed9e75f4cba21e4173297148
10,433
def e_x(x, terms=10): """Approximates e^x using a given number of terms of the Maclaurin series """ n = np.arange(terms) return np.sum((x ** n) / fac(n))
ad924f4b7d713a64b6fa68c44d14a1a3aeff2650
10,434
from bs4 import BeautifulSoup import re async def parser(html: str) -> list: """解析页面 Args: html (str): 返回页面的源码 Returns: list: 最先的3个搜图结果(不满3个则返回所有,没有结果则返回str) """ if "No hits found" in html: return "没有找到符合的本子!" soup = BeautifulSoup(html, "lxml").find_all("table", class...
e676259e3bfe02a5c4fc7f6deb339d617ab5ff63
10,435
def set_namespace_root(namespace): """ Stores the GO ID for the root of the selected namespace. Parameters ---------- namespace : str A string containing the desired namespace. E.g. biological_process, cellular_component or molecular_function. Returns ------- list ...
2719b2766912ad8caf3427513c7affa1cdb92eb3
10,436
import itertools import operator def get_commit(oid): """ get commit by oid """ parents = [] commit = data.get_object(oid, 'commit').decode() lines = iter(commit.splitlines()) for line in itertools.takewhile(operator.truth, lines): key, value = line.split(' ', 1) if key =...
e0e928253ddce7d0087775eedfe6859ddc7e1200
10,437
def _gaussian_dilated_conv2d_oneLearned(x, kernel_size, num_o, dilation_factor, name, top_scope, biased=False): """ Dilated conv2d with antecedent gaussian filter and without BN or relu. """ num_x = x.shape[3].value filter_size = dilation_factor - 1 sigma = _get_sigma(top_scope) # create k...
b05d1e4dd84ac9396fba64b4a158549ed0f11694
10,438
def get_cos_similarity(hy_vec, ref_vec): """ measure similarity from two vec """ return (1 - spatial.distance.cosine(hy_vec, ref_vec))
7bdb483ab443a8253317d2d0cca82701b2c762ec
10,439
def addDepthDimension (ds): """ Create depth coordinate Parameters ---------- ds : xarray DataSet OOI Profiler mooring data for one profiler Returns ------- ds : xarray DataSet dataset with iDEPTH coordinate set as a dimension """ if ( 'prof_depth' not in ds ): ...
9940bc21af373f738c1b0ab682a6cae048e21ba0
10,440
def divide_dataset_by_dataarray(ds, dr, varlist=None): """ Divides variables in an xarray Dataset object by a single DataArray object. Will also make sure that the Dataset variable attributes are preserved. This method can be useful for certain types of model diagnostics that have to be divide...
cdf519c425a3622d2293971650eb0325eda76ba8
10,441
def count_words(my_str): """ count number of word in string sentence by using string spilt function. INPUT - This is testing program OUTPUT - 4 """ my_str_list = my_str.split(" ") return len(my_str_list)
731291937205fd0b9cb9153b4ee95d42416a5124
10,442
from datetime import datetime import pytz def suggest_create(): """Create a suggestion for a resource.""" descriptors = Descriptor.query.all() for descriptor in descriptors: if descriptor.is_option_descriptor and \ descriptor.name != 'supercategories': choices =...
368667911b4eea8debb76ec8d44a17939d7022d4
10,443
def remove_dataset_tags(): """Command for removing tags from a dataset.""" command = Command().command(_remove_dataset_tags).lock_dataset() return command.require_migration().with_commit(commit_only=DATASET_METADATA_PATHS)
dcb45a70b5fb61a70de5acc8c2954771f4dfaed6
10,444
from typing import Optional def delete_device(connection: Connection, id: str, error_msg: Optional[str] = None): """Delete a device. Args: connection: MicroStrategy REST API connection object id: ID of the device error_msg (string, optional): Custom Error Message for Error Handling ...
5beda713239ee46048247d1cfb2952abbc8d1739
10,445
import tokenize def build_model(): """ Build a ML pipeline with RandomForest classifier GriSearch :return: GridSearch Output """ pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(RandomForestCla...
3c38d1e94c78f83fd1edfc91c6b16c67180d0ab6
10,446
def basic_auth(func): """Decorator for basic auth""" def wrapper(request, *args, **kwargs): try: if is_authenticated(request): return func(request, *args, **kwargs) else: return HttpResponseForbidden() except Exception, ex...
652894c4d9eaf8022c0a783d85fde61a8bfdc5eb
10,447
async def test_transmute(request, user: str, env: str=None, group: [str]=None): """ API Description: Transmute Get. This will show in the swagger page (localhost:8000/api/v1/). """ return { "user": user, "env": env, "group": group, }
8b3cf64fdd44b43227d72d63bf38e341a3c20d40
10,448
def ref_from_rfgc(sample): """ rename columns from RFGC catalog """ ref = dict( ra = sample['RAJ2000'], dec = sample['DEJ2000'], a = sample['aO'], b = sample['bO'], PA = sample['PA'] ) return ref
f93f4dfefc107c082f5454a59fb7a145ab9e9e60
10,450
import optparse def build_cmdline(): """ creates OptionParser instance and populates command-line options and returns OptionParser instance (cmd) """ cmd=optparse.OptionParser(version=__version__) cmd.add_option('-c', '', dest='config_fname',type="string", help='WHM/WHMCS configuration file', metavar="FILE") c...
c72dddfbf9bc728d06bae73bf028a85bc16d8261
10,451
import urllib def get_repo_slugname(repo): """ >>> get_repo_slugname("https://build.frida.re") build.frida.re >>> get_repo_slugname("https://build.frida.re/./foo/bar") build.frida.re >>> get_repo_slugname("://build.frida.re") build.frida.re """ parse_result = urllib.parse.urlparse(...
a36eec2c30018d3dbb298649d9d4c03586e60263
10,452
def lowess(x, y, f=2. / 3., itera=3): """lowess(x, y, f=2./3., iter=3) -> yest Lowess smoother: Robust locally weighted regression. The lowess function fits a nonparametric regression curve to a scatterplot. The arrays x and y contain an equal number of elements; each pair (x[i], y[i]) defines a dat...
9fd5543ab76d4ec61a08ad703e734122fe1fb718
10,453
import asyncio import aiohttp async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a config entry.""" tibber_connection = tibber.Tibber( access_token=entry.data[CONF_ACCESS_TOKEN], websession=async_get_clientsession(hass), time_zone=dt_util.DEFAULT_T...
64d893959afa3c5af6e0f293f691183a07d04363
10,454
def scenario_mask_vulnerable(plot=plt, show=False): """ creates scenario with different groups that are more or less vulnerable Args: plot: plot to show show (bool): variable if graphic should be shown Returns: plot: plot to show ani_humans: animation of the humans ...
aebdf569f2670ebb5ffcea5ccd1aad504f2447ae
10,455
def _operator_parser(expr, first, current): """This method parses the expression string and substitutes the temporal operators with numerical values. Supported operators for relative and absolute time are: - td() - the time delta of the current interval in days and fractions of days ...
fcee6006bdd9e96950b6e09f516895d89241a19a
10,456
def _read_data(filename): """ Read the script and return is as string :param filename: :return: """ javascript_path = _get_data_absolute_path(filename) with open(javascript_path) as javascript: return javascript.read()
73b2b3bc94831b761b29c8430044045217fd36ad
10,457
def schoollist(): """ Return all the schools. Return an empty schools object if no schools :return: """ items = get_schools() if items: return response_for_schools_list(get_schools_json_list(items)) return response_for_schools_list([])
3293fe590b3e7754c400c90da15a373fda909b13
10,460
from datetime import datetime def getNumNullops(duration, max_sample=1.0): """Return number of do-nothing loop iterations.""" for amount in [2**x for x in range(100)]: # 1,2,4,8,... begin = datetime.now() for ii in xrange(amount): pass elapsed = (datetime.now() - begin).total_seconds(...
5d3114267c1d844e95fb2fd4f9123914ba69dafc
10,461
def get_dependencies_from_wheel_cache(ireq): """Retrieves dependencies for the given install requirement from the wheel cache. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallReq...
e3bb4f57a989f4f8c049ae68262511a97110204d
10,462
def hbp_fn(): """Create a ReLU layer with HBP functionality.""" return HBPReLU()
3f8b8aaa460ae786b292e98891761b1596e369cc
10,463
def xtrans(r): """RBDA Tab. 2.2, p. 23: Spatial coordinate transform (translation of origin). Calculates the coordinate transform matrix from A to B coordinates for spatial motion vectors, in which frame B is translated by an amount r (3D vector) relative to frame A. """ r1,r2,r3 = r return matrix.sqr(( 1...
58620149cff92a261c3a3c500fdf3b7308aded67
10,464
def get_chop_flux(obs, chunk_method="nanmedian", method="nanmean", err_type="internal", weight=None, on_off=True): """ Calculate the flux in chopped data. The data will first be processed in each chop chunk by chunk_method, unless the chunk_method is set to None or 'none' and the data ...
010d7038ec0e9b3fa683b53077f78181bf656e5d
10,465
def my_example_embeddings_method(paths, embedding_size, default_value=1): """ :param paths: (list) a list of BGP paths; a BGP path is a list of integers (ASNs) :param embedding_size: (int) the size of the embedding :param default_value: (int) the value for the embeddings :return: (pandas dataframe o...
48e0c1b1089c236c74cdb82dde021cd9bebd62bf
10,466
def process_prompt_choice(value, prompt_type): """Convert command value to business value.""" if value is not None: idx = prompt_type(value) return idx raise CommandError("The choice is not exist, please choice again.")
b38f6f43da369928cea0058466578425a9b66024
10,467
import operator def summarise_input(rawimg, labelimg): """This function takes as input: 'rawimg' (the data) and 'labelimg' (the cell boundary cartoon) Then using the z=1, channel=1 frame, produces a summary table for inspection. It also calculates which label is the background, assuming it is the largest cell. ...
9442f8ecf4f00ad21895b4878395a99ec18b2019
10,468
import tempfile def create_inchi_from_ctfile_obj(ctf, **options): """Create ``InChI`` from ``CTfile`` instance. :param ctf: Instance of :class:`~ctfile.ctfile.CTfile`. :type ctf: :class:`~ctfile.ctfile.CTfile` :return: ``InChI`` string. :rtype: :py:class:`str` """ # apply fixed hydrogen l...
19f41603e37087aa6ca6fc79850b3456f86864e4
10,469
import io def get_info(df, verbose = None,max_cols = None, memory_usage = None, null_counts = None): """ Returns the .info() output of a dataframe """ assert type(df) is pd.DataFrame buffer = io.StringIO() df.info(verbose, buffer, max_cols, memory_usage, null_counts) return buffer.getvalue()
48e7e3f004c10125b2fece8a19950d05ac888032
10,470
def iwave_modes(N2, dz, k=None): """ Calculates the eigenvalues and eigenfunctions to the internal wave eigenvalue problem: $$ \left[ \frac{d^2}{dz^2} - \frac{1}{c_0} \bar{\rho}_z \right] \phi = 0 $$ with boundary conditions """ nz = N2.shape[0] # Remove the surface values ...
c3f930421916a2618ab69af4bab984f18cf962cc
10,472
def run_sql_migration(config, migration): """ Returns bool Runs all statements in a SQL migration file one-at-a-time. Uses get_statements as a generator in a loop. """ conn = config['conn'] write_log(config, "SQL migration from file '{}'".format(migration['filename'])) with op...
9a7eacb52f1ce3648f5fc336ef74ca89b3cb267b
10,473
from typing import Dict from typing import Any def get_variable_type(n: int, data: Dict[str, Any]) -> str: """Given an index n, and a set of data, return the type of a variable with the same index.""" if n in data[s.BOOL_IDX]: return VariableTypes.BINARY elif n in data[s.INT_IDX]: retu...
84b8efdf684aa7843edc938bc387df414d6e761a
10,474
import json import time def online_decompilation_main(result_path,path): """ :param online_decompiler_result_save_file: Store all the contract information in the name result.json, and then save it in this folder :param solidity_code_result: The address of the folder where the source code of the contract o...
c7e130c4dd3e148dd14d45a4cb21b36abe72094e
10,475
def calculate_snr( Efield: np.ndarray, freqRange: tuple, h_obs: float = 525.0, Nants: int = 1, gain: float = 10.0, ) -> np.ndarray: """ given a peak electric field in V/m and a frequency range, calculate snr Parameters Efield: np.ndarray peak electric field in V/m freqRa...
86caa7e8fe7d0ac7d47bebb2ae34e25679d23013
10,477
def retrieve_obj_indices(batch_cls: np.ndarray, num_classes: int): """Helper function to save the object indices for later. E.g. a batch of 3 samples with varying number of objects (1, 3, 1) will produce a mapping [[0], [1,2,3], [4]]. This will be needed later on in the bipartite matching. Paramete...
6361a1533f09239782cb96427e686d404bbcf9b5
10,478
def get_code_type(code): """ 判断代码是属于那种类型,目前仅支持 ['fund', 'stock'] :return str 返回code类型, fund 基金 stock 股票 """ if code.startswith(('00', '30', '60')): return 'stock' return 'fund'
6fc389ec053080b596368920adcd00e99e159817
10,479
import profile def sgd(lr, tparams, grads, inp, cost, opt_ret=None): """ Stochastic gradient descent (SGD) optimizer :param lr: :param tparams: :param grads: :param inp: :param cost: :param opt_ret: :return f_grad_shared, f_update: """ gshared = [theano.shared(p.get_value(...
f9dc199a65e807b47a2f95bb5f20cf3ce4dfef0d
10,480
def build_empty_indexes(ngram_len): """ Build and return the nested indexes structure. The resulting index structure can be visualized this way:: 1. The unigrams index is in indexes[1] with this structure: {1: { u1: {index_docid1: [posting_list1], index_docid2: [posting_list2]}, u...
019d141a7f02838de3e7464fae5f8dddf0ff7394
10,481
def test_if_in_for_tensor(): """ Feature: JIT Fallback Description: Test fallback with control flow. Expectation: No exception. """ @ms_function def control_flow_for(): x = Tensor(7) y = Tensor(0) for _ in range(3): if y < Tensor(10): y += ...
6de3a6d41ed1bdae4493ad0a4a6eb8304e7a546c
10,482
def as_dicts(results): """Convert execution results to a list of tuples of dicts for better comparison.""" return [result.to_dict(dict_class=dict) for result in results]
f7d3a77c0ef82439137c2ed6c706afc64d597256
10,483
def merge_dicts(dict_to_merge, merged_dict): """Recursively merge the contents of dict_to_merge into merged_dict. Values that are already present in merged_dict will be overwritten if they are also present in dict_to_merge""" for key, value in iteritems(dict_to_merge): if isinstance(merged_dict....
867d88d796ce51e075f29f1d530dd8d63b05c531
10,484
import importlib def _backend_name_to_class(backend_str: str): """ Convert a backend string to the test configuration class for the backend. """ known_backends = _get_all_backends() if backend_str not in known_backends: raise ValueError( f'Unknown backend {backend_str}. ' ...
1ab3aeb0fb16629197a943ff8fba92cacd692b77
10,485
def concat_allocator_cmd(allocator, cmd): """add env variable for different allocator modes.""" new_cmd = cmd if allocator == "direct": new_cmd = "DIRECT_BUFFER=1 " + cmd elif allocator == "unified": new_cmd = "UNIFIED_BUFFER=1 " + cmd elif allocator == "je_direct": new_cmd =...
b0275705d9a148c4b197e10847a0846e1e96d822
10,486
from typing import Tuple from typing import Optional from typing import List def generate_property_comment( description: intermediate.PropertyDescription, ) -> Tuple[Optional[Stripped], Optional[List[Error]]]: """Generate the documentation comment for the given property.""" return _generate_summary_remark...
21e7655b6efb98cbcac776fb988b7af483d9ebc3
10,487
def create_set(X, y, inds): """ X list and y nparray :return: """ new_X = [] for i in inds: new_X.append(X[i]) new_y = y[inds] return SignalAndTarget(new_X, new_y)
8f983d948449a39d539e8cf021585b936d23882d
10,488
def find_dates(): """ FInd valid dates """ text = read_file() valid = [] for i, c in enumerate(text): # Find "-" which we use identifier for possible dates if c == "-": try: date = validate_date_string(i, text) if date: ...
0af1558438e997685bd793125063be35ec466b36
10,489
def handle_400_error(_error): """Return a http 400 error to client""" return make_response(jsonify({'error': 'Misunderstood'}), 400)
76f85fc2eef7737a24178ca495357d0d0c752472
10,490
def control_norm_backward(grad_out, ustream, vstream, abkw, cache): """ Implements the forward pass of the control norm For each incoming sample it does: grad = grad_out - (1 - abkw) * vstream * out vstream = vstream + mu() y = (x - mstream) / sqrt(varstream) varstream ...
c42abb380addc595b1fb4d54e56313536d26fccc
10,491
from pathlib import Path from typing import Any def get_random_asset_id_of_dataset( db: Session = Depends(deps.get_db), dataset_id: int = Path(..., example="12"), viz_client: VizClient = Depends(deps.get_viz_client), current_user: models.User = Depends(deps.get_current_active_user), current_worksp...
02e6e28c27fc5720c9968e89209b3b3222fa7dcd
10,492
def seconds_to_hours(s): """Convert seconds to hours: :param s: Number of seconds :type s: Float :return: Number of hours :rtype: Float """ return float(s) / 3600
9bf9a7b408bf49714c4e873f59ec5433cc4f1ecf
10,493
def assign_change_priority(zone: dict, change_operations: list) -> None: """ Given a list of change operations derived from the difference of two zones files, assign a priority integer to each change operation. The priority integer serves two purposes: 1. Identify the relative order the changes. T...
6e5e538b8d7e6a7a1d4296bf94875814a47054ec
10,494
def contigs_n_bases(contigs): """Returns the sum of all n_bases of contigs.""" return sum(c.n_bases for c in contigs)
57bbc1712739bf8501ad95a5aa72adece6803bc3
10,495
def parse_input_fn_result(result): """Gets features, labels, and hooks from the result of an Estimator input_fn. Args: result: output of an input_fn to an estimator, which should be one of: * A 'tf.data.Dataset' object: Outputs of `Dataset` object must be a tuple (features, labels) with same cons...
3cada76012f3a56d30bcc29c3658ef32df26d605
10,496