content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import torch from typing import Tuple def get_median_and_stdev(arr: torch.Tensor) -> Tuple[float, float]: """Returns the median and standard deviation from a tensor.""" return torch.median(arr).item(), torch.std(arr).item()
d8fca5a97f00d14beecaa4b508442bc7a3637f86
3,640,180
def connect(user, host, port): """Create and return a new SSHClient connected to the given host.""" client = ssh.SSHClient() if not env.disable_known_hosts: client.load_system_host_keys() if not env.reject_unknown_hosts: client.set_missing_host_key_policy(ssh.AutoAddPolicy()) con...
a13a3ce5e80f603f21933c9e6ad48b073368b97e
3,640,181
import scipy def _chf_to_pdf(t, x, chf, **chf_args): """ Estimate by numerical integration, using ``scipy.integrate.quad``, of the probability distribution described by the given characteristic function. Integration errors are not reported/checked. Either ``t`` or ``x`` must be a scalar. """ ...
7022d335d39c25b73203b63b40b1ebb8c178154b
3,640,182
import re import logging def ParseTraceLocationLine(msg): """Parse the location line of a stack trace. If successfully parsed, returns (filename, line, method).""" parsed = re.match(kCodeLocationLine, msg) if not parsed: return None try: return (parsed.group(1), parsed.group(2), parsed.group(3)) exc...
15e74bb26a7c213cf24171ffdfa32b8d4e6d818a
3,640,183
import functools def return_arg_type(at_position): """ Wrap the return value with the result of `type(args[at_position])` """ def decorator(to_wrap): @functools.wraps(to_wrap) def wrapper(*args, **kwargs): result = to_wrap(*args, **kwargs) ReturnType = type(arg...
30bf4e4a46b0b64b6cb5752286a13c0e6f7618df
3,640,185
def extend(s, var, val): """Copy dict s and extend it by setting var to val; return copy.""" try: # Python 3.5 and later return eval('{**s, var: val}') except SyntaxError: # Python 3.4 s2 = s.copy() s2[var] = val return s2
919e7102bf7f8766d9ddb9ea61a07ddd020d1bb8
3,640,186
from typing import Optional from typing import Any def rx_reduce(observable: Observable, accumulator: AccumulatorOperator, seed: Optional[Any] = None) -> Observable: """Create an observable which reduce source with accumulator and seed value. Args: observable (Observable): source accumulator ...
600d5c47fd7b29ead5293c7a172c8ebdb026706a
3,640,187
def minimum_filter( input, size=None, footprint=None, output=None, mode="reflect", cval=0.0, origin=0, ): """Multi-dimensional minimum filter. Args: input (cupy.ndarray): The input array. size (int or sequence of int): One of ``size`` or ``footprint`` must be ...
fbbda2abbd470b98cb03158377256c7397c17da6
3,640,189
import copy def lowpass(data, cutoff=0.25, fs=30, order=2, nyq=0.75): """ Butter low pass filter for a single or spectra or a list of them. :type data: list[float] :param data: List of vectors in line format (each line is a vector). :type cutoff: float :param cutoff: Desired cuto...
ac42a32c406b1c5a182a1af805e86bf0b0c0606f
3,640,190
from re import M def format(value, limit=LIMIT, code=True, offset=0, hard_stop=None, hard_end=0): """ Recursively dereferences an address into string representation, or convert the list representation of address dereferences into string representation. Arguments: value(int|list): Either the s...
d8eae5b2cc8dbab9a26d7248faf17fe638f5e603
3,640,191
def sogs_put(client, url, json, user): """ PUTs a test `client` request to `url` with the given `json` as body and X-SOGS-* signature headers signing the request for `user`. """ data = dumps(json).encode() return client.put( url, data=data, content_type='application/json', headers=x_sog...
7bb3f34d7aff75f422b898ba6eee2908c8bc4ca4
3,640,192
import tqdm import requests def get_results(heading): """Get all records under a given record heading from PubChem/ Update results from those records.""" page = 1 results = {} with tqdm(total=100) as pbar: while True: url = (f"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/anno...
fba50023290dfde12a54f6d7792f578ecc66e3d9
3,640,193
def create_dictionary(documents): """Creates word dictionary for given corpus. Parameters: documents (list of str): set of documents Returns: dictionary (gensim.corpora.Dictionary): gensim dicionary of words from dataset """ dictionary = Dictionary(documents) dictionary.compactif...
bba8e6af363da3fcdde983c6ebf52432323ccf96
3,640,194
def clone_bitarray(other, src=None): """ Fast clone of the bit array. The actual function used depends on the implementation :param other: :param src: :return: """ if FAST_IMPL_PH4 and src is not None: src.fast_copy(other) return src return to_bitarray(other)
9196474dff0e6c1b79f9307409c5f351f2c015d7
3,640,195
from typing import List from typing import Optional from typing import Dict def _create_graph( expressions: List[expression.Expression], options: calculate_options.Options, feed_dict: Optional[Dict[expression.Expression, prensor.Prensor]] = None ) -> "ExpressionGraph": """Create graph and calculate expr...
e7f5a9dbaf3c34a3c925c5d390d6ee44fac57062
3,640,196
def generate_arn(service, arn_suffix, region=None): """Returns a formatted arn for AWS. Keyword arguments: service -- the AWS service arn_suffix -- the majority of the arn after the initial common data region -- the region (can be None for region free arns) """ arn_value = "arn"...
53dcf55c3fb15784770d1c2d62375d1e750469f8
3,640,198
def prod_list(lst): """returns the product of all numbers in a list""" if lst: res = 1 for num in lst: res *= num return res else: raise ValueError("List cannot be empty.")
8179e2906fb4b517d02972fd4647095d37caf6cd
3,640,199
def create_attribute(representation_uuid, attribute_name): """create a representation of an attribute of a representation""" try: uuid = get_bus().create_attribute(representation_uuid, attribute_name, public=True) return JsonResponse({'type': 'uuid', 'uuid': uuid}) except Exception as except...
f1ddfbc634b459a7e3f179125fd323beb871957d
3,640,200
def check_shift(start_time, end_time, final_minute, starting_minute, record): """ Função que verifica o turno da chamada e calcula o valor da ligação :param start_time: :param end_time: :param final_minute: :param starting_minute: :return value: """ nem_start_time = start_time + (st...
666883348347e8408b087ac63acd8608ff589a1c
3,640,202
import hashlib def s3_avatar_represent(user_id, tablename="auth_user", gravatar=False, **attr): """ Represent a User as their profile picture or Gravatar @param tablename: either "auth_user" or "pr_person" depending on which table the 'user_id' refers to @param a...
2c537a57a5d20ed8b4329338883f209fa9678fc4
3,640,203
from typing import Dict from typing import List import pathlib import json def json_loader(path_to_json_file: str) -> Dict[str, List[str]]: """Reads a JSON file and converts its content in a dictionary. Parameters ---------- path_to_json_file: str The path to the JSON file. Returns -...
d3f26504078e72e1522981a4d8ca5b60c3b8cf23
3,640,204
def get_region_solution_attribute(data, region_id, attribute, func, intervention): """Extract region solution attribute""" regions = data.get('NEMSPDCaseFile').get('NemSpdOutputs').get('RegionSolution') for i in regions: if (i['@RegionID'] == region_id) and (i['@Intervention'] == intervention): ...
0dc26e54ae5f16f8b3158ec00a5dc0bc58776408
3,640,205
def conv1x1(in_planes: int, out_planes: int) -> nn.Conv2d: """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=True)
2c8fcb8e04084ce35a2ae595b457fdf68fd27723
3,640,206
def make_ratio_map(amap, bmap): """Get the ratio of two PISA 2 style maps (amap/bmap) and return as another PISA 2 style map.""" validate_maps(amap, bmap) with np.errstate(divide='ignore', invalid='ignore'): result = {'ebins': amap['ebins'], 'czbins': amap['czbins'], ...
9497ddadd6d983b3094107aceadbdc1e2f1fb0a7
3,640,207
from typing import Collection from typing import Mapping from typing import Sequence import math def _compose_duration( components_tags: Collection[Tags]) -> Mapping[str, Sequence[str]]: """Returns summed duration tags.""" duration_seconds_values = [ component_tags.one_or_none(DURATION_SECONDS...
99bebed06628627211a117c738d89790d11adc1b
3,640,208
def feature_spatial(fslDir, tempDir, aromaDir, melIC): """ This function extracts the spatial feature scores. For each IC it determines the fraction of the mixture modeled thresholded Z-maps respecitvely located within the CSF or at the brain edges, using predefined standardized masks. Parameters ------------------...
fb515a61bd81533b3b79f9cd500ad5b77723b527
3,640,209
from datetime import datetime def str_to_date(date_str, fmt=DATE_STR_FMT): """Convert string date to datetime object.""" return datetime.datetime.strptime(date_str, fmt).date()
102f384b479b217259c9bbfe36c8b66909daee50
3,640,210
import time import json def create_elasticsearch_domain(name, account_id, boto_session, lambda_role, cidr): """ Create Elastic Search Domain """ boto_elasticsearch = boto_session.client('es') total_time = 0 resource = "arn:aws:es:ap-southeast-2:{0}:domain/{1}/*".format(account_id, name) ...
5e33bd1454a2b3d1ce3bc1cc181b44497ce6035a
3,640,211
def get_user(email): """ param: username returns User instance with user data, the MySQL error handle by the try-except senteces """ result = {} connection = _connect_to_db() try: with connection.cursor() as cursor: row_count = 0 e = 'none' # Read...
f05a59dc95ade5157d09d26a7d899fd9b19d3526
3,640,212
def index(request): """ A example of Function-based view method: get request: None response: type: html """ return HttpResponse("Hello, world. You're at the polls index.")
1fe400e5f08728eef5834268d219a3f109325114
3,640,213
import requests def make_https_request(logger, url, jobs_manager, download=False, timeout_attempt=0): """ Utility function for making HTTPs requests. """ try: req = requests_retry_session().get(url, timeout=120) req.raise_for_status() except requests.exceptions.ConnectionError as c...
825d1d79dc44e571fed4437fb1fbebc60bfef669
3,640,214
def falshsort(): """ Do from here: https://en.wikipedia.org/wiki/Flashsort :return: None """ return None
359dc737a6611ebd6a73dd7761a6ade97b44b7ab
3,640,216
import random def random_word(text, label, label_map, tokenizer, sel_prob): """ Masking some random tokens for Language Model task with probabilities as in the original BERT paper. :param tokens: list of str, tokenized sentence. :param tokenizer: Tokenizer, object used for tokenization (we need it's v...
46e7ac7d9fd0d82bbfef97a9a88efd0599bbc3b3
3,640,217
import numpy def _match_storm_objects(first_prediction_dict, second_prediction_dict, top_match_dir_name): """Matches storm objects between first and second prediction files. F = number of storm objects in first prediction file :param first_prediction_dict: Dictionary returned by...
9c3bc60e99dc3d07cbd661b7187833e26f18d6f7
3,640,219
from typing import Optional from typing import cast def get_default_branch(base_url: str, auth: Optional[AuthBase], ssl_verify: bool = True) -> dict: """Fetch a reference. :param base_url: base Nessie url :param auth: Authentication settings :param ssl_verify: ignore ssl errors if False :return: ...
e2ac587705c82c95edeb415b79ca15746e9e9b78
3,640,220
from typing import Tuple from typing import Union def sigmoid( x, sigmoid_type: str = "tanh", normalization_range: Tuple[Union[float, int], Union[float, int]] = (0, 1) ): """ A sigmoid function. From Wikipedia (https://en.wikipedia.org/wiki/Sigmoid_function): A sigmoid function...
b9d660d20f7e398a2e57ad0b907ab52c4a88cc36
3,640,223
def interp(x, x1, y1, x2, y2): """Find a point along a line""" return ((x2 - x) * y1 + (x - x1) * y2) / (x2 - x1)
3af4575c017a32619a5bb2866a7faea5ff5c760d
3,640,224
def gen_cpmfgp_test_data_from_config_file(config_file_name, raw_func, num_tr_data, num_te_data): """ Generates datasets for CP Multi-fidelity GP fitting. """ # Generate data def _generate_data(_proc_func, _config, _num_data): """ Generates data. """ ZX_proc = sample_from_config_space(_config, _num_data)...
c6efaf34601f5b02153fca3ea0926115d1adb918
3,640,226
def csv_to_postgres(engine, file: str, table_name: str): """ Given a *.csv filepath, create a populated table in a database :param engine: SQLAlchemy connection/engine for the target database :param file: Full filepath of the *.csv file :param table_name: ...
e8a913a32a3b0f7d9d617fa000f0b232e9824736
3,640,227
def _custom_padd(a, min_power_of_2=1024, min_zero_padd=50, zero_padd_ratio=0.5): """ Private helper to make a zeros-mirror-zeros padd to the next power of two of a. Parameters ---------- arrays : np.ndarray, array to padd. min_power_of_2 : int (default=512), mi...
eb7f9d675113b8f53558d911462209c2f72c3ce3
3,640,228
def encode_multipart_formdata(fields, files): """ Encode multipart data to be used in data import adapted from: http://code.activestate.com/recipes/146306/ :param fields: sequence of (name, value) elements for regular form fields. :param files: sequence of (name, filename, value) elements for data ...
17cd1ce08d7aac005a07b77517c4644565083cb8
3,640,229
def is_recording(): """ return current state of recording key macro """ global recording return recording
73f3a28d5d37bdc300768d48a6cc8f2ac81c2cf0
3,640,230
from typing import Union from pathlib import Path from typing import List from typing import Dict from typing import Optional import asyncio def download_image_urls( urls_filename: Union[Path, str], synsets: List[str], max_concurrent: int = 50, rewrite: bool = False ) -> Dict[str, Optional[List[str]]]...
36bc1e2993cfd01ef9fca91354f970ffb980a919
3,640,231
def generate_new_split(lines1, lines2, rng, cutoff=14937): """Takes lines1 and lines2 and combines, shuffles and split again. Useful for working with random splits of data""" lines = [l for l in lines1] # lines1 may not be a list but rather iterable lines.extend(lines2) perm = rng.permutation(len(lines...
cac058f44bd5cb729517a1aeb67295a30dac2eb5
3,640,232
import time def train_classification(base_iter, model, dataloader, epoch, criterion, optimizer, cfg, writer=None): """Task of training vide...
8564fe2d520d54c81165adb5025aebb9916ab9b5
3,640,233
import logging def get_top5(prediction): """return top5 index and value of input array""" length = np.prod(prediction.size) pre = np.reshape(prediction, [length]) ind = np.argsort(pre) ind = ind[length - 5 :] value = pre[ind] ind = ind[::-1] value = value[::-1] res_str = "" l...
607ad0b9eee550e1bb389a9a92a76472155bea16
3,640,234
def calculate_parentheses(cases): """Calculate all cases in parameter 'cases' return : case that calculate and it's 24 else return 'No Solutions' Example and Doctest : >>> nums = [5, 5, 9, 5] >>> cases = generate_all_combinations(nums, '+-*/') >>> calculate_parentheses(cases) '( ( 5 + 5 ) +...
b8d51d677e16ed27c0b46ad0f4fe98751ea9759e
3,640,235
import hashlib import hmac import struct def pbkdf2(hash_algorithm, password, salt, iterations, key_length): """ PBKDF2 from PKCS#5 :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha224", "sha256", "sha384", "sha512" :param password: ...
8a3799a2c73b3b3be96f67252f210bc5d114d334
3,640,236
import time def getLocalUtcTimeStamp(): """ Get the universal timestamp for this machine. """ t = time.mktime(time.gmtime()) isDst = time.localtime().tm_isdst return t - isDst * 60 * 60
54eed0893d03f3b6a76de0d36fc3f1ff5b35f64f
3,640,237
def melt_then_pivot_query(df, inspect_result, semiology_term): """ if happy all are the same semiology, after insepction of QUERY_SEMIOLOGY, melt then pivot_table: --- inspect_result is a df Ali Alim-Marvasti July 2019 """ # find all localisation columns present: localisation_l...
97ebd8f30d4b031a6b12412421ad0e4e2458c003
3,640,238
from typing import List from typing import Tuple def maze_solver(maze: List[List[int]]) -> List[Tuple[int, int]]: """ Finds the path that a light ray would take through a maze. :param maze: 2D grid of cells, where 0 = empty cell, -1 = mirror at -45 degrees, 1 = mirror at 45 degrees :return: The coordinates that t...
4ea26e1dec318c9a41babf617d26662d35fe54c1
3,640,239
def looks_like_fasta(test_text): """Determine if text looks like FASTA formatted data. Looks to find at least two lines. The first line MUST start with '>' and the second line must NOT start with '>'. Ignores any starting whitespace. """ text = test_text.strip() return FASTA_START.match(...
352cde2d0d4de692e0598a96d19107ac04a66f53
3,640,240
import signal def firwin_kaiser_bsf(f_stop1, f_pass1, f_pass2, f_stop2, d_stop, fs=1.0, N_bump=0, status=True): """ Design an FIR bandstop filter using the sinc() kernel and a Kaiser window. The filter order is determined based on f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, ...
d5fccbcb9721707f0653065ad7c27d904cc05b97
3,640,241
from typing import List def extract_text(html_text) -> List[List[str]]: """ :param html_text: :return: """ lines = [i.text.replace("\xa0", "") for i in html_text.find("div", attrs={"class": "contentus"}).findAll("h3")] return [line.split(" ") for line in lines if line]
19dfdd513e48f2662dc51661bfeca4b1155762a3
3,640,242
from typing import Iterable from typing import Tuple from re import X from typing import Mapping from typing import List def multidict(pairs: Iterable[Tuple[X, Y]]) -> Mapping[X, List[Y]]: """Accumulate a multidict from a list of pairs.""" rv = defaultdict(list) for key, value in pairs: rv[key].ap...
c94567169a8ea4e3d7fd9a8e5c2a990625181be8
3,640,243
import glob def read_images(pathname): """ Read the images to a list given a path like 'images/cropped/*' :param pathname: file path :return: a list of color images and a list of corresponding file names """ images_path = sorted(glob.glob(pathname)) images = [] names = [] for path ...
9fd4644baa2ca5db204cd7ce442e85bc0d9e3166
3,640,244
def visualize_camera_movement(image1, image1_points, image2, image2_points, is_show_img_after_move=False): """ Plot the camera movement between two consecutive image frames :param image1: First image at time stamp t :param image1_points: Feature vector for the first image :param image2: First image...
5f92bf44885e62ebdc502e8c98ba1466cb8d5279
3,640,246
def get_rgb_masks(data, separate_green=False): """Get the RGGB Bayer pattern for the given data. See `get_rgb_data` for description of data. Args: data (`numpy.array`): An array of data representing an image. separate_green (bool, optional): If the two green channels should be separated, ...
cf31103ca4248ccd96fb89181d0e48d5b71201c5
3,640,247
def _parse_ax(*args, **kwargs): """ Parse plotting *args, **kwargs for an AxesSubplot. This allows for axes and colormap to be passed as keyword or position. Returns AxesSubplot, colormap, kwargs with *args removed""" axes = kwargs.pop('axes', None) cmap = kwargs.get('cmap', None) if ...
78658e2cf66fad184c057b9392b918ffb48406be
3,640,248
import google.colab # noqa: F401 import IPython import IPython def _get_context(): """Determine the most specific context that we're in. Implementation from TensorBoard: https://git.io/JvObD. Returns: _CONTEXT_COLAB: If in Colab with an IPython notebook context. _CONTEXT_IPYTHON: If not in Colab...
b81205aedbe2222019fa6b7e9dc5fb638536869f
3,640,249
def loadSHSMFCCs(IDs): """ Load all of the 12-dim MFCC features """ IDDict = getSHSIDDict() fin = open("SHSDataset/MFCC/bt_aligned_mfccs_shs.txt") mfccs = {} count = 0 while True: ID = fin.readline().rstrip() if not ID: break ID = IDDict[ID] if...
04d82be79d6e89c5f9b6304be82d049bf6af63f5
3,640,250
def __createTransactionElement(doc,tran): """ Return a DOM element represents the transaction given (tran) """ tranEle = doc.createElement("transaction") symbolEle = __createSimpleNodeWithText(doc, "symbol", tran.symbol) buyEle = __createSimpleNodeWithText(doc, "buy", "true" if tran.buy else "fa...
c09fc6abf4cb9599be23bcf6c91c6cc60330df0a
3,640,251
def received_information(update: Update, context: CallbackContext) -> int: """Store info provided by user and ask for the next category.""" text = update.message.text category = context.user_data['choice'] context.user_data[category] = text.lower() del context.user_data['choice'] update.message...
e7b93516975a497f6da11383969a14aeb31e6278
3,640,252
def set_payout_amount(): """ define amount of insurance payout NB must match what was defined in contract constructor at deployment """ return 500000e18
30ff7b07cbbe28b3150be2f1f470236875c8d0e3
3,640,253
def process_season_data(*args) -> pd.DataFrame: """ Takes multiple season data frames, cleans each and combines into single dataframe. """ return pd.concat( map( lambda df: basketball_reference.process_df_season_summary( df=df, url_type="season_summary_per_game" ...
9c2d46ba2b491382e91613e0dc0a35b68e4188cf
3,640,254
def build_frame(station_num: int, snapshots_num: int): """Function to build citi_bike Frame. Args: station_num (int): Number of stations. snapshot_num (int): Number of in-memory snapshots. Returns: CitibikeFrame: Frame instance for citi-bike scenario. """ matrices_cls = gen...
2fd09885f488a4b42f9a2a4a19dfdd5c10743ef9
3,640,255
def rucklidge(XYZ, t, k=2, a=6.7): """ The Rucklidge Attractor. x0 = (0.1,0,0) """ x, y, z = XYZ x_dt = -k * x + y * (a - z) y_dt = x z_dt = -z + y**2 return x_dt, y_dt, z_dt
9d10aa89fb684a95474d45399ae09a38b507913c
3,640,256
def multiext(prefix, *extensions): """Expand a given prefix with multiple extensions (e.g. .txt, .csv, _peaks.bed, ...).""" if any((r"/" in ext or r"\\" in ext) for ext in extensions): raise WorkflowError( r"Extensions for multiext may not contain path delimiters " r"(/,\)." ) re...
39bda078a856cb14fc65174ff48be81909b9034a
3,640,258
def sum_range(n, total=0): """Sum the integers from 1 to n. Obviously the same as n(n+1)/2, but this is a test, not a demo. >>> sum_range(1) 1 >>> sum_range(100) 5050 >>> sum_range(100000) 5000050000L """ if not n: return total else: raise TailCall(sum_range...
6126dd1012346a388ddc37c5a8965f3662b8ad7d
3,640,259
from tcrsampler.sampler import TCRsampler def _default_tcrsampler_human_beta(default_background = None, default_background_if_missing=None): """ Responsible for providing the default human beta sampler 'britanova_human_beta_t_cb.tsv.sampler.tsv' Returns ------- t : tcrsampler.sampler.TCRsampler ...
15b682b3e14e9496514efaf287b10ae6acb12441
3,640,261
def _get_positive_mask(positive_selection, cls_softmax, cls_gt): """Gets the positive mask based on the ground truth box classifications Args: positive_selection: positive selection method (e.g. 'corr_cls', 'not_bkg') cls_softmax: prediction classification softmax scores cls...
8a8e4317f99f691c038b40d7656656f532eba884
3,640,263
def max_min_index(name_index): """Return maximum and minimum value with country of a column from df.""" country_and_name = df_copy[["country", name_index]] counrties_in_name_index = country_and_name.sort_values(name_index).dropna() min_value = [ list(counrties_in_name_index[name_index])[0], ...
7bce42a4d05b52b8e6f0a6d91cecf7775a9484a4
3,640,264
def add_bold_line(latex: str, index: int) -> str: """Makes a provided line number bold """ lines = latex.splitlines() cells = lines[index].split("&") lines[index] = r'\bfseries ' + r'& \bfseries '.join(cells) return '\n'.join(lines)
637338ea9ec576c780ccfa0b37d47a670465cdbb
3,640,265
def square(V,resp,weight): """Computes the expansion coefficients with a least squares regression""" if np.any(weight): Vt = V.T v1 = Vt.dot(np.transpose(weight*Vt)) v2 = Vt.dot(np.transpose(weight*resp.T)) coef = np.linalg.solve(v1,v2) else: coef = np.linalg.lstsq(V,r...
076f580a16c233a087edafb1efd57b9fa194a666
3,640,266
def _unwrap_function(func): """Unwrap decorated functions to allow fetching types from them.""" while hasattr(func, "__wrapped__"): func = func.__wrapped__ return func
8c7a9f5b08dc91b9ae2c8387fbd4860bb554d561
3,640,267
def get_data(exception: bool = True, key_form: str = "data") -> "dict or None": """Função captura os dados de uma rota. A captura é feita caso a rota seja com `JSON` ou `Multipart-form` caso contrario lança um exceção. As imagens são capturadas na função `get_files`. `exception` campo boleano opcional ...
15cd4257e7849d4400231d7e5c2a025b16ad7db5
3,640,268
def get_dec_log(uid): """Convenience method to look up inc_log for a uid.""" rv = query_db('select dec_log from user where uid = ?', [uid], one=True) return rv[0] if rv else None
8927ce657cbabfd1e0f4e852e6163702ab5b3841
3,640,269
def removeItem(request): """ Removes item from logged in customers basket. """ if request.method == 'POST': cust = User.objects.get(username=request.user.username) item_id = request.POST["item_id"] item = Item.objects.get(id=item_id) b_item = Basket.objects.get(customer=cust, item=item) if(b_item): b_i...
80514a322f727478311b7a1b49bd9da8ac7b0d28
3,640,270
def read_file(repo, name): """Read JSON files.""" with open(repo + '/' + name + '.txt') as file: data = [d.rstrip() for d in file.readlines()] file.close() return data
4d91e4c68a4f132dc6ebb41cc51df66bd555107a
3,640,271
def add_end_slash(value: str): """ Added a slash at the end of value """ if type(value) != str: return value return value if value.endswith("/") else value + "/"
bc8f41898c50120ad7ca8b814ff03d19c1c64c27
3,640,272
def shift_fill(a, n, axis=0, fill=0.0, reverse=False): """ shift n spaces backward along axis, filling rest in with 0's. if n is negative, shifts forward. """ shifted = np.roll(a, n, axis=axis) shifted[:n] = fill return shifted
5287eefe7491442e3192069bce4faf975e54344a
3,640,273
from typing import Union def str2bool(v:Union[str, bool]) -> bool: """ finished, checked, converts a "boolean" value possibly in the format of str to bool Parameters ---------- v: str or bool, the "boolean" value Returns ------- b: bool, `v` in the format of bool ...
2f102239ce395ece25022320443ffc6d7183968e
3,640,274
def _none_or_int_or_list(val): """Input conversion - expecting None, int, or a list of ints""" if val is None: return None elif isinstance(val, list): return list(map(int, val)) else: return int(val)
1958c64175a1cd63f8a42044b40b84d7cf8baed2
3,640,275
def hour_of_day(datetime_col): """Returns the hour from a datetime column.""" return datetime_col.dt.hour
18b2f6e16ccbcb488f3863968466fda14f669d8b
3,640,276
def pad_lists(lists, pad_token, seq_lens_idx=[]): """ Pads unordered lists of different lengths to all have the same length (max length) and orders length descendingly Arguments: lists : list of 1d lists with different lengths (list[list[int]]) pad_token : padding value (int) seq...
76a2a9934dfca478e7db43a93db7e56c181a3b3f
3,640,277
def sum_naturals(n): """Sum the first N natural numbers >>> sum_naturals(5) 15 """ total = 0 k = 1 while k <= n: total += k k += 1 return total
4c59057cd82083d615c72a59f682dd218a657ea0
3,640,278
def _gaussian_log_sf(x, mu, sigma): """Log SF of a normal distribution.""" if not isinstance(x, chainer.Variable): x = chainer.Variable(x) return _log_ndtr(-(x - mu) / sigma)
3f33918bf78fc3ab4064f05d038232df218416f6
3,640,279
def sort_list_files(list_patches, list_masks): """ Sorts a list of patches and masks depending on their id. :param list_patches: List of name of patches in the folder, that we want to sort. :param list_masks: List of name of masks in the folder, that we want to sort. :return: List of sorted lists, r...
91557475bf145862ea88ad9f86cef82135eddd6c
3,640,280
def get_model(name): """ get_model """ if name not in __factory: raise KeyError("unknown model:", name) return __factory[name]
00fff4e3596aec487b16fd1114b7d026d6790568
3,640,281
def check_sentence_for_coins(sentence: str) -> str: """Returns the corresponding binance pair if a string contains any words refering to a followed coins Args: sentence (str): the sentence Returns: str: the binance pair if it contains a coins, otherwise returns 'NO_PAIR' """ coin = n...
a9d041ff6c2bcca1c424b059956c33016f93300d
3,640,283
def to24Bit(color8Bit): """The method allows you to convert the 8-bit index created by the color.to8Bit method to 24-bit color value.""" # We ignore first one, so we need to shift palette indexing by one return palette[color8Bit + 1]
b84d2262883a7b3415ae46f174418dc79ef800dc
3,640,284
def make_bag(): """Create a bag.""" return from_sequence( [1, 2], npartitions=2 ).map(allocate_50mb).sum().apply(no_allocate)
8c939dd389ab09811dbbf77aaf479832ab7463d0
3,640,286
def get_testdata_files(pattern="*"): """ Return test data files from dicom3d data root directory """ data_path = join(DATA_ROOT, 'test_files') files = walk_data( base=data_path, pattern=pattern, search_files=True, search_dirs=False) return [filename for filename in files if not filename.endswith('.py')]
9739db355914b288b2fcb29874fcc50d6a2b4487
3,640,287
def safe_text(obj): """Safely turns an object into a textual representation. Calls str(), then on Python 2 decodes the result. """ result = qcore.safe_str(obj) if isinstance(result, bytes): try: result = result.decode("utf-8") except Exception as e: result =...
4d20d5c42b79b6dbb6f8282d74bfd461ffd1dc75
3,640,288
from typing import List def evaluate_blueprints(blueprint_q: mp.Queue, input_size: List[int]) -> List[BlueprintGenome]: """ Consumes blueprints off the blueprints queue, evaluates them and adds them back to the queue if all of their evaluations have not been completed for the curre...
c87d0a37fe32d2af6594564afc44d16adf616737
3,640,289
import tempfile import shlex def run_noble_coder(text, noble_coder): """ Run Noble Coder Args: text: the text to feed into Noble Coder noble_coder: the execution path of Noble Coder Returns: The perturbation agent """ pert_agent = None with tempfile.TemporaryDirect...
20bcee89ddda7c8abc108a42621867017a7e4d63
3,640,290
def xor(*args): """True if exactly one of the arguments of the iterable is True. >>> xor(0,1,0,) True >>> xor(1,2,3,) False >>> xor(False, False, False) False >>> xor("kalimera", "kalinuxta") False >>> xor("", "a", "") True >>> xor("", "", "") False """ retur...
86bbe0350dd18a2508120cec9672661e1aa56ce0
3,640,291
def zjitter(jitter=0.0, radius=5): """ scan jitter is in terms of the fractional pixel difference when moving the laser in the z-direction """ psfsize = np.array([2.0, 1.0, 3.0]) # create a base image of one particle s0 = init.create_single_particle_state(imsize=4*radius, radiu...
7fae2f750cd80708e7cd881a05d535a00b4ecb38
3,640,293
def append_column(rec, col, name=None, format=None): """ Append a column to the end of a records array. Parameters ---------- rec : recarray Records array. col : array_like Array or similar object which will be converted into the new column. name : str, optional Name...
f851ef69946937cbb100d424ddb8502b906940bd
3,640,294
import copy def dfa2nfa(dfa): """Copy DFA to an NFA, so remove determinism restriction.""" nfa = copy.deepcopy(dfa) nfa.transitions._deterministic = False nfa.automaton_type = 'Non-Deterministic Finite Automaton' return nfa
eed8e651a51e71599a38288665604add3d8a0a3d
3,640,295