sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def patch_env(env, path, value): """ Set specified value to yaml path. Example: patch('application/components/child/configuration/__locator.application-id','777') Will change child app ID to 777 """ def pathGet(dictionary, path): for item in path.split("/"): ...
Set specified value to yaml path. Example: patch('application/components/child/configuration/__locator.application-id','777') Will change child app ID to 777
entailment
def get_starter_kit_meta(name): """ Extract metadata link for starter kit from platform configs. Starter kit available on add component - starter kit menu. Beware, config could be changed by deploy scripts during deploy. :param name: Name of starter kit :return: Link to metadata """ kits = y...
Extract metadata link for starter kit from platform configs. Starter kit available on add component - starter kit menu. Beware, config could be changed by deploy scripts during deploy. :param name: Name of starter kit :return: Link to metadata
entailment
def get_manifest_from_meta(metaurl, name): """ Extact manifest url from metadata url :param metaurl: Url to metadata :param name: Name of application to extract :return: """ if 'http' in metaurl: kit = yaml.safe_load(requests.get(url=metaurl).content)['kit']['applications'] else:...
Extact manifest url from metadata url :param metaurl: Url to metadata :param name: Name of application to extract :return:
entailment
def getPayloadStruct(self, attributes, objType=None): """ Function getPayloadStruct Get the payload structure to do a creation or a modification @param key: The key to modify @param attribute: The data @param objType: NOT USED in this class @return RETURN: The API result...
Function getPayloadStruct Get the payload structure to do a creation or a modification @param key: The key to modify @param attribute: The data @param objType: NOT USED in this class @return RETURN: The API result
entailment
def log(function): """ Function log Decorator to log lasts request before sending a new one @return RETURN: None """ def _log(self, *args, **kwargs): ret = function(self, *args, **kwargs) if len(self.history) > self.maxHistory: self.histor...
Function log Decorator to log lasts request before sending a new one @return RETURN: None
entailment
def clearReqVars(self): """ Function clearHistVars Clear the variables used to get history of all vars @return RETURN: None """ self.errorMsg = None self.payload = None self.url = None self.resp = None self.res = None self.method = None ...
Function clearHistVars Clear the variables used to get history of all vars @return RETURN: None
entailment
def list(self, obj, filter=False, only_id=False, limit=20): """ Function list Get the list of an object @param obj: object name ('hosts', 'puppetclasses'...) @param filter: filter for objects @param only_id: boolean to only return dict with name/id @return RETURN: the li...
Function list Get the list of an object @param obj: object name ('hosts', 'puppetclasses'...) @param filter: filter for objects @param only_id: boolean to only return dict with name/id @return RETURN: the list of the object
entailment
def get(self, obj, id, sub_object=None): """ Function get Get an object by id @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @return RETURN: the targeted object """ self.url = '{}{}/{}'.format(self.base_url, obj...
Function get Get an object by id @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @return RETURN: the targeted object
entailment
def get_id_by_name(self, obj, name): """ Function get_id_by_name Get the id of an object @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @return RETURN: the targeted object """ list = self.list(obj, filter='name ...
Function get_id_by_name Get the id of an object @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @return RETURN: the targeted object
entailment
def set(self, obj, id, payload, action='', async=False): """ Function set Set an object by id @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @param action: specific action of an object ('power'...) @param payload: the d...
Function set Set an object by id @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @param action: specific action of an object ('power'...) @param payload: the dict of the payload @param async: should this request be async...
entailment
def create(self, obj, payload, async=False): """ Function create Create an new object @param obj: object name ('hosts', 'puppetclasses'...) @param payload: the dict of the payload @param async: should this request be async, if true use return.result() to ...
Function create Create an new object @param obj: object name ('hosts', 'puppetclasses'...) @param payload: the dict of the payload @param async: should this request be async, if true use return.result() to get the response @return RETURN: the server respo...
entailment
def delete(self, obj, id): """ Function delete Delete an object by id @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @return RETURN: the server response """ self.url = '{}{}/{}'.format(self.base_url, obj, id) ...
Function delete Delete an object by id @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @return RETURN: the server response
entailment
def run(self): """Modified ``run`` that captures return value and exceptions from ``target``""" try: if self._target: return_value = self._target(*self._args, **self._kwargs) if return_value is not None: self._exception = OrphanedReturn(sel...
Modified ``run`` that captures return value and exceptions from ``target``
entailment
def _start_payloads(self): """Start all queued payloads""" with self._lock: payloads = self._payloads.copy() self._payloads.clear() for subroutine in payloads: thread = CapturingThread(target=subroutine) thread.start() self._threads.add...
Start all queued payloads
entailment
def _reap_payloads(self): """Clean up all finished payloads""" for thread in self._threads.copy(): # CapturingThread.join will throw if thread.join(timeout=0): self._threads.remove(thread) self._logger.debug('reaped thread %s', thread)
Clean up all finished payloads
entailment
def update_cache(func): """Decorate functions that modify the internally stored usernotes JSON. Ensures that updates are mirrored onto reddit. Arguments: func: the function being decorated """ @wraps(func) def wrapper(self, *args, **kwargs): """The wrapper function.""" ...
Decorate functions that modify the internally stored usernotes JSON. Ensures that updates are mirrored onto reddit. Arguments: func: the function being decorated
entailment
def s(cls: Type[C], *args, **kwargs) -> Partial[C]: """ Create an unbound prototype of this class, partially applying arguments .. code:: python controller = Controller.s(interval=20) pipeline = controller(rate=10) >> pool """ return Partial(cls, *args,...
Create an unbound prototype of this class, partially applying arguments .. code:: python controller = Controller.s(interval=20) pipeline = controller(rate=10) >> pool
entailment
def _build_mappings( self, classes: Sequence[type] ) -> Tuple[Mapping[type, Sequence[type]], Mapping[type, Sequence[type]]]: """ Collect all bases and organize into parent/child mappings. """ parents_to_children: MutableMapping[type, Set[type]] = {} children_to_parent...
Collect all bases and organize into parent/child mappings.
entailment
def _collect_classes( self, package_paths: Sequence[str], recurse_subpackages: bool = True ) -> Sequence[type]: """ Collect all classes defined in/under ``package_paths``. """ import uqbar.apis classes = [] initial_source_paths: Set[str] = set() # Gra...
Collect all classes defined in/under ``package_paths``.
entailment
def get_auth(): """Return a tuple for authenticating a user If not successful raise ``AgileError``. """ auth = get_auth_from_env() if auth[0] and auth[1]: return auth home = os.path.expanduser("~") config = os.path.join(home, '.gitconfig') if not os.path.isfile(config): ...
Return a tuple for authenticating a user If not successful raise ``AgileError``.
entailment
def checkAndCreate(self, key, payload, osIds): """ Function checkAndCreate Check if an architectures exists and create it if not @param key: The targeted architectures @param payload: The targeted architectures description @param osIds: The list of os ids liked with this archite...
Function checkAndCreate Check if an architectures exists and create it if not @param key: The targeted architectures @param payload: The targeted architectures description @param osIds: The list of os ids liked with this architecture @return RETURN: The id of the object
entailment
def pip_command_output(pip_args): """ Get output (as a string) from pip command :param pip_args: list o pip switches to pass :return: string with results """ import sys import pip from io import StringIO # as pip will write to stdout we use some nasty hacks # to substitute system...
Get output (as a string) from pip command :param pip_args: list o pip switches to pass :return: string with results
entailment
def setup_versioneer(): """ Generate (temporarily) versioneer.py file in project root directory :return: """ try: # assume versioneer.py was generated using "versioneer install" command import versioneer versioneer.get_version() except ImportError: # it looks vers...
Generate (temporarily) versioneer.py file in project root directory :return:
entailment
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: """ import importlib try: # Python ver < 3.3 vermod = importlib.import_module("versioneer") globals()["versioneer"] = ...
Python won't realise that new module has appeared in the runtime We need to clean the cache of module finders. Hacking again :return:
entailment
def get_version(): """ Get project version (using versioneer) :return: string containing version """ setup_versioneer() clean_cache() import versioneer version = versioneer.get_version() parsed_version = parse_version(version) if '*@' in str(parsed_version): import time ...
Get project version (using versioneer) :return: string containing version
entailment
def find_common_prefix( paths: Sequence[Union[str, pathlib.Path]] ) -> Optional[pathlib.Path]: """ 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('f...
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...
entailment
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`. """ result = [] extensions = [x for x in os.environ.get("PATHEXT", "").split(os.pathsep) if x] path = os.environ.ge...
r"""Finds executable `name`. Similar to Unix ``which`` command. Returns list of zero or more full paths to `name`.
entailment
def relative_to( source_path: Union[str, pathlib.Path], target_path: Union[str, pathlib.Path] ) -> pathlib.Path: """ Generates relative path from ``source_path`` to ``target_path``. Handles the case of paths without a common prefix. :: >>> import pathlib >>> source = pathlib.Path(...
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...
entailment
def walk( root_path: Union[str, pathlib.Path], top_down: bool = True ) -> Generator[ Tuple[pathlib.Path, Sequence[pathlib.Path], Sequence[pathlib.Path]], None, None ]: """ Walks a directory tree. Like :py:func:`os.walk` but yielding instances of :py:class:`pathlib.Path` instead of strings. ...
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
entailment
def write( contents: str, path: Union[str, pathlib.Path], verbose: bool = False, logger_func=None, ) -> bool: """ 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 di...
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...
entailment
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)) + '(...)'
Pretty object reference using ``module.path:qual.name`` format
entailment
def remote(ctx): """Display repo github path """ with command(): m = RepoManager(ctx.obj['agile']) click.echo(m.github_repo().repo_path)
Display repo github path
entailment
def graph_order(self): """ Get graph-order tuple for node. :: >>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode >>> root_container = UniqueTreeContainer(name="root") >>> outer_container = UniqueTreeContainer(name="outer") >>> i...
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="...
entailment
def sendQuery(self, cmd, multilines=False): """ 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. ...
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.
entailment
def sendQueryVerify(self, cmd): """ Send command without return value, wait for completion, verify success. :param cmd: command to send """ cmd = cmd.strip() self.logger.debug("sendQueryVerify(%s)", cmd) if not self.is_connected(): raise socket.error("sendQue...
Send command without return value, wait for completion, verify success. :param cmd: command to send
entailment
def find_external_files(self, run_input_dir): """ 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 """ beam_file, geo_file, mat_file, ...
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
entailment
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: for line in beam_f.readlines(): split_line = line.s...
Scan SH12A BEAM file for references to external files and return them
entailment
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 = [] with open(file_path, 'r') as geo_f: for line in geo_f.readlines(): ...
Scan SH12A GEO file for references to external files (like voxelised geometry) and return them
entailment
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_sections)
Scan SH12A MAT file for ICRU+LOADEX pairs and return found ICRU numbers
entailment
def _analyse_mat_sections(sections): """ 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 ...
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 ...
entailment
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')) try: return [ref_dict[e] for e in ...
Find matching file names for given ICRU numbers
entailment
def _rewrite_paths_in_file(config_file, paths_to_replace): """ 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 """ lines = [] # make a copy of config import shutil ...
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
entailment
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
Check if a given LDAP object exists.
entailment
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_single('uidNumber') if uid_number is None: scheme = sett...
Modify a changes to add an automatically generated uidNumber.
entailment
def transform_source(text): '''Replaces instances of switch expression: by for __case in _Switch(n): and replaces case expression: by if __case(expression): and default: by if __case(): ''' toks = tokenize.generate_tokens(StringIO...
Replaces instances of switch expression: by for __case in _Switch(n): and replaces case expression: by if __case(expression): and default: by if __case():
entailment
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) # first results if att...
Search for entries in LDAP database.
entailment
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. """ raise NotImplementedError()
rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled.
entailment
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='Workflow', parameters='{}') # Add services to environm...
Example shows how to configure environment from scratch
entailment
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 version: click.echo(__version...
Commands for devops operations
entailment
def duplicate(obj, value=None, field=None, duplicate_order=None): """ 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...
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 ...
entailment
def getPayloadStruct(self, attributes, objType): """ 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 """ ...
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
entailment
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.')
Validate url.
entailment
def enter_transaction_management(using=None): """ 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 ...
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...
entailment
def leave_transaction_management(using=None): """ 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.) """ if using is None: for using in...
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.)
entailment
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: connection = tldap.backend.connections[using] if connection.is_dirty(): ...
Returns True if the current transaction requires a commit for changes to happen.
entailment
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.backend.connections[using] if connection.is_managed(): ...
Checks whether the transaction manager is in manual or in auto state.
entailment
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 connection = tldap.backend.connections[using] ...
Does the commit itself and resets the dirty flag.
entailment
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] connection.rollback() return connection = tldap.backend....
This function does the rollback itself and resets the dirty flag.
entailment
def _transaction_func(entering, exiting, using): """ 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 defi...
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...
entailment
def commit_on_success(using=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. """ de...
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.
entailment
def commit_manually(using=None): """ 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 entering(using): ...
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.
entailment
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): self.load() for func in self.all_funcs(): try: ...
Yields: tuple (line_number: int, offset: int, text: str, check: type)
entailment
def process_request(self, request): """ Reloads glitter URL patterns if page URLs change. Avoids having to restart the server to recreate the glitter URLs being used by Django. """ global _urlconf_pages page_list = list( Page.objects.exclude(glitter_app_name...
Reloads glitter URL patterns if page URLs change. Avoids having to restart the server to recreate the glitter URLs being used by Django.
entailment
def run(self): """ 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. """ self._logger.info('runner started: %s', self) try: with self._lock...
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.
entailment
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._stopped.wait()
Stop execution of all current and future payloads
entailment
def delimit_words(string: str) -> Generator[str, None, None]: """ 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("S3Buck...
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...
entailment
def normalize(string: str) -> str: """ Normalizes whitespace. Strips leading and trailing blank lines, dedents, and removes trailing whitespace from the result. """ string = string.replace("\t", " ") lines = string.split("\n") while lines and (not lines[0] or lines[0].isspace()): ...
Normalizes whitespace. Strips leading and trailing blank lines, dedents, and removes trailing whitespace from the result.
entailment
def to_dash_case(string: str) -> str: """ 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' >>> pr...
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...
entailment
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"): fixers.append("lib2to3.fixes." + name[:-3]) ...
returns a list of all fixers found in the lib2to3 library
entailment
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 fixname == name[4:-3]): return "lib2to3.fixes...
return a single fixer found in the lib2to3 library
entailment
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 in enumerate(value): value[i] = self.value_to_db(v) ...
Returns field's single value prepared for saving into a database.
entailment
def to_python(self, value): """ 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. """ assert isinstance(value, list) ...
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.
entailment
def validate(self, value): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ # check object type if not isinstance(value, list): raise tldap.exceptions.ValidationError( "is not a li...
Validates value and throws ValidationError. Subclasses should override this to provide validation logic.
entailment
def clean(self, value): """ 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. """ value = self.to_python(value) self.validate(value) return value
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.
entailment
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
Returns field's single value prepared for saving into a database.
entailment
def value_to_python(self, 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. """ if not isins...
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.
entailment
def value_validate(self, value): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ if not isinstance(value, six.string_types): raise tldap.exceptions.ValidationError("should be a string")
Validates value and throws ValidationError. Subclasses should override this to provide validation logic.
entailment
def value_to_python(self, 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. """ if not isins...
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.
entailment
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")
Returns field's single value prepared for saving into a database.
entailment
def value_validate(self, 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. """ if not isinst...
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.
entailment
def value_to_python(self, 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. """ if not isins...
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.
entailment
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 = value - datetime.date(year=1970, month=1, day=1) except Overfl...
Returns field's single value prepared for saving into a database.
entailment
def value_validate(self, 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. """ if not isinst...
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.
entailment
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 OverflowError: raise tldap.exceptions.ValidationError("is...
Returns field's single value prepared for saving into a database.
entailment
def value_validate(self, 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. """ if not isinst...
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.
entailment
def value_to_python(self, 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. """ if not isins...
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.
entailment
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 assert array[0] == 'S' array = array[1:2] + [length, 0, 0,...
Returns field's single value prepared for saving into a database.
entailment
def value_validate(self, 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. """ if not isinst...
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.
entailment
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()
Get data for this component
entailment
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()
Create a new component
entailment
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()
Update a component
entailment
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()
Delete a component by id
entailment
def get_list(self, url=None, callback=None, limit=100, **data): """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: addition...
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
entailment
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))
Return all comments for this issue/pull request
entailment
def has_edit_permission(self, request, obj=None, version=None): """ 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). """ ...
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).
entailment
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_label, self.opts.model_name) has_permission = request.user.has_perm(permission_n...
Returns a boolean if the user in the request has publish permission for the object.
entailment
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 parse "%s", please use ' 'MA...
Get a valid semantic version for tag
entailment
def load(self, data): """ Function load Store the object data """ self.clear() self.update(data) self.enhance()
Function load Store the object data
entailment
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ if self.objName in ['hosts', 'hostgroups', 'puppet_classes']: from foreman.itemSmartClassParameter\ import ItemSmartClassParameter ...
Function enhance Enhance the object with new item or enhanced items
entailment
def reload(self): """ Function reload Sync the full object """ self.load(self.api.get(self.objName, self.key))
Function reload Sync the full object
entailment