content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def geocentric_rotation(sphi, cphi, slam, clam): """ This rotation matrix is given by the following quaternion operations qrot(lam, [0,0,1]) * qrot(phi, [0,-1,0]) * [1,1,1,1]/2 or qrot(pi/2 + lam, [0,0,1]) * qrot(-pi/2 + phi , [-1,0,0]) where qrot(t,v) = [cos(t/2), sin(t/2)*v[1], sin(t/2)*v[...
83d37e79e35cab2fc309a640751fb85a9cab0177
3,659,200
def get_price_sma( ohlcv: DataFrame, window: int = 50, price_col: str = "close", ) -> Series: """ Price to SMA. """ return pd.Series( ohlcv[price_col] / get_sma(ohlcv, window), name="Price/SMA{}".format(window), )
7f356610462b9f0fbc13c02c6f093d5ec29d4e76
3,659,201
def map_to_closest(multitrack, target_programs, match_len=True, drums_first=True): """ Keep closest tracks to the target_programs and map them to corresponding programs in available in target_programs. multitrack (pypianoroll.Multitrack): Track to normalize. target_programs (list): List of availabl...
7fd91726fbc66dd3a3f233be9056c00b1b793f46
3,659,202
import time def train_naive(args, X_train, y_train, X_test, y_test, rng, logger=None): """ Compute the time it takes to delete a specified number of samples from a naive model sequentially. """ # initial naive training time model = get_naive(args) start = time.time() model = model.fit...
0514df318219a9f69dbd49b65cad2664480e3031
3,659,203
def helperFunction(): """A helper function created to return a value to the test.""" value = 10 > 0 return value
2c4f2e5303aca2a50648860de419e8f94581fee7
3,659,204
def app_config(app_config): """Get app config.""" app_config['RECORDS_FILES_REST_ENDPOINTS'] = { 'RECORDS_REST_ENDPOINTS': { 'recid': '/files' } } app_config['FILES_REST_PERMISSION_FACTORY'] = allow_all app_config['CELERY_ALWAYS_EAGER'] = True return app_config
156f48cfd0937e5717de133fdfdf38c86e66ba71
3,659,205
from datetime import datetime def ts(timestamp_string: str): """ Convert a DataFrame show output-style timestamp string into a datetime value which will marshall to a Hive/Spark TimestampType :param timestamp_string: A timestamp string in "YYYY-MM-DD HH:MM:SS" format :return: A datetime object ...
1902e75ab70c7869686e3a374b22fa80a6dfcf1a
3,659,206
def boxes(frame, data, f, parameters=None, call_num=None): """ Boxes places a rotated rectangle on the image that encloses the contours of specified particles. Notes ----- This method requires you to have used contours for the tracking and run boxes in postprocessing. Parameters --...
813ef54a8c8b99d003b9ca74b28befc63da2c0b9
3,659,207
def process_states(states): """ Separate list of states into lists of depths and hand states. :param states: List of states. :return: List of depths and list of hand states; each pair is from the same state. """ depths = [] hand_states = [] for state in states: ...
6f71d2471a50a93a3dac6a4148a6e3c6c2aa61e8
3,659,208
import torch import math def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None): """ Perform uniform spatial sampling on the images and corresponding boxes. Args: images (tensor): images to perform uniform crop. The dimension is `num frames` x `channel` x `height` x `...
c3e1d7eeb50b959fe0a075c742e23e5206730748
3,659,209
from typing import Tuple def plot_xr_complex_on_plane( var: xr.DataArray, marker: str = "o", label: str = "Data on imaginary plane", cmap: str = "viridis", c: np.ndarray = None, xlabel: str = "Real{}{}{}", ylabel: str = "Imag{}{}{}", legend: bool = True, ax: object = None, **kw...
8702f14fe0fbc508c3cb5893cc5a4a73bfdd0b85
3,659,210
import glob import tokenize import os def imread(filename, imread=None, preprocess=None): """Read a stack of images into a dask array Parameters ---------- filename: string A globstring like 'myfile.*.png' imread: function (optional) Optionally provide custom imread function. ...
c9e830db9b0ebd0c7634bb2170bc80df3b2c5dcc
3,659,211
import gzip import tqdm import sys def importPredictions_Tombo(infileName, chr_col=0, start_col=1, readid_col=3, strand_col=5, meth_col=4, baseFormat=1, score_cutoff=(-1.5, 2.5), output_first=False, include_score=False, filterChr=HUMAN_CHR_SET, save_unified_form...
88c998d07f40855694f15d34c53359150dd6f64d
3,659,212
def recommend_with_rating(user, train): """ 用户u对物品i的评分预测 :param user: 用户 :param train: 训练集 :return: 推荐列表 """ rank = {} ru = train[user] for item in _movie_set: if item in ru: continue rank[item] = __predict(user, item) return rank.iteritems()
372cd9f77d8123351f4b76eeea241aa8a3bcaf97
3,659,213
def nl_to_break( text ): """ Text may have newlines, which we want to convert to <br /> when formatting for HTML display """ text=text.replace("<", "&lt;") # To avoid HTML insertion text=text.replace("\r", "") text=text.replace("\n", "<br />") return text
d2baf1c19fae686ae2c4571416b4cad8be065474
3,659,214
import requests import logging def get_page_state(url): """ Checks page's current state by sending HTTP HEAD request :param url: Request URL :return: ("ok", return_code: int) if request successful, ("error", return_code: int) if error response code, (None, error_message: str)...
f7b7db656968bed5e5e7d332725e4d4707f2b14b
3,659,215
def unique(list_, key=lambda x: x): """efficient function to uniquify a list preserving item order""" seen = set() result = [] for item in list_: seenkey = key(item) if seenkey in seen: continue seen.add(seenkey) result.append(item) return result
57c82081d92db74a7cbad15262333053a2acd3a7
3,659,216
import dateutil import pytz def date_is_older(date_str1, date_str2): """ Checks to see if the first date is older than the second date. :param date_str1: :param date_str2: :return: """ date1 = dateutil.parser.parse(date_str1) date2 = dateutil.parser.parse(date_str2) # set or norma...
48fcf26cde4276e68daa07c1250de33a739bc5cb
3,659,217
def shorten_namespace(elements, nsmap): """ Map a list of XML tag class names on the internal classes (e.g. with shortened namespaces) :param classes: list of XML tags :param nsmap: XML nsmap :return: List of mapped names """ names = [] _islist = True if not isinstance(elements, (lis...
73dfc4f24a9b0a73cf7b6af7dae47b880faa3e27
3,659,218
def list_select_options_stream_points(): """ Return all data_points under data_stream """ product_uid = request.args.get('productID', type=str) query = DataStream.query if product_uid: query = query.filter(DataStream.productID == product_uid) streams_tree = [] data_streams = query.many(...
34ce7df0ecd241a009b1c8ef44bf33ec64e3d82d
3,659,219
import math def func2(): """ :type: None :rtype: List[float] """ return [math.pi, math.pi / 2, math.pi / 4, math.pi / 8]
62984ba7d8c1efd55569449adbf507e73888a1b7
3,659,220
def get_playlist_name(pl_id): """returns the name of the playlist with the given id""" sql = """SELECT * FROM playlists WHERE PlaylistId=?""" cur.execute(sql, (pl_id,)) return cur.fetchone()[1]
9488eb1c32db8b66f3239dcb454a08b8ea80b8b4
3,659,221
import random def weight(collection): """Choose an element from a dict based on its weight and return its key. Parameters: - collection (dict): dict of elements with weights as values. Returns: string: key of the chosen element. """ # 1. Get sum of weights weight_sum = s...
383ddadd4a47fb9ac7be0292ecc079fcc59c4481
3,659,222
def knnsearch(y, x, k) : """ Finds k closest points in y to each point in x. Parameters ---------- x : (n,3) float array A point cloud. y : (m,3) float array Another point cloud. k : int Number of nearest neighbors one wishes to compute. ...
84cc1bf0f960e1fb44dd44ab95eccce1c424ec05
3,659,223
def segmentation_gaussian_measurement( y_true, y_pred, gaussian_sigma=3, measurement=keras.losses.binary_crossentropy): """ Apply metric or loss measurement incorporating a 2D gaussian. Only works with batch size 1. Loop and call this function repeatedly over each sa...
377f2fa7706c166756efdb3047937b8db2047674
3,659,224
import h5py import numpy as np import sys def load_AACHEN_PARAMS(AHCHEN_h5_file, log_file_indicator): """ This module extract parameters trainded with the framework https://github.com/rwth-i6/returnn and the neural network proposed in the mdlsmt demo structure. Args: AHCHEN_h5_file: file ...
3c99757a1ff7f7351729d447b54d495241df46b7
3,659,225
import pprint def prep_doc_id_context( doc_id: str, usr_first_name: str, usr_is_authenticated: bool ) -> dict: """ Preps context for record_edit.html template when a doc_id (meaning a `Citation` id) is included. Called by views.edit_record() """ log.debug( 'starting prep_doc_id_context()' ) log.de...
f5d61134aeb8e45d7f21205b00087a11788ac028
3,659,226
import json def request_pull(repo, requestid, username=None, namespace=None): """View a pull request with the changes from the fork into the project.""" repo = flask.g.repo _log.info("Viewing pull Request #%s repo: %s", requestid, repo.fullname) if not repo.settings.get("pull_requests", True): ...
7b83c83a236ed840ed5b2eefbf87859d5e120aac
3,659,227
from typing import List def make_matrix(points: List[float], degree: int) -> List[List[float]]: """Return a nested list representation of a matrix consisting of the basis elements of the polynomial of degree n, evaluated at each of the points. In other words, each row consists of 1, x, x^2, ..., x^n, whe...
d8fbea3a0f9536cb681b001a852b07ac7b17f6c2
3,659,228
def verify(request, token, template_name='uaccounts/verified.html'): """Try to verify email address using given token.""" try: verification = verify_token(token, VERIFICATION_EXPIRES) except VerificationError: return redirect('uaccounts:index') if verification.email.profile != request.u...
56971aca43d04d7909ea6015fd48b6f30fa5b0ab
3,659,229
from typing import Tuple import threading from pydantic_factories import ModelFactory def run_train(params: dict) -> Tuple[threading.Thread, threading.Thread]: """Train a network on a data generator. params -> dictionary. Required fields: * model_name * generator_name * dataset_dir * tile...
c3a96996c3d34c18bfeab89b14836d13829d183e
3,659,230
import six import requests def request(url, method='GET', headers=None, original_ip=None, debug=False, logger=None, **kwargs): """Perform a http request with standard settings. A wrapper around requests.request that adds standard headers like User-Agent and provides optional debug logging of ...
b0a6bdc0ea4fc3c9abc03fed42ec8428f532ab92
3,659,231
def adjust_seconds_fr(samples_per_channel_in_frame,fs,seconds_fr,num_frame): """ Get the timestamp for the first sample in this frame. Parameters ---------- samples_per_channel_in_frame : int number of sample components per channel. fs : int or float sampling frequency. ...
a19775db3ebcdbe66b50c30bc531e2980ca10082
3,659,232
import argparse def create_parser(): """ Construct the program options """ parser = argparse.ArgumentParser( prog="xge", description="Extract, transform and load GDC data onto UCSC Xena", ) parser.add_argument( "--version", action="version", version="%(p...
a26669161e8e768edf850cffa3f405f6b3ce8033
3,659,233
def add_header(unicode_csv_data, new_header): """ Given row, return header with iterator """ final_iterator = [",".join(new_header)] for row in unicode_csv_data: final_iterator.append(row) return iter(final_iterator)
1fa50492d786aa28fba6062ac472f1c6470a6311
3,659,234
def get_most_energetic(particles): """Get most energetic particle. If no particle with a non-NaN energy is found, returns a copy of `NULL_I3PARTICLE`. Parameters ---------- particles : ndarray of dtyppe I3PARTICLE_T Returns ------- most_energetic : shape () ndarray of dtype I3PARTICLE_...
b43e275183b0c2992cfd28239a7e038965b40ccf
3,659,235
import sys import re def parse_file(path): """Parses a file for ObjectFiles. Args: path: String path to the file. Returns: List of ObjectFile objects parsed from the given file. """ if sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # Assume Linux...
f0e32e9ab8bb624038ac2d277eb0b03838a44151
3,659,236
def stack(tup, axis=0, out=None): """Stacks arrays along a new axis. Args: tup (sequence of arrays): Arrays to be stacked. axis (int): Axis along which the arrays are stacked. out (cupy.ndarray): Output array. Returns: cupy.ndarray: Stacked array. .. seealso:: :func:`n...
5f97bed62c77f28415ae82402cbb379372b4708c
3,659,237
def winning_pipeline(mydata,mytestdata,myfinalmodel,feature_selection_done = True,myfeatures =None,numerical_attributes = None): """ If feature _selection has not been performed: Function performs Cross Validation (with scaling within folds) on the data passed through. Scales the data with Robu...
636d922e405842ea338f774dd45b5ff78158bfdf
3,659,238
def calc_single_d(chi_widths, chis, zs, z_widths, z_SN, use_chi=True): """Uses single_m_convergence with index starting at 0 and going along the entire line of sight. Inputs: chi_widths -- the width of the comoving distance bins. chis -- the mean comoving distances of each bin. zs -- the mean re...
6cafe9d8d1910f113fdcd8a3417e127f4f1cf5e6
3,659,239
def ppo( client, symbol, timeframe="6m", col="close", fastperiod=12, slowperiod=26, matype=0 ): """This will return a dataframe of Percentage Price Oscillator for the given symbol across the given timeframe Args: client (pyEX.Client): Client symbol (string): Ticker timeframe (string...
0b6c48408b810131370500921a7ab2addbccea8b
3,659,240
import random def getRandomCoin(): """ returns a randomly generated coin """ coinY = random.randrange(20, int(BASEY * 0.6)) coinX = SCREENWIDTH + 100 return [ {'x': coinX, 'y': coinY}, ]
44a5ea7baddc77f8d1b518c3d1adcccd28935108
3,659,241
def is_success(msg): """ Whether message is success :param msg: :return: """ return msg['status'] == 'success'
43ecbf3c7ac8d03ce92ab059e7ec902e51505d0a
3,659,242
from bs4 import BeautifulSoup def scrape_data(url): """ scrapes relevant data from given url @param {string} url @return {dict} { url : link links : list of external links title : title of the page description : sample text } """ http = httplib2.Http() try: status, response = http.request(url) exce...
4ab640aad73506e74e3a899467a90c2ddec34308
3,659,243
def list_strip_comments(list_item: list, comment_denominator: str = '#') -> list: """ Strips all items which are comments from a list. :param list_item: The list object to be stripped of comments. :param comment_denominator: The character with which comment lines start with. :return list: A cleaned...
e5dd6e0c34a1d91586e12e5c39a3a5413746f731
3,659,244
def guess_number(name): """User defined function which performs the all the operations and prints the result""" guess_limit = 0 magic_number = randint(1, 20) while guess_limit < 6: # perform the multiple guess operations and print output user_guess = get_input("Take...
14c81f8adc18f59c29aa37ecec91808b275524e2
3,659,245
def writerformat(extension): """Returns the writer class associated with the given file extension.""" return writer_map[extension]
a2f981a993ba4be25304c0f41b0e6b51bef68d68
3,659,246
def index_like(index): """ Does index look like a default range index? """ return not (isinstance(index, pd.RangeIndex) and index._start == 0 and index._stop == len(index) and index._step == 1 and index.name is None)
91a8e626547121768ee7708e5c7cdcf8265c3991
3,659,247
def zplsc_c_absorbtion(t, p, s, freq): """ Description: Calculate Absorption coeff using Temperature, Pressure and Salinity and transducer frequency. This Code was from the ASL MatLab code LoadAZFP.m Implemented by: 2017-06-23: Rene Gelinas. Initial code. :param t: :para...
af5a7d1ea0ad4fbfacfd1b7142eaf0a31899cb4c
3,659,248
def estimate_quintic_poly(x, y): """Estimate degree 5 polynomial coefficients. """ return estimate_poly(x, y, deg=5)
be389d9f09208da14d0b5c9d48d3c6d2e6a86e8d
3,659,249
def add(A, B): """ Return the sum of Mats A and B. >>> A1 = Mat([[1,2,3],[1,2,3]]) >>> A2 = Mat([[1,1,1],[1,1,1]]) >>> B = Mat([[2,3,4],[2,3,4]]) >>> A1 + A2 == B True >>> A2 + A1 == B True >>> A1 == Mat([[1,2,3],[1,2,3]]) True >>> zero = Mat([[0,0,0],[0,0,0]]) >>> B...
5b0054397a76a20194b3a34435074fc901a34f6b
3,659,250
def hindu_lunar_event(l_month, tithi, tee, g_year): """Return the list of fixed dates of occurrences of Hindu lunar tithi prior to sundial time, tee, in Hindu lunar month, l_month, in Gregorian year, g_year.""" l_year = hindu_lunar_year( hindu_lunar_from_fixed(gregorian_new_year(g_year))) da...
aca03e1a77ff6906d31a64ab50355642f848f9d9
3,659,251
async def statuslist(ctx, *, statuses: str): """Manually make a changing status with each entry being in the list.""" bot.x = 0 statuses = statuses.replace("\n", bot.split) status_list = statuses.split(bot.split) if len(status_list) <= 1: return await bot.send_embed(ctx, f"You cannot have ...
99c43ea464759356977bc35ffcd941655763d783
3,659,252
def kebab(string): """kebab-case""" return "-".join(string.split())
24bc29e066508f6f916013fa056ff54408dcd46d
3,659,253
def getUserID(person): """ Gets Humhub User ID using name information :param person: Name of the person to get the Humhub User ID for :type person: str. """ # search for person string in humhub db # switch case for only one name (propably lastname) or # two separate strings (firstname +...
31d40b6dd0aec8f6e8481aeaa3252d71c6935c39
3,659,254
def parse_atom(s, atom_index=-1, debug=False): """ Parses an atom in a string s :param s: The string to parse :type s: str :param atom_index: the atom_index counter for continous parsing. Default is -1. :type atom_index: int :return: a list of atoms, a list of bonds and an ...
c269449d3a7d872687b75582264c2c94532016ba
3,659,255
def b58decode(v, length): """ decode v into a string of len bytes """ long_value = 0L for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base**i) result = '' while long_value >= 256: div, mod = divmod(long_value, 256) result = chr(mod) + resu...
4757e451106691de3d8805e9f7bdaeb24bd52816
3,659,256
def get_submission_by_id(request, submission_id): """ Returns a list of test results assigned to the submission with the given id """ submission = get_object_or_404(Submission, pk=submission_id) data = submission.tests.all() serializer = TestResultSerializer(data, many=True) return Response(...
4504b46a03056cb289bb0b53dc01d58f0c5c986c
3,659,257
import pkg_resources def get_resource_path(resource_name): """Get the resource path. Args: resource_name (str): The resource name relative to the project root directory. Returns: str: The true resource path on the system. """ package = pkg_resources.Requirement.parse(...
0f95e5f26edc9f351323a93ddc75df920e65375d
3,659,258
def do_cluster(items, mergefun, distfun, distlim): """Pairwise nearest merging clusterer. items -- list of dicts mergefun -- merge two items distfun -- distance function distlim -- stop merging when distance above this limit """ def heapitem(d0, dests): """Find nearest neighbor for ...
afcd32c390c5d9b57eb070d3f923b4abd6f9ac6b
3,659,259
import csv def read_csv(input_file, quotechar='"'): """Reads a tab separated value file.""" with open(input_file, "r") as f: reader = csv.reader(f,quotechar=quotechar) lines = [] for line in reader: lines.append(line) return lines
3b789904ae612b9b211a7dac5c49289659c415c5
3,659,260
def rotate_coordinates(local3d, angles): """ Rotate xyz coordinates from given view_angles. local3d: numpy array. Unit LOCAL xyz vectors angles: tuple of length 3. Rotation angles around each GLOBAL axis. """ cx, cy, cz = np.cos(angles) sx, sy, sz = np.sin(angles) mat33_x = np.array([ ...
3243cc9d82dd08384995f62709d3fabc7b896dce
3,659,261
import torch def quantize_enumerate(x_real, min, max): """ Randomly quantize in a way that preserves probability mass. We use a piecewise polynomial spline of order 3. """ assert min < max lb = x_real.detach().floor() # This cubic spline interpolates over the nearest four integers, ensuri...
d73083d6078c47456aeb64859d8361ad37f7d962
3,659,262
def counter_format(counter): """Pretty print a counter so that it appears as: "2:200,3:100,4:20" """ if not counter: return "na" return ",".join("{}:{}".format(*z) for z in sorted(counter.items()))
992993a590eabb2966eb9de26625077f2597718c
3,659,263
def drot(x, y, c, s): """ Apply the Givens rotation {(c,s)} to {x} and {y} """ # compute gsl.blas_drot(x.data, y.data, c, s) # and return return x, y
8554586f2069f04db0116dfee7868d5d0527999a
3,659,264
def _update_dict_within_dict(items, config): """ recursively update dict within dict, if any """ for key, value in items: if isinstance(value, dict): config[key] = _update_dict_within_dict( value.items(), config.get(key, {}) ) else: config[key]...
75b840b8091568b80f713b2ca7725b1a1f917d3a
3,659,265
def masterProductFieldUpdate(objectId: str): """ Submit handler for updating & removing field overrides. :param objectId: The mongodb master product id. """ key = request.form.get("field-key") value = request.form.get("field-value") # Clean up and trim tags if being set. if key == MAST...
3d87cf2de42d5ee0ee9d43116c0bff4181f42da0
3,659,266
def recalc_Th(Pb, age): """Calculates the equivalent amount of ThO_2 that would be required to produce the measured amount of PbO if there was no UO_2 in the monazite. INPUTS: Pb: the concentration of Pb in parts per million age: the age in million years """ return (232. / 208.) * Pb / (np...
79ba3cc8e9db8adba1d31ec6f9fe3588d3531b97
3,659,267
def relative_periodic_trajectory_wrap( reference_point: ParameterVector, trajectory: ArrayOfParameterVectors, period: float = 2 * np.pi, ) -> ArrayOfParameterVectors: """Function that returns a wrapped 'copy' of a parameter trajectory such that the distance between the final point of the traject...
ee41bdb547367186b82324e3e080b758984b7747
3,659,268
import warnings def planToSet(world,robot,target, edgeCheckResolution=1e-2, extraConstraints=[], equalityConstraints=[], equalityTolerance=1e-3, ignoreCollisions=[], movingSubset=None, **planOptions): """ Creates...
d03ec2c6c1e00388d1271af1e17a94eda0f50122
3,659,269
def itkimage_to_json(itkimage, manager=None): """Serialize a Python itk.Image object. Attributes of this dictionary are to be passed to the JavaScript itkimage constructor. """ if itkimage is None: return None else: direction = itkimage.GetDirection() directionMatrix = d...
e55f2da9792e4772de4b145375d1eec1e6ee6e06
3,659,270
import threading import os import time def test_two_agents(tmp_path, empty_ensemble): """ :tmp_path: https://docs.pytest.org/en/stable/tmpdir.html """ @fdb.transactional def get_started(tr): return joshua_model._get_snap_counter(tr, ensemble_id, "started") assert len(joshua_model.lis...
19e71ad5ddf0ebb351733cabfab493d6d694ce51
3,659,271
def project(pnt, norm): """Projects a point following a norm.""" t = -np.sum(pnt*norm)/np.sum(norm*norm) ret = pnt+norm*t return ret/np.linalg.norm(ret)
865b658862ebc47eccc117f0daebc8afcc99a2ac
3,659,272
def fix_trajectory(traj): """Remove duplicate waypoints that are introduced during smoothing. """ cspec = openravepy.ConfigurationSpecification() cspec.AddDeltaTimeGroup() iwaypoint = 1 num_removed = 0 while iwaypoint < traj.GetNumWaypoints(): waypoint = traj.GetWaypoint(iwaypoint, ...
30e3925c518dd4aff0f38ef7a02aaa9f7ab3680a
3,659,273
def calculate_edt(im, outpath=''): """Calculate distance from mask.""" mask = im.ds[:].astype('bool') abs_es = np.absolute(im.elsize) dt = distance_transform_edt(~mask, sampling=abs_es) # mask = im.ds[:].astype('uint32') # dt = edt.edt(mask, anisotropy=im.elsize, black_border=True, order='F', ...
469dde8ff81a782125aa29706a82a1da15db965b
3,659,274
def select_report_data(conn): """ select report data to DB """ cur = conn.cursor() cur.execute("SELECT * FROM report_analyze") report = cur.fetchall() cur.close() return report
9d0bf6d4f6758c873bd6643673784239f9bf4557
3,659,275
import numpy def func_lorentz_by_h_pv(z, h_pv, flag_z: bool = False, flag_h_pv: bool = False): """Gauss function as function of h_pv """ inv_h_pv = 1./h_pv inv_h_pv_sq = numpy.square(inv_h_pv) z_deg = z * 180./numpy.pi c_a = 2./numpy.pi a_l = c_a * inv_h_pv b_l = 4.*inv_h_pv_sq z_d...
802029e167439471e892fbfbfe4d6fdce8cb1a0e
3,659,276
from typing import Tuple from typing import Optional from datetime import datetime import os def backup_postgres_db() -> Tuple[Optional[str], bytes]: """Backup postgres db to a file.""" try: time_str = datetime.now().strftime("%d-%m-%YT%H:%M:%S") filename = f"backup_restore/backups/{time_str}-...
b541371f83976d42f8f4c4a55752ac67b792346e
3,659,277
def get_profile(aid): """ get profile image of author with the aid """ if 'logged_in' in session and aid ==session['logged_id']: try: re_aid = request.args.get("aid") re = aController.getAuthorByAid(re_aid) if re != None: return re ...
daa759c1493a15d6a2e300a6ab552aae30f59706
3,659,278
def SystemSettings_GetMetric(*args, **kwargs): """SystemSettings_GetMetric(int index, Window win=None) -> int""" return _misc_.SystemSettings_GetMetric(*args, **kwargs)
d9d6d00e6cf54f8e2ed8a06c616b17d6b2905526
3,659,279
from pathlib import Path def all_files(dir, pattern): """Recursively finds every file in 'dir' whose name matches 'pattern'.""" return [f.as_posix() for f in [x for x in Path(dir).rglob(pattern)]]
45f12cda2e16cb745d99d2c8dfb454b32130e1c8
3,659,280
def get_identity_groups(ctx): """Load identity groups definitions.""" return render_template('identity-groups', ctx)
820eb3ebf8d141f37a93485e4428e1cd79da6a44
3,659,281
from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import AnonymousUser from ..django_legacy.django2_0.utils.deprecation import CallableFalse, CallableTrue def fix_behaviour_contrib_auth_user_is_anonymous_is_authenticated_callability(utils): """ Make user.is_anonymous a...
b3f94992c0ada29b82e64d40cac190a567db9013
3,659,282
def BZPoly(pnts, poly, mag, openPoly=False): """TODO WRITEME. Parameters ---------- pnts : list Measurement points [[p1x, p1z], [p2x, p2z],...] poly : list Polygon [[p1x, p1z], [p2x, p2z],...] mag : [M_x, M_y, M_z] Magnetization = [M_x, M_y, M_z] """ dgz = calcP...
1ba775034c8728c854fc58f4b4f75ad691a7ecec
3,659,283
def matches(spc, shape_): """ Return True if the shape adheres to the spc (spc has optional color/shape restrictions) """ (c, s) = spc matches_color = c is None or (shape_.color == c) matches_shape = s is None or (shape_.name == s) return matches_color and matches_shape
fa9c90ea2be17b0cff7e4e76e63cf2c6a70cc1ec
3,659,284
from typing import Any def jsonsafe(obj: Any) -> ResponseVal: """ Catch the TypeError which results from encoding non-encodable types This uses the serialize function from my.core.serialize, which handles serializing most types in HPI """ try: return Response(dumps(obj), status=200, he...
90aaaad3e890eeb09aaa683395a80f80394bba3e
3,659,285
def get_appliances(self) -> list: """Get all appliances from Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - appliance - GET - /appliance :return: Returns list of dictionaries of each appliance :r...
2f1e48869f4494a995efd4adba80a235c4fb1486
3,659,286
def is_str(element): """True if string else False""" check = isinstance(element, str) return check
c46b80d109b382de761618c8c9a50d94600af876
3,659,287
import tempfile import shutil def anonymize_and_streamline(old_file, target_folder): """ This function loads the edfs of a folder and 1. removes their birthdate and patient name 2. renames the channels to standardized channel names 3. saves the files in another folder with a non-identifyable ...
2210c72891c3faec73a9d5ce4b83d56ee9adef38
3,659,288
def deal_text(text: str) -> str: """deal the text Args: text (str): text need to be deal Returns: str: dealed text """ text = " "+text text = text.replace("。","。\n ") text = text.replace("?","?\n ") text = text.replace("!","!\n ") text = text.replace(";"...
8f16e7cd2431dfc53503c877f9d4b5429f738323
3,659,289
import zipfile import os def extract_zip(src, dest): """extract a zip file""" bundle = zipfile.ZipFile(src) namelist = bundle.namelist() for name in namelist: filename = os.path.realpath(os.path.join(dest, name)) if name.endswith('/'): os.makedirs(filename) else: ...
5e8af22a446e52c26b99b71fefdd29d3b10e02ec
3,659,290
def _find_timepoints_1D(single_stimulus_code): """ Find the indexes where the value of single_stimulus_code turn from zero to non_zero single_stimulus_code : 1-D array >>> _find_timepoints_1D([5,5,0,0,4,4,4,0,0,1,0,2,0]) array([ 0, 4, 9, 11]) >>> _find_timepoints_1D([0,0,1,2,3,0,1,0,0]) a...
b2c3d08f229b03f9b9f5278fea4e25c25274d213
3,659,291
def stiffness_tric( components: np.ndarray = None, components_d: dict = None ) -> np.ndarray: """Generate triclinic fourth-order stiffness tensor. Parameters ---------- components : np.ndarray 21 components of triclinic tensor, see stiffness_component_dict components_d : dic...
f96a2ffb4e0542f56a4329393b77e9a875dc6cd5
3,659,292
from typing import Optional from pathlib import Path def get_dataset( dataset_name: str, path: Optional[Path] = None, regenerate: bool = False, ) -> TrainDatasets: """ Get the repository dataset. Currently only [Retail Dataset](https://archive.ics.uci.edu/ml/datasets/online+retail) is availabl...
f913f613858c444ddac479d65a169b74a9b4db29
3,659,293
def get_info_safe(obj, attr, default=None): """safely retrieve @attr from @obj""" try: oval = obj.__getattribute__(attr) except: logthis("Attribute does not exist, using default", prefix=attr, suffix=default, loglevel=LL.WARNING) oval = default return oval
24b4bace8a8cef16d7cddc44238a24dd636f6ca8
3,659,294
def mkviewcolbg(view=None, header=u'', colno=None, cb=None, width=None, halign=None, calign=None, expand=False, editcb=None, maxwidth=None): """Return a text view column.""" i = gtk.CellRendererText() if cb is not None: i.set_property(u'editable', True) i....
7b49154d9d26cc93f5e42116967634eddc06a06e
3,659,295
def list2str(lst, indent=0, brackets=True, quotes=True): """ Generate a Python syntax list string with an indention :param lst: list :param indent: indention as integer :param brackets: surround the list expression by brackets as boolean :param quotes: surround each item with quotes :return...
ef441632bf59714d3d44ede5e78835625b41f047
3,659,296
import os def full_path(path): """ Get an absolute path. """ if path[0] == "/": return path return os.path.realpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", path) )
0ea845638d541521277fac3904cb1c1b243e88b1
3,659,297
def _roi_pool_shape(op): """Shape function for the RoiPool op. """ dims_data = op.inputs[0].get_shape().as_list() channels = dims_data[3] dims_rois = op.inputs[1].get_shape().as_list() num_rois = dims_rois[0] pooled_height = op.get_attr('pooled_height') pooled_width = op.get_attr('pooled_width') ou...
9c84aa0054dacacefcdf2fd9066538239668ee66
3,659,298
from typing import Optional def get_users(*, limit: int, order_by: str = "id", offset: Optional[str] = None) -> APIResponse: """Get users""" appbuilder = current_app.appbuilder session = appbuilder.get_session total_entries = session.query(func.count(User.id)).scalar() to_replace = {"user_id": "id...
5ef71bfcc79314f0e9481dfa78a8e079dce14339
3,659,299