content
stringlengths
22
815k
id
int64
0
4.91M
def is_pod_not_running(pod_name, deployment_target=None, pod_number=0, verbose=True): """Returns True if the given pod is in "Running" state, and False otherwise.""" json_path = "{.items[%(pod_number)s].status.phase}" % locals() status = get_pod_status(pod_name, json_path, deployment_target=deployment_tar...
71,900
def _bciPercentileBias(replicates,allData,alpha): """Simple percentile CI with bias correction""" #The jackknife, the bootstrap and other resampling plans #(See page 118) #https://statistics.stanford.edu/sites/default/files/BIO%2063.pdf alpha = alpha/2 #get z for the bias and the desired alpha...
71,901
def create_orth_variants_augmenter( level: float, lower: float, orth_variants: Dict[str, List[Dict]] ) -> Callable[["Language", Example], Iterator[Example]]: """Create a data augmentation callback that uses orth-variant replacement. The callback can be added to a corpus or other data iterator during trainin...
71,902
def _download_anno_files(base_url, file_names, anno_dir, cur_config): """Download and install each of the annotation files """ for orig in file_names: if orig.endswith(".gz"): dls = [orig, "%s.tbi" % orig] else: dls = [orig] for dl in dls: if dl in...
71,903
def test_flux_conversion_vega(in_q, out_u, ans): """Test Vega spectrum object and flux conversion with VEGAMAG. .. note:: 1% is good enough given Vega gets updated from time to time. """ result = units.convert_flux(_wave, in_q, out_u, vegaspec=_vspec) assert_quantity_allclose(result, ans, rtol=1e-...
71,904
def check_hcl(hcl): """ hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f. """ if len(hcl) == 7 and hcl.startswith("#"): int(hcl[1:], 16) else: raise
71,905
def create_magnitude_spectrum(image): """Creates a magnitude spectrum from image params: image: A numpy ndarray, which has 2 or 3 dimensions (BGR) return: A numpy ndarray, which has 2 dimensions """ image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) dft = cv2.dft(np.float32(image), flags=cv...
71,906
def traj_loader(parm, crd, step=1000): """ Load and return a trajectory from mda universe. Input parmater file, coordinate file, and loading step interval (default=1000). """ traj = mda.Universe(parm, crd, in_memory=True, in_memory_step=step, verbose=True) return traj
71,907
def index(request: HttpRequest) -> HttpResponse: """Render the index page.""" # Build a list of race options (year/type/state/district/csv) null = None options = [['2004', 'pres', 'National', 'atlarge', '2004_pres_us.csv'],\ ['2006', 'senate', 'Virginia', 'atlarge', '2006_senate_va.csv']...
71,908
def len_and_chsum(msg, group=False): """Calculate length and checksum. Note that the checksum is not moduloed with 256 or formatted, it's just the sum part of the checksum.""" count = 0 chsum_count = 0 for tag, value in list(msg.items()): if not isinstance(tag, bytes): tag = str(...
71,909
def data_writer(file_path, data): """ takes a filepath and data object and writes the data to a file at the filepath :param file_path: path to file :param data: data to write to the file """ outfile = open(file_path, "w+") json.dump(data, outfile)
71,910
def config(): """Configures variables for dp2rathena (api-key).""" api_key = input('Enter your Divine-Pride API key: ') CONFIG_PATH.write_text(f'{DP_KEY}={api_key}\n') click.echo('Configuration saved to ' + str(CONFIG_PATH.resolve()))
71,911
def test_provide_module(code): """Package instance itself should refer to the module.""" Container = code() assert inspect.ismodule(Container.itself) assert inspect.ismodule(Container.submodule)
71,912
def data_parallel_decorator(ModuleClass): """ A decorator for forward function to use multiGPU training while maintaining network layout (and thus saved parameter names). Note: the way pytorch replicate a module only guarantees that pytorch internal parameters, buffers and modules are prop...
71,913
def mapping_dicts(lucid_tokens_df, corpus_df, lucid2pascal): """return id2word, mapping LUCID id's to words, and id2pic, mapping LUCID id's to sets of picture names and pic2id, mapping picture names to tokens""" id2word = dict(zip(lucid_tokens_df['id'], lucid_tokens_df['word'])) word2id = defaultdict(se...
71,914
def test_log_append_true(tmp_path, container_runtime_or_fail): """run 5 times, append to log each time""" def side_effect(*_args, **_kwargs): return None repeat = 5 new_session_msg = "New ansible-navigator instance" log_file = tmp_path / "ansible-navigator.log" cli_args = [ "an...
71,915
def load_config(path): """ """ def scan(l): if l == "": return (NL, l) elif l[0] == '#': return (COMM, l) b = l.find('=') if b < 0: return (COMM, l) key = l[:b].strip() if key == "": return (COMM, l) ret...
71,916
def main(): """ This is the function that is run from commandline with `yagmail` """ import argparse parser = argparse.ArgumentParser( description='Send a (g)mail with yagmail.') parser.add_argument( '-to', '-t', help='Send an email to address "TO"', nargs='+') parser.add_argument('-...
71,917
def dataset(client): """Create a dataset.""" with client.with_dataset(name='dataset') as dataset: dataset.authors = { 'name': 'me', 'email': 'me@example.com', } return dataset
71,918
def run_e2e(graph): """Running end to end example """ import json if debug_fpga_only: graph = mark_nop(graph, skip_conv_layer=(0,)) dt=time.time() m = graph_runtime.create(graph, lib, ctx) timers['execution_time_create_run_time_graph']=(time.time()-dt) total_images=0 corre...
71,919
def err(s, fatal = False): """! Prints an error message. \param s The error message to log \param fatal True if this is a fatal error """ if (_verbosity > 0 and fatal) or (_verbosity > 1): print(('ERROR: ' if not fatal else 'FATAL: ') + s, file=sys.stderr)
71,920
def update_SE_kwargs(kwargs={}, kwargs_update={'DETECT_THRESH':3, 'ANALYSIS_THRESH':3}): """ Update SExtractor keywords in kwargs """ from .detection import default_conv, default_nnw SE_key = kwargs.keys() for key in kwargs_update.keys()...
71,921
def actual_time(ts) -> str: """ Takes in a UNIX timestamp and spits out actual time as a string without microseconds. """ dt = datetime.datetime.fromtimestamp(float(ts)/1000.0) dt = dt.replace(microsecond=0) return str(dt)
71,922
def classify_vector(in_x, weights): """ 最终的分类函数,根据回归系数和特征向量来计算 Sigmoid 的值,大于0.5函数返回1,否则返回0 :param in_x: 特征向量,features :param weights: 根据梯度下降/随机梯度下降 计算得到的回归系数 :return: """ # print(np.sum(in_x * weights)) prob = sigmoid(np.sum(in_x * weights)) if prob > 0.5: return 1.0 ret...
71,923
def pd_resample(pd_object, rule, *args, **kwargs): """ 对pandas中的resample操作,根据pandas version版本自动选择调用方式 :param pd_object: 可迭代的序列,pd.Series, pd.DataFrame或者只是Iterable :param rule: 具体的resample函数中需要的参数 eg. 21D, 即重采样周期值 :return: """ if g_pandas_has_resampler: """pandas版本高,使用如pd_object.resam...
71,924
def test_median_conf_radius(t, alfa, radius): """Сверка расчетных значений.""" assert seq._median_conf_radius(t, alfa) == pytest.approx(radius)
71,925
def clone(pc): """ Return a copy of a pointcloud, including registration metadata Arguments: pc: pcl.PointCloud() Returns: cp: pcl.PointCloud() """ cp = pcl.PointCloud(np.asarray(pc)) if is_registered(pc): force_srs(cp, same_as=pc) return cp
71,926
def strategy_best(cookies, cps, history, time_left, build_info): """ The best strategy that you are able to implement. """ build_items_list = build_info.build_items() max_cps_div_cost_item = None for idx in range(len(build_items_list)): if build_info.get_cost(build_items_list[idx]...
71,927
def wallStop(sprite, partner, game, friction=0): """ Stop just in front of the wall, removing that velocity component, but possibly sliding along it. """ if not oncePerStep(sprite, game, 'laststop'): return stepBack(sprite, partner, game) if abs(sprite.rect.centerx - partner.rect.cente...
71,928
def run_link_removal(path, net_name): """ Sets up framework and runs the edge removal simulation. Parameters ---------- path: string path to the network to be analyzed net_name: string name of the network (for labeling) Returns ------- No direct output, saves figure...
71,929
def test_get_contract_instance(): """Test the get contract instance method.""" contract_address = "0x250A2aeb3eB84782e83365b4c42dbE3CDA9920e4" ethereum_api = EthereumApi(**ETHEREUM_TESTNET_CONFIG) interface = {"abi": [], "bytecode": b""} instance = ethereum_api.get_contract_instance( contrac...
71,930
def assetlink_command(args): """ Link the asset directory of the currently installed theme """ global_config, app_config = setup_global_and_app_config(args.conf_file) theme_registry, current_theme = register_themes(app_config) link_assets(current_theme, app_config['theme_linked_assets_dir'])
71,931
def autofocus_field(field, *args, **kwargs): """ Add the 'autofocus' attribute to an input tag. Usage:: {% autofocus_field field field_class='col-md-12' %} Extra args and kwargs are passed to ``bootstrap_field``. """ return mark_safe(re.sub( '<input', '<input autofocus', ...
71,932
def get_buildrequire_pkgs_from_build(build, session, config): """ Function which queries koji for pkgs whom belong to a given build tag of a koji build and paires rpms with their respective package. :param dict build: build information returned by koji. :param koji.ClientSession session: koji conne...
71,933
def test_index(tmpdir, database_type): """ Test database operations on a table with an index """ if database_type == "postgresql": pytest.skip("Unsupported operation") table = "record_simple" first_record = { "id": 1, "key": "first" } second_record = { "id": 2, "key": "second" } third_record = { "id": 3, "key...
71,934
def test_get_task_inexistent(client): """Tests getting a task that does not exists.""" with pytest.raises(Exception): client.get_task('abc')
71,935
def set_up_database(path, engine): """ Set up or connect to an SQLite database Return the database connection """ if not os.path.exists(path): LOG.info("Creating dir: %s", path) os.mkdir(path) LOG.info("Attempting to create db") BASE.metadata.create_all(engine)
71,936
def SceneShadowManagerPrepareAddShadowManager(builder, shadowManager): """This method is deprecated. Please switch to AddShadowManager.""" return AddShadowManager(builder, shadowManager)
71,937
def load_scaler(scaler_filepath): """Load MinMaxScaler save object. Parameters ---------- scaler_filepath : pathlib.PosixPath Path to MinMaxScaler save object Returns ------- sklearn.preprocessing._data.MinMaxScaler """ return joblib.load(scaler_filepath)
71,938
def get_sender_sparse_date_info(email_ids_per_sender, senders_idx_to_mid_dic, df_info): """ gets time info as one-hot encoding in sparse matrix idx matching mids as in idx_to_mids in rows and days in columns idx_to_mids for each sende...
71,939
def is_existing_group(group_name): """Asserts the group exists on the host. Returns: bool, True if group exists on the box, False otherwise """ try: grp.getgrnam(group_name) return True except KeyError: return False
71,940
def unpack_struct(struct: Tag, keydict: Dict[str, Any]) -> Dict[str, Any]: """Parse a tag with children, if tag is not arrayof.... Parameters ---------- struct: bs4.Tag Section of returned tree to be parsed as a complex type Returns ------- Dict[str,Any] The parsed section ...
71,941
def server_error_error(): """ 500错误处理 """ return server_error('Server error')
71,942
def get_c2d_topic_for_subscribe(device_id): """ :return: The topic for cloud to device messages.It is of the format "devices/<deviceid>/messages/devicebound/#" """ return _get_topic_base(device_id) + "/messages/devicebound/#"
71,943
def loadfolded(fname): """Load the folded power spectrum file""" if fname in folded_filedata and os.path.getmtime(fname) <= folded_filedata[fname][0]: return folded_filedata[fname][1] f_in= np.fromfile(fname, sep=' ',count=-1) #Load header scale=1000 time=f_in[0] bins_a=int(f_in[1]) ...
71,944
def stakeholder_tweets(users, keywords, credentials=None, limit=None): """ Get tweets from users by keywords @users = list of annotated entities (see find_stakeholder_twitter_users) @keywords = list of keyword objects (see content.content_keywords) """ # Throw ...
71,945
def re_search(text: str, expression: str) -> bool: """ Test regex match. This method is comparatively very slow and should be avoided where possible. """ return re.search(expression, text) is not None
71,946
def test_options_ok_duplicated_wantlistaction(mocker): """test_options_ok_duplicated_wantlistaction Test the usage of duplicated '--wantlist' argument and the custom 'Action' assign to it. Args: mocker (pytest_mock.plugin.MockerFixture): Mocker. """ testargs = ['prog', '--apikey', 'dummy...
71,947
def phabricator(parser, xml_parent, data): """yaml: phabricator Integrate with `Phabricator <http://phabricator.org/>`_ Requires the Jenkins :jenkins-wiki:`Phabricator Plugin <Phabricator+Plugin>`. :arg bool comment-on-success: Post a *comment* when the build succeeds. (optional) :arg bo...
71,948
def test_group_by_commas10(): """Tests that commas are inserted properly.""" from grouped_by_commas import group_by_commas n = 1234567890 assert group_by_commas(n) == '1,234,567,890'
71,949
def get_conf_json(path, file): """ 通用: 获取 JSON 配置文件 :param path: 相对于 conf, e.g. bgp :param file: 文件名, 不带扩展名, e.g. as-name :return: dict,e.g. {'123': '成都'} """ ret = {} file = os.path.join(current_app.root_path, 'conf', path, file + '.json') try: with open(file, 'r', encodin...
71,950
def saved_model_graph(): """ save the graph of model and check it in tensorboard :return: """ from os.path import join from network_mv2_cpm_2 import build_network import tensorflow as tf import os os.environ['CUDA_VISIBLE_DEVICES'] = '' input_node = tf.placeholder(tf.float32,...
71,951
def GenerateStochasticBlockModelWithFeatures( num_vertices, num_edges, pi, prop_mat = None, out_degs = None, feature_center_distance = 0.0, feature_dim = 0, num_feature_groups = None, feature_group_match_type = MatchType.RANDOM, feature_cluster_variance = 1.0, edge_feature_di...
71,952
def make_unique_filename(initial_filename): """Add a random part to a filename so it's unique. File extension is preserved.""" before_ext, ext = os.path.splitext(initial_filename) ext = ext.replace('.', '') # Remove the dot, if already there. random_part = uuid.uuid4() return f"{before_ext}-{random...
71,953
def _add_spatial_variables(root, grid, **kwds): """Add spatial variables to a NetCDF file. Add the variables to *root* that define the structured grid, *grid*. Parameters ---------- root : netcdf_file A NetCDF file. grid : RasterModelGrid A structured grid. long_name : dict...
71,954
def median(lst): """ Get the median value of a list Arguments: lst (list) -- list of ints or floats Returns: (int or float) -- median value in the list """ n = len(lst) if n < 1: return None if n % 2 == 1: return sorted(lst)[n//2] else: ...
71,955
def fit_taus(zi, Kti, iter_max=42, eps_max=1e-6, plot=False, quiet=False): """ Fit the ASHRAE pseudo-spectral coefficients tau_b & tau_d given a set of elevation z and clear sky index Kt values. """ # Need at least two points if len(Kti) < 2: if not quiet: print("Warning: In...
71,956
def api_get_flights(airline: str, flight_date: datetime, api_url=api_url, api_token=api_token, tries=0, timeout=api_timeout) -> typing.List[typing.Dict]: """ Call REST API to get flight records for a given date ...
71,957
def e_log() -> str: """Check next update content.""" with open(file=TMERGE_LOGFILE, encoding='utf-8') as log_file: content = log_file.read() return content
71,958
def read_ferre_headers(path): """ Read a full FERRE library header with multi-extensions. :param path: The path of a FERRE header file. Returns: libstr0, libstr : first header, then list of extension headers; headers returned as dictionaries """ try: with open(path, "r")...
71,959
def load_images(folder_path, img_size=32, num_channels=3, dtype=np.float32, normalize=True): """Loads images from a folder. Args: folder_path: Path to a folder with png images. img_size: Size of the image. num_channels: Number of channels in the output image. dtype: Data type of...
71,960
def orop(funeval, *aa): """ Lazy version of `or' """ for a in aa: if funeval(a): return True return False
71,961
def get_value(kind, index): """ Retrieve a previously stored value """ data = retrieve(kind, index) if data is not None: data = data["value"] return data
71,962
def load_labels(): """Load the image label file and transform it to the desired format""" y_labels = pd.read_csv("../data/y_labels/train_v2.csv") y_labels["tags"] = y_labels["tags"].apply(lambda x:x.split(" ")) y_labels["image_name"] = y_labels["image_name"].apply(lambda x: x + ".jpg") UNIQUE_LABELS...
71,963
def example_human_player(human): """ A Human "game player" (decider) -- a generator that chooses behaviors like put Cube through Portal. The Human yields to this generator each time it needs instructions; this generator in turn updates the Human and returns a behavior description. The actions d...
71,964
def get_QBias(mobile, bc, sss=[None, None, None], d_cutoff=8.0, prec=3, norm=True, plot=True, warn=True, verbose=True, **kwargs): """ Get QValue for formed bias contacts. .. Note :: selection of get_QBias() is hardcoded to sel='protein and name CA'. Reason: bias contacts are unique RES...
71,965
def weakref_props(*properties): """A class decorator to assign properties that hold weakrefs to objects. This decorator will not overwrite existing attributes and methods. Parameters ---------- properties : list of str A list of property attributes to assign to weakrefs. Examples ...
71,966
def edge_total_communicability(G, u, v, t=1, tol=1e-7, maxit=50): """ Computes the edge total communicabilities of edge :math:`(u, v)`. If nodes :math:`u` and :math:`v` are the :math:`i^{th}` and :math:`j^{th}` nodes of the graph, the edge total communicability of :math:`(u, v)` is given by the product...
71,967
def kernel_eligible_pair(X, Y): """ Validate X and Y if those are eligible to compute karnel Parameters ---------- X: np.ndarray (n, d) of real (-inf, inf) n: number of samples in X d: number of features if a 1d array (d,) is given, it's automatically converted ...
71,968
def getBadges( steamId ): """ :param steamId: int :return: { "player_xp": int, "player_level": 13, "player_xp_needed_to_level_up": int, "player_xp_needed_current_level": int, "badges": [ { ...
71,969
def detect_objects(interpreter, image, threshold): """Returns a list of detection results, each a dictionary of object info.""" set_input_tensor(interpreter, image) interpreter.invoke() # Get all output details boxes = get_output_tensor(interpreter, 0) classes = get_output_tensor(interpreter, 1...
71,970
def convert_dict_float_to_dec(dict): """ Given a dict, take any values that is a float number and convert it to decimal so it can be written to DDB. :param dict: :return: a new dict object with all floating number values replaced with Decimal representation. """ new_dict = {} for key in dict...
71,971
def lglob(self: Path, pattern="*"): """Like Path.glob, but returns a list rather than a generator""" return list(self.glob(pattern))
71,972
def test_package_removal_via_check_box_button(driver: selenium.webdriver, *args, **kwargs): """ Test that packages can be removed successfully via check box button. Args: driver """ # Create project r = testutils.prep_py3_minimal_base(driver) username, project_title = r.username, r....
71,973
def simulationStep(step=0): """ Make a simulation step and simulate up to the given second in sim time. If the given value is 0 or absent, exactly one step is performed. Values smaller than or equal to the current sim time result in no action. """ if "" not in _connections: raise FatalTr...
71,974
def transformer_low_resource(configs): """ Configuration for training transformer on low-resource datasets. This is equivalent to configuration of IWSLT'14 De2en in fairseq. """ configs = transformer_base_v2(configs) # model configurations model_configs = configs['model_configs'] model_co...
71,975
def handle_credential_command(command, credentials, target_location='.'): """Function that executes a git command that requires credentials. Parameters ---------- command : str String command to run credentials : list of str The user's entered git remote credentials target_locat...
71,976
def _get_setting(name, default=None): """Get the Sublime setting.""" return sublime.load_settings('Preferences.sublime-settings').get(name, default)
71,977
def status(): """Endpoint to get the current status of the service. This endpoints returns information about the activated functionality and the models used. Returns: A JSON Response containing information about the functionalities (classification and detection) and their current status. ...
71,978
def forward_step(apps, schema_editor): """ Function to remove the duplicate CaseAssignment's that would break the new unique together field """ CaseAssignment = apps.get_model("cases.CaseAssignment") dups = ( CaseAssignment.objects.values("case_id", "user_id", "queue_id") .annotate...
71,979
def vuln_delete_multiid_route(): """delete multiple vulns route""" form = MultiidForm() if form.validate_on_submit(): Vuln.query.filter(Vuln.id.in_([tmp.data for tmp in form.ids.entries])).delete(synchronize_session=False) db.session.commit() db.session.expire_all() return '...
71,980
def save_settings(settings): """ Save settings to yaml file. @param settings: trseeker settings """ file_name = os.path.abspath(__file__) settings_file = os.path.join(os.path.split(file_name)[0], SETTINGS_FILENAME) with open(settings_file, "w") as fh: ...
71,981
def operator_enum_converter(operator: OperatorEnum): """ Function for internal use. Used to translate an OperatorEnum into a string representation of that operator """ if operator == OperatorEnum.Equals: return "==" elif operator == OperatorEnum.GreaterThan: return ">" elif operator == OperatorEnum.GreaterTh...
71,982
def put_using_index_tuple(a, index_tuple, v): """Replaces specified elements of an array with given values. This function is very similar to put(), but takes a tuple of index arrays rather than a single index array. The indexing works like fancy indexing: a[index_tuple] = v Parameters ----...
71,983
def travis_configure(user, project): """Configure travis so that it skips building if there is no .travis.yml present.""" headers = travis_headers() repo_info = travis_get_repo_info(user, project) repo_id = repo_info["id"] if repo_info["active"] is not True: raise ValueError( "...
71,984
def process_batch_sol_rewards_transfer_instructions( session: Session, transfer_instructions: List[RewardTransferInstruction], redis: Redis ): """Validates that the transfer instruction is consistent with DB and inserts ChallengeDisbursement DB entries""" try: eth_recipients = [instr["eth_recipient"...
71,985
def ins_to_dict(ins, option=None): """ Convert instance object to dictionary ex) ins_to_dict(A, { 'cascade': 3, # 如果子项没有cascade,则使用父项-1,如果cascade不大于0,则不对象属性 'recursion_value': '{...}' # 'include': ['a1'], # 只有include中的字段才会返回,不区分值是否是对象,include的优先级>exclude # 'excl...
71,986
def expandFile(filename, no_stdin_warning=False, **kwargs): """Get a filename, expand the text in it and print it. args: (see `processToList`) no_stdin_warning (bool) : If True, print short message on stderr when the program is waiting on input from ...
71,987
def unflatten(flattened: dict) -> dict: """ Unflattens a dictionary :param flattened: Flattened dictionary :return: Unflattened dictionary """ unflattened = {} for key, value in flattened.items(): parts = key.split(".") d = unflattened for part in parts[:-1]: ...
71,988
def interact(): """Basic dumb input mode""" while True: i = input() if i == "quit" or i == 'q': break print(f"hello {i}")
71,989
def install(sig=SIG_DEFAULT, **kwargs): """Installs the PromDump signal handler.""" dump = PromDump(**kwargs) dump.install(sig)
71,990
def col2asset(col, assetPath, scale=30, region=None, create=True, **kwargs): """ Upload all images from one collection to a Earth Engine Asset. You can use the same arguments as the original function ee.batch.export.image.toDrive :param col: Collection to upload :type col: ee.ImageCollection :param...
71,991
def wod_load_index(wod_dir,data_dirs): """ Parse index of WOD cast data in netCDF format. Args: data_dirs: list of strings specifying data directory locations to examine Returns: wod_index: dict with following keys to NumPy arrays of equal length 'filepaths' (comple...
71,992
def train(args, trainer, task, epoch_itr): """Trains the model for one epoch and return validation losses. It is modified to optimize the posterior (selector) and summarizer separately. """ # Initialize data iterator itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=args.fix_batches_t...
71,993
def verify_free_ram(data, n_samples, n_channels, max_prop=0.95): """Check if enough memory is free to run ransac with the given parameters. Parameters ---------- data : np.ndarray 2-D EEG data n_samples : int Number of samples to use for computation of ransac. n_channels : int ...
71,994
def test_scope_nsd_del(namespaceable, namespace): """Test scope del with nesting.""" scopes = {} class Test(namespaceable): """Throwaway test class, for testing scope delete.""" with namespace() as namespace_: with namespace() as namespace_: footer = 1 ...
71,995
def write_to_log_on_success(module, logFileDir): """ Write log data to log file in case of successful operation Args: module (str): module of site being scrapped logFileDir (str): path to log directory """ logData = build_log_data_on_success(module) write_to_file(logFileDir, logDat...
71,996
def upload_notebook(notebook: Path, enable_annotations: bool, enable_discovery: bool, nbss_url: str): """ Upload a notebook file to an nbss instance with """ upload_url = f"{nbss_url.rstrip('/')}/api/v1/notebook" with open(notebook, 'rb') as f: return requests.post( upload_url, ...
71,997
def compat_assert_outcomes(): """ Use RunResult.assert_outcomes() in a way that's consistent across pytest versions. For more info, on how/why this is inconsistent between pytest versions: https://github.com/pytest-dev/pytest/issues/6505 """ def _compat_assert_outcomes(run_result, **kwargs...
71,998
def parse_attrs(attrs): """Parse an attrs sequence/dict to have tuples as keys/items.""" if isinstance(attrs, Sequence): ret = [item.split(".") for item in attrs] else: ret = dict() for key, value in attrs.items(): ret[tuple(key.split("."))] = value return ret
71,999