content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def orthonormal_initializer(output_size, input_size, debug=False): """adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py Parameters ---------- output_size : int input_size : int debug : bool Whether to skip this initializer Returns ------- ...
3fee5d0c2ffdf7e91eadddf72a079b3837fc3ef6
45,600
import requests def get_items(access_token, env, realm_id): """ Uses access token to get Item data for Invoice API """ half_url = f"{env}/v3/company/{realm_id}/query" api_parameters = {"query": "select * from Item", "minorversion": "38"} api_headers = {"Accept": "application/json", ...
5766a0d381a75dd096e0d4800cd71d7ca3a9ff24
45,601
import torch def create_dummy_tensors_single(): """ Binary: 1 actual, 1 predicted (tp: 1, fp: 0, fn: 0) """ label = torch.tensor([1]) pred = torch.tensor([1]) return (label, pred)
25a4f5de0b9fed74a5e0ce7a62507eb9a341b385
45,602
def uniqueroots(nodes): #(1) """Returns a list of the nodes in `nodes` that are not children of any node in `nodes`.""" result = [] def handle_node(n): #(2) """If any of the ancestors of n are in realroots, just return, otherwise, append n to realroots. """ for ancestor i...
b8855a9d5bc40ae51b779662c2b4db2be149f4d3
45,603
def autodoc_skip(app, what, name, obj, skip, options): """ Hook to tell autodoc to include or exclude certain fields (see :event:`autodoc-skip-member`). Sadly, it doesn't give a reference to the parent object, so only the ``name`` can be used for referencing. :param app: The Sphinx application obj...
6841451fd2c6e28028ab3d6da67b035bc57b236d
45,604
async def get_interval_data(meta_ids: str, start: str, end: str): """ 获取某时间段内的统计数据和 :param meta_ids: 请求的 meta_ids, 以英文 , 分隔的字符串 :param day: 开始时间,例如 2020-12-01 :param end: 结束时间,例如 2020-12-01 :param db: 数据库连接,不需要传 :return: """ ...
4d07441208a68b97a85bddd41413c24d911ab4ac
45,605
def convert_tf_config_to_jax_bert(config): """Convert TF BERT model config to be compatible with JAX BERT model. Args: config: dictionary of TF model configurations Returns: dictionary of param names and values compatible with JAX BERT model """ unnecessary_keys = ['initializer_range', 'backward_com...
2e527dbdbef404ebf3015eca2aa9eea2b9d892e0
45,606
import os def create_shapers(aces_ctl_directory, lut_directory, lut_resolution_1d, cleanup): """ Creates sets of shaper colorspaces covering the *Log 2* and *Dolby PQ* transfer functions and dynamic ranges suitable of use with the 48 nit, 100...
d9755ab1c33cd08c8452a30f71f400faf9ce5700
45,607
def find_sequences_before(context, strip): """ Returns a list of sequences that are before the strip in the current context """ return [s for s in context.sequences if s.frame_final_end <= strip.frame_final_start]
d49a950c06c2a92d076d9790055c21d30afdd627
45,608
import json def unpack_line_key(key): """Retrieve a model instance and options dict from a unique key created by create_line_key. """ bits = key.split(KEY_SEPARATOR) instance = unpack_instance_key(*bits[:-1]) options = json.loads(bits[-1]) return (instance, options)
c776f12eb140db242ff31a39db78990755a1d379
45,609
def profile_stgs(request): """ Display the users current settings and allow them to be modified """ user = request.user prof = get_object_or_404(Profile, user=user) if request.POST: form = SettingsForm(request.POST) if form.is_valid(): user.email = form.cleaned_data['ema...
8e48e2046b887c0d8710485363dfeeb7e4afa531
45,610
def pipe(*args, **kwargs): """A source that fetches the result of a given YQL query. Args: item (dict): The entry to process kwargs (dict): The keyword arguments passed to the wrapper Kwargs: conf (dict): The pipe configuration. Must contain the key 'query'. May contain...
e7d3ce05d7b5dbedfce4733fb41257d48846a79b
45,611
def calculate_percentages(df: pd.DataFrame, numer_columns: list, denom_column: str = 'total', column_name_add: str = 'percent_') -> pd.DataFrame: """Convenience function to calculate percentages based on counts data By default the cor...
c35b6d478691aa7a79ba4ae8da11cc0210ae14dc
45,612
def image_to_array(img_path:str): """ Convert image to numpy array Paramenter: img_path: str - Path to the image Returns: array: numpy.ndarray - The array converted from the image """ image = Image.open(str(img_path)) return np.array(image)
e4f5dd7aa7a3c6cac8f356dfd7dc0f72f9ad8f05
45,613
import json def liquidation(): """清算""" rps = {} rps["status"] = True if request.form.get("token"): token = request.form["token"] liq_date = request.form["check_date"] price_dict = {} if request.form.get("price_dict"): price_dict = request.form["price_dict"...
8ee956c6ffbecdde90a01487527b2869abd4d119
45,614
def _do_get_latest_featuregroup_version(featuregroup, featurestore_metadata): """ Utility method to get the latest version of a particular featuregroup Args: :featuregroup: the featuregroup to get the latest version of :featurestore_metadata: metadata of the featurestore Returns: ...
6370e61bdb6b4bfb3ea6d692721a8267f930100e
45,615
async def get_user_info( storage: StorageInterface = Depends(StorageInterface), ) -> models.UserInfo: """Get info about the current user""" with storage.start_transaction() as st: out: models.UserInfo = st.get_user() return out
d5a69faedbb1b7319b839bba3b4d37e4a79183dc
45,616
import math def update_one_contribute_score(user_total_click_num): """ item cf update sim contribution score by user """ return 1/math.log10(1+user_total_click_num)
3e80ae2f85a53737d0e155ff5f97910f73c9053f
45,617
def mel_spec(audio, sample_rate, window_stride=(160, 80), fft_size=512, num_filt=20): """Calculates mel spectrogram (condensed spectrogram)""" spec = power_spec(audio, window_stride, fft_size) return safe_log(np.dot(spec, filterbanks(sample_rate, num_filt, spec.shape[1]).T))
a9d85428d5bc66d64e5fd7094e03547724959bf0
45,618
def test1_feasible_actions(): """ Method for preparing the feasible actions for the movie booking data set """ # all of the request slots the agent can pick sys_request_slots = ['moviename', 'theater', 'starttime', 'date', 'numberofpeople', 'genre', 'state', 'city', 'zip', ...
13eee03f842bf76e627953a30bd766ddaf6ea50b
45,619
import sys import ctypes def _init_env(): """Initialize ODBC env handle Maybe add some more settings here, connection pooling etc. """ if sys.platform == 'darwin': api = ctypes.cdll.LoadLibrary('libodbc.2.dylib') else: api = ctypes.cdll.LoadLibrary('libodbc.so') env_h = ctypes....
afea2d636e472d74aae21ab0c23b134a482aa988
45,620
def get_percent_alloc(values): """ Determines a portfolio's allocations. Parameters ---------- values : pd.DataFrame Contains position values or amounts. Returns ------- allocations : pd.DataFrame Positions and their allocations. """ return values.divide( ...
7f4ec48b2adbdb812292930e7fda50038b6d5e96
45,621
import os def Multi30k(root, split, task='task1', language_pair=('de', 'en'), train_set="train", valid_set="val", test_set="test_2016_flickr"): """Multi30k Dataset The available datasets include following: **Language pairs (task1)**: ...
ec05164a0ed0b6f4f789b8792755adb4f49f79a4
45,622
def server_static(filepath): """Defina a Root para os ficheiros estaticos""" return static_file(filepath, root='/var/www/core/static')
a88cae7360f0932aa242618b81847f5fd1e174d0
45,623
def check_send_files(logger): """ Sends all queued files to the Bouldair server for the website. :param logger: logging logger to record to :return: bool, True if ran correctly, False if exit on error """ logger.info('Running check_send_files()') try: engine, session = connect_to_d...
87ec9ced8630ca2b706a94ffb11b53e822d22c02
45,624
import os import json def get_summary_level_config(dataset: str, q_variable: str, api_key: str = '', force_fetch: bool = False) -> dict: """Computes a list of summary levels available, their dependencies and list of required geo IDs for API calls. Args: dataset: Dataset of US census(e.g. acs/...
d323cc6440656ba49f65abe06b2f085c3eb19e3e
45,625
def create_embeddings_mapping(X_train_tokenized, X_test_tokenized, debug=False): """create the mapping from each token to its index Arguments: X_train_tokenized {DataFrame} -- train set X_test_tokenized {DataFrame} -- test set Keyword Arguments: debug {bool} -- print debug ...
42a90b77c809b9e173cd3ca082a2c74b351696eb
45,626
def get_used_namespace(project_id): """通过应用实例获取使用的命名空间""" # 通过project_id查询模板集信息 all_tmpl = Template.objects.filter(project_id=project_id).values("id") tmpl_id_list = [info["id"] for info in all_tmpl] ns_id_info = VersionInstance.objects.filter( is_deleted=False, is_bcs_success=True, template...
2e9ac5f94f955bec58be029a08995991dec5ad06
45,627
import argparse def parse_args(): """Argument parser.""" parser = argparse.ArgumentParser(description='Argument parser for AUPR-in/AUPR-out evaluations.') parser.add_argument('--algo_name', type=str, default='e3outlier-0.1') parser.add_argument('--positive', type=str, default='inliers', choices=['inli...
fe555da78a56ebd57ccca5fc160debabd0310c3d
45,628
def random_transform(im, gt, target_shape, saturation_range=None, value_range=None, brightness_range=None, contrast_range=None, blur_params=None, flip_lr=False, rotation_range=None, shift_range=None, zoom_range=None, ignore_label=0): """ Applies a list of transformation...
d4542d4283df85bb02d6c385adfea774a169b0ec
45,629
import re import os def is_excluded_path(args, filepath): """Returns true if the filepath is under the one of the exclude path.""" # Try regular expressions first. for regexp_exclude_path in args.regexp: if re.match(regexp_exclude_path, filepath): return True abspath = os.path.absp...
10b39df70faff491120c482dacfe6da51283e9a1
45,630
import json def getSurvivedStatus(survivedStatus): """ ---> Select survived passengers depending on status 0 or 1 <--- Return encoded list as a JSON payload with passengers data """ filterQuery = session.query(Titanic).filter(Titanic.Survived==survivedStatus).all() survivedList = [] for i...
4b3c06da186de46684444899eae7b1191453b4a9
45,631
import vtk def read_vertices(filename): """ Load VERTICES segment from a VTK file (actually indices to vertices). Parameters ---------- filename : string The path/filename of a VTK format file. Returns ------- indices : a list of integers Each element is an integer de...
0306df74ab5be52e413a5651a8e0a51f22c7d75d
45,632
def logout_auth(): """ This function is used for logged in user to logout. Clear all session data :return: if successful return status 1 """ session.clear() return jsonify({"status": 1})
33664d4634d9e2cfee15ccd2f6371cebff2614c1
45,633
def image_diff_threshold() -> float: """ Set default threshold differences of images. By default - 0.001 """ return 0.1
60d953425e2d33f1a075e3f223567fe6d731bf2b
45,634
from timeit import Timer from math import log def time_call(func, setup=None, maxtime=1, bestof=3): """ timeit() wrapper which tries to get as accurate a measurement as possible w/in maxtime seconds. :returns: ``(avg_seconds_per_call, log10_number_of_repetitions)`` """ timer = Timer(func,...
218f9032e02347ee58f1f2d725089d9d5a310951
45,635
def ustr(string): """ Returns the Python version relevant string type """ try: return unicode(string) except NameError: return str(string)
77ef97998215cbbee1a3db3ffe691da679878e5a
45,636
def get_blender_mesh_shape_key(me): """Return main shape deformer's key.""" return "|".join((get_blenderID_key(me), "Shape"))
3602cf4987b9ded7fc06b4b18bb9d7834682ba37
45,637
import multiprocessing import sys def generate_STS_distance_matrix(slope_matrix, nthreads=4): """Takes in the slope matrix and returns the distance matrix. Uses parallel processing. Parameters ---------- slope_matrix: np.matrix Matrix of the time-series slopes, produced by calculate_slope...
f281f6f4806cedebe2657242e997f2947d471e59
45,638
def binary_peirce_score(target_tensor, forecast_probability_tensor): """Returns binary Peirce score. :param target_tensor: See docstring for the 2 possible formats. :param forecast_probability_tensor: Same. :return: binary_peirce_score: Binary Peirce score. """ return ( binary_pod(targ...
1786cba03f31ce801d9586f564b438237bf3e4af
45,639
def addURL(g: rdflib.ConjunctiveGraph) -> rdflib.ConjunctiveGraph: """ Add a URL to the public permalink of the RKD website to each manuscript resource. Args: g: The graph object. Returns: The graph object with the URL added. """ manuscripts = g.subjects(RDF.type, SCHEMA.Manus...
dca63a8518942b20a816d3dca53a8df1bd6cf53e
45,640
from typing import Union from typing import Optional from datetime import datetime import traceback def fit_and_check_correctness(pipeline: Pipeline, data: Union[InputData, MultiModalData], logger: Log, cache: Optional[OperationsCache] = None, n_jobs=1): ...
e3a01f2be9068c090dcd700d3d46d3e5ae4267f9
45,641
def insertNodeAtPosition(head, data, position): """Function to insert a new node into a linked list at the specified index position Args: head (SinglyLinkedListNode): Head of the linked list data (int): Data to store in the linked list position (int): The position to store the new node ...
3498853d4fad38e4e345e4ef4d7194c6bc86c0da
45,642
def fase1(): """ Render the fase1 template on the /fase1 route """ pagesClassIDs = { "fase1": { "bannertitle": [], "subtitle": [], "firstText": [], "secondText": [] } } for key in pagesClassIDs["fase1"].keys(): pagesClassID...
3e62a6193a2407e23d3441ddbb945558c54ff9c3
45,643
import sys import os import platform import glob def run_git_hook(cmd, param=[]): """Execute a hook if the hook exists.""" if verbose: sys.stderr.write("Looking for hook: %s\n" % cmd) sys.stderr.flush() hooks_path = gitConfig("core.hooksPath") if len(hooks_path) <= 0: hooks_pa...
683d06265a52d832c03025af7f7f8866ceffb8c6
45,644
from datetime import datetime def service( valid: datetime = Query(None), ): """Replaced above.""" df = run(valid) return deliver_df(df, "geojson")
89816044e4f23c60b70a3dbee7522ff2d2e8ee90
45,645
from typing import Type def has_bytes_component(typ: Type, py2: bool = False) -> bool: """Is this one of builtin byte types, or a union that contains it?""" typ = get_proper_type(typ) if py2: byte_types = {'builtins.str', 'builtins.bytearray'} else: byte_types = {'builtins.bytes', 'bui...
795450f0905224d2060634998236607228bf829c
45,646
from pathlib import Path def parameters(): """ Generate the platform-scenario test cases. """ exclude, include = read_skip_list() number = 0 params = [] scenarios = [p.parent.name for p in Path().glob('molecule/*/molecule.yml')] for p in PLATFORMS: for s in scenarios: ...
6e967c6ddfd291bdf1b6e303f3d861acf9bd3324
45,647
def dis(func): """ Disassemble a function into cpython_assembly format """ co = func.__code__ result = [] if func.__doc__: for line in func.__doc__.splitlines(): result.append(line) result.append(' :::asm') result.append(' .stacksize {0}'.format(co.co_stacksiz...
2013a3ba5bf3d38a42a239831f155e67a000ef5f
45,648
def cluster(distance_matrix, threshold, linkage_method='weighted', show_result=False, file_id=None, den_label_size=9, mat_label_size=7, trim_indices=[]): """Computes the clustering solution for a distance matrix and threshold Computes the linkages for a distance matrix using SciPy's hierarchical (agglomera...
74e4c00d755ac40b258d095cdb0298f81956d9b0
45,649
def get_length(token, negative=True, percentage=False): """Parse a <length> token.""" if percentage and token.type == 'percentage': if negative or token.value >= 0: return Dimension(token.value, '%') if token.type == 'dimension' and token.unit in LENGTH_UNITS: if negative or toke...
1d2de66ef2acb13b5933d321bc3f40918608e7c2
45,650
from masci_tools.vis.common import convergence_plot def test_convergence_mpl(): """ Test of the convergence_plot function with mpl backend """ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6)) convergence_plot(CONVERGENCE_ITERATIONS, CONVERGENCE_DISTANCES, ...
1cc9960dabcef7cde85e6bd70d8797e56826dbf5
45,651
import os def fixture_encode_vorbis(): """fixture_encode_vorbis""" wav_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "test_audio", "ZASFX_ADSR_no_sustain.wav", ) audio = tf.audio.decode_wav(tf.io.read_file(wav_path)) value = audio.audio * (1 << 15) va...
356b468bbbe38d19dad4023cdfb06acb59536660
45,652
from operator import gt def structure_sampling2(graph, centrality, function, retain_factor): """ Returns a graph view for the graph with close to retain_factor edges centrality should have a function .get_values that returns the values for the centrality function should be a function that takes two vector...
8c8fa2c481e54995fcd6a21e2e14cef6f76e24ca
45,653
def atcab_aes_cbcmac_finish(ctx, mac, mac_size): """ Finish a CBC-MAC operation returning the CBC-MAC value. If the data provided to the atcab_aes_cbcmac_update() function has incomplete block this function will return an error code. Args: ctx AES-128 CBC-MAC context. mac ...
b98fc024c3bf364214025e173596cd10571e3835
45,654
def make_wsgi_app(registry=REGISTRY): """Create a WSGI app which serves the metrics from a registry.""" def prometheus_app(environ, start_response): # Prepare parameters accept_header = environ.get('HTTP_ACCEPT') params = parse_qs(environ.get('QUERY_STRING', '')) if environ['PATH...
6844bd4cb89c67d82d003087756f6a38eeaeb176
45,655
import click def init(): """Treadmill Websocket""" @click.command() @click.option('--fs-root', help='Root file system directory to zk2fs', required=True) @click.option('-m', '--modules', help='API modules to load.', required=True, type=cli.LIST) ...
a2e684386ea9ed463bc81cf76780432f4f1ee73e
45,656
def _tournament_selection(parents: Population, n: int, fitness_idx: int = 0, k: int = 2, w: int = 1, replacement: bool = False): """ Tournament selection is an operator that doesn't require any global knowledge of the population, nor a quantifiable measure of quality. In this case ...
b506f4a69c7c33eebea03b973796089e07ef62c6
45,657
import threading def setup(hass, config=None): """ Sets up the HTTP API and debug interface. """ if config is None or DOMAIN not in config: config = {DOMAIN: {}} api_password = util.convert(config[DOMAIN].get(CONF_API_PASSWORD), str) no_password_set = api_password is None if no_password...
d74326b5dc2e4d640dd82c308a00b6b05b58bdf4
45,658
def format_latex(ss): """ Formats a string so that it is compatible with Latex. :param ss: The string to format :type ss: string :return: The formatted string :rtype: string """ tt = (str(ss).replace('_', ' ') .replace('%', '\%') ) r...
5081e65375faf592f2f1fb52d11b0dcee99fa85f
45,659
import os def CheckForInstalledBinary(binary_name, custom_message=None): """Check if binary is installed and return path or raise error. Prefer the installed component over any version found on path. Args: binary_name: str, name of binary to search for. custom_message: str, custom message to used by ...
52d7b248828d949e85072a41cd68a711046cc46a
45,660
from typing import Optional def get_by_ref(db_session: Session, *, ref: str) -> Optional[TriggerDB]: """Return trigger object based on trigger ref. Arguments: db_session {Session} -- SQLAlchemy Session object ref {str} -- ref string Returns: Optional[TriggerDB] -- Returns a Trigg...
66198a92e70889a824454eab5fed7d6361c1ef2e
45,661
def cross_entropy(output, labels, target=None): """ Compute the cross entropy between output and labels. Can do multiple examples at a time. Dimensions of output and labels must match and the target collapses along the row axis """ if not target: n = _cudanet.get_nonleading_dimension(outpu...
e057ea1ff9a37888d5aa37402dd7f10c6944d8d7
45,662
def CheckTreeIsOpen(input_api, output_api, url, closed, url_text): """Similar to the one in presubmit_canned_checks except it shows an helpful status text instead. """ assert(input_api.is_committing) try: connection = input_api.urllib2.urlopen(url) status = connection.read() connection.close() ...
e442c04f95e0c8c65fadd408d3e472b3f18faac8
45,663
def temporal_split(df, start_year=2019, start_month=6, start_day=1, end_year=2019, end_month=8, end_day=1): """ Starts with client_df, returns DataFrame of clients labeled churn or not. ...
11052803980527077c79307fbc4ade927b579fa9
45,664
def _node(visuals, args, kwargs, level=0): """Recursive part of recursive Panel constructions""" B, K = _broadcast(visuals, args, kwargs) mk = _leaf if len(B) == 1 and Visual.isvisualable(B[0][0]) else _node # recursion N, L = zip(*(mk(p, a, k, level+1) for p, a, k in B)) if level+1 < max(L)-1: ...
e67d38327db993e7f37bcd5637eb57cc73cf3964
45,665
def best_solution_program(bundle: SpendBundle) -> SerializedProgram: """ This could potentially do a lot of clever and complicated compression optimizations in conjunction with choosing the set of SpendBundles to include. For now, we just quote the solutions we know. """ r = [] for coin_sol...
4a4db3e2aca61e77d6eda7620286f108014968a6
45,666
def os_aware(data: dict) -> dict: """ Makes data OS aware by changing all separators in file paths to match the current operating system. :param data: JSON data. :return: OS aware JSON data. """ for key, val in data.items(): if isinstance(val, dict): data[key] = os_aware(val...
6e8d5a0b26a2721442a4850d757867969be6641e
45,667
def mock_engine_port(sim_def, attr_ref, attr_val): """Mock Engine gRPC server fixture that handles test requests""" # define servicer that handles requests class TestEngine(EngineServiceServicer): def GetVersion(self, request, context): return GetVersionResp(commit_hash="HASH12") ...
c2392326d1d5a1629dc59c3d305d8bdd68394631
45,668
def parseX(sol, *args): """Parse a sol into plotable piece""" tX = np.reshape(sol[:25*4], (25, 4)) tU = np.reshape(sol[100: 100 + 2*24], (24, 2)) tf = sol[-1] return tX, tU, tf
b17f7cb4168bf0b0f3777997994d151adac3cb05
45,669
def MatchingFileType(file_name, extensions): """Returns true if the file name ends with one of the given extensions.""" return bool([ext for ext in extensions if file_name.lower().endswith(ext)])
5fe5121d270cdfc13f6f9f3c72471fc3572b0efe
45,670
import os def process_data(path_to_folder, class_index): """process_data processes all data in a file and resizes it to IMG_WIDTH and IMG_HEIGHT and returns a list of all images in the given folder Args: path_to_folder (str) : absolute path to the folder that contains all the images with backslash at the...
43443236d05d9e7ef2a8db8f7891902da25f5dc7
45,671
def get_connection_mask(a): """ Given a subset mask, return the appropriate vispy.Line connection array for the subset. Only the points in the subset are plotted, so return an array where each group of connected points in the array is terminated by a FALSE """ new_mask = [] for k,g ...
de4400a35f6a496c3629aad99022f5339c8d722f
45,672
def escape_path(value: bytes) -> str: """ Take a binary path value, and return a printable string, with special characters escaped. """ def human_readable_byte(b: int) -> str: if b < 0x20 or b >= 0x7F: return "\\x{:02x}".format(b) elif b == ord(b"\\"): return...
07a0c28cd531d8e3bd4330afe1d4d51265cd80c4
45,673
from typing import Any from typing import AnyStr from typing import Union def fdumpit(object_: Any, view_: AnyStr = 'vertical', colors: Union[bool, str] = False, all_: bool = True) -> AnyStr: """ Export object to string. :param object_: Any kind of python object. :...
07fa2eaf3f7b2c98cf23a3d492224109eb52acce
45,674
def opval_ADO(key, value): """A helper function for parse_branch.""" operation, value = value return "[%s] %s %s" % (key, cmpcasts_ADO[operation], quoted_field(value))
e1e4533e4f864574d1b0d48062b2ecd486e56d4a
45,675
import types def graphMethod(funcOrFlags=0, delegateTo=None): """Declare a GraphObject method as on-graph. Use as a decorator, for example: class Example(GraphObject): @graphMethod def X(self): return self.Y() @graphMethod(Settable) d...
11161f282097711c0f2edf400375baebb03ca939
45,676
from typing import Union from typing import Dict import os import yaml def get_config(key: str = "", fallback: Union[str, Dict] = None, envvar_prefix: str = "DOING_CONFIG_"): """ Finds and reads doing configuration file. Note you can overwrite a value in the config by setting an environment variable: ...
58ed28cc9efb8f8362f1ac02eb51161d641ba48b
45,677
def get_data(filters: typing.List[dict], threads=1, async=False, processor: typing.Callable = None): """ Get async data for a list of filters. Works only for the historical API :param filters: a list of filters :param threads: number of threads for data retrieval :param async: if True, return queue....
d2143195c42833c2faedb66dd8030137dc41234b
45,678
def get_row_col_matrix(row_index_set, col_index_set): """ Returns the resulting matrix when using a row and column of indices (list of tuples) row_index_set: the index set that would be taken from wells A-H (or equivalent) on that plate. Should be dim 8 or 16. col_index_set: the index set that would be ...
c16deb6d31ed3203cec9b17d0a68f9e45dee8871
45,679
def on_exam_finish(s): """ This method finishes exam when either time is up or educator requests so. :param s: It is for handling class structure. :return: """ def on_exam_finish_confirm(self, dt): """ This method changes exam's status to finished through server. :param ...
ef7b292b9e78b093cef084577299ac37102b1ba7
45,680
def temporal_centroid(alpha, bin_freqs): """Spectral centroid of the temporal spectrum. Calculated as the weighted average of analysis bin magnitudes. Note, temporal centroid depends on the spec frequency bins/scale (as well as the choice of `aggr_func` if custom spec is used). That is, temporal centr...
e9a1c263dacead40857fac442f0964aae59103ef
45,681
import warnings def _obtain_input_shape( input_shape, default_size, min_size, data_format, require_flatten): """Internal utility to compute/validate an ImageNet model's input shape. Args: input_shape: either None (will return the default network input shape), or a user-provide...
7183f9d96711f83fb94c9233ec1466f32ee82910
45,682
def get_auction_lores(auctions): """return lore for each auction, use asyncio.to_thread for this""" return [get_safe_content(i["item_lore"]) for i in auctions]
c4920ef5b8c617e83a393270c4f7343a15366227
45,683
import requests def create_update_dashboard(orgname=None, profile="grafana", **kwargs): """ Create or update a dashboard. dashboard A dict that defines the dashboard to create/update. overwrite Whether the dashboard should be overwritten if already existing. orgname Name...
c8cdc33d8e00dbf1f1bb72d08dc64c686c1fc7e7
45,684
def raw_reward_threshold(threshold): """Return a reward processor that cut off at a threshold.""" def fn(metadata): if metadata['raw_reward'] > threshold: return 1. elif metadata['raw_reward'] > 0: return -1 return metadata['raw_reward'] return fn
1efbd90c352d99c6e65b05214d8ccb82bb155606
45,685
def O2_conv(S, T, P, O2conc): """sal, temp, press, oxy conc""" sigmatheta_pri = sw.eos80.dens(s=S, t=T, p=P) density = sigmatheta_pri / 1000 O2conc = O2conc / density return O2conc
b3d72bde77d8b9125d29c2d6a7fd74c0886b6b19
45,686
def parse_input(input_): """Convert the puzzle input in a list of "Line" objects.""" lines = [] for l in input_.splitlines(): tokens = l.split('->') startpos, endpos = tokens[0], tokens[1] startpos = startpos.split(',') x1 = int(startpos[0]) y1 = int(startpos[1]) ...
50b6522991fe3a480de7983b33b1f34b82b775b9
45,687
import re import logging def ShortSetNames(set_names_nparray, dbg_lvl=0): """ Using a table with rules, shorten the names of these sets Args: set_names_nparray (numpy.ndarray): Array of string, unique set names from exps file Returns: set_names_nparray (numpy.ndarray): Edited set Names to...
b50c2ce2ce9900b647c646a0cdc56ea963b852db
45,688
import tqdm def generate_box(anchors, color = [], rotate = False): """ input: Anchor (n, 7) color: if true then the generated box will display red, otherwise black """ anchor_boxes = [] for anchor in tqdm(anchors): anchor[3:-1] = np.array([anchor[4],anchor[3],anchor[5]]) bo...
9cf3315dbc500f2a8dc8d7dfebd12b5b79440709
45,689
from pathlib import Path import dill import tqdm def load_xps(save_as): """Load `xps` (as a `list`) from given dir.""" save_as = Path(save_as).expanduser() files = [d / "xp" for d in uplink.list_job_dirs(save_as)] if not files: raise FileNotFoundError(f"No results found at {save_as}.") de...
3d43d9b8516e838dc135cd725e95ea489f24852b
45,690
import logging def process_target_counters(): """ This function extracts the target counters and converts them to the appropriate format using the convert_target_counters function. It then converts the "object" dtype records of the output dataframe (df2) to "numeric" dtype in order for the df2 to hav...
e1b8185fa0131176264e47438b70179e36264fdc
45,691
import re def read_ID_and_GO_multiCols(file_name, name_col, GO_col, header_rows = 0, split_char = "\t"): """ This opens the file and read GO classes and Gene Identifier Everything is stored as a dict that has Gene ID as key GO classes are as a list (or array, how is it called...) ...
dabcdacc3a881f6ab952d60a81fe590d0541eb02
45,692
def build_pruned_tree(tree, cases): """ Build new tree with only the specifiied cases Parameters ---------- tree : List[...] the sidebar tree cases : List[int] the cases to keep Returns ------- tree_final : List[...] the updated sidebar tree Examples ...
78b10b1a3149d712312d3610268a3401c3a14400
45,693
import warnings def filter_median(im, filter_size): """ Abstracted media filter function that catches warnings about image type conversion (float to uint8) Args: im (ndarray): image filter_size (int): size of disk filter Returns: uint8 ndarray: filtered image """ with warnings.catch_warning...
31aeeb5a22f4e10efbea17e14c65883b715535ba
45,694
def comp_profit_inc_div_drp(price, price_bought_list, vol_list, DRP_list, admin_fee_list, div): """ return current market value - total cost of buying this stock, after deduct admin fees, with DRP and div """ vol_DRP_list = [i[0] + i[1] for i in zip(vol_list, DRP_list)] return comp_market_value(pric...
cb04957a84126542a4484badfccb2cac11d7d4e0
45,695
def get_migration_table(environment, Base): """Get the migration table for a given environment.""" class MigrationTable(Base): __tablename__ = "migrations_{}".format(environment) id = Column(String(100), primary_key=True) commit_time = Column( TIMESTAMP, onupdate...
8b66abd329ce36fe44e3d530716d3f5235e6169f
45,696
import math def get_rotation(box): """Return the rotation of a rectangle contour based on the slope of one of its long side.""" x1 = 0 x2 = 0 # Take the first three vertices and calculate side lengths of the right angle triangle they form d1 = math.sqrt(pow((box[0][0]-box[1][0]),2)+pow((...
1ed79ef8ee62a8ecf77dda6e0c7d6b6e97942937
45,697
def resample_with_sepconv(feat, target_width, target_num_filters, use_native_resize_op=False, batch_norm_activation=nn_ops.BatchNormActivation(), data_format='channels_last', ...
06399c031f2e5dd82cfde870145015827b97bf09
45,698
def authenticate(): """Authenticate user. Since this goes via modifying the app, undo modifications afterwards. """ async def logged_in_user(token=None): # pylint: disable=unused-argument """Fake active user.""" return UserInDB(**config.fake_users_db["johndoe@example.com"]) app.d...
c24d0fdd7de27f4f7d20f49715577cfaf4dcec9d
45,699