text
stringlengths
81
112k
Generate (temporarily) versioneer.py file in project root directory :return: def setup_versioneer(): """ Generate (temporarily) versioneer.py file in project root directory :return: """ try: # assume versioneer.py was generated using "versioneer install" command import versionee...
Python won't realise that new module has appeared in the runtime We need to clean the cache of module finders. Hacking again :return: def clean_cache(): """ Python won't realise that new module has appeared in the runtime We need to clean the cache of module finders. Hacking again :return: ...
Get project version (using versioneer) :return: string containing version def get_version(): """ Get project version (using versioneer) :return: string containing version """ setup_versioneer() clean_cache() import versioneer version = versioneer.get_version() parsed_version = p...
Find the common prefix of two or more paths. :: >>> import pathlib >>> one = pathlib.Path('foo/bar/baz') >>> two = pathlib.Path('foo/quux/biz') >>> three = pathlib.Path('foo/quux/wuux') :: >>> import uqbar.io >>> str(uqbar.io.find_common_prefix([one, two, thre...
r"""Finds executable `name`. Similar to Unix ``which`` command. Returns list of zero or more full paths to `name`. def find_executable(name: str, flags=os.X_OK) -> List[str]: r"""Finds executable `name`. Similar to Unix ``which`` command. Returns list of zero or more full paths to `name`. "...
Generates relative path from ``source_path`` to ``target_path``. Handles the case of paths without a common prefix. :: >>> import pathlib >>> source = pathlib.Path('foo/bar/baz') >>> target = pathlib.Path('foo/quux/biz') :: >>> target.relative_to(source) Tracebac...
Walks a directory tree. Like :py:func:`os.walk` but yielding instances of :py:class:`pathlib.Path` instead of strings. :param root_path: foo :param top_down: bar def walk( root_path: Union[str, pathlib.Path], top_down: bool = True ) -> Generator[ Tuple[pathlib.Path, Sequence[pathlib.Path], Se...
Writes ``contents`` to ``path``. Checks if ``path`` already exists and only write out new contents if the old contents do not match. Creates any intermediate missing directories. :param contents: the file contents to write :param path: the path to write to :param verbose: whether to print out...
Pretty object reference using ``module.path:qual.name`` format def pretty_ref(obj: Any) -> str: """Pretty object reference using ``module.path:qual.name`` format""" try: return obj.__module__ + ':' + obj.__qualname__ except AttributeError: return pretty_ref(type(obj)) + '(...)'
Display repo github path def remote(ctx): """Display repo github path """ with command(): m = RepoManager(ctx.obj['agile']) click.echo(m.github_repo().repo_path)
Get graph-order tuple for node. :: >>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode >>> root_container = UniqueTreeContainer(name="root") >>> outer_container = UniqueTreeContainer(name="outer") >>> inner_container = UniqueTreeContainer(name="...
Send command, wait for response (single or multi lines), test for errors and return the returned code. :param cmd: command to send :param multilines: True - multiline response, False - single line response. :return: command return value. def sendQuery(self, cmd, multilines=False): """ ...
Send command without return value, wait for completion, verify success. :param cmd: command to send def sendQueryVerify(self, cmd): """ Send command without return value, wait for completion, verify success. :param cmd: command to send """ cmd = cmd.strip() self.logger...
Scan all SHIELDHIT12A config files to find external files used and return them. Also change paths in config files to match convention that all resources are symlinked in job_xxxx/symlink def find_external_files(self, run_input_dir): """ Scan all SHIELDHIT12A config files to find externa...
Scan SH12A BEAM file for references to external files and return them def _parse_beam_file(self, file_path, run_input_dir): """Scan SH12A BEAM file for references to external files and return them""" external_files = [] paths_to_replace = [] with open(file_path, 'r') as beam_f: ...
Scan SH12A GEO file for references to external files (like voxelised geometry) and return them def _parse_geo_file(self, file_path, run_input_dir): """Scan SH12A GEO file for references to external files (like voxelised geometry) and return them""" external_files = [] paths_to_replace = [] ...
Scan SH12A MAT file for ICRU+LOADEX pairs and return found ICRU numbers def _parse_mat_file(self, file_path): """Scan SH12A MAT file for ICRU+LOADEX pairs and return found ICRU numbers""" mat_file_sections = self._extract_mat_sections(file_path) return self._analyse_mat_sections(mat_file_sectio...
Cases: - ICRU flag present, LOADDEDX flag missing -> data loaded from some data hardcoded in SH12A binary, no need to load external files - ICRU flag present, LOADDEDX flag present -> data loaded from external files. ICRU number read from ICRU flag, any number following LOADDEDX flag is ...
Find matching file names for given ICRU numbers def _decrypt_icru_files(numbers): """Find matching file names for given ICRU numbers""" import json icru_file = resource_string(__name__, os.path.join('data', 'SH12A_ICRU_table.json')) ref_dict = json.loads(icru_file.decode('ascii')) ...
Rewrite paths in config files to match convention job_xxxx/symlink Requires path to run_xxxx/input/config_file and a list of paths_to_replace def _rewrite_paths_in_file(config_file, paths_to_replace): """ Rewrite paths in config files to match convention job_xxxx/symlink Requires path t...
Check if a given LDAP object exists. def _check_exists(database: Database, table: LdapObjectClass, key: str, value: str): """ Check if a given LDAP object exists. """ try: get_one(table, Q(**{key: value}), database=database) return True except ObjectDoesNotExist: return False
Modify a changes to add an automatically generated uidNumber. def save_account(changes: Changeset, table: LdapObjectClass, database: Database) -> Changeset: """ Modify a changes to add an automatically generated uidNumber. """ d = {} settings = database.settings uid_number = changes.get_value_as_singl...
Replaces instances of switch expression: by for __case in _Switch(n): and replaces case expression: by if __case(expression): and default: by if __case(): def transform_source(text): '''Replaces instances of switch expression: ...
Search for entries in LDAP database. def search(self, base, scope, filterstr='(objectClass=*)', attrlist=None, limit=None) -> Generator[Tuple[str, dict], None, None]: """ Search for entries in LDAP database. """ _debug("search", base, scope, filterstr, attrlist, limit) ...
rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None: """ rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled....
Example shows how to configure environment from scratch def prepare_env(org): """ Example shows how to configure environment from scratch """ # Add services key_service = org.service(type='builtin:cobalt_secure_store', name='Keystore') wf_service = org.service(type='builtin:workflow_service', name='Wo...
Commands for devops operations def start(ctx, debug, version, config): """Commands for devops operations""" ctx.obj = {} ctx.DEBUG = debug if os.path.isfile(config): with open(config) as fp: agile = json.load(fp) else: agile = {} ctx.obj['agile'] = agile if versi...
Duplicate all related objects of obj setting field to value. If one of the duplicate objects has an FK to another duplicate object update that as well. Return the duplicate copy of obj. duplicate_order is a list of models which specify how the duplicate objects are saved. For complex objects ...
Function getPayloadStruct Get the payload structure to do a creation or a modification @param attribute: The data @param objType: SubItem type (e.g: hostgroup for hostgroup_class) @return RETURN: the payload def getPayloadStruct(self, attributes, objType): """ Function getPaylo...
Validate url. def validate_url(value): """ Validate url. """ if not re.match(VIMEO_URL_RE, value) and not re.match(YOUTUBE_URL_RE, value): raise ValidationError('Invalid URL - only Youtube, Vimeo can be used.')
Enters transaction management for a running thread. It must be balanced with the appropriate leave_transaction_management call, since the actual state is managed as a stack. The state and dirty flag are carried over from the surrounding block or from the settings, if there is no surrounding block (dirt...
Leaves transaction management for a running thread. A dirty flag is carried over to the surrounding block, as a commit will commit all changes, even those from outside. (Commits are on connection level.) def leave_transaction_management(using=None): """ Leaves transaction management for a running threa...
Returns True if the current transaction requires a commit for changes to happen. def is_dirty(using=None): """ Returns True if the current transaction requires a commit for changes to happen. """ if using is None: dirty = False for using in tldap.backend.connections: ...
Checks whether the transaction manager is in manual or in auto state. def is_managed(using=None): """ Checks whether the transaction manager is in manual or in auto state. """ if using is None: managed = False for using in tldap.backend.connections: connection = tldap.backen...
Does the commit itself and resets the dirty flag. def commit(using=None): """ Does the commit itself and resets the dirty flag. """ if using is None: for using in tldap.backend.connections: connection = tldap.backend.connections[using] connection.commit() return ...
This function does the rollback itself and resets the dirty flag. def rollback(using=None): """ This function does the rollback itself and resets the dirty flag. """ if using is None: for using in tldap.backend.connections: connection = tldap.backend.connections[using] c...
Takes 3 things, an entering function (what to do to start this block of transaction management), an exiting function (what to do to end it, on both success and failure, and using which can be: None, indiciating transaction should occur on all defined servers, or a callable, indicating that using is None...
This decorator activates commit on response. This way, if the view function runs successfully, a commit is made; if the viewfunc produces an exception, a rollback is made. This is one of the most common ways to do transaction control in Web apps. def commit_on_success(using=None): """ This decorato...
Decorator that activates manual transaction control. It just disables automatic transaction control and doesn't do any commit/rollback of its own -- it's up to the user to call the commit and rollback functions themselves. def commit_manually(using=None): """ Decorator that activates manual transac...
Yields: tuple (line_number: int, offset: int, text: str, check: type) def run(self) -> Generator[Tuple[int, int, str, type], None, None]: """ Yields: tuple (line_number: int, offset: int, text: str, check: type) """ if is_test_file(self.filename): sel...
Reloads glitter URL patterns if page URLs change. Avoids having to restart the server to recreate the glitter URLs being used by Django. def process_request(self, request): """ Reloads glitter URL patterns if page URLs change. Avoids having to restart the server to recreate the glitte...
Execute all current and future payloads Blocks and executes payloads until :py:meth:`stop` is called. It is an error for any orphaned payload to return or raise. def run(self): """ Execute all current and future payloads Blocks and executes payloads until :py:meth:`stop` is ca...
Stop execution of all current and future payloads def stop(self): """Stop execution of all current and future payloads""" if not self.running.wait(0.2): return self._logger.debug('runner disabled: %s', self) with self._lock: self.running.clear() self._sto...
Delimit a string at word boundaries. :: >>> import uqbar.strings >>> list(uqbar.strings.delimit_words("i want to believe")) ['i', 'want', 'to', 'believe'] :: >>> list(uqbar.strings.delimit_words("S3Bucket")) ['S3', 'Bucket'] :: >>> list(uqbar.strings.del...
Normalizes whitespace. Strips leading and trailing blank lines, dedents, and removes trailing whitespace from the result. def normalize(string: str) -> str: """ Normalizes whitespace. Strips leading and trailing blank lines, dedents, and removes trailing whitespace from the result. """ ...
Convert a string to dash-delimited words. :: >>> import uqbar.strings >>> string = 'Tô Đặc Biệt Xe Lửa' >>> print(uqbar.strings.to_dash_case(string)) to-dac-biet-xe-lua :: >>> string = 'alpha.beta.gamma' >>> print(uqbar.strings.to_dash_case(string)) al...
returns a list of all fixers found in the lib2to3 library def get_lib2to3_fixers(): '''returns a list of all fixers found in the lib2to3 library''' fixers = [] fixer_dirname = fixer_dir.__path__[0] for name in sorted(os.listdir(fixer_dirname)): if name.startswith("fix_") and name.endswith(".py"...
return a single fixer found in the lib2to3 library def get_single_fixer(fixname): '''return a single fixer found in the lib2to3 library''' fixer_dirname = fixer_dir.__path__[0] for name in sorted(os.listdir(fixer_dirname)): if (name.startswith("fix_") and name.endswith(".py") and fixna...
Returns field's single value prepared for saving into a database. def to_db(self, value): """ Returns field's single value prepared for saving into a database. """ # ensure value is valid self.validate(value) assert isinstance(value, list) value = list(value) for i, v ...
Converts the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. def to_python(self, value): """ Converts the input value into the expected Python dat...
Validates value and throws ValidationError. Subclasses should override this to provide validation logic. def validate(self, value): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ # check object type ...
Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised. def clean(self, value): """ Convert the value's type and run validation. Validation errors from to_python and validate ...
Returns field's single value prepared for saving into a database. def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ if isinstance(value, six.string_types): value = value.encode("utf_8") return value
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. def value_to_python(self, value): """ Converts the input single value...
Validates value and throws ValidationError. Subclasses should override this to provide validation logic. def value_validate(self, value): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ if not isinstance(va...
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. def value_to_python(self, value): """ Converts the input single value...
Returns field's single value prepared for saving into a database. def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, six.integer_types) return str(value).encode("utf_8")
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. def value_validate(self, value): """ Converts the input single value ...
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. def value_to_python(self, value): """ Converts the input single value...
Returns field's single value prepared for saving into a database. def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, datetime.date) assert not isinstance(value, datetime.datetime) try: value = val...
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. def value_validate(self, value): """ Converts the input single value ...
Returns field's single value prepared for saving into a database. def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, datetime.datetime) try: value = value - datetime.datetime(1970, 1, 1) except Ov...
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. def value_validate(self, value): """ Converts the input single value ...
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. def value_to_python(self, value): """ Converts the input single value...
Returns field's single value prepared for saving into a database. def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, str) array = value.split("-") length = len(array) - 3 assert length >= 0 ...
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. def value_validate(self, value): """ Converts the input single value ...
Get data for this component def get(self, id): """Get data for this component """ id = self.as_id(id) url = '%s/%s' % (self, id) response = self.http.get(url, auth=self.auth) response.raise_for_status() return response.json()
Create a new component def create(self, data): """Create a new component """ response = self.http.post(str(self), json=data, auth=self.auth) response.raise_for_status() return response.json()
Update a component def update(self, id, data): """Update a component """ id = self.as_id(id) response = self.http.patch( '%s/%s' % (self, id), json=data, auth=self.auth ) response.raise_for_status() return response.json()
Delete a component by id def delete(self, id): """Delete a component by id """ id = self.as_id(id) response = self.http.delete( '%s/%s' % (self.api_url, id), auth=self.auth) response.raise_for_status()
Get a list of this github component :param url: full url :param Comp: a :class:`.Component` class :param callback: Optional callback :param limit: Optional number of items to retrieve :param data: additional query data :return: a list of ``Comp`` objects with data def ge...
Return all comments for this issue/pull request def comments(self, issue): """Return all comments for this issue/pull request """ commit = self.as_id(issue) return self.get_list(url='%s/%s/comments' % (self, commit))
Returns a boolean if the user in the request has edit permission for the object. Can also be passed a version object to check if the user has permission to edit a version of the object (if they own it). def has_edit_permission(self, request, obj=None, version=None): """ Returns a boole...
Returns a boolean if the user in the request has publish permission for the object. def has_publish_permission(self, request, obj=None): """ Returns a boolean if the user in the request has publish permission for the object. """ permission_name = '{}.publish_{}'.format(self.opts.app_lab...
Get a valid semantic version for tag def semantic_version(tag): """Get a valid semantic version for tag """ try: version = list(map(int, tag.split('.'))) assert len(version) == 3 return tuple(version) except Exception as exc: raise CommandError( 'Could not pa...
Function load Store the object data def load(self, data): """ Function load Store the object data """ self.clear() self.update(data) self.enhance()
Function enhance Enhance the object with new item or enhanced items def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ if self.objName in ['hosts', 'hostgroups', 'puppet_classes']: from foreman.i...
Function reload Sync the full object def reload(self): """ Function reload Sync the full object """ self.load(self.api.get(self.objName, self.key))
Function getParam Return a dict of parameters or a parameter value @param key: The parameter name @return RETURN: dict of parameters or a parameter value def getParam(self, name=None): """ Function getParam Return a dict of parameters or a parameter value @param key: T...
Function checkAndCreateClasses Check and add puppet class @param classes: The classes ids list @return RETURN: boolean def checkAndCreateClasses(self, classes): """ Function checkAndCreateClasses Check and add puppet class @param classes: The classes ids list @...
Function checkAndCreateParams Check and add global parameters @param key: The parameter name @param params: The params dict @return RETURN: boolean def checkAndCreateParams(self, params): """ Function checkAndCreateParams Check and add global parameters @param ...
Turn a version string into a dict with major/minor/... info. def version_dict(version): """Turn a version string into a dict with major/minor/... info.""" match = version_re.match(str(version) or '') letters = 'alpha pre'.split() numbers = 'major minor1 minor2 minor3 alpha_ver pre_ver'.split() if m...
Get the diff between two records list in this order: - to_create - to_delete def get_diff(source, dest): """Get the diff between two records list in this order: - to_create - to_delete """ # First build a dict from the lists, with the ID as the key. source_dict = {record...
Return a list of form choices for versions of this object which can be published. def object_version_choices(obj): """ Return a list of form choices for versions of this object which can be published. """ choices = BLANK_CHOICE_DASH + [(PublishAction.UNPUBLISH_CHOICE, 'Unpublish current version')] ...
Load a manifest file and apply template values def manifest(self, values, *paths, filename: str = None) -> Dict: """Load a manifest file and apply template values """ filename = filename or self.filename(*paths) with open(filename, 'r') as fp: template = Template(fp.read()) ...
Set packet header. The method will try to set ps_headerprotocol to inform the Xena GUI and tester how to interpret the packet header byte sequence specified with PS_PACKETHEADER. This is mainly for information purposes, and the stream will transmit the packet header bytes even if no pro...
Add modifier. :param m_type: modifier type - standard or extended. :type: xenamanager.xena_stram.ModifierType :return: newly created modifier. :rtype: xenamanager.xena_stream.XenaModifier def add_modifier(self, m_type=XenaModifierType.standard, **kwargs): """ Add modifier. ...
Remove modifier. :param m_type: modifier type - standard or extended. :param index: index of modifier to remove. def remove_modifier(self, index, m_type=XenaModifierType.standard): """ Remove modifier. :param m_type: modifier type - standard or extended. :param index: index of...
:return: dictionary {index: object} of standard modifiers. def modifiers(self): """ :return: dictionary {index: object} of standard modifiers. """ if not self.get_objects_by_type('modifier'): for index in range(int(self.get_attribute('ps_modifiercount'))): Xe...
:return: dictionary {index: object} of extended modifiers. def xmodifiers(self): """ :return: dictionary {index: object} of extended modifiers. """ if not self.get_objects_by_type('xmodifier'): try: for index in range(int(self.get_attribute('ps_modifierextcou...
DRAGONS cosmology assumes WMAP7 + BAO + H_0 mean from Komatsu et al. (2011) ApJS 192 18K (arxiv:1001.4538v1) Parameters ---------- flat: boolean If True, sets omega_lambda_0 = 1 - omega_M_0 to ensure omega_k_0 = 0 exactly. Also sets omega_k_0 = 0 explicitly. extras: boolean If...
Planck 2015 XII: Cosmological parameters Table 4 column Planck TT, TE, EE + lowP + lensing + ext from Ade et al. (2015) A&A in press (arxiv:1502.01589v1) Parameters ---------- flat: boolean If True, sets omega_lambda_0 = 1 - omega_M_0 to ensure omega_k_0 = 0 exactly. Also sets omega_k...
Add a DN to the LDAP database; See ldap module. Doesn't return a result if transactions enabled. def add(self, dn: str, mod_list: dict) -> None: """ Add a DN to the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ return self._do_with...
Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. def modify(self, dn: str, mod_list: dict) -> None: """ Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ return self...
delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. def delete(self, dn: str) -> None: """ delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ return self._do_with_retry(...
rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None: """ rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled....
Get a column for given column name from META api. def get_column_name(self, column_name): """ Get a column for given column name from META api. """ name = pretty_name(column_name) if column_name in self._meta.columns: column_cls = self._meta.columns[column_name] if colum...
Software version of the current repository def version(self): """Software version of the current repository """ branches = self.branches() if self.info['branch'] == branches.sandbox: try: return self.software_version() except Exception as exc: ...
Validate version by checking if it is a valid semantic version and its value is higher than latest github tag def validate_version(self, prefix='v'): """Validate version by checking if it is a valid semantic version and its value is higher than latest github tag """ version = se...
Check if build should be skipped def skip_build(self): """Check if build should be skipped """ skip_msg = self.config.get('skip', '[ci skip]') return ( os.environ.get('CODEBUILD_BUILD_SUCCEEDING') == '0' or self.info['current_tag'] or skip_msg in self...