content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def unique(table, key=None, presorted=False, buffersize=None, tempdir=None, cache=True): """ Select rows with unique values under a given key (or unique rows if no key is given). E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar', 'baz'], ... ['A', 1, 2],...
f08dc4ff28e3759dd5c684a314261e9dd4e96a16
46,300
def apply_over_axes(func, a, axes): """ Applies a function repeatedly over multiple axes. `func` is called as `res = func(a, axis)`, where `axis` is the first element of `axes`. The result `res` of the function call must have either the same dimensions as `a` or one less dimension. If `res` has one...
15bc9036f6d041310f556f5bacae600d09402e12
46,301
def history(dynamodb_client, table_name, metric, i, interval=50): """ Returns an event's history (items in a DynamoDB table) as a DataFrame :param dynamodb_client: Connection to DynamoDB service :param table_name: Name of DynamoDB table (string) :param metric: Name of metric subtopic (string) :p...
063284fd5f88dd7c4c6b327f690c7a336c892dcc
46,302
import re import os def with_migrations(*migrations): """ Decorator taking a list of migrations. Creates a temporary directory writes each migration to a file (named '0.py', '1.py', '2.py' etc), calls the decorated function with the directory name as the first argument, and cleans up the temporary...
e2bebe2834aff5a02e441c9c379f65f382422339
46,303
from typing import Counter def cleanObject(data): """ input raw pandas dataframe output : cleaned form object """ # ============================================================================= # load data # ============================================================================= ...
7f3e378689ff78f47039e5a9cdbaecab177801bc
46,304
import os from typing import Dict from typing import Tuple def create_lm_ds_kilt_eli5( *, tokenizer, context_window_size, # pylint: disable=unused-argument dataset_name, # pylint: disable=unused-argument batch_size, split, db_path, # pylint: disable=unused-argument random_seed, ...
3545a828f46859ef6173c3809a191f8bb7e022eb
46,305
def memoize(**kwargs): """ Memoize Function. Arguments: until: func, memoize until time specified (seconds, using time.time) disable_kw bool, do not memoize around kwargs. This is a significant performance benefit. ignore_nulls: bool, do not store null values in the cache....
15b52d5fe1f934b3c7a8acbe1036df4b37234105
46,306
import math def logberkopec_hypergeometric_tail_inverse(k, m, log_delta, M, start='below'): """ Computes the pseudo-inverse of the hypergeometric distribution tail for a logarithmic delta term and with a logarithmic algorithm to avoid under- and overflows and less memory usage. Args: k (int): Num...
62cfebe0113a8ab8976d0db7a8269c653996a590
46,307
def MFInt(indices): """ indices a (N,) array of integers """ return " ".join([('%i' % i) for i in indices])
8e5e928c5d38a3ef55e0bf8d177f1db8d5435d11
46,308
def isolated_recovery_rate_10(): """ Real Name: b'isolated recovery rate 10' Original Eqn: b'Isolated 10*(1-fraction of critical cases 10)/isolation duration 10' Units: b'person/Day' Limits: (None, None) Type: component b'' """ return isolated_10() * (1 - fraction_of_critical_cases_...
934dadf89a4f9a7e87cb6a0b44ef2e01e1a0dcf9
46,309
def invert_jacdict(jacdict, unknowns, targets, tau, test_invertible=False): """Given a nested dict of ATI Jacobians that maps unknowns -> targets, e.g. an asymptotic H_U matrix, get the inverse H_U^(-1) as a nested dict. This is implemented by inverting the FFT-based multiplication that was implemented abo...
150a49076ed55ec41d0a2654b7f1cb962aec1e7b
46,310
def stream_view() -> Response: """/""" # Generator rows = generate() # returns Response to stream the data return Response(stream_with_context(stream_template('layouts/row.html', rows=rows)))
11c7ff00a0ccf630b86044d204cba97351572bec
46,311
async def validate_usb_connection(self, device_path=None) -> dict[str, str]: """Test if device_path is a real Plugwise USB-Stick.""" errors = {} # Avoid creating a 2nd connection to an already configured stick if device_path in plugwise_stick_entries(self): errors[CONF_BASE] = "already_configur...
87e3a47718c2eed92d7269e1a8f9c84dd6680f16
46,312
def _validate_and_fill_dertype(dertype=None): """Issue `do_gradient=True` unless `dertype` is energy or nonsense.""" if dertype is None: do_gradient = True elif der0th.match(str(dertype)): do_gradient = False elif der1st.match(str(dertype)): do_gradient = True else: ...
2c546301bf0cef382ce47d3294d81a668f19bb3c
46,313
from typing import Any def accepted(message: Any = None) -> Response: """ Returns an HTTP 202 Accepted response, with optional message; sent as plain text or JSON. """ return status_code(202, message)
6a66a78c5602f668efcfbc9557b42de18bb855b2
46,314
def readheader(struct,hdu): """read image from HDU structure""" headerdata=[] try: headerdata = struct[hdu].header except: raise SaltIOError('Cannot read header data from HDU '+str(hdu)) return headerdata
412b721aa96f9a4a5daecbcca7c2d2c7f79b58b3
46,315
import random def subsample_files_in_tree(root, filename_pattern, size): """ Sub-sample list of filenames under root folder. This ensures to keep sample balance among folders. Arguments: root: Root folder to search files from. filename_pattern: Wildcard pattern like: '*.png'. ...
6bffdf683071d712f0b1ccb382a145a74f642d24
46,316
def can_handle(ctx, permission: str): """ Checks if bot has permissions or is in DMs right now """ return isinstance(ctx.channel, discord.DMChannel) or getattr( ctx.channel.permissions_for(ctx.guild.me), permission )
b51419c28e43e8a3bddcc35e79080dac5f13fe62
46,317
from typing import List from typing import Tuple from typing import OrderedDict from typing import NoReturn from typing import Optional from typing import Iterator import sys import inspect from typing import Any def sumtype( typename: str, variant_specs: List[ Tuple[str, List[Tuple[str, type]] ] ], *, type...
56fa1b20eb4d9996c9a2707bd7b03b6dab4bb538
46,318
def get_text(item_id): """ Returns the text of an item :param item_id: Id of the item :return: str: Text """ if item_id in all_items: return all_items[item_id]['text'] return None
ae8b79426bcc00a1ba23b67daccd9866756d2ebf
46,319
def _matches_generator_helper(type_obj, allowed_types): """Check if type_obj matches a Generator/AsyncGenerator type.""" if isinstance(type_obj, _typing.Union): return all(_matches_generator_helper(sub_type, allowed_types) for sub_type in type_obj.options) else: base_cls = type_obj if i...
86e857847ecfde7605f1466c4eaf38a2280724cd
46,320
def handle_failure(request): """ Handles failure message from paytrail """ # Get parameters order_number = request.GET.get('ORDER_NUMBER', '') timestamp = request.GET.get('TIMESTAMP', '') authcode = request.GET.get('RETURN_AUTHCODE', '') secret = settings.VMAKSUT_SECRET # Validate, and mar...
e3602d361ffcc3bfded3b201ab9f784519f88a40
46,321
def _get_transformer_list(estimators): """ Construct (name, trans, column) tuples from list """ transformers, columns = zip(*estimators) names, _ = zip(*_name_estimators(transformers)) transformer_list = list(zip(names, transformers, columns)) return transformer_list
1a768e3415dff34e6d015d7fcf028cc9cdaf283c
46,322
def pane_list(pane, ids=None, list_all=False): """Get a list of panes. This makes it easier to target panes from the command line. """ if ids is None: ids = [] if list_all or pane.identifier != -1: ids.append(pane) for p in pane.panes: pane_list(p, ids, list_all=list_all...
845ecb7e74ed1bfb67f6cdb25bfed512ea2c995d
46,323
import os def _load_image_set_index(_year, _image_set): """ Load the indexes listed in this dataset's image set file. """ # Example path to image set file: # self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt _devkit_path = os.path.join(cfg.DATA_DIR, 'VOC...
5b840f091d5d2c924aefbf007c9dfe4cce19ec69
46,324
def check_indent(codestr): """If the code is indented, add a top level piece of code to 'remove' the indentation""" i = 0 while codestr[i] in ["\n", "\t", " "]: i = i + 1 if i == 0: return codestr if codestr[i-1] == "\t" or codestr[i-1] == " ": if codestr[0] == "\n": ...
a5537c68056386f834f09fc50b26219d48129d4f
46,325
def agentGet(_id): """ Responds to GET requests sent to the /v1/agents/<_id> API endpoint. """ if request.args.get('attrs') is None: attrs = None else: attrs = request.args.get('attrs') return ContextBroker.Agents.getAgent(_id, attrs)
c2da087e263934af1d42817f14ec99e7419ed32f
46,326
def run_SAM(df_data, skeleton=None, device=None, **kwargs): """Execute the SAM model. :param df_data: Input data; either np.array or pd.DataFrame """ device = SETTINGS.get_default(device=device) train_epochs = kwargs.get('train_epochs', 1000) test_epochs = kwargs.get('test_epochs', 1000) ba...
2dbbc03ca3fb16f3a9ec23300ed8bb8393720a7c
46,327
def normalize_path(path): """ Strip non-alphanumeric characters from path and downcase it. """ stripped = NORMALIZER.sub('', path) downed = stripped.lower() return downed
db44ab8083408460c8b522f07be371b1f660d70b
46,328
def target_encode_loo(X, y=None, cols=None, dtype='float64', bayesian_c=None): """Leave-one-out target encode columns in a DataFrame. Replaces category values in categorical column(s) with the mean target (dependent variable) value for each category, using a leave-one-out strategy such that no sample's...
17b62ed5f4519dab3fe35d18b3e907378e6935b1
46,329
from typing import Dict import pathlib def save_files(folder: Filepath, file_data: Dict[Filepath, str]) -> bool: """Save all `file_data` under `folder`. All paths in `file_data` are relative to `folder`. Inputs: folder: Filepath file_data: Dict[Filepath, str] The file name (r...
7f4c59de147db94f6bec913b799dbc3437154191
46,330
def build_forecast( data, forecast_range, truncate_range=0 ): """build a forecast for publishing Args: data (:obj:`pandas.data_frame`): data to build prediction forecast_range (int): how much time into the future to forecast truncate_range (int, optional): trunca...
06e6eedb850a25c1067b9f15a6f7b23946aa52a3
46,331
def get_psycopg2_connection_kwargs(_id: str) -> dict: """Get connection kwargs for psycopg2""" return get_connection_kwargs(_id, credentials_mapping=PSYCOPG2_CONNECTION_KWARG_MAP)
2922ed5178120c1c2ea13523d5ddf9c611c091b5
46,332
def motivation_adjustment(): """ Real Name: Motivation Adjustment Original Eqn: (Income - Motivation) / Motivation Adjustment Time Units: 1/Month Limits: (None, None) Type: component """ return (income() - motivation()) / motivation_adjustment_time()
0e62ff58c9906654f0aed5d1e6e3585b519f3023
46,333
def distance(data,a,b,variables_numeriques): """ Cette fonction permet de calculer la distance entre deux éléments. Les paramètres sont : - Les données du graph - Noeud du départ graphe - Noeud de la destination graphe - Les coordonnées latitude et longitude """ for v...
4b907d5341e8d71ca80ef6c71d1f57c7382eae5a
46,334
def login(session, url, username, password): """ Login to given url with given username and password. Use given request session (requests.session) """ log.debug("Trying to login to {0} with user: {1} and pass {2}".format(url,username,password)) response = session.post(url, ...
1f1309d12d5165ab4e34f60c9fcface15ed1583c
46,335
import random def pick_card(deck_to_pick_from): """Returns a random card from the deck""" return random.choice(deck_to_pick_from)
2267058ed9833d7b67dbc3142c98a88a4e3cefb3
46,336
import torch def bbox_iou(box1, box2, xyxy=True): """Compute Intersection over Union (IoU) of two given bounding boxes.""" # get x1, x2, y1, y2 coordinates for each box box2 = box2.t() if not xyxy: b1_x1, b1_y1, b1_x2, b1_y2 = xywh2xyxy(box1) b2_x1, b2_y1, b2_x2, b2_y2 = xywh2xyxy(box2...
6d16ac0e77acb340e5174fc6e34ea6ff8e924073
46,337
def confirm( changeset_id, api_key=None, client_secret=None, auth_token_manager=None, timeout=None, ): """Confirm asset change notifications. """ auth_token_manager = flex_auth( api_key=api_key, client_secret=client_secret, auth_token_manager=auth_token_manager, ...
0982258c18c97395c4d60f9a999f920f5e77c97d
46,338
def get_hash(string): """ Returns a hash from a string Parameters: string (str): the string used to generate the hash Returns: hash(string): the hash of the string """ byte_string = string.encode() digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.up...
bd8f3fce3fea11967c2ebb3eb00e600bb554afe3
46,339
from typing import Mapping from typing import Sequence def default_options() -> (OptionSet, Mapping[str, Labels], Sequence[int], Sequence[int]): """ Default options for plotting data Returns ------- opts = dict of dicts...
e55097cf9b4126bde6587a52dcb770fe7b38ef34
46,340
def tfds_path(*relative_path: PathLike) -> ReadOnlyPath: """Path to `tensorflow_datasets/` root dir. The following examples are equivalent: ```py path = tfds.core.tfds_path() / 'path/to/data.txt' path = tfds.core.tfds_path('path/to/data.txt') path = tfds.core.tfds_path('path', 'to', 'data.txt') ``` N...
faea395cc2c6e205c6aeffb9435c9fe43069d8bb
46,341
import importlib def get_dictum_info(channel): """ 获取每日一句。 :return:str """ if not channel: return None source = DICTUM_NAME_DICT.get(channel, '') if source: addon = importlib.import_module('everyday_wechat.control.onewords.' + source, __package__) dictum = addon.get...
d4d68b88650f8b5c089e88393bb1cae07b23a518
46,342
def graph_users(request): """Grafico plot del modelo de usuarios.""" user = User.objects.all().values() df = pd.DataFrame(user, columns=['date_joined']) data = df['date_joined'].dt.month_name().value_counts() data = data.sort_values(ascending=True) data.plot.bar(xlabel="Mes", ylabel="Usuarios", ...
f097b4585c445ac335e5995d0f33462cff5ae285
46,343
def create_user(**params: str) -> User: """Creates a User with a given params""" return get_user_model().objects.create_user(**params)
24e851516aa6ea120384ff35255617984fe6ef67
46,344
import random def crossover(population, parents, gp_par): """ Generates offspring by crossovers """ if len(parents) % 2 != 0: raise ValueError("Number of parents for crossover must be even number") crossover_offspring = [] max_attempts = 100 for _ in range(gp_par.n_offspring_cro...
4df11ecce48804f57e2db2955f7910b8e92cb6a9
46,345
def spacy_evaluator(ner_model, examples): """ Evaluate the created NER model using different metrics Args: ner_model (spacy model object): The dataset examples (list): testing examples Returns: score_object (score object): object with different scoring metrics """ try:...
b75ebfc758c6015ae0e717916db3409785659a53
46,346
def _process_list_for_saving(l: [list, tuple]) -> [list, tuple]: """ The yaml.dump function can't save PyTorch tensors, numpy arrays, or callables, so we cast them to types it can save. :param l: list or tuple containing parameters to save :return: list or tuple with values processable by yaml.dump ...
9d4f1f260ce995ba1cedb8133cfc9c6b0c3a9fa0
46,347
def road_curvature_F5(curvature, ego_vehicle_speed): """ The method estimate the magnitude of the road curvature using the curvature of a number of regions of the road ahead the vehicle. The closest to vehicle regions are more important so we use higher values of weights in an equation with weights for ...
fbade1e7d63931aa05d67979e6ca76864e6f6c09
46,348
def select_tables(): """Select all table names from sqlite_master.""" return (sa.select(sqlite_master.c.name) .select_from(sqlite_master) .filter_by(type='table') .where(~sqlite_master.c.name.like('sqlite_%')) .order_by('name'))
722a3404a8481e14d10738377c99a041b353a278
46,349
def get_sparse_index(x, sparse_index_dict, feat): """sparse特征id编码""" if feat in sparse_index_dict: values = sparse_index_dict[feat] if x in values: return values.index(x) else: return len(values) #unk问题 else: raise LookupError("{} is not in sparse_ind...
8bf3380f87f658f5d7e349bde8d85059adbe5d8f
46,350
def nonzero_rmse(y_true, y_pred): """RMSE that ignores zero values, assuming that there is at least one nonzero value per row """ mask = K.cast(K.not_equal(y_true, 0), K.floatx()) count = K.sum(mask, 1) se = K.sum(K.square(y_true-y_pred)*mask, 1) rmse = K.sqrt(se / count) return K.mean(r...
c31b3a8cd842700617052fb7b43baf75a1a24634
46,351
def _infer_storage_long_name(field: xr.DataArray) -> str: """Infer the long_name for the storage component of a budget.""" field_long_name = field.attrs.get("long_name", field.name) return f"Storage of {field_long_name}"
cc97c4159441062656d303a80c9e51502a423935
46,352
def get_sparsity(arr): """Calculates sparsity of ndarray (0 - 1)""" if isinstance(arr, np.ndarray): return 1 - (np.count_nonzero(arr) / arr.size) elif isinstance(arr, pd.DataFrame): return arr.isnull().sum().sum() / arr.size else: raise TypeError("input must be a numpy array")
cd37295db925ca4a16a502df5bbd66aaddc9dfd0
46,353
import shelve import sys def update_board(screen, event, first, last, peg_color, flag): """update the board as guesses are made""" global LOCATION, POSITION, GUESS_LIST_SCREEN pygame.draw.rect(screen, WHITE, SHIELD) if event.type == QUIT: saved_game = shelve.open("SavedGame") save...
ce683b3d4982f1a9aa2bb220060e404d97614fb5
46,354
def jvp_solve_Ez_source(g, Ez, info_dict, eps_vec, source, iterative=False, method=DEFAULT_SOLVER): """ Gives jvp for solve_Ez with respect to source """ A = make_A_Ez(info_dict, eps_vec) return 1j * info_dict['omega'] * sparse_solve(A, g, iterative=iterative, method=method)
9e0126bbbdb419bdc90077dbffa554fba42d11c5
46,355
def is_unary_operator(oper): """returns True, if operator is unary operator, otherwise False""" # definition: # memeber in class # ret-type operator symbol() # ret-type operator [++ --](int) # globally # ret-type operator symbol( arg ) # ret-type operator [++ --](X&, int) symbols = [...
619122710316dd2ddc839e1e516c22c3c37babb5
46,356
def read_sparse(*args, **kwargs): """ given a collection of file paths representing relational data returns a pandas pandas DataFrame of the data :param args: collection of file paths representing an input file :param kwargs: keyword arguments to pass to pandas read function :return: pandas Data...
b83a0e584f14c03d2866db981154d8a9d551f1a1
46,357
import logging from typing import Any async def create_app() -> web.Application: """Create an web application.""" app = web.Application( middlewares=[ cors_middleware(allow_all=True), error_middleware(), # default error handler for whole application ], ) # Set ...
27e44d1e48892155854dbc8c53b4e213290b7d9f
46,358
import numpy def split3(img): """Splits a 3-channel image into its constituent channels. Convenience function using numpy slices, ~300x faster than cv2.split().""" assert(isinstance(img, numpy.ndarray)) assert(nchannels(img) == 3) return img[:, :, 0], img[:, :, 1], img[:, :, 2] #TODO: split i...
b65d211fd01ec0170a7ab137f0014ee520b7a7ff
46,359
def when(obj, strict=True): """Central interface to stub functions on a given `obj` `obj` should be a module, a class or an instance of a class; it can be a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface where you configure a stub in three steps:: when(<obj>).<method_...
d7b1adfebeac5251d5f6bfbe91b209e5182b4cb0
46,360
def get_nrg_const_hyb_coefficients(V, Lambda, nof_coefficients, corrected=True): """ Coefficients for the exact chain mapping for a constant hybridization in the SIAM, V_k = V (equivalent to setting Delta(eps) = pi*V^2 / 2, for eps in [-1.0, 1.0]) using logarithmic discratization Sou...
74571e999ccb983be1019987dfe74e195a4146d2
46,361
async def async_setup(hass): """Set up the Hassbian config.""" hass.http.register_view(CheckConfigView) websocket_api.async_register_command(hass, websocket_update_config) websocket_api.async_register_command(hass, websocket_detect_config) return True
40b1030544706b90e97e490d27780824e2ae4a88
46,362
def split_apt(field): """ Parses the ADDRESS field (<site address>, <apt number> <municipality>) from the CLEMIS CFS Report and returns the apartment number. """ if ',' in field: f = field.split(', ') f = f[1] f = f.split(' ') apt = f[0] else: apt = None ...
881f73ebe3de52ebd3ff31448ad488e2586be5bf
46,363
import math def sin(angle): """ Examples >>> sin(90*degrees) 1.0 """ if is_quantity(angle): return math.sin(angle/radians) else: return math.sin(angle)
43429de5bdcb13fc411c1231d873fa2230375a55
46,364
import os import tempfile import shutil def tempread(fp: str): """reads an audio file into a numpy array via a temp file Returns a tuple containing the sample rate in Hz followed by the audio data """ if not FFMPEG_INSTALLED: raise FFmpegException("ffmpeg is not available") fp = os.path.absp...
477c3bdb439fdd816ed0d753cba4adc89d5c1bf0
46,365
def random_series( n: int = 1, dtype=int, p_missing: float = 0, astype=None, low: (int, float) = 0, high: (int, float) = 1, ): """ Generate random pandas Series with given length, type and percentage of corrupted data. Parameters ---------- n : int, optional ...
53c20bf335ce4cc527a284c7f71cb33c80d6f6ad
46,366
def compile_partition(formulaPartition): """ Compile a formula Partition of UPPER case letters as numeric digits. E.g., compile_word('YOU') => '(1*U+10*O+100*Y)' Non-uppercase Partitions unchanged: compile_word('+') => '+' """ if formulaPartition.isupper(): terms = [('{}*{}'.format(10**i...
fb54f38508a9de686dc3768cb5a1688b01f1a368
46,367
def cla(): """Clear the current axes.""" # Not generated via boilerplate.py to allow a different docstring. return gca().cla()
8091d223c6737f9aaf5da932521d845e48c7b3cf
46,368
def is_distinguished_by_hyp_invars(M, s, t, tries, verbose): """ Given a manifold M and two slopes (where we think that both fillings are hyperbolic), try to prove that M(s) is not orientation-preservingly homeomorphic to M(t). Returns a tuple of booleans (distinguished, rigor) distinguished is...
ae8c41496760c697d07fa258df1de4e571e9b59f
46,369
import re def camel_to_snake_case(name): """ AssimilatedVatBox --> assimilated_vat_box """ exceptional = { "avg_c_p_a": "avg_cpa", "avg_c_p_m": "avg_cpm", "avg_c_p_t": "avg_cpt" } sn = re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower() sn = sn.split(" ")[0] # i.e. "dur...
fb3b6aac0d1ae3f0e328e59605da1b5e967d45e3
46,370
import os def initialize_and_download(datadir, state, year, horizon, survey, download=False): """Download the dataset (if required).""" assert horizon in ['1-Year', '5-Year'] assert int(year) >= 2014 assert state in state_list assert survey in ['person', 'household'] state_code = _STATE_CODES...
0cc05d276580920fd68335a7b62bda78e82d99fc
46,371
def get_all_members(): """Gets all current members (potential hassle participants).""" query = sqlalchemy.text(""" SELECT user_id, name, graduation_year, member_type, membership_desc, user_id IN ( SELECT user_id FROM hassle_participants ) AS participating FROM members NATURAL JOIN ...
b535bf895534d39e7a72add61fe035eb3cc3bbd7
46,372
def content(f, *gens, **args): """Returns GCD of polynomial coefficients. """ F = NonStrictPoly(f, *_analyze_gens(gens), **args) if not F.is_Poly: raise GeneratorsNeeded("can't compute content of %s without generators" % f) else: return F.content()
9178c2ab51c58ffdf0f0565ce29e7150412d943f
46,373
def entropy_of_list(lst): """Given a list of values, generate histogram and calculate the entropy.""" unique_values = N.unique(lst) unique_counts = N.array([float(len([i for i in lst if i == unique_val])) for unique_val in unique_values]) total = N.sum(unique_counts) probs = unique_counts/total ...
fb64032248c6495186b390e06bd769a30507cc91
46,374
def polygon_from_points(points): """ Returns a Polygon object to use with the Polygon2 class from a list of 8 points: x1,y1,x2,y2,x3,y3,x4,y4 """ resBoxes = np.empty([1, 8], dtype='int32') resBoxes[0, 0] = int(points[0]) resBoxes[0, 4] = int(points[1]) resBoxes[0, 1] = int(points[2]) res...
2be03580094d1bd71fe9bfc517f703668a41c269
46,375
import os def get_awsathena_db_name(db_name_env_var: str = "ATHENA_DB_NAME") -> str: """Get awsathena database name from environment variables. Returns: String of the awsathena database name. """ athena_db_name: str = os.getenv(db_name_env_var) if not athena_db_name: raise ValueEr...
a80150f079a778d119ee553e0f5c132e022b1bf0
46,376
from pathlib import Path def get_microservice_target_directory(path: Path, name: str) -> Path: """Get the target directory for a microservice. :param path: The starting path. :param name: The name of the microservice. :return: A ``Path`` instance. """ current = path while current != curre...
72f082d531c13966170e60a06c3ce01e7cfbf0b9
46,377
import os def load_experiments(file_name, experiment_names=None): """ Returns experimental parameters for experiment names of choice. :param file_name: str. Only the file name (not the path) of the yml file, located in conf folder. :param experiment_names: list. List of the experiment names to be...
fc4a1482964d92c0e82bacc99b810eba2a9cc1a6
46,378
def update_order_status(order_id): """updates order status """ if request.method == "PUT": data = request.get_json() if not data.get('complete'): return FeedbackResponse.display("status changed to complete", 406) complete = data.get('complete') status = customer_...
f2678fcbfbb17594a53d24375b7f006f347cabc3
46,379
import unittest def BasicTest(): """Return a new class - we do it this way to allow this to work properly for multiple tests""" class _BasicTest(unittest.TestCase): """Holder class which gets built into a whole test case""" dialect = 'VB6' container = vb2py.parserclasses.VBModule ...
f3891f141f24e0a488960744d2438e1366d30a99
46,380
from typing import Optional def category_to_detection_name(category_name: str) -> Optional[str]: """ Default label mapping from nuScenes to nuScenes detection classes. Note that pedestrian does not include personal_mobility, stroller and wheelchair. :param category_name: Generic nuScenes class. :r...
3e89526e0d4f897a7bb07808af3719d94aa0e12a
46,381
import os def derive_schema_path(catalog, request_version, schema): """Handle the implicit schema case by falling back on locally provided schema (matching the catalog).""" if schema: LOG.debug(f"xml validate try reading schema catalog={catalog}," f" schema={schema}, catalog env=({os...
86095303bb3fdf47eb6e70e501f5f04721fb727e
46,382
def acosh(x): """ Calculates the hyperbolic arccosine of the given input tensor element-wise. Args: x (Tensor): Input tensor Returns: Tensor, the output """ return Acosh()(x)[0]
e694011d578878d08dd5310b154b050824680d34
46,383
def multiclass_positive_predictive_value(confusion_matrix: np.ndarray, label_index: int) -> float: """ Gets the "positive predictive value" for a multi-class confusion matrix. The positive predictive value is also known as *precision*. See the documentation of ...
ae804312bcfae431edd4bd8bd6ab3a0b1269c53f
46,384
from datetime import datetime def mine_next_block(last_block, difficulty=None): """Generate and return the next block in the chain. Arguments: last_block: the last block in the chain to point to difficulty: [int] the difficulty, number of zeros the hash much start with Returns: A...
fd3b0698f7e4f6b8009714a7093977c168a456d0
46,385
def flatten_enumeration(my_enumeration): """ Flatten a dictionary of DCIMAttributeObjects """ pure_dictionary = {k: v.dictionary for k, v in my_enumeration.items()} return flatten_dict(pure_dictionary)
084dff2a6d9cc3dba9860be71bec86f92bd6c9d2
46,386
import unicodedata def transliterate(string: str) -> str: # Copy from inflection Library https://github.com/jpvanhal/inflection """ Replace non-ASCII characters with an ASCII approximation. If no approximation exists, the non-ASCII character is ignored. The string must be ``unicode``. Examples...
77e505f9b747f40b395d4207be7a75801d0c628c
46,387
import subprocess def zfs_create_zvol(volume: str, size: int, size_suffix: str = "G", blocksize: int = None, create_parent: bool = False, sparse: bool = False, properties: list = None) -> str: "...
516b4dcc84bf2562b8f7028b0d85db2a23bf64b9
46,388
def delete_ec2_nodes( instance_id_list, client=None ): """This deletes EC2 nodes and terminates the instances. Parameters ---------- instance_id_list : list of str A list of EC2 instance IDs to terminate. client : boto3.Client or None If None, this function will in...
6388ec17bc05eb0f2a4e45a547648d45adf88ab9
46,389
def handle_test_runners(args): """usage: {program} test-runners List the available test-runner plugins. """ assert args print('\n'.join(cosmic_ray.plugins.test_runner_names())) return ExitCode.OK
4443e58748f402df77b56e8f442356014e7779d6
46,390
def filter_by_status(project_name:str, dataset_name:str, task_id:str, status:str, email:str, timestamp:str): """ Function to filter items per task by status, works for all statuses (e.g., approved, completed...
bc038a5b40dfaf7db03ce3487e5d952cbf3db5d6
46,391
from io import StringIO def real_device_online_setup( arntask, creds, s3_folder, info, search_value, device_value, res_completed, results_json, ): """Real device online value test setup.""" qtarntask = {'quantumTaskArn': arntask} body = StreamingBody(StringIO(results_json),...
b2ffebc58ae3ccd0549a37fa8a31b071a989011f
46,392
def hex(value): """ return `value` in hex format :param value: :return: """ return hex(value)
5692717c5660cd5b02d47695f8e00aea6c33e19c
46,393
def change_password(session, uid_hash, current_password, new_password, logout_sessions=True): """Change the User's Password. Change or set the user password and create a new user hash so that any login tokens referencing the current user will be invalidated and the sessions must log in again with the n...
377a60f2f97a436effb5ca7747a7d202102935e8
46,394
def get_amino_acids(table): """ Get field "amino acids" from table Receives a results table Returns a list of amino acids """ return get_field(table, 1)
b734cfaedea9dc9fc9970e266a9f095ea4d2c0f6
46,395
def add_host_network(host_id): """add host network. Must fields: ['interface', 'ip', 'subnet_id'] Optional fields: ['is_mgmt', 'is_promiscuous'] """ data = _get_request_data() return utils.make_json_response( 200, host_api.add_host_network(host_id, user=current_user, **data) )
73f3a7f64dcaee4aad1ed3cacaaf9b9f9cf29cd7
46,396
def get_inverse_transform(transform): """Generates a transform which is the inverse of the provided transform""" inverse_transform = [0] * len(transform) for i in range(len(transform)): inverse_transform[transform[i]] = i return inverse_transform
80d577292c98a84eecbcfb84cef935245385b63b
46,397
from typing import Any def recover_password(email: str) -> Any: """ Password Recovery """ user = user_crud.get_by_email(db, email=email) if not user: raise HTTPException( status_code=404, detail="The user with this username does not exist in the system.", )...
92388c7c4075550467d9ca5c221b234b1664103f
46,398
import os def is_text(filename): """Return True if file is a text file. This is a guess. Files with null bytes are considered to be binary. Also, files that start with an extremely long line are considered to be binary. Empty files are considered as not text. """ if os.path.islink(filename):...
ccad4fd2e288b29bfca85c33ace23bd95ef4fecc
46,399