content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_mgga_data(mol, grid, rdm1): """ Get atomic orbital and density data. See eval_ao and eval_rho docs for details. Briefly, returns 0-3 derivatives of the atomic orbitals in ao_data; and the density, first derivatives of density, Laplacian of density, and kinetic energy density in r...
11de048bbe320721204171d9786a997411b953d6
3,645,000
def _stringify_lmer_warnings(fg_lmer): """create grid w/ _ separated string of lme4::lmer warning list items, else "" """ warning_grids = fitgrid.utils.lmer.get_lmer_warnings( fg_lmer ) # dict of indicator dataframes warning_string_grid = pd.DataFrame( np.full(fg_lmer._grid.shape, ""),...
bbd0fedb2480d4d1ef2a98689861c112552c0b59
3,645,001
def index(): """Loads the index page for the 'Admin' controller :returns: a dictionary to pass to the view with the list of ctr_enabled and the active module ('admin') """ ctr_data = get_ctr_data() users = db().select(db.auth_user.ALL) approvals = db(db.auth_user.registration_key=='pending').select(db.auth_user....
4b5dc978361b970d2dc6b2f5c6df28b06c9f28bf
3,645,002
def get_language_codes(): """Returns a list of available languages and their 2 char input codes """ languages = get_languages() two_dig_codes = [k for k, v in languages.items()] return two_dig_codes
2e368b73783630835ee1ec32875318725f62d72e
3,645,003
def fun_evaluate_ndcg(user_test_recom_zero_one): """ 计算ndcg。所得是单个用户test的,最后所有用户的求和取平均 :param test_lst: 单个用户的test集 :param zero_one: 0/1序列 :param test_mask: 单个用户的test列表对应的mask列表 :return: """ test_lst, zero_one, test_mask, _ = user_test_recom_zero_one test_lst = test_lst[:np.sum(test_ma...
018dcf1095ebdd02e253ae6c1c36e17d1f13431a
3,645,004
def prettyDataSize(size_in_bytes): """ Takes a data size in bytes and formats a pretty string. """ unit = "B" size_in_bytes = float(size_in_bytes) if size_in_bytes > 1024: size_in_bytes /= 1024 unit = "kiB" if size_in_bytes > 1024: size_in_bytes /= 1024 unit = "MiB" ...
30eb068bafe2d9457ea43b59f2f62bdd0ce1c927
3,645,005
import os def get_env(env_name: str) -> str: """ Safely read an environment variable. Raises errors if it is not defined or it is empty. :param env_name: the name of the environment variable :return: the value of the environment variable """ if env_name not in os.environ: raise KeyError(f"{env_name} not def...
742a251561e02f59da667d8ebc586d5e0b399103
3,645,006
def image_resize_and_sharpen(image, size, preserve_aspect_ratio=False, factor=2.0): """ Create a thumbnail by resizing while keeping ratio. A sharpen filter is applied for a better looking result. :param image: PIL.Image.Image() :param size: 2-tuple(width, height) :param pre...
7f581a0a8b1dccf62a3840269e7b2cea1e78a13b
3,645,007
import subprocess import pipes def callHgsql(database, command): """ Run hgsql command using subprocess, return stdout data if no error.""" cmd = ["hgsql", database, "-Ne", command] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) cmdout, cmderr = p.communicate() if p.retu...
d44dce04452323b417830fad1c34fb1ebca300fe
3,645,008
def validate_mash(seq_list, metadata_reports, expected_species): """ Takes a species name as a string (i.e. 'Salmonella enterica') and creates a dictionary with keys for each Seq ID and boolean values if the value pulled from MASH_ReferenceGenome matches the string or not :param seq_list: List of OLC Se...
9eb4fd6e1f156a4fed3cc0be0c5b7153a05b038b
3,645,009
def style_strokes(svg_path: str, stroke_color: str='#ff0000', stroke_width: float=0.07559055) -> etree.ElementTree: """Modifies a svg file so that all black paths become laser cutting paths. Args: svg_path: a file path to the svg file to modify and overwrite. stroke_color: the...
6387625cd71143edb632833cd40006858f239089
3,645,010
import json def preview_pipeline( pipeline: Pipeline, domain_retriever: DomainRetriever, limit: int = 50, offset: int = 0 ) -> str: """ Execute a pipeline but returns only a slice of the results, determined by `limit` and `offset` parameters, as JSON. Return format follows the 'table' JSON table sche...
f1e640ec73bbdeb978762774c81d80e00e98adc9
3,645,011
def redirect_to_url(url): """ Return a bcm dictionary with a command to redirect to 'url' """ return {'mode': 'redirect', 'url': url}
01e4deb80bbd8f8e119c99d64001866c6cd644d9
3,645,012
def get_xml_tagged_data(buffer, include_refstr=True): """ figure out what format file it is and call the respective function to return data for training :param buffer: :param include_refstr: during training do not need refstr :return: """ if len(buffer) > 1 and 'http://www.elsevier.com/...
e51cdde728d3e4c5c1f4936bfeb874be8aabf292
3,645,013
from typing import Dict from typing import Any def de_dup( data: pd.DataFrame, drop_duplicates_kwargs: Dict[str, Any] = {}, ) -> pd.DataFrame: """Drop duplicate rows """ return data.drop_duplicates(**drop_duplicates_kwargs)
2cd78627226170af7e184bc60caa5ee39290ab42
3,645,014
def get_task_defs(workspace: str, num_validators: int, num_fullnodes: int) -> dict: """ Builds a dictionary of: family -> current_task_def task_def can be used to get the following when updating a service: - containerDefinitions - volumes - placementConstraints NOTE: on...
99c131ac60999dd1b2b657575e40f2b813633f61
3,645,015
from azure.mgmt.marketplaceordering.models import OfferType def get_terms(cmd, urn=None, publisher=None, offer=None, plan=None): """ Get the details of Azure Marketplace image terms. :param cmd:cmd :param urn:URN, in the format of 'publisher:offer:sku:version'. If specified, other argument values can ...
7483e6d150b784535dd47ead0b63d079e66c391d
3,645,016
def encode_payload( result ): """JSON encodes a dictionary, named tuple, or object for sending to the server """ try: return tornado.escape.json_encode( result ) except TypeError: if type( result ) is list: return [ tornado.escape.json_encode( r ) for r in result ] ...
551264dcb0b9ad6d380b8ae393b2dfbfafb93dee
3,645,017
def relu(shape) -> np.ndarray: """ Creates a gaussian distribution numpy array with a mean of 0 and variance of sqrt(2/m). Arguments: shape : tuple : A tuple with 2 numbers, specifying size of the numpy array. Returns: output : np.ndarray : A uniform numpy array. """ return np.random.normal(0, np.s...
e41835dc5e6de8f0b6161c8ea73afeffd8f84c31
3,645,018
def reset_all(): """Batch reset of batch records.""" _url = request.args.get("url") or request.referrer task_id = request.form.get("task_id") task = Task.get(task_id) try: count = utils.reset_all_records(task) except Exception as ex: flash(f"Failed to reset the selected records:...
a4241ce81531db7d18d226327f6a96b600a50fd0
3,645,019
def update_to_report(db, data, section_name, img_path,id): """ Update data of report """ query = '''UPDATE report SET data = "{}" , section_name = "{}", image_path = "{}" WHERE id = "{}" '''.format(data, section_name, img_path, id) result = ge...
995d17b364bcb6a0b338b1b0323b0fd1f7692f25
3,645,020
from datetime import datetime def keyboard(table, day=None): """Handler for showing the keyboard statistics page.""" cols, group = "realkey AS key, COUNT(*) AS count", "realkey" where = (("day", day),) if day else () counts_display = counts = db.fetch(table, cols, where, group, "count DESC") if "c...
d3053f06b85d6606353b71a76096558d760e5a8e
3,645,021
import base64 import logging def fetch(uri, username='', password=''): """Can fetch with Basic Authentication""" headers = {} if username and password: headers['Authorization'] = 'Basic ' + base64.b64encode('%s:%s' % (username, password)) headers['User-Agent'] = 'Twimonial' f = urlfetch.fetch(uri, ...
e28e96c049d7b4844ca23bd8943b00b29ede3419
3,645,022
def tsCrossValidationScore(params, series,loss_function=mean_squared_error, nsplits=3, slen=1): """ #Parameters: params : vector of parameters for optimization (three parameters: alpha, beta, gamma for example series : dataset with timeseries sle: ...
f3278ad55a423f6df0b108636c88151a72451cfa
3,645,023
from typing import Any def get_psf_fwhm(psf_template: np.ndarray) -> float: """ Fit a symmetric 2D Gaussian to the given ``psf_template`` to estimate the full width half maximum (FWHM) of the central "blob". Args: psf_template: A 2D numpy array containing the unsaturated PSF templ...
1982d89eb5f952d10336003e4d580fda3ab210b7
3,645,024
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: (int): Floored Square Root """ assert number >= 0, 'Only square root of positive numbers are valid' start = 0 end = number res = None...
7ed4d547e0dbabebff7ffdf1e368817a415cbb9e
3,645,025
def repetition_sigmoid(M): """ Used to model repetition-driven effects of STDP. More repetitions results in stronger increase/decrease. """ return 1.0/(1+np.exp(-0.2*M+10))
5cfae40b12f2ff871b60f9cad13308b8bb9189b9
3,645,026
def generate_features(ids0, ids1, forcefield, system, param): """ This function performs a minimization of the energy and computes the matrix features. :param ids0: ids of the atoms for the 1st protein :param ids1: ids of the atoms for the 2nd protein :param forcefield: forcefield for OpenMM simula...
86fbc0fa67ea5a14b38af4c1fc37566b066b50a3
3,645,027
def extract_bow_feature_vectors(reviews, dictionary): """ Inputs a list of string reviews Inputs the dictionary of words as given by bag_of_words Returns the bag-of-words feature matrix representation of the data. The returned matrix is of shape (n, m), where n is the number of reviews and m the...
3373179024127ab0202ab50f3e20184d02ed016c
3,645,028
from astropy.io.fits import Header from scipy.optimize import least_squares def model_wcs_header(datamodel, get_sip=False, order=4, step=32): """ Make a header with approximate WCS for use in DS9. Parameters ---------- datamodel : `jwst.datamodels.ImageModel` Image model with full `~g...
1b43d5382b92f7da47d72dcf5acaaca65c6329df
3,645,029
def create_session(): """Return a session to be used for database connections Returns: Session: SQLAlchemy session object """ # Produces integrity errors! # return _Session() # db.session is managed by Flask-SQLAlchemy and bound to a request return db.session
8c7dbc2ee1db64cfbbb3466704a7e4f70ef073be
3,645,030
def meta_to_indexes(meta, table_name=None, model_name=None): """Find all the indexes (primary keys) based on the meta data """ indexes, pk_field = {}, None indexes = [] for meta_model_name, model_meta in meta.iteritems(): if (table_name or model_name) and not (table_name == model_meta['Met...
12c12055f424680a68d81d5466dc6d3515d797a5
3,645,031
def index(): """Render and return the index page. This is a informational landing page for non-logged-in users, and the corp homepage for those who are logged in. """ success, _ = try_func(auth.is_authenticated) if success: module = config.get("modules.home") if module: ...
9ebc7a98ee60a59a5bed6ec5a726c5c1a5a11ca7
3,645,032
def _(origin, category="", default=None): """ This function returns the localized string. """ return LOCALIZED_STRINGS_HANDLER.translate(origin, category, default)
58f1d7033b1689068bf1bcb532eea78e8bf51250
3,645,033
from datetime import datetime def next_month(month: datetime) -> datetime: """Find the first day of the next month given a datetime. :param month: the date :type month: datetime :return: The first day of the next month. :rtype: datetime """ dt = this_month(month) return datetime((dt+_...
1d5cb70fa7b3d98689e3dd967aa95deb29f5de45
3,645,034
from typing import Mapping from typing import OrderedDict def walk_json(d, func): """ Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result """ if isinstance(d, Mapping): return OrderedDict((k, walk_json(v, func)) for k, v in d.items()) elif...
cc977f4cf3eaec03bd591fa4cd1e44ab5717caee
3,645,035
def getUser(): """This method will be called if a GET request is made to the /user/ route It will get the details of a specified user Parameters ---------- username the name of the user to get info about Raises ------ DoesNotExist Raised if the username provided doe...
edc8570b83e4a173ac8028f2d8b51e93a19b27a1
3,645,036
import types def _create_ppo_agent( time_step_spec: types.NestedTensorSpec, action_spec: types.NestedTensorSpec, preprocessing_layers: types.NestedLayer, policy_network: types.Network) -> tfa.agents.TFAgent: """Creates a ppo_agent.""" actor_network = policy_network( time_step_spec.observation, ...
931e7078bdf634187ac0a506decb2d651373fbab
3,645,037
def stiffness_matrix_CST(element=tetra_4()): """Calculate stiffness matrix for linear elasticity""" element.volume() B = strain_matrix_CST(element) D = material() print('B') print(B) print('V',element.V) return element.V * np.dot(np.dot(np.transpose(B),D),B)
5c5c443ab1007997848357d698fcce91f069a13f
3,645,038
async def can_action_member(bot, ctx: SlashContext, member: discord.Member) -> bool: """ Stop mods from doing stupid things. """ # Stop mods from actioning on the bot. if member.id == bot.user.id: return False # Stop mods from actioning one another, people higher ranked than them or themselves....
c3fa4eee66ec80df2c4f91cfee181d900f0b8c45
3,645,039
import types def trim_waveform_signal( tr: obspy.Trace, cfg: types.ModuleType = config ) -> obspy.Trace: """Cut the time series to signal window Args: tr: time series cfg: configuration file Returns: tr: trimmed time series """ starttime, en...
bce3a0f88903b7c62c287f6e40bb7d377215a45d
3,645,040
def animation_plot( x, y, z_data, element_table, ani_fname, existing_fig, ani_funcargs=None, ani_saveargs=None, kwargs=None, ): """ Tricontourf animation plot. Resulting file will be saved to MP4 """ global tf # Subtract 1 from element table to alig...
e9ef60c6240900de6fd082ff5933dbbbc471933a
3,645,041
def preprocess_adj(adj): """Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation.""" # adj_appr = np.array(sp.csr_matrix.todense(adj)) # # adj_appr = dense_lanczos(adj_appr, 100) # adj_appr = dense_RandomSVD(adj_appr, 100) # if adj_appr.sum(1).min()<0: # ...
82674be0b9573c24135e56f2a5e3988fbb0966e1
3,645,042
def plot_figure_one_input_resource_2(style_label=""): """ Plot two bar graphs side by side, with letters as x-tick labels. latency_dev_num_non_reuse.log """ prng = np.random.RandomState(96917002) #plt.set_cmap('Greys') #plt.rcParams['image.cmap']='Greys' # Tweak the figure size to b...
69c25829adf9ef3d5dc818621bb724bb92c29f31
3,645,043
def comp_rot_dir(self): """Compute the rotation direction of the winding Parameters ---------- self : LamSlotWind A LamSlotWind object Returns ------- rot_dir : int -1 or +1 """ MMF = self.comp_mmf_unit() p = self.get_pole_pair_number() # Compute rotation ...
524fdfd195a70bcd07b89e594a90e624ec4db4ea
3,645,044
def search_pk(uuid): """uuid can be pk.""" IterHarmonicApprox = WorkflowFactory("phonopy.iter_ha") qb = QueryBuilder() qb.append(IterHarmonicApprox, tag="iter_ha", filters={"uuid": {"==": uuid}}) PhonopyWorkChain = WorkflowFactory("phonopy.phonopy") qb.append(PhonopyWorkChain, with_incoming="ite...
d1a8d9d32e6d3272d49163ee8abf74363a520c8d
3,645,045
def _region_bulk(mode='full', scale=.6): """ Estimate of the temperature dependence of bulk viscosity zeta/s. """ plt.figure(figsize=(scale*textwidth, scale*aspect*textwidth)) ax = plt.axes() def zetas(T, zetas_max=0, zetas_width=1): return zetas_max / (1 + ((T - Tc)/zetas_width)**2) ...
9a76f28b47a5e8c1ce45a9ea0dcaef723032bcce
3,645,046
def bias(struct,subover=True,trim=True, subbias=False, bstruct=None, median=False, function='polynomial',order=3,rej_lo=3,rej_hi=3,niter=10, plotover=False, log=None, verbose=True): """Bias subtracts the bias levels from a frame. It will fit and subtract the overscan region, trim the images...
035da6b5eaa73a30ffec3f148d33199b275529a8
3,645,047
def getItemStatus(selected_item, store_id, num_to_average): """ Method pulls the stock status of the selected item in the given store :param selected_item: current item being processed (toilet paper or hand sanitizer) :param store_id: id of the current store :param num_to_average: number of recent stat...
00c0ecdec56ac4446b3db247fd234daeecada589
3,645,048
def filter_and_copy_table(tab, to_remove): """ Filter and copy a FITS table. Parameters ---------- tab : FITS Table object to_remove : [int ...} list of indices to remove from the table returns FITS Table object """ nsrcs = len(tab) mask = np.zeros((nsrcs), '?') mas...
cc13a002715c36cc2c07b836a5045cfb62311529
3,645,049
def _archive_logs(conn, node_type, logger, node_ip): """Creates an archive of all logs found under /var/log/cloudify plus journalctl. """ archive_filename = 'cloudify-{node_type}-logs_{date}_{ip}.tar.gz'.format( node_type=node_type, date=get_host_date(conn), ip=node_ip ) ...
970683258d664a1170fe9ab5253287313fa9f871
3,645,050
def get_scripts(): """Returns the list of available scripts Returns: A dict holding the result message """ return Response.ok("Script files successfully fetched.", { "scripts": list_scripts() })
5aa2ecd9a19c3e4d577c679e5249b71b01b62f20
3,645,051
from typing import Any from typing import Optional import functools import contextvars import asyncio from typing import cast async def invoke( fn: callbacks.BaseFn, *args: Any, settings: Optional[configuration.OperatorSettings] = None, cause: Optional[causation.BaseCause] = None, ...
4f132bab3eaae0ebe64f4cfdcfefa89cd2b59f3f
3,645,052
import sys def getLatestFare(_origin, _destination, _date): """ _origin and _destination take airport codes , e.g. BLR for Bangalore _date in format YYYY-MM-DD e.g.2016-10-30 Returns either: 10 latest results from the results page. 1 lastest result from the results page. """ tr...
209c9c4ee05dc25b575565b0953097049ba21c28
3,645,053
from datetime import datetime def home(): """Renders the home page.""" return render_template( 'index.html', title='Rococal', year=datetime.now().year, )
4cee1eed6c45d79aad0acebdd55ed61ef7dff9da
3,645,054
def Dx(x): """Nombre de survivants actualisés. Args: x: l'âge. Returns: Nombre de survivants actualisés. """ return lx(x)*v**x
886fdfb8b5337e9520f94fa937cb967328391823
3,645,055
def tracek(k,aee,aii,see,sii,tau=1,alpha=0): """ Trace of recurrently connected network of E,I units, analytically determined input: k: spatial frequency aee: ampltidue E to E connectivity aii: ampltidue I to I connectivity see: standard deviation/width of E to E connectivity sii: standard deviation/width of I ...
005c612f8d54b4ba61b7e701d40b9814136695b4
3,645,056
import os def set_working_dir_repo_root(func): """ Decorator for checking whether the current working dir is set as root of repo. If not, changes the working dir to root of repo Returns ------- """ def inner(*args, **kwargs): git_repo = git.Repo(".", search_parent_directories...
07a6d667129d94557fdd20956124933920338e30
3,645,057
def get_verbose_name(model_or_queryset, field): """ returns the value of the ``verbose_name`` of a field typically used in the templates where you can have a dynamic queryset :param model_or_queryset: target object :type model_or_queryset: :class:`django.db.models.Model`, :class:`django.db.query....
1f395d62a20b307dce2f802c498630fd237aec33
3,645,058
def if_then_else(cond, t, f, span=None): """Conditional selection expression. Parameters ---------- cond : PrimExpr The condition t : PrimExpr The result expression if cond is true. f : PrimExpr The result expression if cond is false. span : Optional[Span] ...
dba758c13d3108244f389f0cbae97c1eeb1f8e04
3,645,059
import argparse def get_args() -> argparse.Namespace: """Get arguments.""" parser = argparse.ArgumentParser(description="Dump Instance") parser.add_argument( "network_state_path", type=str, help="File path to network state dump JSON." ) parser.add_argument("--host", type=str, help="Host to...
30b1aacc2c13d1ac8fad3411b95d9aeabf625f62
3,645,060
def get_resources(filetype): """Find all HTML template or JavaScript files in the package. Caches the results for quick access. Parameters ---------- filetype : {'templates', 'js'} The type of file resource needed. Returns ------- :class:`dict` A dictionary mapping fil...
73244ac590db5a310170142b6b43b7840cfc94ca
3,645,061
def sum_fn(xnum, ynum): """ A function which performs a sum """ return xnum + ynum
61a1ae2e4b54348b9e3839f7f2779edd03f181df
3,645,062
def categorical_iou(y_true, y_pred, target_classes=None, strict=True): """画像ごとクラスごとのIoUを算出して平均するmetric。 Args: target_classes: 対象のクラスindexの配列。Noneなら全クラス。 strict: ラベルに無いクラスを予測してしまった場合に減点されるようにするならTrue、ラベルにあるクラスのみ対象にするならFalse。 """ axes = list(range(1, K.ndim(y_true))) y_classes = K.ar...
b79f399479127271c3af3ee9b28203622f8d17fe
3,645,063
def convert_string(string: str, type: str) -> str: """Convert the string by [e]ncrypting or [d]ecrypting. :param type: String 'e' for encrypt or 'd' for decrypt. :return: [en/de]crypted string. """ hash_string = hash_() map_ = mapping(hash_string) if type.lower() == 'e': output = e...
824122fa035dcb164f21eadb5c0e840f8acd2914
3,645,064
def create_saml_security_context(token, private_key): """ Create a security context for SAML token based authentication scheme :type token: :class:`str` :param token: SAML Token :type private_key: :class:`str` :param private_key: Absolute file path of the private key of the user :rtyp...
430e71697eb3e5b3df438f400a7f07ab8e936af7
3,645,065
def predictIsDeviceLeftRunning(): """ Returns if the device is presumed left running without a real need --- parameters: name: -device_id in: query description: the device id for which the prediction is made required: false style: form explode: true ...
8a50962f3c52e100d79a74413df0d4bf8230bafd
3,645,066
from typing import Optional from typing import Callable from pathlib import Path def load( source: AnyPath, wordnet: Wordnet, get_synset_id: Optional[Callable] = None, ) -> Freq: """Load an Information Content mapping from a file. Arguments: source: A path to an information content weigh...
962bdfbe5d101bdeae966566c16d8a7216c36d8b
3,645,067
from datetime import datetime def iso_time_str() -> str: """Return the current time as ISO 8601 format e.g.: 2019-01-19T23:20:25.459Z """ now = datetime.datetime.utcnow() return now.isoformat()[:-3]+'Z'
203617006175079181d702f7d7ed6d2974714f2e
3,645,068
def mass(snap: Snap) -> Quantity: """Particle mass.""" massoftype = snap._file_pointer['header/massoftype'][()] particle_type = np.array( np.abs(get_dataset('itype', 'particles')(snap)).magnitude, dtype=int ) return massoftype[particle_type - 1] * snap._array_code_units['mass']
cf67d66f1e1a47f162b5e538444d2c406b377238
3,645,069
import os def _build_pytest_test_results_path(cmake_build_path): """ Build the path to the Pytest test results directory. :param cmake_build_path: Path to the CMake build directory. :return: Path to the Pytest test results directory. """ pytest_results_path = os.path.join(cmake_build_path, TES...
52198ce508d5d30c322da285c66ff9ba45418ebd
3,645,070
import logging async def create_object_detection_training( train_object_detection_model_request: TrainImageModel, token: str = Depends(oauth2_scheme), ): """[API router to train AutoML object detection model] Args: train_object_detection_model_request (TrainImageModel): [Train AutoML Object d...
293dc0bfd8acb52a3207138e13028b6766c7be20
3,645,071
import torch def batchify_rays(rays_flat, chunk=1024*32, random_directions=None, background_color=None, **kwargs): """Render rays in smaller minibatches to avoid OOM. """ all_ret = {} for i in range(0, rays_flat.shape[0], chunk): ret = render_rays(rays_flat[i:i+chunk], random_directions=random...
9897575462e47f98016ebd0a2fcaee186c440f9a
3,645,072
def extract_surfaces(pvol): """ Extracts surfaces from a volume. :param pvol: input volume :type pvol: abstract.Volume :return: extracted surface :rtype: dict """ if not isinstance(pvol, BSpline.abstract.Volume): raise TypeError("The input should be an instance of abstract.Volume") ...
cd2b24f200adf9f5ff29cc847693d57d450521ad
3,645,073
import os import logging def read_file(filepath: str, config: Config = DEFAULT_CONFIG) -> pd.DataFrame: """ Read .csv, .xlsx, .xls to pandas dataframe. Read only a certain sheet name and skip to header row using sheet_name and header_index. :filepath: path to file (str) :config: dtype...
09f9e626be020cf2d3c02a09863489cf84735c05
3,645,074
def euler2quaternion( euler_angs ): """ Description ----------- This code is directly from the following reference [REF] https://computergraphics.stackexchange.com/questions/8195/how-to-convert-euler-angles-to-quaternions-and-get-the-same-euler-angles-back-fr Conv...
307385911573af8a6e65617a8b438ca680130b79
3,645,075
def run_server(server, thread=False, port=8080): """ Runs the server. @param server if None, it becomes ``HTTPServer(('localhost', 8080), SimpleHandler)`` @param thread if True, the server is run in a thread and the function returns right away, ...
524b58f012a1029e52d845f40a20e2ae1f7f9c0a
3,645,076
def validate(aLine): """ >>> validate(b"$GPGSA,A,2,29,19,28,,,,,,,,,,23.4,12.1,20.0*0F") [b'GPGSA', b'A', b'2', b'29', b'19', b'28', b'', b'', b'', b'', b'', b'', b'', b'', b'', b'23.4', b'12.1', b'20.0'] >>> validate(b"$GPGSA,A,2,29,19,28,,,,,,,,,,23.4,") # doctest: +IGNORE_EXCEPTION_DETAIL Traceb...
a8f302f0a03f567bc3c61930ecdf147ff9670b04
3,645,077
def matlabize(s): """Make string s suitable for use as a MATLAB function/script name""" s = s.replace(' ', '_') s = s.replace('.', '_') s = s.replace('-', '_') assert len(s) <= 63 # MATLAB function/script name length limitation return s
5dccb9497a3ee28dae5fb7de6e15a1fa02f144cf
3,645,078
def getApiResults(case, installer, version, criteria): """ Get Results by calling the API criteria is to consider N last results for the case success criteria """ results = json.dumps([]) # to remove proxy (to be removed at the end for local test only) # proxy_handler = urllib2.ProxyHandler...
d54eaf785bc1e80e633cf3f6588f135c54425b79
3,645,079
def generate_noisy_gaussian(center, std_dev, height, x_domain, noise_domain, n_datapoints): """ Generate a gaussian with some aspect of noise. Input: center = central x value std_dev = standard deviation of the function height = height (y-off set) of the ...
5120bb23be1b98663b61ad67df0aa43c61ed1714
3,645,080
from typing import Tuple def filter_group_delay( sos_or_fir_coef: np.ndarray, N: int = 2048, fs: float = None, sos: bool = True, ) -> Tuple[np.ndarray, np.ndarray]: """ Given filter spec in second order sections or (num, den) form, return group delay. Uses method in [1], which is cited by ...
9cdcf30db5f1308dac27ce057f392fb38d805f1f
3,645,081
import re def query(): """Perform a query on the dataset, where the search terms are given by the saleterm parameter""" # If redis hasn't been populated, stick some tweet data into it. if redis_db.get("tweet_db_status") != "loaded": tweet_scraper.add_tweets(default_num_tweets_to_try) sale_ter...
9cdb937d45b1314884afb0d53aee174ef160f8a8
3,645,082
def get_spec_res(z=2.2, spec_res=2.06, pix_size=1.8): """ Calculates the pixel size (pix_size) and spectral resolution (spec_res) in km/s for the MOCK SPECTRA. arguments: z, redshift. spec_res, spectral resoloution in Angst. pixel_size in sngst. returns: (pixel_size, spec_res) in km/s """ ...
597db8ce00c071624b0877fe211ab9b01ec889de
3,645,083
from datetime import datetime import os def _process_general_config(config: ConfigType) -> ConfigType: """Process the `general` section of the config Args: config (ConfigType): Config object Returns: [ConfigType]: Processed config """ general_config = deepcopy(config.general) ...
370367f718c3830964c6f5f276b1d699400fd1ab
3,645,084
def api_response(response): """Response generation for ReST API calls""" # Errors present if response.message: messages = response.message if not isinstance(messages, list): messages = [messages] # Report the errors return Response({'errors': messages}, status=s...
f41bca36b1cabc6002f730b3b40170415baffc62
3,645,085
from tensorflow.python.training import moving_averages def batch_norm(name, inpvar, decay=0.9, epsilon=1e-5, use_affine=True, param_dtype=__default_dtype__): """ Batch normalization. :param name: operator name :param inpvar: input tensor, of data type NHWC :param decay: decay for moving average ...
74565379d15d4ec7cfa647a4f7833328f2c86ac7
3,645,086
import os def get_engine(onnx_file_path, engine_file_path="", input_shapes=((1, 3, 640, 640)), force_rebuild=False): """Attempts to load a serialized engine if available, otherwise builds a new TensorRT engine and saves it.""" assert len(input_shapes) in [1, 3], 'length of input_shapes should be 1 or 3, 3 fo...
57489225c3854408f880f024443811d59c88df9f
3,645,087
from typing import Callable def _window_when(closing_mapper: Callable[[], Observable]) -> Callable[[Observable], Observable]: """Projects each element of an observable sequence into zero or more windows. Args: source: Source observable to project into windows. Returns: An observable ...
d0f51f8385b2d45f1cbd64649953c312247644eb
3,645,088
def generate_features(df): """Generate features for a stock/index based on historical price and performance Args: df(dataframe with columns "Open", "Close", "High", "Low", "Volume", "Adjusted Close") Returns: dataframe, data set with new features """ df_new = pd.DataFrame() #...
ec64c9562287e0dd32b7cfd07c477acd8d799dc3
3,645,089
from typing import Dict from typing import Union from typing import Optional def format_plate(barcode: str) -> Dict[str, Union[str, bool, Optional[int]]]: """Used by flask route /plates to format each plate. Determines whether there is sample data for the barcode and if so, how many samples meet the fit to pi...
5508ee508ef6d2a8329a2899bf9e90c9ac399874
3,645,090
def method_only_in(*states): """ Checks if function has a MethodMeta representation, calls wrap_method to create one if it doesn't and then adds only_in to it from *states Args: *args(list): List of state names, like DefaultStateMachine.RESETTING Returns: function: Updated function...
33fbd619deb4b2a1761b3bf7f860ed2ae728df44
3,645,091
import igraph def to_igraph(adjacency_matrix:Image, centroids:Image=None): """ Converts a given adjacency matrix to a iGraph [1] graph data structure. Note: the given centroids typically have one entry less than the adjacency matrix is wide, because those matrices contain a first row and column repre...
e0cac1dd85b79b30e3f7e3139201b97e092603eb
3,645,092
def Laplacian(src, ddepth, dst=None, ksize=1, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT): """dst = cv.Laplacian( src, ddepth[, dst[, ksize[, scale[, delta[, borderType]]]]] ) Executes the Laplacian operator on hardware if input parameters fit to hardware constraints. Otherwise the OpenCV Laplacian fun...
88237f83ed9b2159829f4a9b194c18007699c1a9
3,645,093
def get_docptr(n_dw_matrix): """ Parameters ---------- n_dw_matrix: array-like Returns ------- np.array row indices for the provided matrix """ return _get_docptr(n_dw_matrix.shape[0], n_dw_matrix.indptr)
7a20ca17f16475d6fd836bb5b7b70221f5cf4378
3,645,094
def check_if_shift_v0(data, column_name, start_index, end_index, check_period): """ using median to see if it changes significantly in shift """ period_before = data[column_name][start_index - check_period: start_index] period_in_the_middle = data[column_name][start_index:end_index] period_after = data[...
e73629dae7d6cce70b344f24acb98a3ae24c4e64
3,645,095
def opening2d(value, kernel, stride=1, padding="SAME"): """ erode and then dilate Parameters ---------- value : Tensor 4-D with shape [batch, in_height, in_width, depth]. kernel : Tensor Must have the same type as 'value'. 3-D with shape '[kernel_height, kernel_width, depth]...
b425735dacceac825b4394fdc72a744b168acc91
3,645,096
def convert_npy_mat(user_num, item_num, df): """ method of convert dataframe to numpy matrix Parameters ---------- user_num : int, the number of users item_num : int, the number of items df : pd.DataFrame, rating dataframe Returns ------- mat : np.matrix, rating matrix """ ...
627fcc45a490be1554445582dc8a2312e25b1152
3,645,097
def user_enter_state_change_response(): """ Prompts the user to enter a key event response. nothing -> str """ return input('>> ')
22da5cb99fa603c3dff04e8afd03cb9fae8210cd
3,645,098
def call_worker(job_spec): """Calls command `cron_worker run <job_spec>` and parses the output""" output = call_command("cron_worker", "run", job_spec) status = exc_class_name = exc_message = None if output: result_match = RESULT_PATTERN.match(output) if result_match: status ...
5a914c742319e2528b1668309ff57e507efd26bb
3,645,099