content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_user_data(user): """ Extrats user data to be save in the session """ extract_attrs = current_app.config.get('SESION_USER_FIELDS', []) user_data = {} for attr in extract_attrs: user_data[attr] = getattr(user, attr, None) return user_data
fdaff20825669a04a1973af400287119b28af5e0
50,200
import scipy def pv_optimize_orientation( objective, dfsun, info, tznode, elevation, solpos, dni_et, airmass, systemtype, yearsun, resolutionsun, dflmp=None, yearlmp=None, resolutionlmp=None, tzlmp=None, pricecutoff=None, max_angle=60, backtrack=True, gcr=1./3., dcac=1.3, l...
1a22c07efb113daa4e2f75484bcc7c194522c98a
50,201
def sanitize_metric_name(name): """Sanitize a metric name by removing double dots. :param name: Metric name :return: Sanitized metric name """ if name is None: return None return ".".join(_components_from_name(name))
6fa8e856d06b8ec374594a20b2376911fc428e6f
50,202
import argparse def get_parser(): """Args Description""" # current_year = datetime.datetime.today().year parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--data-dir", type=str, help="baseball data dire...
6063b667be373f823e481914ed0736dc86abcbb9
50,203
from typing import Union def multinomial_mode( distribution_or_probs: Union[tfd.Distribution, jnp.DeviceArray] ) -> jnp.DeviceArray: """Calculates the (one-hot) mode of a multinomial distribution. Args: distribution_or_probs: `tfp.distributions.Distribution` | List[tensors]. If the former...
233a19bdae03dd68650a322e7960e450fb241c53
50,204
import io def get_image(key): """Get image by key (index) from images preloaded when starting the viewer by preload_images(). """ key=int(key) img = images[key] img_buffer = io.BytesIO(img) return send_file(img_buffer, attachment_filename=str(key)+'.jpeg', mimetype='i...
9bf5897d5c40afc20375cabd39aa40d982af754c
50,205
from re import T import re def pql_PY(state: State, code_expr: T.string, code_setup: T.string.as_nullable() = objects.null): """Evaluate the given Python expression and convert the result to a Preql object Parameters: code_expr: The Python expression to evaluate code_setup: Setup code to prep...
0c642e7aa0e44d7e575c02765dcf8569fd5fa0ed
50,206
import json def load_statics(): """Reload all static content from their files""" global questions global static for file in ["admin", "end", "index", "question"]: with open("templates/" + file + ".html") as f: static[file] = f.read() for file in ["client"]: with open("...
5423930733860fcaca19a1f7eaeb93b553a28645
50,207
import os def set_env_variables(): """ Set different variables if the environment is running on a local machine or in the sandbox. :return: a tuple with a string and a boolean """ if 'SERVER_SOFTWARE' not in os.environ \ or os.environ['SERVER_SOFTWARE'].startswith('Development'): ...
33dee8f2367eea6d84d0228ce5e37a675fc45082
50,208
def farey_alg(n, largest_divisor=100): """ This started simple, but then i figured it could be really close and then come farther away again, so i changed it to a much more complicated one. It can still gives a closing range, but it now gives the best approximate it has come across, not the las...
30dd6815908aa9d05cb4387909e5aac37aa7bc4a
50,209
def clean(data, columns, inplace=False) -> pd.DataFrame: """ Cleans a dataframe :param data: the dataframe to clean :param columns: a single column name or list of column names to clean :param inplace: if True, changes are made to the specified column; otherwise, a 'cleaned' column is appended t...
27ccc2e2fe8ba1369b0f274d904424e6761f78d3
50,210
def vector_add(v, w): """向量加法""" return [v_i + w_i for v_i, w_i in zip(v, w)]
0030a6b83bc998167a1f25c6242bd657d030a937
50,211
def load_data( data_list, batch_categories=None, profile='RNA', join='inner', batch_key='batch', batch_name='batch', min_features=600, min_cells=3, n_top_features=2000, batch_size=64, chunk_size=CHUNK_SIZE, log=None,...
a67f54f2906d54ba71362879514afe83e521d718
50,212
def fast_p_val(A, B, axis=0, metric=np.mean, numResamples=10000): """Return the p value that metric(A) and metric(B) differ along an axis. Parameters ---------- A : array_like Array containing numbers of first group. B : array_like Array containing numbers of second group. ...
91a2655538e8d8cfa7ee05f9b6a2487972976c23
50,213
def api_categorize(): """ the API will receive a POST request containing a JSON with the labels title and tags, with the data provided it'll serve a category that best fit the data """ model = CategoryCLF() all_predicted = list() if not request.is_json: r = {"message": "Input is not...
0df3b39d757cb00ca583006c8aedd019db367052
50,214
def is_calldef_pointer(type): """returns True, if type represents pointer to free/member function, False otherwise""" if not is_pointer(type): return False nake_type = remove_alias( type ) nake_type = remove_const( nake_type ) nake_type = remove_volatile( nake_type ) return isinstance( n...
089f255d0497b2949641b13be735bc94f98379f7
50,215
def collate_amplifyers(): """Grab the RT and QT columns then concat assign post type and hashtag Returns: amplifyers: A dataframe with a filtered columns bearing the fields with the network """ select_columns = ['hit_sentence','influencer','post_type...
142f4eb219832b5cc66119487586a84b39e6420c
50,216
import time def _get_valid_stan_args(base_args=None): """Fill in default values for arguments not provided in `base_args`. RStan does this in C++ in stan_args.hpp in the stan_args constructor. It seems easier to deal with here in Python. """ args = base_args.copy() if base_args is not None else ...
a0bdeba03dca4c5e0f8162ca7c1010a7aaf8fa65
50,217
from re import X def cancel_env_set_get(resources, node, equiv): """Simplify combinations of env_get/setitem. * get(set(env, k1, v), k2, dflt) => * v when k1 == k2 * get(env, k2, dflt) when k1 != k2 """ key1 = equiv[C1] key2 = equiv[C2] if key1.value == key2.v...
8799830d9c085b72208ba52978f1779970470df2
50,218
from typing import Iterable def get_donchian(quotes: Iterable[Quote], lookback_periods: int = 20): """Get Donchian Channels calculated. Donchian Channels, also called Price Channels, are derived from highest High and lowest Low values over a lookback window. Parameters: `quotes` : Iterable[Quote...
ae9f8df115ac719ce475b35f33b098d84e1ab33e
50,219
def getLigandCodeFromSdf ( sdfFileName ): """ Funkcja sluzy do pobierania kodow ligandow z pliku .sdf Wejscie: sdfFileName - nazwa pliku sdf Wyjscie: ligandCodes - lista znalezionych kodow ligandow """ sdfFile= open(sdfFileName, 'r' ) line = sdfFile.readline() ligandC...
9b25f91b754448f6fab4ce11e0f816cbf5406dea
50,220
def pav(y): """ PAV uses the pair adjacent violators method to produce a monotonic smoothing of y translated from matlab by Sean Collins (2006) as part of the EMAP toolbox Author : Alexandre Gramfort license : BSD """ y = np.asarray(y) assert y.ndim == 1 n_samples = len(y) v...
64b4e4bff18c5d7bdf34556cad2fae75ac01d1b0
50,221
def get_segment_library_list(instrument, detector, filt, library_path, pupil='CLEAR'): """Given an instrument and filter name along with the path of the PSF library, find the appropriate 18 segment PSF library files. Parameters ----------- instrument : str Name ...
a16d49548a66ab598ae2e1ffe4784cd1cd027e80
50,222
def resize(mat, width, height): """ Resize the input image to width x height :param mat: input image :param width: new width :param height: new height :return: resized image """ return cv2.resize(mat, (width, height))
a521aa2c1839a67989708590840e3fd3afe72009
50,223
import os from re import DEBUG def read_write_star(file, mics_to_remove, line_range, star_column_num, output_fname) : """ Open a .star file and read it line-by-line. Evaluate each line with conditional functions. ============================================ PARAMETERS: ====================...
3ca2d18271b21c4d5e03f8d9abb2877cd9932384
50,224
def stockout_box_pack_api(order_id): """ 包裹信息, 有明细行 post req: { lines: [ {sku, qty_pack} ] } """ box = None if request.method == 'POST': order = Stockout.query.t_query.filter_by(id=order_id).with_for_update().first() lines ...
063c89afccfb74512232af6c6069201a411c9be8
50,225
def create_model(google_colab, n_features): """Creates Keras model""" LSTM_ = CuDNNLSTM if google_colab else LSTM inputs = Input(shape=(None, n_features)) x = Conv1D( filters=32, kernel_size=16, padding="same", kernel_initializer="he_uniform", )(inputs) x = Batc...
801a490beccb3f8032f192acb0dcb88b95e2ee6f
50,226
def get_hash_command(client: Client, args: dict) -> CommandResults: """ Get hash reputation. Removed hash classification since SentinelOne has deprecated it - Breaking BC. """ hash_ = args.get('hash') type_ = get_hash_type(hash_) if type_ == 'Unknown': raise DemistoException('Enter a...
d14b910353b2c6621fc9fab4e38c3e9c026f1efe
50,227
from typing import Optional import random def map_color(color: Optional[str]) -> Color: """Maps color onto Nozbe color""" colors = list(list(Color.allowed_values.values())[0].values()) colors.remove("null") return Color(color if color in colors else random.choice(colors))
ec7c6d4b83daa07223e7aca38dd6887098aedbc9
50,228
def transform_labels_into_names(labels, entity_idx_to_name): """ Trasform a list of number labels to the related names of characters :param labels: :param entity_idx_to_name: :return: list of names labels """ names_labels = [] for label in labels: if label < len(entity_idx_to_nam...
87ad913737eda52ee7cf808cf1a930e1a81b02c6
50,229
from typing import Dict from typing import Any def validate_alert_report_type_arguments(args: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: """ Validates the arguments required for alert details report type from input arguments of reports command. Will raise ValueError if inappropriate input ...
b57df54c93b09ed73607a0de8863fb7d836f93d4
50,230
def laplacian(csgraph, normed=False, return_diag=False, use_out_degree=False, *, copy=True): """ Return the Laplacian matrix of a directed graph. Parameters ---------- csgraph : array_like or sparse matrix, 2 dimensions compressed-sparse graph, with shape (N, N). normed : ...
895b742e7a7b9f0640085a9cd6b958901bb67354
50,231
def individual_amalgamate(subitem, past_subitem, create_subitem, ys1): """ amalgamate the individual items. Recurse when needed. """ try: if subitem['name'] != past_subitem['name']: pass else: create_subitem['children'].append(subitem['children'][0]) past_subi...
f066b11f5d2995b26b704ae4bc90db3631dd0ec5
50,232
import warnings def interpolated_acf(times, fluxes, cadences=None): """ Calculate the autocorrelation function after interpolating over missing times and fluxes. Parameters ---------- times : numpy.ndarray Incomplete but otherwise uniformly sampled times fluxes : numpy.ndarray ...
c2fdcdf7705e5eb4dc36b32c94511a5333041485
50,233
def _transformer( emb_dim=512, num_heads=8, num_layers=6, qkv_dim=512, mlp_dim=2048, dropout_rate=None, attention_dropout_rate=None, nonlinearity='gelu', ): """Transformer config.""" configs = { 'models.build_transformer_config.emb_dim': emb_dim, 'models.build_transformer...
547f585d68a798324ef47e0c5093ff89956e9e9a
50,234
def get_vpc_list(): """获取所有的vpc信息""" s = get_aws_session(**settings.get("aws_key")) clients = s.client("ec2") resp_dict = clients.describe_vpcs() vpc_list = resp_dict.get("Vpcs") return vpc_list
5e866331704d6ae81c3b37e616d9ba5e08a4b6bf
50,235
import os def get_package_path(repodir, packagename): """ Return the path to an individual package file. """ return os.path.join(repodir, PACKAGESDIR, packagename)
011fcc9232bf51cc736ff49db071475c1d4a74a8
50,236
import random def make_bank_act_tp_data(ctif_tp): """ 生成银行账号种类 :param ctif_tp: 主体类型 :return: 账号类型 """ if ctif_tp == "1": act_tp = random.choice(["02", "03"]) elif ctif_tp == "2": act_tp = random.choice(["01", "03"]) else: raise TypeError("ctif_tp={}类型错误!".format...
90e394b44dd6802b5c9a7773edb3b9baa32b0eef
50,237
def v70_from_params_asdict(v70_from_params): """Converts a sparse `v70_from_params` array to a dict.""" dict_v70_from_params = {} for i in range(v70_from_params.shape[0]): for j in range(v70_from_params.shape[1]): v = v70_from_params[i, j] if v: dict_v70_from_params[(i, j)] = str(v) retu...
355ba80c131d08b6aedf20680545b4b31e07832e
50,238
def open_r(filename): """Open a file for reading with encoding utf-8 in text mode.""" return open(filename, 'r', encoding='utf-8')
08086625a9c05738a3536001a158eff3b0718ddf
50,239
def get_current_kernel_release(): """ Get the release of the current kernel as a string. """ return api.current_actor().configuration.kernel.split('-')[1]
98353b45b458a45414823c1927597eaa4fbb43eb
50,240
import random def genetic_algorithm_optimizer(starting_path, cost_func, new_path_func, pop_size, generations): """Selects best path from set of coordinates by randomly joining two sets of coordinates Arguments: starting_path -- List of coordinates, e.g. [(0,0), (1,1)] cost_func -- Optimization me...
c9dcc1517f41e9a22e070a3cd670a4c249611b72
50,241
def get_a_mock_request_packet_and_raw(): """Returns a tuple of mock (IncomingPacket, REQID, RegisterResponse message)""" reqid = REQID.generate() message = mock_protobuf.get_mock_register_response() pkt = convert_to_incoming_packet(reqid, message) return pkt, reqid, message
b0096a6567ce3f5f7b7bd7f472dfc14800ad2414
50,242
import os def _settingFileList(): """ Get list of setting files from settings folder. """ ret = [] files = [f for f in os.listdir(os.path.dirname(__file__)) if os.path.isfile(os.path.join(os.path.dirname(__file__), f))] for f in files: if f.endswith(Global.settingFileExten...
e7862584edab8896d261ef514966294933379ff1
50,243
import torch import pickle def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: ...
b68f27b5b9f5edf94e2f959ae35a4b3955052d2f
50,244
def random_transform(random_state=np.random.RandomState(0)): """Generate random transform. Each component of the translation will be sampled from :math:`\mathcal{N}(\mu=0, \sigma=1)`. Parameters ---------- random_state : np.random.RandomState, optional (default: random seed 0) Random n...
844a76f790e10befdd29ebc013d9166b3b3b9d4c
50,245
import warnings def normalize_frequency_locations(samples, Kmax=None): """ This function normalize the samples locations between [-0.5; 0.5[ for the non-cartesian case Parameters: ----------- samples: np.ndarray Unnormalized samples Kmax: float Maximum Frequency of the sam...
4520ef6bb9a9e13be30dc9a2141e4f7987d71c41
50,246
def max_value(uncert_val): """Maximum confidence interval for a ufloat quantity.""" return uncert_val.nominal_value + uncert_val.std_dev
e9a3b8541e8456d370945e9fcc4d80d0a49b6d0b
50,247
from config import SWAP12 from config import CUT_INTERP from config import EXTRA_MDET_CONFIG from config import DO_METACAL_MOF from config import DO_METACAL_TRUEDETECT from config import DO_METACAL_SEP from config import METACAL_GAUSS_FIT from config import SHEAR_MEAS_CONFIG from config import DO_END2END_SIM def get_...
885fc49f8849d39316aba6d784dcb49cc903f652
50,248
import json def load_labels_schema(): """Loads the label json schema file :return: json schema """ json_schema = {} with open(label_schema_json, "r") as schema_file: json_schema = json.load(schema_file) return json_schema
3120e71d0dd04972c822b78ff91bb1076864b34e
50,249
import argparse def run(argv=None): """The main function which creates the pipeline and runs it.""" parser = argparse.ArgumentParser() # Here we add some specific command line arguments we expect. Specifically # we have the input file to load and the output table to write to. parser.add_argument...
0c40b7310979d929ecb316f787149e4510894349
50,250
def _parabolic_interpolation(y_frames): """Piecewise parabolic interpolation for yin and pyin. Parameters ---------- y_frames : np.ndarray [shape=(frame_length, n_frames)] framed audio time series. Returns ------- parabolic_shifts : np.ndarray [shape=(frame_length, n_frames)] ...
0d629c9027d59a6e4360a55bad0ac550cf13a20e
50,251
import logging def create_api(): """ Create API with auth info provided in keys.txt Return and log relevant errors. """ auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API( auth, wait_on_rate_limit=True, wait_o...
ad2778841d5976abcc3ca3f7c40887592c6a53a5
50,252
def exp(h, Omega): """ :param h: steglengde :param Omega: matrise med vinkelhastigheter :return: exp(h*Omega) etter definisjonen i likning (21) i oppgaven """ I = np.identity(3, dtype=np.double) omega = np.sqrt(Omega[2, 1] ** 2 + Omega[0, 2] ** 2 + Omega[1, 0] ** 1) return ( I ...
c274fc6aa97566b7816b159438464aa6f07ca4c5
50,253
import torch def compute_mae(vec1, vec2): """ vec1, vec2 is torch.Tensor """ vec1 = vec1.reshape(-1, vec1.shape[-1]) vec2 = vec2.reshape(-1, vec2.shape[-1]) if vec2.shape[-1] == 2 and vec1.shape[-1] == 3: vec1 = vec1[..., :2] / torch.norm(vec1[..., :2], dim=-1, keepdim=True) if v...
14b023666d726004b05f57efa874d2cbe6b81db7
50,254
from rest_framework_simplejwt.settings import api_settings as jwt_settings from rest_framework_simplejwt.views import TokenRefreshView def get_refresh_view(): """ Returns a Token Refresh CBV without a circular import """ class RefreshViewWithCookieSupport(TokenRefreshView): serializer_class = CookieT...
82c702d96b5dd670c0723db812b4bdfc075eb6a7
50,255
def prepend_protocol(url: str) -> str: """Prefix a URL with a protocol schema if not present Args: url (str) Returns: str """ if '://' not in url: url = 'https://' + url return url
856961526207510c630fe503dce77bdcfc58d0cc
50,256
def jackknife_errors(data_input, weights_input, bins, num_sub_samps): """Returns the jackknife resampling errors for the estimation of histogram bar height, for the provided weighted data and bin edges. Parameters ---------- data : numpy.ndarray Input first-passage time data. weights: n...
bdb5d5da0e6c303ead396eaca03db7a00f72ab0b
50,257
import os def test_nov0512_as_planned(): """NOV0512 the way it really is. This is how old loads with no characteristics will process when run through the checker.""" ok, lines, sc = run_nov0512(with_characteristics=False) # hopper.pcad now uses the default ODB_SI_ALIGN if not supplied, # so we ge...
c88a435ee116d00b15a4328ab46ff96e6353dc29
50,258
def NL3P_sinc(A, to, BW, E1, k2, cDiss, nu, R, dt, startprint, simultime, fo1, k_m1, zb, printstep = 1, Q1=156.7, Q2=300, Q3=450): """This function performs sinc excitation simulation of the cantilever at the tip""" """This is designed for the NL3P model described in: “Theory of single-impact atomic force spect...
b1c46a1cb2f96ce68f4beb92c2325e0e1d3e853f
50,259
def get_dataset(dataset_id, client_email, private_key_path): """Shortcut method to establish a connection to a particular dataset in the Cloud Datastore. You'll generally use this as the first call to working with the API: >>> from gcloud import datastore >>> dataset = datastore.get_dataset('dataset-id', emai...
eb23b6565afb8e882e705ecd809d6b929e9710bb
50,260
def authenticate(inner_function): """:param inner_function: any python function that accepts a user object Wrap any python function and check the current session to see if the user has logged in. If login, it will call the inner_function with the logged in user object. To wrap a function, we can p...
f45b7608052eb082131f3ac31721c5c08519473f
50,261
def Ptoa(P, m1, m2): # input not in SI """ Calculates orbital radius from period :param P: period [yr] :param m1: mass of primary [Msol] :param m2: mass of secondary [Mjup] :return: semi-major axis [AU] """ # a^3/P^2 = (G / 4 pi pi) (m1 + m2) c = G / (4. * np.pi * np.pi) mu = (m...
46ced6e6521cbc242c0fa4ad349779eabd67b418
50,262
import time import os import platform def buildinfo(lenv, build_type): """ Generate a buildinfo object """ build_date = time.strftime ("%Y-%m-%d") build_time = time.strftime ("%H:%M:%S") build_rev = os.popen('svnversion').read()[:-1] # remove \n if build_rev == '': build_rev = '-U...
ec7066e318b2ffe3054fab0975868ae6cbc43ae2
50,263
def nlopt_bobyqa( criterion_and_derivative, x, lower_bounds, upper_bounds, *, convergence_relative_params_tolerance=CONVERGENCE_RELATIVE_PARAMS_TOLERANCE, convergence_absolute_params_tolerance=CONVERGENCE_ABSOLUTE_PARAMS_TOLERANCE, convergence_relative_criterion_tolerance=CONVERGENCE_REL...
e85a29f68067cf9120ed4b9789769d4a64379356
50,264
def templated_name_logger(template): """Returns a classmethod that calculates logger names by first applying the class name to `template`. For instance: class Foo(core.Configuration): NAME = 'foo' get_logger_name = helpers.templated_name_logger('my.%s') class Bar(Foo):...
9ac506c1b676d3d9283af6b1c5eda7a0ce22580e
50,265
from datetime import datetime def search_vehicle(alarm_day_count, plate_num): """ 获取需要报警的车辆信息 :parameter: alarm_day_count 提前报警天数 :parameter: plate_num 车牌号 :return: List[ (客户名称,客户性别,身份证号,电话, 车牌号,车辆型号,车辆登记日期,公里数,过户次数 贷款产品,贷款期次,贷款年限,贷款金额,贷款提报日期,贷款通过日期,放款日期, 承保公司,险种,保险...
37ce0e80cddf8770165b8721e0ba2e000a35828f
50,266
def readBinaryWatch(self, num): # ! 44ms,进行双重循环,并统计1的数量,没什么太多的技巧性 """ :type num: int :rtype: List[str] """ return ['%d:%02d' % (h, m) for h in range(12) for m in range(60) if (bin(h) + bin(m)).count('1') == num]
1e14be488a54f4746b39771c81e4dd50bce1a9b3
50,267
def tdb_minus_tt(jd_tdb, fraction_tdb=0.0): """Computes how far TDB is in advance of TT, given TDB. Given that the two time scales never diverge by more than 2ms, TT can also be given as the argument to perform the conversion in the other direction. """ t = (jd_tdb - T0 + fraction_tdb) / 36525...
066c8a112bb11377b80afdf6b34572d6426303d2
50,268
def login_not_required(f): """ Decorate routes to not require login. """ @wraps(f) def decorated_function(*args, **kwargs): if session.get("user_id"): return redirect("/home") return f(*args, **kwargs) return decorated_function
93ae33003eaf719b0ab5dfdde5b038b8e5aea0b4
50,269
def build_function(type_, params, variable): """ Create object function matching type and parameters given. Parameters ---------- type_ : str 'name' attribute of one of the classes of this module. params : dict Dict mapping parameter names with their values. variable : str ...
88d93db2a15b13608d295ef17c7528a5c2bb406b
50,270
def test_empty_block(): """Test an empty program """ @mb.program(input_specs=[mb.TensorSpec(shape=(2, 4))]) def prog(x0): return x0 block = prog.functions["main"] if len(block.operations) != 0: raise AssertionError if len(block.inputs) != 1: raise AssertionError ...
83b61f860d61e62f1410e6b0faa8f7db521843ed
50,271
def download_blow(load=True): # pragma: no cover """Download blow dataset. Parameters ---------- load : bool, optional Load the dataset after downloading it when ``True``. Set this to ``False`` and only the filename will be returned. Returns ------- pyvista.UnstructuredGr...
64ae542ee110a1efaa55752d86c99153bd87a0dc
50,272
def batch_retrieve_for_processing(ftp_as_object): """ Used for mapping an s3_retrieve function. """ # Convert the ftp object to a dict so we can use __getattr__ ftp = ftp_as_object.as_dict() data_type = file_path_to_data_type(ftp['s3_file_path']) # Create a dictionary to populate and retur...
50b06d7bd88296c8e22bfcab4c14ad58c7f917e1
50,273
def register_map(**kwargs): """Register an ObjectMapper to use for a Container class type If mapper_cls is not specified, returns a decorator for registering an ObjectMapper class as the mapper for container_cls. If mapper_cls specified, register the class as the mapper for container_cls """ contain...
5cd90411e84059bd76643790cd48a6374e3bcbd7
50,274
def textilize(s): """Remove markup from html""" s = s.replace("<p>", " ").replace("&nbsp;", " ") return _re_html.sub("", s)
51eff59c5194d5fcd90c9956d8ff923cb4875cd5
50,275
import posixpath def safe_join(base, *paths): """ A version of django.utils._os.safe_join for S3 paths. Joins one or more path components to the base path component intelligently. Returns a normalized version of the final path. The final path must be located inside of the base path component ...
ecb8c2b155ef2872ca443e4fae093ba3e7055e35
50,276
import configparser def miniterm(owf_instance=None, *args): """ Run a serial console session (using miniterm from serial package). :param args: Varargs command options. :param owf_instance: Octowire framework instance (self). :return: Nothing. """ if len(args) < 1: config = None ...
52079d07b5af8c8bf73021bf71c1f3acd49937bb
50,277
import os import pickle def create_dataset(data_dir, train_mode=True, epochs=1, batch_size=4096, is_tf_dataset=True, line_per_sample=4096, rank_size=None, rank_id=None): """ cre...
332296ef66fab2f755210a12d70b8e22c22591bc
50,278
import requests def _request_user_ids(): """Get dataframe of user emails, gids, names.""" params = { 'workspace': WORKSPACE_ID, 'opt_fields': 'email,name' } endpoint = 'teams/{}/users/'.format(TEAM_ID) url = 'https://app.asana.com/api/1.0/{}'.format(endpoint) r = requests.g...
1f5c0cd29785ca25b8beb8654901ad11fc503712
50,279
def _squash_context(*args): """ Unwraps ``RequiresContext`` values, merges them into tuple, and wraps back. .. code:: python >>> from returns.context import RequiresContext >>> from returns.converters import squash_context >>> assert squash_context( ... RequiresContext....
cc25dcd2df3de351ce58c95514e9a5c3ddffadd1
50,280
import six def decode_message(buf, message_type=None, config=None): """Decode a message to a Python dictionary. Returns tuple of (values, types) """ if config is None: config = blackboxprotobuf.lib.config.default if isinstance(buf, bytearray): buf = bytes(buf) buf = six.ensur...
459ffafda7848f2342feb7865a4759f8f4a429cb
50,281
def ca_all(request): """Lists all files readable by the current user""" method = request.method if method == 'POST': keys = ['c', 'st', 'l', 'o', 'ou', 'cn', 'email'] values = {} for key in keys: if request.data.get(key): values[key] = request.data.get(ke...
625c2ddbd97e17efa94ac43d5cfe793bcbad892a
50,282
def supervised_disagreement(labels, logits_1, logits_2): """ Supervised disagreement """ labels = tf.cast(labels, tf.int32) preds_1 = tf.argmax(logits_1, axis=-1, output_type=tf.int32) preds_2 = tf.argmax(logits_2, axis=-1, output_type=tf.int32) par1 = tf.reduce_mean(tf.cast(tf.math.logical_and(preds_1 == lab...
e632a0bde59a3e669c8abb4d733f57e2fec4de49
50,283
import unittest import inspect def sort_tests(tests) -> unittest.TestSuite: """Sort supplied test suites such that MemoryTestCases are at the end. `lsst.utils.tests.MemoryTestCase` tests should always run after any other tests in the module. Parameters ---------- tests : sequence Seq...
8dee0b3be96874b2f2020bb489aeb9716ca6f151
50,284
def chunk_by_image(boxes): """ turn a flat list of boxes into a hierarchy of: image category [boxes] :param boxes: list of box detections :return: dictionary of boxes chunked by image/category """ chunks = {} for b in boxes: if b['image_id'] not in chunks: ...
d6eaf46214a97853407112a9d0a3c47a132fb3c4
50,285
from typing import List from typing import Dict def get_all_secret_registry_events( chain: BlockChainService, secret_registry_address: Address, events: List[str] = ALL_EVENTS, from_block: BlockSpecification = 0, to_block: BlockSpecification = 'latest', ) -> List[Dict]: """ ...
d865c852237db1566e937200b08c0602228a74ff
50,286
def test_label_fiber_array_align_ports(): """Test that adds the correct label for measurements.""" c = pp.c.waveguide() assert len(c.labels) == 0 c = pp.routing.add_fiber_single(c, with_align_ports=True) pp.show(c) print(len(c.labels)) assert len(c.labels) == 4 l0 = c.labels[0].text ...
30dfb9ed239ce549d621c01be9456c7fc801ed4b
50,287
def run_simulation(simulation, n_steps, run_ideal=False, simdir="r"): """ Run a neural network model simulation computing occupancy histograms :param simulation: The simulation to run :param n_steps: The number of steps to simulation :param run_ideal: If True, instead of using neural network movemen...
0c291ec950a1c23752547dc541244f037cf0b946
50,288
def find_duplicate_uuids(images): """ Create error records for UUID duplicates. There is no real way to figure out which is the correct image to keep, so we keep the first one and mark all of the others as an error. We also remove the images with duplicate UUIDs from the image dataframe. """ ...
ac8b396692df921de56c0a18aa2d9f1953f4c5ca
50,289
import json def accounts_root(): """ --- get: summary: Get all accounts this user has access to tags: - Accounts description: Returns the list of accounts that this user (person or bot) has permission to access. The list is returned in a single...
7e45f0a2a8ac849293508ab5604e9ce3aff045d6
50,290
from datetime import datetime async def arrival(request: Request): # data { name, phone, remark } """ D -> H 到达现场并开始处理 """ _oid = get_maintenance_id(request) data = await request.json() _time_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S') try: _edit = data['name'] _phone = da...
3d01a3a60a02ab78c2fddde34a4387f7878e2ef3
50,291
from typing import Union from typing import Optional def to_graph(inp: Union[Graph, str], fmt: Optional[str] = "turtle") -> Graph: """ Convert inp into a graph :param inp: Graph, file name, url or text :param fmt: expected format of inp :return: Graph representing inp """ if isinstance(inp...
cd17e018a65859153de463d0187ee6e9373faa8c
50,292
def file_exists(session, ds_browser, ds_path, file_name): """Check if the file exists on the datastore.""" client_factory = session._get_vim().client.factory search_spec = search_datastore_spec(client_factory, file_name) search_task = session._call_method(session._get_vim(), ...
79090ad5095d5e2e9e37bc5d8297148d9a7ceb0c
50,293
def data_source_get_all(context, regex_search=False, **kwargs): """Get all Data Sources filtered by **kwargs. :param context: The context, and associated authentication, to use with this operation :param regex_search: If True, enable regex matching for filter v...
f03e328ff8d79931b45a891a3fd729521ff035d0
50,294
from typing import Union import torch def normalize_img(img: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]: """ Normalizes an input image. Parameters ---------- img: Image which should be normalized. Returns ------- img: Normalized image. """ if type(im...
b110e882235bad48e7eb2e9404307ff3159bd6e5
50,295
def get_horizon_endpoint(goc_db_url, path, service_type, host): """ Retrieve the Horizon OpenStack dashboard of the given hostname """ dashboard_endpoint = "" endpoints = get_GOCDB_endpoints(goc_db_url, path, service_type) for item in endpoints.findall("SERVICE_ENDPOINT"): sitename = item.find...
9c83aaa2cf752f33f43a3577ed393262b5e44cbe
50,296
def create_process_chain_entry(input_object: DataObject, formula, operators, output_object: DataObject): """Create a Actinia process description. :param input_object: The input time series object :param output_object: The output time series or raster object :return: A Act...
245677913af3cefebfc0c13505e1f798bd46472a
50,297
def checksync(st, resample=False): """Check if all traces in st are synced, if so, return basic info """ samprates = [trace.stats.sampling_rate for trace in st] if np.mean(samprates) != samprates[0]: if resample: print('sample rates are not all equal, resampling to lowest sample rat...
500b9df5869473a52b0837133cb3e49821fd3343
50,298
from scipy.optimize import minimize def hill_estimator(points, counts, xmin, xmax=np.inf, discrete=False, **kwargs): """ Give the MLE for continuous power-law distribution exponent. :param points: observed values, shape (n,) :param counts: number of occurrences for `points`, shape (n,) :param xmin...
7fec0ee8077188958d4f5d349590de6c951937a1
50,299