content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import csv def load_testingData(tempTrainingVectors, tempTestingVectors): """ TODO: Merge load_testingData() and load_trainingData() functions This reads file DSL-StrongPasswordData.csv and returns the testing data in an ndarray of shape tempTestingVectors*noOfFeatures and target ndarray of shape (tempTestingVec...
bffd94e65017c1ab1ab830f1af4d6256464a5d3a
4,300
async def anext(*args): """Retrieve the next item from the async generator by calling its __anext__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopAsyncIteration is raised. """ if len(args) < 1: raise TypeError( f"anext expected at leas...
60f71e2277501b1c274d691cef108937a2492147
4,301
def __prepare_arguments_for_d3_data(db_arguments, edge_type): """ :param db_arguments: :param edge_type: :return: """ all_ids = [] nodes = [] edges = [] extras = {} LOG.debug("Enter private function to prepare arguments for d3") # for each argument edges will be added as w...
70bfc5a8196ce831f21935f0d429180aea7019a5
4,302
from typing import List def get_service_gateway(client: VirtualNetworkClient = None, compartment_id: str = None, vcn_id: str = None) -> List[RouteTable]: """ Returns a complete, unfiltered list of Service Gateways of a vcn in the compartment. """ ser...
d1635dac2d6e8c64617eb066d114785674e9e8b3
4,303
def get_road_network_data(city='Mumbai'): """ """ data = pd.read_csv("./RoadNetwork/"+city+"/"+city+"_Edgelist.csv") size = data.shape[0] X = np.array(data[['XCoord','YCoord']]) u, v = np.array(data['START_NODE'], dtype=np.int32), np.array(data['END_NODE'], dtype=np.int32) w = np.a...
1d014e50b2d2883b5fda4aba9c2de5ca5e9dae2a
4,304
from apps.jsonapp import JSONApp def main_json(config, in_metadata, out_metadata): """ Alternative main function ------------- This function launches the app using configuration written in two json files: config.json and input_metadata.json. """ # 1. Instantiate and launch the App log...
302ba667a775dd09a6779235a774a4a95f26af32
4,305
def _infection_active(state_old, state_new): """ Parameters ---------- state_old : dict or pd.Series Dictionary or pd.Series with the keys "s", "i", and "r". state_new : dict or pd.Series Same type requirements as for the `state_old` argument in this function apply. Retu...
a81376ee1853d34b1bc23b29b2a3e0f9d8741472
4,306
def isnum(txt): """Return True if @param txt, is float""" try: float(txt) return True except TypeError: return False except ValueError: return False
c4f3aa3769810439d02312d0b616bd18c45a3da7
4,307
def xhr(func): """A decorator to check for CSRF on POST/PUT/DELETE using a <form> element and JS to execute automatically (see #40 for a proof-of-concept). When an attacker uses a <form> to downvote a comment, the browser *should* add a `Content-Type: ...` header with three possible values: * appl...
9a721d5eaa90be92cc05aa565b7ceb57fd209c7d
4,308
def updateStyle(style, **kwargs): """Update a copy of a dict or the dict for the given style""" if not isinstance(style, dict): style = getStyle(style) # look up the style by name style = style.copy() style.update(**kwargs) return style
57db589ff5b1b7d3e6eb3874826f77f5572c2aa7
4,309
def lift2(f, a, b): """Apply f => (a -> b -> c) -> f a -> f b -> f c""" return a.map(f).apply_to(b)
6b54cacf23ac4acb9bf9620cd259aa6f9630bbc3
4,310
def project_version(file_path=settings.PROJECT_VERSION_FILE): """Project version.""" try: with open(file_path) as file_obj: version = file_obj.read() return parse_version(version) except Exception: pass return None
4dd4bc6d9ae4570fa1278a709d45d12e8a7a2f8e
4,311
import numpy def readBinary(fileName): """Read a binary FIXSRC file.""" with FIXSRC(fileName, "rb", numpy.zeros((0, 0, 0, 0))) as fs: fs.readWrite() return fs.fixSrc
053c21a5cbc5b9c5b31eed94cfbea171d1a37d5e
4,312
def short_whitelist(whitelist): """A condensed version of the whitelist.""" for x in ["guid-4", "guid-5"]: whitelist.remove(x) return whitelist
e0de5f4f8c86df301af03c9362b095f330bffc14
4,313
def extract_paths(actions): """ <Purpose> Given a list of actions, it extracts all the absolute and relative paths from all the actions. <Arguments> actions: A list of actions from a parsed trace <Returns> absolute_paths: a list with all absolute paths extracted from the actions ...
94aaf8fef1a7c6d3efd8b04c980c9e87ee7ab4ff
4,314
def str2int(s): """converts a string to an integer with the same bit pattern (little endian!!!)""" r = 0 for c in s: r <<= 8 r += ord(c) return r
0dd190b8711e29e12be8cc85a641d9a68251205b
4,315
def load_operations_from_docstring(docstring): """Return a dictionary of OpenAPI operations parsed from a a docstring. """ doc_data = load_yaml_from_docstring(docstring) return { key: val for key, val in iteritems(doc_data) if key in PATH_KEYS or key.startswith('x-') }
6199a7e8b0c1cdb67f043e656d0797906fbf8bae
4,316
import torch def inference_model(model, img): """Inference image(s) with the classifier. Args: model (nn.Module): The loaded segmentor. img (str/ndarray): The image filename or loaded image. Returns: result (list of dict): The segmentation results that contains: ... """ cfg...
814ab13018245e51e5c32e43f2c6c67020d4e7dd
4,317
def run_egad(go, nw, **kwargs): """EGAD running function Wrapper to lower level functions for EGAD EGAD measures modularity of gene lists in co-expression networks. This was translated from the MATLAB version, which does tiled Cross Validation The useful kwargs are: int - nFold : Nu...
816a4c71830b0c576d045c3e413327b8927a7a5e
4,318
def prepare_new(): """ Handles a request to add a prepare project configuration. This is the first step in a two-step process. This endpoint generates a form to request information about the new project from the user. Once the form is submitted a request is sent to begin editing the new config. """ ...
5e103264f9bb2543a577fdb013c0fe641bd7ad14
4,319
def generic_plot(xy_curves, title, save_path, x_label=None, y_label=None, formatter=None, use_legend=True, use_grid=True, close=True, grid_spacing=20, yaxis_sci=False): """ :param xy_curves: :param title: :param x_label: :param y_label: :param formatter: :param save_path: :param use_leg...
f598578bfb6d63f9e9575223ecc25cdc9ace8082
4,320
from pathlib import Path import io def dump(module, path, **kwargs): """Serialize *module* as PVL text to the provided *path*. :param module: a ``PVLModule`` or ``dict``-like object to serialize. :param path: an :class:`os.PathLike` :param ``**kwargs``: the keyword arguments to pass to :func:`dumps()...
3c0d145883c4787ba0a69a3006ed5680dfba952b
4,321
def get_user_labels(client: Client, *_): """ Returns all user Labels Args: client: Client """ labels = client.get_user_labels_request() contents = [] for label in labels: contents.append({ 'Label': label }) context = { 'Exabeam.UserLabel(val.Lab...
a0ed0f71d2f39ef32a6fcdfd7586017e67957a6d
4,322
def hdf5_sample(sample, request): """Fixture which provides the filename of a HDF5 tight-binding model.""" return sample(request.param)
7d3320f5e4ce84bfa2cf0dbc1b5f321b2e3f6df8
4,323
def get_graph_embedding_features(fn='taxi_all.txt'): """ Get graph embedding vector, which is generated from LINE """ ge = [] with open(fn, 'r') as fin: fin.readline() for line in fin: ls = line.strip().split(" ") ge.append([float(i) for i in ls]) ge = np....
5710714ad3dea46ee64cf9fcacdfbdfec37c8c1c
4,324
def sub_0_tron(D, Obj, W0, eta=1e0, C=1.0, rtol=5e-2, atol=1e-4, verbose=False): """Solve the Sub_0 problem with tron+cg is in lelm-imf.""" W, f_call = W0.copy(), (f_valp, f_grad, f_hess) tron(f_call, W.reshape(-1), n_iterations=5, rtol=rtol, atol=atol, args=(Obj, D, eta, C), verbose...
54b4ae6f884da13fe538da6c7d8cb38fc05e2e46
4,325
def find_flavor_name(nova_connection: NovaConnection, flavor_id: str): """ Find all flavor name from nova_connection with the id flavor_id :param nova_connection: NovaConnection :param flavor_id: str flavor id to find :return: list of flavors name """ flavor_list = [] for flavor in nov...
c7252ad2b1f2f0676c4b2fed0304f6ddfe64f97f
4,326
def entity_decode(txt): """decode simple entities""" # TODO: find out what ones twitter considers defined, # or if sgmllib.entitydefs is enough... return txt.replace("&gt;", ">").replace("&lt;", "<").replace("&amp;", "&")
975dbd1b51773989455a16751f860af5b19f8fb5
4,327
def __format_focal_length_tuple(_tuple): """format FocalLenght tuple to short printable string we ignore the position after the decimal point because it is usually not very essential for focal length """ if (isinstance(_tuple,tuple)): numerator = _tuple[0] divisor = _tuple[1] els...
c27feee47f07558a822acaf57cd6a8a8a1a61c3f
4,328
import json def submit_resume_file(request): """ Submit resume """ resume_file = request.FILES['json_file'] # print('resume file=%s' % resume_file) file_content = resume_file.read() data = json.loads(file_content.decode('utf-8')) response = create_resume(data, request.user) return response
59f359d3c9c915f8ec228d3fb6ef17cc15ebac77
4,329
def inner_E_vals(vec): """ Returns a list of the terms in the expectation times without dividing by the length or one minus length.\nThis is meant to be used in conjunction with an inner-product of two inner_E_vals() lists to compute variance or covariance. """ out = [None] *...
a470674f899341c2ded1bdc682586274daa76ff0
4,330
def count_infected(pop): """ counts number of infected """ return sum(p.is_infected() for p in pop)
03b3b96994cf4156dcbe352b9dafdd027de82d41
4,331
def esum(expr_iterable): """ Expression sum :param term_iterable: :return: """ var_dict = {} constant = 0 for expr in expr_iterable: for (var_name, coef) in expr.var_dict.items(): if coef not in var_dict: var_dict[var_name] = coef else: ...
e63d574c4442843febf66e0326780d6ffb3ba647
4,332
def _prompt(func, prompt): """Prompts user for data. This is for testing.""" return func(prompt)
c5e8964e5b3a3d0a222e167341a44d8953d1e0c1
4,333
def show_trace(func, *args, **kwargs): # noinspection PyShadowingNames """ Display epic argument and context call information of given function. >>> @show_trace >>> def complex_function(a, b, c, **kwargs): ... >>> complex_function('alpha', 'beta', False, debug=True) calling haystack.sub...
1111b5a61a357de8a094647b3a659e5097822ecb
4,334
from pathlib import Path from typing import List import os import subprocess def record_editor(project_path: Path, debug: bool = False) -> List[Path]: """ Records ezvi running for each instructions file in a project. The files to record a found using `fetch_project_editor_instructions()`. Args: ...
c603816c86bb18c7a18e1793f5068c2e23bf7cf0
4,335
def to_percent__xy(x, y): """ To percent with 2 decimal places by diving inputs. :param x: :param y: :return: """ return '{:.2%}'.format(x / y)
3d5cfcde6f1dbd65b99a4081790e03efb669ee02
4,336
def generic_constructor(value, name=None, strict=False, allow_downcast=None): """SharedVariable Constructor""" return SharedVariable(type=generic, value=value, name=name, strict=strict, allow_downcast=allow_downcast)
e4d168449099154ce936d49c18dfc1754a774115
4,337
import torch def u_scheme(tree, neighbours): """Calculates the u-:ref:`scheme <presolve>`. """ unique_neighbours = torch.sort(neighbours, 1, descending=True).values unique_neighbours[:, 1:][unique_neighbours[:, 1:] == unique_neighbours[:, :-1]] = -1 pairs = torch.stack([tree.id[:, None].expand_as...
4b0727f6bbaa8121435b347100751928e6f0a348
4,338
def find_and_open_file(f): """ Looks in open windows for `f` and focuses the related view. Opens file if not found. Returns associated view in both cases. """ for w in sublime.windows(): for v in w.views(): if normpath(f) == v.file_name(): w.focus_view(v) ...
f300b76c9c4f4cf50e34490996d0f57feeb01728
4,339
def stochastic_fit(input_data: object) -> FitParams: """ Acquire parameters for the stochastic input signals. """ params = FitParams(0.000036906289210966747, 0.014081285145600045) return params
b138b1b434c9a4270c6915d67d6fdca3434a59a5
4,340
from typing import Dict from typing import Tuple from typing import List def sort_features_by_normalization( normalization_parameters: Dict[int, NormalizationParameters] ) -> Tuple[List[int], List[int]]: """ Helper function to return a sorted list from a normalization map. Also returns the starting in...
7beca199dc71e43fcf9f5c8870ee3f450a116e86
4,341
def block_sort(): """ Do from here: https://en.wikipedia.org/wiki/Block_sort :return: None """ return None
69143373200b0dfc560404c12d1500988869a688
4,342
def prep_ground_truth(paths, box_data, qgt): """adds dbidx column to box data, sets dbidx in qgt and sorts qgt by dbidx """ orig_box_data = box_data orig_qgt = qgt path2idx = dict(zip(paths, range(len(paths)))) mapfun = lambda x : path2idx.get(x,-1) box_data = box_data.assign(dbidx=box_...
6c01fb121933d5fdf235948136ffc73e08e7d6ee
4,343
def top_1_pct_share(df, col, w=None): """Calculates top 1% share. :param df: DataFrame. :param col: Name of column in df representing value. :param w: Column representing weight in df. :returns: The share of w-weighted val held by the top 1%. """ return top_x_pct_share(df, col, 0.01, w)
9fca3e9fdd1c69bda3a96111ca110791adb729be
4,344
def containsdupevalues(structure) -> bool or None: """Returns True if the passed dict has duplicate items/values, False otherwise. If the passed structure is not a dict, returns None.""" if isinstance(structure, dict): # fast check for dupe keys rev_dict = {} for key, value in structure....
4d3c72e71740e69a13889cef816fc4c00ead5790
4,345
import re def only_letters(answer): """Checks if the string contains alpha-numeric characters Args: answer (string): Returns: bool: """ match = re.match("^[a-z0-9]*$", answer) return bool(match)
32c8905294f6794f09bb7ea81ed7dd4b6bab6dc5
4,346
def is_finally_visible_func(*args): """ is_finally_visible_func(pfn) -> bool Is the function visible (event after considering 'SCF_SHHID_FUNC' )? @param pfn (C++: func_t *) """ return _ida_funcs.is_finally_visible_func(*args)
468687af0bafb42887f8e43453a4e6c641abde5e
4,347
def _losetup_list(): """ List all the loopback devices on the system. :returns: A ``list`` of 2-tuple(FilePath(device_file), FilePath(backing_file)) """ output = check_output( ["losetup", "--all"] ).decode('utf8') return _losetup_list_parse(output)
00ad4bdb76e22f44da50b35a296d43c5678698ce
4,348
def gaussian_product_center(a,A,b,B): """ """ A = np.array(A) B = np.array(B) return (a*A+b*B)/(a+b)
a52828d72f99bef8f666d1dbd33ee8d748e0b543
4,349
from yaml import YAMLError def read_yaml_file(yaml_path): """Loads a YAML file. :param yaml_path: the path to the yaml file. :return: YAML file parsed content. """ if is_file(yaml_path): try: file_content = sudo_read(yaml_path) yaml = YAML(typ='safe', pure=True) ...
7739f55b4b872392ddad4d5184fa718d8c1daa5e
4,350
def _InUse(resource): """All the secret names (local names & remote aliases) in use. Args: resource: Revision Returns: List of local names and remote aliases. """ return ([ source.secretName for source in resource.template.volumes.secrets.values() ] + [ source.secretKeyRef.name ...
cf13ccf1d0fffcd64ac8b3a40ac19fdb2b1d12c5
4,351
def filter_dwnmut(gene_data): """Removes the variants upstream to Frameshift/StopGain mutation. Args: - gene_data(dictionary): gene_transcript wise variants where there is at least one Frameshift/Stopgain mutation. Return...
9573e5cbd0ed3f96f8e7f47fa395476cc7bd513b
4,352
def format_scwgbs_file(file_path): """ Format a scwgbs file to a more usable manner :param file_path: The path of the file to format :type file_path: str :return: A dict where each key is a chr and the value is an array with all the scwgbs reads :rtype: dict """ chr_dict = extract_cols(f...
eaf2925e3f634138ba8eb7bf1f61189d30f86d7c
4,353
import torch def ls_generator_loss(scores_fake): """ Computes the Least-Squares GAN loss for the generator. Inputs: - scores_fake: PyTorch Tensor of shape (N,) giving scores for the fake data. Outputs: - loss: A PyTorch Tensor containing the loss. """ loss = None ##############...
6b6d1b94e13de514e56fe83764869b8c2948a40a
4,354
def rmsd(predicted, reference): """ Calculate root-mean-square deviation (RMSD) between two variables. Calculates the root-mean-square deviation between two variables PREDICTED and REFERENCE. The RMSD is calculated using the formula: RMSD^2 = sum_(n=1)^N [(p_n - r_n)^2]/N where p is the p...
5903c0a900b6f66bddd640f9c65146a08e0b768d
4,355
from typing import List def _get_ranks_for_sequence(logits: np.ndarray, labels: np.ndarray) -> List[float]: """Returns ranks for a sequence. Args: logits: Logits of a single sequence, dim = (num_tokens, vocab_size). labels: Target labels of a single sequence, dim = (num_tokens...
59cb646f5f4f498f3bfe1c3c01672ce61e124428
4,356
import torch import time def eval_model_on_grid(model, bbox, tx, voxel_grid_size, cell_vox_min=None, cell_vox_max=None, print_message=True): """ Evaluate the trained model (output of fit_model_to_pointcloud) on a voxel grid. :param model: The trained model returned from fit_model_to_pointcloud :param ...
7486d27d11c250cccd1c9de5fc65b8f8f773f906
4,357
from typing import IO from typing import Iterable from typing import Mapping import subprocess import errno import csv import struct def create_gop(mpeg_file_object: IO[bytes]) -> bytes: """Create an index that allows faster seeking. Note: as far as I can tell, this is not a standard GOP / group of pictures ...
3738ca12ab7c61d0a595455dcffe326c6171c9eb
4,358
import torch import tqdm def beam_search(model, test_data_src, beam_size, max_decoding_time_step): """ Run beam search to construct hypotheses for a list of src-language sentences. @param model : Model @param test_data_src (List[List[str]]): List of sentences (words) in source language, from test set. ...
ff5a52a336defa4f647a6eb8d7d39c12aa13b9be
4,359
def filter_months(c, months): """Filters the collection by matching its date-time index with the specified months.""" indices = find_all_in(get_months(c), get_months(months)) return take_at(c, indices)
c635c80fb007f49c2ef9238830374d0465b488b3
4,360
import itertools def kmode_fisher(ks,mus,param_list,dPgg,dPgv,dPvv,fPgg,fPgv,fPvv,Ngg,Nvv, \ verbose=False): """ Fisher matrix for fields g(k,mu) and v(k,mu). Returns F[g+v] and F[g] dPgg, dPgv, dPvv are dictionaries of derivatives. fPgg, fPgv, fPvv are fiducial powers. """ ...
e27699d51ce65b284d1289d5e6ae4472ae6fa63e
4,361
def detect_device(model): """ Tries to determine the best-matching device for the given model """ model = model.lower() # Try matching based on prefix, this is helpful to map e.g. # FY2350H to FY2300 for device in wavedef.SUPPORTED_DEVICES: if device[:4] == model[:4]: return device raise wav...
6b58b5a8dc67a1f30e499c31b545b70ead908aaf
4,362
import re def re_identify_image_metadata(filename, image_names_pattern): """ Apply a regular expression to the *filename* and return metadata :param filename: :param image_names_pattern: :return: a list with metadata derived from the image filename """ match = re.match(image_names_pattern,...
1730620682f2457537e3f59360d998b251f5067f
4,363
import yaml import sys def load_config(config_file: str) -> dict: """ Function to load yaml configuration file :param config_file: name of config file in directory """ try: with open(config_file) as file: config = yaml.safe_load(file) except IOError as e: print(e) ...
f811aa4d6a16d8a5e56d14b91d616f9f8b3ad492
4,364
def PSF_Moffat(alpha,beta,x,y): """ Compute the PSF of the instrument with a Moffat function Parameters ----------- alpha: float radial parameter beta: float power indice of the function x: float position along the x axis y: float position along the y axi...
c70fe8582c27518ab521d3d663da87e1354f0668
4,365
def _tf_range_for_stmt(iter_, extra_test, body, get_state, set_state, init_vars, basic_symbol_names, composite_symbol_names, opts): ""...
37e21af2fbf5bd910743c220e872c45e08131e97
4,366
import importlib def _import_class(module_and_class_name: str) -> type: """Import class from a module, e.g. 'text_recognizer.models.MLP'""" module_name, class_name = module_and_class_name.rsplit(".", 1) # splits into 2 elements at "." module = importlib.import_module(module_name) class_ = getattr(modu...
c5666b6393c89bf9cb32a7a3351d3a8706ffd631
4,367
def mark_task(func): """Mark function as a defacto task (for documenting purpose)""" func._is_task = True return func
9f0156fff2a2a6dcb64e79420022b78d1c254490
4,368
from operator import getitem import math def dict_diff(left: Map, right: Map) -> t.List[t.Dict]: """Get the difference between 2 dict-like objects Args: left (Map): The left dict-like object right (Map): The right dict-like object The value returned is a list of dictionaries with keys ["...
23f7aa611230879099590b696f9484aa9881a34b
4,369
def make_slack_message_divider() -> dict: """Generates a simple divider for a Slack message. Returns: The generated divider. """ return {'type': 'divider'}
9d0243c091065056a29d9fa05c62fadde5dcf6f6
4,370
import os def username(): """ Return username from env. """ return os.environ["USER"]
adcb6da63823d78203d02b2a3910f92e3ae97724
4,371
def get_history(filename: str, extension: int = 0) -> str: """ Returns the HISTOR header lines. Args: filename: image filename. extension: image extension number. Returns: string containing all HISTORY lines. """ filename = azcam.utils.make_image_filename(filename) ...
495b5d85a9313c081cf5bea837440dc51e9f8d6e
4,372
def product_detail(request, product_id): """ A view to show one product's details """ product = get_object_or_404(Product, pk=product_id) review_form = ReviewForm() reviews = Review.objects.filter(product_id=product_id).order_by('-created_at') context = { 'product': product, 're...
5e83dd11b2cfb4e43186c584424e96e35f52333a
4,373
import json def deserialize_response_content(response): """Convert utf-8 encoded string to a dict. Since the response is encoded in utf-8, it gets decoded to regular python string that will be a json string. That gets converted to python dictionary. Note: Do not use this method to process non-js...
ff5494e38f7a6f5b49b4e84e1e8a2ee1633d3872
4,374
def _remove_header_create_bad_object(remove, client=None): """ Create a new bucket, add an object without a header. This should cause a failure """ bucket_name = get_new_bucket() if client == None: client = get_client() key_name = 'foo' # remove custom headers before PutObject call ...
bb1f6fb6ca61c7c3137ec4dbf35c2c3500c0e82d
4,375
def SpawnObjectsTab(): """This function creates a layout containing the object spawning functionality. Returns: str : The reference to the layout. """ ### Create main Layout for the tab mainTab = cmds.columnLayout(adjustableColumn=True, columnAttach=('both', 20)) cmds.separator(height...
8381058ce0d7607f81fcdc6ba3e9f03c1495c719
4,376
from typing import List from typing import Tuple def train_val_test_split(relevant_data: List[str], seed: int = 42) -> Tuple[List[str], List[str], List[str]]: """Splits a list in seperate train, validate and test datasets. TODO: add params for train / val / test sizes :param relevant_data: The list to b...
be8acaabfb9d6ad4043ef82f1899f3a8cbcf7ced
4,377
import math def getShdomDirections(Y_shdom, X_shdom, fov=math.pi/2): """Calculate the (SHDOM) direction of each pixel. Directions are calculated in SHDOM convention where the direction is of the photons. """ PHI_shdom = np.pi + np.arctan2(Y_shdom, X_shdom) PSI_shdom = -np.pi + fov * np.sqrt(...
e564f5a9988a6a3a0f14b319ea553dd6bfd7d75a
4,378
def twos_comp(val, bits): """returns the 2's complement of int value val with n bits - https://stackoverflow.com/questions/1604464/twos-complement-in-python""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value r...
53bc689f9dd0cf1dff6cd3e073608d1827a3dad9
4,379
def get_batch(source, i, cnf): """ Gets a batch shifted over by shift length """ seq_len = min(cnf.batch_size, len(source) - cnf.forecast_window - i) data = source[i : i + seq_len] target = source[ i + cnf.forecast_window : i + cnf.forecast_window + seq_len ].reshape(-1) return d...
8f4bbfca44bed498dc22d52706389378bf03f7e0
4,380
def verify_df(df, constraints_path, epsilon=None, type_checking=None, repair=True, report='all', **kwargs): """ Verify that (i.e. check whether) the Pandas DataFrame provided satisfies the constraints in the JSON ``.tdda`` file provided. Mandatory Inputs: *df*: ...
03daa527e9edb61d57a960c335ba574930baf130
4,381
def logical_and(image1, image2): """Logical AND between two videos. At least one of the videos must have mode "1". .. code-block:: python out = ((image1 and image2) % MAX) :rtype: :py:class:`~PIL.Image.Image` """ image1.load() image2.load() return image1._new(image1.im.chop_a...
040ec91a09f0ce7251e3e40f95a087e6d1f81b87
4,382
def predict(endpoint_id: str, instance: object) -> object: """Send a prediction request to a uCAIP model endpoint Args: endpoint_id (str): ID of the uCAIP endpoint instance (object): The prediction instance, should match the input format that the endpoint expects Returns: object: Prediction re...
9b7801d23e9aed0fc8292cd1b0a7f9621c313797
4,383
async def resolve_address(ipaddr, *args, **kwargs): """Use a resolver to run a reverse query for PTR records. See ``dns.asyncresolver.Resolver.resolve_address`` for more information on the parameters. """ return await get_default_resolver().resolve_address(ipaddr, *args, **kwargs)
b5fbd218ba3e8e1d1a51873a4c12cfc304bfc2fd
4,384
def _stringify(item): """ Private funtion which wraps all items in quotes to protect from paths being broken up. It will also unpack lists into strings :param item: Item to stringify. :return: string """ if isinstance(item, (list, tuple)): return '"' + '" "'.join(item) + '"' i...
7187b33dccce66cb81b53ed8e8c395b74e125633
4,385
def _get_tree_filter(attrs, vecvars): """ Pull attributes and input/output vector variables out of a tree System. Parameters ---------- attrs : list of str Names of attributes (may contain dots). vecvars : list of str Names of variables contained in the input or output vectors. ...
fb96025a075cfc3c56011f937d901d1b87be4f03
4,386
def gradient2(Y,x,sum_p): """ Description ----------- Used to calculate the gradients of the beta values (excluding the first). Parameters ---------- Y: label (0 or 1) x: flux value sum_p: sum of all beta values (see 'param_sum' function) Returns ------- num/denom: gradient value """ if Y...
985b0e72419127291b2ddf99e81a129693e7e8fe
4,387
def takeBlock2(aList, row_list, col_list): """ Take sublist given from rows specified by row_list and column specified by col_list from a doublely iterated list. The convention for the index of the rows and columns are the same as in slicing. """ result = [] for row in row_list: result.append(map(lambda col...
4f891fd0ce8b3bcca88f2f8f6f572ce4253d1d46
4,388
def param(key, desired_type=None): """Return a decorator to parse a JSON request value.""" def decorator(view_func): """The actual decorator""" @wraps(view_func) def inner(*args, **kwargs): data = request.get_json() # May raise a 400 try: value = ...
1dca83eb24df9623ddae270ebe1f06461c372af0
4,389
def make_client(instance): """Returns a client to the ClientManager.""" tacker_client = utils.get_client_class( API_NAME, instance._api_version[API_NAME], API_VERSIONS) LOG.debug('Instantiating tacker client: %s', tacker_client) kwargs = {'service_type': 'nfv-orchestration', ...
554394a29978b13523532f55d858f25ae1a17619
4,390
def rasterize( vectors, layer=0, output=None, nodata=None, pixel_size=None, bounds=None, affine=None, shape=None, attribute=None, fill=0, default_value=1, ): """Rasterize features Options for definining the boundary and pixel size of rasterization: User may prov...
a8f47fd768f8173c74605f533c1a50974b6acc63
4,391
def blockchain_key_seed(request): """ Private key template for the nodes in the private blockchain, allows different keys to be used for each test to avoid collisions. """ # Using the test name as part of the template to force the keys to be # different accross tests, otherwise the data directories ...
05a940c5a18f816b4bba3fb65e354a5dac2ce1cd
4,392
def wls_simple(X, y, yerr): """ weighted least squares: (X.T*W*X)*beta = X.T*W*y solution: beta = (X.T*X)^-1 * X.T *y Note ---- wls solves single problems (n_problems=1) BUT! is able to solve multiple-template (same error) problems Parameters ---------- X: predictors (n...
d428eb22dee7b587788e065a7dd883992f183ef7
4,393
import re import copy def _filter(dict_packages, expression): """Filter the dict_packages with expression. Returns: dict(rst): Filtered dict with that matches the expression. """ expression_list = ['(' + item + ')' for item in expression.split(',')] expression_str = '|'.join(expression_l...
866bca2847b9d3c8220319f4b394f932931fc076
4,394
def multi_index_tsv_to_dataframe(filepath, sep="\t", header_rows=None): """ Loads a multi-header tsv file into a :py:class:`pd.DataFrame`. Parameters ---------- filepath : `str` Path pointing to the tsv file. sep : `str`, optional, default: '\t' Character to use as the delim...
9ae5816aed2bfacd05d4130ccc1598c037b9b353
4,395
def generate_summoner_tab_summoner(db, profile, ss): """ :type db: darkarisulolstats.lolstats.database.Database """ summoner = {} for s in ss: raw_summoner = db.summoners.get(s) if "profileIconPath" not in summoner: summoner["profileIconPath"] = data.DataDragon.get_profil...
0bee2b48c71910ed273925a7cae1c4539b411401
4,396
def preserve_quotes (s): """ Removes HTML tags around greentext. """ return quot_pattern.sub(get_first_group, s)
a87ac4ee7fdb0e0c879047066e805f2c9382c599
4,397
import os import configparser import logging def test_init_logger(monkeypatch): """ Tests `init_logger()`. """ test_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test_config') def mock_get_conf_path(): """ Replaces the conf path with the one f...
5beb83bfd4b858b50e2572c2907c0536193b30bb
4,398
def with_whitespace_inside(expr): """ Returns an expression that allows for whitespace inside, but not outside the expression. """ return Combine(OneOrMore(expr | White(' ', max=1) + expr))
9306ffb73277d249062ffca45ded9d0bd9a45e3c
4,399