content
stringlengths
22
815k
id
int64
0
4.91M
def cli_target(): """ Parses the targets configuration. """ pass
64,100
def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')): """ Filter a distribution of logits using top-k and/or nucleus (top-p) filtering Args: logits: logits distribution shape (vocabulary size) top_k > 0: keep only top k tokens with highest probability (to...
64,101
def compute_angular_error(input_: np.array, target_: np.array) -> float: """ Args: input_: N*2 numpy array containing the predicted yaw and pitch angle target_: N*2 numpy array containing the corresponding target_ yaw and pitch angle. Returns: Average angular error (in degree) ""...
64,102
def messages(request): """ need to check user login or not""" if request.POST.get("mode") == "get_messages": data = get_messages(request) return HttpResponse(json.dumps(data)) if request.POST.get("post_message"): data = { "message": request.POST.get("message"), ...
64,103
def from_strings_to_dict(data: Dict[str, str]): """ Makes a model for a given list of string like : "mission.document.name": "test" => { mission: { document: { name: "test" } } } This way we will merge the model with the input in order to ensu...
64,104
def test_certify_dabs_submission(database, monkeypatch): """ Tests the certify_dabs_submission function """ with Flask('test-app').app_context(): now = datetime.datetime.utcnow() sess = database.session user = UserFactory() cgac = CGACFactory(cgac_code='001', agency_name='CGAC A...
64,105
def to_rgb(img): """ Converts the given array into a RGB image. If the number of channels is not 3 the array is tiled such that it has 3 channels. Finally, the values are rescaled to [0,255) :param img: the array to convert [nx, ny, channels] :returns img: the rgb image [nx, ny, 3] ...
64,106
def reset_servicemanager_configuration(): """Reset the network configuration for the Service Manager to listen on and accept connections from the service host address only""" configFileName = os.path.join(get_deployment_directory(['ServiceManager', 'var', 'lib', 'conf']), 'ServiceManager-config.dat') with o...
64,107
def stopwatch(): """Track the running time.""" if not hasattr(stopwatch, "start"): stopwatch.start = datetime.now() return str(datetime.now() - stopwatch.start)[:-7]
64,108
def get_list_probs( mutation_list: List[Tuple[Mutation]], mutate_probs: SequenceProbsList, length_mutations: List[int], ) -> Tuple[List[List[float]], List[List[float]]]: """This function build a list of mutate and native probabilities to compute the mutate_score. For each position in the mutate list...
64,109
def test_read_number(lexer): """Checks read_number""" lexer.i = Stream("123") if 123 != read_number(lexer).value: raise AssertionError lexer.i = Stream("abc") if read_number(lexer) is not None: raise AssertionError
64,110
def decrypt_file(key, in_filename, out_filename): """ Decrypts a file using AES (CBC mode) with the given key. Parameters are similar to encrypt_file, with one difference: out_filename, if not supplied will be in_filename without its last extension (i.e. if in_filename is 'aaa.zip.en...
64,111
def centerOfRect(rect): """ Returns the center of NSRect rect as an NSPoint. """ x = rect.origin.x + rect.size.width * 0.5 y = rect.origin.y + rect.size.height * 0.5 return NSPoint(x,y)
64,112
def gcj02towgs84(coor): """ GCJ02(火星坐标系)转GPS84 :param lng:火星坐标系的经度 :param lat:火星坐标系纬度 :return: """ lng = coor[0] lat = coor[1] if out_of_china(lng, lat): return lng, lat dlat = transformlat(lng - 105.0, lat - 35.0) dlng = transformlng(lng - 105.0, lat - 35.0) radl...
64,113
def encode_data(labeldata,hot_vector = 1): """ Takes array of label data, and transforms it into array of one-hot encoded vectors. Args: labeldata (iterable): Array or list of data labels hot_vector: value assingned for hot, default 1 Returns: n...
64,114
def get_delay(delay_str: Union[str, int]) -> float: """Get the delay from an api call Args: json (List[str]): The delay from the json body Returns: int: The delay in seconds, 0 if no delay was found """ delay = 0 # Already in seconds if isinstance(delay_str, int): ...
64,115
def is_polymorphic(v, on_types=None): """ Tests if a function is polymorphic. If `on_types` is provided, checks to see if a function is generic on the set of provided types. """ if isinstance(v, Function) and v.polymorphic: if on_types is not None: gens = set(on_types) ...
64,116
def main(): """Displays the properties of elements of a body.""" # parse the command-line args = read_inputs() # read the body file with open(args.path, 'r') as infile: n = int(infile.readline()) x, y = np.loadtxt(infile, dtype=float, delimiter='\t', unpack=True) # compute segment-lengths ds = np.append( n...
64,117
def change_password(login, passw=None): """Changes the password of an existing user.""" from ..database import db from .models.auth import auth, User login = unicode(login) user = User.by_login(login) if not user: print('User not found') return if passw is None: pas...
64,118
def get_random_word(min_word_length): """Get a random word from the wordlist using no extra memory.""" num_words_processed = 0 curr_word = None with open(WORDLIST, 'r') as f: for word in f: if '(' in word or ')' in word: continue word = word.strip().lower(...
64,119
def get_copysetup(copytools, copytool_name): """ Return the copysetup for the given copytool. :param copytools: copytools list from infosys. :param copytool name: name of copytool (string). :return: copysetup (string). """ copysetup = "" for ct in copytools.keys(): if copytool_...
64,120
def nurbsSelect(*args, **kwargs): """ Performs selection operations on NURBS objects.If any of the border flags is set, then the appropriate borders are selected. Otherwise the current CV selection is used, or all CVs if the surfaces is selected as an object.The growSelection, shrinkSelection, borderSel...
64,121
def last_occurence_of_tag_chain(sequence, tag_type): """ Takes a sequence of tags. Assuming the first N tags of the sequence are all of the type tag_type, it will return the index of the last such tag in that chain, i.e. N-1 If the first element of the sequence is not of type tag_type, it will return -...
64,122
def tail(count): """Print the last COUNT lines. Roughly equivalent to: tail -n COUNT """ from itertools import islice from collections import deque def tail(lines): if count <= 0: # TODO: don't read in memory, use a temporary file return iter(deque(lines, maxle...
64,123
def supports_parenting(): """Does this Engine support parenting of objects, aka nesting of transforms or attaching objects. This is important when sending transformation values. """ return False
64,124
def dec_to_deg(degree: float, minute: float, second: float) -> float: """ Convert Dec from (deg, arcmin, arcsec) -> degree """ deg_sign = 1. if (degree + np.absolute(degree)) > 0 else - 1. return deg_sign * (np.absolute(degree) + minute / 60. + second / 3600.)
64,125
def sigmoidDerivative(X): """ input : array of features output : Sigmoid derivative of the input """ return stable_sigmoid(X) * (1.0 - stable_sigmoid(X))
64,126
def extract_sub_type(vfm_array): """ Extracts the subtype for each element of the array. Its interpretation depends on whether the feature is an aerosol, cloud, or Polar Stratospheric Cloud. Aerosol: 0 = not determined 1 = clean marine 2 = dust 3 = polluted co...
64,127
def set_enabled_equivalencies(equivalencies): """ Sets the equivalencies enabled in the unit registry. These equivalencies are used if no explicit equivalencies are given, both in unit conversion and in finding equivalent units. This is meant in particular for allowing angles to be dimensionless. ...
64,128
def yieldGuideRelativeDictionary(mesh, guideOrder, relativeGuide_dict): """create a dictionary of guide:[[shape.vtx[int]], relativeMatrix] Args: mesh (string): name of the mesh guideOrder (list): the order to query the guide hierarchy Returns: dictionary: create a dictionary of gui...
64,129
def get_links(source: str, subdir: str) -> List[Tuple[str, str]]: """Returns a list of all symlinks (and the directories they point to) between *source* and *subdir*. """ if not source: return [(subdir, realpath(subdir))] if islink(subdir) else [] links = [(source, realpath(source))] if isl...
64,130
def validate_query(query_str, verbose=True): """ Given a query, ensure it has a year and a denomination and extract them :param query_str: (str), query input from user :return query_params: (tuple) year(str), denomination(str), mint mark(str), str if included, None if not ...
64,131
def test_multisurf_pipeline_parallel(): """Check: Data (Binary Endpoint, Discrete Features): MultiSURF works in a sklearn pipeline when MultiSURF is parallelized""" np.random.seed(320931) clf = make_pipeline(MultiSURF(n_features_to_select=2, n_jobs=-1), RandomForestClassifier(n_esti...
64,132
def tune_clf_binary_grid(X, y_true, clf_name, n_splits_cv=5, refit_score='precision'): """ Tune a classifier using grid search cross validation """ scorers = { 'precision': metrics.make_scorer(metrics.precision_score), 'recall': metrics.make_scorer(metrics.recall_sco...
64,133
def ESMP_GridGetCoordBounds(grid, staggerloc=constants.StaggerLoc.CENTER, localde=0): """ Preconditions: An ESMP_Grid has been created and coordinates have been added via ESMP_GridAddCoord().\n Postconditions: Two numpy arrays containing the grid coordinate ...
64,134
def set_user_stared(oauth_id, uindex): """ 设置用户收藏,保存一年时间 """ key = settings.REDIS_USER_STAR_KEY % (oauth_id, uindex) return R.set(key, '1', 365 * 24 * 3600)
64,135
def isChar(ch): """This function is DEPRECATED. Use xmlIsChar_ch or xmlIsCharQ instead """ ret = libxml2mod.xmlIsChar(ch) return ret
64,136
def scipy_graduate_walk(*args, **kwargs): """Scipy-compatible graduate_walk function wrapper. parameters: args[0]: target, function to be minimized args[1]: x0, starting point for minimization dx=1e-8: step in change of the point dx_start=0.1: starting value for dx step. Must be...
64,137
def extract_sequences(infile, identifiers=None): """Extract sequence(s) from a multi-sequence FASTA file. Parameters ---------- infile : str file path to input multi-sequence FASTA file identifiers : int sequence index (n-th sequence in the file) str ...
64,138
def extract_doc(pdf_path, window_len): """Create a Document with features extracted from a pdf.""" pdf_path = Path(pdf_path) tokens = tokenize_pdf(pdf_path) # Remove tokens shorter than three characters. df = tokens[tokens["token"].str.len() >= 3] df = add_base_features(df) df["tok_id"] = np...
64,139
async def _process_media_source_platform(hass, domain, platform): """Process a media source platform.""" hass.data[DOMAIN][domain] = await platform.async_get_media_source(hass)
64,140
def test_ground_atom_dataset(): """Test creation of demo+ground_atoms dataset.""" utils.reset_config({ "env": "cover", "approach": "interactive_learning", "num_train_tasks": 15, "offline_data_method": "demo+ground_atoms", "teacher_dataset_num_examples": 1, "exclud...
64,141
def get_version(rel_path): """Fetch the version of package by parsing the __init__ file """ for line in read(rel_path).splitlines(): if line.startswith('__version__'): delim = '"' if '"' in line else "'" return line.split(delim)[1] else: raise RuntimeError("Unable...
64,142
async def test_creating_entry_removes_entries_for_same_host_or_bridge(hass): """Test that we clean up entries for same host and bridge. An IP can only hold a single bridge and a single bridge can only be accessible via a single IP. So when we create a new entry, we'll remove all existing entries that e...
64,143
def get_job_class_from_module(user_bp_module): """Returns Job class given a module""" UserJob = None for item in dir(user_bp_module): obj = getattr(user_bp_module, item) if isinstance(obj, (type(Job))): if obj.__bases__[0] == Job: UserJob = obj return UserJo...
64,144
def welford_simulatenous_update(prev_avg, prev_M2, new_value, count): """Perform Welford's simulatenous update on mean and variance M2 = n*sigma_n^2 Parameters ---------- prev_avg: array_like Vector of (count-1)th step averages prev_M2: array_like Vector of (count-1)...
64,145
def magma_sgeqrf_ooc(m, n, A, lda, tau, work, lwork): """ QR factorization (ooc). """ info = ctypes.c_int() status = _libmagma.magma_sgeqrf_ooc(m, n, int(A), lda, int(tau), int(work), lwork, ctypes.byref(info)) mag...
64,146
async def download_file(post_id: int = None, contribuition_id: int = None, database: Session = Depends(get_db)) -> FileResponse: """ Description ----------- Função que permite fazer o download do arquivo de audio da publicação ou da contrib...
64,147
def run(output_dir, data_dict, transform_func): """ Transform mapped data tables into merged dataframes, one df for each target entity type. transform_func must return a dict where keys are names of OMOP SQLAlchemy models: df_out = { 'Person': person_df, 'Speciman': spec...
64,148
def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_d...
64,149
def parse(source: str, eval_: bool = True, globals_=None, locals_=None, ast_module=typed_ast.ast3, *args, **kwargs): """Act like ast_module.parse() but also put static type info into AST.""" if globals_ is None or locals_ is None: frame_info = inspect.getouterframes(inspect.currentframe())[1]...
64,150
def gitCommitId(path, ref): """Return the commit id of *ref* in the git repository at *path*. """ cmd = gitCmdBase(path) + ['show', ref] try: output = runSubprocess(cmd, stderr=None, universal_newlines=True) except sp.CalledProcessError: print(cmd) raise NameError("Unknown gi...
64,151
def cvFree(*args): """cvFree(void ptr)""" return _cv.cvFree(*args)
64,152
def make_constant_schedule(step, cutoff_idx=np.inf): """ step - - - ▖▖▖▖▖▖▖▖▖▖▖▖ 0.0 - - - - - - - - - -▖▖▖▖▖▖ | | 0 cutoff_idx """ def schedule(n): if n >= cutoff_idx: return 0. return step return schedule
64,153
def delete_custom_data(request_ctx, user_id, scope, ns, **request_kwargs): """ Delete custom user data. Arbitrary JSON data can be stored for a User. This API call deletes that data for a given scope. Without a scope, all custom_data is deleted. See `UsersController#set_custom_data <https://g...
64,154
def _pipespawn(argv, env): """ Pipe spawn """ # pylint: disable = R0912 import pickle as _pickle fd, name = mkstemp('.py') try: _os.write(fd, ((r""" import os import pickle import subprocess import sys argv = pickle.loads(%(argv)s) env = pickle.loads(%(env)s) if 'X_JYTHON_WA_PATH' in env: ...
64,155
def test_charge_preservation(): """Unusually charged histidine should be preserved. (See charge parent for normalization).""" eq_(standardize_smiles('[NH3+]C(Cc1cnc[nH]1)C(=O)[O-]'), '[NH3+]C(Cc1cnc[nH]1)C(=O)[O-]')
64,156
def clean_date(date): """ Ensure a date has the correct English format. :param (str) date: date to clean. """ try: dt = datetime.datetime.fromisoformat(date) except ValueError: return '' else: return datetime.datetime.strftime(dt, "%m/%d/%Y")
64,157
def returnCAM(feature_conv, weight_softmax, class_idx): """create cam image""" # generate the class activation maps upsample to 256x256 size_upsample = (256, 256) nc, h, w = feature_conv.shape output_cam = [] for _ in class_idx: cam = weight_softmax[class_idx].dot(feature_conv.reshape((n...
64,158
def to_str(tree, astlib=ast): """Convenient function to get the python source for an AST.""" class Printer(annotate.get_base_visitor(astlib)): """Traverses an AST and generates formatted python source code. This uses the same base visitor as annotating the AST, but instead of eating a token it spits o...
64,159
def _load_config(path: str) -> dict: """Load the JSON formatted config file. Parameters ---------- path : str The path of the JSON file we should load. Return ------ dict The parsed data from the JSON file. """ path = Path(path).expanduser() if not path.exists()...
64,160
def correct_cutoffs(pivot,thresh_dict,cut): """ reduce to zero based on above distributions """ pivot = pivot.transpose() for barcode in list(pivot.columns): pivot[barcode] = cut.apply(lambda row: 0.0 if row[barcode]<thresh_dict[barcode] else pivot.loc[row.name][ba...
64,161
def _add_dummy_encoder(circ): """add a dummy parameterized gate""" para_name = circ.para_name index = 0 while True: name = f'_d_{index}' if name not in para_name: dummy_circ = Circuit().rx(name, 0).no_grad() return dummy_circ + circ, name index += 1
64,162
def main(): """Generate .js files defining Blockly core and language messages.""" # Process command-line arguments. parser = argparse.ArgumentParser(description='Convert JSON files to JS.') parser.add_argument('--source_lang', default='en', help='ISO 639-1 source language code') parser....
64,163
def title(label, style=None): """Sets the title for the current figure. Parameters ---------- label : str The new title for the current figure. style: dict The CSS style to be applied to the figure title """ fig = current_figure() fig.title = label if style is not No...
64,164
def get_target_group_with_type_color_and_workspace(tg_type, color, workspace): """ Récupère un target group ayant un type et une couleur précise :param tg_type: Type recherché :type tg_type: str :param color: Couleur recherché :type color: str :param workspace: Workspace :type work...
64,165
def resource_path(level = 2): """Return a resource path calculated from the caller's stack. """ return get_resource_path(level + 1)
64,166
def create_thread(message: Message): """ Create a new thread for a message """ # Attempt to get a category for the thread try: category = Category.objects.get(addresses__contains=[message.from_email]) except Category.DoesNotExist: category = None # Create and save the thread...
64,167
def split_residue_id(atom): """Takes an atom and splits its het ID into components. :param Atom atom: the atom to read. :rtype: ``tuple``""" if atom.het: id = atom.het.id.split(".")[-1] num = "".join([c for c in id if c.isdigit()]) insert = "".join([c for c in id if c.isalpha()...
64,168
def get_latest_education(education_history: list[Education]) -> Union[Education, HigherEducation, None]: """ Currently we presume that the education history passed in is ordered, we can add in sorting here by attendance date if we need to in the future """ if len(education_history) == 0: ...
64,169
def main(argc, argv): """ ============================================================================ Name: main Description: The main program function. Parameter(s): argc: The number of arguments passed on invocation. argv: A list (tuple) of all supplied arguments...
64,170
def md2pdf( pdf_file_path, md_content=None, md_file_path=None, css_file_path=None, header_content=None, header_file_path=None, footer_content=None, footer_file_path=None, base_url=None, ): """ Converts input markdown to styled HTML and renders it to a PDF file. Args: ...
64,171
def get_model(controller, name): """ List information for model Arguments: name: model name controller: name of controller to work in Returns: Dictionary of model information """ models = get_models(controller)['models'] for m in models: if m['short-name'] == name: ...
64,172
def test_union_structs(): """ Attempt to construct a union between mismatched structs """ @packtype.struct() class StructA: field_a : Scalar(width= 5, desc="Description A") field_b : Scalar(width=10, desc="Description B") field_c : Scalar(width=18, desc="Description C") @packtype...
64,173
def transform_coord(y_coordMat, x_coordMat, rotationCenter, transformVect): """ Transform x-y coordinate (y_mat & x_mat) by transformVect | round to int | return rotated y & x coord as vector""" """ y_mat and x_mat are the coord to be rotated | rotationCenter [y;x] or [y;x;phi] are the centre of rotation by the...
64,174
def pvs(t): """ Saturation vapor pressure as a function of tempetature t [°C] """ import numpy as np T = t + 273.15 # [K] Temperature # pws(T) [Pa] saturation pressure over liquid water # for temp range [0 200] °C eq. (6) C8 = -5.800_220_6e3 C9 = 1.391_499_3e0 C10 = -4.8...
64,175
def heatmap(data, arguments): """ Creates a heatmap """ default = ARGUMENTS.copy() default.update(arguments) arguments = default figure, axes = matplotlib.pyplot.subplots() figure.set_figwidth(arguments['width']) figure.set_figheight(arguments['height']) figure.set_dpi(arguments[...
64,176
def createPresenter(opener: Callable[[], IO[bytes]], fileName: str ) -> Optional[ReportPresenter]: """Attempt to create a custom presenter for the given artifact. Return a resource that handles the presentation, or None if no custom presentation is available or desire...
64,177
def enumerate_bonds(mol): """ A helper function for calling Molecule.enumerate_bonds First, get the Kekulized molecule (get the Kekule version with alternating single and double bonds if the molecule is aromatic), since we don't have implementation for aromatic bond additivity corrections """ mo...
64,178
def _build_link_str(frame_info: Traceback) -> str: """ Build the clickable link string for a frame info object. """ return f'{INDENT}File "{frame_info.filename}", line {frame_info.lineno}, in {frame_info.function}'
64,179
def test_simple_optimizer(): """Tests registration""" pt.optimizers.get("simpleoptimizer")
64,180
def db_nuke(config): """Clear all database contents and drop database itself""" if db_exists(config): kwargs = connection_dict(config) conn = MySQLdb.connect(**kwargs) try: conn.select_db(config.RDBMS_NAME) except: # no, it doesn't exist pass ...
64,181
def save_output_node(out): """ This calcfunction saves the out dict in the db """ out_wc = out.clone() return out_wc
64,182
def inject_spectrum(model, snr=100, dt=1, res=50, planet_params={}): """ Inject the synthetic model into chromatic Rainbow Parameters ---------- model : synthetic_planet Synthetic planet object with wavelength-varying limb-darkening coefficients, as defined in generate_spectrum_ld r_sta...
64,183
def l2_regularizer(scale, name='l2_regularizer'): """Returns a function that can be used to apply L2 regularization to weights. Small values of L2 can help prevent overfitting the training data. Args: scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. name: An optional name/scope name. ...
64,184
def select_edges(networkx_graph, topology, list_of_bonds, list_of_labels): """Select and view edges in the topology.""" plot_networkx_bonds( networkx_graph, list_of_labels=list_of_labels, list_of_bonds=list_of_bonds, ) # The final level prints the parameters of the selected bond ...
64,185
def _same_filter(node1, node2, candidate_list): """ Filter out candidates which do not adhere the same target composition request. """ for candidate in list(candidate_list.keys()): n1_trg = '' n2_trg = '' for src, trg in candidate_list[candidate]: if n1_trg == '' ...
64,186
def TransferImage(pm_id, image_path, vm_filename): """ Copies the Image file to the client machine if host and client are not same. """ client_username = PM_ADDRS[pm_id]['ip'].split('@')[0].strip() # --- Client and Host are same --- # if PM_ADDRS[pm_id]['ip'].strip() == image_path.split(':'...
64,187
def cal_fdp_power(selected, non_zero_index, r_index=False): """ Calculate power and False Discovery Proportion Parameters ---------- selected: list index (in R format) of selected non-null variables non_zero_index: true index of non-null variables r_index : True if the index is taken from rpy2 ...
64,188
def lambda_handler(event, context): """ Checks buckets permissions and sends report. Will be invoked only by AWS Lambda service. :param event: Not used. :param context: Not used. """ import boto3 import botocore globals()['boto3'] = boto3 globals()['botocore'] = botocore glo...
64,189
def _serialize_dictionary_value(value, charset) : """ Serialize dictionary value """ error_code = Error(errOk) if value is None : return error_code, NULL_STRING result = "{" comma = "" for key, child_value in sorted( value.value.items(), key = lambda value: (value[1].order_number, value[0])...
64,190
def _create_types_map(sqltypes): """Take a types module and utilising the `dir` function create a mapping from the string value of that attribute to the SQLAlchemy type instance. """ sql_types_map = { item.lower(): getattr(sqltypes, item) for item in dir(sqltypes) if item[0]....
64,191
def discuss(topic) : """Discuss a topic with the user and return their response. Ask if the user likes the topic and why. Parameters: topic (str): The topic under discussion. Return: str: Response to the question of why they like the topic. """ like = input("Do you like " + to...
64,192
def sigmoid(x): """ sigmoid function :param x: :return: """ return 1.0/(1.0+np.exp(-x))
64,193
def numba_update_portability_matrix( portability_matrix, r_ct_g, c_ct_g, c_f_g, c_cf_g, c_dt_g ): """ updating the probability matrix """ for a, b, c, d, e in zip(r_ct_g, c_ct_g, c_f_g, c_cf_g, c_dt_g): portability_matrix[a, b, c, d, e] = 1 return portability_matrix
64,194
def _sin(t: 'Tensor') -> 'Tensor': """ Also see: --------- :param t: :return: """ data = np.sin(t.data) requires_grad = t.requires_grad if requires_grad: def grad_fn(grad: np.ndarray) -> np.ndarray: return grad * np.cos(t.data) depends_on = [Dependency(...
64,195
def confirm(prompt, default=False): """Give a yes/no prompt with the default letter (y or n) presented as uppercase""" if default: prompt += " [Y/n] " else: prompt += " [y/N] " response = None while response is None: raw_input = input(prompt) if raw_input == "": ...
64,196
def set_cli_logging( logger, verbose, more_verbose, quiet=False, with_time=False): """Set logging for cli scripts. Args: logger: logging.Logger instance verbose: if True, level is set to logging.INFO more_verbose: if True, level is set to logging....
64,197
def test_get_delimited_list(): """get_delimited_list should parse a list of strings""" assert envs.get_delimited_list( name="LIST_DELIMITED", default=["noth", "ing"], description="description" ) == ["x", "y", "z"] assert envs.get_delimited_list( name="LIST_MISSING", default=["noth", "ing...
64,198
def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support treeType - the name of the tree type required (case-insensitive). Supported values are: "dom" - The xml.dom.minidom DOM implementation ...
64,199