content
stringlengths
22
815k
id
int64
0
4.91M
def test_error_without_data(): """Check status and fields of a failed response. 1. Build a response with error, but without data. 2. Check the status. 3. Check data fields. """ error = APIError("Test") response = build_response(error=error, data=None) assert response["status"] == Respon...
5,291,400
def check_and_get_org_by_repo(repo_id, user): """ Check whether repo is org repo, get org info if it is, and set base template. """ org_id = get_org_id_by_repo_id(repo_id) if org_id > 0: # this repo is org repo, get org info org = get_org_by_id(org_id) org._dict['is_staff...
5,291,401
def upload_large(file, **options): """ Upload large files. """ upload_id = utils.random_public_id() with open(file, 'rb') as file_io: upload = None current_loc = 0 chunk_size = options.get("chunk_size", 20000000) file_size = getsize(file) chunk = file_io.read(...
5,291,402
def coordinate_val_generator(grid, out_of_bound=999): """yields tuple of ((x_coord, y_coord), val) within the bounds of the grid""" for coord in grid.items(): if coord[1] != 999: yield coord
5,291,403
def kappa(y_true, y_pred, weights=None, allow_off_by_one=False): """ Calculates the kappa inter-rater agreement between two the gold standard and the predicted ratings. Potential values range from -1 (representing complete disagreement) to 1 (representing complete agreement). A kappa value of 0 is ...
5,291,404
def p_queryopts_elem(p): """queryopts_elem : string '=' string | string '=' stringset""" p[0] = (p[1], p[3])
5,291,405
def get_post(id): """获取文章 """ post = Post.query.get_or_404(id) post.reading_num += 1 models.add_or_update(post) root_comment_list = db.session.query(Comment).filter_by( post_id=post.post_id, root_comment_id=-1).all() comment = { i: db.session.query(Comment).filter_by( ...
5,291,406
def sample_noise_using_sigma(log_sigma_sample, n_obs): """Produces a sample of residual noises based on sigma values. Args: log_sigma_sample: (tf.Tensor) Samples of log sigmas, shape (n_sample, ) n_obs: (int) Number of observation to sample for each sigma value. Returns: (tf.Tensor...
5,291,407
def rjd_to_jdn(rjd: int) -> int: """Return Julian day number (JDN) from Reduced Julian Day (RJD) number. :param rjd: Reduced Julian Day (RJD) number. :type rjd: int """ return rjd + 2400000
5,291,408
def clip_pad_images(tensor, pad_shape, pad=0): """ Clip clip_pad_images of the pad area. :param tensor: [c, H, W] :param pad_shape: [h, w] :return: [c, h, w] """ if not isinstance(tensor, paddle.Tensor): tensor = paddle.to_tensor(tensor) H, W = tensor.shape[1:] h = pad_shape[...
5,291,409
def make_tree_parallel_nj(distance_matrix: np.ndarray, names: np.ndarray) -> Tree: """ Nj tree is made from random sampling with replacement from the distance matrix. :param distance_matrix: :param names :return: """ np.random.seed(randint(0, 1000000)) selected_ids = np.random.choice(np....
5,291,410
def get_doc_for_user(trunk_id, user): """Retrieves document based on user's visit history. If the user has visited a particular revision (document of a trunk), user will see that document, else user will be directed to the latest revision. We pass user instead of using users.get_current_user, so that this f...
5,291,411
def png_segno(data='QR Code Symbol'): """Segno PNG 1-M""" segno.make_qr(data, error='m', boost_error=False).save(os.path.join(_output_dir(), 'segno_%s.png' % data), scale=10)
5,291,412
def clean_up_old_files(): """Save 2 most recent meditation log files""" log_files = stored_meditation_log_files() if len(log_files) > 2: for i, f in enumerate(sorted(log_files)[:-2]): os.remove(f) print("removed old files: {}".format(i + 1))
5,291,413
def resolve_match_norm_seq_alleles(data, maf_data): """ Resolves matched normal seq alleles. """ norm_allele1 = "" for col in MATCHED_NORMAL_SEQ_ALLELE1_COLUMNS: if col in data.keys(): norm_allele1 = process_datum(data.get(col,"")) break norm_allele2 = "" for col in ...
5,291,414
async def listplayers(ctx): """ List players on the ARK Server """ try: command = subprocess.check_output( ['arkmanager', 'rconcmd', '@all', 'listplayers'] ) except subprocess.CalledProcessError as e: command = e.output command_output = command.decode('UTF-8')...
5,291,415
def __lt__(self, other): """Computes the rich comparison LOWER THAN between two images. Parameters ---------- self : ee.Image Left operand. other : ee.Image | numeric | list[numeric] Right operand. If numeric, an ee.Image is created from its value. If list, an ee.Image with ...
5,291,416
def google_query(query: str, page_count: int) -> List: """Use the google package to pull weburls from google results. Args: query (str): query string page_count (int): how many results to get from google Returns: List: List of result dict {title: title string, url:...
5,291,417
def test_ft_sf_verify_buffer_pool_counters(): """ Author : prudviraj k (prudviraj.kristipati@broadcom.com) and phani kumar ravula(phanikumar.ravula@broadcom.com) """ result = 0 per_result = 0 sf_data.platform_name_summary = get_platform_summary(vars.D1) sf_data.platform_name = sf_data.platfo...
5,291,418
def _missing_synset(lex: lmf.Lexicon, ids: _Ids) -> _Result: """synset of sense is missing""" synset_ids = ids['synset'] return {s['id']: {'synset': s['synset']} for e in _entries(lex) for s in _senses(e) if s['synset'] not in synset_ids}
5,291,419
def create_component_analysis_timing_graph(durations, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, dpi=DPI): """Create graph with component analysis timings.""" N = len(durations) component_selectors = ["security_issues", "source_licenses", ...
5,291,420
def ask_for_path(): """asks for the path to the GPS-device and returns it if no path is specified: returns the standard PATH""" print("\nGib den Pfad zum GPS-Geraet ein (NICHT zum Unterordner 'GPX').") print("Falls Standardpfad uebernommen werden soll: keine Eingabe") inp = input(">> ") if inp ...
5,291,421
def add_til2(*args): """add_til2(char name, int flags) -> int""" return _idaapi.add_til2(*args)
5,291,422
def meta_sync_register(model, fields=None, exclude=()): """ 注册ORM模型(model)为需要进行元数据同步的类 Args: model 需要进行数据同步的model,必须继承至django.db.models.Model fields 需要进行数据同步的字段 exclude 不需要进行数据同步的字段 Examples: class DemoModel(models.Model): param1 = models.CharField(max_lengt...
5,291,423
def animation_export_button(self, context: Context): """Targets animation exporter class on menu button press. Args: self (): A reference to this bpy dynamic draw function. context (Context): The context containing data for the current 3d view. """ self.layout.operator(CalAnimationExpor...
5,291,424
def is_neq_prefix(text_1, text_2): """Return True if text_1 is a non-equal prefix of text_2""" return text_1 != text_2 and text_2.startswith(text_1)
5,291,425
def find_common_cond_attrs(sql_obj1, sql_obj2): """ Find common attributes for SQL join condition :param sql_obj1: :param sql_obj2: :return: """ commonpr_list = [] for project1 in sql_obj1.pr_list: for project2 in sql_obj2.pr_list: if project1.alias == project2.alias...
5,291,426
def tail(app, host, container, number_of_lines, all=False, follow=False, lines=None): """ Tail the logs of a container. Optional second argument specifies a number of lines to print. """ if all: tail = "all" else: tail = lines or number_of_lines _logs(app, host, container, tail, ...
5,291,427
def walk_hist(b, hist): """Makes a sequence of choices specified by hist towards specifying b. This function directly changes b. """ for ch_i in hist: b.choose(ch_i)
5,291,428
def read_config(fn, perm="r"): """ Read config file which consists parameters used in program. :param str fn: Name of config file (config.json) :param str perm: Mode in which the file is opened :return: Config file paramteres """ with open(fn, perm) as file: config = json.load(file...
5,291,429
def getParse(): """Desc: get Options parse.""" usage='''\ Desc: This is dataprocessing Tool FOR Beverly. # python datapro.py --dir ./dir/data''' parser = optparse.OptionParser(usage=usage) parser.add_option("-d","--dir",dest="dataDir",help="This is the data dir path") parser.add_option("-f"...
5,291,430
def test_get_group_by_name() -> None: """Try to get a group by its name and check returned value. Note: You must have a group named `RemNote` (case-sensitive) in your account before running the test, for this to work. """ group_name: str = "RemNote" remnote_group: Union[Mapping[str,...
5,291,431
def load_dataset(data_dir, url, batch_size): """Loads the colors data at path into a PaddedDataset.""" # Downloads data at url into data_dir/basename(url). The dataset has a header # row (color_name, r, g, b) followed by comma-separated lines. path = maybe_download(os.path.basename(url), data_dir, url)...
5,291,432
def get_version_from_git_describe(): """Determine a version by incrementing the git version in the context of master. This calls `git describe`, if git is available. Returns: version from `git describe --tags --always --dirty` if git is available; otherwise, None """ branch = subproc...
5,291,433
def assert_pyspark_df_equal( left_df: pyspark.sql.DataFrame, right_df: pyspark.sql.DataFrame, check_data_type: bool, check_cols_in_order: bool = True, order_by: Optional[str] = None ) -> None: """ left_df: destination layer, ex: raw right_df: origin layer, ex: oracle """ # Check ...
5,291,434
def check_invalid_indentation(path: str) -> Tuple[int, str, str, IndentationErrorType]: """ Check if the file contains any indentation errors. :param path: Path to file :return: Tuple[line number: int, error line: str, previous start of indentation block line: str...
5,291,435
def parseFile(filename, listener, strict=False): """ Parse a PCAP with the given filename. :param filename: str The file to parse :param listener: PcapListener :param strict: bool Indicating strict validation """ with gzip.open(filename, 'rb') if filename.endswith('.gz') else open(filename, 'rb') as pcapFile: ...
5,291,436
def yolo2_filter_boxes(boxes, box_confidence, box_class_probs, threshold=.6): """Filter YOLOv2 boxes based on object and class confidence.""" box_scores = box_confidence * box_class_probs box_classes = K.argmax(box_scores, axis=-1) box_class_scores = K.max(box_scores, axis=-1) prediction_mask = box_...
5,291,437
def publish_drs_object_registered( drs_object: models.DrsObjectInitial, config: Config = CONFIG ): """ Publishes a message to a specified topic """ topic_name = config.topic_name_drs_object_registered message = { "request_id": "", "file_id": drs_object.file_id, "timesta...
5,291,438
def timed_info(func): """Decorator to measure and logger.info a function's execution time.""" @functools.wraps(func) def timed_(*args, **kwargs): return _timed(func, logger.info, *args, **kwargs) return timed_
5,291,439
def test_move_all_photos_of_all_folders_month(move_photos_del_folders_month): """ Test for src//photonomist//__main__ > tidy_photos """ export_path = os.path.abspath('test/data/testing_folder_with_photos/move_folder') tidy_photos(export_path, move_photos_del_folders_month, year=False, month=True) as...
5,291,440
def pytest_runtest_setup(item): """Before test runs, reset Tensorflow graph. Parameters ---------- item : test function """ # pylint: disable=unused-argument LOGGER.info("Reset default graph") tf.reset_default_graph()
5,291,441
def get_label_base(label_path): """ Gets directory independent label path """ return '/'.join(label_path.split('/')[-2:])
5,291,442
def _bind_dpdk_interfaces(dpdk_interfaces): """ Bind NIC in DPDK """ for nic in dpdk_interfaces: logging.info("Attach {} to DPDK".format(nic)) helpers.run_command( "/usr/sbin/dpdk-devbind", "--force", "--bind=vfio-pci", nic )
5,291,443
def computeTriadCounts(G, signs): """ :param - G: graph :param - signs: Dictionary of signs (key = node pair (a,b), value = sign) return type: List, each position representing count of t0, t1, t2, and t3, respectively. return: Return the counts for t0, t1, t2, and t3 triad types. Count each triad only once...
5,291,444
def test_prefers(player_others): """Test that a Player instance can compare its preference between two players.""" player, others = player_others player.set_prefs(others) for i, other in enumerate(others[:-1]): assert player.prefers(other, others[i + 1])
5,291,445
def test_atomic_time_max_inclusive_4_nistxml_sv_iv_atomic_time_max_inclusive_5_2(mode, save_output, output_format): """ Type atomic/time is restricted by facet maxInclusive with value 23:59:59. """ assert_bindings( schema="nistData/atomic/time/Schema+Instance/NISTSchema-SV-IV-atomic-time-max...
5,291,446
def main(): """ Set OS to Windows XP to pass the black menu screen """ util.protontricks('winxp')
5,291,447
def properties_var(): """ Stream properties: 1. n_chunks 2. chunk_size """ return (200, 250)
5,291,448
def factored_joint_mvn(distributions): """Combine MultivariateNormals into a factored joint distribution. Given a list of multivariate normal distributions `dist[i] = Normal(loc[i], scale[i])`, construct the joint distribution given by concatenating independent samples from these distributions. This is m...
5,291,449
def cli_command(fn): """Register function as subcommand.""" command = SUBPARSERS.add_parser(fn.__name__, description=fn.__doc__) command.set_defaults(func=fn) unspecified = object() args = reversed(list(zip_longest( reversed(fn.__code__.co_varnames[:fn.__code__.co_argcount]), revers...
5,291,450
def mutate(file, factor): """Mutate $factor% of bytes in the $file""" file = bytearray(file) mutations = len(file) * factor if mutations is 0 and factor is not 0: mutations = 1 while mutations > 0: random_byte = random.randint(0,255) random_position = random.randint(0, len(file)-1) file[random_position] ...
5,291,451
def forward_fill_series(s1, s2): """ For two pandas series with DateTimeIndex , return corresponding series with the same numer of entries, forward-filled. :type s1: pd.Series :type s2: pd.Series """ def dedup_index(s): """ Deduplicate index values of pd.Series""" df = s.to...
5,291,452
def last_value_with_no_frame(self): """Check last_value function with no frame. """ expected = convert_output(""" four | ten | sum | last_value ------+-----+-----+------------ 0 | 0 | 0 | 0 0 | 2 | 2 | 2 0 | 4 | 6 | 4 0 | 6 | ...
5,291,453
def prepare_clang_coverage_data(): """ Prepare clang/llvm profile data. """ binary_paths = [ "unittests/Feature/VaRAFeatureTests", "unittests/Utils/VaRAVariantUtilsTests", "bin/fm-viewer", ] merge_llvm_data() subprocess_cmd = [ get_llvm_cov_binary_name(), "s...
5,291,454
def uuid_uri(prefix): """Construct a URI using a UUID""" return prefix + str(uuid.uuid1())
5,291,455
def mempool_command(update: Update, context: CallbackContext): """ Get current mempool stats """ mempool_space_mempool_stats(update, context)
5,291,456
def trainNetwork(x_train, tb_train, uc_train, gradc_train, nut_train, x_dev, tb_dev, uc_dev, gradc_dev, nut_dev): """ This function takes in training data and validation data (aka dev set) and runs the training routine. We initialize parameters of the TBNN-s through the dictionary...
5,291,457
def is_raw_json_null(py_obj: Any) -> bool: """ Checks if the given Python object is a raw JSON null. :param py_obj: The Python object to check. :return: True if the Python object is a raw JSON null, False if not. """ # Must be None return py_obj is None
5,291,458
def download_symbol_directory(): """ https://quant.stackexchange.com/a/1862/55288 https://stackoverflow.com/a/11573946/101923 """ ftp = ftplib.FTP("ftp.nasdaqtrader.com") ftp.login() ftp.cwd("Symboldirectory") with open(NASDAQ_DIR / "nasdaqlisted.txt", "wb") as handle: ftp.retrbi...
5,291,459
async def async_setup_entry(hass, config, async_add_entities): """Create wallbox sensor entities in HASS.""" wallbox = hass.data[DOMAIN][CONF_CONNECTIONS][config.entry_id] station = config.data[CONF_STATION] async def async_update_data(): try: return await hass.async_add_executor_...
5,291,460
def raise_sigint(): """ Raising the SIGINT signal in the current process and all sub-processes. os.kill() only issues a signal in the current process (without subprocesses). CTRL+C on the console sends the signal to the process group (which we need). """ if hasattr(signal, 'CTRL_C_EVENT'): ...
5,291,461
def xpdacq_grid_scan_with_dark(detectors: list, *args, snake_axes: typing.Union[bool, typing.Iterable[bool], None] = None, per_step: typing.Callable = xpdacq_per_step, md: typing.Union[dict, None] = None) -> typing.Generator: ...
5,291,462
def various_indexes(request): """Parametrized cached index of various types with source.""" source = mangasource.MangaSource( 'test source', 'http://www.source.com/', '_', index_tag=request.param['tag'], index_attrs=request.param['attr'] ) now = datetime.utcnow().timestamp() cac...
5,291,463
def underscore_2_space(string: str): """ Return string with underscores replaced by spaces. """ return re.sub('[_]', ' ', string)
5,291,464
def _print_summary(args: argparse.Namespace, stats: Dict): """Print a summary of what was done. :param args: Parsed command line arguments. :param stats: Statistics data structure. """ LOGGER.info("Filebeat Scrubber Summary:") if args.move: LOGGER.info(" Moved files: %s", s...
5,291,465
def jid_to_time(jid): """ Convert a salt job id into the time when the job was invoked """ jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != "_"): return "" year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = jid[10:12] ...
5,291,466
def iotc_connect_by_uid_parallel( tutk_platform_lib: CDLL, p2p_id: str, session_id: c_int ) -> c_int: """Used by a client to connect a device and bind to a specified session ID. This function is for a client to connect a device by specifying the UID of that device, and bind to a tutk_platform_free sess...
5,291,467
def import_entry_point() -> Iterator[Callable[[str], Optional[int]]]: """ Yields a function that imports a module in a seperate Python process and returns the exit code. """ context = multiprocessing.get_context("spawn") def do_import(module: str) -> Optional[int]: process = context.Process...
5,291,468
def sort_radius_front_to_back( render_position, render_direction, objects, object_positions ): """Sorts objects from front to back based on their distance from the camera. :param numpy.array render_position: The position of the camera the scene is being rendered from. ...
5,291,469
def preprocess_inputs(batched_data, max_sub_l, max_vcpt_l, max_vid_l, device="cuda:0"): """clip and move to target device""" max_len_dict = {"sub": max_sub_l, "vcpt": max_vcpt_l, "vid": max_vid_l} text_keys = ["q", "a0", "a1", "a2", "a3", "a4", "sub", "vcpt"] label_key = "answer_idx" qid_key = "qid"...
5,291,470
def test_md009_good_unordered_list_item_empty_lines(): """ Test to make sure this rule does not trigger with a document that has trailing spaces at the end of a blank line within a list item. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/reso...
5,291,471
def make_diff_prop_modified(pname, pval1, pval2): """Return a property diff for modification of property PNAME, old value PVAL1, new value PVAL2. PVAL is a single string with no embedded newlines. Return the result as a list of newline-terminated strings.""" return [ "Modified: " + pname + "\n", ...
5,291,472
def check_bvmp_samples(value, num_samples, n, pool_size, mean, tol): """ bvmp=BinaryVectorMaxPool value: a tuple giving (pooled batch, detector batch) (all made with same params) num_samples: number of samples there should be in the batch n: detector layer dimension pool_size: size of each poo...
5,291,473
def test_init(logger): """ Tests various strategy initialization. """ # 1 inbound tree with 1 action, zero outbound trees strat = actions.strategy.Strategy([], []).initialize(logger, 1, 0, 1, 0, None) s = "[TCP:flags:R]-drop-| \/" # initialize with a seed assert str(actions.strategy.Stra...
5,291,474
def mean_confidence_interval(data, confidence=0.95): """ Calculates 95% confidence intervals (CI). Taken from: https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data : data (pd.DataFrame): : confidence (float): """ a = 1.0 * np.array(data) ...
5,291,475
def wmean( x: torch.Tensor, weight: Optional[torch.Tensor] = None, dim: Union[int, Tuple[int]] = -2, keepdim: bool = True, eps: float = 1e-9, ) -> torch.Tensor: """ Finds the mean of the input tensor across the specified dimension. If the `weight` argument is provided, computes weighted ...
5,291,476
def GetDeleteSQLByName(name): """获取 Delete 配置 SQL 语句""" PS = __ParserSQL__() return PS.GetDeleteSQLByName(name)
5,291,477
def CPUs(): """ Detects the number of CPUs on a system. Cribbed from pp. """ global cpu_count if cpu_count is None: cpu_count = 1 # default # Linux, Unix and MacOS: if hasattr(os, "sysconf"): if "SC_NPROCESSORS_ONLN" in os.sysconf_names: # Linux &...
5,291,478
async def test_async_plasmawave_on_off(): """Test turning plasmawave on.""" # async_plasmawave does not need the device to be turned on with patch(f"{WinixDriver_TypeName}.plasmawave_on") as plasmawave_on, patch( f"{WinixDriver_TypeName}.plasmawave_off" ) as plasmawave_off: wrapper = bu...
5,291,479
def authorized_access(response): """Check if access is authorized""" return check_uuid(response.headers.get("Bearer"))
5,291,480
def language_is_allowed(code): """ Check a language code is valid """ return code in get_language_dict()
5,291,481
def calculate_distance(vector1, vector2): """ Calculates Euclidean distance between two vectors. :param vector1:vector presents a face feature :param vector2:vector presents a face feature :return:disance:the Euclidean distance between vector1 and vector2. """ temp = vector1 - vector2 di...
5,291,482
def classify(img, is_url=False): """ Runs the given image through the model and returns the results. """ data = ImageData([[True], [img]]) if not is_url else ImageData([[True], [img]], is_url=True) # pass image to be "tensorized" tensor_image, _, img_path = data[0] # get image tensor etc tensor_image =...
5,291,483
def rb_interleaved_execution(rb_opts: dict, shots: int): """ Create interleaved rb circuits with depolarizing error and simulate them Args: rb_opts: the options for the rb circuits shots: number of shots for each circuit simulation Returns: list: list of ...
5,291,484
def nd_to_columns(data, layers, rows, columns): """ Reshapes an array from nd layout to [samples (rows*columns) x dimensions] """ if layers == 1: return np.ascontiguousarray(data.flatten()[:, np.newaxis]) else: return np.ascontiguousarray(data.transpose(1, 2, 0).reshape(rows*column...
5,291,485
def server_error(exception): """Return True if we should retry (in this case when it's an ServerError, False otherwise""" return isinstance(exception, ServerError) or isinstance(exception, ConnectionError)
5,291,486
def lat_weights_regular_grid(lat): """ Generate latitude weights for equally spaced (regular) global grids. Weights are computed as sin(lat+dlat/2)-sin(lat-dlat/2) and sum to 2.0. """ dlat = np.abs(np.diff(lat)) np.testing.assert_almost_equal(dlat, dlat[0]) w = np.abs(np.sin(np.radians(lat +...
5,291,487
def get_universe(name, cache=False, environ=None): """ Parameters ---------- name: str cache: Returns ------- AbstractUniverse """ # cache universe in case we use it in-memory... if name == 'test': return TestUniverse(cache) elif name == 'quandl': retu...
5,291,488
def batch_normalization(x, mean, variance, offset, scale, variance_epsilon, data_format, name=None): """Data Format aware version of tf.nn.batch_normalization.""" if data_format == 'channels_last': mean = tf.reshape(mean, [1] * (len(x.shape) - 1) + [-1]) variance = tf.reshape(variance, [1] * (le...
5,291,489
def explore_CordAttractor(N=10, angle=0.0, max_time=4.0, a=0.25, b=4.0, F=8.0, G=1.0, Plot=False): """ You can use it with animated widgets: from IPython.html.widgets import interact, interactive w = interactive(solve_lorenz, angle=(0.,360.), N=(0,50), sigma=(0.0,50.0), rho...
5,291,490
def test_pos_err_on_guide(): """Test the check that no guide star has large POS_ERR""" stars = StarsTable.empty() stars.add_fake_star(id=100, yang=100, zang=-200, POS_ERR=2010, mag=8.0) stars.add_fake_star(id=101, yang=0, zang=500, mag=8.0, POS_ERR=1260) # Just over warning stars.add_fake_star(id=1...
5,291,491
def get_current_user(sql: Session = Depends(db_session), token: str = Depends(oauth2_scheme)): """get authenticated user""" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ...
5,291,492
def long_from_bytes(data): """ Return an integer from base64-encoded string. :param data: UTF-8 string containing base64-encoded data. :returns: Corresponding decoded integer. """ return int.from_bytes(decode_base64(data.encode("ascii")), 'big')
5,291,493
def download_model(name: str, download_dir: str, cache_dir: str, force_download: bool, logger: logging.Logger) -> str: """ Downloads and extracts a model into cache dir and returns the path to the model directory :param name: unique name of the model :param download_dir: directory to store zipped mode...
5,291,494
def valid_browser(ua): """ Returns boolean depending on whether we support their browser based on their HTTP_USER_AGENT Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; en-us) AppleWebKit/531.21.8...
5,291,495
def openREADME(): """ This is only needed because README.rst is UTF-8 encoded and that won't work under python3 iff sys.getfilesystemencoding() returns 'ascii' Since open() doesn't accept an encoding in python2... """ try: f = open("README.rst", encoding="utf-8") except: f =...
5,291,496
def test_get_price_policies_01(): """ Test getting all price_policies. """ response = client.get("/price_policies/all/") assert response.status_code == 200 assert response.json() is not None
5,291,497
def draw_one_smarts_subset_relation(directed_edge: DirectedEdge, viewer_path: str, output_path: str): """ Draws one DirectedEdge, i.e., a subset relationship from directed_edge.from_smarts to directed_edge.to_smarts, as an SVG file to t...
5,291,498
def set_host_enabled(self, arg_dict): """Sets this host's ability to accept new instances. It will otherwise continue to operate normally. """ enabled = arg_dict.get("enabled") if enabled is None: raise pluginlib.PluginError( "Missing 'enabled' argument to set_host_enabled") ...
5,291,499