content
stringlengths
22
815k
id
int64
0
4.91M
def pbar_header(msg_prefix='', msg='', seq=[], char='*'): """Generate a progress bar header for a given iterable or sequence. The given sequence must have a countable length. A bar of `char` characters is printed between square brackets. :param string msg_prefix: Header text to print in heavy green text :p...
5,300,700
def test_spec_config_list_no_out(): """Test creation of SpecConfig model with valid list data in path""" res = SpecConfig(**SPEC_CONFIG_LIST_NO_OUT) assert isinstance(res, SpecConfig) assert res.path_out is not None assert Path(res.path_out).is_absolute()
5,300,701
def CV_ARE_SIZES_EQ(*args): """CV_ARE_SIZES_EQ(CvMat mat1, CvMat mat2) -> int""" return _cv.CV_ARE_SIZES_EQ(*args)
5,300,702
def card_lookup(lrrbot, conn, event, respond_to, search): """ Command: !card card-name Section: misc Show the details of a given Magic: the Gathering card. """ real_card_lookup(lrrbot, conn, event, respond_to, search)
5,300,703
def test_get_serverinfo(): """Test to get all server information. :return: """ am = openam.Openam(openam_url="http://openam.example.com:8080/openam/") am.authenticate(username="amadmin", password="password_openam") data = am.get_serverinfo() am.logout() assert data['selfRegistration'] ==...
5,300,704
def sph2car(theta, phi, radius=1.0): """ Transform the spherical coordinate to cartesian 3D point. :param theta: longitude :type theta: numpy :param phi: latitude :type phi: numpy :param radius: the radius of projection sphere :type radius: float :return: +x right, +y down, +z is fr...
5,300,705
def test_decrypt_1(): """ Test w/ keylength of 1, should be identical to a shift of 1 """ plaintext = "BCDEFGH" key = "B" assert vignere.decrypt(plaintext, key) == "ABCDEFG"
5,300,706
def expand_range_spec( spec: T.Union[int, str], min_value: int, max_value: int ) -> T.Set[int]: """Expands strings of the range specification format to RangingSet objects containing the individual numbers. Any whitespace is ignored. If an int is given instead of a string, a set containing only that ...
5,300,707
def get_tasks_by_project_id(workspace_id: str, project_id: str, api_key_header: Dict) -> Dict: """Get tasks associated with a given project ID and workspace ID. This function returns a dictionary of tasks corresponding to a given project ID and workspace ID. The dictionary has task IDs as ...
5,300,708
def get_files(datadir, filename, format, size): """Get all file (names) with given name, size and format """ import glob dir = check_dir(datadir) pattern = dir + os.sep + filename + '_size=%d*.%s' % (size, format) return glob.glob(pattern)
5,300,709
def insert_db_data_command(): """Insert user and role sample data.""" from slr_label.init_data import insert_users, insert_papers, insert_questions, insert_assignments insert_users(db) click.echo("Inserted the users to database.") insert_papers(db) click.echo("Inserted the papers to database.") ...
5,300,710
def checksum_file(path: str) -> str: """ Gets the checksum of a file Parameters ---------- path : str The path to checksum Returns ------- string Checksum """ message = PrettyStatusPrinter("Getting MD5 hash of " + path).print_start() result = run_piped_comma...
5,300,711
def bool_to_int(bool_value: Optional[bool]) -> Optional[int]: """Cast bool to int value. :param bool_value: some bool value :return: int represenation """ if bool_value is None: return bool_value return int(bool_value)
5,300,712
def create_pool2d(pooling_params, ifm_expr): """Create a relay pooling operation""" assert pooling_params.ifm.layout == "NHWC" params = { "pool_size": (pooling_params.size[0], pooling_params.size[1]), "strides": (pooling_params.strides[0], pooling_params.strides[1]), "padding": [0, 0...
5,300,713
def test_list_no_token(client, session, model): """Only the public model should be listed without a JWT.""" response = client.get("/models") assert response.status_code == 200 assert len(response.json) == 0
5,300,714
def set_log(args): """Set loglevel and format""" loglevel = args.loglevel numeric_level = getattr(logging, loglevel.upper(), None) FORMAT = '[%(asctime)-15s %(name)s:%(levelname)-8s] %(message)s' DATEFMT = '%Y-%m-%d %H:%M:%S' if loglevel in ['debug', 'info', 'warning', 'error', 'critical']: ...
5,300,715
def send_msg(msg: bytes) -> bool: """Send a msg. Returns True on success, False otherwise""" succeed = True try: # 1 second timeout sock = socket.create_connection((c.HOSTNAME, c.PORT), timeout=1) except Exception: return False try: sock.send(msg) sock.recv(1)...
5,300,716
def check_dwd_observations_parameter_set( parameter_set: DWDObservationParameterSet, resolution: DWDObservationResolution, period: DWDObservationPeriod, ) -> bool: """ Function to check for element (alternative name) and if existing return it Differs from foldername e.g. air_temperature -> tu ...
5,300,717
def ensure_virtualenv(three=None, python=None): """Creates a virtualenv, if one doesn't exist.""" if not project.virtualenv_exists: do_create_virtualenv(three=three, python=python) # If --three, --two, or --python were passed... elif (python) or (three is not None): click.echo(crayons....
5,300,718
def _scale_samples(params: np.ndarray, bounds: List): """Rescale samples in 0-to-1 range to arbitrary bounds Parameters ---------- params : numpy.ndarray numpy array of dimensions `num_params`-by-:math:`N`, where :math:`N` is the number of samples bounds : list list of list...
5,300,719
def speed_is_valid(my_car): """Speed is valid.""" assert my_car.speed_validate()
5,300,720
def init_db(): """ Initialize the database.""" db.drop_all() db.create_all() create_customer()
5,300,721
def plt100_5(simulation_path_base, plots_output_path_base=None, plt_name=None, episodes=[900, 902]): """" input : simulation path and outpath output: plot for each exepriment: x-distance of 12 and -1 vs. timestep from 1 test episode """ subfolders = cutils.get_subfolders(simulation_path_base) ve...
5,300,722
def pobj_ident(l, r): """ Check if value of PObject `l` is the same Python Object as value of PObject `r` """ return mkbool(r.hasvalue and l.value is r.value)
5,300,723
def pytest_saltfactories_minion_verify_configuration(request, minion_config, username): """ This hook is called to vefiry the provided minion configuration """ # verify env to make sure all required directories are created and have the # right permissions verify_env_entries = [ os.path.j...
5,300,724
def test_digit_required_messages(dummy_form, dummy_field, validator, message): """ It should raise ValidationError for string with incorect digit_required. """ dummy_field.data = "FOObar" with pytest.raises(ValidationError) as e: validator(dummy_form, dummy_field) assert str(e.value...
5,300,725
def _task_callback(task): """Print task status. :param task: XML representation of a task resource :type task: lxml.objectify.ObjectifiedElement """ message = '{0}: {1}, status: {2}'.format( task.get('operationName'), task.get('operation'), task.get('status')) if hasattr(task, 'Progress...
5,300,726
def arghash(args: Any, kwargs: Any) -> int: """Simple argument hash with kwargs sorted.""" sorted_args = tuple( x if hasattr(x, "__repr__") else x for x in [*args, *sorted(kwargs.items())] ) return hash(sorted_args)
5,300,727
def visualize_accuracy_grouped_by_probability(y_test: np.ndarray, labeled_class: Union[str, int], probabilities: np.ndarray, threshold: float = 0.5, display_breakdown: bool = False, ...
5,300,728
def _applyReplacements(cfile, replacements): """Applies custom replacements. Argument cfile is string. Argument replacements is a list of dicts, with keys "match", "replacement", and (optional) "is_regex" """ for rep in replacements: if not rep.get('with_extension', False): ...
5,300,729
def run_workflow_stddft(config: DictConfig) -> PromisedObject: """Compute the excited states using simplified TDDFT using `config`.""" # Single Point calculations settings using CP2K mo_paths_hdf5, energy_paths_hdf5 = unpack(calculate_mos(config), 2) # Read structures molecules_au = [change_mol_uni...
5,300,730
def dosim( inputfile, simname='', perfect=False, simargs='', verbose=False ): """ Run the snana light curve simulator with the given .input file """ SNANA_DIR = os.environ['SNANA_DIR'] SNDATA_ROOT = os.environ['SNDATA_ROOT'] simdir = os.path.abspath( os.path.join( SNDATA_ROOT, 'SIM') ) if not ...
5,300,731
def log_exception(ex, domain, config): """Generate log exception for config validation.""" message = 'Invalid config for [{}]: '.format(domain) if 'extra keys not allowed' in ex.error_message: message += '[{}] is an invalid option for [{}]. Check: {}->{}.'\ .format(ex.path[-1], d...
5,300,732
def time_trials_bigQ( ): """ Compare the speed of the random partitioning functions developed in Locey and McGlinn (2013), for cases when zero values are and are not allowed. The code generates figure ? of the Appendix from Locey and McGlinn (2013) """ fig = plt.figure() sample_size=1...
5,300,733
def build_resnet_fpn_gnbn_lowlevel_cbp10_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ bottom_up = build_resnet_gnbn_lowlevel_model_backbone(cfg, input_shape, gra...
5,300,734
def run_batch_test(request): """ 批量运行用例 :param request: :return: """ kwargs = { "failfast": False, } runner = HttpRunner(**kwargs) test_case_dir_path = os.path.join(os.getcwd(), "suite") test_case_dir_path = os.path.join(test_case_dir_path, get_time_stamp()) if req...
5,300,735
def load_db(fname, binp=True, keys=None ): """ Submodule to read the station database from file Parameters ---------- fname : str File name binp : bool Whether or not to use binary input keys : List Default None If a list, then load database and select only k...
5,300,736
def _get_pcluster_version_from_stack(stack): """ Get the version of the stack if tagged. :param stack: stack object :return: version or empty string """ return next((tag.get("Value") for tag in stack.get("Tags") if tag.get("Key") == "Version"), "")
5,300,737
def start_bottle_skill(skill_name: str = None): """Download the latest skill template""" skill_name = input("Skill name: ") if not skill_name else skill_name skill_dirrectory = input(f"Skill directory ({skill_name}): ") if not skill_dirrectory: skill_dirrectory = skill_name print("Downloadin...
5,300,738
def condor_object(net): """Initialization of the condor object. The function gets a network in edgelist format encoded in a pandas dataframe. Returns a dictionary with an igraph network, names of the targets and regulators, list of edges, modularity, and vertex memberships. """ t = time.time() ...
5,300,739
def test_load_user_from_request_with_non_existing_api_key(client): """ Test authentication with a non existing api key. """ with client as cl: res = cl.get('/test_authentication', headers={'Authorization': b64encode(b'invalid')}) assert res.status_code == 401
5,300,740
def RunNinjaCommand(args, root_dir=None): """Runs ninja quietly. Any failure (e.g. clang not found) is silently discarded, since this is unlikely an error in submitted CL.""" command = [os.path.join(find_depot_tools.DEPOT_TOOLS_PATH, 'ninja')] + args p = subprocess.Popen(command, cwd=r...
5,300,741
def extract(spark, source): """Return an RDD[String].""" rdd = spark.sparkContext.textFile(source) return rdd.map(lambda x: json.loads(x))
5,300,742
def initKML(widthLength = "10"): """ Initializes KML tree and makes the """ global ET global KMLTag global Document global widthText widthText = widthLength from lxml import etree as ET KMLTag = ET.Element("kml") KMLTag.set("xmlns", "http://www.opengis.net/kml/2.2") Do...
5,300,743
def folder(ctx): """folder sub commands Manage EVE-NG folders """ global client client = ctx.obj.client
5,300,744
def _remove_leading_zeroes_in_field(string): """If blank-separated fields are integer, remove the leading zero.""" split = string.split(" ") for i, field in enumerate(split): if field.isdigit(): split[i] = f"{int(field)}" return " ".join(split)
5,300,745
def pstdev(data): """Calculates the population standard deviation.""" #: http://stackoverflow.com/a/27758326 n = len(data) if n < 2: raise ValueError('variance requires at least two data points') ss = _ss(data) pvar = ss/n # the population variance return pvar**0.5
5,300,746
def make_sharded_index(index_prefix: str, release_date: Date) -> str: """Make a sharded Elasticsearch index given an index prefix and a date. :param index_prefix: the index prefix. :param release_date: the date. :return: the sharded index. """ return f'{index_prefix}-{release_date.strftime("%Y...
5,300,747
def optimise_acqu_func_additive(acqu_func, bounds, X_ob, func_gradient=True, gridSize=5000, n_start=1, nsubspace=12): """ Optimise acquisition function built on ADDGP model :param acqu_func: acquisition function :param bounds: input space bounds :param X_ob: observed input data :param func_grad...
5,300,748
def kmp(pattern, text): """Knuth-Morris-Pratt substring matching""" pattern_length = len(pattern) matched, subpattern = 0, [0] * pattern_length for i, glyph in enumerate(pattern): if i: while matched and (pattern[matched] != glyph): matched = subpattern[matched - 1] ...
5,300,749
def collect_files(data_dir, specific_issue_date,csv_importer_impl=CsvImporter): """Fetch path and data profile details for each file to upload.""" logger= get_structured_logger('collect_files') if specific_issue_date: results = list(csv_importer_impl.find_issue_specific_csv_files(data_dir)) else: result...
5,300,750
def ssl_valid_time_remaining(hostname): """Get the number of days left in a cert's lifetime.""" expires = ssl_expiry_datetime(hostname) return expires - datetime.datetime.utcnow()
5,300,751
def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT ret...
5,300,752
def make_dataset(name, args): """ Creates the dataset with the given name. Parameters ---------- name: the name of the dataset to create. args: hyper-paremeters for the dataset. Returns ------- dataset_fn: a function which creates the specified dataset. """ if name not in _data...
5,300,753
def create_df(client, candles): """ Создаеv датафрейм для списка свечей :param dict candles: List of candles from API :return: DataFrame with candles """ df = DataFrame([{ 'time': c.time, 'volume': c.volume, 'open': cast_money(client, c.open), 'cl...
5,300,754
def current_user(request, user_id=None): """Return the list of all the users with their ids. """ print("TODO Take time and refact this s...") session = request.dbsession if user_id is not None: userid = user_id else: userid = int(request.authenticated_userid['iss']) TI...
5,300,755
def test_list_duration_max_length_4_nistxml_sv_iv_list_duration_max_length_5_2(mode, save_output, output_format): """ Type list/duration is restricted by facet maxLength with value 10. """ assert_bindings( schema="nistData/list/duration/Schema+Instance/NISTSchema-SV-IV-list-duration-maxLength-5....
5,300,756
def istext(obj): """ Deprecated. Use:: >>> isinstance(obj, str) after this import: >>> from future.builtins import str """ return isinstance(obj, type(u''))
5,300,757
def create_text_authors_citations_from_json(database, directory): """ Function that gathers all calls to specialized create() functions, in order to create the entirety of the graph. """ dirpath = join(directory, 'dataset') current_system = platform.system() # Read plaintext from files, whi...
5,300,758
def track_to_p_matrix(track, char_map=CHAR_MAP, x_vel_limits=None, y_vel_limits=None, x_accel_limits=None, y_accel_limits=None, max_total_accel=np.inf): """ Converts a map described by a list of strings to P-matrix format for an OpenAI Gym Discrete environment. Maps are specified usin...
5,300,759
def crc16(string, value=0): """CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 @param string: Data over which to calculate crc. @param value: Initial CRC value. """ crc16_table = [] for byte in range(256): crc = 0 for _ in range(8): if (byte ^ crc) & 1: ...
5,300,760
def get_fpn_featureMaps(features,num_filt=256): """ features: list of different maps produced by a backbone **Resnet50** : for resnet50 it contains all the 5 feature maps from each block Return: list of pyramid features """ C1,C2,C3,C4,C5 = features C5d1 = keras.layers.Conv2D(num_filt,(...
5,300,761
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version ...
5,300,762
def chng_service_welcome_status_by_id(obj_mongo_coll, int_uid, int_val): """Replaces welcome message service status for a specific user Parameters ---------- obj_mongo_coll : MongoDB collection object Mongo collection for which to add empty collection int_uid : int user id int_v...
5,300,763
def Interface_Static_Standards(*args): """ * Initializes all standard static parameters, which can be used by every function. statics specific of a norm or a function must be defined around it :rtype: void """ return _Interface.Interface_Static_Standards(*args)
5,300,764
def batch_inputs(input_records: Sequence[Dict[K, V]]) -> Dict[K, List[V]]: """Batch inputs from list-of-dicts to dict-of-lists.""" assert input_records, 'Must have non-empty batch!' ret = {} for k in input_records[0]: ret[k] = [r[k] for r in input_records] return ret
5,300,765
def chunks(seq, size): """Breaks a sequence of bytes into chunks of provided size :param seq: sequence of bytes :param size: chunk size :return: generator that yields tuples of sequence chunk and boolean that indicates if chunk is the last one """ length = len(seq) return ((seq...
5,300,766
def create_ospf_interface(vrf, ospf_id, area_id, interface_name, **kwargs): """ Perform POST calls to attach an interface to an OSPF area. :param vrf: Alphanumeric name of the VRF the OSPF ID belongs to :param ospf_id: OSPF process ID between numbers 1-63 :param area_id: Unique identifier as a strin...
5,300,767
def compare( left, right, left_label="left", right_label="right", drop_close=True, **kwargs ): """Compare the data in two IamDataFrames and return a pandas.DataFrame Parameters ---------- left, right : IamDataFrames two :class:`IamDataFrame` instances to be compared left_label, right_la...
5,300,768
def locate_package_directory(): """Identify a directory of the package and its associated files.""" try: return path.abspath(path.dirname(__file__)) except Exception as path_error: message = ('The directory in which the package and its ' 'associated files are stored could ...
5,300,769
def add_default_decks(username): """ The initial decks for a new player. """ save_new_to_decks_database(username, default_deck()) # save_new_to_decks_database(username, default_deck_vampire_lich()) # save_new_to_decks_database(username, default_deck_genie_wizard()) # save_new_to_decks_da...
5,300,770
async def test_quickmode_system_off_mode_hvac_off(hass): """Test with quick mode off.""" await _test_mode_hvac( hass, QuickModes.SYSTEM_OFF, "IDLE", HVAC_MODE_OFF, Room.MIN_TARGET_TEMP, PRESET_SYSTEM_OFF, CURRENT_HVAC_IDLE, )
5,300,771
def combine_shuffle(parcellation, scale, spatnull, alpha): """ Combines outputs of all simulations into single files for provided inputs Parameters ---------- parcellation : str Name of parcellation to be used scale : str Scale of `parcellation` to be used spatnull : str ...
5,300,772
def tcycle(iterable, n): """ >>> tcycle([1, 2, 3], 2) (1, 2) >>> tcycle([1, 2, 3], 4) (1, 2, 3, 1) """ return tuple(islice(cycle(iterable), n))
5,300,773
def compute_best_permutation(x: List, y: List, sim: Callable[[Any, Any], Union[bool, int, float]], agg: Callable[[List], float]) -> \ Tuple[float, Tuple]: """Computes similarity for all possible pairings of `x` and `permu...
5,300,774
def change_box_order(boxes, order): """Change box order between (xmin,ymin,xmax,ymax) and (xcenter,ycenter,width,height). Args: boxes: (tensor) bounding boxes, sized [N,4]. order: (str) either 'xyxy2xywh' or 'xywh2xyxy'. Returns: (tensor) converted bounding boxes, sized [N,4]. """ ...
5,300,775
def register_model( origin_model, dataset: str, metric: Dict[Metric, float], task: Task, inputs: List[IOShape], outputs: List[IOShape], model_input: Optional[List] = None, architecture: str = None, framework: Framework = None, engine: Engin...
5,300,776
def GetLidarSimulation(environment,position,orientation): """ This function simulates the operation of the LIDAR by returning a list with the polar coordinates of the location of the obstacles environment -> List with all objects that are in the circuit as well as the edges of the circuit posi...
5,300,777
def For_range(t, x): """Special conversion for ``for name in range(n)``, which detects ``range()`` calls and converts the statement to: .. code:: javascript for (var name = 0, bound = bound; name < bound; name++) { // ... } """ if (isinstance(x.target, ast.Name) and ...
5,300,778
def test_recursive_uninstall(mutable_database): """Test recursive uninstall.""" uninstall('-y', '-a', '--dependents', 'callpath') all_specs = spack.store.layout.all_specs() assert len(all_specs) == 9 # query specs with multiple configurations mpileaks_specs = [s for s in all_specs if s.satisfie...
5,300,779
def calculate_G3( n_numbers, neighborsymbols, neighborpositions, G_elements, gamma, zeta, eta, cutoff, cutofffxn, Ri, normalized=True, image_molecule=None, n_indices=None, weighted=False, ): """Calculate G3 symmetry function. These are 3 body or angular i...
5,300,780
def evaluate( ckpt: str, dataset_file: str, error_analysis_fname: str, classification_metrics_fname: str, ) -> None: """ Evaluate model checkpoint on given dataset. Perform postprocessig of predictions to match initial tokenization :param ckpt: path to model checkpoint :param data...
5,300,781
def decimals(): """Generates instances of decimals.Decimal.""" return ( floats().map(float_to_decimal) | fractions().map( lambda f: Decimal(f.numerator) / f.denominator ) )
5,300,782
def main(): """Create the model and start the training.""" parser = get_arguments() print(parser) with Engine(custom_parser=parser) as engine: args = parser.parse_args() if args.num_gpus > 1: torch.cuda.set_device(args.local_rank) writer = SummaryWriter(args.snapsho...
5,300,783
def is_index(obj): """Verifies whether an object is a table index.""" return isinstance(obj, _supported_types().index_types)
5,300,784
def stack_controls(controls: list[dict], key: str = "tau"): """ Stack the controls in one vector Parameters ---------- controls : list[dict] List of dictionaries containing the controls key : str Key of the controls to stack such as "tau" or "qddot" """ the_tuple = (c[ke...
5,300,785
def checkIndexSpaceNotTooBig(): """ Check if index space is of correct size """ pass
5,300,786
def siggen_app( filename, args, rate, ampl=0.7, freq=None, tx_bw=None, tx_chan=0, tx_gain=None, tx_ant=None, clock_rate=None, wave_freq=None ): """Generate signal until an interrupt signal is received.""" if wave_freq is No...
5,300,787
def secondYAxis(requestContext, seriesList): """ Graph the series on the secondary Y axis. """ for series in seriesList: series.options['secondYAxis'] = True series.name= 'secondYAxis(%s)' % series.name return seriesList
5,300,788
def _next_incompatible_version(version): """ Find the next non-compatible version. This is for use with the ~= compatible syntax. It will provide the first version that this version must be less than in order to be compatible. :param str version: PEP 440 compliant version number :return: T...
5,300,789
def SNR_tot(G, BP, RP, J, H, K, lum, mass, teff, rad, numax, s=1., deltaT=1550, Amax_sun=2.5, obs='kepler-sc', D=1): """ predicted S/N for a given set of parameters INPUT: mag - relevant magnitude e.g. V or Kp for kepler... lum - luminosity in Lsun mass - stellar mass in Msun ...
5,300,790
def checkFormat(DATAFIL): """ check the file format """ # Open file, read first 4 bytes as string f = open(DATAFIL, 'rb') dataBytes = np.fromfile(f, dtype=np.uint8, count=4) data = "".join(map(chr, dataBytes)) f.close() # If string matches a particular format, return format if d...
5,300,791
def parse_csv(csv_path, ftype='csv', dt_col="date_time", dt_format="%Y%m%d %H:%M:%S", dni_col='DNI', dhi_col='DHI', stime=None, etime=None): """Parse a csv file containing direct normal and diffuse horizontal data, ignoring NULL and zero values. Parameters: csv_path:...
5,300,792
def _make_bundles(operations, size=None): """Utility function for the generation of bundles. This function splits an iterable of operations into equally sized bundles and a possibly smaller final bundle. """ n = None if size == 0 else size operations = iter(operations) while True: b...
5,300,793
def has_surr_char(string): """ Returns True if the given string contains any 'surround' characters, False otherwise. These characters many cause bugs in programs if used. """ re1 = re.compile(INVALID_CHARACTERS) if re1.search(string): return True else: return False
5,300,794
def CreateChrootSnapshot(snapshot_name, chroot_vg, chroot_lv): """Create a snapshot for the specified chroot VG/LV. Args: snapshot_name: The name of the new snapshot. chroot_vg: The name of the VG containing the origin LV. chroot_lv: The name of the origin LV. Returns: True if the snapshot was c...
5,300,795
def decode_u256(as_bytes: typing.List[int]) -> int: """Decodes an unsigned 256 bit integer. """ size = as_bytes[0] if size <= NUMERIC_CONSTRAINTS[CLTypeKey.U8].LENGTH: return decode_u8(as_bytes[1:]) elif size <= NUMERIC_CONSTRAINTS[CLTypeKey.U32].LENGTH: return decode_u32(as_byt...
5,300,796
def test_insert_rows(): """ Institution.ingest_world() should load rows. """ Institution.ingest_world( 'osp.test.institutions.models.institution', 'fixtures/ingest_world/insert_rows.csv', ) assert Institution.select().count() == 3 for i in map(str, [1, 2, 3]): as...
5,300,797
def test_all(): """Test pypatterns import""" expected = [ 'singleton', 'logging', 'prototype', 'rts', ] assert __all__ == expected
5,300,798
def import_image( dbsession, account: str, operation_id: str, import_manifest: ImportManifest, force: bool = False, annotations: dict = None, ) -> dict: """ Process the image import finalization, creating the new 'image' record and setting the proper state for queueing :param dbsess...
5,300,799