content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_graph_names(test_dir): """Parse test_dir/*GRAPHFILES and return basenames for all .graph files""" graph_list = [] GRAPHFILES_files = [f for f in os.listdir(test_dir) if f.endswith("GRAPHFILES")] for GRAPHFILE in GRAPHFILES_files: with open(os.path.join(test_dir, GRAPHFILE), '...
b60f6e5a1b3654e6e7a982902356c18db0e740ae
3,650,500
import logging def get_sagemaker_feature_group(feature_group_name: str): """Used to check if there is an existing feature group with a given feature_group_name.""" try: return sagemaker_client().describe_feature_group(FeatureGroupName=feature_group_name) except botocore.exceptions.ClientError as e...
1e94e894b1686a6833df51f1006f3f845a9e63b4
3,650,501
def check_system(command, message, exit=0, user=None, stdin=None, shell=False, timeout=None, timeout_signal='TERM'): """Runs the command and checks its exit status code. Handles all of the common steps associated with running a system command: runs the command, checks its exit status code against the expec...
31d83941d5198d0786a6a67a4b1bcd320c26218a
3,650,502
import requests import json import pandas as pd from common_functions import read_orgs import sys def get_repo_data(api_token): """Executes the GraphQL query to get repository data from one or more GitHub orgs. Parameters ---------- api_token : str The GH API token retrieved from the gh_key f...
0fcb024aa2f68d6687aebbce93f7ea5a0004afa5
3,650,503
import json def getJson(file, filters={}): """Given a specific JSON file (string) and a set of filters (dictionary key-values pairs), will return a JSON-formatted tree of the matching data entries from that file (starting as a null-key list of objects). """ with open(file, 'r') as f: j = json.loads(f.rea...
7b6832eae476eef48584690d993c2dee301bb565
3,650,504
def underline_node_formatter(nodetext, optionstext, caller=None): """ Draws a node with underlines '_____' around it. """ nodetext_width_max = max(m_len(line) for line in nodetext.split("\n")) options_width_max = max(m_len(line) for line in optionstext.split("\n")) total_width = max(options_widt...
598e3aaf875b2539b93ec03d8665cc8011872015
3,650,505
from pywps.dependencies import ogr import jsonschema import json import mimetypes import os def validategeojson(data_input, mode): """GeoJSON validation example >>> import StringIO >>> class FakeInput(object): ... json = open('point.geojson','w') ... json.write('''{"type":"Feature", "prop...
5b9364ecc0c8f92f82448bd5541eb606df776c12
3,650,506
def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes): """ Create the layers for a fully convolutional network. Build skip-layers using the vgg layers. :param vgg_layer3_out: TF Tensor for VGG Layer 3 output :param vgg_layer4_out: TF Tensor for VGG Layer 4 output :param vgg_layer7...
cf907d29555fbb7e9a11a1b2f6981637a977bf48
3,650,507
def determine_issues(project): """ Get the list of issues of a project. :rtype: list """ issues = project["Issue"] if not isinstance(issues, list): return [issues] return issues
7b8b670e4ad5a7ae49f3541c87026dd603406c9f
3,650,508
import os def find_image_files(path=None): """ Used to find image files. Argument: path - path to directory of 'img.image' files """ if path is None: path = os.getcwd() folders = [] for folder in os.listdir(path): if folder.endswith("img.image"): folders.append(os.pa...
f6813672c1619204caa45d21df47289227ab4d5f
3,650,509
def get_media_after_date(mountpoint: str, date:str): """ Date format in EXIF yyyy:mm:dd, look for EXIF:CreateDate """ metadata = get_media_list(mountpoint) filtered_meta = list() for m in metadata: if 'File:FileModifyDate' in m: if is_after(m['File:FileModifyDate'].split(' ')...
950c937540bd44cd1f577f1ee763262dad51d353
3,650,510
import random def run_normal_game(): """Run a complex game, like the real thing.""" stage = create_stage() contestant_first_pick = random.randrange(3) montys_pick_algorithm(stage, contestant_first_pick) contestant_second_pick = contestants_second_pick_algorithm(stage, contestant_first_pick) ...
04f3e8805b3b7d7d9e9f631eee635c4b9af75fdf
3,650,511
def reformat_wolfram_entries(titles, entries): """Reformat Wolfram entries.""" output_list = [] for title, entry in zip(titles, entries): try: if ' |' in entry: entry = '\n\t{0}'.format(entry.replace(' |', ':') .replace('\n', '\n\t...
ba236671187ba4ab80fb013b3ee40c6ae58cc1c8
3,650,512
import os def project_root() -> str: """Returns path to root directory of a project""" return os.path.join(_file_directory_path(__file__), '..')
175090bf05b5bc79f78e8fbbbb491d62696e8d35
3,650,513
import six def GetAndValidateRowId(row_dict): """Returns the integer ID for a new Row. This method is also responsible for validating the input fields related to making the new row ID. Args: row_dict: A dictionary obtained from the input JSON. Returns: An integer row ID. Raises: BadRequest...
be9f096ddb8bba036d1fa06cdd3565296a949762
3,650,514
def generate_test_cases(ukernel, channel_tile, pixel_tile, isa): """Generates all tests cases for a BILINEAR micro-kernel. Args: ukernel: C name of the micro-kernel function. channel_tile: Number of channels processed per one iteration of the inner loop of the micro-kernel. pixel_tile...
4fe3243c3f8d2ab3ce7861b46aa96ee79ef1014a
3,650,515
def get_file_range(ase, offsets, timeout=None): # type: (blobxfer.models.azure.StorageEntity, # blobxfer.models.download.Offsets, int) -> bytes """Retrieve file range :param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity :param blobxfer.models.download.Offsets offsets: download ...
be4f2f06c64ee457152fe582128b36db1a1baae4
3,650,516
def parse_cli_args(): """Return parsed command-line arguments.""" parser = ArgumentParser(description='parse and summarize a GLSL file') parser.add_argument('path') shader_type_names = [member.name for member in ShaderType] parser.add_argument('shader_type', nargs='?', choice...
a044e20ea91e05c09cccc118641dac68ce748142
3,650,517
def genus_species_name(genus, species): """Return name, genus with species if present. Copes with species being None (or empty string). """ # This is a simple function, centralising it for consistency assert genus and genus == genus.strip(), repr(genus) if species: assert species == spe...
1fed57c5c87dfd9362262a69429830c7103b7fca
3,650,518
def _native_set_to_python_list(typ, payload, c): """ Create a Python list from a native set's items. """ nitems = payload.used listobj = c.pyapi.list_new(nitems) ok = cgutils.is_not_null(c.builder, listobj) with c.builder.if_then(ok, likely=True): index = cgutils.alloca_once_value(c....
808a10d85cc19c0b1c31b3e01afc9bbb402e1e90
3,650,519
def JointAngleCalc(frame,vsk): """ Joint Angle Calculation function. Calculates the Joint angles of plugingait and stores the data in array Stores: RPel_angle = [] LPel_angle = [] RHip_angle = [] LHip_angle = [] RKnee_angle = [] LKnee_angle = [] RAnkle_angle = [] LAnkle_angl...
0b3c7df9e514a1a08f23d487f909952df9a168b5
3,650,520
def var_to_str(var): """Returns a string representation of the variable of a Jax expression.""" if isinstance(var, jax.core.Literal): return str(var) elif isinstance(var, jax.core.UnitVar): return "*" elif not isinstance(var, jax.core.Var): raise ValueError(f"Idk what to do with this {type(var)}?") ...
820645057359f8704cbd28d2545b9bb3c6e2f4d3
3,650,521
def lal_binary_neutron_star( frequency_array, mass_1, mass_2, luminosity_distance, a_1, tilt_1, phi_12, a_2, tilt_2, phi_jl, theta_jn, phase, lambda_1, lambda_2, **kwargs): """ A Binary Neutron Star waveform model using lalsimulation Parameters ---------- frequency_array: array_...
4641e65e9f422bb9be9a90f2f849ab58f1cdea51
3,650,522
def handledisc(tree): """Binarize discontinuous substitution sites. >>> print(handledisc(Tree('(S (X 0 2 4))'))) (S (X 0 (X|<> 2 (X|<> 4)))) >>> print(handledisc(Tree('(S (X 0 2))'))) (S (X 0 (X|<> 2))) """ for a in tree.postorder(lambda n: len(n) > 1 and isinstance(n[0], int)): binarize(a, rightmostunary=Tru...
1e164d0174a4b31462369a10e56f9d69d936d18b
3,650,523
def check_bounds(shape: Shape, point: Coord) -> bool: """Return ``True`` if ``point`` is valid index in ``shape``. Args: shape: Shape of two-dimensional array. point: Two-dimensional coordinate. Return: True if ``point`` is within ``shape`` else ``False``. """ return (0 <...
88ab89fddf3f85fc38f3404ed90f384f50337905
3,650,524
def logout(home=None): """ Logs out current session and redirects to home :param str home: URL to redirect to after logout success """ flask_login.logout_user() return redirect(request.args.get('redirect', home or url_for('public.home')))
bded682e6807532aa6382ea0855ee4d335da550f
3,650,525
def N(u,i,p,knots): """ u: point for which a spline should be evaluated i: spline knot p: spline order knots: all knots Evaluates the spline basis of order p defined by knots at knot i and point u. """ if p == 0: if knots[int(i)] < u and u <=knots[int(i+1)]: retu...
0cd0756d558ee99b0ed32350860bc27f023fa88b
3,650,526
import tqdm import scipy def infer_growth_rate(data, od_bounds=None, convert_time=True, groupby=None, cols={'time':'clock_time', 'od':'od_600nm'}, return_opts=True, print_params=True...
cef58ddc864bc683708170289439c318363b6561
3,650,527
def check_merge(s, idn) -> bool: """ Check whether a set of nodes is valid to merge """ found = False in_size = None out_size = None stride = None act = None nds = [idn[i] for i in state2iset(s)] if len(nds) == 1: return True for nd in nds: if not isinstance(n...
d0edfee6150d7814c926fb59d413b61a989c9808
3,650,528
def typeMap(name, package=None): """ typeMap(name: str) -> Module Convert from C/C++ types into VisTrails Module type """ if package is None: package = identifier if isinstance(name, tuple): return [typeMap(x, package) for x in name] if name in typeMapDict: return ty...
6f8ed31cfe1eb88201d0131d43c0fb0da2295405
3,650,529
def _rm_from_diclist(diclist, key_to_check, value_to_check): """Function that removes an entry form a list of dictionaries if a key of an entry matches a given value. If no value of the key_to_check matches the value_to_check for all of the entries in the diclist, the same diclist will be returned that ...
89806ec5029923709bd44d794d75a84f440c5aa7
3,650,530
import scipy def odr_linear(x, y, intercept=None, beta0=None): """ Performs orthogonal linear regression on x, y data. Parameters ---------- x: array_like x-data, 1D array. Must be the same lengths as `y`. y: array_like y-data, 1D array. Must be the same lengths as `x`. ...
51fc464cb60e5b05645907d5ed3ec40d1b9cdb54
3,650,531
def get_centroid_world_coordinates(geo_trans, raster_x_size, raster_y_size, x_pixel_size, y_pixel_size): """Return the raster centroid in world coordinates :param geo_trans: geo transformation :type geo_trans: tuple with six values :param raster_x_size: number of columns :type raster_x_size: int ...
e0dd1d57cb020a85d9784f2c9bf22b4b8035ffae
3,650,532
import json def save_change_item(request): """ 保存改变项 算法:在rquest_list中查找对应的uuid,找到后将数据更新其中 :param request: :return: """ if request.method != 'POST': return HttpResponse("数据异常.") str_data = request.POST.get('jsons') logger.info("change_item: " + str_data) jsons = json.lo...
434bd1e77690cd60dd163a39fd1cb90dd0cb4952
3,650,533
import pytdx.hq import pytdx.util.best_ip def get_lastest_stocklist(): """ 使用pytdx从网络获取最新券商列表 :return:DF格式,股票清单 """ print(f"优选通达信行情服务器 也可直接更改为优选好的 {{'ip': '123.125.108.24', 'port': 7709}}") # ipinfo = pytdx.util.best_ip.select_best_ip() api = pytdx.hq.TdxHq_API() # with api.connect(ipi...
2953cbd800ad2e2b6bc6122ec225f34d165773ea
3,650,534
from datetime import datetime def grpc_detect_ledger_id(connection: "GRPCv1Connection") -> str: """ Return the ledger ID from the remote server when it becomes available. This method blocks until a ledger ID has been successfully retrieved, or the timeout is reached (in which case an exception is thro...
a60b84db2b8274d71b601920eb8325123191109b
3,650,535
import logging def cross_mcs(input_vectors, value_fields, verbose=False, logger=None): """ Compute map comparison statistics between input vector features. MCS (Map Comparison Statistic) indicates the average difference between any pair of feature polygon values, expressed as a fraction of the highest ...
cc10bb30489c13a2ce0243e1f7ab13037aa23986
3,650,536
def extrapolate_trace(traces_in, spec_min_max_in, fit_frac=0.2, npoly=1, method='poly'): """ Extrapolates trace to fill in pixels that lie outside of the range spec_min, spec_max). This routine is useful for echelle spectrographs where the orders are shorter than the image by a signfiicant amount, since...
d2da076badb70147fd124bbf8ceaba24f26d4c0f
3,650,537
def getStopWords(stopWordFileName): """Reads stop-words text file which is assumed to have one word per line. Returns stopWordDict. """ stopWordDict = {} stopWordFile = open(stopWordFileName, 'r') for line in stopWordFile: word = line.strip().lower() stopWordDict[word] = None...
8bb85683f257c35de9d04e4993b42cd758a802e6
3,650,538
def metade(valor): """ -> Realiza o calculo de metade salárial :param valor: Valor do dinheiro :param view: Visualizar ou não retorno formatado :return: Retorna a metade do valor """ if not view: return moeda(valor / 2) else: return valor / 2 return valor / 2
fb1bbb605b8a0f1b8623ca70940377bd3c6a440a
3,650,539
def monopole(uvecs: [float, np.ndarray], order: int=3) -> [float, np.ndarray]: """ Solution for I(r) = 1. Also handles nonzero-w case. Parameters ---------- uvecs: float or ndarray of float The cartesian baselines in units of wavelengths. If a float, assumed to be the magnitude of ...
6828b4014fc7970a4d85b6d04b6d3e16249d3dae
3,650,540
def get_question( numbers: OneOrManyOf(NUMBERS_AVAILABLE), cases: OneOrManyOf(CASES_AVAILABLE), num: hug.types.in_range(1, MAX_NUM + 1) = 10): """When queried for one or multiple numbers and cases, this endpoint returns a random question.""" questions = [] bag = NounCaseQuestionBag( no...
b32d76f6ee7519935292743f6d7d8b8ad7357d3a
3,650,541
from textwrap import dedent def _print_attrs(attr, html=False): """ Given a Attr class will print out each registered attribute. Parameters ---------- attr : `sunpy.net.attr.Attr` The attr class/type to print for. html : bool Will return a html table instead. Returns ...
5044764b8799eed66d3e11fe9423922d79fd9981
3,650,542
import struct def create_wave_header(samplerate=44100, channels=2, bitspersample=16, duration=3600): """Generate a wave header from given params.""" # pylint: disable=no-member file = BytesIO() numsamples = samplerate * duration # Generate format chunk format_chunk_spec = b"<4sLHHLLHH" fo...
b0b53b33733e5456e321cd7c276ad95754140f8a
3,650,543
import unicodedata import re def xslugify(value): """ Converts to ASCII. Converts spaces to hyphens. Removes characters that aren't alphanumerics, underscores, slash, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace. (I.e., does the same as slugify, but also converts...
7a8a3f00011a46465ccafdcaf1ac797577511b2b
3,650,544
def firstcond(list1, list2): """this is a fixture for testing conditions when the list is a four node list """ ll = LinkedList() ll.insert(1, 5) ll.insert(3, 9) ll.insert(2, 4) return ll
6e50038285e84e986304de5d2b28bef0db32b63d
3,650,545
import os def read_bert_vocab(bert_model_path): """读取bert词典""" dict_path = os.path.join(bert_model_path, 'vocab.txt') token2idx = {} with open(dict_path, 'r', encoding='utf-8') as f: tokens = f.read().splitlines() for word in tokens: token2idx[word] = len(token2idx) return toke...
f38c82a1a2b8f69b6c10e8d0bfcf8bdf4f63e123
3,650,546
import textwrap def _template_message(desc, descriptor_registry): # type: (Descriptor, DescriptorRegistry) -> str """ Returns cls_def string, list of fields, list of repeated fields """ this_file = desc.file desc = SimpleDescriptor(desc) if desc.full_name in WKTBASES: desc.bases.ap...
d56f79317d4599db2f722f9a665eb912a60aa5b8
3,650,547
def random_portfolio(n, k, mu=0., sd=0.01, corr=None, dt=1., nan_pct=0.): """ Generate asset prices assuming multivariate geometric Brownian motion. :param n: Number of time steps. :param k: Number of assets. :param mu: Drift parameter. Can be scalar or vector. Default is 0. :param sd: Volatility o...
86801609a44619565188cd58b1d519c2e326086b
3,650,548
import time def vulnerabilities_for_image(image_obj): """ Return the list of vulnerabilities for the specified image id by recalculating the matches for the image. Ignores any persisted matches. Query only, does not update the data. Caller must add returned results to a db session and commit in order ...
3017ebfdeb2965760df7bb4db426fea175a3bf39
3,650,549
def superpose_images(obj, metadata, skip_overlaps=False, num_frames_for_bkgd=100, every=1, color_objs=False, disp_R=False, b=1.7, d=2, false_color=False, cmap='jet', remove_positive_noise=True): """ Superposes images of an object onto one frame. ...
10767c9d10e5d32af51a31f1f8eb85d8989bb5d4
3,650,550
def gen_s_linear(computed_data, param ): """Generate sensitivity matrix for wavelength dependent sensitivity modeled as line""" mat=np.zeros((computed_data.shape[0],computed_data.shape[0])) #print(mat.shape) for i in range(computed_data.shape[0]): for j in range(computed_data.shape[0]): ...
c18c31e65804d65ac7419a2037f889a0f9de2f96
3,650,551
import numpy def upsample2(x): """ Up-sample a 2D array by a factor of 2 by interpolation. Result is scaled by a factor of 4. """ n = [x.shape[0] * 2 - 1, x.shape[1] * 2 - 1] + list(x.shape[2:]) y = numpy.empty(n, x.dtype) y[0::2, 0::2] = 4 * x y[0::2, 1::2] = 2 * (x[:, :-1] + x[:, 1:]...
4eb23d668154ac12755c0e65eeff485ac5e5dd23
3,650,552
import six def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate. Can be called multiple times on a single string. """ if isinstance(s, SafeData): return s if isinstan...
dab8c0dfb78fd22fb35b5abc3680f74de8a1089a
3,650,553
def _unravel_plug(node, attr): """Convert Maya node/attribute combination into an MPlug. Note: Tries to break up a parent attribute into its child attributes: .t -> [tx, ty, tz] Args: node (str): Name of the Maya node attr (str): Name of the attribute on the Maya node ...
6513af00896a19e316e55beb5424fc15b2748b55
3,650,554
def index(): """ Root URL response """ return jsonify(name='Payment Demo REST API Service', version='1.0'), status.HTTP_200_OK
2d370a9fdf1878f60af6de264d99193d06ff96d2
3,650,555
def unvoigt(A): """ Converts from 6x1 to 3x3 :param A: 6x1 Voigt vector (strain or stress) :return: 3x3 symmetric tensor (strain or stress) """ a=np.zeros(shape=(3,3)) a[0,0]=A[0] a[0,1]=A[5] a[0,2]=A[4] a[1,0]=A[5] a[1,1]=A[1] a[1,2]=A[3] a[2,0]=A[4] a[2,1]=A[3] a[2,2]=A[2] return (a)
72b28fceedb5ae2d34c768d5c29b5924310ff2b3
3,650,556
import argparse def get_parser(): """ Creates a new argument parser. """ parser = argparse.ArgumentParser('niget_yyyymm.py', formatter_class=argparse.RawDescriptionHelpFormatter, description=""" help description """ ) version = '%(prog)s ' + __version__ parser.add_argument('--version', '-v', action='v...
27be28a2a1e2d6a90a4485d27c22ce33998886c6
3,650,557
def _calculate_rmsd(P, Q): """Calculates the root-mean-square distance between the points of P and Q. The distance is taken as the minimum over all possible matchings. It is zero if P and Q are identical and non-zero if not. """ distance_matrix = cdist(P, Q, metric='sqeuclidean') matching = lin...
22261e75edf3edf378fa30daa5c33abc68ff93cd
3,650,558
def initialize_parameters(): """ Initializes weight parameters to build a neural network with tensorflow. The shapes are: W1 : [4, 4, 3, 8] W2 : [2, 2, 8, 16] Note that we will hard code the shape values in the function to make the grading simpler. Normall...
43481172a70ea88bcf5cfbc95792365c5af2ea52
3,650,559
import time import random import string import hashlib def generate_dynamic_secret(salt: str) -> str: """Creates a new overseas dynamic secret :param salt: A ds salt """ t = int(time.time()) r = "".join(random.choices(string.ascii_letters, k=6)) h = hashlib.md5(f"salt={salt}&t={t}&r={r}".enco...
2a9bdf00daea91f13f34724d1c744c17e9b4d6cf
3,650,560
import os import shutil def upload(slot_id): """ Upload a file """ form = request.form # Is the upload using Ajax, or a direct POST by the form? is_ajax = False if form.get("__ajax", None) == "true": is_ajax = True # Target folder for these uploads. target = os.path.join(...
c0a67ed62c581cbe8fdb644f5240d7c3d0bf2016
3,650,561
def is_sim_f(ts_kname): """ Returns True if the TSDist is actually a similarity and not a distance """ return ts_kname in ('linear_allpairs', 'linear_crosscor', 'cross_correlation', 'hsdotprod_autocor_truncated', ...
11c18983d8d411714ba3147d4734ad77c40ceedf
3,650,562
import pika from typing import Union def initialise_pika_connection( host: Text, username: Text, password: Text, port: Union[Text, int] = 5672, connection_attempts: int = 20, retry_delay_in_seconds: float = 5, ) -> "BlockingConnection": """Create a Pika `BlockingConnection`. Args: ...
7364547a4836aea0b277098bed75b8c5ec874522
3,650,563
def units(arg_name, unit): """Decorator to define units for an input. Associates a unit of measurement with an input. Parameters ---------- arg_name : str Name of the input to attach a unit to. unit : str Unit of measurement descriptor to use (e.g. "mm"). Example -----...
45bd1695cada5612e2ce9e39632ed1357556535f
3,650,564
from typing import Callable async def to_thread_task(func: Callable, *args, **kwargs) -> Task: """Assign task to thread""" coro = to_thread(func, *args, **kwargs) return create_task(coro)
ad666a91588a670be7babf84294f338f0148b8e1
3,650,565
import logging import sys def setup_logging(stream_or_file=None, debug=False, name=None): """ Create a logger for communicating with the user or writing to log files. By default, creates a root logger that prints to stdout. :param stream_or_file: The destination of the log messages. If None, ...
95f31df5f468261d0d0a0b85c8ffc8b6c5b7d1b7
3,650,566
from typing import Dict from typing import Any from typing import Optional from typing import Union from pathlib import Path def combo2fname( combo: Dict[str, Any], folder: Optional[Union[str, Path]] = None, ext: Optional[str] = ".pickle", sig_figs: int = 8, ) -> str: """Converts a dict into a hum...
9951171647167e39753546645f8e1f185d9fa55a
3,650,567
def cls_from_str(name_str): """ Gets class of unit type from a string Helper function for end-users entering the name of a unit type and retrieving the class that contains stats for that unit type. Args: name_str: str Returns: UnitStats """ name_str = name_str.l...
4dc26f8586065319a25f8965a5267308bd8dbfea
3,650,568
def convert_to_github_url_with_token(url, token): """ Convert a Github URL to a git+https url that identifies via an Oauth token. This allows for installation of private packages. :param url: The url to convert into a Github access token oauth url. :param token: The Github access token to use for th...
9b9c5e17cb389eb938af1221518a6838e65712bc
3,650,569
from datetime import datetime import numpy def get_numbers_of_papers(metrics): """ Convert the metrics into a format that is easier to work with. Year-ordered numpy arrays. """ publications = metrics['histograms']['publications'] year, total, year_refereed, refereed = [], [], [], [] y = l...
ce8b079ea416ff01b4974ea7ae7aa82080321cbb
3,650,570
import json from typing import Dict def test_base_provider_get_transform_json_exception(mock_name, mock_value): """ Test BaseProvider.get() with a json transform that raises an exception """ mock_data = json.dumps({mock_name: mock_value}) + "{" class TestProvider(BaseProvider): def _get(...
abb81b142a34f264466b808867bc3a7cc4460fcf
3,650,571
def load_check_definitions(lang): """ Retrieve Trust Advisor check definitions """ retval = {} resp = TA_C.describe_trusted_advisor_checks(language=lang) if resp: try: checks = resp['checks'] retval = {a['id']:a for a in checks} except ValueError: ...
43bca091506d33270a7e0fa3ec6ca84e4c342bf6
3,650,572
def filter_phrase(comments, phrase): """Returns list of comments and replies filtered by substring.""" results = [] for comment in comments: if phrase.lower() in comment.message.lower(): results.append(comment) for reply in comment.replies: if phrase.lower() in reply....
0865163f117550e36b2c21608739649b7b99f825
3,650,573
def asses_completeness(language_code: str, sw: ServiceWorker = Depends(get_sw)): """ make a completion test for language: check fe,be, domains and entries @param language_code: @param sw: @return: """ if language_code not in sw.messages.get_added_languages(): raise ApplicationExcepti...
9de6a9130ec34e47782679ac63d80707de5b98ce
3,650,574
def create_intrinsic_node_class(cls): """ Create dynamic sub class """ class intrinsic_class(cls): """Node class created based on the input class""" def is_valid(self): raise TemplateAttributeError('intrisnic class shouldn\'t be directly used') intrinsic_class.__name__ =...
ddcb0ba5f36981288fd9748f1f533f02f1eb1604
3,650,575
import os def load(provider, config_location=DEFAULT_CONFIG_DIR): """Load provider specific auth info from file """ auth = None auth_file = None try: config_dir = os.path.join(config_location, NOIPY_CONFIG) print("Loading stored auth info [%s]... " % config_dir, end="") auth_f...
b9dfb27bcef9216ff5fddd94decbd6bf3b9dc297
3,650,576
def segment_fish(image): """Attempts to segment the clown fish out of the provided image.""" hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) light_orange = (1, 190, 200) dark_orange = (18, 255, 255) mask = cv2.inRange(hsv_image, light_orange, dark_orange) light_white = (0, 0, 200) dark_wh...
c9ee166f12e9c344143f677939a82dd1a00a5fb5
3,650,577
def get_bugzilla_url(bug_id): """Return bugzilla url for bug_id.""" return u'https://bugzilla.mozilla.org/show_bug.cgi?id=%d' % bug_id
051f37ab1eeb096d353317bfd9514b30d13ddd8a
3,650,578
def enable_faster_encoder(self, need_build=True, use_fp16=False): """ Compiles fusion encoder operator intergrated FasterTransformer using the method of JIT(Just-In-Time) and replaces the `forward` function of `paddle.nn.TransformerEncoder` and `paddle.nn.TransformerEncoderLayer` objects inherited f...
4da1f669cefd291df4bc790dfc68fcbe5ce93f86
3,650,579
def func(*x): """ Compute the function to minimise. Vector reshaped for more readability. """ res = 0 x = np.array(x) x = x.reshape((n, 2)) for i in range(n): for j in range(i+1, n): (x1, y1), (x2, y2) = x[i, :], x[j, :] delta = (x2 - x1)**2 + (y2 - y1)**2 - ...
775d4330ca77e04662f1920dd2160631deb30430
3,650,580
import torch def transform_target(target, classes=None): """ Accepts target value either single dimensional torch.Tensor or (int, float) :param target: :param classes: :return: """ if isinstance(target, torch.Tensor): if target.ndim == 1: target = target.item() if tar...
5e1423b4beac4385fa4f328bfdfeed2859c28f7b
3,650,581
from typing import List from typing import Tuple def merge_all_regions(out_path: str, id_regions: List[Tuple[int, File]]) -> Tuple[int, int, File]: """ Recursively merge a list of region files. """ if len(id_regions) == 1: # Base case 1. [(sample_id, region_file)] = id_regions ...
d9ebbdfec49b6e5702e4c16476a20440185e39ef
3,650,582
import os def write_champ_file_geometry(filename, nucleus_num, nucleus_label, nucleus_coord): """Writes the geometry data from the quantum chemistry calculation to a champ v2.0 format file. Returns: None as a function value """ if filename is not None: if isinstance(filename, str...
dfaaddb754e50c4343b60ae3f19f6f7b3af8ee73
3,650,583
def check_for_collision(sprite1: arcade.Sprite, sprite2: arcade.Sprite) -> bool: """Check for collision between two sprites. Used instead of Arcade's default implementation as we need a hack to return False if there is just a one pixel overlap, if it's not multiplayer... """...
679de76d880c2e2e9ac34e0d87cc5cdd0211daa9
3,650,584
def modify_color(hsbk, **kwargs): """ Helper function to make new colors from an existing color by modifying it. :param hsbk: The base color :param hue: The new Hue value (optional) :param saturation: The new Saturation value (optional) :param brightness: The new Brightness value (optional) ...
ecc5118873aaf0e4f63bad512ea61d2eae0f7ead
3,650,585
def train_val_test_split(df, train_p=0.8, val_p=0.1, state=1, shuffle=True): """Wrapper to split data into train, validation, and test sets. Parameters ----------- df: pd.DataFrame, np.ndarray Dataframe containing features (X) and labels (y). train_p: float Percent of data to assign...
67b50b172f94ee65981ab124f03e192c7631c49c
3,650,586
def add_logs_to_table_heads(max_logs): """Adds log headers to table data depending on the maximum number of logs from trees within the stand""" master = [] for i in range(2, max_logs + 1): for name in ['Length', 'Grade', 'Defect']: master.append(f'Log {i} {name}') if i < max_logs...
5db494650901bfbb114135da9596b9b453d47568
3,650,587
def stations_at_risk(stations, level): """Returns a list of tuples, (station, risk_level) for all stations with risk above level""" level = risk_level(level) stations = [(i, station_flood_risk(i)) for i in stations] return [i for i in stations if risk_level(i[1]) >= level]
c18ef9af1ac02633f2daed9b88dfe6d72e83481a
3,650,588
from pathlib import Path import fsspec def try_to_acquire_archive_contents(pull_from: str, extract_to: Path) -> bool: """Try to acquire the contents of the archive. Priority: 1. (already extracted) local contents 2. adress-specified (local|remote) archive through fsspec Returns: True...
e510e165db9d57357b5c1e588db5563b08bf407f
3,650,589
def unproxy(proxy): """Return a new copy of the original function of method behind a proxy. The result behaves like the original function in that calling it does not trigger compilation nor execution of any compiled code.""" if isinstance(proxy, types.FunctionType): return _psyco.unproxycode(proxy.func_...
7fad2339a8e012fd95117b73b79a371d4488e439
3,650,590
from typing import Optional def get_measured_attribute(data_model, metric_type: str, source_type: str) -> Optional[str]: """Return the attribute of the entities of a source that are measured in the context of a metric. For example, when using Jira as source for user story points, the points of user stories (...
f15379e528b135ca5d9d36f50f06cb95a145b477
3,650,591
def get_one_frame_stack_dynamic(sp, idx): """ for a given sp and index number in a dynamic caller operand_stack data, return its data type and value. Note, at runtime, caller.operand_stack is dynamic, sp, idx, types and values are all changing during the run time. """ if idx > sp: r...
b621c25294e3d4aac720a35e73c3969b02ba5e31
3,650,592
def getIntArg(arg, optional=False): """ Similar to "getArg" but return the integer value of the arg. Args: arg (str): arg to get optional (bool): argument to get Returns: int: arg value """ return(int(getArg(arg, optional)))
a30e39b5a90bd6df996bdd8a43faf787aed7128f
3,650,593
from typing import Iterable def get_in_with_default(keys: Iterable, default): """`get_in` function, returning `default` if a key is not there. >>> get_in_with_default(["a", "b", 1], 0)({"a": {"b": [0, 1, 2]}}) 1 >>> get_in_with_default(["a", "c", 1], 0)({"a": {"b": [0, 1, 2]}}) 0 """ gett...
dbb5a9753bad224245ffea884e33802930bb8ded
3,650,594
def conv_HSV2BGR(hsv_img): """HSV画像をBGR画像に変換します。 Arguments: hsv_img {numpy.ndarray} -- HSV画像(3ch) Returns: numpy.ndarray -- BGR画像(3ch) """ V = hsv_img[:, :, 2] C = hsv_img[:, :, 1] H_p = hsv_img[:, :, 0] / 60 X = C * (1 - np.abs(H_p % 2 - 1)) Z = np.zeros_like(C) ...
f748c88e9f4b2a3da2ee7d7703b0d3c9615e564b
3,650,595
import torch def remap(tensor, map_x, map_y, align_corners=False): """ Applies a generic geometrical transformation to a tensor. """ if not tensor.shape[-2:] == map_x.shape[-2:] == map_y.shape[-2:]: raise ValueError("Inputs last two dimensions must match.") batch_size, _, height, wid...
ff88d66b6692548979e45d2a00f6905e2d973c2a
3,650,596
def AutoRegression(df_input, target_column, time_column, epochs_to_forecast=1, epochs_to_test=1, hyper_params_ar={}): """ This function performs regression using feature augmentation and then training XGB with Crossval...
704daf914897b7a43971b22d721ec0f1bb919d3e
3,650,597
def VMACD(prices, timeperiod1=12, timeperiod2=26, timeperiod3=9): """ 39. VMACD量指数平滑异同移动平均线 (Vol Moving Average Convergence and Divergence,VMACD) 说明: 量平滑异同移动平均线(VMACD)用于衡量量能的发展趋势,属于量能引趋向指标。 MACD称为指数平滑异同平均线。分析的数学公式都是一样的,只是分析的物理量不同。 VMACD对成交量VOL进行分析计算,而MACD对收盘价CLOSE进行分析计算。 计算方法: SHORT=...
5de5f372cb7ef6762b82f30d16465469b2cb6afc
3,650,598
def try_compress_numbers_to_range(elements): """ Map the "number" attribute of any element in `elements` to the most compact range possible (starting from 1). If the resulting numbers are within [MIN_RANGE, MAX_RANGE], return True, otherwise, return False. If it is not possible to obtain a mapping w...
2927046f5bb4217a5267db764fd58275f3fe65ce
3,650,599