content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_boxes_info( boxes_thinned, retr_mode, approx_method=cv2.CHAIN_APPROX_SIMPLE): """ Retreive contours and return a list of lists, each area of the box, and coordinates of the box. Parameters ---------- boxes_thinned : numpy.array Array containing photographic informati...
d3a877a2ebae771d521141048f0c05b15ac0aff5
3,633,000
def getMaxLen(fastaFilePath): """ Gets the length of the sequence that has maximum length in a fasta file. """ maxLen = 0 for val in fasta.getSequenceToBpDict(fastaFilePath).itervalues(): if maxLen < int(val): maxLen = int(val) return maxLen
7b5893c5563b96f4253025f39ee8e171694ae418
3,633,001
import scipy def align_face(filepath, output_size=1024, transform_size=4096, enable_padding=True): """ :param filepath: str :return: PIL Image """ ensure_checkpoint_exists("models/dlibshape_predictor_68_face_landmarks.dat") predictor = dlib.shape_predictor("models/dlibshape_predictor_68_face_...
507c59ba35e62cff4c07a0caf7d75e654d56aca1
3,633,002
def build_model(lr_source, scaling_factor=3, hr_target=None): """ build espcn model lr_source: source image batch tensor to be super resolved hr_target: target image batch as training labels in sub-pixel convolved shape, build a partial model for testing if hr_target is None scali...
8383684eb4ca69c6c8b517fe50914dde902320dd
3,633,003
def sum_up_validation_dataset(dataset, batch_size, repeat=True, number_of_repetitions=0): """Define how the validation dataset is suppose to behave during training. This function is applied to the validation dataset just before the actual training process. The characteristics...
9bab85eba802d5198bfd39bc42bd2fae5209d356
3,633,004
def moist_lift_parcel(parcel_pressure, parcel_temperature, to_pressure, step=1): """ Recursively determine the temperature of a parcel lifted from one pressure to another, assuming moist pseudoadiabatic processes. Arguments: parcel_pressure: The starting parcel pressure. parcel_tem...
5b2ae0f29258602f921395b4a3c187523509bad3
3,633,005
def has_rule(table, chain, rule_d, ipv6=False): """ Return True if rule exists in chain False otherwise """ iptc_chain = _iptc_getchain(table, chain, ipv6) iptc_rule = encode_iptc_rule(rule_d, ipv6) return iptc_rule in iptc_chain.rules
9ff524f71334e82b2bb971794427da3ec98f4df3
3,633,006
def get_pings_measurements(ip): """ Performs a ping measurement to an IP or returns cached result :param ip: string ip address :return: dictionary {src: rtt} where src is the string ip address of the measurement source, and rtt is the minimum rtt recorded for a ping from that src to the ip addre...
2c703be4a6e585690b90a846580ea56ea2d712a0
3,633,007
def get_timestamp(date_time): """Return the Unix timestamp of an ISO8601 date/datetime in seconds. If the datetime has no offset, it is assumed to be an UTC datetime. :param date_time: the datetime string to return as timestamp :type date_time: str :returns: the timestamp corresponding to the date...
daee72734b8994c11f4051a328ce49b7006451d6
3,633,008
def ssd_arg_scope(weight_decay=0.0005, data_format='NHWC'): """Defines the MobileNetV1 arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope. """ with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu,...
8b466f120f0ac8cb385a8a26d31ab7d3c54c17c3
3,633,009
import subprocess def fntDoOneLine(mysLine, mynProc, mynLine): """Execute one single-line command. Input: single line of command. Output: tuple of the (Popen PIPE return code, command return code, list of output lines as strings. Contributes line(s) to be in log file. Input lines an...
1e70b01083b0be7cc1ed3ff83ca3f5fcf642f8a4
3,633,010
def _build_module_page(page_info: parser.ModulePageInfo, table_view: bool) -> str: """Constructs a markdown page given a `ModulePageInfo` object. Args: page_info: A `ModulePageInfo` object containing information that's used to create a module page. For example, see https://ww...
95ac983b19a216c4e421182a2c1ae6c0dffc5838
3,633,011
async def async_get_maker_for_service(hass, service): """Get coffee maker to be used for specified service.""" device_id = None key = 'device_id' if key in service.data: device_id = service.data.get(key)[0] _LOGGER.info(f'Found target: {device_id}') device = None if device_id is...
19c4a9742f84796c2ebd1cebefa22e39cd57333f
3,633,012
def make_deferred_related(factory, fixture, attr): """Make deferred function for the related factory declaration. :param factory: Factory class. :param fixture: Object fixture name e.g. "book". :param attr: Declaration attribute name e.g. "publications". :note: Deferred function name results in "b...
c27e18adf7e7cd3646fea27ef34e9ae888d38510
3,633,013
import webbrowser def getbrowser(): """ Get the name of the browser currently being used """ # Try to find the browser try: # Get the browser name webbrowser.get(using=None) # Catch an error except RuntimeError: # Return nothing return None
cc74f7db8cf82b32516a0f3b462ba91b7c48b21b
3,633,014
def minimize_bias_geodetic(x, gd_mb=None, mb_geodetic=None, h=None, w=None, pf=2.5, absolute_bias=False, ys=np.arange(2000, 2019, 1), oggm_default_mb = False, **kwargs): """ calibra...
08313e2ed2bb04f58dba4f5c978978a3124005f2
3,633,015
def unpack_big_integer(binary_string): """ Convert a byte string into an integer. Akin to a base-256 decode, big-endian. """ if len(binary_string) <= 8: return unpack_big_integer_by_struct(binary_string) # NOTE: 1.1 to 4 times as fast as unpack_big_integer_by_brute() else: ...
3200758ff58076c03cb21280a4af9805da438436
3,633,016
import os def file_uploader_helper(file) -> tuple: """ file upload helper function :param file: :return: """ temp_folder = os.path.join(os.getcwd(), 'temp') if not os.path.isdir(temp_folder): try: os.mkdir(temp_folder) except OSError: raise OSError(f...
c320bfa8405c527fa230db8ad275355119257075
3,633,017
def extractLineFromTarget(**kwargs): """ based on the corridor and the related points, extract lines from original point clouds. """ img_buffer = kwargs['img_buffer'] min_xyz = kwargs['min_xyz'] cellsize = kwargs['cellsize'] pts_target = kwargs['pts_target'] # deep copy of the original data ...
4cabf1a6de49d6014b0c31ce67aa87ff116d162a
3,633,018
def contract_expanded_and_prob_pattern_nodes( product: ProductNode ) -> ProductNode: # P(A and B) = P(A when B) * P(B) """Contract expanded And Probability pattern nodes ` P(Y) * P(X when Y) = P(X and Y)` in `product` >>> contract_expanded_and_prob_pattern_nodes(1.5 * N(P(A when B)) * N(P(B))) ...
24eed700f76d3afcf46e3c2035c1157bb7428dfd
3,633,019
import requests def get_api_data(quote, date_range): """request to API with error check Error message if any of query params are invaild Note if API call limit is reached""" print(API_URL.format(date_range, quote)) data = requests.get(API_URL.format(date_range, quote)).json() if "Error Messag...
a1718a7d8f558bd06da8a6d1925dc2cc00795a87
3,633,020
from typing import Tuple from typing import List from typing import Optional import importlib def find_module_path_and_all(module: str, pyversion: Tuple[int, int], no_import: bool, search_path: List[str], interpreter: str) -> Optio...
f9537eb435db824bde3ae163531de8fb86f9eee9
3,633,021
import numpy def solve_TLS_Ab(A, b): """Solve an overdetermined TLS system by singular value decomposition. """ ## solve by SVD U, W, Vt = linalg.singular_value_decomposition(A, full_matrices=0) V = numpy.transpose(Vt) Ut = numpy.transpose(U) ## analyze singular values and generate smal...
5a68f574f2779cf1f436c268975955805d5c35c5
3,633,022
import torch def FixCentralTensorCalculateAuxiliaryTensor(ori_tensor_set, ori_matrix, mpo_input_shape, mpo_output_shape, ranks): """ In put tensor set product by matrix2MPO, and New_matrix. return the central tensor when auxiliary tensor was fixed. We assumes n = 5 """ ori_matrix = torch.from...
c330725679f64532872f6477189a97753a085ca9
3,633,023
def AddEntryPoint(ordinal, ea, name, makecode): """ Add entry point @param ordinal: entry point number if entry point doesn't have an ordinal number, 'ordinal' should be equal to 'ea' @param ea: address of the entry point @param name: name of the entry point. If null string,...
3218edc3663c2f575941141b9b063b8adf9d377e
3,633,024
import json import requests def goodsEditSkuChannel(skuId,regionId): """ :param skuId: :param regionId: :return: """ reqUrl = req_url('goods', "/sku/updateGroup") if reqUrl: url = reqUrl else: return "服务host匹配失败" headers = { 'Content-Type': 'application/js...
1fc51eb4f6ee2ee3bd0144bd3ad1e77d9962cdfc
3,633,025
import math def poly(x, y, order, rej_lo, rej_hi, niter): """linear least square polynomial fit with sigma-clipping""" # x = list of x data # y = list of y data # order = polynomial order # rej_lo = lower rejection threshold (units=sigma) # rej_hi = upper rejection threshold (units=sugma) ...
0043c58e4a579810d9f13218d6a6d0a768d1b8e4
3,633,026
import os def check_watched_dir(): """ A celery task that runs and moves files in WATCHED_DIR via the blind_media_move function :return: None """ media_files = recursive_extract_files(WATCHED_DIR) if len(media_files) > 0: for item in media_files: item_path = os.path.join(WA...
54f2fb74c7d68b3850320309592576d4a097308e
3,633,027
def on_step_start(func): """A function decorator that wraps a Callable inside the NeMoCallback object and runs the function with the on_step_start callback event. """ class NeMoCallbackWrapper(NeMoCallback): def __init__(self, my_func): self._func = my_func def on_step_star...
2028a8c0994927f6097fbc6f08852450e9ccb465
3,633,028
import ast from operator import add def reindent_docstring(node, indent_level=1, smart=True): """ Reindent the docstring :param node: AST node :type node: ```ast.AST``` :param indent_level: docstring indentation level whence: 0=no_tabs, 1=one tab; 2=two tabs :type indent_level: ```int``` ...
2dd90c2e72e79584ae8b4fed5fff2a4a5ba01d53
3,633,029
import numpy def xyz(x, y, z): """Construct a Toyplot color from CIE XYZ values, using observer = 2 deg and illuminant = D65.""" x = x / 100.0 y = y / 100.0 z = z / 100.0 r = x * 3.2406 + y * -1.5372 + z * -0.4986 g = x * -0.9689 + y * 1.8758 + z * 0.0415 b = x * 0.0557 + y * -0.2040 + z ...
3d3189ac0d8987309d6c4839b7909d65a47f49af
3,633,030
def _is_large_prime(num): """Inefficient primality test, but we can get away with this simple implementation because we don't expect users to be running print_fizzbuzz(n) for Fib(n) > 514229""" if not num % 2 or not num % 5: return False test = 5 while test*test <= num: if not nu...
090b641872d8d25d55e8f32296e3893f59518308
3,633,031
def cleanup_code(content: str): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` return content.strip('` \n')
a026668f01e1641618c5b25b06396516410dbe1e
3,633,032
def name_generator(identifier: str= "") -> str: """ Generates a unique name. :param identifier: identifier to add to the name :return: the generated name """ return f"thrifty-builder-test-{identifier}{uuid4()}"
f1da6477beb1ce373b6d5e47e7f2375fe1a74661
3,633,033
import os def merge_fcs(fcs, merged_fc, gdb): """combines like geometries into a feature class""" desc = arcpy.Describe(os.path.join(gdb, fcs[0])) if arcpy.Exists(merged_fc): arcpy.Delete_management(merged_fc) ifc = arcpy.CreateFeatureclass_management(out_path=os.path.dirname(merged_fc), ...
8aa53f3a064e6888adb0ea250efe73ff495e4e4a
3,633,034
import signal def _ssim_for_multi_scale(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03): """Calculate SSIM (structural similarity...
5bf91fbb85a8eca8e52aeae566f23dc750037330
3,633,035
def index(request): """ :param request: :return: """ panel = True # auto login for test users user = authenticate(username='admin', password='Aa1234567890') login(request, user) return render(request, "back/index.html", locals())
fadd7e80eebf03c44c064754884e3dd0984450f8
3,633,036
def membersof(parser, token): """ Given a collection and a content type, sets the results of :meth:`collection.members.with_model <.CollectionMemberManager.with_model>` as a variable in the context. Usage:: {% membersof <collection> with <app_label>.<model_name> as <var> %} """ params=token.split_contents(...
011488e1949c1314b2f3fe73623879b9459c7585
3,633,037
def ext_s(variable, value, substitution): """ext_s is a helper function for eq, without checking for duplicates or contradiction it adds a variable/value pair to the given substitution. `unify` deals with all of the related verification. @param variable: A LogicVariable @param value: A value that c...
bced042fc8ea5882d4dc901e3b7df94c9b0d0893
3,633,038
def sc_fermi_sub_wrap( calc, non_native, native, stoich, non_native_limit, native_limit, im_cor, charge ): """ sc_fermi_sub_wrap determines the formation energy of a substitutional defect, and formats a 'ChargeState' object to be fed into sc_fermi args: calc = DFT calculation summary of the defective materi...
1ff6161f0b88b9f1a7765565041549f50bd7c2aa
3,633,039
import re def _include_matcher(keyword="#include", delim="<>"): """Match an include statement and return a (keyword, file, extra) duple, or a touple of None values if there isn't a match.""" rex = re.compile(r'^(%s)\s*%s(.*)%s(.*)$' % (keyword, delim[0], delim[1])) def matcher(context, line): ...
b5f57a8f007870952810a591bb8e15c86af467b1
3,633,040
import logging def cod_converter(cod_decimal_string): """ From a decimal value of CoD, map and retrieve the corresponding major class of a Bluetooth device :param cod_decimal_string: numeric string corresponding to the class of device :return: list of class(es) """ if not cod_decimal_string or c...
b566c70fcdfe8bd8801ce12e2358b1dcb9eb9f4d
3,633,041
def get_params(ntrain, EXP_NAME, order, Nside, architecture="FCN", verbose=True): """Parameters for the cgcnn and cnn2d defined in deepsphere/models.py""" n_classes = 2 params = dict() params['dir_name'] = EXP_NAME # Types of layers. params['conv'] = 'chebyshev5' # Graph convolution: chebysh...
fb46d04050f88ce16f75a414dce62c1b08a0d3c9
3,633,042
def historify( X: np.ndarray, history_len: int, ): """Generate (num_histories, history_len, input_dim) history from time series data Todo: * Implement striding Warning: * This converts back and forth between jnp and np, which is fine for CPU, but may cause issues if we need to ...
e6f86932aa227bc88246e4ce78a865fc10cdb446
3,633,043
import operator def lcs(l1, l2, eq=operator.eq): """Finds the longest common subsequence of l1 and l2. Returns a list of common parts and a list of differences. >>> lcs([1, 2, 3], [2]) ([2], [1, 3]) >>> lcs([1, 2, 3, 3, 4], [2, 3, 4, 5]) ([2, 3, 4], [1, 3, 5]) >>> lcs('banana', 'baraban')...
4b5d3cb9911a6834c006e78f7b40061695c464e2
3,633,044
from mpunet.preprocessing import get_preprocessing_func def get_data_sequences(project_dir, hparams, logger, args): """ Loads training and validation data as specified in the hyperparameter file. Returns a batch sequencer object for each dataset, not the ImagePairLoader dataset itself. The preprocess...
57230e155c1f9817ad6974198e10c0ff04a7891f
3,633,045
def request_factory(environ): """Factory function that adds the headers necessary for Cross-domain calls. Adapted from: http://stackoverflow.com/questions/21107057/pyramid-cors-for-ajax-requests Copied from mtholder/pyraphyletic """ request = Request(environ) _LOG.debug('trunctated reque...
7f241ed4e24cb3a58779b29015b1c8a1889bc338
3,633,046
def tick_payload(): """ Payload for tick """ data = TickEvent(tick_type=TickType.FULL).json() return { "context": { "eventId": "some-eventId", "timestamp": "some-timestamp", "eventType": "some-eventType", "resource": "some-resource", }, ...
266490cd502619ad27ee248171c1fd812baa4d6a
3,633,047
def calc_sparsity(optimizer, total_params, total_quant_params): """ Returns the sparsity of the overall network and the sparsity of quantized layers only. Parameters: ----------- optimizer: An optimizer containing quantized model layers in param_groups[1]['params'] and non-quantized...
92ee924239ee8d7ac97aebba2958671043aa2d89
3,633,048
def get_pck_normalized_joint_distances(gt_array: np.ndarray, pred_array: np.ndarray, visible_array: np.array, threshold, ref_distances): """ n = number of records :param gt_array: (n, num_joints, 2) :param pred_array: (n, num_joints, 2) :param visible_array: (n, num_joints) # 0 if invisible, 1 if vi...
8e42b418cdda3e89007ee44ccd8c91b859b8ea69
3,633,049
import warnings def dict_to_header_arrays(header=None, byteorder='='): """ Returns null hf, hi, hs arrays, optionally filled with values from a dictionary. No header checking. :param header: SAC header dictionary. :type header: dict :param byteorder: Desired byte order of initialized arr...
c137ec7de45a248d638a87aaaf9c24a1710f0091
3,633,050
def swapKeys(d,keySwapDict): """ Swap keys in dictionary according to keySwap dictionary """ dNew = {} for key, keyNew in keySwapDict.iteritems(): if key in d: dNew[keyNew] = d[key] for key in d: if key not in keySwapDict: dNew[key] = d[key] return dN...
0d8917e224574ee0bf682fed10d367f3a5d2bc2f
3,633,051
def render_pyramid(pyr, levels): """ Renders a big image of horizontally stacked pyramid levels :param pyr: Gaussian or Laplacian pyramid :param levels: number of levels to present in the result <= max_levels :return: single black image with pyramid levels stacked horizontally """ pyr[0] = (...
46bd9fbcf8f973bb23a681f478087a848e93d559
3,633,052
def test_scatter_plot(): """ Test plot of predicted electric conductivity as a function of the mole fractions. Input ----- x_vals : numpy vector x-axis (mole fractions) y_vals : numpy vector y-axis (predicted conductivities) x_variable : string for labeling the x-axis Returns -...
5e3ac6de37eb13574e85403921aea368b2224f71
3,633,053
def networkx2pandas(current_graph, input_type): """Converting current graph into a pandas data frame :param: current_graph: a python dict containing all paths :param: input_type: the semantic type of the input """ data = [] for paths in current_graph.values(): for path in paths: ...
8f6a1166c8bd5818ff0d3b433f5fa84e1e064dc1
3,633,054
from typing import Union from typing import Sequence def assemble_matrix(form: _fem.FormMetaClass, constraint: Union[MultiPointConstraint, Sequence[MultiPointConstraint]], bcs: Sequence[_fem.DirichletBCMetaClass] = [], d...
e7d0bc5f779cc97889e52860f13b4e5e9b84b022
3,633,055
import torch def getLayers(model): """ get each layer's name and its module :param model: :return: each layer's name and its module """ layers = {} root = '' def unfoldLayer(model, root): """ unfold each layer :param model: the given model or a single layer ...
e1120460b35fa49fe8ad43cc9ce606c1d217a584
3,633,056
def redeploy(): """ Implements redeploy handle Runs docker-compose pull and up commands for specified service Service must be preconfigured with yml file in SERVICES_DIR Docker URL can be configured with DOCKER_URL option """ service = request.args.get("service", type=str) if not service...
e7e898c59f9719f6c0d136ffd1ada480f3e0f9e8
3,633,057
import unittest def unittests(): """ Short tests. Runs on CircleCI on every commit. Returns everything in the tests root directory. """ test_loader = unittest.TestLoader() test_suite = test_loader.discover('tests') test_suite = _circleci_parallelism(test_suite) return test_suite
153d716b4731bd3290d7af9ce5ff5d77f5b5309e
3,633,058
import requests import json def get_weekly_forecasts(country_code, zip_code): #for the web app examining trends """ Fetches the weekly data from the Weather.gov API, for a given country and zip code. Params: country_code (str) the requested country, like "US" zip_code (str) the requested ...
aa224eb54194f5115b221c66510a5b52e3b68bf8
3,633,059
import re def parse_nml(string, ignore_comments=False): """ parse a string namelist, and returns a list of param bundles with four attrs: name, value, help, group """ group_re = re.compile(r'&([^&]+)/', re.DOTALL) # allow blocks to span multiple lines array_re = re.compile(r'(\w+)\((\d+)\)') ...
6463e9b5b3fb7824b496fd4426a5728a797d0c92
3,633,060
def glo2loc_2D(c,s): """ Build rotation matrix from global to local 2D coordinate system. ------- Inputs: c: cosine in radian of the angle from global to local coordinate system s: sine in radian of the angle from global to local coordinate system ------- Output: R_m: rotation matrix...
6e3a7d1e05b438a93099390c580ae49b7e5ae006
3,633,061
def model_scatter_2d(c=1500, dc=150, freq=25, dx=5, dt=0.0001, nx=[50, 50], propagator=None, prop_kwargs=None): """Create a point scatterer model, and the expected waveform at point, and the forward propagated wave. """ nx = np.array(nx) model = np.ones(nx, dtype=np.float32) ...
c2f7ec47dd4da5094a673edc4236ae39d1c772dc
3,633,062
def contours_and_bounding_boxes(bw_image, rgb_image): """Extract contours and bounding_boxes. Parameters ---------- bw_image: np.uint8 Input thresholded image rgb_image: np.uint8 Input rgb image Returns ------- image_label_overlay: label """ cleare...
8e46f837d1fc6bf1c6413f32a9339b9028052694
3,633,063
def Compute_RHS_and_LHS(functional, testfunc, dofs, do_simplifications = False): """ This computes the LHS matrix and the RHS vector Keyword arguments: functional -- The functional to derivate testfunc -- The test functions dofs -- The dofs vectors do_simplifications -- If apply simplifications...
a8deb075186dbf2f05c87eeeb1adf48e30eba19d
3,633,064
import os from datetime import datetime import logging def init_logging_yaml(config_file): """initialize logging configuration via a dict specified from a YAML file """ # https://docs.python.org/3/library/logging.config.html#logging-config-api global log_root, log_file, log_dir yaml=YAML(typ='safe') ...
3455434f627e1bccf8bf26a763b96897c33e71ac
3,633,065
def buscaVizinhos(matrizCapacidades): """Função para buscar os vizihos de cada vertice""" vizinhos = {} for v in range(len(matrizCapacidades)): vizinhos[v] = [] for v, fluxos in enumerate(matrizCapacidades): for vizinho, fluxo in enumerate(fluxos): if fluxo > 0: ...
1e9ace4be94d80ae2637689b3d25ee1116714888
3,633,066
import logging def get_server_numeric_version(ami_env, is_local_run=False): """ Gets the current server version Arguments: ami_env: (str) AMI version name. is_local_run: (bool) when running locally, assume latest version. Returns: (str) Server numeric v...
1ee8b0eb40b5db28b38bbe9e1a2080b47534b99a
3,633,067
def get_all_images(): """ :return: all data from db, except db id's """ return list(cursor.find({}, {'_id': False}))
27764e962d11f71d6f536a70f22013a032158aa3
3,633,068
import typing def historical_market_capitalization( apikey: str, symbol: str, limit: int = DEFAULT_LIMIT ) -> typing.List[typing.Dict]: """ Query FMP /historical-market-capitalization/ API. :param apikey: Your API key. :param symbol: Company ticker. :param limit: Number of rows to return. ...
79a2adb718b6c60e4bf3a159476c7462dc8c39eb
3,633,069
def get_search_url(query=None, start=None, end=None, page=None): # type: (str, int, int, int) -> str """Constructs a search URL based on the given parameters""" query = "+" if query is None else query start = "+" if start is None else start end = "+" if end is None else end page = 1 if page is N...
6a58f61ca3f30ef27db46bf346597fb8ca4f9a19
3,633,070
from pathlib import Path import hashlib def hash_file(path: PathType, algo: str, enc: str = "utf-8", bsize: int = 65536) -> str: """ Hash the name and contents of a file. Parameters ---------- path : PathType file to hash. algo : str hash algorithm name supported by haslib Pyt...
fc9208fa762e50c5049afd2f5c37eaf351356c0c
3,633,071
import json import os import shutil def _check_json(out_file, status, hold_file): """Function: _check_json Description: Private function for file_check function. Arguments: (input) out_file -> Path and file name of output file. (input) status -> Status of check. (input) hold_f...
616ef16200e07975cdaedbebfa3fcf21746c367b
3,633,072
import numpy def _guess_z_grid_shape(x, y): """Guess the shape of a grid from (x, y) coordinates. The grid might contain more elements than x and y, as the last line might be partly filled. :param numpy.ndarray x: :paran numpy.ndarray y: :returns: (order, (height, width)) of the regular grid...
ce84b67ead9083f297de62fb3030569353143512
3,633,073
def get_hosts_with_state(state): """Helper function to check the maintenance status and return all hosts listed as being in a current state :param state: State we are interested in ('down_machines' or 'draining_machines') :returns: A list of hostnames in the specified state or an empty list if no machi...
075464cc7c8a0e6f66be5f655669167bab52ea1a
3,633,074
def load_category_index(label_map_path, num_classes): """ load the category index from the lablemap with the given path for example, a cateory index is like the following CATEGORORY_INDEX = { 1 : {'id':1, 'name':'Green'}, 2 : {'id':2, 'name':'Red'}, 3 : {'id':3, 'name':'Yellow'} ...
1eba86fa8c6d28d265daa1c752e09e8114ad9368
3,633,075
def create_mask(M, N, path, radius): """ Fill a square block with values Parameters ---------- M: int Number of points in the first trajectory N: int Number of points in the second trajectory p: list of [i, j] A warping path one level up radius: int Half ...
ecbc8aabef79856aadc76ac41fff915226024ab9
3,633,076
def format_hostname(domain_parts, uid): """Formats hostname for a docker based on domain parts and uid. NOTE: Hostnames are also used as docker names! domain_parts - a single or a list of consecutive domain parts that constitute a unique name within environment e.g.: ['worker1', 'prov1'], ['ccm1', 'prov...
e7ad7ef470c23f132ed564caa0c157cc7ffc04b8
3,633,077
def get_aspect_ratio(width_first=True): """ Returns the aspect ratio of the game window, or the window's width / the window's height. If width_first is True (default), then it will return the window's height / the window's width. :param width_first: Bool - Whether to divide the height by the width. ...
3c87d3520aa26692835ce46ccab2ed5915bed444
3,633,078
import os from datetime import datetime def upload_to_blob(file_path, client, container): """ Upload a file to Azure Blob storage. Args: file_path (str): Path of the file to upload. client (`azure.storage.blob.BlockBlobService`): Blob service container (str): Name for the containe...
b2965de554038c26aa22846f31992a500796993a
3,633,079
def _environ_cols_wrapper(): # pragma: no cover """ Return a function which returns console width. Supported: linux, osx, windows, cygwin. """ warn("Use `_screen_shape_wrapper()(file)[0]` instead of" " `_environ_cols_wrapper()(file)`", DeprecationWarning, stacklevel=2) shape = _screen_...
e35669b63fd755b7ce44446f0327f9c01f2dcf71
3,633,080
from typing import Optional def encode(content, encoding: Optional[str] = "json") -> Response: """Encode content in given encoding. Warning: Not all encodings supports all types of content. :param content: Content to encode :param encoding: - `json` (default) - `bin`: nD array/scalar...
fb903e3d5465328f471c3ef368023647da4e24ed
3,633,081
def yesNoDialog(parent, msg, title): """ Convenience function to display a Yes/No dialog Returns: bool: return True if yes button press. No otherwise """ m = QMessageBox(parent) m.setText(msg) m.setIcon(QMessageBox.Question) yesButton = m.addButton(_(Text.txt0082), QMessageBox....
cc6165e017193fe85d64765fdeecbf2d056767ba
3,633,082
def import_all_references(except_namespaces = []): """ 导入所有reference文件 """ done = False while (done == False or (len(pm.listReferences()) != 0)): refs = pm.listReferences() #get rel refs pro = [] if except_namespaces: for ref in refs: if ref.n...
145cc3b6260651728f5b16661fd1f9d68d70c91a
3,633,083
from labels import get_annotation def get_annotations(element): """ returns a dictionary of all the annotation features of an element, e.g. tiger.pos = ART or coref.type = anaphoric. """ annotations = {} for label in element.getchildren(): if get_xsi_type(label) == 'saltCore:SAnnotatio...
7189e3f7b3d671af40b689c2586d373d344ca10c
3,633,084
def _prefAdj(coupling, leg): """Prefactor for the creation of an adjoint Only implemented for regular three-legged tensors with an (in, in, out) flow and their adjoints at the moment. """ if len(coupling) != 1: raise NotImplementedError("Only for three-legged tensors") flow = tuple(c[1...
e2889badba0cef27c4ce8c51ed14bda71524c3ec
3,633,085
def recon_traj_with_preds(dataset, preds, seq_id=0, **kwargs): """ Reconstruct trajectory with predicted global velocities. """ ts = dataset.ts[seq_id] ind = np.array([i[1] for i in dataset.index_map if i[0] == seq_id], dtype=int) dts = np.mean(ts[ind[1:]] - ts[ind[:-1]]) # pos = np.zeros([p...
aa3150fef73450ca83617292dd9e3abf7cfd2054
3,633,086
def fitfunPowerLaw(fitparamStart, fixedparam, fitInfo, x, y): """ Power law fit function y = A * B^x + C ========== =============================================================== Input Meaning ---------- --------------------------------------------------------------- fitparamStart ...
8e1d234ef8f123ca3d11e8b0896865c63e15407c
3,633,087
def make_2d_histogram(x, y, n_bins, xlabel, ylabel, cbar_label, figsize=(12, 4)): """ Generate a rainbow-colored 2D histogram. :param x: X-axis values, i.e. barcode group indices :param y: Y-axis values corresponding to x :param n_bins: (x,y) bin sizes; x should usually be 1 ...
ed839db7428d743463ea37a22b0b7a16dc58aef1
3,633,088
def ingest_cop(years, month): """ Args: years: list month: str Returns: list """ cop_data = [] for year in years: directory = 'data\\raw\\copernicus\\' wrf_file_name = year + month + '-C3S-L4_OZONE-O3_PRODUCTS-MSR-ASSIM-ALG-MONTHLY-v0021.nc' nc = netcd...
bbe6496e5240d1d3749707a4ab79e803ca156267
3,633,089
import os import glob def utils_files_count(directory): """Get number of files by searching directory recursively""" if not os.path.exists(directory): return 0 cnt = 0 for r, dirs, files in os.walk(directory): for dr in dirs: cnt += len(glob.glob(os.path.join(r, dr + "/*"))...
3d749cfa55816612b3fb11016ad70e8d7aba16d5
3,633,090
from scipy.io.wavfile import read as readwav def readwav(filename): """Read a WAV file and returns the data and sample rate :: from spectrum.io import readwav readwav() """ samplerate, signal = readwav(filename) return signal, samplerate
580b50d7d3585a300da1967d4481b5e9b0b9bf24
3,633,091
def get_connections_from_file(parent, filename): """load connections from connection file""" error = 0 try: doc = etree.parse(filename).getroot() if doc.tag != 'qgsCSWConnections': error = 1 msg = parent.tr('Invalid CSW connections XML.') except etree.ParseError ...
64fad1ae1f5ab295d8f09aa64f69f487407f62d2
3,633,092
from typing import List def extract_provenance_chain(credential: Credential) -> List[Credential]: """ Extract the chain into an ordered list of credentials. Root credential will be at the start of the returned list """ def decode(credential: Credential, acc: List[Credential]): if credenti...
00ed19cd953ba2fd6a3eaf591fde6c6b0113b64b
3,633,093
def make_induces(x, y): """return [ [(0,0), (0,1),...,(0,y-1)], [(1,0),...], [(x-1, 0), (x-1, 1), ..., (x-1, y-1)] """ index_x = tf.expand_dims(tf.range(0, x), 1) index_y = tf.expand_dims(tf.range(0, y), 0) index_x = tf.tile(index_x, [1, y]) index_y = tf.tile(index_y, [x, 1]) induces = tf.stack([index_x, ...
64780900a4c854881ec0dbd0a058b1dfa523bdd3
3,633,094
def unused_argument(editor, item): """ Pylint unused-argument method """ line_no = item.line_no error_text = editor.lines[line_no] LOGGER.info("unused argument: {0}".format(error_text)) return (line_no, 0)
fd4dc3cae169b34c3e2c16321f746cbe4b83054c
3,633,095
def fitjordan(f, B, losses, Bo, fo): """fit coeffs of losses(f,B)=(ch*(f/fo)**alpha + ch*(f/fo)**beta)*(B/Bo)**gamma returns (ch, alpha, cw, beta, gamma) """ pfe = np.asarray(losses).T z = [] for i, fx in enumerate(f): if fx: if isinstance(B[0], float): z ...
c236a0f3a7dd956cfee468b56d27a99fd90bb90c
3,633,096
import itertools def count_temporal_motif(G, sequence, delta, get_count_dict=False): """Count all temporal motifs. Parameters ---------- G : the graph to count temporal motif from. This function only supports ImpulseDiGraph sequence: a sequence of edges specifying the order of the motif. For exa...
88851133592fc002a3cde8e7712388361e3c8f51
3,633,097
from datetime import datetime def calc_expiry_time(minutes_valid): """Return specific time an auth_hash will expire.""" return ( timezone.now() + datetime.timedelta(minutes=minutes_valid + 1) ).replace(second=0, microsecond=0)
2915ca419d234808d960d9982e234aab16a10784
3,633,098
import re def parse(s): """ Parse an XML tree from the given string, removing all of the included namespace strings. """ ns = re.compile(r'^{.*?}') et = etree.fromstring(s) for elem in et.iter(): elem.tag = ns.sub('', elem.tag) return et
1d026ef8978c4d774543bc1149c218bbfcf97fe8
3,633,099