content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def severe_obesity_wfl(gender, length, weight, units='metric', severity=1): """ Returns a boolean indicator for a zscore determining if the reading is classified as severely obese from: https://jamanetwork.com/journals/jamapediatrics/fullarticle/2667557. NOTE: This should only be used for ...
c6de69ec90d278b69fb802ce8a435502b1668644
3,635,285
def calc_Flesh_Kincaid_Grade_rus_flex(n_syllabes, n_words, n_sent): """Метрика Flesh Kincaid Grade для русского языка с константными параметрами""" if n_words == 0 or n_sent == 0: return 0 n = FLG_X_GRADE * (float(n_words) / n_sent) + FLG_Y_GRADE * (float(n_syllabes) / n_words) - FLG_Z_GRADE return n
93467f013107660f3b8ad03ac882e857434fbc45
3,635,286
import signal def psd(x: np.ndarray, delf: float, type_psd: list, n: float = None) -> np.ndarray: """Returns 2d array of PSD computed with specified method Args: x (np.ndarray): Values in time domain delf (float): Sampling Rate type (list): [x, y] x=0 psd, x=1 psd density && y=0 stand...
0efeb38798ddda5d09a4e3c762f1ebbed69c50da
3,635,287
def comment(request): """留言功能""" if request.method == "POST": form = CommentForm(request.POST) blog_id = request.POST["blog_id"] user = request.user if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = user new_commen...
a3f8cf5beed1edf3156817aaa0e36e377256d4b1
3,635,288
def calculate_height_filtration( graph, direction, attribute_in='position', attribute_out='f', ): """Calculate height filtration of a graph in some direction. *Note*: This function works for *all* vector-valued attributes of a graph, but in the following, it will be assumed that those a...
79010055e4a61862267b4cb9e9f5ebc9c3d1cdca
3,635,289
def read_file(file_name, encoding='utf-8'): """ 读文本文件 :param encoding: :param file_name: :return: """ with open(file_name, 'rb') as f: data = f.read() if encoding is not None: data = data.decode(encoding) return data
4e4a90512727b4b40d4968930479f226dc656acb
3,635,290
def cbf_qei(gm, wm, csf, img, thresh=0.8): """ Quality evaluation index of CBF base on Sudipto Dolui work Dolui S., Wolf R. & Nabavizadeh S., David W., Detre, J. (2017). Automated Quality Evaluation Index for 2D ASL CBF Maps. ISMR 2017 """ def fun1(x, xdata): d1 = np.exp(-(x[0])*np.po...
d52badc74cc01c615afa0a0a5cdab1d040d110e5
3,635,291
import sqlite3 def calendar(): """page for all events""" events = get_all_events(sqlite3.connect(DB_NAME).cursor()) return render_template("calendar.html", events=events)
bf6c1f12cb2261dc68389c56b8c92a4dbe879fda
3,635,292
def _ui_device_family_plist_value(ctx): """Returns the value to use for `UIDeviceFamily` in an info.plist. This function returns the array of value to use or None if there should be no plist entry (currently, only macOS doesn't use UIDeviceFamily). Args: ctx: The Skylark context. Returns: ...
8d6669fcdaf02f1ef254dc77910f2e2e9dfa5126
3,635,293
def map_amplitude_grid( ds_ind, data_columns, stokes='I', chunk_size:int=10**6, return_index:bool=False ): """ Map functions to a concurrent dask functions to an Xarray dataset with pre-computed grid indicies. Parameters ---------- ds_ind : xarray.dataset An...
f363f1bc8de2eb58d5d6ecca529e0d8fca255496
3,635,294
def fetch_query(query, columns): """ Creates a connection to database, returns query from specified table as a list of dictionaries. Input: query: a SQL query (string) Returns: pairs: dataframe of cursor.fetchall() response in JSON pairs """ # Fetch query response = fetch_query_records(q...
75465b0a920a19ca339c732bfe5b8ca4c356a9a5
3,635,295
import logging def fetch(key): """Gets snapshots referenced by the given instance template revision. Args: key: ndb.Key for a models.InstanceTemplateRevision entity. Returns: A list of snapshot URLs. """ itr = key.get() if not itr: logging.warning('InstanceTemplateRevision does not exist: %s...
c567a0e76c602936b7fd018c8824c6d3cce0d70d
3,635,296
def EFI(data, period=13): """ Elder Force Index EFI is an indicator that uses price and volume to assess the power behind a move or identify possible turning points. :param pd.DataFrame data: pandas DataFrame with open, high, low, close data :param int period: period used for indicator calcula...
ae644c82a5dc4fd304fd17f9939e427eccb47468
3,635,298
def Gdelta(GP, testfunc, firstY, delta=0.01, maxiter=10, **kwargs): """ given a GP, find the max and argmax of G_delta, the confidence-bounded prediction of the max of the response surface """ assert testfunc.maximize mb = MuBound(GP, delta) _, optx = cdirect(mb.objective, testfunc.bounds, m...
0a74a922cba87cfccc4a63e1195abe4dca8b6d9c
3,635,299
def xirrcal(cftable, trades, date, startdate=None, guess=0.01): """ calculate the xirr rate :param cftable: cftable (pd.Dateframe) with date and cash column :param trades: list [trade1, ...], every item is an trade object, whose shares would be sold out virtually :param date: string of date...
a01d874ae4a79202aec373f2b1c0b1b2b0904f10
3,635,300
def calc_synch_kappa(b, ne, delta, sinth, nu, E0=1.): """Calculate the relativstic synchrotron absorption coefficient κ_ν. This is Dulk (1985) equation 41, which is a fitting function assuming a power-law electron population. Arguments are: b Magnetic field strength in Gauss ne The den...
546cbdf24459fa7cac6e9b1465b94b63ed722ebf
3,635,301
def random_rotation(): """Generate a 3D random rotation matrix. Returns: np.matrix: A 3D rotation matrix. """ x1, x2, x3 = np.random.rand(3) R = np.matrix([[np.cos(2 * np.pi * x1), np.sin(2 * np.pi * x1), 0], [-np.sin(2 * np.pi * x1), np.cos(2 * np.pi * x1), 0], ...
a8b68784973bdccea5331fa685cf8f86a00de04a
3,635,302
def outdir_project(outdir, project_mode, pd_samples, mode): """ """ # Group dataframe by sample name sample_frame = pd_samples.groupby(["new_name"]) dict_outdir = {} for name, cluster in sample_frame: if (project_mode): #print ("Create subdir for every sample: ", mode) sample_dir = create_subfolder('dat...
c59ab5d985820fbbff0ea876a6e4623fc00dc1e0
3,635,303
def _get_percentage_bid_offer(df_with_positions, day, daily_spread_percent_override): """Defines the daily spread used in computation.""" if daily_spread_percent_override is not None: daily_spread_percentage = daily_spread_percent_override else: try: daily_spread_percentage = df_...
7515eb5117eaaac45e89259d5d9d2b8efccb955c
3,635,304
def getChoice(options: list): """ Only for Windows and MacOS """ # showOptions = '\n'.join(options) # print(showOptions) print("操作選項") for i in range(len(options)): print(f"{i+1}. {options[i]}") choice = input(': ') clearScene() return choice
936936d82e20e459af75fa80a3aae650bb4e45e3
3,635,305
def label_accuracy_score(label_trues, label_preds, n_class): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc """ hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += fast_hist(lt.flatten(), lp...
23fbcfea1942ca86bb306f2cb0b8855bc5652749
3,635,306
def Update(name, notification_emails, enrolled_services, update_mask): """Get the access approval settings for a resource. Args: name: the settings resource name (e.g. projects/123/accessApprovalSettings) notification_emails: list of email addresses enrolled_services: list of services update_mask: ...
a09577e797c39e3b5b82b50bf37855569721ca52
3,635,308
from datetime import datetime def training(request): """Renders the training page.""" assert isinstance(request, HttpRequest) return render( request, 'magic/training.html', { 'title':'Training', 'year':datetime.now().year, } )
60d916e0e4f44b9b617c8bbc7f3d8800f37634fd
3,635,309
def MOP( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2022-02-01", **kwargs ) -> Graph: """Ret...
044bbec68722598ce858012d8272755d652a8fbc
3,635,310
import warnings def stetson_sharpness(temp, middle, mask, d): """Stetson compute of sharpness.""" mask = np.array(mask) # work with a copy mask[middle, middle] = 0 sharp = temp[middle, middle] - (np.sum(mask*temp))/np.sum(mask) with warnings.catch_warnings(): warnings.simplefilter('ignore...
bce6ab472b7a96b2575687215788355cdac56529
3,635,311
def add_variant_to_variant_set(prim, variant_set_name, variant_name): """ Adds a new variant to given variant set in prim :param prim: Usd.Prim :param variant_set_name: str :param variant_name: str :return: Usd.Variant """ variant_set = get_variant_set(prim, variant_set_name) if not...
f77643eb26e703045825c7e728c338e6c4e4abfb
3,635,312
def load_data(messages_filepath, categories_filepath): """ Load messages_file and categories_file Args: messages_filepath: csv file with the disaster messages categories_filepath: csv file with the categories for disaster messages Returns: a file that is merge of the two input files ...
fafd059d8847b7bd0b5c39f9f690bd52e79bd6da
3,635,313
def _cmd(cmd): """Utility function to run commands.""" result = __salt__["cmd.run_all"](cmd) if result["retcode"]: raise CommandExecutionError(result["stdout"] + result["stderr"]) return result["stdout"]
e9d0de256d849cb562e3a83ea93f2766d9ce48cb
3,635,314
from typing import Union from typing import Tuple from typing import Optional def min( x: Union[ivy.Array, ivy.NativeArray], axis: Union[int, Tuple[int]] = None, keepdims: bool = False, out: Optional[Union[ivy.Array, ivy.NativeArray]] = None, ) -> ivy.Array: """Calculates the minimum value of the ...
f875d77a73a554c96c3361134822c761a5a8751a
3,635,315
def bkg_3d(): """Example with simple values to test evaluate""" energy = [0.1, 10, 1000] * u.TeV energy_axis = MapAxis.from_energy_edges(energy) fov_lon = [0, 1, 2, 3] * u.deg fov_lon_axis = MapAxis.from_edges(fov_lon, name="fov_lon") fov_lat = [0, 1, 2, 3] * u.deg fov_lat_axis = MapAxis.f...
cccf110037d2ed9b10b9877e7e413a3d48efe9b3
3,635,316
import requests import pickle def pd_read_pickle(fname): """ Read the :class:`.PupilData`-object `pdobj` from file using :mod:`pickle`. Parameters ---------- fname: str filename or URL to load data from Returns ------- pdobj: :class:`.PupilData` ...
2d92966fcb9834026e352fb01a3a7e3c7f18e5bf
3,635,317
def checkLevel(n): """ Check if a level, identified by its name, exists return : - Boolean call example : chechLevel(1) """ levelsList = getLevelsList() levelExists = False for level in levelsList: if "natas"+str(n) == level["name"]: levelExists = True break return levelExists
72b6e15464462da7e91c88253a64002063da7845
3,635,318
def get_payload(dataset, site_code, year): """returns payload needed for a post request to get EANET csv files""" if dataset == "dry_deposition_auto": item_code = 2 elif dataset == "dry_deposition_filter_pack": item_code = 3 elif dataset == "dry_deposition_passive_sampler": ...
6ba2b6b75debb3369869e29f36c5e8a2adec0bf1
3,635,320
def safe_encode(s, coding='utf-8', errors='surrogateescape'): """encode str to bytes, with round-tripping "invalid" bytes""" return s.encode(coding, errors)
1b1ba8439db8ec4c82c571197e5007e58f397c87
3,635,321
def group_required(*group_names): """ Requires user membership in at least one of the groups passed in. """ def in_groups(u): if u.is_authenticated: if u.is_superuser or bool(u.groups.filter(name__in=group_names)): return True return False return user_p...
2c021dd4f71d804bc1e656d5de1a4194bd4131cf
3,635,322
def initialize_service(storage_socket, logger, service_input, tag=None, priority=None): """Initializes a service from a API call. Parameters ---------- storage_socket : StorageSocket A StorageSocket to the currently active database logger A logger for use by the service service_...
4274ba9e7ad1c6bf59155704c0dec2b54c0869ea
3,635,323
import collections def extract_stats(output): """Extract stats from `git status` output """ lines = output.splitlines() return collections.Counter([x.split()[0] for x in lines])
41d8aef4df3401ee8127ad0b72402ff9c54c41e3
3,635,324
def save_csv(filename, shape_features, centroid_features, label_features=None, mode='w'): """ Create and save a .csv file containing all the features (shapes, centroids and labels) Parameters ---------- filename : string full name (path and name) of the .csv file ...
d40cca38c0670bcbd0c67e2d63c670b1033e29e7
3,635,326
from typing import Optional from typing import Union from typing import Pattern def turn_connect(start: Port, end: Port, radius: float, radius_end: Optional[float] = None, euler: float = 0, resolution: int = DEFAULT_RESOLUTION, include_width: bool = True) -> Union[Pattern, Curve]: """Turn connect...
7d9e1572b22a2066f5468d6fad159364f00dd9f4
3,635,327
import base64 import struct import hmac import hashlib import time def GoogleAuth(key): """ 谷歌验证码 # RFC 协议下有HOTP和TOTP 前者是计数 后者是计时 生成验证码 # hopt 由 RFC 协议 RFC4266 # google auth 用的是TOTP 而TOTP是在HOTP的基础上计时 :return: """ def get_hotp_token(secret, intervals_no): """This is where the...
3a2df9626a7f2f5705b1286dcc18c1eae0b331a4
3,635,328
def adjust_opts(in_opts, config): """Establish JVM opts, adjusting memory for the context if needed. This allows using less or more memory for highly parallel or multicore supporting processes, respectively. """ memory_adjust = config["algorithm"].get("memory_adjust", {}) out_opts = [] for ...
f932224902df9d61efbd6390447e41813280c3a6
3,635,330
import binascii def from_address(text, v4_origin=ipv4_reverse_domain, v6_origin=ipv6_reverse_domain): """Convert an IPv4 or IPv6 address in textual form into a Name object whose value is the reverse-map domain name of the address. *text*, a ``str``, is an IPv4 or IPv6 address in textual ...
c66d8357c955b177a201ad6f94fb98aeaf72d909
3,635,332
import time def blog_claim(): """Blog info If the user (check the username) has already bought the item or its author, To display the content of the article . :param blog_id ,token , address :return: { "msg": { "author": "0x035EB55d4260455075A8418C4B94Ba6...
ce4344a01f6f71afadc078c6d3bed3b26f5540ee
3,635,333
def _expr_rshift_as_multiplication_of_reverse_order(lhs, rhs): """The multiply express will reverse order. """ return rhs * lhs
4f245d8a8071cf4bcfc6543e0abae24cb1cdde9d
3,635,335
def pathsuboption(option, attr): """Decorator used to declare a path sub-option. Arguments are the sub-option name and the attribute it should set on ``path`` instances. The decorated function will receive as arguments a ``ui`` instance, ``path`` instance, and the string value of this option from ...
08b7f4134b79038a4df77b27d52504fc49df07a6
3,635,336
import numpy def CalculateHarmonicTopoIndex(mol): """ ################################################################# Calculation of harmonic topological index proposed by Narnumi. ---->Hato Usage: result=CalculateHarmonicTopoIndex(mol) Input: mol is a molecule object ...
65984702d49071f18089cdf17b1ba4a21b70357e
3,635,337
import functools def record_metrics(func): """ The metrics decorator records each time a route is hit in redis The number of times a route is hit and an app_name query param are used are recorded. A redis a redis hash map is used to store each of these values. NOTE: This must be placed before the...
768804fed0b77bac58f59cc8773f1dfc1acfc0f8
3,635,338
def is_long_path(path: PathOrString) -> bool: """ A long path is a path that has more than 260 characters """ return len(str(path)) > MAX_PATH_LENGTH
4fc9798364c4bf8499c042273685f085476b93b5
3,635,339
def build_model(): """ Builds up the SoundNet model and loads the weights from a given model file (8-layer model is kept at models/sound8.npy). :return: """ model_weights = np.load('models/sound8.npy').item() model = Sequential() model.add(InputLayer(batch_input_shape=(1, None, 1))) fil...
6ba2d75389f03d6636e353d5a03c6416b9478251
3,635,340
def open( urlpath, mode="rb", compression=None, encoding="utf8", errors=None, protocol=None, newline=None, **kwargs ): """ Given a path or paths, return one ``OpenFile`` object. Parameters ---------- urlpath: string or list Absolute or relative filepath. Prefix w...
4d0be7fe29d8d76a057a4eeb4736e21f80400a55
3,635,341
def evaluate_surface(name, oname=None, mesh=False, topology=False, intersections=False, collisions=0, opts={}): """Evaluate properties of surface mesh""" argv = ['evaluate-surface-mesh', name] if oname: argv.extend([oname, '-v']) argv.extend(['-threads', str(threads)]) if mesh: argv.appe...
faa5309818e7ac4e740adf1fbaa9665d519c3b5b
3,635,343
def uu_query_STK_STATUS_CHANGE(): """ 上市公司状态变动 获取上市公司已发行未上市、正常上市、实行ST、*ST、暂停上市、终止上市的变动情况等 :param :query(finance.STK_STATUS_CHANGE):表示从finance.STK_STATUS_CHANGE这张表中查询上市公司的状态变动信息,还可以指定所要查询的字段名,格式如下:query(库名.表名.字段名1,库名.表名.字段名2),多个字段用英文逗号进行分隔;query函数的更多用法详见:sqlalchemy.orm.query.Query对象 finance....
1e23ddfb233f6ad1231008ac760cc70a9b8b84ce
3,635,344
def add_custom_encoder_arguments(group): """Define arguments for Custom encoder.""" group.add_argument( "--enc-block-arch", type=eval, action="append", default=None, help="Encoder architecture definition by blocks", ) group.add_argument( "--enc-block-repea...
f49a778b78351a08bdb411e8004d00da0ccd96a4
3,635,345
def expost_te(returns, bmk_returns, periods): """ Calculate the EX-POST Tracking Error. Returns a Dataframe of rolling Ex-Post Tracking Error Annualized """ temp = pd.concat([pd.DataFrame(returns) - pd.DataFrame(bmk_returns)], axis=1) temp = temp.dropna() temp.columns = ["returns", "bmk_returns"...
d8c5de00eb415ad318f6a9c5c397efb8ba2004b7
3,635,346
def cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H'): """ Cruise control with PI controller and hill disturbance. This function returns various system function configurations for a the cruise control Case Study example found in the supplementary article. The plant model is obtained by the li...
61be0dc8f6688d602efad01203a4f65f5f51613d
3,635,347
import itertools def svd(a, compute_uv=True, sort=True, copy=True, eps=1e-9): """ Performs singular value decomposition of a ds-array via the one-sided block Jacobi algorithm described in Arbenz and Slapnicar [1]_ and Dongarra et al. [2]_. Singular value decomposition is a factorization of the form A...
5bc0c65b0b730625e13b918681d384285771d59e
3,635,349
def renameID(idFrom, idTo, identifiedElements, referringNodes): """ Changes the ID name from idFrom to idTo, on the declaring element as well as all nodes in referringNodes. Updates identifiedElements. Returns the number of bytes saved by this replacement. """ num = 0 definingNode = ...
2d081eb4f5892b53f7f2d6ffb1f72e21ce1e3f89
3,635,350
def rotate_hue(im, x): """ Adjust the hue of *im* by *x*, where *x* is a value between 0.0 to 1.0. Full red to full green is 1/3, red to blue is 2/3. """ assert im.mode == 'RGB' ima = np.asarray(im) / 255 ima_hsv = colors.rgb_to_hsv(ima) ima_hsv[...,0] = (ima_hsv[...,0] + x) % 1 ima...
4f1a6805e3cf59009013631a394899c5135facd7
3,635,351
def Pa_2_psig(value): """ converts pressure in abs Pa (Pascal) to gauged psig (pound-force per square inch) :param value: pressure value in Pa :return: pressure value in psi """ return value / const.psi - 14.7
d34671a458f6796134ab80eeddcb3c9f0f637a25
3,635,353
def get_vedges_details(customer, api_response_data, query_condition): """ Parses JSON response and builds CSV file with vEdge details All other devices, such as vBond, vSmart are excluded :param query_condition: filter :param customer: string to build correct directory to store CSV files :param...
6b0971b8eaff9b70eaf42efd5ed65d6f6615ba04
3,635,354
def correct_errors(page, labels, bboxes, model): """Error correction. parameters: page - 2d array, each row is a feature vector to be classified labels - the output classification label for each feature vector bboxes - 2d array, each row gives the 4 bounding box coords of the character model -...
7561c3174d3ec214f5d469b7437d65339a08bcd0
3,635,356
def sign(x): """Returns sign of x""" if x==0: return 0 return x/abs(x)
677dfd796b0ee354fbcaf78b58cf7a5a660446b5
3,635,357
import urllib import json def get_sources(category): """ function that gets response from the api call """ sources_url = base_url.format(category,api_key) with urllib.request.urlopen(sources_url) as url: sources_data = url.read() sources_response = json.loads(sources_data) ...
e1c17709ba93cd0eba46a179bcabc638ebb631c5
3,635,358
def split(geometry, (dx_max, dy_max), (rx, ry), (bx0, by0, bx1, by1)): """ Cut geometry to smaller blocks. """ #pylint: disable=invalid-name def _get_sizes(v0, v1, dv_max, rv, bv0, bv1): if rv > 0: dv_max *= rv if rv > 0: vr0 = vr1 = 0.5*(rv*ceil((v1-v0)/rv) - (v1-v0...
bc7d6dd69768057195a2c5c75c91846355fdb21f
3,635,359
from typing import Optional import requests import json def execute_web_hook(hook_url: Optional[str], status_id: int) -> bool: """execute_web_hook Discordに対してBOT用のデータを送る Args: hook_url (Optional[str]): webhook url status_id (int): tweet id Returns: bool: hookに成功した場合はTrue失敗した...
f90696cf4cf03eacdc87e175776cbbc4138c4c2f
3,635,361
from datetime import datetime def handler_callback(callback, user): """ A method for handling callbacks :param user: user object :param callback: callback from telebot.types.CallbackQuery :return: datetime.date object if some date was picked else None """ if callback == "prev" and user.c...
27eb78f77d77543fe02a984751078cee96d38b06
3,635,362
import torch def get_weight(df): """This will give weights to encounter imbalanced class problem""" # Getting number of data points for each class weight_count = df["sentiment"].value_counts(sort=False) # print(weight_count) # Weight of class c is the size of largest class divided by the size of...
316e000ee262bf7324228c0ca6b752e6e2908510
3,635,363
from django.contrib.contenttypes.models import ContentType def bestellungen(request): """ Übersicht der abgeschlossenen Bestellungen Es werden die Käufe vom Nutzer gesucht und in einem dict nach Kategorien geordnet ausgegeben, folgende Kategorien: - kommende Veranstaltungen - elektronische Medi...
b2c87525c85a1e73737e7c373492cf5db5a02263
3,635,364
def comp_indexes_fcn(site, comp_name, n_inds): """ Returns an array of indexes to associate with new emissions :param site: a GeneralClassesFunctions.simulation_classes.Site object :param comp_name: name of a component contained in Site.comp_dict :param n_inds: Integer of indexes to generate :re...
969727d7da3663bbca8f3733d0dab9f46d117d7b
3,635,365
def update_cache_and_get_specs(): """ Get all concrete specs for build caches available on configured mirrors. Initialization of internal cache data structures is done as lazily as possible, so this method will also attempt to initialize and update the local index cache (essentially a no-op if it ha...
eabd2b4d356651de624946d6d8cff6e6aa501209
3,635,366
def sodium_unpad(s, blocksize): """ Remove ISO/IEC 7816-4 padding from the input byte array ``s`` :param s: input bytes string :type s: bytes :param blocksize: :type blocksize: int :return: unpadded string :rtype: bytes """ ensure(isinstance(s, bytes), raising=exc.TypeError) ...
bdb86073a29b46ee3029ed0fe51b79ab6da2e7f8
3,635,367
from datetime import datetime def find_lag(t,x,t_ref,x_ref): """ Report lag in time between x(t) and a reference x_ref(t_ref). If times are already numeric, they are left as is and the lag is reported in the same units. If times are not numeric, they are converted to date nums via utils.to_d...
aa30dfcb75847af9490077563438f0769775412d
3,635,368
def classname(obj: _rinterface_capi.SupportsSEXP) -> str: """Name of the R class.""" res = dollar(obj, 'classname') if res is not rpy2.robjects.NULL: assert len(res) == 1 res = res[0] return res
4ad0e8a4d399802373f6a4d4bb480e76a8cec70d
3,635,369
import inspect def get_ofp_cls(ofp_version, name): """get class for name of a given OF version""" (_consts_mod, parser_mod) = get_ofp_module(ofp_version) for i in inspect.getmembers(parser_mod, inspect.isclass): if i[0] == name: return i[1] return None
179f24640c2539ce2fb38767d3bd7fd472049c95
3,635,370
import tempfile def split_file(rows_per_file: int, inpath: str, dir): """Split file from inpath into multiple named tempfiles with delete set to false, each containing rows_per_file number of rows. All split files are placed in dir. The intent is to use this function with dir as a TemporaryDirect...
44b0723c5073a82d548daabd08d4e556012229a2
3,635,371
def HHCF(r, sigma, xi , alpha): """ Model for height-height correlation function. This model is suitable for fitting when data is present for both above and below the correlation length. Inputs: r: Numpy array. This contains the distance data which would be used for the x coordinate on a HHCF plot....
49542983271666400085dc050b1218a6759d7009
3,635,372
def process_reaction_with_product_maps_atoms( rxn, skip_if_not_in_precursors=False ): """ Remove atom-mapping, move reagents to reactants and canonicalize reaction. If fragment group information is given, keep the groups together using the character defined with fragment_bond. Args: rx...
107452f44d079bdfe9dafce82b2744f170c239d6
3,635,373
def echo_handler(completed_proc): """Immediately return ``completed_proc``.""" return completed_proc
53f3ef51bf349ac5146014ef25b88326d5bc010e
3,635,374
import time import tqdm from pathlib import Path def render_path( render_poses, hwf, K, chunk, render_kwargs, gt_imgs=None, savedir=None, render_factor=0, fixed_viewdir=None): """ Render a batch of full images. fixed_viewdir: If a 4 x 4 matrix, use this view direction for all frames. ...
29413d4306ba46c2ef069b7845e780df7bfcd764
3,635,375
def _check_pr(pr, cfg): """make sure a PR is ok to automerge""" if any(label.name == "automerge" for label in pr.get_labels()): return True, None # only allowed users if pr.user.login not in ALLOWED_USERS: return False, "user %s cannot automerge" % pr.user.login # only if [bot-auto...
2ed229c393dffbaeec6822bd4e2492b6339c8fca
3,635,376
from typing import Any import joblib def read_joblib( bucket: str, key: str, ) -> Any: """Read a joblib model from a given s3 bucket and key. Parameters ---------- bucket : str The S3 bucket to load from. key : str The object key within the s3 bucket. Returns ----...
90ff368b89b583678f2c41b3d2d76e9d66bc393b
3,635,377
import random def random_choice(choices): """returns a random choice from a list of (choice, probability)""" # sort by probability choices = sorted(choices, key=lambda x:x[1]) roll = random.random() acc_prob = 0 for choice, prob in choices: acc_prob += prob if roll <= acc_...
f477abe220fa9d87ee3692bed8c41973af4c637c
3,635,379
def set_rdmol_positions_(mol, pos): """ Args: rdkit_mol: An `rdkit.Chem.rdchem.Mol` object. pos: (N_atoms, 3) """ assert mol.GetNumAtoms() == pos.shape[0] conf = Chem.Conformer(mol.GetNumAtoms()) for i in range(pos.shape[0]): conf.SetAtomPosition(i, pos[i].tolist()) ...
81ea738f5a548403f8860f055c7fa79be633e5cf
3,635,380
import torch def convert_label_to_color(label, color_map): """Convert integer label to RGB image. """ n, h, w = label.shape rgb = torch.index_select(color_map, 0, label.view(-1)).view(n, h, w, 3) rgb = rgb.permute(0, 3, 1, 2) return rgb
a37ec3ad382f88bdc9de8fbc2b4e2524213607c3
3,635,381
def is_collection(name): """compare with https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/user""" return name in [ 'assignedLicenses', 'assignedPlans', 'businessPhones', 'imAddresses', 'interests', 'provisionedPlans', 'proxyAddresses', 'responsibilities', 's...
c2557f142f3ca066506256b273c9f65657079478
3,635,382
def unpack_list(string_: str): """ Recursively strip, split, translate and unpack provided string to the list. :param string_: str -- string to be unpacked into the list :return: list """ list_ = [] string2 = string_.replace("[", "", 1).strip("]") elements = string2.split("], ") if "[" ...
2271b4d67461ce20b4f11d77b47838a2689ba196
3,635,383
def in_nested_list(my_list, item): """ Determines if an item is in my_list, even if nested in a lower-level list. """ if item in my_list: return True else: return any(in_nested_list(sublist, item) for sublist in my_list if isinstance(sublist, list))
3daeaf89099bf19ba82eabfedd943adfb32fc146
3,635,385
def from_numpy_array(nparr, framerate): """ Returns an AudioSegment created from the given numpy array. The numpy array must have shape = (num_samples, num_channels). :param nparr: The numpy array to create an AudioSegment from. :param framerate: The sample rate (Hz) of the segment to generate. ...
4aa9e4e2f43de0bce106f0ddc685480a198b3255
3,635,386
import functools def visits_stmt(node_cls): """Decorator that registers a function as a visitor for ``node_cls``. :param node_cls: subclass of :class:`jinja2.nodes.Stmt` """ def decorator(func): stmt_visitors[node_cls] = func @functools.wraps(func) def wrapped_func(node, macro...
d902269e56ff5d6cb839852f767c2cc63d91c990
3,635,388
def is_prebuffer() -> bool: """ Return whether audio is in pre-buffer (threadsafe). Returns ------- is_prebuffer : bool Whether audio is in pre-buffer. """ is_prebuffer = bool(RPR.Audio_IsPreBuffer()) # type:ignore return is_prebuffer
8afa4979578be310fd71b22907c99bb747780454
3,635,389
def ad_reset_user_pwd_by_mail(user_mail_addr, new_password): """ 通过mail重置某个用户的密码 :param user_mail_addr: :return: """ conn = __ad_connect() user_dn = ad_get_user_dn_by_mail(user_mail_addr) result = conn.extend.microsoft.modify_password(user="%s" % user_dn, new_password="%s" % new_password...
91237ac20805f3a4999c627cf74f9c2de90415d7
3,635,390
def get_data(name: str, override: bool=True) -> str: """ Obtiene el contenido del archivo SVG que coincida con el nombre. Si override es False, se lanzará una excepción en caso de no encontrar el archivo con el nombre indicado. """ if not ".svg" in name: name += ".svg" overri...
f8facd1ab9e37f7fc3e8ffb6cbbb5e9ea5161abb
3,635,391
def array_read(array, i): """ This OP is used to read data at the specified position from the input array :ref:`api_fluid_LoDTensorArray` . ``array`` is the input array and ``i`` is the specified read position. This OP is often used together with :ref:`api_fluid_layers_array_write` OP. Case 1...
ca7acc95c9ae8213a38a981c3d6c7c86b77a17a5
3,635,392
import requests def get_user_posts (user_id, count, tags = None, expiry = None): """Get a user's Instagram posts. Filter by tags and and max $count items. Returns: Response: the JSON items representing instagram posts. """ # create the cache key cache_key = filecache.create_key('{us...
f2f4b95a9b7dd1b1e477ac8c5ffff0667f46466b
3,635,393
def list_active_containers(): """Return python list of all containers in state table list of tuples """ containers = [] state_info = ContainerState.query.all() for state in state_info: containers.append([state.c_id, state.name]) return containers
64b37ee392b981e264457a486651cbc9641ab0af
3,635,395
import typing def filter_imports(language: Language, t: pydsdl.CompositeType, sort: bool = True) -> typing.List[str]: """ Returns a list of all modules that must be imported to use a given type. :param pydsdl.CompositeType t: The type to scan for dependencies. :p...
e9171ff6b39e082e2e6e735366b890d689a3bed9
3,635,396
def compute_ramlak_filter(dwidth_padded, dtype=np.float32): """ Compute the Ramachandran-Lakshminarayanan (Ram-Lak) filter, used in filtered backprojection. :param dwidth_padded: width of the 2D sinogram after padding :param dtype: data type """ L = dwidth_padded h = np.zeros(L, dtype=d...
e8370f28d140de83d913fbddd71aadf5809b3fa4
3,635,397
def t_seg(p1, p2, t, align=0): """ trim segment Args: p1, p2: point(x, y) t: scaling factor (1 - trimed segment / original segment) align: 1: trim p2, 2: trim p1, 0: both side Return: trimmed segment(p1, p2) """ v = vector(p1, p2) result = { 1: lambda a, b: (a, tr...
879f8cad825f0787d71a152a5d673f9269696870
3,635,398
def isomorphic(tt,ttt): """True if isomorphic.""" (a,b) = isomorphism(tt,ttt) return (len(b) > 0)
e5f63e3a65fd9a6928940ad53a0fda745002ac03
3,635,399
def make_connector(name=None): """A connector between constraints""" informant = None constraints = [] def set_value(source, value): nonlocal informant val = connector["val"] if val is None: informant, connector["val"] = source, value if name is not None:...
46b6574b6e8965d56f71efa89a1d7389502f2867
3,635,400