content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def productos_pos(): """ Muestra las configuraciones para productos pos """ productos = db(db.maestro_pos).select() return dict(productos=productos)
87e80d5789f65df46c3178a9d83e575321b423a7
3,632,000
def _build_measurement_vectors(ppci): """ Building measurement vector z, pandapower to ppci measurement mapping and covariance matrix R :param ppci: generated ppci which contains the measurement columns :param branch_cols: number of columns in original ppci["branch"] without measurements :param bus_...
b51be7da841ce5c54942834133d64263fcf29ff1
3,632,001
import zipfile from io import StringIO import numpy import json import pickle def load(path): """Load data and reconstruct model.""" with zipfile.ZipFile(path,'r') as zf: buf = StringIO.StringIO(zf.read('weights.npy')) weights = numpy.load(buf) config = json.loads(zf.read('config.json...
bee50593f16a534c16f9961e53aaf6a31b5bd3d1
3,632,002
def env( a, import_models=False, c=None, f=None, dir='', ): """ Return web2py execution environment for application (a), controller (c), function (f). If import_models is True the exec all application models into the environment. """ request = Request() response ...
3d78e71866eb1daf06e6e20e9437a0bf39210363
3,632,003
import copy import hashlib import json def get_payload_hash(payload): """Return unique hash of HySDS job JSON payload.""" clean_payload = copy.deepcopy(payload) for k in ('_disk_usage', '_sciflo_job_num', '_sciflo_wuid'): if k in clean_payload: del clean_payload[k] return hashlib....
e5122c85c3bfc358dda0404d029d06efbe2fefde
3,632,004
def binStack(array, bins, id0=1): """ Bin a hyperstack according to a known list of frames per bin @param array: input array to be binned, hyperstack or otherwise. Binning occurs along the first axis @type array: numpy.ndarray @param bins: list of frames in each bin. Each index in bins is a...
3367566a37e6328cd8af039e91a40d176b488617
3,632,005
import torch def knn(A, B, k, distFcn): """ Returns the indices of the k-nearest neighbors of A in B Parameters ---------- A : Tensor a (N,F,) tensor B : Tensor a (M,F,) tensor k : int the number of neighbors to find distFcn : callable the distance func...
f9c3bac58ff3fcffe53bb9b2a25ffbcc57870ec9
3,632,006
def set_purpose(slack_client, channel, purpose): """ Set the purpose of a given channel. """ response = slack_client.api_call("channels.setPurpose", purpose=purpose, channel=channel) return response
786a495b55300b955e2f7ec525117be75b251a07
3,632,007
import os def generate_aes_key(size=256): """ Generates aes key with specified size :param size: aes bits, default 256 :return: generated key bytes """ return os.urandom(int(size / 8))
604b626ae0996499c2d855ede91f70ded8f585cc
3,632,008
def masked_minimum(data, mask, dim=1): """Computes the axis wise minimum over chosen elements. Args: data: 2-D float `Tensor` of size [n, m]. mask: 2-D boolean `Tensor` of size [n, m]. dim: The dimension over which to compute the minimum. Returns: masked_minimum: N-D `Tensor`. The minimize...
7629c1a2ba9c2089935a68354d748a80e1eff488
3,632,009
from typing import Tuple import subprocess import os def spawn_node_process(output_dir: PathLike) -> Tuple[subprocess.Popen, str]: """ Spawn an rfbrowser node process, that can be shared between library instances. Usage example: rc = 1 background_process, port = spawn_node_process(ATEST_OUTPUT /...
cbdd9660060910b74f75803e1dfa0f6cacfbc25d
3,632,010
import json def decode_stderr_json(stderr): """ return a list of decoded json messages in stderr """ # - check for blank input if not stderr: # - nothing to do return list() # - split the input (based on newlines) into list of json strings output = list() for line in stderr.spl...
d527730d8d9a77a1ec434ee6203c4e08433306c9
3,632,011
import collections def hash_params(params): """ Construct a data structure of parameters that is hashable. This requires changing any mutable data structures into immutable ones. We chose a frozenset because role parameters have to be unique. .. warning:: this does not handle unhashable scalars...
eb83122e2b1f7097917f1029e84f2053352127f4
3,632,012
def get_validate_result_form(tel_num, validate_code): """ Assemble form for get_validate_result :param tel_num: Tel number :param validate_code: Validate code from capcha image :return: Param in dict """ post_data_dict = dict() post_data_dict['source'] = 'wsyyt' post_data_dict['telno...
6340c97522a097c0cf96170e08466fb795e16dc3
3,632,013
def create_user(): """Create a new user record.""" request = flask.request.get_json() try: # NOTE(jk0): We expect all of these keys to exist to be considered a # valid user record. Ignore all others. user = _lookup_user(request["userid"]) if user: flask.abort(40...
8d98667aba51172535768d6c57d9fc8f2e2e7821
3,632,014
def softmax_cross_entropy(logits, labels): """ Cross-entropy loss applied to softmax. """ one_hot = hk.one_hot(labels, logits.shape[-1]) return -jnp.sum(jax.nn.log_softmax(logits) * one_hot, axis=-1)
c0850fdebbf69629763e94c489ed0aaf67e67184
3,632,015
def get_category_detail(comp_id, cat_id): """Retrives information about the category and the reviews in it""" json = [Category.query.filter_by(id=cat_id).filter_by(comp_id=comp_id).first_or_404().to_json()] submissions = Submission.query.filter_by(comp_id=comp_id).all() cat_submissions = [] for _, s...
d6b780a8d2c985f55a6500faf386c437669d0e9a
3,632,016
def build_input_from_segments(persona, history, reply, vocab, labels=False, with_eos=True): """ Build a sequence of input from 3 segments: persona, history and last reply. """ bos, eos, speaker1, speaker2 = vocab[SPECIAL_TOKENS[:-1]] sequence = [[bos] + list(chain(*...
3b47bbc0fb7c666188f36a1e1df520d84327d336
3,632,017
from scipy.stats import norm def dual_gaussian(x, amp1=1.0, mean1=0.0, std1=1.0, amp2=1.0, mean2=0.0, std2=1.0): """Sum of two Gaussians. Parameters ---------- x : array Function argument amp1: float Amplitude parameter of the first Gaussian mean1: float Mean parameter of th...
6d46ffcfcfd0327d06ccc8c92157bd9f82813124
3,632,018
import os def getFileInfoFromXML(thisfile): """ Get the PFN from the XML """ pfn = thisfile.getElementsByTagName("pfn")[0].getAttribute("name") # lfn will not be present in XML any longer, get it from the PFN - possible problem with LFN file name extensions # lfn = thisfile.getElementsByTagName("lfn"...
788080388a4c7984f8646a944eefa04a7ce22536
3,632,019
def get_district_info(request, code): """ Get district info by 'code' """ try: district = District.objects.get(code=code) child_districts = District.objects.filter(parent=district.code) data = district_model2dict(district) children = [district_model2dict(c) for c in child...
57136fe7d77375b6d9c258b42bccf24e4c7a3750
3,632,020
def calculate_price(prices, concentrations): """ From a list of prices in $USD / kg and concentrations in mass %, calculate the price of the formulation in $USD / kg """ # Normalise ingredient concentrations concentrations = np.asarray(concentrations) / np.sum(concentrations) # Calculate a...
7131bb0aa5f9502f564e43eba76ee3b878041b22
3,632,021
def cos_convolve(evidence): """Take as input the classifier evidence for single trials in dictionary format and return alligned evidence and evidence convolved with a cosine. Input: dictionary: accuracy : ndarray dimensions: time matrix containing class predi...
cf292eb0af8d4f44a0d64c02b9a09e6b7d149eb9
3,632,022
from io import StringIO def get_image_info(real_image_type, body): """ only in webp, gif, png, jpeg, bmp """ image_fp = StringIO(body) if real_image_type == 'webp': data = image_fp.read() width, height = decode.GetInfo(data) image_pix_count = int(width) * int(height) else:...
9570de917deafdcaa2d2a2d208e40710bcb12d04
3,632,023
def estimate_ranks(layer): """ Unfold the 2 modes of the Tensor the decomposition will be performed on, and estimates the ranks of the matrices using VBMF source: https://github.com/jacobgil/pytorch-tensor-decompositions/blob/master/decompositions.py """ weights = layer.weight.data unfold_0 = ...
3c4efeb5ad56a32ad3908657c013bfb153aaf01e
3,632,024
def _add_batch_dim(img): """Many TF functions require NWHC input. Convert WHC image to NWHC of batch size 1.""" get_hwc(img) # validate dimensions return tf.expand_dims(img, 0)
53a995d6a1398f137abb69b38aa91b98257e50c3
3,632,025
def read_inventory_file(inventory): """ Read an inventory file, return the list of dicts :param str inventory: The inventory file :return list[dict, ..]: List of hostname and IP definitions """ log.info("Reading and validating inventory file") inventory_hosts = load_json(inventory) if no...
cff1d3c84b3617b12e4bee7b4726207d4d4747cd
3,632,026
def ground_truth_to_word(ground_truth): """ Return the word string based on the input ground_truth """ try: return ''.join([config.CHAR_VECTOR[np.argmax(arr)] for arr in ground_truth if np.argmax(arr) < len(config.CHAR_VECTOR)]) except Exception as ex: print(ground_truth) ...
ae07266f34f01d605705d60e7c331cefb1fb845a
3,632,027
import itertools def build_dataframe(dimension_names, dimension_members, data_values, null_values, sd_values): """Build a dataframe from dimensions and data. Adds the cartesian product of dimension members plus the series of data. Args: dimension_names (list of string) ...
1d5621d753466a69bd0bef4120c2c445e959bbb9
3,632,028
def fs_url_exists(fs_url): """ verifies for a valid fs url :param fs_url: fs_url string :return: boolean """ try: fs.open_fs(fs_url) except fs.errors.CreateFailed: return False return True
98aad242d04b169e1a1e3204bf40e0b4ac9c4018
3,632,029
def _serialize_noise_model(config): """Traverse the dictionary looking for noise_model keys and apply a transformation so it can be serialized. Args: config (dict): The dictionary to traverse Returns: dict: The transformed dictionary """ for k, v in config.items(...
f3453e174d5ba858b9eec678e7bc1574f74d50eb
3,632,030
def create_app() -> falcon.API: """ Typical application factory style setup. Returns: falcon.API: The falcon API object. """ engine = create_engine("sqlite:///") app = falcon.API(middleware=[DbSessionMiddleware(engine)]) app.add_route("/", ExampleResource()) return app
ab134f8d25644da01718a16e4887d023f5e0221f
3,632,031
def show_tracker(secure=False): """ Output the analytics tracker code. """ google = getattr(settings, 'ANALYTICS', {}) if google: analytics_code = google.get('ANALYTICS_CODE') if analytics_code: return {"analytics_code": analytics_code} return {}
32d30b031e979cf91165dba4872a93995289bbc4
3,632,032
from typing import Awaitable import re async def formatCommand(cls:"PhaazebotDiscord", Command:DiscordCommand, CommandContext:DiscordCommandContext, direct_call:bool=False) -> dict: """ This function is suppost to do everything. It takes the placeholder in Command.content and replaces them with the wanted data. ...
306e44d6b493c08140f24834d715669afb00477b
3,632,033
def k8s_net_client(k8s_conf): """ Retrieves the kubernetes networking client :param k8s_conf: the k8s configuration used to deploy the cluster :return: a kubernetes.client.NetworkingV1Api instance """ logger.debug('Retrieving K8s networking API client') return client.NetworkingV1Api(get_clie...
be57c7ba0558db35237b426dbfbc813b9f435ff4
3,632,034
import os def sequential_name(folder, basename): """ Given a proposed name for a file (string 'basename') to be saved in a folder (identified by its path in string 'folder'), produces a new name to use that avoids overwriting other files - as long as their names were made with this function, too. """ i...
1a1afd78371da050ef6e44aa909d8c800f82ac21
3,632,035
def metric_max_over_ground_truths(metric_fn, predictions, ground_truths): """Take the average best score against all ground truth answers. This is a bit different than SQuAD in that there are multiple answers **and** predictions that we average over. For some situations (e.g., *top k* beams or multiple human r...
7c78fc1cca29bc9784a4e4687d794c1f2b6872c9
3,632,036
def parse_gsod_data(filename): """Parse Global Summary of the Day (GSOD) data from a comma separated .txt file. Source: https://www7.ncdc.noaa.gov/CDO/cdoselect.cmd?datasetabbv=GSOD&countryabbv=&georegionabbv= Format Specification: https://www7.ncdc.noaa.gov/CDO/GSOD_DESC.txt Parameters: ...
963444222e7627c25354ec6d0d891df4fee4fe8c
3,632,037
def deserialize(xml): """ Deserializes a Pubmed response into an article object.""" article = {} root = ET.fromstring(xml) article_el = root.find('.//PubmedArticle') if article_el is None: print('INFO: XML did not contain a Pubmed Article.') return None pmid_el = article_el.find('.//MedlineC...
5cdb8c622f9155eaf36659bd9cab092e3adc4c44
3,632,038
def attSummaryDict(request, reqs, flist): """ Return a dictionary summarizing the field values for the chosen most interesting fields """ sumd = {} for req in reqs: for f in flist: if f in req and req[f]: if not f in sumd: sumd[f] = {} if not req[f] i...
bafbbe51555cb46c664d33ea31a0e36c56152fa9
3,632,039
def immutable_kwargs( kwargs: tp.Dict[str, str] ) -> tp.Tuple[tp.Tuple[str, str], ...]: """ Convert str-typed kwargs into a hashable tuple. """ return tuple((k, v) for k, v in kwargs.items())
900e263e0a7928bfb2c65e3dc7f9c8e405014fb5
3,632,040
import os def get_markings(catalogue_dir, cid, result): """ Take a directory of catalogue entries and extract the specific metadata related to CID Add it to fields as defined in serene_metadata """ catalogue = load_markings(os.path.normpath(catalogue_dir)) catalogue_markings = catalogue[cid...
c4ad3863559e35b55993771d5b02ee274da9fea0
3,632,041
import numpy def revise_max_intake( max_intake, total_digestibility, energy_intake, energy_maintenance, degr_protein_intake, protein_req, animal_type, CRD1, CRD2): """Calculate revised maximum intake from protein content of the diet. When animals are unable to obtain enough protein from the d...
cfe61d2717fcf42104423499e1e1343873c905a0
3,632,042
from pegasusio.cylib.io import read_fcs def load_fcs_file(input_fcs: str, genome: str = None) -> MultimodalData: """Load Cyto data from a FCS file, support v2.0, v3.0 and v3.1. Parameters ---------- input_fcs : `str` The FCS file. genome : `str`, optional (default None) The genom...
232b849679c209863fdc3cc17ad1dc254ed23ab0
3,632,043
def ext_bottom_up_cut_rod(price, length): """ bottom up implementation of cut rod memoized algorithm """ incomelst = [float("-Inf") for _ in range(length + 1)] cutlst = [0 for _ in range(length + 1)] # set zero income for zero length incomelst[0] = 0 for j in range(1, length + 1): income...
7dd8c43afa9f71793d372b474963ff84d2ce607f
3,632,044
def _build_config_dict(cfg_node): """ Updates the config dict provided from the given etcd node, which should point at a config directory. """ config_dict = {} for child in cfg_node.children: key = child.key.rsplit("/").pop() value = str(child.value) config_dict[key] = va...
567fca19a6e1890c881170200ba44fc262148948
3,632,045
import time def stamp_to_ymd(timestamp): """ Caller sends a timestamp in seconds of epoch. Return string for year month day of that time as YYYYMMDD' as used by url requests, as in http://<fitsstore_server>/qaforgui/20130616 parameters: <float>, seconds of epochs. return: <string>, YYYYM...
2928e93a48f1a5c3abdddcb6285bed7b0cebb369
3,632,046
def ESMP_GridCreateCubedSphere(tilesize, regDecompPTile=None, #decompFlagPTile=None, deLabelList=None, staggerLocList=None, name=None): """ Preconditions: ESMP has been initialized.\n Postconditions: An ESMP_Grid has been created.\n Arguments...
999d9b995671af9e410f73e29b2e1af8d79ad5a4
3,632,047
def extract_asymbox2(image,left_in,right_in, ycen=None, weight_image=None): """ Extract the total flux within a variable window at many positions. This routine will accept an asymmetric/variable window specified by the left_in and right_in traces. The ycen position is optional. If it is not provied, it is assu...
34a7b2bf8ea79023f6847469ceafe376ef4d3fd0
3,632,048
import os def exists(b, d, n): """Check if the folder specified by the given parameters exists""" return os.path.isdir("../Output/B" + str(b) + " D" + str(d) + " N" + str(n))
b94f8bfb38351127e77fa9f19b706906d9805e82
3,632,049
def version() -> str: """版本号""" return f'Version: {VERSION}'
df0dee3edebdaf24b52a9ad128b5198c89c779a5
3,632,050
import ctypes def UnpackMessage(swig_obj_pointer, msg_name): """Unpack a SWIG-wrapped memory object into an AIO message. Args: swig_obj_pointer: A SWIG-wrapped memory object pointing to the raw AIO message payload. msg_name: Name or short name of the message type. Returns: An AIO message s...
2e445f5248ba023190298eec30e0e473804f3df5
3,632,051
def a2b_hashed_base58(s): """ If the passed string is hashed_base58, return the binary data. Otherwise raises an EncodingError. """ data = a2b_base58(s) data, the_hash = data[:-4], data[-4:] if double_sha256(data)[:4] == the_hash: return data raise EncodingError("hashed base58 ha...
82276533405e952f8f89cf3caefce6e653ab5694
3,632,052
def predict(theta, X): """ computes the predictions for X using a threshold at 0.5 (i.e., if sigmoid(theta'*x) >= 0.5, predict 1) """ return np.array([1 if theta.dot(xi) >= 0.5 else 0 for xi in X])
3a80add19d08989f94cb3f9e4c058a37bd128f20
3,632,053
def not_contains(a, b): """Evaluates a does not contain b""" result = False if b in a else True return result
a0dc087049c8e93c1acdf0e59e3530a6ff8b54e5
3,632,054
def build_positional_encoding(cfg, default_args=None): """Builder for Position Encoding.""" return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args)
9db2eb7d88b5d4ceea0a9d62adc3239035a34cec
3,632,055
def create_func_result_identifier(func, params_str, key=None, key_separator="__"): """ Creates a string of the following format: If ``key`` is None: ``<FUNC_NAME><PARAMS_STR>`` If ``key`` is not None: ``<FUNC_NAME><PARAMS_STR>__key`` In both cases, ``<FUNC_NAME>`` represents the name of...
6f3a7a6a8a94629dae7817403d78ef1f970ad5b2
3,632,056
def quat_to_euler(q): """ Converts a unit quaternion: q = (w, x, y, z) = w + (x i, y j, z k) into the aircraft Euler angles (roll, pitch, yaw) = (phi, th, psi). """ R00 = 1 - 2*q[2]**2 - 2*q[3]**2 R10 = 2*q[1]*q[2] + 2*q[3]*q[0] if np.sqrt(R00**2 + R10**2) >= .000001: phi = np...
507e26d657a868bc136c901612ffba5dff62975d
3,632,057
def idc_get_local_type_name(*args): """ idc_get_local_type_name(ordinal) -> char """ return _ida_typeinf.idc_get_local_type_name(*args)
c0921c70f0f42d913bbbe4e6d41a02a58660da0e
3,632,058
import csv def import_town(data_file): """ Reads town raster data from a CSV file. Parameters ---------- data_file : str Name of CSV raster data file to use for the town. Returns ------- town : list List (cols) of lists (rows) representing raster data of the town. ...
b7749dfd4d698fddfe610c6a51c8ccc43c375cc2
3,632,059
def init_network(): """신경망(neural network)에서 사용되는 가중치 행렬과 bias 행렬을 생성 교재 p.88 입력층: (x1, x2) -> 1x2 행렬 은닉층: - 1st 은닉층: 뉴런 3개 (x @ W1 + b1) - 2nd 은닉층: 뉴런 2개 출력층: (y1, y2) -> 1x2 행렬 W1, W2, W3, b1, b2, b3를 난수로 생성 1x2 2x3 3x2 """ np.random.seed(1...
ddf727e651d46523f83d5d4e870c26e6bbc0b54c
3,632,060
def reduce_detections(detections, detection_indices, img_w, img_h): """ Removes overlapping detections Important note: Tensorflow detections are already sorted by detection score! (optional) TODO: Could tweak this paramter based on num of faces (2 ears, 1 of each class, per pers...
d774f88eaa91c79b6e9982520a836a4f5e1fb609
3,632,061
import os def load_fiveplates_summary(platerun): """ """ summary_file = paths.fiveplates_summary(platerun) if summary_file.exists(): pass else: raise FileNotFoundError(os.fspath(summary_file)) return Table.read(os.fspath(summary_file), format='ascii')
4abd9d534647546a793f796bd006e2ff19474a48
3,632,062
def make_connection(): """Connection function to establish database connection. During development, the connection information will be hard coded, however during actual deployment to AWS, the connection information will be retrieved from other services eg aws secret manager etc. Returns: ...
fa69c2752444cbee1d5630ee829bd5ebc4c0e0c5
3,632,063
import random def a_noun(random=random, *args, **kwargs): """ Return a noun, but with an 'a' in front of it. Or an 'an', depending! >>> mock_random.seed(0) >>> a_noun(random=mock_random) 'an onion' >>> a_noun(random=mock_random, capitalize=True) 'A Chimp' >>> a_noun(random=mock_random...
1eae1f7b445017d64fc17fe0364275d73ead1b87
3,632,064
def _tree_flatten_with_names(tree): """Populates tree_flatten with leaf names. This function populates output of tree_flatten with leaf names, using a custom traversal that produces names is provided. The custom traversal does NOT have to traverse tree in the same order as jax, as we take care of automatical...
2878ece5d63d09d42d4b195706a4594b135ce849
3,632,065
def inhomogeneous_poisson_process(rate, as_array=False, refractory_period=None): """ Returns a spike train whose spikes are a realization of an inhomogeneous Poisson process with the given rate profile. Parameters ---------- rate : neo.AnalogSignal A `n...
240b04f5e5ed316d911aad0ee690516982f123cd
3,632,066
import re def enumerate_quotes(filename, encoding="utf-8", empty_name="Inconnu"): """ Enumerates quote from a filename or a stream @param filename filename or stream @param encoding applicable only if filename @param empty_name replces an empty author name @r...
51e3a406c05ab81ade918123ee4fba801fb9ef9e
3,632,067
def _params_to_df(params: Parameters) -> DataFrame: """Convert lmfit.Parameters to pandas.DataFrame.""" return DataFrame( [ (p.name, p.vary, p.value, p.stderr, p.min, p.max, p.brute_step, p.expr) for p in params.values() ], columns=( "name", ...
7485f43a474eef1ebb20ddb73bb411dad52cd918
3,632,068
def w(P, T, region = 0): """ Speed of sound [m / s]""" if region is 0: region = idRegion(P, T) if region is 1: return region1.w(P, T) elif region is 2: return region2.w(P, T) else: return 0.000
7589c57071484d0f46e67a18bd125ad46edbe777
3,632,069
def WaitForOperation(api_version, response, asynchronous): """Handles waiting for the operation and printing information about it. Args: api_version: Cloud Domains API version to call. response: Response from the API call asynchronous: If true, do not wait for the operation Returns: The last inf...
518e68421082bb3a2a90b38ae62c5be02f20d9fb
3,632,070
from datetime import datetime def generateVtBar(symbol, d): """生成K线""" bar = VtBarData() bar.symbol = symbol bar.vtSymbol = symbol bar.open = d['open'] bar.high = d['high'] bar.low = d['low'] bar.close = d['close'] bar.volume = d['volume'] bar.openInterest = d['open_oi'] ...
d155bda31fba71f07af4d23d17fcaa09c6a277e4
3,632,071
def produce_validation_report(stages, jobs, validation_json, **kwargs): """Produce validation report inside CI pipeline. @param stages: the GitLab CI stages to consider @param jobs: the job names to consider @param validation_json: local job path to validation JSON output @return summary of valida...
bdcb0c87db61c78766bd3afddc1cd74737a43b51
3,632,072
def search_file(drive_service, num_of_responses, query): """ Search for files and store results of query in pd.DataFrame """ results = ( drive_service.files() .list( pageSize=num_of_responses, q=query, fields="nextPageToken, files(id, name, kind, expor...
b7bb340f0c1bb89bc76ecc420b473609a0bbbb2c
3,632,073
from datetime import datetime import numpy def L6_summary_daily(ds,series_dict): """ Purpose: Calculate the daily averages or sums of various quantities and write them to a worksheet in an Excel workbook. Usage: L6_summary_daily(ds,series_dict) where ds is an OzFluxQC data structure ...
d1f57bb364abd7c92b73eab2d9787f5893264a3c
3,632,074
def check_eol(file, eol): """Check file EOL. :param file: Path to file to check :param eol: Expected End of Line :return: Resulting error messages :rtype: str """ error = '' with open(file, 'rb') as open_file: content = open_file.read() if eol == '\n': if b'\r\n' i...
44bb060531c50ab5d072906414b8c948c9d6ecfa
3,632,075
def pe44(limit=1500): """ >>> pe44() (5482660, 7042750, 1560090, 2166, 1019) """ pents = [i * (3 * i - 1) >> 1 for i in range(1, limit << 1)] ps = set(pents) for i in range(limit): p1 = pents[i] for j in range(i + 1, (limit << 1) - 1): p2 = pents[j] di...
e41f513c518b502de0c47f3a70390f9df01a1868
3,632,076
import re def text_cut(questions): """ This def will cut the text into words by jieba and del the stopwords then return the words,else return a string when fail to find the stop_list. :param questions: A list of text. :return: A list of cut-words Raises: FileNotFoundError: An error occurred se...
c7cc8e52265b6e7cbe222d899952ee2ddc13231d
3,632,077
import logging import sys def mask_3D(hPa, sect, MBL=True, res='4x5', extra_mask=None, M_all=False, use_multiply_method=True, trop_limit=False, verbose=True, debug=False): """ Creates Maskes by pressure array (required shape: 72,46,47), with conditions (lower and upper bounds) set...
b44124174b8c9ed82989d31f6b5a4ed6b43d73a0
3,632,078
def export_visible_cells( self, export_keyword="FLUXNUM", visible_active_cells_value=1, hidden_active_cells_value=0, inactive_cells_value=0, ): """Export special properties for all visible cells. Arguments: export_keyword (string): The keyword to export. Choices: 'FLUXNUM' o...
e7f03371a7c14385a2039ccb597e7e464f54b4f1
3,632,079
def sanitize_markdown(markdown_body): """ There are some symbols used in the markdown body, which when go through Markdown -> HTML conversion, break. This does a global replace on markdown strings for these symbols. """ return markdown_body.replace( # This is to solve the issue where <s> and...
adf21a9bbea1a95f0f4c0aca8d61ab6d69627074
3,632,080
def ProjectsInsightTypeInsightsService(api_version): """Returns the service class for the Project insights.""" client = RecommenderClient(api_version) return client.projects_locations_insightTypes_insights
7173907ad599fd4457050a2fb1d15d01d19098cf
3,632,081
def get_course_dict(only_active=True): """ Return a dictionary of courses. By default only active courses. key will be course ID. courses[cid] = {id:, name:, title:} """ cdict = {} reload_if_needed() for course in COURSES: if only_active: if COURSES[cours...
6e538b473224274c5ec7e8db17975c934e126c44
3,632,082
def _build_jinja2_expr_tmp(jinja2_exprs): """Build a template to evaluate jinja2 expressions.""" exprs = [] tmpls = [] for var, expr in jinja2_exprs.items(): tmpl = f"{var}: >-\n {{{{ {var} }}}}" if tmpl not in tmpls: tmpls.append(tmpl) if expr.strip() not in exprs: ...
3e5d944345316a40b7b8052f9b13801228607099
3,632,083
def create_blueprint(app): """Register blueprint routes on app.""" routes = app.config.get("APP_ROUTES") blueprint = Blueprint( "{{cookiecutter.package_name}}_records", __name__, template_folder="../templates", ) # TODO: register your record views here. # Register temp...
28e8a6c1b54b2aeee4f901e110d9915c4f4f89f0
3,632,084
def normal(x, mu=0, sig=1): """ Normal distribution log-likelihood. :param x: *int, float, np.array.* :param mu: (optional) *int, float, np.array.* Location parameter of the normal distribution. Defaults to 0. :param sig: (optional) *int, float.* Standard deviatio...
fc88fd34b4c5e5be835c1d29b2f8f38b7f1f21b9
3,632,085
import optparse import platform def parse_args(args): """ Parse arguments """ parser = optparse.OptionParser() parser.add_option('--os', default=platform.system().lower(), help='Set the target os (default %default)') parser.add_option('--cc', default='gcc', ...
04d5c4c4168f04c2e4ec9de39a3a6c44a9c131e4
3,632,086
def BitmapFromImage(image): """ A compatibility wrapper for the wx.Bitmap(wx.Image) constructor """ return Bitmap(image)
4593506342bfd8b3f1bb3e6077031291a8eb87aa
3,632,087
def load_coco_name(path): """Load labels from coco.name """ coco = {} with open(path, 'rt') as file: for index, label in enumerate(file): coco[index] = label.strip() return coco
2da456b7c2879ec5725172280dacbcaaacd86bfc
3,632,088
def qsat(T, p) : """ Saturation vapour pressure. Derived variable name: qsat Parameters ---------- T : numpy array or xarray DataArray Temperature. (K) p : numpy array or xarray DataArray Pressure (Pa). Returns ------- qs : numpy array or xarray DataArray ...
2e257dade4531e49f813b3fb96b71f0298819509
3,632,089
def extract_features(df, action): """ 提取特征 :param df: DataFrame 样本(训练和测试) :param action: str action :return: x: DataFrame 特征 y: Series 标签 """ # 特征-训练每个任务都需要初始化 DENSE_FEATURE_COLUMNS = ['videoplayseconds'] # 1,特征处理 # dense df.fillna(value={f: 0.0 for f in DEN...
af648a66146d1af34777c85417745c55e95f0122
3,632,090
def quick_sort(input_list): """Quick sort.""" if not isinstance(input_list, (list, tuple)): raise ValueError('input takes list/tuple only') if isinstance(input_list, (tuple)): input_list = list(input_list) if not all(isinstance(val, (int, float)) for val in input_list): raise V...
41224487ab352dc88ebd39007a02cf2fe2993651
3,632,091
from typing import List def validate_execution_order(relations: List[RelationDescription], keep_going=False): """ Make sure we can build an execution order. We'll catch an exception and set a flag if the keep_going option is true. """ try: ordered_relations = etl.relation.order_by_depende...
773303496c3a0ac62e195ea62622e4605acb19fc
3,632,092
def now(): """Returns a java.util.Date object that represents the current time according to the local system clock. Returns: Date: A new date, set to the current date and time. """ return Date()
4d32130ed1af12370012186084b270dde6fdd986
3,632,093
def create_session_factory(session_id_store, backend_store, *, loop=None): """Creates new session factory. Create new session factory from two storage: session_id_store and backend_store. """ return _SessionFactory(session_id_store=session_id_store, backend_store=backend_...
c8f302af26894e16f5a24aa9ca460400746fed06
3,632,094
import os async def get_mnemonic(strict=False): """Attempt to gather a mnemonic from one of the available sources First, if a mnemonic is defined in the env, use that. Next, check the config file for the secret If no mnemonic can be found, optionally raise an Exception Args: strict ...
b0056eb251c4426ab252ceb1a628a7ef3e057ab9
3,632,095
def process(callable_, *args, **kwargs): """ Submit a callable to a background process. Return an proxy object for the future return value. NOTE: Use only, if you really need control over the type of background execution. """ return _submit(callable_, 'cpu', *args, **kwargs)
ac596fef8e72f1ba65450928aba9ea173764d564
3,632,096
def encode_entities(string): """ Encodes HTML entities in the given string ("<" => "&lt;"). For example, to display "<em>hello</em>" in a browser, we need to pass "&lt;em&gt;hello&lt;/em&gt;" (otherwise "hello" in italic is displayed). """ if isinstance(string, basestring): string = ...
949d76b25ff65020b3b560a0fd984107c13d1bfb
3,632,097
import os def load_node_handle(fname, mode="r"): """ Read a conduit file node handle. Does not read into memory. """ if os.path.exists(fname): options = conduit.Node() options["mode"] = mode handle = conduit.relay.io.IOHandle() handle.open(fname, options=options) ...
dce4c6aa262e6ae27ea0804959459dbeb20348eb
3,632,098
async def upload_data_generation_file( background_tasks: BackgroundTasks, doc: UploadFile = File(...), current_user: User = Depends(auth.get_current_user_and_bot) ): """ Uploads document for training data generation and triggers event for intent creation """ TrainingDataGenerationProcessor.i...
742f61a13491f2fe84301d3bcd9c5f5ee18e3df0
3,632,099