content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def computeRealExpectation(params1, params2, angles, backend): """ Computes the real part of the inner product of the quantum states produced by acting with U(θ) characterised by two sets of parameters, params1 and params2. """ qreg = QuantumRegister(2) anc = QuantumRegister(1) creg ...
5a800a7f543c4d54e58d3d4a122fa3b428bd67a2
3,623,300
def green_on_black(string, *funcs, **additional): """Text color - green on background color - black. (see sgr_combiner()).""" return sgr_combiner(string, ansi.GREEN, *funcs, attributes=(ansi.BG_BLACK,))
50311029d1659d09ade8a9cb6b5eff191bcc7424
3,623,301
from typing import List from typing import Any def format_params_diff(parameter_diff: List[DictValue[Any, Any]]) -> str: """Handle the formatting of differences in parameters. Args: parameter_diff: A list of :class:`DictValue` detailing the differences between two dicts returned by :func:...
85022afae55b7b06715d0bf675e29db1f129ecda
3,623,302
import hashlib import gzip def hashfile(path, hasher=None, blocksize=65536): """ A function to hash files. See: http://stackoverflow.com/questions/3431825 """ if hasher is None: hasher = hashlib.md5() try: try: f = gzip.open(path, "rb") buf = f.read(blocksize...
44946dfa3eeb1c82353b3470423a3a4f699c1d9d
3,623,303
def EditFragNeighborIds(fnids: list, bbtps: list) -> list: """Remove fragment neighbor ids that are doubly/triply bonded to fragment.""" # not double/triple bonds n23bonds = [ [ (x != Chem.rdchem.BondType.DOUBLE and x != Chem.rdchem.BondType.TRIPLE) for x in y ] ...
655e229422ac0b212e35bc43fea3a65372a0e666
3,623,304
def db_add_game(game: str, channel: str, set_default_game: bool=False) -> bool: """Adds a game to the database for a channel, does not allow duplicates """ if not db_check_for_duplicate(game, channel): return False else: if set_default_game: default = "YES" else: ...
ab47a57f94428afe84c45d6ed4d1608079562bd8
3,623,305
import json import sys import os def get_ip_from_mac(): """ A HTTP GET function to fetch the IP address for mentioned MAC and Subnet in the JSON request parameters Parameters --- mac_address : subnet_id : <int> : Subnet ID """ LOGGER.info("Request url -> /d...
ab91c7f2aac90d9c7c496c3fc7532c5aa170177c
3,623,306
def _proxy_for_evolvable_object(obj): """ :returns: an ``_IRecursiveEvolverProxy`` suitable for the type of ``obj``. """ if not _IEvolvable.providedBy(obj): raise TypeError( "{!r} does not provide {}".format( obj, _IEvolvable.__name__ ) ...
c5c71484e392cf387cc4259c3c3c2df13385b60d
3,623,307
from pathlib import Path import argparse def dir_abs_path(path_str: str) -> Path: """ Validate directory `path_str` and make it absolute. Arguments: path_str -- A path to check. Returns: An absolute path. Raises: argparse.ArgumentTypeError -- If path is not a directory. ...
8fc8a3c5fbb7555bf6b2e6e76d40b8c32aa4e001
3,623,308
from typing import List def parse_download_data(data: List[AnimeThemeAnime]) -> List[DownloadData]: """ Parses a list of animethemes api returns for anime. Returns download data. """ out = [] songs = set() for anime in data: last_group = None for tracknumber,t...
b91db9b9eb5c0c34fe7dcf6b03e64ea7e0976cbb
3,623,309
def parse_glyphs_groups(names, groups): """ Parse a ``gstring`` and a groups dict into a list of glyph names. """ glyph_names = [] for name in names: # group names if name[0] == '@': group_name = name[1:] if group_name in groups: glyph_names +...
50e79acffdc6d26576e8524b52219afad3e40a4e
3,623,310
from typing import Sequence from typing import Mapping def ensure_strings_have_quotes_sequence(sequence_object): """Ensures Sequence objects have quotes on string entries. Args: sequence_object (iter): A python iterable object to ensure strings have quotes. Returns: iter: The ``sequence_...
a0299f52b4d16816a00002fbc8ef14f64645ac2c
3,623,311
import argparse def set_parser(): """ set custom parser """ parser = argparse.ArgumentParser(description="") parser.add_argument("-r", "--regions", nargs='+', required=False, default=['R1', 'R2', 'R3'], help="The regions to train on (default is R1 R2 R3)") parser.add_argu...
6f60e197401f6170f1edfb43e88777a59785540d
3,623,312
import json def patient_detail(request, pk): """ View to display patient details (name, ID, fractions) """ patient = get_object_or_404(Patient, pk=pk) fractions = Fraction.objects.filter(patient=pk) url = 'doseapp/static/doseapp/tolerances.json' json_data = open(url)# False tolerances ...
91518c26e092f75024689d29be586472252f4652
3,623,313
def event_fixture(): """Return a received event from the websocket client.""" return { "type": "event", "event": { "source": "node", "event": "value updated", "nodeId": 52, "args": { "commandClassName": "Basic", "com...
4866641f285ca65003c3dada9c2f406ae2f5d218
3,623,314
import os import requests def check_urls(file, urls): """ check urls extracted from a certain file and print the checks results. Args: file (str) : path to file. urls (list) : list of urls to check. """ # get longest url size long_url = str(max([len(url) for url in urls])) ...
58a2ca633b66252b2e94cbcfb411dc5010bc7c99
3,623,315
import tempfile import os import requests import tarfile import json import subprocess def run_dcos_engine(dcos_engine_url: str, dcos_engine_template): """ Runs the dcos-engine """ tmpdir = tempfile.mkdtemp() # pull down dcos engine in temp dir download_path = os.path.join(tmpdir, 'download.tar.gz...
755538defc135e9ce3c9af32215cfc9bbabde04e
3,623,316
def tf_idf(train_data, test_data, weight_type, sentence_type): """ :param train_data: :param test_data: :param weight_type: :param sentence_type: :return: """ tfidf_vectorizer = TfidfVectorizer(ngram_range=(1,2),max_df=0.9, min_df=3, use_idf=1, smooth_idf=1, sublinear_tf=1) # tfidf_...
22cd362dc350a2039c919233d9a799d40c413e25
3,623,317
import subprocess def get_workspace_diff(workflow_a, workflow_b, brief=False, context_lines=5): """Return differences between two workspaces. :param workflow_a: The first workflow to be compared. :type: reana_db.models.Workflow instance. :param workflow_b: The second workflow to be compared. :typ...
94dfc4c9ab552d5021e01e172a64f04e0a3ae67f
3,623,318
def receive_product_view(sender, product, user, request, response, **kwargs): """ Receiver to handle viewing single product pages Requires the request and response objects due to dependence on cookies """ return CustomerHistoryManager.update(product, request, response)
880954a38b79fc7a3443d015a22758c503fb28bb
3,623,319
from typing import Union from typing import List from datetime import datetime def bulk_create_entries( es_client: elasticsearch.Elasticsearch, es_index: Union[str, UUID], journal_id: Union[str, UUID], entries: List[JournalEntryResponse], ) -> str: """ Index a new entry in a journal. Returns t...
24ea4c618feac971f05b3a795b81bfaa5b943068
3,623,320
def norm_density(matrix: np.ndarray): """ Calculate normalized density for a given activity matrix. :param matrix: activity matrix :return: normalized density value """ return 1 - abs(1 - 2 * (np.count_nonzero(matrix) / matrix.size))
a6fed6febc697cc84d1691b9f95dbb04cd6eba9e
3,623,321
def kernel(a, b, length_scale=1.): """ GP squared exponential kernel """ n = a.shape[0] m = b.shape[0] K = np.zeros(shape=(n, m), dtype=float) for i in np.arange(n): for j in np.arange(m): dif = a[i, :] - b[j, :] sqdist = dif * dif.T if sqdist.shape[0] != ...
e15d1c755ed607dae5046d5f2ebee01e7ffaf808
3,623,322
def str_id(qualified_name): """Return PROVN representation of a URI qualified name. Params ------ qualified_name : QualifiedName Qualified name for which to return the PROVN string representation. """ return qualified_name.provn_representation().replace("'", "")
ff1cf6614a098818e8a70de105d7bfb7810548dc
3,623,323
def detect(text_proposals, scores, size): """ Detect text boxes Args: text_proposals(numpy.array): Predict text proposals. scores(numpy.array): Bbox predicts scores. size(numpy.array): Image size. Returns: boxes(numpy.array): Text boxes after connect. """ keep_pr...
6030a0e859c2fabc4ca6ad89470fca0da937be0e
3,623,324
import requests from bs4 import BeautifulSoup def GetImage(): """ 获得Bing壁纸 """ url = 'https://cn.bing.com' # 请求标头 # 获取页面并转为dict格式 req = requests.get(url=url) req.encoding = req.apparent_encoding soup = BeautifulSoup(req.text, 'html.parser') # 用BeautifulSoup库解析网页 head = soup.he...
e451628d54b5ae7894d1dbbd9339e98c6e3dad37
3,623,325
def csr_load(data, prefix=None): """ Rematerialize a CSR matrix from loaded data. The inverse of :py:func:`csr_save`. Args: data(dict-like): the input data. prefix(str): the prefix for the data keys. Returns: CSR: the matrix described by ``data``. """ if prefix is None...
9899ee559e7e5e8d7dcf5aceab6bde895127e5b8
3,623,326
def perc_range(n, min_val, max_val, rounding=2): """ Return percentage of `n` within `min_val` to `max_val` range. The ``rounding`` argument is used to specify the number of decimal places to include after the floating point. Example:: >>> perc_range(40, 20, 60) 50 """ ret...
379515f6c0483b4bfed93d0c1012bb2ca111e410
3,623,327
import asyncio async def test_upgraded_extended_version_sync_analysis_module(concurrency_mode, redis_url, manager): """Tests the ability of a sync analysis module to update extended version data.""" # we want to bail after the first execution of the module class CustomAnalysisModuleManager(AnalysisModule...
27811ae36c0ac7027938dff305d0b0b5a6a3d5c3
3,623,328
def _translate_tag_class(tag_class): """ Translate ASN.1 tag class names to pyasn1 equivalents. Defaults to tag.tagClassContext if tag_class is not recognized. """ return _ASN1_TAG_CONTEXTS.get(tag_class, 'tag.tagClassContext')
6abe7ce27b0904d1767a561ec403816bdc45c0b1
3,623,329
def memo(f): """Memoization for function $f$""" cache = {} @wraps(f) def wrap(*args): if args not in cache: cache[args] = f(*args) return cache[args] return wrap
084f6bbd212b25694ea512ba4c407085b4a2ca04
3,623,330
def expand_nested_tasks_or_globs(p, tasksglobs_to_filenames): """ Expand globs and tasks "in-line", unless they are the top level, in which case turn it into a list N.B. Globs are only expanded if they are in tasksglobs_to_filenames This function is called for @split descriptors which leave ou...
949f1c9f221c21470ba6f476f58a36a9e4ee35ce
3,623,331
from typing import List def process_experience( experience: List[List[agent.ExpTuple]], actor_steps: int, num_agents: int, gamma: float, lambda_: float): """Process experience for training, including advantage estimation. Args: experience: collected from agents in the form of nested lists...
234adfdc0b4abc7f4eb44e85bbd159a01a3b3e6d
3,623,332
def associateIpAddress(**kargs): """ Get additional public IP in Selected Zone * Args: - zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2] * Examples : print(server.associateIpAddress(zone='KR-M')) """ my_apikey, my_secretkey = c.read_config() if not 'zone' in kargs: retu...
84474d50ef8f47f7150791781c41a7b6ef86f6b4
3,623,333
def nltk_regex_tokenizer(input_dict): """ The Regex Tokenizer splits a string into substrings using a regular expression. :param :param pattern: The pattern used to build this tokenizer. (This pattern may safely contain capturing parentheses.) :param gaps: True if this tokenizer's pattern shoul...
df4bfb4f002e6588edabef99b65e29e7226ff131
3,623,334
def load_hetrec_to_df(data_dir_path, encoding='utf-8', ): """ Loads hetrec data into pandas DataFrame. Currently only minimal subset of data, containing info only about users movie rating (identified by pair user_id/movie_id) is being loaded. Note that nans/empty values in general are replaced with dumm...
39642fc609e7d52c93b6c06b957c8359fdfca758
3,623,335
def get_or_create_default_gcs_bucket(options): """Create a default GCS bucket for this project.""" if getattr(options, 'dataflow_kms_key', None): _LOGGER.warning( 'Cannot create a default bucket when --dataflow_kms_key is set.') return None project = getattr(options, 'project', None) region = g...
bd2e905c37984eb7b75021c7ef9ce8b81baf220f
3,623,336
def lab_to_xyz(image: tf.Tensor) -> tf.Tensor: """ Convert an image from LAB color space to XYZ color space Parameters ---------- image: tf.Tensor Returns ------- tf.Tensor : LAB image """ l, a, b = tf.unstack(image, axis=-1) var_y = (l + 16) / 116 var_x = a / 500 + var...
7534222c16c8d654eaad43515af54582af54ffb3
3,623,337
from datetime import datetime import os def get_index_constituents(constituency_matrix: pd.DataFrame, date: datetime.date, folder_path: str, print_constituents=False) -> pd.Index: """ Return company name list (pd.Index) of index constituents for given date :param print_constitu...
fbb53bf062cc1b07ce12269c61833d8566f1cc4f
3,623,338
def make_pairs(coords,pair_indices,offset=.01): """Returns list of Polygon objects, given a list of coordinates and indices. - coords: list of [x,y] coordinates, already scaled to matplotlib axes. - pair_indices: indices in the coordinate list that are paired. """ pairs = [] for fir...
21137de57e666f0789a115467bfc1a75df5e8631
3,623,339
def medialive_multiplexes(region): """ Return the MediaLive Multiplexes for the given region. Tags included. """ items = [] service_name = "medialive" if region in boto3.Session().get_available_regions(service_name): service = boto3.client(service_name, region_name=region, config=MSA...
5cb3a57b40d44d630c4ab720290451b98e76110d
3,623,340
import os import base64 def embed64(filename=None, file=None, data=None, extension='image/gif' ): """ helper to encode the provided (binary) data into base64. Args: filename: if provided, opens and reads this file in 'rb' mode file: if provi...
99e407191a0474da0dc47745a7472db12edf00a1
3,623,341
def sort_sequence_by_key(sequence, key_name, reverse=False): """ often when setting up initial serializations (especially during testing), I pass a list of dictionaries representing a QS to some fn. That list may or may not be sorted according to the underlying model's "order" attribute This fn sort...
fbe46c942ac35d5399450c6bba430a096e6b7503
3,623,342
from typing import Union from typing import List from typing import Dict from typing import Any def process_hdmedia(hdmedia: Union[List, Dict[Any, Any]]) -> Dict[Any, Any]: """Pull out the relevant HDMedia dictionary based on SAP code values :param hdmedia (list): list of HDMedia dictionaries""" # Note: H...
549867a866763459f58c1f4b7e8ffd14f0b7ab0a
3,623,343
def gauss_newton(x_init, model, cost_thresh=1e-9, delta_thresh=1e-9, max_num_it=10): """Implements nonlinear least squares using the Gauss-Newton algorithm :param x_init: The initial state :param model: Model with a function linearise() the returns A, b and the cost for the current state estimate. :par...
abdb34810c1fa5d393649b8ca9ba125ec8535ad6
3,623,344
def SRCNNex(input_shape= (None, None, 3), depth_multiplier=1, multi_output=False): #33.12 """ Implementation of SRCNNex. The kernel size of the mapping layer is increased from 1 to 5. @ multi_output : set to True """ inputs = Input(input_shape, name="inputs") # normalize value betw...
565edc3be6e4e35af0dddf1ce2a19c96b6b2f27b
3,623,345
def identity() -> GradientTransformation: """Stateless identity transformation that leaves input gradients untouched. This function passes through the *gradient updates* unchanged. Note, this should not to be confused with `set_to_zero`, which maps the input updates to zero - which is the transform required f...
16700a32bc9b17a6c5f7f8f64e2affb0be746740
3,623,346
import logging import os import sys def setup_ngrok(): """ Build ngrok tunnel for inbound webhook calls """ logging.info("ngrok enabled. Spinning up tunnels...") # Get Auth token: NGROK_AUTH_TOKEN = os.environ.get("NGROK_TOKEN") if not NGROK_AUTH_TOKEN: logging.error("Missing conf...
8e7d547d961a923e17d3afbd79a17e20b92f619a
3,623,347
def width_from_bitdefs(bitdefs): """ Determine how wide an binary value needs to be based on bitdefs used to define it. Args: bitdefs (list(BitDef)): List of bitdefs to find max width of Returns: (int): Maximum width """ max_index = max([bitdef.end for bitdef in bitdefs]) ...
59503f335d6d427579be730806c738108091e9ed
3,623,348
import sys import json def mercury(url, mercury_cli_path): """Wrap the Mercury Parser command line driver url: URL string to parse mercur_cli_path: path to mercury-parser command line driver """ response = muterun_js( mercury_cli_path, url ) if response.exitcode != 0: ...
7ccfe3aae17d4539653adc9861cfe335a18cd118
3,623,349
def _mkdir_recursive_local(uri, local=None): """ Recursively create local directory specified by URI. Args: uri: parsed URI to create. local: local context options. Returns: On success: True. On failure: False. """ # same as the non-recursive call return _m...
2902fe96a8aa8169e6a686681496e4c0a633dcb0
3,623,350
import subprocess def build_docs(): """Build docs for package """ subprocess.check_call(['scons', '-f', 'src/SConstruct']) return ['doc/spowtd.1', 'doc/user_guide.pdf']
03415279da466d496f12cc674bce2ee0c0ec73ed
3,623,351
def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to fi...
41e93460afba46cafb3d88986f36312dad7c4fb9
3,623,352
def get_intersection_over_union(first_segmentation, second_segmentation): """ Computes intersection over union (IoU) between two segmentation maps. Maps are binary - that is their values are 0s and 1s only. IoU is computed between non-zero elements of both segmentation maps. :param first_segmentatio...
d313d6117bd14fbe242697c6e28136e036981465
3,623,353
def logLikelihood(params, main_time_series, reply_time_series, verbose=False): """Log-likelihood object function""" " The log-likelihood fucntion is composed with main post stream and reply post stream events " " ...
66e8ae4c481fe6973969656f8f0bf9de852349a9
3,623,354
def getAnglesFromDict(d):# NOTE Fails currently if dict is None """ Converts a dictionary to a angles of a JointState() :param d (dict): The dictionary to be converted :return (sensor_msgs.msg.JointState): The angles """ # print datapath if d is None: rospy.loger...
9af5671cfa3d5e26d8a47812a57eaf85b0a0d3ad
3,623,355
import string def generate_randomkey(length): """Generate random key, given a number of characters""" chars = string.ascii_letters + string.digits return ''.join([choice(chars) for i in range(length)])
143d9053b3b2fdfbf02fb5e19760ba711f0585ee
3,623,356
def get_vectorized_series(text_series, vectorizer): """ 사전 훈련된 벡터화 객체를 사용해 입력 시리즈를 벡터화합니다. :param text_series: 텍스트의 판다스 시리즈 :param vectorizer: 사전 훈련된 sklearn의 벡터화 객체 :return: 벡터화된 특성 배열 """ vectors = vectorizer.transform(text_series) vectorized_series = [vectors[i] for i in range(vectors...
31c9d550d60443da41277833c2f79be66238951a
3,623,357
def _gen_request_slices(**kwargs): """Creates a TaskRequest.""" now = utils.utcnow() args = { u'created_ts': now, u'manual_tags': [u'tag:1'], u'name': u'Request name', u'priority': 50, u'task_slices': [ task_request.TaskSlice(expiration_secs=30, properties=_gen_properties()), ], ...
3874e4f6abfe3b22cd9916e20874eb54ee68fb73
3,623,358
def idm_cutin_pars(**kwargs): """ Define the parameters for the IDM model in a cut-in scenario. The reaction time is sampled from the lognormal distribution mentioned in Wang & Stamatiadis (2014) if it not provided through kwargs. :param kwargs: Parameter object that can be passed via init_simulation....
694da1c2635a998981168b16c77f0176aa9032c8
3,623,359
import os def extractcode(ctx, input, verbose, quiet, shallow, replace_originals, ignore, *args, **kwargs): # NOQA """extract archives and compressed files found in the <input> file or directory tree. Archives found inside an extracted archive are extracted recursively. Extraction for each archive is do...
7dab336682af54d7be6952d8719012e4fa6b0cdd
3,623,360
def profile(request): """A view handler for fetching the user's profile data.""" profile_id = begin(request) request_id = param_or_null(request, "request_id") cursor = connection.cursor() cursor.execute("""SELECT p.username, p.real_name, p.em...
0a9b6fe68bfd000cfe6cc0a11065609ca7eadacd
3,623,361
def snapshot_stabilizer(self, label): """Take a stabilizer snapshot of the simulator state. Args: label (str): a snapshot label to report the result. Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. Additional Information...
6678c3d2f33db7073e0a3ddc97a612cf1f621f14
3,623,362
def normalise_composition(comp): """Normalise rows of an array to unit sum, i.e. rows are compositional vectors.""" s = comp.sum(axis=-1) if type(s) is float: return comp / s return comp / s[..., np.newaxis]
e7387c5e068078aa62c64ed8dbdfab445241eecf
3,623,363
from typing import Sequence import difflib def _validate_magics_with_black(before: Sequence[str], after: Sequence[str]) -> bool: """ Validate the state of the notebook before and after running nbqa with black. Parameters ---------- before Notebook contents before running nbqa with black ...
e6e655f2e6ea5e8d055f27e8da14cf0233c0c202
3,623,364
def segment_denoise(rec_vol, rhos): """This function computes the segmentation of the denoised image. :param rec_vol: The reconstruction (np.array_like) :param rhos: The segmentation target levels (np.array_like) :returns: The segmented image :rtype: np.array_like """ prnt_str = "Solving w...
dd9b8ebf0f25128aa1ed72eda0b31a47015ec363
3,623,365
import os import tempfile def _select_variable(work_dir,infile,variablename,remove=False): """ select variables from infile """ cdo=Cdo() oname=work_dir + os.sep + "temp" + os.sep + tempfile.NamedTemporaryFile().name.split('/')[-1] cdo.selname(variablename,input=infile,output=oname,options='-f nc4 -b ...
ba8cdbc5c7016db5474f15eece5ec9cea38a45d6
3,623,366
import requests import json import random def get_gelImage(tags): """Returns pictures from Gelbooru with given tags.""" tags = list(tags) formatted_tags = "" rating = "" ratings = { "re": "rating%3aexplicit", "rq": "rating%3aquestionable", "rs": "rating%3asafe" } ...
1ad643483d96ab53dd217b14dae6cfa5febc3d44
3,623,367
def deriv_MCP(w, alpha=1., g=3): """Derivative of the MCP, w > 0""" return (w < alpha * g) * (alpha - w / g)
0982f3354650d0cc5a9cbc14dbce9b007f56239b
3,623,368
def bidirectional_rnn(cell_fw, cell_bw, inputs, initial_state_fw=None, initial_state_bw=None, dtype=None, sequence_length=None, scope=None): """Creates a bidirectional recurrent neural network. Similar to the unidirectional case above (rnn) but takes input and builds i...
03c5901c6153863cbeab5331dbc2399dace443ca
3,623,369
def get_colors(): """ Returns a list of all the available color constants. :rtype: list of :py:class:`Color` """ return GraphicsWindow.colors
68b96a78c82b8fd2a2aafdecea5c7cc7427934d7
3,623,370
def area_circ(r_in): """Calculates the area of a circle with given radius. :Input: The radius of the circle (float, >=0). :Returns: The area of the circle (float).""" if r_in < 0: raise ValueError("The radius must be >= 0.") area_out = np.pi * r_in**2 print("The area of a circle with ra...
4748f2b161d80557243826e21ce8801c3a19f088
3,623,371
def _ve_pdg_format_ ( ve , latex = False ) : """Round value/error accoridng to PDG prescription and format it for print @see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf @see section 5.3 of doi:10.1088/0954-3899/33/1/001 Quote: The basic rule states that if the three highest orde...
7ad0b158810aadcd34c39e5b9b5ee647e2fdabbd
3,623,372
import re def parse_stdout_data(stdout): """解析输出 Args: stdout ([byte]): 标准输出 Returns: [list]: 返回解析后的数据 """ if stdout is None: #判断输出是否为None return pattern = r'[\r\n|\r|\n|=]' # 防止不同平台下回车不同,无法正确解析 res = re.split(pattern,stdout.decode('UTF-8').strip()) #依照回车分割字符串 ...
17f2c191c792ef473ff1c89829488ed1f119db29
3,623,373
def split(array, nrows, ncols): """Split a matrix into sub-matrices.""" return array.reshape(array.shape[1]//nrows, nrows, -1, ncols).swapaxes(1, 2)
a153ee015cd03b2cbc89d7e434a67bef3740237f
3,623,374
async def push_status(req): """Push a status update to a job.""" data = req["data"] if data["state"] == "error" and not data["error"]: raise HTTPBadRequest(text="Missing error information") try: document = await get_data_from_req(req).jobs.push_status( req.match_info["job_i...
37ca34f64715405fc705ec71d11e9fa5996ff5e3
3,623,375
import dataclasses def _remove_spans(node): """Return a new ``QASMNode`` with all spans recursively set to ``None`` to reduce noise in test failure messages.""" if isinstance(node, list): return [_remove_spans(item) for item in node] if not isinstance(node, QASMNode): return node k...
8dbc57c6a2440fac1b766f05adb2d59af3ec26ca
3,623,376
def maskToOrignimalImg(img,mask): """add mask to color image""" if img.shape != mask.shape: #mask = expandImageTo3chan(mask) img = expandImageTo3chan(img) #print(img.shape,mask.shape) return cv2.addWeighted(img, 1.0, mask, 0.8, 0)
4afaadb0573a10fdcc60259f90fe3da15a480571
3,623,377
from typing import Iterable def has_clockwise_orientation(vertices: Iterable['Vertex']) -> bool: """ Returns True if 2D `vertices` have clockwise orientation. Ignores z-axis of all vertices. Args: vertices: iterable of :class:`Vec2` compatible objects Raises: ValueError: less than 3 ...
56b3f68f1362e05dfd34430a93eb09c625650fa2
3,623,378
import re def parse_views(data): """parse view count to .views""" m = re.search("videoPlayCount: \d+", data) return int(m.group(0)[16:])
ae297e0560826b5f036a25aeba98f4a894a58809
3,623,379
def row_to_dict(): """Convert pyspark.Row to dict for easier unordered comparison""" def func(row, recursive=True): return row.asDict(recursive=recursive) return func
ebc2395354d07a11895e7c85f0813279fea4630a
3,623,380
def get_flask_celery_apps(): """Call generate_context() and generate_config(). :return: First item is the Flask app instance, second is the Celery app instance. :rtype: tuple """ config = generate_config() flask_app = generate_context(config=config) celery_app = flask_app.extensions['celery...
960905c2f796cff8b54efa131a16469b615a9bef
3,623,381
def is_type_bitfld(*args): """ is_type_bitfld(t) -> bool See 'BT_BITFIELD' . @param t (C++: type_t) """ return _ida_typeinf.is_type_bitfld(*args)
e85c9272ec85a81762f7c25daa59e46c9b1f9101
3,623,382
import traceback import time def subpool_map(pool_size, func, iterable): """ Starts a Gevent pool and run a map. Takes care of setting current_job and cleaning up. """ if not pool_size: return [func(*args) for args in iterable] counter = itertools_count() current_job = get_current_job() ...
63c0a954e30aa635758a2c0324bf541ecd881049
3,623,383
def parse_xiaogui(self, data, source_mac, rssi): """Xiaogui Scales parser""" msg_length = len(data) if msg_length == 17: firmware = "Xiaogui" xiaogui_mac = data[11:] if xiaogui_mac != source_mac: _LOGGER.error("Xiaogui MAC address doesn't match data MAC address. Data: %...
d79b367af24a21b9b924113b4726ca9c8990f60d
3,623,384
import re from functools import reduce import operator import ast def eval_function(dataset, function, functions): """Evaluate a given function on a dataset. This function parses and evaluates a (possibly nested) function call, returning its result. """ name, args = FUNCTION.match(function).grou...
63f5faf34574e6d52b12930d98e728d6c519e8bb
3,623,385
def RSI(data, period=14, price='close'): """ Relative Strength Index RSI is a momentum oscillator that measures the speed and change of price movements. RSI oscillates between zero and 100. Traditionally, and according to Wilder, RSI is considered overbought when above 70 and oversold when below 3...
061d925bc0ee62cfef9fabc7f1ccb5537d1248d9
3,623,386
def qrscaner(): """Render template with QR scanner.""" title = 'Сканер' return render_template( 'receipt/qrscaner.html', page_title=title, )
3ce6ab1307c008383dace3a7549f3132e6c71b3b
3,623,387
def get_extrinsics(sim, cam_name): """ TODO: for some reason this returns me the -ve z-axis fix that TODO: also the extrinsic is correct for the flipped images fix that too """ pos = sim.data.get_camera_xpos(cam_name) mat = sim.data.get_camera_xmat(cam_name) ...
a53da8f68467c6c455a3e3455b671d375c0eafdb
3,623,388
def ConvertVFSGRRClient(client): """Converts from `VFSGRRClient` to `rdfvalues.objects.ClientSnapshot`.""" snapshot = rdf_objects.ClientSnapshot(client_id=client.urn.Basename()) snapshot.filesystems = client.Get(client.Schema.FILESYSTEM) snapshot.hostname = client.Get(client.Schema.HOSTNAME) snapshot.fqdn = ...
66172ec6d720f32cd1b26d17815564552a2e9936
3,623,389
from datetime import datetime def validate_trigger(config: Config, trigger: client.models.v1_config_map.V1ConfigMap) -> bool: """Evaluate trigger ConfigMap age, returning True if valid.""" cm_ts = trigger.metadata.creation_timestamp.timestamp() now = datetime.now().timestamp() return cm_ts + config.tr...
8a5c27faa33f723f5894b4ce9da07d669a53d5c2
3,623,390
def PrepareLocalPatches(manifest, patches): """Finish validation of parameters, and save patches to a temp folder. Args: manifest: The manifest object for the checkout in question. patches: A list of user-specified patches, in project[:branch] form. """ patch_info = [] for patch in _CheckLocalPatches...
181b0ace6b33c0c43914b5e0991b16d325e0bb4d
3,623,391
def update_hsl_value(color, hue=None, sat=None, lum=None, inmodel=HSL, outmodel=HSL): """Change hue, saturation, or lumenosity of the color based on the hue, sat, lum parameters provided. Parameters: color (Any): The color hue (int): A number between 0 and 360....
cf92fac981439ae9bcd96f71b506a4f2f1121426
3,623,392
def get_fits_image(fimage): """ reads fits image data and header fimage: filename with or without extension converts 32-bit floating values and 16-bit data to Python compatible values reads also color images and transposes matrix to correct order (normalizes images to +/- 1 range) returns: i...
83f59e30b69a3c483fb85e3dd7e129cae67f4dc6
3,623,393
def morph_trans(original_images, transformation): """ Apply morphological transformations on images. :param: original_images - the images to applied transformations on. :param: transformation - the standard transformation to apply. :return: the transformed dataset. """ if MODE.DEBUG: ...
6359bed14866dcd9b60aca4c0004317b41f62817
3,623,394
def plot_histograms(ax, prng, nb_samples=10000): """Plot 4 histograms and a text annotation. """ params = ((10, 10), (4, 12), (50, 12), (6, 55)) for a, b in params: values = prng.beta(a, b, size=nb_samples) ax.hist(values, histtype="stepfilled", bins=30, alpha=0.8)#, dens...
887e4d1fafd6023767a7902b43b6356d807bd0ad
3,623,395
def cleanup(wd, initdir, wrflag, rmwkdir): """ cleanup function """ tolog("Overall cleanup function is called") # collect any zombie processes wd.collectZombieJob(tn=10) tolog("Collected zombie processes") # get the current work dir wkdir = readStringFromFile(os.path.join(initdir, "CURRENT...
aa158af3939fae509f24b99c294c069e7b9dfe9b
3,623,396
import torch def render_rays_sm(img_idx, chain_bwd, chain_5frames, num_img, ray_batch, network_fn, network_query_fn, rigid_network_query_fn, N_samples, retraw=False, ...
94c78684f4ff32f33dcc6b9287faa5aa7356d303
3,623,397
import tqdm def generate_locations( staypoints, method="dbscan", epsilon=100, num_samples=1, distance_metric="haversine", agg_level="user", print_progress=False, ): """ Generate locations from the staypoints. Parameters ---------- staypoints : GeoDataFrame (as trackint...
6ca7e5d31be1c8dda5edeedab4de7babe1a489bf
3,623,398
def expand(im, filter_vec): """ Zero pads and blurs an image to expand it by 2 :param im: a grayscale image with double values in [0,1] :param filter_vec: row vector of shape(1, filter_size) to blur with :return: expanded image """ expanded_im = np.zeros((2 * im.shape[0], 2 * im.shape[1])) ...
2252bc5a6f10fadd961008c62bcd3adf9256e512
3,623,399