content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_state(module_instance, incremental_state, key_postfix): """ Helper for extracting incremental state """ if incremental_state is None: return None full_key = _get_full_key(module_instance, key_postfix) return incremental_state.get(full_key, None)
b3ba8f10fd26ed8878cb608076873cad52a19841
3,647,650
def get_lenovo_urls(from_date, to_date): """ Extracts URL on which the data about vulnerabilities are available. :param from_date: start of date interval :param to_date: end of date interval :return: urls """ lenovo_url = config['vendor-cve']['lenovo_url'] len_p = LenovoMainPageParser(l...
503f078d9a4b78d60792a2019553f65432c21320
3,647,651
def normalize_batch_in_training(x, gamma, beta, reduction_axes, epsilon=1e-3): """ Computes mean and std for batch then apply batch_normalization on batch. # Arguments x: Input tensor or variable. gamma: Tensor by which to scale the input. beta: Tens...
2c1cc9368438cbd62d48c71da013848068a7664e
3,647,652
def itemAPIEndpoint(categoryid): """Return page to display JSON formatted information of item.""" items = session.query(Item).filter_by(category_id=categoryid).all() return jsonify(Items=[i.serialize for i in items])
33abd39d7d7270fe3b040c228d11b0017a8b7f83
3,647,654
def command(settings_module, command, bin_env=None, pythonpath=None, *args, **kwargs): """ run arbitrary django management command """ da = _get_django_admin(bin_env) cmd = "{0} {1} --settings={2}".format(da, command, settings_module) if pythonpat...
6f7f4193b95df786d6c1540f4c687dec89cf01a6
3,647,655
def read_input(fpath): """ Read an input file, and return a list of tuples, each item containing a single line. Args: fpath (str): File path of the file to read. Returns: list of tuples: [ (xxx, xxx, xxx) ] """ with open(fpath, 'r') as f: data = [...
ceeb418403bef286eda82ba18cd0ac8e4899ea4f
3,647,656
def find_level(key): """ Find the last 15 bits of a key, corresponding to a level. """ return key & LEVEL_MASK
30c454220e6dac36c1612b5a1a5abf53a7a2911c
3,647,658
def _whctrs(anchor): """return width, height, x center, and y center for an anchor (window).""" w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) return w, h, x_ctr, y_ctr
e1a6ff1745aac77e80996bfbb98f42c18af059d7
3,647,659
def filter_tiddlers(tiddlers, filters, environ=None): """ Return a generator of tiddlers resulting from filtering the provided iterator of tiddlers by the provided filters. If filters is a string, it will be parsed for filters. """ if isinstance(filters, basestring): filters, _ = parse_...
25c86fdcb6f924ce8349d45b999ebe491c4b6299
3,647,660
def apply_move(board_state, move, side): """Returns a copy of the given board_state with the desired move applied. Args: board_state (3x3 tuple of int): The given board_state we want to apply the move to. move (int, int): The position we want to make the move in. side (int): The side we...
b47da6ddab3bd1abf99ee558471a3696e46b8352
3,647,661
import copy from functools import reduce def merge(dicts, overwrite=False, append=False, list_of_dicts=False): """ merge dicts, starting with dicts[1] into dicts[0] Parameters ---------- dicts : list[dict] list of dictionaries overwrite : bool if true allow overwriting of curr...
fdbde1c83f2fbcb74be5c4fb1376af4981655ad7
3,647,662
import re def compute_delivery_period_index(frequency = None, delivery_begin_dt_local = None, delivery_end_date_local = None, tz_local = None, profile ...
4eb47c857a235a7db31624dc78c83f291f0ba67a
3,647,663
def make_proxy(global_conf, address, allowed_request_methods="", suppress_http_headers=""): """ Make a WSGI application that proxies to another address: ``address`` the full URL ending with a trailing ``/`` ``allowed_request_methods``: a space seperated list of request m...
054bcce2d10db2947d5322283e4e3c87328688cb
3,647,664
import unittest def test(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('eachday/tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 r...
3d8fcfada7309e62215fd2b3a1913ed51d5f14f8
3,647,665
async def save_training_result(r: dependency.TrainingResultHttpBody): """ Saves the model training statistics to the database. This method is called only by registered dataset microservices. :param r: Training Result with updated fields sent by dataset microservice :return: {'status': 'success'} i...
60302a3053a8be3781ad8da9e75b05aed85a5b06
3,647,666
def sort2nd(xs): """Returns a list containing the same elements as xs, but sorted by their second elements.""" xs.sort(cmp2nd) return xs
9b9ccef6794db2cfaa31492eeddb0d6344ff30e5
3,647,667
def is_one_of_type(val, types): """Returns whether the given value is one of the given types. :param val: The value to evaluate :param types: A sequence of types to check against. :return: Whether the given value is one of the given types. """ result = False val_type = type(val) for tt ...
4bda5ebc41aa7377a93fdb02ce85c50b9042e2c1
3,647,668
def get_online(cheat_id): """Получение онлайна чита --- consumes: - application/json parameters: - in: path name: cheat_id type: string description: ObjectId чита в строковом формате responses: 200: desc...
bcfc0c44a0284ad298f533bdb8afd1e415be13b8
3,647,670
def grpc_client_connection(svc: str = None, target: str = None, session: Session = None) -> Channel: """ Create a new GRPC client connection from a service name, target endpoint and session @param svc: The name of the service to which we're trying to connect (ex. blue) @param target: The endpoint, assoc...
fc805b15c1d94bcde5ac4eacfc72d854f860f95f
3,647,671
def aqi(pm25): """AQI Calculator Calculates AQI from PM2.5 using EPA formula and breakpoints from: https://www.airnow.gov/sites/default/files/2018-05/aqi-technical -assistance-document-may2016.pdf Args: - pm25 (int or float): PM2.5 in ug/m3 """ if pm25 < 0: raise ValueErr...
199066221d91a527ea3c2f3f67a994eb13b7a708
3,647,672
from django.db import connection def require_lock(model, lock='ACCESS EXCLUSIVE'): """ Decorator for PostgreSQL's table-level lock functionality Example: @transaction.commit_on_success @require_lock(MyModel, 'ACCESS EXCLUSIVE') def myview(request) ... PostgreSQL's...
1cfa74246ddbde9840f5e519e1481cd8773fb038
3,647,673
def welcome(): """List all available api routes.""" # Set the app.route() decorator for the "/api/v1.0/precipitation" route return ( f"Available Routes:<br/>" f"/api/v1.0/names<br/>" f"/api/v1.0/precipitation" )
74d6509fede66bf4243b9e4a4e107391b13aef16
3,647,674
def pbootstrap(data, R, fun, initval = None, ncpus = 1): """ :func pbootstrap: Calls boot method for R iteration in parallel and gets estimates of y-intercept and slope :param data: data - contains dataset :param R: number of iterations :param func: optim - function to get estimate of y-intercept and slo...
f5d1b523969735ef30873f593472e79f8399622c
3,647,675
def _el_orb(string): """Parse the element and orbital argument strings. The presence of an element without any orbitals means that we want to plot all of its orbitals. Args: string (str): The element and orbitals as a string, in the form ``"C.s.p,O"``. Returns: dict: T...
654d085347913bca2fd2834816b988ea81ab7164
3,647,676
import numpy def create_LOFAR_configuration(antfile: str, meta: dict = None) -> Configuration: """ Define from the LOFAR configuration file :param antfile: :param meta: :return: Configuration """ antxyz = numpy.genfromtxt(antfile, skip_header=2, usecols=[1, 2, 3], delimiter=",") nants = a...
0ed07f1cdd0ef193e51cf88d336cbb421f6ea248
3,647,677
def fmla_for_filt(filt): """ transform a set of column filters from a dictionary like { 'varX':['lv11','lvl2'],...} into an R selector expression like 'varX %in% c("lvl1","lvl2")' & ... """ return ' & '.join([ '{var} %in% c({lvls})'.format( var=k, ...
149d23822a408ad0d96d7cefd393b489b4b7ecfa
3,647,678
def sfen_board(ban): """Convert ban (nrow*nrow array) to sfen string """ s = '' num = 0 for iy in range(nrow): for ix in range(nrow): i = iy*nrow + ix if ban[i]: if num: s += str(num) num = 0 s +=...
55bf08c39457278ff8aaca35f1dd5f3fd6955590
3,647,679
import time def join_simple_tables(G_df_dict, G_data_info, G_hist, is_train, remain_time): """ 获得G_df_dict['BIG'] """ start = time.time() if is_train: if 'relations' in G_data_info: G_hist['join_simple_tables'] = [x for x in G_data_info['relations'] if ...
ba625cee3d4ede6939b8e12ce734f85325044349
3,647,680
def create_epochs(data, events_onsets, sampling_rate=1000, duration=1, onset=0, index=None): """ Epoching a dataframe. Parameters ---------- data : pandas.DataFrame Data*time. events_onsets : list A list of event onsets indices. sampling_rate : int Sampling rate (sam...
d173b04d5e5835509a41b3ac2288d0d01ff54784
3,647,681
from typing import Type def is_equal_limit_site( site: SiteToUse, limit_site: SiteToUse, site_class: Type[Site] ) -> None: """Check if site is a limit site.""" if site_class == Site: return site.point.x == limit_site.x and site.point.y == limit_site.y elif site_class == WeightedSite: r...
1ebe8b18749bb42cf1e55e89a1e861b687f8881b
3,647,682
def get_header(filename): """retrieves the header of an image Args: filename (str): file name Returns: (str): header """ im = fabio.open(filename) return im.header
a3c195d23b671179bc765c081c0a1e6b9119a71d
3,647,683
def gaussian_ll_pdf(x, mu, sigma): """Evaluates the (unnormalized) log of the normal PDF at point x Parameters ---------- x : float or array-like point at which to evaluate the log pdf mu : float or array-like mean of the normal on a linear scale sigma : float or array-like ...
dbf1e389ad8349093c6262b2c595a2e511f2cb28
3,647,684
def _show_traceback(method): """decorator for showing tracebacks in IPython""" def m(self, *args, **kwargs): try: return(method(self, *args, **kwargs)) except Exception as e: ip = get_ipython() if ip is None: self.log.warn("Exception in widget ...
28909d57247d68200adf1e658ed4d3f7c36f0221
3,647,685
def ecdf(data): """Compute ECDF for a one-dimensional array of measurements.""" # Number of data points n = len(data) # x-data for the ECDF x = np.sort(data) # y-data for the ECDF y = np.arange(1, len(x)+1) / n return x, y
e0271f87e2c031a55c84de94dbfed34ec34d34f1
3,647,686
def import_module_part(request, pk): """Module part import. Use an .xlsx file to submit grades to a module part On GET the user is presented with a file upload form. On POST, the submitted .xlsx file is processed by the system, registering Grade object for each grade in the excel file. It dynamically ...
a915b426b8c870ee62a154a1370080e87a7de42f
3,647,687
from typing import Tuple def ordered_pair(x: complex) -> Tuple[float, float]: """ Returns the tuple (a, b), like the ordered pair in the complex plane """ return (x.real, x.imag)
c67e43cf80194f7a5c7c5fd20f2e52464816d056
3,647,688
from FuXi.Rete.RuleStore import SetupRuleStore def HornFromDL(owlGraph, safety=DATALOG_SAFETY_NONE, derivedPreds=[], complSkip=[]): """ Takes an OWL RDF graph, an indication of what level of ruleset safety (see: http://code.google.com/p/fuxi/wiki/FuXiUserManual#Rule_Safety) to apply, and a list of der...
37dfe479dd0f150956261197b47cfbd468285f92
3,647,690
def _assembleMatrix(data, indices, indptr, shape): """ Generic assemble matrix function to create a CSR matrix Parameters ---------- data : array Data values for matrix indices : int array CSR type indices indptr : int array Row pointer shape : tuple-like ...
6ada37b14270b314bcc6ba1ef55da10c07619731
3,647,691
def mock_state_store(decoy: Decoy) -> StateStore: """Get a mocked out StateStore.""" return decoy.mock(cls=StateStore)
db8e9e99dcd4bbc37094b09febb63c849550bc81
3,647,692
from typing import Callable from typing import List def beam_search_runner_range(output_series: str, decoder: BeamSearchDecoder, max_rank: int = None, postprocess: Callable[ [List[str]], List[str]]=...
01c63368219f4e1c95a7557df585893d68134478
3,647,693
def read_variants( pipeline, # type: beam.Pipeline all_patterns, # type: List[str] pipeline_mode, # type: PipelineModes allow_malformed_records, # type: bool representative_header_lines=None, # type: List[str] pre_infer_headers=False, # type: bool sample_name_encoding=SampleNameEncodin...
5f706219ccc5a5f59980122b4fdac93e35056f5d
3,647,694
import numpy def carla_location_to_numpy_vector(carla_location): """ Convert a carla location to a icv vector3 Considers the conversion from left-handed system (unreal) to right-handed system (icv) :param carla_location: the carla location :type carla_location: carla.Location :return: a ...
a207ec5d878a07e62f96f21cd33c980cb1e5dacc
3,647,695
def prev_cur_next(lst): """ Returns list of tuples (prev, cur, next) for each item in list, where "prev" and "next" are the previous and next items in the list, respectively, or None if they do not exist. """ return zip([None] + lst[:-1], lst, lst[1:]) + [(lst[-2], lst[-1], None)]
c00cd27e1eaeffd335a44ac625cb740f126a06e5
3,647,696
import pathlib def vet_input_path(filename): """ Check if the given input file exists. Returns a pathlib.Path object if everything is OK, raises InputFileException if not. """ putative_path = pathlib.Path(filename) if putative_path.exists(): if not putative_path.is_file(): ...
9c517cf9e56781b995d7109ea0983171760cf58c
3,647,697
import requests def check_for_updates(repo: str = REPO) -> str: """ Check for updates to the current version. """ message = "" url = f"https://api.github.com/repos/{repo}/releases/latest" response = requests.get(url) if response.status_code != 200: raise RuntimeError( ...
0d3b37a74e252552f1e912a0d7072b60a34de86d
3,647,698
def _process_image(record, training): """Decodes the image and performs data augmentation if training.""" image = tf.io.decode_raw(record, tf.uint8) image = tf.cast(image, tf.float32) image = tf.reshape(image, [32, 32, 3]) image = image * (1. / 255) - 0.5 if training: padding = 4 image = tf.image.re...
0a255d954c7ca537f10be6ac5c077fd99aaf72cd
3,647,699
def svn_diff_fns2_invoke_token_discard(*args): """svn_diff_fns2_invoke_token_discard(svn_diff_fns2_t _obj, void diff_baton, void token)""" return _diff.svn_diff_fns2_invoke_token_discard(*args)
cdfd25973cf87190a6f82b07c82e741233c65fcd
3,647,700
import torch def process_bb(model, I, bounding_boxes, image_size=(412, 412)): """ :param model: A binary model to create the bounding boxes :param I: PIL image :param bounding_boxes: Bounding boxes containing regions of interest :param image_size: Choose the size of the patches :return: Patche...
2029fa67fb85ce3e15913ce9c1684cbe762ea3b7
3,647,701
def roc( observations, forecasts, bin_edges="continuous", dim=None, drop_intermediate=False, return_results="area", ): """Computes the relative operating characteristic for a range of thresholds. Parameters ---------- observations : xarray.Dataset or xarray.DataArray Lab...
328e00060c758ddf3c12cecdec1961561bb2d3f3
3,647,702
from typing import Literal def make_grammar(): """Creates the grammar to be used by a spec matcher.""" # This is apparently how pyparsing recommends to be used, # as http://pyparsing.wikispaces.com/share/view/644825 states that # it is not thread-safe to use a parser across threads. unary_ops = (...
aef2a3fc897c42e61ebd81c9d43cb42f342b1fb6
3,647,703
def _pull(keys): """helper method for implementing `client.pull` via `client.apply`""" if isinstance(keys, (list,tuple, set)): return [eval(key, globals()) for key in keys] else: return eval(keys, globals())
779fcec45c3693bdd8316c14138a88c57f0c318c
3,647,704
def position(df): """ 根据交易信号, 计算每天的仓位 :param df: :return: """ # 由 signal 计算出实际每天持有的股票仓位 df['pos'] = df['signal'].shift(1) df['pos'].fillna(method='ffill', inplace=True) # 将涨跌停时不得买卖股票考虑进来 # 找出开盘涨停的日期 cond_cannot_buy = df['开盘价'] > df['收盘价'].shift(1) * 1.097 # 今天的开盘价相对于昨天的收盘价上...
15666e26cf8a9d6ae98ff1746aecab759de9139b
3,647,705
def prepare_data(data, preprocessed_data, args): """Prepare Data""" data = data.to_numpy() train_size = int(len(data) * args.train_split) test_size = len(data) - train_size train_X = preprocessed_data[0:train_size] train_Y = data[0:train_size] test_X = preprocessed_data[train_size:len(pre...
b5e120eebd6060656d71f8f76755afd0d8eccce5
3,647,706
def svn_client_conflict_tree_get_victim_node_kind(conflict): """svn_client_conflict_tree_get_victim_node_kind(svn_client_conflict_t * conflict) -> svn_node_kind_t""" return _client.svn_client_conflict_tree_get_victim_node_kind(conflict)
6258c011eb947ddedb1e060cd036ddcf9cbc1758
3,647,707
import importlib def load_module(script_path: str, module_name: str): """ return a module spec.loader.exec_module(foo) foo.A() """ spec = importlib.util.spec_from_file_location(module_name, script_path) module = importlib.util.module_from_spec(spec) return spec, module
61ebc105d0c7a168b37210452445e8e24e16f87a
3,647,708
def memory_func(func): """ декоратор для замера памяти занимаемой функцией в оперативной памяти. """ def wrapper(*args, **kwargs): proc = Process(getpid()) # получение идентификатора текущего процесса и объявление класса start_memory = proc.memory_info().rss # сохранение начального зна...
a8c634b3415925b65fe35df584328705eb0d171e
3,647,710
def read_data(datafile='sampling_data_2015.txt'): """Imports data from an ordered txt file and creates a list of samples.""" sample_list = [] with open(datafile, 'r') as file: for line in file: method, date, block, site, orders = line.split('|') new_sample = sample(method, da...
4aee4b2ef0cd9d31eefbd9f394714f0ea789b49d
3,647,711
async def get_https(method: str = "all"): """Get https proxies from get_proxies_func() function.""" return await get_proxies_func("https", method)
575eccf2149724c29062d866fcc420fe3b34be78
3,647,712
def apply_mask(input, mask): """Filter out an area of an image using a binary mask. Args: input: A three channel numpy.ndarray. mask: A black and white numpy.ndarray. Returns: A three channel numpy.ndarray. """ return cv2.bitwise_and(input, input, mask=mask)
34451c71b9f18a64f5b27e3ff9269a9c4e3b803d
3,647,716
import requests import json def fetch_track_lyrics(artist, title): """ Returns lyrics when found, None when not found """ MUSIXMATCH_KEY = get_musixmatch_key() api_query = 'https://api.musixmatch.com/ws/1.1/matcher.lyrics.get?' api_query += 'q_track=%s&' % title api_query += 'q_artist=%s&' % arti...
f8e049578bb8c6b52636fd1e1789a81af30b28e6
3,647,718
def string_avg(strings, binary=True): """ Takes a list of strings of equal length and returns a string containing the most common value from each index in the string. Optional argument: binary - a boolean indicating whether or not to treat strings as binary numbers (fill in leading zeros if lengths...
3d515cbeedc93b95c5f38de62000629002e41166
3,647,719
def refresh(): """Pull fresh data from Open AQ and replace existing data.""" DB.drop_all() DB.create_all() api = openaq.OpenAQ() status, body = api.measurements(city='Los Angeles', parameter='pm25') reading_list = [] for reading in body['results']: object = Record(datetime = reading[...
9fcf71ffe0e5a46119e98f17c12aae29721285c8
3,647,720
import json def update_organization(current_user): """ Обновление информации об организации. """ try: if CmsUsers.can(current_user.id, "put", "contacts"): organization = CmsOrganization.query.first() update_data = request.get_json() for key in list(update_data.k...
ff7826b1b4537eb0b793b426a6b6aa097936bfa9
3,647,721
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_sep] sep_base_path=/sepm/api/v1 sep_auth_path=/sepm/api/v1/identity/authenticate sep_host=<SEPM server dns name or ip address> sep_port=...
fcad9aa412d66b4a48dfb753d64e0f84979df617
3,647,722
def read_eieio_command_message(data, offset): """ Reads the content of an EIEIO command message and returns an object\ identifying the command which was contained in the packet, including\ any parameter, if required by the command :param data: data received from the network :type data: byte...
05abce201acf3b706e4b476c15eb2af5a0102cc8
3,647,723
def quote(): """Get stock quote.""" if request.method == "POST": # Get values get_symbol = request.form.get("symbol") stock = lookup(get_symbol) # Ensure symbol was submitted if not get_symbol: return apology("must provide symbol") # Ensure symbol ...
b26c04c01e5ddb26c19e555a45e3fac6f58c0fef
3,647,724
def counts_to_df(value_counts, colnames, n_points): """DO NOT USE IT! """ pdf = pd.DataFrame(value_counts .to_frame('count') .reset_index() .apply(lambda row: dict({'count': row['count']}, **d...
85d5283f2d53dcf3ec33d7a1f3f52d9acc0affde
3,647,725
import math def make_pair_plot(samples, param_names=None, pair_plot_params=PairPlotParams()): """ Make a pair plot for the parameters from posterior destribution. Parameters ----------- samples : Panda's DataFrame Each column contains samples from posterior distributi...
73f5d8fc7dee8b3179cb8c1513eb2989c788e7cf
3,647,726
def read_meta_soe(metafile): """read soe metadata.csv to get filename to meta mapping""" wavfiles = csv2dict(metafile) return {f['fid']:{k:v for (k,v) in f.items() if k!='fid'} for f in wavfiles}
51f82a45d12b332d9edbe7b027dc7ee2582af35b
3,647,727
def send_message(message, string, dm=False, user=None, format_content=True): """send_message Sends a message with string supplied by [lang]_STRING.txt files. :param message: MessageWrapper object with data for formatting. :param string: Name of the string to read. :param dm: Whether the message shou...
c8396108126fcaea735a94be3dcd4ed954f43d70
3,647,728
def calc_torque(beam, fforb, index=False): """ Calculates torque from a neutral beam (or beam component) torque = F * r_tan = (P/v) * r_tan = (P/sqrt(2E/m)) * r_tan = P * sqrt(m/(2E)) * r_tan :param fforb: :param index: :param beam: beam object with attributes z, m, a, en, pwr, rtan :return: t...
55cb8172f874a1d25c6dcf36c693f818d11d59c4
3,647,729
def cli(ctx, user_id): """Create a new API key for a given user. Output: the API key for the user """ return ctx.gi.users.create_user_apikey(user_id)
d7dafd77ef983286184b6f5aa2362bb734389696
3,647,730
import re def whitespace_tokenizer(text): """Tokenize on whitespace, keeping whitespace. Args: text: The text to tokenize. Returns: list: A list of pseudo-word tokens. """ return re.findall(r"\S+\s*", text)
e79234b15912fdc225e2571788844732296f93d7
3,647,731
def _u2i(number): """ Converts a 32 bit unsigned number to signed. If the number is negative it indicates an error. On error a pigpio exception will be raised if exceptions is True. """ v = u2i(number) if v < 0: if exceptions: raise error(error_text(v)) return v
920a2dcbf68df34141c482c2318917ccff248501
3,647,732
def apply_once(func, arr, axes, keepdims=True): """ Similar to `numpy.apply_over_axes`, except this performs the operation over a flattened version of all the axes, meaning that the function will only be called once. This only makes a difference for non-linear functions. Parameters ---------- ...
939eea81d4443a4ef144105b1cc9335000b20f49
3,647,733
from io import BytesIO def bytes_to_bytesio(bytestream): """Convert a bytestring to a BytesIO ready to be decoded.""" fp = BytesIO() fp.write(bytestream) fp.seek(0) return fp
d59e4f5ccc581898da20bf5d3f6e70f8e8712aa6
3,647,734
from typing import List def image_scatter_channels(im: Image, subimages=None) -> List[Image]: """Scatter an image into a list of subimages using the channels :param im: Image :param subimages: Number of channels :return: list of subimages """ image_list = list() if subimages is None:...
f87cb88ef060a6d093dacabdaab0ebc94861b734
3,647,735
def unauthorized_handler(): """ If unauthorized requests are arrived then redirect sign-in URL. :return: Redirect sign-in in page """ current_app.logger.info("Unauthorized user need to sign-in") return redirect(url_for('userView.signin'))
72b505ae13023aea23e0353b6571da64d9f647b8
3,647,736
import posixpath def pre_order_next(path, children): """Returns the next dir for pre-order traversal.""" assert path.startswith('/'), path # First subdir is next for subdir in children(path): return posixpath.join(path, subdir) while path != '/': # Next sibling is next name = posixpath.basenam...
fcbe2b17b29396ac978f4a931a454c988e6fe05b
3,647,737
def gettiming(process_list, typetiming): """ Used to get a sort set for different duration needed to conver to morse code. """ timing = [] for x in process_list: if(x[0] == typetiming): timing.append(x[3]) timing = set(timing) return sorted(timing)
8e71449eacaee086f9f9147e1c3b8602ce8e553f
3,647,738
import click def init(): """Top level command handler.""" @click.command() @click.option('--approot', type=click.Path(exists=True), envvar='TREADMILL_APPROOT', required=True) @click.argument('eventfile', type=click.Path(exists=True)) def configure(approot, eventfile): ""...
2c24fe8dc2225b7f2f848ac3d2ef09275829c754
3,647,739
def tobooks(f: '(toks, int) -> DataFrame', bks=bktksall) -> DataFrame: """Apply a function `f` to all the tokens in each book, putting the results into a DataFrame column, and adding a column to indicate each book. """ return pd.concat([f(v, i) for i, v in bks.items()])
e081e1c01d68b7b84cb6395f32f217360657636f
3,647,741
def _identity_error_message(msg_type, message, status_code, request): """ Set the response code on the request, and return a JSON blob representing a Identity error body, in the format Identity returns error messages. :param str msg_type: What type of error this is - something like "badRequest"...
d73e182fc794f01c3415069ffeb37e76a01df7af
3,647,742
def _string_to_list(s, dtype='str'): """ converts string to list Args: s: input dtype: specifies the type of elements in the list can be one of `str` or `int` """ if ' <SENT/> ' in s: return s.split(' <SENT/> ') elif dtype == 'int': return [int(e) for e in s.split(L...
9d2950afcd9f47e1fef7856af117953dbf99410a
3,647,743
import warnings def internal_solve_pounders( criterion, x0, lower_bounds, upper_bounds, gtol_abs, gtol_rel, gtol_scaled, maxinterp, maxiter, delta, delta_min, delta_max, gamma0, gamma1, theta1, theta2, eta0, eta1, c1, c2, solver_sub, ...
c3f602af6f78a1cb57c15a6488e4aeadcd081951
3,647,744
import torch def get_overlap_info(bbox): """ input: box_priors: [batch_size, number_obj, 4] output: [number_object, 6] number of overlapped obj (self not included) sum of all intersection area (self not included) sum of IoU (Intersection over Union) average of all i...
451507a49fca589bc1102b085eab551ebe32bcc7
3,647,745
def get_current_language(request, set_default=True, default_id=1): """ Description: Returns the current active language. Will set a default language if none is found. Args: request (HttpRequest): HttpRequest from Django set_default (Boolean): Indicates if a default language must be a...
98bc2a25201dc87afcee24d8ff5d10fcab7849bb
3,647,746
def is_leap_year(year): """ returns True for leap year and False otherwise :param int year: calendar year :return bool: """ # return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) return year % 100 != 0 or year % 400 == 0 if year % 4 == 0 else False
5bd0bb7a44dc7004b9198cb3d8ed244dc02417c2
3,647,747
def update_search_params(context, **kwargs): """Update the set parameters of the current request""" params = context["request"].GET.copy() for k, v in kwargs.items(): params[k] = v return params.urlencode()
e3ce5a5a1dadc90bb544a761e154214d7a538f30
3,647,748
def dynamic2message(dynamic_dict: dict) -> Message: """ 将从api获取到的原始动态转换为消息 """ author_name = dynamic_dict['desc']['user_profile']['info']['uname'] dynamic_id = dynamic_dict['desc']['dynamic_id'] if dynamic_dict['desc']['type'] == 1: # 转发或投票 text = f"用户[{author_name}]转发了动态:\n" + dynamic_...
b5330876cb58bf71c73ef9f4d3cbcdd0e583aba6
3,647,749
def dem_to_roughness(src_raster, band=0): """Calculate the roughness for the DEM. Parameters ---------- src_raster : Raster The dem used to calculate the roughness. band : int, optional, default: 0 source band number to use. Returns ------- dst_raster: Raster ro...
f8ba073560aaf18ab9101befc5a3d1727a7cb93e
3,647,750
from typing import Any from typing import List def batch_matmul_checker( attrs: Any, args: List[relay.expr.Expr], op_name: str ) -> bool: # pylint: disable=unused-variable """Check if dense is supported by TensorRT.""" if get_tensorrt_use_implicit_batch_mode() and len(args[0].checked_type.shape) != len( ...
6c83ce1116a88e864bd577ee2dd7d669d43c43a3
3,647,752
def func_run_dynamic(input_file, dynamic_dic, exclude, pprint): """ Execute one dynamic template :param input_file: (string) The template file name :param dynamic_dic: (dict) The dictionary of the dynamic variables :return: """ new_template_filename = create_dynamic_template(input_file, dyn...
9432eadb4e3735a06f35aedd8fd9bb175ab2ba55
3,647,753
import ctypes def xclGetDeviceInfo2 (handle, info): """ xclGetDeviceInfo2() - Obtain various bits of information from the device :param handle: (xclDeviceHandle) device handle :param info: (xclDeviceInfo pointer) Information record :return: 0 on success or appropriate error number """ li...
794b6208c19a4f982a9fffb9270a3485299b62eb
3,647,755
def template_failure(request, status=403, **kwargs): """ Renders a SAML-specific template with general authentication error description. """ return render(request, 'djangosaml2/login_error.html', status=status)
fbcc8ad756213b4ba7f44d799c67b67beaad18f8
3,647,756
def zflatten2xyz(z, x=None, y=None): """ flatten an nxm 2D array to [x, y, z] of shape=(n*m, 3)""" if x is None: x = np.arrange(0, z.shape[0], step=1) if y is None: y = np.arrange(0, z.shape[1], step=1) xlen = len(x) ylen = len(y) assert z.shape[0] == xlen and z.shape[1] == ylen,...
96fcc9755660a85f5501958cf3f7d8c7a0e35b69
3,647,757
def penalized_log_likelihood(curve,t,pairwise_contact_matrix,a,b,term_weights,square_root_speed=None,pairwise_distance_matrix=None): """ penalized log likelihood """ if pairwise_distance_matrix is None: #if the do not already have the pairwise distance matrix computed, then compute it pairwise_d...
f26b5148b5f56be958d99714e5207417fd40a15d
3,647,758
def dict2array(X): """ Returns a Numpy array from dictionary Parameters ---------- X: dict """ all_var = [] for k in X.keys(): all_var.append(X[k]) return np.array(all_var)
e3d1ecabe9897af7c60a8e4be1e92603619d130a
3,647,760
import requests def dfs_level_details(): """This function traverses all levels in a DFS style. It gets the child directories and recursively calls the same function on child directories to extract its level details Returns: Dictionary: Key is the level name, value is a list with first element as ...
31cf9fdf49620798e9411dda1eda99b95411858b
3,647,762
import copy def makeNonParameterized(p): """Return a new Pointset stripped of its parameterization. """ if isinstance(p, Pointset) and p._isparameterized: return Pointset({'coordarray': copy(p.coordarray), 'coordnames': copy(p.coordnames), 'norm': ...
778eed55d3da10dcfb4681484cb31d6469009ae8
3,647,763