content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os import json def read_config(): """Read configuration file.""" config_file = os.getenv('CONFIG_FILE_PATH') if not config_file: config_file = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'config.json') with open(config_file) as file: return json.load(f...
3df2d5d081e9a6f8326d4d85e0ab4405dd37d461
22,800
def sendSingleCommand(server, user, password, command): """Wrapper function to open a connection and execute a single command. Args: server (str): The IP address of the server to connect to. username (str): The username to be used in the connection. password (str): The password asso...
78a339b2bcb320ad81e79b8656867b894be22ecd
22,801
def test_piecewise_fermidirac(precision): """Creates a Chebyshev approximation of the Fermi-Dirac distribution within the interval (-3, 3), and tests its accuracy for scalars, matrices, and distributed matrices. """ mu = 0.0 beta = 10.0 def f(x): return 1 / (np.exp(beta * (x - mu)) + 1) is_vectori...
587b7acfc5a114677f1bf5ab5a72a9f2019c6063
22,802
def load_img(flist): """ Loads images in a list of arrays Args : list of files Returns list of all the ndimage arrays """ rgb_imgs = [] for i in flist: rgb_imgs.append(cv2.imread(i, -1)) # flag <0 to return img as is print "\t> Batch import of N frames\t", len(rgb_imgs) size_var = ...
74d3c312e936f434b3738eae79b8f499755cdd0a
22,803
import astropy.io.fits as pyfits def makesimpleheader(headerin,naxis=2,radesys=None,equinox=None,pywcsdirect=False): """ Function to make a new 'simple header' from the WCS information in the input header. Parameters ---------- headerin : astropy.io.fits.header Header object nax...
ffdc8f755227451e3df2329e8ec804b7444a553d
22,804
def _callcatch(ui, func): """like scmutil.callcatch but handles more high-level exceptions about config parsing and commands. besides, use handlecommandexception to handle uncaught exceptions. """ detailed_exit_code = -1 try: return scmutil.callcatch(ui, func) except error.AmbiguousC...
495531b930187f1d3aff329453235f9683bc25bc
22,805
def _determ_estim_update(new_bit, counts): """Beliefs only a sequence of all ones or zeros. """ new_counts = counts[:] new_counts[new_bit] += 1 if new_counts[0] > 0 and new_counts[1] > 0: return LOG_ZERO log_p_new = _determ_log_p(new_counts) log_p_old = _determ_log_p(counts) ret...
ea6f172161b215d5d474241da18fdd222692f245
22,806
def get_projects(config): """Find all XNAT projects and the list of scan sites uploaded to each one. Args: config (:obj:`datman.config.config`): The config for a study Returns: dict: A map of XNAT project names to the URL(s) of the server holding that project. """ proje...
09824b67e73f8190d777ec782454940f27b70e33
22,807
import json def load_jsonrpc_method(name): """Load a method based on the file naming conventions for the JSON-RPC. """ base_path = (repo_root() / "doc" / "schemas").resolve() req_file = base_path / f"{name.lower()}.request.json" resp_file = base_path / f"{name.lower()}.schema.json" request = C...
173fdaad563989042f6ff3c5622c4b56be1a5fa5
22,808
def download_missing_namespace(network_id: int, namespace: str): """Output a namespace built from the missing names in the given namespace. --- tags: - network parameters: - name: network_id in: path description: The database network identifier required: true ...
daca8a78454aec73bbf1e8a54f1a006aa748681c
22,809
def client_decrypt_hello_reply(ciphertext, iv1, key1): """ Decrypt the server's reply using the IV and key we sent to it. Returns iv2, key2, salt2 (8 bytes), and the original salt1. The pair iv2/key2 are to be used in future communications. Salt1 is returned to help confirm the integrity of the oper...
70f3361acbeaa26376d4a54605a526ecac5ea61e
22,810
import pandas def load_labeled_data(filename): """ Loads data from a csv, where the last column is the label of the data in that row :param filename: name of the file to load :return: data frames and labels in separate arrays """ dataframe = pandas.read_csv(filename, header=None) dataset = dat...
727691d376b744ccfdffbd62dd9f386e7bd7c4dd
22,811
import logging def get_logger(name, level='debug', log_file='log.txt'): """ Retrieve the logger for SWIFLow with coloredlogs installed in the right format """ # Setup logging log_level = level.upper() level = logging.getLevelName(log_level) # Add a custom format for logging fmt = ...
bb990320b689faa7385952612afe44fc17ae4d7b
22,812
import sh import os import errno import shutil def filesystem_move( source_path, source_type, destination_path, destination_type, backup_ending, ): """ Moves a file from the source to the destination. Arguments --------- source_path: path to the source ...
5d3cb03248f04dc93d086026a01d43cc1c3bdd9f
22,813
def _get_data_tuple(sptoks, asp_termIn, label): """ Method obtained from Trusca et al. (2020), no original docstring provided. :param sptoks: :param asp_termIn: :param label: :return: """ # Find the ids of aspect term. aspect_is = [] asp_term = ' '.join(sp for sp in asp_termIn)....
2dae699ba4da27f6a36b7aac21cc8bc759a71d67
22,814
from pathlib import Path def setup_environment(new_region: Path) -> bool: """Try to create new_region folder""" if new_region.exists(): print(f"{new_region.resolve()} exists, this may cause problems") proceed = input("Do you want to proceed regardless? [y/N] ") sep() return pro...
175e21b10aca860d9886841be743d8f2a240dfc6
22,815
def is_favorable_halide_environment( i_seq, contacts, pdb_atoms, sites_frac, connectivity, unit_cell, params, assume_hydrogens_all_missing=Auto): """ Detects if an atom's site exists in a favorable environment for a halide ion. This includes coordinating by a positively charged sid...
dc09952a022c0bf8d946773db0487293da88c4a5
22,816
def headers(): """Default headers for making requests.""" return { 'content-type': 'application/json', 'accept': 'application/json', }
53e42df6cae8ba9cbdc5f0e0a86a0154d3ba360e
22,817
def merge_two_lists(l1: ListNode, l2: ListNode) -> ListNode: """Returns a single sorted, in-place merged linked list of two sorted input linked lists The linked list is made by splicing together the nodes of l1 and l2 Args: l1: l2: Examples: >>> l1 = linked_list.convert_list_t...
49033ef17e0940a201c70555cc0e49b8e745fb3b
22,818
import csv def map_SOPR_to_firm(): """ Map SOPR identifiers to a lobbying CUID. Return a dictionnary. """ firms = {} with open(DATASET_PATH_TO['LOBBYING_FIRMS'], 'rb') as f: reader = csv.reader(f, delimiter='%', quoting=csv.QUOTE_NONE) for record in reader: SOPR_reports =...
e0f00d7f720512eef3e32685bb8ba5ed4ed0203c
22,819
from typing import Set def specialbefores_given_external_square( befores: Set[Before], directly_playable_squares: Set[Square], external_directly_playable_square: Square) -> Set[Specialbefore]: """ Args: befores (Set[Before]): a set of Befores used to create Specialbefores. ...
bb0405cc783ee94130893d0dca0f0b06e43d71c5
22,820
import os from typing import Tuple def load_sets(path: WindowsPath = project_dir / 'data/processed') -> \ Tuple[pd.DataFrame, pd.DataFrame, pd.Series, pd.Series]: """ :param path: :return: """ X_train = pd.read_csv(os.path.join(path, "X_train.c...
31afd27131579d2d14e9bf8e2ddbd81db4825c72
22,821
import pytest def check_if_all_tests_pass(option='-x'): """Runs all of the tests and only returns True if all tests pass. The -x option is the default, and -x will tell pytest to exit on the first encountered failure. The -s option prints out stdout from the tests (normally hidden.)""" options =...
81e41cb985bcf346d9351d327d0ca0941ed7320e
22,822
import http def init(api, _cors, impl): """Configures REST handlers for allocation resource.""" namespace = webutils.namespace( api, __name__, 'Local nodeinfo redirect API.' ) @namespace.route('/<hostname>/<path:path>') class _NodeRedirect(restplus.Resource): """Redirects to loca...
77430c891ceac87bec3d8b1cfa46557fbc1fd9f5
22,823
def split_matrix_2(input1): """ Split matrix. Args: inputs:tvm.Tensor of type float32. Returns: akg.tvm.Tensor of type float32 with 3d shape. """ dim = input1.shape[0] split_num = dim // split_dim result_3 = allocate((split_num, split_dim, split_dim), input1.dtype, 'loc...
8ee5b4069c28166ef6181cb8c6ef1e21232239a4
22,824
import glob def load_all(path, jobmanager=None): """Load all jobs from *path*. This function works as a multiple execution of |load_job|. It searches for ``.dill`` files inside the directory given by *path*, yet not directly in it, but one level deeper. In other words, all files matching ``path/*/*.dill`` ar...
f76e2baeaa0b35283eed4748d68403827bdaff97
22,825
import numpy def relative_error(estimate, exact): """ Compute the relative error of an estimate, in percent. """ tol = 1e-15 if numpy.abs(exact) < tol: if numpy.abs(estimate - exact) < tol: relative_error = 0.0 else: relative_error = numpy.inf else: ...
4170fd4a7c448eb312ea9f42d436d12acd828695
22,826
import os def extract_sample_paths(seq_dir): """ Obtain the sample paths. Parameters ---------- seq_dir : str Input directory containing all of the sample files. Returns ------- dict of list of str Samples with a list of their forward and reverse files. """ fps = os...
8e02cec67a6c836bb08d31f47c9513af5fae6114
22,827
def list_users(cursor): """ Returns the current roles """ cursor.execute( """ SELECT r.rolname AS name, r.rolcanlogin AS login, ARRAY( SELECT b.rolname FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid) W...
b51efbae5da08089987e3bc2753e1da3c13ee365
22,828
import subprocess def getVelocityRange(vis, options={}): """ Parse the velocity range from uvlist. Useful when resampling and re-binning data in `line` selections Returns a tuple of the form (starting velocity, end velocity) """ options['vis'] = vis options['options'] = 'spec' specdata = uvlist(options, std...
268a2228f45f05b364b8173ec0ee4b2571ae068f
22,829
def get_job_exe_output_vol_name(job_exe): """Returns the container output volume name for the given job execution :param job_exe: The job execution model (must not be queued) with related job and job_type fields :type job_exe: :class:`job.models.JobExecution` :returns: The container output volume name ...
c625b596f9ee819eb0c7afc9aed1328ecef0e206
22,830
def bytes2human(n, format='%(value).1f %(symbol)s', symbols='customary'): """ Convert n bytes into a human readable string based on format. symbols can be either "customary", "customary_ext", "iec" or "iec_ext", see: http://goo.gl/kTQMs >>> bytes2human(0) '0.0 B' >>> bytes2human(0.9) ...
21d3f52fe60a25a860c8350c20e0b43209802751
22,831
def check_if_free(driver, available, movie_hulu_url): """ Check if "Watch Movie" button is there if not, it's likely available in a special package (Starz etc) or availabe for Rent on Hulu. """ is_free = False if available: driver.get(movie_hulu_url) sleep(3) watch_movie_button = driver.find_elements_...
e27d62538e5bf9c416bcaedb4b7c5c4706493ba0
22,832
def scatter_add(data, indices, updates, axis=0): """Update data by adding values in updates at positions defined by indices Parameters ---------- data : relay.Expr The input data to the operator. indices : relay.Expr The index locations to update. updates : relay.Expr ...
641d96562700553a2ed4a5c4df323d468bba1bd8
22,833
def generate_test_linked_list(size=5, singly=False): """ Generate node list for test case :param size: size of linked list :type size: int :param singly: whether or not this linked list is singly :type singly: bool :return: value list and generated linked list """ assert size >= 1 ...
5d6d5fc3c6027cc18fd6da24a7cefc506e64eb2a
22,834
def _bytes_to_long(bytestring, byteorder): """Convert a bytestring to a long For use in python version prior to 3.2 """ result = [] if byteorder == 'little': result = (v << i * 8 for (i, v) in enumerate(bytestring)) else: result = (v << i * 8 for (i, v) in enumerate(reversed(byt...
fcaa038b21aef2822ad7a513c28a7a2ed3c08cbc
22,835
import os def process_manifest_for_key(manifest, manifest_key, installinfo, parentcatalogs=None): """Processes keys in manifests to build the lists of items to install and remove. Can be recursive if manifests include other manifests. Probably doesn't handle circular mani...
1bb5386f35c9197963a4640203965aa79fa7e221
22,836
import contextlib import ast def SoS_exec(script: str, _dict: dict = None, return_result: bool = True) -> None: """Execute a statement.""" if _dict is None: _dict = env.sos_dict.dict() if not return_result: if env.verbosity == 0: with contextlib.redirect_stdout(None): ...
c524aa064dfc396d421cdef9962d81ca79c7010b
22,837
def aten_dim(mapper, graph, node): """ 构造获取维度的PaddleLayer。 TorchScript示例: %106 : int = aten::dim(%101) 参数含义: %106 (int): 输出,Tensor的维度。 %101 (Tensor): 输入的Tensor。 """ scope_name = mapper.normalize_scope_name(node) output_name = mapper._get_outputs_name(node)[0] lay...
8037cc1943577aed2737aceee47b97b59c6a9244
22,838
import numpy def calcBlockingMatrix(vs , NC = 1 ): """Calculate the blocking matrix for a distortionless beamformer, and return its Hermitian transpose.""" vsize = len(vs) bsize = vsize - NC blockMat = numpy.zeros((vsize,bsize), numpy.complex) # Calculate the perpendicular projection op...
a46955771ba729a22fe18959ca6f9ac82af031b3
22,839
def plot_LA(mobile, ref, GDT_TS, GDT_HA, GDT_ndx, sel1="protein and name CA", sel2="protein and name CA", cmap="GDT_HA", **kwargs): """ Create LocalAccuracy Plot (heatmap) with - xdata = residue ID - ydata = frame number - color = color-coded pair distance .. Note...
8103dbeb9801b08125ebb5e26cb5f76c948262ec
22,840
import os import pickle def calculate_psfs(output_prefix): """Tune a family of comparable line-STED vs. point-STED psfs. """ comparison_filename = os.path.join(output_prefix, 'psf_comparisons.pkl') if os.path.exists(comparison_filename): print("Loading saved PSF comparisons...") compar...
0608ceee2089d692268d422acc0c16270aaa733f
22,841
def simulateGVecs(pd, detector_params, grain_params, ome_range=[(-np.pi, np.pi), ], ome_period=(-np.pi, np.pi), eta_range=[(-np.pi, np.pi), ], panel_dims=[(-204.8, -204.8), (204.8, 204.8)], pixel_pitch=(0.2, 0.2), ...
bdff9dc1b7fd15d7b3b1cf45a4364dc495790293
22,842
import logging def get_logger(name: str): """Get logger call. Args: name (str): Module name Returns: Logger: Return Logger object """ logger = logging.getLogger(name) logger.setLevel(logging.INFO) logger.addHandler(get_file_handler()) logger.addHandler(get_stream_hand...
6d661896d38e2227b6825e649bdbd719dd64670a
22,843
def create_label_colormap(dataset=_PASCAL): """Creates a label colormap for the specified dataset. Args: dataset: The colormap used in the dataset. Returns: A numpy array of the dataset colormap. Raises: ValueError: If the dataset is not supported. """ if dataset == _PASCAL: return create...
683d52f3f2c476b0e39e41ae7f2a0f897fee60d3
22,844
def SDM_lune(params, dvals, title=None, label_prefix='ham='): """Exact calculation for SDM circle intersection. For some reason mine is a slight upper bound on the results found in the book. Uses a proof from Appendix B of the SDM book (Kanerva, 1988). Difference is neglible when norm=True.""" res = expected_i...
e1465e002632ceb1431fa1a668abfdaa7deb307b
22,845
def font_match(obj): """ Matches the given input againts the available font type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ return match(obj, f...
8cf99e626578d278b3ce9e598233cb6dfa407820
22,846
def process_image(debug=False): """Processes an image by: -> sending the file to Vision Azure api -> returns a dictionary containing the caption and confidence level associated with that image TODO implement """ # get the json data json_data = response.json() if json_...
6931d523223c960721c37bffd47d89f2daeba7f6
22,847
import six def time_monotonically_increases(func_or_granularity): """ Decorate a unittest method with this function to cause the value of :func:`time.time` and :func:`time.gmtime` to monotonically increase by one each time it is called. This ensures things like last modified dates always increase....
f3f76502cf0cd5f402cb4f585d6cd06db8eb5851
22,848
def rotate_coordinates(coords: np.ndarray, axis_coords: np.ndarray) -> np.ndarray: """ Given a set of coordinates, `coords`, and the eigenvectors of the principal moments of inertia tensor, use the scipy `Rotation` class to rotate the coordinates into the principal axis frame. Parameters ------...
686657f464fdf846fa394128ad1f8be6d00adf06
22,849
from typing import Type from typing import Any def get_maggy_ddp_wrapper(module: Type[TorchModule]): """Factory function for MaggyDDPModuleWrapper. :param module: PyTorch module passed by the user. """ class MaggyDDPModuleWrapper(TorchDistributedDataParallel): """Wrapper around PyTorch's DDP...
53f7e5096c41221072d7584470dd8a1bcf32a04f
22,850
def random_jitter(cv_img, saturation_range, brightness_range, contrast_range): """ 图像亮度、饱和度、对比度调节,在调整范围内随机获得调节比例,并随机顺序叠加三种效果 Args: cv_img(numpy.ndarray): 输入图像 saturation_range(float): 饱和对调节范围,0-1 brightness_range(float): 亮度调节范围,0-1 contrast_range(float): 对比度调节范围,0-1 Retur...
f7ff6d2e0bbe1656abe5ad1dca404e1903417166
22,851
from typing import Union def render_orchestrator_inputs() -> Union[Driver, None]: """ Renders input form for collecting orchestrator-related connection metadata, and assembles a Synergos Driver object for subsequent use. Returns: Connected Synergos Driver (Driver) """ with st.sidebar....
d67f3a40347a2f247183e2b9092429ca118bc739
22,852
import logging def json_cache_wrapper(func, intf, cache_file_ident): """ Wrapper for saving/restoring rpc-call results inside cache files. """ def json_call_wrapper(*args, **kwargs): cache_file = intf.config.cache_dir + '/insight_dash_' + cache_file_ident + '.json' try: # looking int...
176c6f5a7b14dc2389592c415ffa9e122ebcd794
22,853
def type_assert_dict( d, kcls=None, vcls=None, allow_none: bool=False, cast_from=None, cast_to=None, dynamic=None, objcls=None, ctor=None, desc: str=None, false_to_none: bool=False, check=None, ): """ Checks that every key/value in @d is an instance of @kcls: @vcls ...
8a5590a86a0f2e1b4dbef5218c4a294dde3675e1
22,854
def get_missing_ids(raw, results): """ Compare cached results with overall expected IDs, return missing ones. Returns a set. """ all_ids = set(raw.keys()) cached_ids = set(results.keys()) print("There are {0} IDs in the dataset, we already have {1}. {2} are missing.".format(len(all_ids), len...
cb380c12f26de8b4d3908964f4314bc7efe43056
22,855
import collections def _spaghettinet_edgetpu_s(): """Architecture definition for SpaghettiNet-EdgeTPU-S.""" nodes = collections.OrderedDict() outputs = ['c0n1', 'c0n2', 'c0n3', 'c0n4', 'c0n5'] nodes['s0'] = SpaghettiStemNode(kernel_size=5, num_filters=24) nodes['n0'] = SpaghettiNode( num_filters=48, ...
93b98a29654f8a838f39d6bfa59f78719ff6c42c
22,856
def instance_of(type): """ A validator that raises a :exc:`TypeError` if the initializer is called with a wrong type for this particular attribute (checks are perfomed using :func:`isinstance` therefore it's also valid to pass a tuple of types). :param type: The type to check for. :type type: t...
2d41d457e9f7e60fa5e5d77f83454ca75dc112f7
22,857
import subprocess import os def execute_command(command): """ execute command """ output = subprocess.PIPE flag = 0 # for background execution if("nohup" in command) or ("\&" in command): output = open('result.log', 'w') flag = 1 child = subprocess.Popen(command.split()...
a5f80a2fc0c9adc4f8f01eab26d1466aa4b0b438
22,858
def ass(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#ass""" return filter(stream, ass.__name__, *args, **kwargs)
7f9d88fe1fdeb2337acce25e8b40db94d59f8748
22,859
def resultcallback(group): """Compatibility layer for Click 7 and 8.""" if hasattr(group, "result_callback") and group.result_callback is not None: decorator = group.result_callback() else: # Click < 8.0 decorator = group.resultcallback() return decorator
1eb938400c90667eb532366f5ca83d02dd6429e1
22,860
from licensedcode import cache def get_license_matches(location=None, query_string=None): """ Return a sequence of LicenseMatch objects. """ if not query_string: return [] idx = cache.get_index() return idx.match(location=location, query_string=query_string)
5d2891d36dd10e6c4d1c24280df86d1bf39e464a
22,861
def compute_corrector_prf(results, logger, on_detected=True): """ References: https://github.com/sunnyqiny/ Confusionset-guided-Pointer-Networks-for-Chinese-Spelling-Check/blob/master/utils/evaluation_metrics.py """ TP = 0 FP = 0 FN = 0 all_predict_true_index = [] all_gol...
1f86b5f7cd91aba9a50007493d83cd3480eb9e20
22,862
def nonzero_sign(x, name=None): """Returns the sign of x with sign(0) defined as 1 instead of 0.""" with tf.compat.v1.name_scope(name, 'nonzero_sign', [x]): x = tf.convert_to_tensor(value=x) one = tf.ones_like(x) return tf.compat.v1.where(tf.greater_equal(x, 0.0), one, -one)
1955f37bece137537d53cde6681a8f56554cafea
22,863
def tls_control_system_tdcops(tls_control_system): """Control system with time-dependent collapse operators""" objectives, controls, _ = tls_control_system c_op = [[0.1 * sigmap(), controls[0]]] c_ops = [c_op] H1 = objectives[0].H H2 = objectives[1].H objectives = [ krotov.Objective(...
b94f438291671e863bb759ce024a0e42e6230481
22,864
def create_new_credential(site_name,account_name, account_password): """Function to create a new account and its credentials""" new_credential = Credentials(site_name,account_name, account_password) return new_credential
127335a31054d1b89521a1bc8b354ad51e193be6
22,865
import os def create_inception_graph(): """"Creates a graph from saved GraphDef file and returns a Graph object. Returns: Graph holding the trained Inception network, and various tensors we'll be manipulating. """ with tf.Session() as sess: model_filename = os.path.join( ...
69fc47bdceca23e530c21d6beb0e53b4adc24a3a
22,866
from typing import Dict def prepare_request_params( request_params: Dict, model_id: Text, model_data: Dict ) -> Dict: """ reverse hash names and correct types of input params """ request_params = correct_types(request_params, model_data["columns_data"]) if model_data["hashed_indexes"]: request...
c7aee17db83e96cb3bcf6ce75ea650414035654a
22,867
import pandas as pd import os def help_full(path): """Health Evaluation and Linkage to Primary Care The HELP study was a clinical trial for adult inpatients recruited from a detoxification unit. Patients with no primary care physician were randomized to receive a multidisciplinary assessment and a brief mo...
ec84932a5fb6cceeb86530145bd136890ed60568
22,868
from typing import List def get_all_listening_ports() -> List[int]: """ Returns all tcp port numbers in LISTEN state (on any address). Reads port state from /proc/net/tcp. """ res = [] with open('/proc/net/tcp', 'r') as file: try: next(file) for line in file: ...
cfc1b4b93358954ad802ce3727bd9d424ef9d136
22,869
async def mock_race_result() -> dict: """Create a mock race-result object.""" return { "id": "race_result_1", "race_id": "190e70d5-0933-4af0-bb53-1d705ba7eb95", "timing_point": "Finish", "no_of_contestants": 2, "ranking_sequence": ["time_event_1", "time_event_2"], ...
33a2889bcb2665642a3e5743128a478bb103a82b
22,870
import re import binascii def qr_to_install_code(qr_code: str) -> tuple[zigpy.types.EUI64, bytes]: """Try to parse the QR code. if successful, return a tuple of a EUI64 address and install code. """ for code_pattern in QR_CODES: match = re.search(code_pattern, qr_code, re.VERBOSE) if...
91ec3f90385e95b94c47c338f56b26315ff12e99
22,871
def vwr(scene, analyzer, test_number, workbook=None, sheet_format=None, agg_dict=None): """ Calculates Variability Weighted Return (VWR). :param workbook: Excel workbook to be saved to disk. :param analyzer: Backtest analyzer. :param sheet_format: Dictionary holding formatting information such as co...
7fa8c9794e443be91d0cf246c209dfdc86e19f54
22,872
def dec2hms(dec): """ ADW: This should really be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. dec = float(dec) fhour = dec*(HOUR/DEGREE) hour = int(fhour) fminute = (fhour - hour)*MINUTE minute = int(fminute) second = (fminut...
4c2c564631d431d908f66486af40e380598f2724
22,873
def logfpsd(data, rate, window, noverlap, fmin, bins_per_octave): """Computes ordinary linear-frequency power spectral density, then multiplies by a matrix that converts to log-frequency space. Returns the log-frequency PSD, the centers of the frequency bins, and the time points. Adapted from Matlab...
cf9a9ee3a248760e6bfa36a82ae782d607269b10
22,874
def ppg_dual_double_frequency_template(width): """ EXPOSE Generate a PPG template by using 2 sine waveforms. The first waveform double the second waveform frequency :param width: the sample size of the generated waveform :return: a 1-D numpy array of PPG waveform having diastolic peak at the...
9c04afb7687e19a96fb84bf1d5367dc79ce6ceea
22,875
import os import fnmatch def _run_fast_scandir(dir, fn_glob): """ Quickly scan nested directories to get a list of filenames that match the fn_glob string. Modified from https://stackoverflow.com/a/59803793/2441026 (faster than os.walk or glob methods, and allows filename matching in subdirectories). ...
79f95bb312663c7870ec71cc93a0b6000c08ebdd
22,876
def str_input(prompt: str) -> str: """Prompt user for string value. Args: prompt (str): Prompt to display. Returns: str: User string response. """ return input(f"{prompt} ")
ac6c3c694adf227fcc1418574d4875d7fa637541
22,877
def action(ra_deg, dec_deg, d_kpc, pm_ra_masyr, pm_dec_masyr, v_los_kms, verbose=False): """ parameters: ---------- ra_deg: (float) RA in degrees. dec_deg: (float) Dec in degress. d_kpc: (float) Distance in kpc. pm_ra_masyr: (float) RA proper motion...
0e707bff67cee3c909213f14181927a14d5d5656
22,878
def getProcWithParent(host,targetParentPID,procname): """ returns (parentPID,procPID) tuple for the procname with the specified parent """ cmdStr="ps -ef | grep '%s' | grep -v grep" % (procname) cmd=Command("ps",cmdStr,ctxt=REMOTE,remoteHost=host) cmd.run(validateAfter=True) sout=cmd.get_re...
77f4f13eb381dc840eee26875724cd6e1cdf1e57
22,879
def temporal_autocorrelation(array): """Computes temporal autocorrelation of array.""" dt = array['time'][1] - array['time'][0] length = array.sizes['time'] subsample = max(1, int(1. / dt)) def _autocorrelation(array): def _corr(x, d): del x arr1 = jnp.roll(array, d, 0) ans = arr1 * ar...
69640da51fa94edd92e793f2c86ac34090e70a28
22,880
import json def kv_detail(request, kv_class, kv_pk): """ GET to: /core/keyvalue/api/<kv_class>/<kv_pk>/detail/ Returns a single KV instance. """ Klass = resolve_class(kv_class) KVKlass = Klass.keyvalue_set.related.model try: kv = KVKlass.objects.get(pk=kv_pk) except KVKlas...
bd8961c25e39f8540b57753b8f923229e77ae795
22,881
from typing import Protocol import json def opentrons_protocol(protocol_id): """Get OpenTrons representation of a protocol.""" current_protocol = Protocol.query.filter_by(id=protocol_id).first() if not current_protocol: flash('No such specification!', 'danger') return redirect('.') i...
3a8cc4355763f788f01bb1d95aa43f5cb249a68f
22,882
import os def get_link_external(): """ Return True if we should link to system BLAS / LAPACK If True, attempt to link to system BLAS / LAPACK. Otherwise, compile lapack_lite, and link to that. First check ``setup.cfg`` file for section ``[lapack]`` key ``external``. If this value undefined, th...
2a6c867bf3cebf7966951f19f9beddddd22f0fad
22,883
def flag(request, comment_id, next=None): """ Flags a comment. Confirmation on GET, action on POST. Templates: `comments/flag.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings....
e0997313c13446150ed3a0f402b2df74089aa4e9
22,884
from typing import List def get_nodes_for_homek8s_group(inventory, group_name) -> List[str]: """Return the nodes' names of the given group from the inventory as a list.""" hosts_dict = inventory['all']['children']['homek8s']['children'][group_name]['hosts'] if hosts_dict: return list(hosts_dict.keys()) el...
806394259816ec4311e69dcd46e7b111c7ca0652
22,885
def is_blank_or_none(value: str): """ Returns True if the specified string is whitespace, empty or None. :param value: the string to check :return: True if the specified string is whitespace, empty or None """ try: return "".__eq__(value.strip()) except AttributeError: retur...
062e1ab33fc5043435af9e97cdf2443ffc4625bd
22,886
import typing def __get_play_widget(function: typing.Any) -> typing.Any: """Generate play widget. :param function: Function to associate with Play. :return: Play widget. """ play = widgets.interactive( function, i=widgets.Play( value=0, min=0, m...
5bb63256f84f1c6f50e2ae007a08e6e794535bc5
22,887
def add_data_to_profile(id, profile_id, read_only, tree_identifier, folder_path=None, web_session=None): """Shares data to user group Args: id (int): The id of the data profile_id (int): The id of profile read_only (int): The flag that specifies whether the data is read only tre...
489d246b90506b7581ee8aef66c7f5f2ba6b9b88
22,888
def get_activation_function(activation): """ Gets an activation function module given the name of the activation. :param activation: The name of the activation function. :return: The activation function module. """ if activation == 'ReLU': return nn.ReLU() elif activation == 'LeakyR...
ae5d8e91667e2dc4fe34eb1ac96cff329d542103
22,889
def get_value_from_time(a_node="", idx=0): """ gets the value from the time supplied. :param a_node: MFn.kAnimCurve node. :param idx: <int> the time index. :return: <tuple> data. """ return OpenMaya.MTime(a_node.time(idx).value(), OpenMaya.MTime.kSeconds).value(), a_node.value(idx),
77c6cb47c4381df3537754dc66e03ef4366557de
22,890
def getrinputs(rtyper, graph): """Return the list of reprs of the input arguments to the 'graph'.""" return [rtyper.bindingrepr(v) for v in graph.getargs()]
bb0f8861a29cd41af59432f267f07ff67601460c
22,891
import os def _apply_mask(head_file, mask_file, write_dir=None, caching=False, terminal_output='allatonce'): """ Parameters ---------- head_file : str Path to the image to mask. mask_file : str Path to the image mask to apply. write_dir : str or None, optional...
fe2964ad62aa466f6ca92c0329e15ef80ca48460
22,892
def mars_reshape(x_i): """ Reshape (n_stacks, 3, 16, 112, 112) into (n_stacks * 16, 112, 112, 3) """ return np.transpose(x_i, (0, 2, 3, 4, 1)).reshape((-1, 112, 112, 3))
d842d4d9b865feadf7c56e58e66d09c4a3389edf
22,893
def Rz_to_coshucosv(R,z,delta=1.): """ NAME: Rz_to_coshucosv PURPOSE: calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta INPUT: R - radius z - height delta= focus OUTPUT: (cosh(u),cos(v)) HISTORY: 2012-11-27 -...
f01ed002c09e488d89cfd4089343b16346dfb5fd
22,894
import ast import numpy def rpFFNET_createdict(cf,ds,series): """ Creates a dictionary in ds to hold information about the FFNET data used to gap fill the tower data.""" # get the section of the control file containing the series section = pfp_utils.get_cfsection(cf,series=series,mode="quiet") ...
60646de63106895eeb716f763c49195b9c5459e8
22,895
def svn_client_relocate(*args): """ svn_client_relocate(char dir, char from_prefix, char to_prefix, svn_boolean_t recurse, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t """ return _client.svn_client_relocate(*args)
55e78e311d461e5a20e5cd04778e6c8431a6d990
22,896
def get_pairs(image1, image2, global_shift, current_objects, record, params): """ Given two images, this function identifies the matching objects and pairs them appropriately. See disparity function. """ nobj1 = np.max(image1) nobj2 = np.max(image2) if nobj1 == 0: print('No echoes found in ...
5013764c7e2a1d5e12abc2107ffdbfca640f1423
22,897
def getComparedVotes(request): """ * @api {get} /getComparedVotes/?people_same={people_same_ids}&parties_same={parties_same_ids}&people_different={people_different_ids}&parties_different={parties_different_ids} List all votes where selected MPs/PGs voted the same/differently * @apiName getComparedVotes ...
e49b2e1b181761e56795868a3dd6ff5a0452cd05
22,898
def get_bits(register, index, length=1): """ Get selected bit(s) from register while masking out the rest. Returns as boolean if length==1 :param register: Register value :type register: int :param index: Start index (from right) :type index: int :param length: Number of bits (default 1...
0663d925c2c74ece359a430392881cf24b75a575
22,899