id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
11,400
relekang/python-semantic-release
semantic_release/history/logs.py
evaluate_version_bump
def evaluate_version_bump(current_version: str, force: str = None) -> Optional[str]: """ Reads git log since last release to find out if should be a major, minor or patch release. :param current_version: A string with the current version number. :param force: A string with the bump level that should be forced. :return: A string with either major, minor or patch if there should be a release. If no release is necessary None will be returned. """ debug('evaluate_version_bump("{}", "{}")'.format(current_version, force)) if force: return force bump = None changes = [] commit_count = 0 for _hash, commit_message in get_commit_log('v{0}'.format(current_version)): if (current_version in commit_message and config.get('semantic_release', 'version_source') == 'commit'): debug('found {} in "{}. breaking loop'.format(current_version, commit_message)) break try: message = current_commit_parser()(commit_message) changes.append(message[0]) except UnknownCommitMessageStyleError as err: debug('ignored', err) pass commit_count += 1 if changes: level = max(changes) if level in LEVELS: bump = LEVELS[level] if config.getboolean('semantic_release', 'patch_without_tag') and commit_count: bump = 'patch' return bump
python
def evaluate_version_bump(current_version: str, force: str = None) -> Optional[str]: """ Reads git log since last release to find out if should be a major, minor or patch release. :param current_version: A string with the current version number. :param force: A string with the bump level that should be forced. :return: A string with either major, minor or patch if there should be a release. If no release is necessary None will be returned. """ debug('evaluate_version_bump("{}", "{}")'.format(current_version, force)) if force: return force bump = None changes = [] commit_count = 0 for _hash, commit_message in get_commit_log('v{0}'.format(current_version)): if (current_version in commit_message and config.get('semantic_release', 'version_source') == 'commit'): debug('found {} in "{}. breaking loop'.format(current_version, commit_message)) break try: message = current_commit_parser()(commit_message) changes.append(message[0]) except UnknownCommitMessageStyleError as err: debug('ignored', err) pass commit_count += 1 if changes: level = max(changes) if level in LEVELS: bump = LEVELS[level] if config.getboolean('semantic_release', 'patch_without_tag') and commit_count: bump = 'patch' return bump
[ "def", "evaluate_version_bump", "(", "current_version", ":", "str", ",", "force", ":", "str", "=", "None", ")", "->", "Optional", "[", "str", "]", ":", "debug", "(", "'evaluate_version_bump(\"{}\", \"{}\")'", ".", "format", "(", "current_version", ",", "force", ")", ")", "if", "force", ":", "return", "force", "bump", "=", "None", "changes", "=", "[", "]", "commit_count", "=", "0", "for", "_hash", ",", "commit_message", "in", "get_commit_log", "(", "'v{0}'", ".", "format", "(", "current_version", ")", ")", ":", "if", "(", "current_version", "in", "commit_message", "and", "config", ".", "get", "(", "'semantic_release'", ",", "'version_source'", ")", "==", "'commit'", ")", ":", "debug", "(", "'found {} in \"{}. breaking loop'", ".", "format", "(", "current_version", ",", "commit_message", ")", ")", "break", "try", ":", "message", "=", "current_commit_parser", "(", ")", "(", "commit_message", ")", "changes", ".", "append", "(", "message", "[", "0", "]", ")", "except", "UnknownCommitMessageStyleError", "as", "err", ":", "debug", "(", "'ignored'", ",", "err", ")", "pass", "commit_count", "+=", "1", "if", "changes", ":", "level", "=", "max", "(", "changes", ")", "if", "level", "in", "LEVELS", ":", "bump", "=", "LEVELS", "[", "level", "]", "if", "config", ".", "getboolean", "(", "'semantic_release'", ",", "'patch_without_tag'", ")", "and", "commit_count", ":", "bump", "=", "'patch'", "return", "bump" ]
Reads git log since last release to find out if should be a major, minor or patch release. :param current_version: A string with the current version number. :param force: A string with the bump level that should be forced. :return: A string with either major, minor or patch if there should be a release. If no release is necessary None will be returned.
[ "Reads", "git", "log", "since", "last", "release", "to", "find", "out", "if", "should", "be", "a", "major", "minor", "or", "patch", "release", "." ]
76123f410180599a19e7c48da413880185bbea20
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/logs.py#L25-L63
11,401
relekang/python-semantic-release
semantic_release/history/logs.py
generate_changelog
def generate_changelog(from_version: str, to_version: str = None) -> dict: """ Generates a changelog for the given version. :param from_version: The last version not in the changelog. The changelog will be generated from the commit after this one. :param to_version: The last version in the changelog. :return: a dict with different changelog sections """ debug('generate_changelog("{}", "{}")'.format(from_version, to_version)) changes: dict = {'feature': [], 'fix': [], 'documentation': [], 'refactor': [], 'breaking': []} found_the_release = to_version is None rev = None if from_version: rev = 'v{0}'.format(from_version) for _hash, commit_message in get_commit_log(rev): if not found_the_release: if to_version and to_version not in commit_message: continue else: found_the_release = True if from_version is not None and from_version in commit_message: break try: message = current_commit_parser()(commit_message) if message[1] not in changes: continue changes[message[1]].append((_hash, message[3][0])) if message[3][1] and 'BREAKING CHANGE' in message[3][1]: parts = re_breaking.match(message[3][1]) if parts: changes['breaking'].append(parts.group(1)) if message[3][2] and 'BREAKING CHANGE' in message[3][2]: parts = re_breaking.match(message[3][2]) if parts: changes['breaking'].append(parts.group(1)) except UnknownCommitMessageStyleError as err: debug('Ignoring', err) pass return changes
python
def generate_changelog(from_version: str, to_version: str = None) -> dict: """ Generates a changelog for the given version. :param from_version: The last version not in the changelog. The changelog will be generated from the commit after this one. :param to_version: The last version in the changelog. :return: a dict with different changelog sections """ debug('generate_changelog("{}", "{}")'.format(from_version, to_version)) changes: dict = {'feature': [], 'fix': [], 'documentation': [], 'refactor': [], 'breaking': []} found_the_release = to_version is None rev = None if from_version: rev = 'v{0}'.format(from_version) for _hash, commit_message in get_commit_log(rev): if not found_the_release: if to_version and to_version not in commit_message: continue else: found_the_release = True if from_version is not None and from_version in commit_message: break try: message = current_commit_parser()(commit_message) if message[1] not in changes: continue changes[message[1]].append((_hash, message[3][0])) if message[3][1] and 'BREAKING CHANGE' in message[3][1]: parts = re_breaking.match(message[3][1]) if parts: changes['breaking'].append(parts.group(1)) if message[3][2] and 'BREAKING CHANGE' in message[3][2]: parts = re_breaking.match(message[3][2]) if parts: changes['breaking'].append(parts.group(1)) except UnknownCommitMessageStyleError as err: debug('Ignoring', err) pass return changes
[ "def", "generate_changelog", "(", "from_version", ":", "str", ",", "to_version", ":", "str", "=", "None", ")", "->", "dict", ":", "debug", "(", "'generate_changelog(\"{}\", \"{}\")'", ".", "format", "(", "from_version", ",", "to_version", ")", ")", "changes", ":", "dict", "=", "{", "'feature'", ":", "[", "]", ",", "'fix'", ":", "[", "]", ",", "'documentation'", ":", "[", "]", ",", "'refactor'", ":", "[", "]", ",", "'breaking'", ":", "[", "]", "}", "found_the_release", "=", "to_version", "is", "None", "rev", "=", "None", "if", "from_version", ":", "rev", "=", "'v{0}'", ".", "format", "(", "from_version", ")", "for", "_hash", ",", "commit_message", "in", "get_commit_log", "(", "rev", ")", ":", "if", "not", "found_the_release", ":", "if", "to_version", "and", "to_version", "not", "in", "commit_message", ":", "continue", "else", ":", "found_the_release", "=", "True", "if", "from_version", "is", "not", "None", "and", "from_version", "in", "commit_message", ":", "break", "try", ":", "message", "=", "current_commit_parser", "(", ")", "(", "commit_message", ")", "if", "message", "[", "1", "]", "not", "in", "changes", ":", "continue", "changes", "[", "message", "[", "1", "]", "]", ".", "append", "(", "(", "_hash", ",", "message", "[", "3", "]", "[", "0", "]", ")", ")", "if", "message", "[", "3", "]", "[", "1", "]", "and", "'BREAKING CHANGE'", "in", "message", "[", "3", "]", "[", "1", "]", ":", "parts", "=", "re_breaking", ".", "match", "(", "message", "[", "3", "]", "[", "1", "]", ")", "if", "parts", ":", "changes", "[", "'breaking'", "]", ".", "append", "(", "parts", ".", "group", "(", "1", ")", ")", "if", "message", "[", "3", "]", "[", "2", "]", "and", "'BREAKING CHANGE'", "in", "message", "[", "3", "]", "[", "2", "]", ":", "parts", "=", "re_breaking", ".", "match", "(", "message", "[", "3", "]", "[", "2", "]", ")", "if", "parts", ":", "changes", "[", "'breaking'", "]", ".", "append", "(", "parts", ".", "group", "(", "1", ")", ")", "except", "UnknownCommitMessageStyleError", "as", "err", ":", "debug", "(", "'Ignoring'", ",", "err", ")", "pass", "return", "changes" ]
Generates a changelog for the given version. :param from_version: The last version not in the changelog. The changelog will be generated from the commit after this one. :param to_version: The last version in the changelog. :return: a dict with different changelog sections
[ "Generates", "a", "changelog", "for", "the", "given", "version", "." ]
76123f410180599a19e7c48da413880185bbea20
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/logs.py#L66-L116
11,402
relekang/python-semantic-release
semantic_release/history/logs.py
markdown_changelog
def markdown_changelog(version: str, changelog: dict, header: bool = False) -> str: """ Generates a markdown version of the changelog. Takes a parsed changelog dict from generate_changelog. :param version: A string with the version number. :param changelog: A dict from generate_changelog. :param header: A boolean that decides whether a header should be included or not. :return: The markdown formatted changelog. """ debug('markdown_changelog(version="{}", header={}, changelog=...)'.format(version, header)) output = '' if header: output += '## v{0}\n'.format(version) for section in CHANGELOG_SECTIONS: if not changelog[section]: continue output += '\n### {0}\n'.format(section.capitalize()) for item in changelog[section]: output += '* {0} ({1})\n'.format(item[1], item[0]) return output
python
def markdown_changelog(version: str, changelog: dict, header: bool = False) -> str: """ Generates a markdown version of the changelog. Takes a parsed changelog dict from generate_changelog. :param version: A string with the version number. :param changelog: A dict from generate_changelog. :param header: A boolean that decides whether a header should be included or not. :return: The markdown formatted changelog. """ debug('markdown_changelog(version="{}", header={}, changelog=...)'.format(version, header)) output = '' if header: output += '## v{0}\n'.format(version) for section in CHANGELOG_SECTIONS: if not changelog[section]: continue output += '\n### {0}\n'.format(section.capitalize()) for item in changelog[section]: output += '* {0} ({1})\n'.format(item[1], item[0]) return output
[ "def", "markdown_changelog", "(", "version", ":", "str", ",", "changelog", ":", "dict", ",", "header", ":", "bool", "=", "False", ")", "->", "str", ":", "debug", "(", "'markdown_changelog(version=\"{}\", header={}, changelog=...)'", ".", "format", "(", "version", ",", "header", ")", ")", "output", "=", "''", "if", "header", ":", "output", "+=", "'## v{0}\\n'", ".", "format", "(", "version", ")", "for", "section", "in", "CHANGELOG_SECTIONS", ":", "if", "not", "changelog", "[", "section", "]", ":", "continue", "output", "+=", "'\\n### {0}\\n'", ".", "format", "(", "section", ".", "capitalize", "(", ")", ")", "for", "item", "in", "changelog", "[", "section", "]", ":", "output", "+=", "'* {0} ({1})\\n'", ".", "format", "(", "item", "[", "1", "]", ",", "item", "[", "0", "]", ")", "return", "output" ]
Generates a markdown version of the changelog. Takes a parsed changelog dict from generate_changelog. :param version: A string with the version number. :param changelog: A dict from generate_changelog. :param header: A boolean that decides whether a header should be included or not. :return: The markdown formatted changelog.
[ "Generates", "a", "markdown", "version", "of", "the", "changelog", ".", "Takes", "a", "parsed", "changelog", "dict", "from", "generate_changelog", "." ]
76123f410180599a19e7c48da413880185bbea20
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/logs.py#L119-L142
11,403
relekang/python-semantic-release
semantic_release/hvcs.py
get_hvcs
def get_hvcs() -> Base: """Get HVCS helper class :raises ImproperConfigurationError: if the hvcs option provided is not valid """ hvcs = config.get('semantic_release', 'hvcs') debug('get_hvcs: hvcs=', hvcs) try: return globals()[hvcs.capitalize()] except KeyError: raise ImproperConfigurationError('"{0}" is not a valid option for hvcs.')
python
def get_hvcs() -> Base: """Get HVCS helper class :raises ImproperConfigurationError: if the hvcs option provided is not valid """ hvcs = config.get('semantic_release', 'hvcs') debug('get_hvcs: hvcs=', hvcs) try: return globals()[hvcs.capitalize()] except KeyError: raise ImproperConfigurationError('"{0}" is not a valid option for hvcs.')
[ "def", "get_hvcs", "(", ")", "->", "Base", ":", "hvcs", "=", "config", ".", "get", "(", "'semantic_release'", ",", "'hvcs'", ")", "debug", "(", "'get_hvcs: hvcs='", ",", "hvcs", ")", "try", ":", "return", "globals", "(", ")", "[", "hvcs", ".", "capitalize", "(", ")", "]", "except", "KeyError", ":", "raise", "ImproperConfigurationError", "(", "'\"{0}\" is not a valid option for hvcs.'", ")" ]
Get HVCS helper class :raises ImproperConfigurationError: if the hvcs option provided is not valid
[ "Get", "HVCS", "helper", "class" ]
76123f410180599a19e7c48da413880185bbea20
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/hvcs.py#L121-L131
11,404
relekang/python-semantic-release
semantic_release/hvcs.py
check_build_status
def check_build_status(owner: str, repository: str, ref: str) -> bool: """ Checks the build status of a commit on the api from your hosted version control provider. :param owner: The owner of the repository :param repository: The repository name :param ref: Commit or branch reference :return: A boolean with the build status """ debug('check_build_status') return get_hvcs().check_build_status(owner, repository, ref)
python
def check_build_status(owner: str, repository: str, ref: str) -> bool: """ Checks the build status of a commit on the api from your hosted version control provider. :param owner: The owner of the repository :param repository: The repository name :param ref: Commit or branch reference :return: A boolean with the build status """ debug('check_build_status') return get_hvcs().check_build_status(owner, repository, ref)
[ "def", "check_build_status", "(", "owner", ":", "str", ",", "repository", ":", "str", ",", "ref", ":", "str", ")", "->", "bool", ":", "debug", "(", "'check_build_status'", ")", "return", "get_hvcs", "(", ")", ".", "check_build_status", "(", "owner", ",", "repository", ",", "ref", ")" ]
Checks the build status of a commit on the api from your hosted version control provider. :param owner: The owner of the repository :param repository: The repository name :param ref: Commit or branch reference :return: A boolean with the build status
[ "Checks", "the", "build", "status", "of", "a", "commit", "on", "the", "api", "from", "your", "hosted", "version", "control", "provider", "." ]
76123f410180599a19e7c48da413880185bbea20
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/hvcs.py#L134-L144
11,405
relekang/python-semantic-release
semantic_release/hvcs.py
post_changelog
def post_changelog(owner: str, repository: str, version: str, changelog: str) -> Tuple[bool, dict]: """ Posts the changelog to the current hvcs release API :param owner: The owner of the repository :param repository: The repository name :param version: A string with the new version :param changelog: A string with the changelog in correct format :return: a tuple with success status and payload from hvcs """ debug('post_changelog(owner={}, repository={}, version={})'.format(owner, repository, version)) return get_hvcs().post_release_changelog(owner, repository, version, changelog)
python
def post_changelog(owner: str, repository: str, version: str, changelog: str) -> Tuple[bool, dict]: """ Posts the changelog to the current hvcs release API :param owner: The owner of the repository :param repository: The repository name :param version: A string with the new version :param changelog: A string with the changelog in correct format :return: a tuple with success status and payload from hvcs """ debug('post_changelog(owner={}, repository={}, version={})'.format(owner, repository, version)) return get_hvcs().post_release_changelog(owner, repository, version, changelog)
[ "def", "post_changelog", "(", "owner", ":", "str", ",", "repository", ":", "str", ",", "version", ":", "str", ",", "changelog", ":", "str", ")", "->", "Tuple", "[", "bool", ",", "dict", "]", ":", "debug", "(", "'post_changelog(owner={}, repository={}, version={})'", ".", "format", "(", "owner", ",", "repository", ",", "version", ")", ")", "return", "get_hvcs", "(", ")", ".", "post_release_changelog", "(", "owner", ",", "repository", ",", "version", ",", "changelog", ")" ]
Posts the changelog to the current hvcs release API :param owner: The owner of the repository :param repository: The repository name :param version: A string with the new version :param changelog: A string with the changelog in correct format :return: a tuple with success status and payload from hvcs
[ "Posts", "the", "changelog", "to", "the", "current", "hvcs", "release", "API" ]
76123f410180599a19e7c48da413880185bbea20
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/hvcs.py#L147-L158
11,406
relekang/python-semantic-release
semantic_release/cli.py
version
def version(**kwargs): """ Detects the new version according to git log and semver. Writes the new version number and commits it, unless the noop-option is True. """ retry = kwargs.get("retry") if retry: click.echo('Retrying publication of the same version...') else: click.echo('Creating new version..') try: current_version = get_current_version() except GitError as e: click.echo(click.style(str(e), 'red'), err=True) return False click.echo('Current version: {0}'.format(current_version)) level_bump = evaluate_version_bump(current_version, kwargs['force_level']) new_version = get_new_version(current_version, level_bump) if new_version == current_version and not retry: click.echo(click.style('No release will be made.', fg='yellow')) return False if kwargs['noop'] is True: click.echo('{0} Should have bumped from {1} to {2}.'.format( click.style('No operation mode.', fg='yellow'), current_version, new_version )) return False if config.getboolean('semantic_release', 'check_build_status'): click.echo('Checking build status..') owner, name = get_repository_owner_and_name() if not check_build_status(owner, name, get_current_head_hash()): click.echo(click.style('The build has failed', 'red')) return False click.echo(click.style('The build was a success, continuing the release', 'green')) if retry: # No need to make changes to the repo, we're just retrying. return True if config.get('semantic_release', 'version_source') == 'commit': set_new_version(new_version) commit_new_version(new_version) tag_new_version(new_version) click.echo('Bumping with a {0} version to {1}.'.format(level_bump, new_version)) return True
python
def version(**kwargs): """ Detects the new version according to git log and semver. Writes the new version number and commits it, unless the noop-option is True. """ retry = kwargs.get("retry") if retry: click.echo('Retrying publication of the same version...') else: click.echo('Creating new version..') try: current_version = get_current_version() except GitError as e: click.echo(click.style(str(e), 'red'), err=True) return False click.echo('Current version: {0}'.format(current_version)) level_bump = evaluate_version_bump(current_version, kwargs['force_level']) new_version = get_new_version(current_version, level_bump) if new_version == current_version and not retry: click.echo(click.style('No release will be made.', fg='yellow')) return False if kwargs['noop'] is True: click.echo('{0} Should have bumped from {1} to {2}.'.format( click.style('No operation mode.', fg='yellow'), current_version, new_version )) return False if config.getboolean('semantic_release', 'check_build_status'): click.echo('Checking build status..') owner, name = get_repository_owner_and_name() if not check_build_status(owner, name, get_current_head_hash()): click.echo(click.style('The build has failed', 'red')) return False click.echo(click.style('The build was a success, continuing the release', 'green')) if retry: # No need to make changes to the repo, we're just retrying. return True if config.get('semantic_release', 'version_source') == 'commit': set_new_version(new_version) commit_new_version(new_version) tag_new_version(new_version) click.echo('Bumping with a {0} version to {1}.'.format(level_bump, new_version)) return True
[ "def", "version", "(", "*", "*", "kwargs", ")", ":", "retry", "=", "kwargs", ".", "get", "(", "\"retry\"", ")", "if", "retry", ":", "click", ".", "echo", "(", "'Retrying publication of the same version...'", ")", "else", ":", "click", ".", "echo", "(", "'Creating new version..'", ")", "try", ":", "current_version", "=", "get_current_version", "(", ")", "except", "GitError", "as", "e", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "str", "(", "e", ")", ",", "'red'", ")", ",", "err", "=", "True", ")", "return", "False", "click", ".", "echo", "(", "'Current version: {0}'", ".", "format", "(", "current_version", ")", ")", "level_bump", "=", "evaluate_version_bump", "(", "current_version", ",", "kwargs", "[", "'force_level'", "]", ")", "new_version", "=", "get_new_version", "(", "current_version", ",", "level_bump", ")", "if", "new_version", "==", "current_version", "and", "not", "retry", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "'No release will be made.'", ",", "fg", "=", "'yellow'", ")", ")", "return", "False", "if", "kwargs", "[", "'noop'", "]", "is", "True", ":", "click", ".", "echo", "(", "'{0} Should have bumped from {1} to {2}.'", ".", "format", "(", "click", ".", "style", "(", "'No operation mode.'", ",", "fg", "=", "'yellow'", ")", ",", "current_version", ",", "new_version", ")", ")", "return", "False", "if", "config", ".", "getboolean", "(", "'semantic_release'", ",", "'check_build_status'", ")", ":", "click", ".", "echo", "(", "'Checking build status..'", ")", "owner", ",", "name", "=", "get_repository_owner_and_name", "(", ")", "if", "not", "check_build_status", "(", "owner", ",", "name", ",", "get_current_head_hash", "(", ")", ")", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "'The build has failed'", ",", "'red'", ")", ")", "return", "False", "click", ".", "echo", "(", "click", ".", "style", "(", "'The build was a success, continuing the release'", ",", "'green'", ")", ")", "if", "retry", ":", "# No need to make changes to the repo, we're just retrying.", "return", "True", "if", "config", ".", "get", "(", "'semantic_release'", ",", "'version_source'", ")", "==", "'commit'", ":", "set_new_version", "(", "new_version", ")", "commit_new_version", "(", "new_version", ")", "tag_new_version", "(", "new_version", ")", "click", ".", "echo", "(", "'Bumping with a {0} version to {1}.'", ".", "format", "(", "level_bump", ",", "new_version", ")", ")", "return", "True" ]
Detects the new version according to git log and semver. Writes the new version number and commits it, unless the noop-option is True.
[ "Detects", "the", "new", "version", "according", "to", "git", "log", "and", "semver", ".", "Writes", "the", "new", "version", "number", "and", "commits", "it", "unless", "the", "noop", "-", "option", "is", "True", "." ]
76123f410180599a19e7c48da413880185bbea20
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/cli.py#L43-L93
11,407
relekang/python-semantic-release
semantic_release/cli.py
publish
def publish(**kwargs): """ Runs the version task before pushing to git and uploading to pypi. """ current_version = get_current_version() click.echo('Current version: {0}'.format(current_version)) retry = kwargs.get("retry") debug('publish: retry=', retry) if retry: # The "new" version will actually be the current version, and the # "current" version will be the previous version. new_version = current_version current_version = get_previous_version(current_version) else: level_bump = evaluate_version_bump(current_version, kwargs['force_level']) new_version = get_new_version(current_version, level_bump) owner, name = get_repository_owner_and_name() ci_checks.check('master') checkout('master') if version(**kwargs): push_new_version( gh_token=os.environ.get('GH_TOKEN'), owner=owner, name=name ) if config.getboolean('semantic_release', 'upload_to_pypi'): upload_to_pypi( username=os.environ.get('PYPI_USERNAME'), password=os.environ.get('PYPI_PASSWORD'), # We are retrying, so we don't want errors for files that are already on PyPI. skip_existing=retry, ) if check_token(): click.echo('Updating changelog') try: log = generate_changelog(current_version, new_version) post_changelog( owner, name, new_version, markdown_changelog(new_version, log, header=False) ) except GitError: click.echo(click.style('Posting changelog failed.', 'red'), err=True) else: click.echo( click.style('Missing token: cannot post changelog', 'red'), err=True) click.echo(click.style('New release published', 'green')) else: click.echo('Version failed, no release will be published.', err=True)
python
def publish(**kwargs): """ Runs the version task before pushing to git and uploading to pypi. """ current_version = get_current_version() click.echo('Current version: {0}'.format(current_version)) retry = kwargs.get("retry") debug('publish: retry=', retry) if retry: # The "new" version will actually be the current version, and the # "current" version will be the previous version. new_version = current_version current_version = get_previous_version(current_version) else: level_bump = evaluate_version_bump(current_version, kwargs['force_level']) new_version = get_new_version(current_version, level_bump) owner, name = get_repository_owner_and_name() ci_checks.check('master') checkout('master') if version(**kwargs): push_new_version( gh_token=os.environ.get('GH_TOKEN'), owner=owner, name=name ) if config.getboolean('semantic_release', 'upload_to_pypi'): upload_to_pypi( username=os.environ.get('PYPI_USERNAME'), password=os.environ.get('PYPI_PASSWORD'), # We are retrying, so we don't want errors for files that are already on PyPI. skip_existing=retry, ) if check_token(): click.echo('Updating changelog') try: log = generate_changelog(current_version, new_version) post_changelog( owner, name, new_version, markdown_changelog(new_version, log, header=False) ) except GitError: click.echo(click.style('Posting changelog failed.', 'red'), err=True) else: click.echo( click.style('Missing token: cannot post changelog', 'red'), err=True) click.echo(click.style('New release published', 'green')) else: click.echo('Version failed, no release will be published.', err=True)
[ "def", "publish", "(", "*", "*", "kwargs", ")", ":", "current_version", "=", "get_current_version", "(", ")", "click", ".", "echo", "(", "'Current version: {0}'", ".", "format", "(", "current_version", ")", ")", "retry", "=", "kwargs", ".", "get", "(", "\"retry\"", ")", "debug", "(", "'publish: retry='", ",", "retry", ")", "if", "retry", ":", "# The \"new\" version will actually be the current version, and the", "# \"current\" version will be the previous version.", "new_version", "=", "current_version", "current_version", "=", "get_previous_version", "(", "current_version", ")", "else", ":", "level_bump", "=", "evaluate_version_bump", "(", "current_version", ",", "kwargs", "[", "'force_level'", "]", ")", "new_version", "=", "get_new_version", "(", "current_version", ",", "level_bump", ")", "owner", ",", "name", "=", "get_repository_owner_and_name", "(", ")", "ci_checks", ".", "check", "(", "'master'", ")", "checkout", "(", "'master'", ")", "if", "version", "(", "*", "*", "kwargs", ")", ":", "push_new_version", "(", "gh_token", "=", "os", ".", "environ", ".", "get", "(", "'GH_TOKEN'", ")", ",", "owner", "=", "owner", ",", "name", "=", "name", ")", "if", "config", ".", "getboolean", "(", "'semantic_release'", ",", "'upload_to_pypi'", ")", ":", "upload_to_pypi", "(", "username", "=", "os", ".", "environ", ".", "get", "(", "'PYPI_USERNAME'", ")", ",", "password", "=", "os", ".", "environ", ".", "get", "(", "'PYPI_PASSWORD'", ")", ",", "# We are retrying, so we don't want errors for files that are already on PyPI.", "skip_existing", "=", "retry", ",", ")", "if", "check_token", "(", ")", ":", "click", ".", "echo", "(", "'Updating changelog'", ")", "try", ":", "log", "=", "generate_changelog", "(", "current_version", ",", "new_version", ")", "post_changelog", "(", "owner", ",", "name", ",", "new_version", ",", "markdown_changelog", "(", "new_version", ",", "log", ",", "header", "=", "False", ")", ")", "except", "GitError", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "'Posting changelog failed.'", ",", "'red'", ")", ",", "err", "=", "True", ")", "else", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "'Missing token: cannot post changelog'", ",", "'red'", ")", ",", "err", "=", "True", ")", "click", ".", "echo", "(", "click", ".", "style", "(", "'New release published'", ",", "'green'", ")", ")", "else", ":", "click", ".", "echo", "(", "'Version failed, no release will be published.'", ",", "err", "=", "True", ")" ]
Runs the version task before pushing to git and uploading to pypi.
[ "Runs", "the", "version", "task", "before", "pushing", "to", "git", "and", "uploading", "to", "pypi", "." ]
76123f410180599a19e7c48da413880185bbea20
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/cli.py#L132-L188
11,408
aljosa/django-tinymce
tinymce/views.py
flatpages_link_list
def flatpages_link_list(request): """ Returns a HttpResponse whose content is a Javascript file representing a list of links to flatpages. """ from django.contrib.flatpages.models import FlatPage link_list = [(page.title, page.url) for page in FlatPage.objects.all()] return render_to_link_list(link_list)
python
def flatpages_link_list(request): """ Returns a HttpResponse whose content is a Javascript file representing a list of links to flatpages. """ from django.contrib.flatpages.models import FlatPage link_list = [(page.title, page.url) for page in FlatPage.objects.all()] return render_to_link_list(link_list)
[ "def", "flatpages_link_list", "(", "request", ")", ":", "from", "django", ".", "contrib", ".", "flatpages", ".", "models", "import", "FlatPage", "link_list", "=", "[", "(", "page", ".", "title", ",", "page", ".", "url", ")", "for", "page", "in", "FlatPage", ".", "objects", ".", "all", "(", ")", "]", "return", "render_to_link_list", "(", "link_list", ")" ]
Returns a HttpResponse whose content is a Javascript file representing a list of links to flatpages.
[ "Returns", "a", "HttpResponse", "whose", "content", "is", "a", "Javascript", "file", "representing", "a", "list", "of", "links", "to", "flatpages", "." ]
a509fdbc6c623ddac6552199da89712c0f026c91
https://github.com/aljosa/django-tinymce/blob/a509fdbc6c623ddac6552199da89712c0f026c91/tinymce/views.py#L72-L79
11,409
aio-libs/aiomonitor
aiomonitor/monitor.py
Monitor._interactive_loop
def _interactive_loop(self, sin: IO[str], sout: IO[str]) -> None: """Main interactive loop of the monitor""" self._sin = sin self._sout = sout tasknum = len(all_tasks(loop=self._loop)) s = '' if tasknum == 1 else 's' self._sout.write(self.intro.format(tasknum=tasknum, s=s)) try: while not self._closing.is_set(): self._sout.write(self.prompt) self._sout.flush() try: user_input = sin.readline().strip() except Exception as e: msg = 'Could not read from user input due to:\n{}\n' log.exception(msg) self._sout.write(msg.format(repr(e))) self._sout.flush() else: try: self._command_dispatch(user_input) except Exception as e: msg = 'Unexpected Exception during command execution:\n{}\n' # noqa log.exception(msg) self._sout.write(msg.format(repr(e))) self._sout.flush() finally: self._sin = None # type: ignore self._sout = None
python
def _interactive_loop(self, sin: IO[str], sout: IO[str]) -> None: """Main interactive loop of the monitor""" self._sin = sin self._sout = sout tasknum = len(all_tasks(loop=self._loop)) s = '' if tasknum == 1 else 's' self._sout.write(self.intro.format(tasknum=tasknum, s=s)) try: while not self._closing.is_set(): self._sout.write(self.prompt) self._sout.flush() try: user_input = sin.readline().strip() except Exception as e: msg = 'Could not read from user input due to:\n{}\n' log.exception(msg) self._sout.write(msg.format(repr(e))) self._sout.flush() else: try: self._command_dispatch(user_input) except Exception as e: msg = 'Unexpected Exception during command execution:\n{}\n' # noqa log.exception(msg) self._sout.write(msg.format(repr(e))) self._sout.flush() finally: self._sin = None # type: ignore self._sout = None
[ "def", "_interactive_loop", "(", "self", ",", "sin", ":", "IO", "[", "str", "]", ",", "sout", ":", "IO", "[", "str", "]", ")", "->", "None", ":", "self", ".", "_sin", "=", "sin", "self", ".", "_sout", "=", "sout", "tasknum", "=", "len", "(", "all_tasks", "(", "loop", "=", "self", ".", "_loop", ")", ")", "s", "=", "''", "if", "tasknum", "==", "1", "else", "'s'", "self", ".", "_sout", ".", "write", "(", "self", ".", "intro", ".", "format", "(", "tasknum", "=", "tasknum", ",", "s", "=", "s", ")", ")", "try", ":", "while", "not", "self", ".", "_closing", ".", "is_set", "(", ")", ":", "self", ".", "_sout", ".", "write", "(", "self", ".", "prompt", ")", "self", ".", "_sout", ".", "flush", "(", ")", "try", ":", "user_input", "=", "sin", ".", "readline", "(", ")", ".", "strip", "(", ")", "except", "Exception", "as", "e", ":", "msg", "=", "'Could not read from user input due to:\\n{}\\n'", "log", ".", "exception", "(", "msg", ")", "self", ".", "_sout", ".", "write", "(", "msg", ".", "format", "(", "repr", "(", "e", ")", ")", ")", "self", ".", "_sout", ".", "flush", "(", ")", "else", ":", "try", ":", "self", ".", "_command_dispatch", "(", "user_input", ")", "except", "Exception", "as", "e", ":", "msg", "=", "'Unexpected Exception during command execution:\\n{}\\n'", "# noqa", "log", ".", "exception", "(", "msg", ")", "self", ".", "_sout", ".", "write", "(", "msg", ".", "format", "(", "repr", "(", "e", ")", ")", ")", "self", ".", "_sout", ".", "flush", "(", ")", "finally", ":", "self", ".", "_sin", "=", "None", "# type: ignore", "self", ".", "_sout", "=", "None" ]
Main interactive loop of the monitor
[ "Main", "interactive", "loop", "of", "the", "monitor" ]
fe5f9caa0b117861afef13b64bce5dce3a415b80
https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L156-L184
11,410
aio-libs/aiomonitor
aiomonitor/monitor.py
Monitor.do_help
def do_help(self, *cmd_names: str) -> None: """Show help for command name Any number of command names may be given to help, and the long help text for all of them will be shown. """ def _h(cmd: str, template: str) -> None: try: func = getattr(self, cmd) except AttributeError: self._sout.write('No such command: {}\n'.format(cmd)) else: doc = func.__doc__ if func.__doc__ else '' doc_firstline = doc.split('\n', maxsplit=1)[0] arg_list = ' '.join( p for p in inspect.signature(func).parameters) self._sout.write( template.format( cmd_name=cmd[len(self._cmd_prefix):], arg_list=arg_list, cmd_arg_sep=' ' if arg_list else '', doc=doc, doc_firstline=doc_firstline ) + '\n' ) if not cmd_names: cmds = sorted( c.method_name for c in self._filter_cmds(with_alts=False) ) self._sout.write('Available Commands are:\n\n') for cmd in cmds: _h(cmd, self.help_short_template) else: for cmd in cmd_names: _h(self._cmd_prefix + cmd, self.help_template)
python
def do_help(self, *cmd_names: str) -> None: """Show help for command name Any number of command names may be given to help, and the long help text for all of them will be shown. """ def _h(cmd: str, template: str) -> None: try: func = getattr(self, cmd) except AttributeError: self._sout.write('No such command: {}\n'.format(cmd)) else: doc = func.__doc__ if func.__doc__ else '' doc_firstline = doc.split('\n', maxsplit=1)[0] arg_list = ' '.join( p for p in inspect.signature(func).parameters) self._sout.write( template.format( cmd_name=cmd[len(self._cmd_prefix):], arg_list=arg_list, cmd_arg_sep=' ' if arg_list else '', doc=doc, doc_firstline=doc_firstline ) + '\n' ) if not cmd_names: cmds = sorted( c.method_name for c in self._filter_cmds(with_alts=False) ) self._sout.write('Available Commands are:\n\n') for cmd in cmds: _h(cmd, self.help_short_template) else: for cmd in cmd_names: _h(self._cmd_prefix + cmd, self.help_template)
[ "def", "do_help", "(", "self", ",", "*", "cmd_names", ":", "str", ")", "->", "None", ":", "def", "_h", "(", "cmd", ":", "str", ",", "template", ":", "str", ")", "->", "None", ":", "try", ":", "func", "=", "getattr", "(", "self", ",", "cmd", ")", "except", "AttributeError", ":", "self", ".", "_sout", ".", "write", "(", "'No such command: {}\\n'", ".", "format", "(", "cmd", ")", ")", "else", ":", "doc", "=", "func", ".", "__doc__", "if", "func", ".", "__doc__", "else", "''", "doc_firstline", "=", "doc", ".", "split", "(", "'\\n'", ",", "maxsplit", "=", "1", ")", "[", "0", "]", "arg_list", "=", "' '", ".", "join", "(", "p", "for", "p", "in", "inspect", ".", "signature", "(", "func", ")", ".", "parameters", ")", "self", ".", "_sout", ".", "write", "(", "template", ".", "format", "(", "cmd_name", "=", "cmd", "[", "len", "(", "self", ".", "_cmd_prefix", ")", ":", "]", ",", "arg_list", "=", "arg_list", ",", "cmd_arg_sep", "=", "' '", "if", "arg_list", "else", "''", ",", "doc", "=", "doc", ",", "doc_firstline", "=", "doc_firstline", ")", "+", "'\\n'", ")", "if", "not", "cmd_names", ":", "cmds", "=", "sorted", "(", "c", ".", "method_name", "for", "c", "in", "self", ".", "_filter_cmds", "(", "with_alts", "=", "False", ")", ")", "self", ".", "_sout", ".", "write", "(", "'Available Commands are:\\n\\n'", ")", "for", "cmd", "in", "cmds", ":", "_h", "(", "cmd", ",", "self", ".", "help_short_template", ")", "else", ":", "for", "cmd", "in", "cmd_names", ":", "_h", "(", "self", ".", "_cmd_prefix", "+", "cmd", ",", "self", ".", "help_template", ")" ]
Show help for command name Any number of command names may be given to help, and the long help text for all of them will be shown.
[ "Show", "help", "for", "command", "name" ]
fe5f9caa0b117861afef13b64bce5dce3a415b80
https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L299-L334
11,411
aio-libs/aiomonitor
aiomonitor/monitor.py
Monitor.do_ps
def do_ps(self) -> None: """Show task table""" headers = ('Task ID', 'State', 'Task') table_data = [headers] for task in sorted(all_tasks(loop=self._loop), key=id): taskid = str(id(task)) if task: t = '\n'.join(wrap(str(task), 80)) table_data.append((taskid, task._state, t)) table = AsciiTable(table_data) self._sout.write(table.table) self._sout.write('\n') self._sout.flush()
python
def do_ps(self) -> None: """Show task table""" headers = ('Task ID', 'State', 'Task') table_data = [headers] for task in sorted(all_tasks(loop=self._loop), key=id): taskid = str(id(task)) if task: t = '\n'.join(wrap(str(task), 80)) table_data.append((taskid, task._state, t)) table = AsciiTable(table_data) self._sout.write(table.table) self._sout.write('\n') self._sout.flush()
[ "def", "do_ps", "(", "self", ")", "->", "None", ":", "headers", "=", "(", "'Task ID'", ",", "'State'", ",", "'Task'", ")", "table_data", "=", "[", "headers", "]", "for", "task", "in", "sorted", "(", "all_tasks", "(", "loop", "=", "self", ".", "_loop", ")", ",", "key", "=", "id", ")", ":", "taskid", "=", "str", "(", "id", "(", "task", ")", ")", "if", "task", ":", "t", "=", "'\\n'", ".", "join", "(", "wrap", "(", "str", "(", "task", ")", ",", "80", ")", ")", "table_data", ".", "append", "(", "(", "taskid", ",", "task", ".", "_state", ",", "t", ")", ")", "table", "=", "AsciiTable", "(", "table_data", ")", "self", ".", "_sout", ".", "write", "(", "table", ".", "table", ")", "self", ".", "_sout", ".", "write", "(", "'\\n'", ")", "self", ".", "_sout", ".", "flush", "(", ")" ]
Show task table
[ "Show", "task", "table" ]
fe5f9caa0b117861afef13b64bce5dce3a415b80
https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L337-L349
11,412
aio-libs/aiomonitor
aiomonitor/monitor.py
Monitor.do_where
def do_where(self, taskid: int) -> None: """Show stack frames for a task""" task = task_by_id(taskid, self._loop) if task: self._sout.write(_format_stack(task)) self._sout.write('\n') else: self._sout.write('No task %d\n' % taskid)
python
def do_where(self, taskid: int) -> None: """Show stack frames for a task""" task = task_by_id(taskid, self._loop) if task: self._sout.write(_format_stack(task)) self._sout.write('\n') else: self._sout.write('No task %d\n' % taskid)
[ "def", "do_where", "(", "self", ",", "taskid", ":", "int", ")", "->", "None", ":", "task", "=", "task_by_id", "(", "taskid", ",", "self", ".", "_loop", ")", "if", "task", ":", "self", ".", "_sout", ".", "write", "(", "_format_stack", "(", "task", ")", ")", "self", ".", "_sout", ".", "write", "(", "'\\n'", ")", "else", ":", "self", ".", "_sout", ".", "write", "(", "'No task %d\\n'", "%", "taskid", ")" ]
Show stack frames for a task
[ "Show", "stack", "frames", "for", "a", "task" ]
fe5f9caa0b117861afef13b64bce5dce3a415b80
https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L352-L359
11,413
aio-libs/aiomonitor
aiomonitor/monitor.py
Monitor.do_signal
def do_signal(self, signame: str) -> None: """Send a Unix signal""" if hasattr(signal, signame): os.kill(os.getpid(), getattr(signal, signame)) else: self._sout.write('Unknown signal %s\n' % signame)
python
def do_signal(self, signame: str) -> None: """Send a Unix signal""" if hasattr(signal, signame): os.kill(os.getpid(), getattr(signal, signame)) else: self._sout.write('Unknown signal %s\n' % signame)
[ "def", "do_signal", "(", "self", ",", "signame", ":", "str", ")", "->", "None", ":", "if", "hasattr", "(", "signal", ",", "signame", ")", ":", "os", ".", "kill", "(", "os", ".", "getpid", "(", ")", ",", "getattr", "(", "signal", ",", "signame", ")", ")", "else", ":", "self", ".", "_sout", ".", "write", "(", "'Unknown signal %s\\n'", "%", "signame", ")" ]
Send a Unix signal
[ "Send", "a", "Unix", "signal" ]
fe5f9caa0b117861afef13b64bce5dce3a415b80
https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L361-L366
11,414
aio-libs/aiomonitor
aiomonitor/monitor.py
Monitor.do_stacktrace
def do_stacktrace(self) -> None: """Print a stack trace from the event loop thread""" frame = sys._current_frames()[self._event_loop_thread_id] traceback.print_stack(frame, file=self._sout)
python
def do_stacktrace(self) -> None: """Print a stack trace from the event loop thread""" frame = sys._current_frames()[self._event_loop_thread_id] traceback.print_stack(frame, file=self._sout)
[ "def", "do_stacktrace", "(", "self", ")", "->", "None", ":", "frame", "=", "sys", ".", "_current_frames", "(", ")", "[", "self", ".", "_event_loop_thread_id", "]", "traceback", ".", "print_stack", "(", "frame", ",", "file", "=", "self", ".", "_sout", ")" ]
Print a stack trace from the event loop thread
[ "Print", "a", "stack", "trace", "from", "the", "event", "loop", "thread" ]
fe5f9caa0b117861afef13b64bce5dce3a415b80
https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L369-L372
11,415
aio-libs/aiomonitor
aiomonitor/monitor.py
Monitor.do_cancel
def do_cancel(self, taskid: int) -> None: """Cancel an indicated task""" task = task_by_id(taskid, self._loop) if task: fut = asyncio.run_coroutine_threadsafe( cancel_task(task), loop=self._loop) fut.result(timeout=3) self._sout.write('Cancel task %d\n' % taskid) else: self._sout.write('No task %d\n' % taskid)
python
def do_cancel(self, taskid: int) -> None: """Cancel an indicated task""" task = task_by_id(taskid, self._loop) if task: fut = asyncio.run_coroutine_threadsafe( cancel_task(task), loop=self._loop) fut.result(timeout=3) self._sout.write('Cancel task %d\n' % taskid) else: self._sout.write('No task %d\n' % taskid)
[ "def", "do_cancel", "(", "self", ",", "taskid", ":", "int", ")", "->", "None", ":", "task", "=", "task_by_id", "(", "taskid", ",", "self", ".", "_loop", ")", "if", "task", ":", "fut", "=", "asyncio", ".", "run_coroutine_threadsafe", "(", "cancel_task", "(", "task", ")", ",", "loop", "=", "self", ".", "_loop", ")", "fut", ".", "result", "(", "timeout", "=", "3", ")", "self", ".", "_sout", ".", "write", "(", "'Cancel task %d\\n'", "%", "taskid", ")", "else", ":", "self", ".", "_sout", ".", "write", "(", "'No task %d\\n'", "%", "taskid", ")" ]
Cancel an indicated task
[ "Cancel", "an", "indicated", "task" ]
fe5f9caa0b117861afef13b64bce5dce3a415b80
https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L374-L383
11,416
aio-libs/aiomonitor
aiomonitor/monitor.py
Monitor.do_console
def do_console(self) -> None: """Switch to async Python REPL""" if not self._console_enabled: self._sout.write('Python console disabled for this sessiong\n') self._sout.flush() return h, p = self._host, self._console_port log.info('Starting console at %s:%d', h, p) fut = init_console_server( self._host, self._console_port, self._locals, self._loop) server = fut.result(timeout=3) try: console_proxy( self._sin, self._sout, self._host, self._console_port) finally: coro = close_server(server) close_fut = asyncio.run_coroutine_threadsafe(coro, loop=self._loop) close_fut.result(timeout=15)
python
def do_console(self) -> None: """Switch to async Python REPL""" if not self._console_enabled: self._sout.write('Python console disabled for this sessiong\n') self._sout.flush() return h, p = self._host, self._console_port log.info('Starting console at %s:%d', h, p) fut = init_console_server( self._host, self._console_port, self._locals, self._loop) server = fut.result(timeout=3) try: console_proxy( self._sin, self._sout, self._host, self._console_port) finally: coro = close_server(server) close_fut = asyncio.run_coroutine_threadsafe(coro, loop=self._loop) close_fut.result(timeout=15)
[ "def", "do_console", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "_console_enabled", ":", "self", ".", "_sout", ".", "write", "(", "'Python console disabled for this sessiong\\n'", ")", "self", ".", "_sout", ".", "flush", "(", ")", "return", "h", ",", "p", "=", "self", ".", "_host", ",", "self", ".", "_console_port", "log", ".", "info", "(", "'Starting console at %s:%d'", ",", "h", ",", "p", ")", "fut", "=", "init_console_server", "(", "self", ".", "_host", ",", "self", ".", "_console_port", ",", "self", ".", "_locals", ",", "self", ".", "_loop", ")", "server", "=", "fut", ".", "result", "(", "timeout", "=", "3", ")", "try", ":", "console_proxy", "(", "self", ".", "_sin", ",", "self", ".", "_sout", ",", "self", ".", "_host", ",", "self", ".", "_console_port", ")", "finally", ":", "coro", "=", "close_server", "(", "server", ")", "close_fut", "=", "asyncio", ".", "run_coroutine_threadsafe", "(", "coro", ",", "loop", "=", "self", ".", "_loop", ")", "close_fut", ".", "result", "(", "timeout", "=", "15", ")" ]
Switch to async Python REPL
[ "Switch", "to", "async", "Python", "REPL" ]
fe5f9caa0b117861afef13b64bce5dce3a415b80
https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/monitor.py#L391-L409
11,417
aio-libs/aiomonitor
aiomonitor/utils.py
alt_names
def alt_names(names: str) -> Callable[..., Any]: """Add alternative names to you custom commands. `names` is a single string with a space separated list of aliases for the decorated command. """ names_split = names.split() def decorator(func: Callable[..., Any]) -> Callable[..., Any]: func.alt_names = names_split # type: ignore return func return decorator
python
def alt_names(names: str) -> Callable[..., Any]: """Add alternative names to you custom commands. `names` is a single string with a space separated list of aliases for the decorated command. """ names_split = names.split() def decorator(func: Callable[..., Any]) -> Callable[..., Any]: func.alt_names = names_split # type: ignore return func return decorator
[ "def", "alt_names", "(", "names", ":", "str", ")", "->", "Callable", "[", "...", ",", "Any", "]", ":", "names_split", "=", "names", ".", "split", "(", ")", "def", "decorator", "(", "func", ":", "Callable", "[", "...", ",", "Any", "]", ")", "->", "Callable", "[", "...", ",", "Any", "]", ":", "func", ".", "alt_names", "=", "names_split", "# type: ignore", "return", "func", "return", "decorator" ]
Add alternative names to you custom commands. `names` is a single string with a space separated list of aliases for the decorated command.
[ "Add", "alternative", "names", "to", "you", "custom", "commands", "." ]
fe5f9caa0b117861afef13b64bce5dce3a415b80
https://github.com/aio-libs/aiomonitor/blob/fe5f9caa0b117861afef13b64bce5dce3a415b80/aiomonitor/utils.py#L115-L126
11,418
vxgmichel/aioconsole
aioconsole/events.py
set_interactive_policy
def set_interactive_policy(*, locals=None, banner=None, serve=None, prompt_control=None): """Use an interactive event loop by default.""" policy = InteractiveEventLoopPolicy( locals=locals, banner=banner, serve=serve, prompt_control=prompt_control) asyncio.set_event_loop_policy(policy)
python
def set_interactive_policy(*, locals=None, banner=None, serve=None, prompt_control=None): """Use an interactive event loop by default.""" policy = InteractiveEventLoopPolicy( locals=locals, banner=banner, serve=serve, prompt_control=prompt_control) asyncio.set_event_loop_policy(policy)
[ "def", "set_interactive_policy", "(", "*", ",", "locals", "=", "None", ",", "banner", "=", "None", ",", "serve", "=", "None", ",", "prompt_control", "=", "None", ")", ":", "policy", "=", "InteractiveEventLoopPolicy", "(", "locals", "=", "locals", ",", "banner", "=", "banner", ",", "serve", "=", "serve", ",", "prompt_control", "=", "prompt_control", ")", "asyncio", ".", "set_event_loop_policy", "(", "policy", ")" ]
Use an interactive event loop by default.
[ "Use", "an", "interactive", "event", "loop", "by", "default", "." ]
8223435723d616fd4db398431d6a6182a6015e3f
https://github.com/vxgmichel/aioconsole/blob/8223435723d616fd4db398431d6a6182a6015e3f/aioconsole/events.py#L71-L79
11,419
vxgmichel/aioconsole
aioconsole/events.py
run_console
def run_console(*, locals=None, banner=None, serve=None, prompt_control=None): """Run the interactive event loop.""" loop = InteractiveEventLoop( locals=locals, banner=banner, serve=serve, prompt_control=prompt_control) asyncio.set_event_loop(loop) try: loop.run_forever() except KeyboardInterrupt: pass
python
def run_console(*, locals=None, banner=None, serve=None, prompt_control=None): """Run the interactive event loop.""" loop = InteractiveEventLoop( locals=locals, banner=banner, serve=serve, prompt_control=prompt_control) asyncio.set_event_loop(loop) try: loop.run_forever() except KeyboardInterrupt: pass
[ "def", "run_console", "(", "*", ",", "locals", "=", "None", ",", "banner", "=", "None", ",", "serve", "=", "None", ",", "prompt_control", "=", "None", ")", ":", "loop", "=", "InteractiveEventLoop", "(", "locals", "=", "locals", ",", "banner", "=", "banner", ",", "serve", "=", "serve", ",", "prompt_control", "=", "prompt_control", ")", "asyncio", ".", "set_event_loop", "(", "loop", ")", "try", ":", "loop", ".", "run_forever", "(", ")", "except", "KeyboardInterrupt", ":", "pass" ]
Run the interactive event loop.
[ "Run", "the", "interactive", "event", "loop", "." ]
8223435723d616fd4db398431d6a6182a6015e3f
https://github.com/vxgmichel/aioconsole/blob/8223435723d616fd4db398431d6a6182a6015e3f/aioconsole/events.py#L82-L93
11,420
vxgmichel/aioconsole
aioconsole/execute.py
make_arg
def make_arg(key, annotation=None): """Make an ast function argument.""" arg = ast.arg(key, annotation) arg.lineno, arg.col_offset = 0, 0 return arg
python
def make_arg(key, annotation=None): """Make an ast function argument.""" arg = ast.arg(key, annotation) arg.lineno, arg.col_offset = 0, 0 return arg
[ "def", "make_arg", "(", "key", ",", "annotation", "=", "None", ")", ":", "arg", "=", "ast", ".", "arg", "(", "key", ",", "annotation", ")", "arg", ".", "lineno", ",", "arg", ".", "col_offset", "=", "0", ",", "0", "return", "arg" ]
Make an ast function argument.
[ "Make", "an", "ast", "function", "argument", "." ]
8223435723d616fd4db398431d6a6182a6015e3f
https://github.com/vxgmichel/aioconsole/blob/8223435723d616fd4db398431d6a6182a6015e3f/aioconsole/execute.py#L16-L20
11,421
vxgmichel/aioconsole
aioconsole/execute.py
make_coroutine_from_tree
def make_coroutine_from_tree(tree, filename="<aexec>", symbol="single", local={}): """Make a coroutine from a tree structure.""" dct = {} tree.body[0].args.args = list(map(make_arg, local)) exec(compile(tree, filename, symbol), dct) return asyncio.coroutine(dct[CORO_NAME])(**local)
python
def make_coroutine_from_tree(tree, filename="<aexec>", symbol="single", local={}): """Make a coroutine from a tree structure.""" dct = {} tree.body[0].args.args = list(map(make_arg, local)) exec(compile(tree, filename, symbol), dct) return asyncio.coroutine(dct[CORO_NAME])(**local)
[ "def", "make_coroutine_from_tree", "(", "tree", ",", "filename", "=", "\"<aexec>\"", ",", "symbol", "=", "\"single\"", ",", "local", "=", "{", "}", ")", ":", "dct", "=", "{", "}", "tree", ".", "body", "[", "0", "]", ".", "args", ".", "args", "=", "list", "(", "map", "(", "make_arg", ",", "local", ")", ")", "exec", "(", "compile", "(", "tree", ",", "filename", ",", "symbol", ")", ",", "dct", ")", "return", "asyncio", ".", "coroutine", "(", "dct", "[", "CORO_NAME", "]", ")", "(", "*", "*", "local", ")" ]
Make a coroutine from a tree structure.
[ "Make", "a", "coroutine", "from", "a", "tree", "structure", "." ]
8223435723d616fd4db398431d6a6182a6015e3f
https://github.com/vxgmichel/aioconsole/blob/8223435723d616fd4db398431d6a6182a6015e3f/aioconsole/execute.py#L50-L56
11,422
libfuse/python-fuse
fuse.py
feature_needs
def feature_needs(*feas): """ Get info about the FUSE API version needed for the support of some features. This function takes a variable number of feature patterns. A feature pattern is either: - an integer (directly referring to a FUSE API version number) - a built-in feature specifier string (meaning defined by dictionary) - a string of the form ``has_foo``, where ``foo`` is a filesystem method (refers to the API version where the method has been introduced) - a list/tuple of other feature patterns (matches each of its members) - a regexp (meant to be matched against the builtins plus ``has_foo`` patterns; can also be given by a string of the from "re:*") - a negated regexp (can be given by a string of the form "!re:*") If called with no arguments, then the list of builtins is returned, mapped to their meaning. Otherwise the function returns the smallest FUSE API version number which has all the matching features. Builtin specifiers worth to explicit mention: - ``stateful_files``: you want to use custom filehandles (eg. a file class). - ``*``: you want all features. - while ``has_foo`` makes sense for all filesystem method ``foo``, some of these can be found among the builtins, too (the ones which can be handled by the general rule). specifiers like ``has_foo`` refer to requirement that the library knows of the fs method ``foo``. """ fmap = {'stateful_files': 22, 'stateful_dirs': 23, 'stateful_io': ('stateful_files', 'stateful_dirs'), 'stateful_files_keep_cache': 23, 'stateful_files_direct_io': 23, 'keep_cache': ('stateful_files_keep_cache',), 'direct_io': ('stateful_files_direct_io',), 'has_opendir': ('stateful_dirs',), 'has_releasedir': ('stateful_dirs',), 'has_fsyncdir': ('stateful_dirs',), 'has_create': 25, 'has_access': 25, 'has_fgetattr': 25, 'has_ftruncate': 25, 'has_fsinit': ('has_init'), 'has_fsdestroy': ('has_destroy'), 'has_lock': 26, 'has_utimens': 26, 'has_bmap': 26, 'has_init': 23, 'has_destroy': 23, '*': '!re:^\*$'} if not feas: return fmap def resolve(args, maxva): for fp in args: if isinstance(fp, int): maxva[0] = max(maxva[0], fp) continue if isinstance(fp, list) or isinstance(fp, tuple): for f in fp: yield f continue ma = isinstance(fp, str) and re.compile("(!\s*|)re:(.*)").match(fp) if isinstance(fp, type(re.compile(''))) or ma: neg = False if ma: mag = ma.groups() fp = re.compile(mag[1]) neg = bool(mag[0]) for f in list(fmap.keys()) + [ 'has_' + a for a in Fuse._attrs ]: if neg != bool(re.search(fp, f)): yield f continue ma = re.compile("has_(.*)").match(fp) if ma and ma.groups()[0] in Fuse._attrs and not fp in fmap: yield 21 continue yield fmap[fp] maxva = [0] while feas: feas = set(resolve(feas, maxva)) return maxva[0]
python
def feature_needs(*feas): """ Get info about the FUSE API version needed for the support of some features. This function takes a variable number of feature patterns. A feature pattern is either: - an integer (directly referring to a FUSE API version number) - a built-in feature specifier string (meaning defined by dictionary) - a string of the form ``has_foo``, where ``foo`` is a filesystem method (refers to the API version where the method has been introduced) - a list/tuple of other feature patterns (matches each of its members) - a regexp (meant to be matched against the builtins plus ``has_foo`` patterns; can also be given by a string of the from "re:*") - a negated regexp (can be given by a string of the form "!re:*") If called with no arguments, then the list of builtins is returned, mapped to their meaning. Otherwise the function returns the smallest FUSE API version number which has all the matching features. Builtin specifiers worth to explicit mention: - ``stateful_files``: you want to use custom filehandles (eg. a file class). - ``*``: you want all features. - while ``has_foo`` makes sense for all filesystem method ``foo``, some of these can be found among the builtins, too (the ones which can be handled by the general rule). specifiers like ``has_foo`` refer to requirement that the library knows of the fs method ``foo``. """ fmap = {'stateful_files': 22, 'stateful_dirs': 23, 'stateful_io': ('stateful_files', 'stateful_dirs'), 'stateful_files_keep_cache': 23, 'stateful_files_direct_io': 23, 'keep_cache': ('stateful_files_keep_cache',), 'direct_io': ('stateful_files_direct_io',), 'has_opendir': ('stateful_dirs',), 'has_releasedir': ('stateful_dirs',), 'has_fsyncdir': ('stateful_dirs',), 'has_create': 25, 'has_access': 25, 'has_fgetattr': 25, 'has_ftruncate': 25, 'has_fsinit': ('has_init'), 'has_fsdestroy': ('has_destroy'), 'has_lock': 26, 'has_utimens': 26, 'has_bmap': 26, 'has_init': 23, 'has_destroy': 23, '*': '!re:^\*$'} if not feas: return fmap def resolve(args, maxva): for fp in args: if isinstance(fp, int): maxva[0] = max(maxva[0], fp) continue if isinstance(fp, list) or isinstance(fp, tuple): for f in fp: yield f continue ma = isinstance(fp, str) and re.compile("(!\s*|)re:(.*)").match(fp) if isinstance(fp, type(re.compile(''))) or ma: neg = False if ma: mag = ma.groups() fp = re.compile(mag[1]) neg = bool(mag[0]) for f in list(fmap.keys()) + [ 'has_' + a for a in Fuse._attrs ]: if neg != bool(re.search(fp, f)): yield f continue ma = re.compile("has_(.*)").match(fp) if ma and ma.groups()[0] in Fuse._attrs and not fp in fmap: yield 21 continue yield fmap[fp] maxva = [0] while feas: feas = set(resolve(feas, maxva)) return maxva[0]
[ "def", "feature_needs", "(", "*", "feas", ")", ":", "fmap", "=", "{", "'stateful_files'", ":", "22", ",", "'stateful_dirs'", ":", "23", ",", "'stateful_io'", ":", "(", "'stateful_files'", ",", "'stateful_dirs'", ")", ",", "'stateful_files_keep_cache'", ":", "23", ",", "'stateful_files_direct_io'", ":", "23", ",", "'keep_cache'", ":", "(", "'stateful_files_keep_cache'", ",", ")", ",", "'direct_io'", ":", "(", "'stateful_files_direct_io'", ",", ")", ",", "'has_opendir'", ":", "(", "'stateful_dirs'", ",", ")", ",", "'has_releasedir'", ":", "(", "'stateful_dirs'", ",", ")", ",", "'has_fsyncdir'", ":", "(", "'stateful_dirs'", ",", ")", ",", "'has_create'", ":", "25", ",", "'has_access'", ":", "25", ",", "'has_fgetattr'", ":", "25", ",", "'has_ftruncate'", ":", "25", ",", "'has_fsinit'", ":", "(", "'has_init'", ")", ",", "'has_fsdestroy'", ":", "(", "'has_destroy'", ")", ",", "'has_lock'", ":", "26", ",", "'has_utimens'", ":", "26", ",", "'has_bmap'", ":", "26", ",", "'has_init'", ":", "23", ",", "'has_destroy'", ":", "23", ",", "'*'", ":", "'!re:^\\*$'", "}", "if", "not", "feas", ":", "return", "fmap", "def", "resolve", "(", "args", ",", "maxva", ")", ":", "for", "fp", "in", "args", ":", "if", "isinstance", "(", "fp", ",", "int", ")", ":", "maxva", "[", "0", "]", "=", "max", "(", "maxva", "[", "0", "]", ",", "fp", ")", "continue", "if", "isinstance", "(", "fp", ",", "list", ")", "or", "isinstance", "(", "fp", ",", "tuple", ")", ":", "for", "f", "in", "fp", ":", "yield", "f", "continue", "ma", "=", "isinstance", "(", "fp", ",", "str", ")", "and", "re", ".", "compile", "(", "\"(!\\s*|)re:(.*)\"", ")", ".", "match", "(", "fp", ")", "if", "isinstance", "(", "fp", ",", "type", "(", "re", ".", "compile", "(", "''", ")", ")", ")", "or", "ma", ":", "neg", "=", "False", "if", "ma", ":", "mag", "=", "ma", ".", "groups", "(", ")", "fp", "=", "re", ".", "compile", "(", "mag", "[", "1", "]", ")", "neg", "=", "bool", "(", "mag", "[", "0", "]", ")", "for", "f", "in", "list", "(", "fmap", ".", "keys", "(", ")", ")", "+", "[", "'has_'", "+", "a", "for", "a", "in", "Fuse", ".", "_attrs", "]", ":", "if", "neg", "!=", "bool", "(", "re", ".", "search", "(", "fp", ",", "f", ")", ")", ":", "yield", "f", "continue", "ma", "=", "re", ".", "compile", "(", "\"has_(.*)\"", ")", ".", "match", "(", "fp", ")", "if", "ma", "and", "ma", ".", "groups", "(", ")", "[", "0", "]", "in", "Fuse", ".", "_attrs", "and", "not", "fp", "in", "fmap", ":", "yield", "21", "continue", "yield", "fmap", "[", "fp", "]", "maxva", "=", "[", "0", "]", "while", "feas", ":", "feas", "=", "set", "(", "resolve", "(", "feas", ",", "maxva", ")", ")", "return", "maxva", "[", "0", "]" ]
Get info about the FUSE API version needed for the support of some features. This function takes a variable number of feature patterns. A feature pattern is either: - an integer (directly referring to a FUSE API version number) - a built-in feature specifier string (meaning defined by dictionary) - a string of the form ``has_foo``, where ``foo`` is a filesystem method (refers to the API version where the method has been introduced) - a list/tuple of other feature patterns (matches each of its members) - a regexp (meant to be matched against the builtins plus ``has_foo`` patterns; can also be given by a string of the from "re:*") - a negated regexp (can be given by a string of the form "!re:*") If called with no arguments, then the list of builtins is returned, mapped to their meaning. Otherwise the function returns the smallest FUSE API version number which has all the matching features. Builtin specifiers worth to explicit mention: - ``stateful_files``: you want to use custom filehandles (eg. a file class). - ``*``: you want all features. - while ``has_foo`` makes sense for all filesystem method ``foo``, some of these can be found among the builtins, too (the ones which can be handled by the general rule). specifiers like ``has_foo`` refer to requirement that the library knows of the fs method ``foo``.
[ "Get", "info", "about", "the", "FUSE", "API", "version", "needed", "for", "the", "support", "of", "some", "features", "." ]
2c088b657ad71faca6975b456f80b7d2c2cea2a7
https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L502-L593
11,423
libfuse/python-fuse
fuse.py
FuseArgs.assemble
def assemble(self): """Mangle self into an argument array""" self.canonify() args = [sys.argv and sys.argv[0] or "python"] if self.mountpoint: args.append(self.mountpoint) for m, v in self.modifiers.items(): if v: args.append(self.fuse_modifiers[m]) opta = [] for o, v in self.optdict.items(): opta.append(o + '=' + v) opta.extend(self.optlist) if opta: args.append("-o" + ",".join(opta)) return args
python
def assemble(self): """Mangle self into an argument array""" self.canonify() args = [sys.argv and sys.argv[0] or "python"] if self.mountpoint: args.append(self.mountpoint) for m, v in self.modifiers.items(): if v: args.append(self.fuse_modifiers[m]) opta = [] for o, v in self.optdict.items(): opta.append(o + '=' + v) opta.extend(self.optlist) if opta: args.append("-o" + ",".join(opta)) return args
[ "def", "assemble", "(", "self", ")", ":", "self", ".", "canonify", "(", ")", "args", "=", "[", "sys", ".", "argv", "and", "sys", ".", "argv", "[", "0", "]", "or", "\"python\"", "]", "if", "self", ".", "mountpoint", ":", "args", ".", "append", "(", "self", ".", "mountpoint", ")", "for", "m", ",", "v", "in", "self", ".", "modifiers", ".", "items", "(", ")", ":", "if", "v", ":", "args", ".", "append", "(", "self", ".", "fuse_modifiers", "[", "m", "]", ")", "opta", "=", "[", "]", "for", "o", ",", "v", "in", "self", ".", "optdict", ".", "items", "(", ")", ":", "opta", ".", "append", "(", "o", "+", "'='", "+", "v", ")", "opta", ".", "extend", "(", "self", ".", "optlist", ")", "if", "opta", ":", "args", ".", "append", "(", "\"-o\"", "+", "\",\"", ".", "join", "(", "opta", ")", ")", "return", "args" ]
Mangle self into an argument array
[ "Mangle", "self", "into", "an", "argument", "array" ]
2c088b657ad71faca6975b456f80b7d2c2cea2a7
https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L129-L148
11,424
libfuse/python-fuse
fuse.py
Fuse.parse
def parse(self, *args, **kw): """Parse command line, fill `fuse_args` attribute.""" ev = 'errex' in kw and kw.pop('errex') if ev and not isinstance(ev, int): raise TypeError("error exit value should be an integer") try: self.cmdline = self.parser.parse_args(*args, **kw) except OptParseError: if ev: sys.exit(ev) raise return self.fuse_args
python
def parse(self, *args, **kw): """Parse command line, fill `fuse_args` attribute.""" ev = 'errex' in kw and kw.pop('errex') if ev and not isinstance(ev, int): raise TypeError("error exit value should be an integer") try: self.cmdline = self.parser.parse_args(*args, **kw) except OptParseError: if ev: sys.exit(ev) raise return self.fuse_args
[ "def", "parse", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "ev", "=", "'errex'", "in", "kw", "and", "kw", ".", "pop", "(", "'errex'", ")", "if", "ev", "and", "not", "isinstance", "(", "ev", ",", "int", ")", ":", "raise", "TypeError", "(", "\"error exit value should be an integer\"", ")", "try", ":", "self", ".", "cmdline", "=", "self", ".", "parser", ".", "parse_args", "(", "*", "args", ",", "*", "*", "kw", ")", "except", "OptParseError", ":", "if", "ev", ":", "sys", ".", "exit", "(", "ev", ")", "raise", "return", "self", ".", "fuse_args" ]
Parse command line, fill `fuse_args` attribute.
[ "Parse", "command", "line", "fill", "fuse_args", "attribute", "." ]
2c088b657ad71faca6975b456f80b7d2c2cea2a7
https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L714-L728
11,425
libfuse/python-fuse
fuse.py
Fuse.main
def main(self, args=None): """Enter filesystem service loop.""" if get_compat_0_1(): args = self.main_0_1_preamble() d = {'multithreaded': self.multithreaded and 1 or 0} d['fuse_args'] = args or self.fuse_args.assemble() for t in 'file_class', 'dir_class': if hasattr(self, t): getattr(self.methproxy, 'set_' + t)(getattr(self,t)) for a in self._attrs: b = a if get_compat_0_1() and a in self.compatmap: b = self.compatmap[a] if hasattr(self, b): c = '' if get_compat_0_1() and hasattr(self, a + '_compat_0_1'): c = '_compat_0_1' d[a] = ErrnoWrapper(self.lowwrap(a + c)) try: main(**d) except FuseError: if args or self.fuse_args.mount_expected(): raise
python
def main(self, args=None): """Enter filesystem service loop.""" if get_compat_0_1(): args = self.main_0_1_preamble() d = {'multithreaded': self.multithreaded and 1 or 0} d['fuse_args'] = args or self.fuse_args.assemble() for t in 'file_class', 'dir_class': if hasattr(self, t): getattr(self.methproxy, 'set_' + t)(getattr(self,t)) for a in self._attrs: b = a if get_compat_0_1() and a in self.compatmap: b = self.compatmap[a] if hasattr(self, b): c = '' if get_compat_0_1() and hasattr(self, a + '_compat_0_1'): c = '_compat_0_1' d[a] = ErrnoWrapper(self.lowwrap(a + c)) try: main(**d) except FuseError: if args or self.fuse_args.mount_expected(): raise
[ "def", "main", "(", "self", ",", "args", "=", "None", ")", ":", "if", "get_compat_0_1", "(", ")", ":", "args", "=", "self", ".", "main_0_1_preamble", "(", ")", "d", "=", "{", "'multithreaded'", ":", "self", ".", "multithreaded", "and", "1", "or", "0", "}", "d", "[", "'fuse_args'", "]", "=", "args", "or", "self", ".", "fuse_args", ".", "assemble", "(", ")", "for", "t", "in", "'file_class'", ",", "'dir_class'", ":", "if", "hasattr", "(", "self", ",", "t", ")", ":", "getattr", "(", "self", ".", "methproxy", ",", "'set_'", "+", "t", ")", "(", "getattr", "(", "self", ",", "t", ")", ")", "for", "a", "in", "self", ".", "_attrs", ":", "b", "=", "a", "if", "get_compat_0_1", "(", ")", "and", "a", "in", "self", ".", "compatmap", ":", "b", "=", "self", ".", "compatmap", "[", "a", "]", "if", "hasattr", "(", "self", ",", "b", ")", ":", "c", "=", "''", "if", "get_compat_0_1", "(", ")", "and", "hasattr", "(", "self", ",", "a", "+", "'_compat_0_1'", ")", ":", "c", "=", "'_compat_0_1'", "d", "[", "a", "]", "=", "ErrnoWrapper", "(", "self", ".", "lowwrap", "(", "a", "+", "c", ")", ")", "try", ":", "main", "(", "*", "*", "d", ")", "except", "FuseError", ":", "if", "args", "or", "self", ".", "fuse_args", ".", "mount_expected", "(", ")", ":", "raise" ]
Enter filesystem service loop.
[ "Enter", "filesystem", "service", "loop", "." ]
2c088b657ad71faca6975b456f80b7d2c2cea2a7
https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L730-L757
11,426
libfuse/python-fuse
fuse.py
Fuse.fuseoptref
def fuseoptref(cls): """ Find out which options are recognized by the library. Result is a `FuseArgs` instance with the list of supported options, suitable for passing on to the `filter` method of another `FuseArgs` instance. """ import os, re pr, pw = os.pipe() pid = os.fork() if pid == 0: os.dup2(pw, 2) os.close(pr) fh = cls() fh.fuse_args = FuseArgs() fh.fuse_args.setmod('showhelp') fh.main() sys.exit() os.close(pw) fa = FuseArgs() ore = re.compile("-o\s+([\w\[\]]+(?:=\w+)?)") fpr = os.fdopen(pr) for l in fpr: m = ore.search(l) if m: o = m.groups()[0] oa = [o] # try to catch two-in-one options (like "[no]foo") opa = o.split("[") if len(opa) == 2: o1, ox = opa oxpa = ox.split("]") if len(oxpa) == 2: oo, o2 = oxpa oa = [o1 + o2, o1 + oo + o2] for o in oa: fa.add(o) fpr.close() return fa
python
def fuseoptref(cls): """ Find out which options are recognized by the library. Result is a `FuseArgs` instance with the list of supported options, suitable for passing on to the `filter` method of another `FuseArgs` instance. """ import os, re pr, pw = os.pipe() pid = os.fork() if pid == 0: os.dup2(pw, 2) os.close(pr) fh = cls() fh.fuse_args = FuseArgs() fh.fuse_args.setmod('showhelp') fh.main() sys.exit() os.close(pw) fa = FuseArgs() ore = re.compile("-o\s+([\w\[\]]+(?:=\w+)?)") fpr = os.fdopen(pr) for l in fpr: m = ore.search(l) if m: o = m.groups()[0] oa = [o] # try to catch two-in-one options (like "[no]foo") opa = o.split("[") if len(opa) == 2: o1, ox = opa oxpa = ox.split("]") if len(oxpa) == 2: oo, o2 = oxpa oa = [o1 + o2, o1 + oo + o2] for o in oa: fa.add(o) fpr.close() return fa
[ "def", "fuseoptref", "(", "cls", ")", ":", "import", "os", ",", "re", "pr", ",", "pw", "=", "os", ".", "pipe", "(", ")", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", "==", "0", ":", "os", ".", "dup2", "(", "pw", ",", "2", ")", "os", ".", "close", "(", "pr", ")", "fh", "=", "cls", "(", ")", "fh", ".", "fuse_args", "=", "FuseArgs", "(", ")", "fh", ".", "fuse_args", ".", "setmod", "(", "'showhelp'", ")", "fh", ".", "main", "(", ")", "sys", ".", "exit", "(", ")", "os", ".", "close", "(", "pw", ")", "fa", "=", "FuseArgs", "(", ")", "ore", "=", "re", ".", "compile", "(", "\"-o\\s+([\\w\\[\\]]+(?:=\\w+)?)\"", ")", "fpr", "=", "os", ".", "fdopen", "(", "pr", ")", "for", "l", "in", "fpr", ":", "m", "=", "ore", ".", "search", "(", "l", ")", "if", "m", ":", "o", "=", "m", ".", "groups", "(", ")", "[", "0", "]", "oa", "=", "[", "o", "]", "# try to catch two-in-one options (like \"[no]foo\")", "opa", "=", "o", ".", "split", "(", "\"[\"", ")", "if", "len", "(", "opa", ")", "==", "2", ":", "o1", ",", "ox", "=", "opa", "oxpa", "=", "ox", ".", "split", "(", "\"]\"", ")", "if", "len", "(", "oxpa", ")", "==", "2", ":", "oo", ",", "o2", "=", "oxpa", "oa", "=", "[", "o1", "+", "o2", ",", "o1", "+", "oo", "+", "o2", "]", "for", "o", "in", "oa", ":", "fa", ".", "add", "(", "o", ")", "fpr", ".", "close", "(", ")", "return", "fa" ]
Find out which options are recognized by the library. Result is a `FuseArgs` instance with the list of supported options, suitable for passing on to the `filter` method of another `FuseArgs` instance.
[ "Find", "out", "which", "options", "are", "recognized", "by", "the", "library", ".", "Result", "is", "a", "FuseArgs", "instance", "with", "the", "list", "of", "supported", "options", "suitable", "for", "passing", "on", "to", "the", "filter", "method", "of", "another", "FuseArgs", "instance", "." ]
2c088b657ad71faca6975b456f80b7d2c2cea2a7
https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuse.py#L796-L840
11,427
libfuse/python-fuse
fuseparts/subbedopts.py
SubOptsHive.filter
def filter(self, other): """ Throw away those options which are not in the other one. Returns a new instance with the rejected options. """ self.canonify() other.canonify() rej = self.__class__() rej.optlist = self.optlist.difference(other.optlist) self.optlist.difference_update(rej.optlist) for x in self.optdict.copy(): if x not in other.optdict: self.optdict.pop(x) rej.optdict[x] = None return rej
python
def filter(self, other): """ Throw away those options which are not in the other one. Returns a new instance with the rejected options. """ self.canonify() other.canonify() rej = self.__class__() rej.optlist = self.optlist.difference(other.optlist) self.optlist.difference_update(rej.optlist) for x in self.optdict.copy(): if x not in other.optdict: self.optdict.pop(x) rej.optdict[x] = None return rej
[ "def", "filter", "(", "self", ",", "other", ")", ":", "self", ".", "canonify", "(", ")", "other", ".", "canonify", "(", ")", "rej", "=", "self", ".", "__class__", "(", ")", "rej", ".", "optlist", "=", "self", ".", "optlist", ".", "difference", "(", "other", ".", "optlist", ")", "self", ".", "optlist", ".", "difference_update", "(", "rej", ".", "optlist", ")", "for", "x", "in", "self", ".", "optdict", ".", "copy", "(", ")", ":", "if", "x", "not", "in", "other", ".", "optdict", ":", "self", ".", "optdict", ".", "pop", "(", "x", ")", "rej", ".", "optdict", "[", "x", "]", "=", "None", "return", "rej" ]
Throw away those options which are not in the other one. Returns a new instance with the rejected options.
[ "Throw", "away", "those", "options", "which", "are", "not", "in", "the", "other", "one", ".", "Returns", "a", "new", "instance", "with", "the", "rejected", "options", "." ]
2c088b657ad71faca6975b456f80b7d2c2cea2a7
https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuseparts/subbedopts.py#L59-L76
11,428
libfuse/python-fuse
fuseparts/subbedopts.py
SubOptsHive.add
def add(self, opt, val=None): """Add a suboption.""" ov = opt.split('=', 1) o = ov[0] v = len(ov) > 1 and ov[1] or None if (v): if val != None: raise AttributeError("ambiguous option value") val = v if val == False: return if val in (None, True): self.optlist.add(o) else: self.optdict[o] = val
python
def add(self, opt, val=None): """Add a suboption.""" ov = opt.split('=', 1) o = ov[0] v = len(ov) > 1 and ov[1] or None if (v): if val != None: raise AttributeError("ambiguous option value") val = v if val == False: return if val in (None, True): self.optlist.add(o) else: self.optdict[o] = val
[ "def", "add", "(", "self", ",", "opt", ",", "val", "=", "None", ")", ":", "ov", "=", "opt", ".", "split", "(", "'='", ",", "1", ")", "o", "=", "ov", "[", "0", "]", "v", "=", "len", "(", "ov", ")", ">", "1", "and", "ov", "[", "1", "]", "or", "None", "if", "(", "v", ")", ":", "if", "val", "!=", "None", ":", "raise", "AttributeError", "(", "\"ambiguous option value\"", ")", "val", "=", "v", "if", "val", "==", "False", ":", "return", "if", "val", "in", "(", "None", ",", "True", ")", ":", "self", ".", "optlist", ".", "add", "(", "o", ")", "else", ":", "self", ".", "optdict", "[", "o", "]", "=", "val" ]
Add a suboption.
[ "Add", "a", "suboption", "." ]
2c088b657ad71faca6975b456f80b7d2c2cea2a7
https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuseparts/subbedopts.py#L78-L96
11,429
libfuse/python-fuse
fuseparts/subbedopts.py
SubbedOpt.register_sub
def register_sub(self, o): """Register argument a suboption for `self`.""" if o.subopt in self.subopt_map: raise OptionConflictError( "conflicting suboption handlers for `%s'" % o.subopt, o) self.subopt_map[o.subopt] = o
python
def register_sub(self, o): """Register argument a suboption for `self`.""" if o.subopt in self.subopt_map: raise OptionConflictError( "conflicting suboption handlers for `%s'" % o.subopt, o) self.subopt_map[o.subopt] = o
[ "def", "register_sub", "(", "self", ",", "o", ")", ":", "if", "o", ".", "subopt", "in", "self", ".", "subopt_map", ":", "raise", "OptionConflictError", "(", "\"conflicting suboption handlers for `%s'\"", "%", "o", ".", "subopt", ",", "o", ")", "self", ".", "subopt_map", "[", "o", ".", "subopt", "]", "=", "o" ]
Register argument a suboption for `self`.
[ "Register", "argument", "a", "suboption", "for", "self", "." ]
2c088b657ad71faca6975b456f80b7d2c2cea2a7
https://github.com/libfuse/python-fuse/blob/2c088b657ad71faca6975b456f80b7d2c2cea2a7/fuseparts/subbedopts.py#L170-L177
11,430
tasdikrahman/vocabulary
vocabulary/vocabulary.py
Vocabulary.__parse_content
def __parse_content(tuc_content, content_to_be_parsed): """ parses the passed "tuc_content" for - meanings - synonym received by querying the glosbe API Called by - meaning() - synonym() :param tuc_content: passed on the calling Function. A list object :param content_to_be_parsed: data to be parsed from. Whether to parse "tuc" for meanings or synonyms :returns: returns a list which contains the parsed data from "tuc" """ initial_parsed_content = {} i = 0 for content_dict in tuc_content: if content_to_be_parsed in content_dict.keys(): contents_raw = content_dict[content_to_be_parsed] if content_to_be_parsed == "phrase": # for 'phrase', 'contents_raw' is a dictionary initial_parsed_content[i] = contents_raw['text'] i += 1 elif content_to_be_parsed == "meanings": # for 'meanings', 'contents_raw' is a list for meaning_content in contents_raw: initial_parsed_content[i] = meaning_content['text'] i += 1 final_parsed_content = {} # removing duplicates(if any) from the dictionary for key, value in initial_parsed_content.items(): if value not in final_parsed_content.values(): final_parsed_content[key] = value # calling __clean_dict formatted_list = Vocabulary.__clean_dict(final_parsed_content) return formatted_list
python
def __parse_content(tuc_content, content_to_be_parsed): """ parses the passed "tuc_content" for - meanings - synonym received by querying the glosbe API Called by - meaning() - synonym() :param tuc_content: passed on the calling Function. A list object :param content_to_be_parsed: data to be parsed from. Whether to parse "tuc" for meanings or synonyms :returns: returns a list which contains the parsed data from "tuc" """ initial_parsed_content = {} i = 0 for content_dict in tuc_content: if content_to_be_parsed in content_dict.keys(): contents_raw = content_dict[content_to_be_parsed] if content_to_be_parsed == "phrase": # for 'phrase', 'contents_raw' is a dictionary initial_parsed_content[i] = contents_raw['text'] i += 1 elif content_to_be_parsed == "meanings": # for 'meanings', 'contents_raw' is a list for meaning_content in contents_raw: initial_parsed_content[i] = meaning_content['text'] i += 1 final_parsed_content = {} # removing duplicates(if any) from the dictionary for key, value in initial_parsed_content.items(): if value not in final_parsed_content.values(): final_parsed_content[key] = value # calling __clean_dict formatted_list = Vocabulary.__clean_dict(final_parsed_content) return formatted_list
[ "def", "__parse_content", "(", "tuc_content", ",", "content_to_be_parsed", ")", ":", "initial_parsed_content", "=", "{", "}", "i", "=", "0", "for", "content_dict", "in", "tuc_content", ":", "if", "content_to_be_parsed", "in", "content_dict", ".", "keys", "(", ")", ":", "contents_raw", "=", "content_dict", "[", "content_to_be_parsed", "]", "if", "content_to_be_parsed", "==", "\"phrase\"", ":", "# for 'phrase', 'contents_raw' is a dictionary", "initial_parsed_content", "[", "i", "]", "=", "contents_raw", "[", "'text'", "]", "i", "+=", "1", "elif", "content_to_be_parsed", "==", "\"meanings\"", ":", "# for 'meanings', 'contents_raw' is a list", "for", "meaning_content", "in", "contents_raw", ":", "initial_parsed_content", "[", "i", "]", "=", "meaning_content", "[", "'text'", "]", "i", "+=", "1", "final_parsed_content", "=", "{", "}", "# removing duplicates(if any) from the dictionary", "for", "key", ",", "value", "in", "initial_parsed_content", ".", "items", "(", ")", ":", "if", "value", "not", "in", "final_parsed_content", ".", "values", "(", ")", ":", "final_parsed_content", "[", "key", "]", "=", "value", "# calling __clean_dict", "formatted_list", "=", "Vocabulary", ".", "__clean_dict", "(", "final_parsed_content", ")", "return", "formatted_list" ]
parses the passed "tuc_content" for - meanings - synonym received by querying the glosbe API Called by - meaning() - synonym() :param tuc_content: passed on the calling Function. A list object :param content_to_be_parsed: data to be parsed from. Whether to parse "tuc" for meanings or synonyms :returns: returns a list which contains the parsed data from "tuc"
[ "parses", "the", "passed", "tuc_content", "for", "-", "meanings", "-", "synonym", "received", "by", "querying", "the", "glosbe", "API" ]
54403c5981af25dc3457796b57048ae27f09e9be
https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L96-L136
11,431
tasdikrahman/vocabulary
vocabulary/vocabulary.py
Vocabulary.meaning
def meaning(phrase, source_lang="en", dest_lang="en", format="json"): """ make calls to the glosbe API :param phrase: word for which meaning is to be found :param source_lang: Defaults to : "en" :param dest_lang: Defaults to : "en" For eg: "fr" for french :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase """ base_url = Vocabulary.__get_api_link("glosbe") url = base_url.format(word=phrase, source_lang=source_lang, dest_lang=dest_lang) json_obj = Vocabulary.__return_json(url) if json_obj: try: tuc_content = json_obj["tuc"] # "tuc_content" is a "list" except KeyError: return False '''get meanings''' meanings_list = Vocabulary.__parse_content(tuc_content, "meanings") return Response().respond(meanings_list, format) # print(meanings_list) # return json.dumps(meanings_list) else: return False
python
def meaning(phrase, source_lang="en", dest_lang="en", format="json"): """ make calls to the glosbe API :param phrase: word for which meaning is to be found :param source_lang: Defaults to : "en" :param dest_lang: Defaults to : "en" For eg: "fr" for french :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase """ base_url = Vocabulary.__get_api_link("glosbe") url = base_url.format(word=phrase, source_lang=source_lang, dest_lang=dest_lang) json_obj = Vocabulary.__return_json(url) if json_obj: try: tuc_content = json_obj["tuc"] # "tuc_content" is a "list" except KeyError: return False '''get meanings''' meanings_list = Vocabulary.__parse_content(tuc_content, "meanings") return Response().respond(meanings_list, format) # print(meanings_list) # return json.dumps(meanings_list) else: return False
[ "def", "meaning", "(", "phrase", ",", "source_lang", "=", "\"en\"", ",", "dest_lang", "=", "\"en\"", ",", "format", "=", "\"json\"", ")", ":", "base_url", "=", "Vocabulary", ".", "__get_api_link", "(", "\"glosbe\"", ")", "url", "=", "base_url", ".", "format", "(", "word", "=", "phrase", ",", "source_lang", "=", "source_lang", ",", "dest_lang", "=", "dest_lang", ")", "json_obj", "=", "Vocabulary", ".", "__return_json", "(", "url", ")", "if", "json_obj", ":", "try", ":", "tuc_content", "=", "json_obj", "[", "\"tuc\"", "]", "# \"tuc_content\" is a \"list\"", "except", "KeyError", ":", "return", "False", "'''get meanings'''", "meanings_list", "=", "Vocabulary", ".", "__parse_content", "(", "tuc_content", ",", "\"meanings\"", ")", "return", "Response", "(", ")", ".", "respond", "(", "meanings_list", ",", "format", ")", "# print(meanings_list)", "# return json.dumps(meanings_list)", "else", ":", "return", "False" ]
make calls to the glosbe API :param phrase: word for which meaning is to be found :param source_lang: Defaults to : "en" :param dest_lang: Defaults to : "en" For eg: "fr" for french :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase
[ "make", "calls", "to", "the", "glosbe", "API" ]
54403c5981af25dc3457796b57048ae27f09e9be
https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L161-L186
11,432
tasdikrahman/vocabulary
vocabulary/vocabulary.py
Vocabulary.part_of_speech
def part_of_speech(phrase, format='json'): """ querrying Wordnik's API for knowing whether the word is a noun, adjective and the like :params phrase: word for which part_of_speech is to be found :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase """ # We get a list object as a return value from the Wordnik API base_url = Vocabulary.__get_api_link("wordnik") url = base_url.format(word=phrase.lower(), action="definitions") json_obj = Vocabulary.__return_json(url) if not json_obj: return False result = [] for idx, obj in enumerate(json_obj): text = obj.get('partOfSpeech', None) example = obj.get('text', None) result.append({"seq": idx, "text": text, "example": example}) return Response().respond(result, format)
python
def part_of_speech(phrase, format='json'): """ querrying Wordnik's API for knowing whether the word is a noun, adjective and the like :params phrase: word for which part_of_speech is to be found :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase """ # We get a list object as a return value from the Wordnik API base_url = Vocabulary.__get_api_link("wordnik") url = base_url.format(word=phrase.lower(), action="definitions") json_obj = Vocabulary.__return_json(url) if not json_obj: return False result = [] for idx, obj in enumerate(json_obj): text = obj.get('partOfSpeech', None) example = obj.get('text', None) result.append({"seq": idx, "text": text, "example": example}) return Response().respond(result, format)
[ "def", "part_of_speech", "(", "phrase", ",", "format", "=", "'json'", ")", ":", "# We get a list object as a return value from the Wordnik API", "base_url", "=", "Vocabulary", ".", "__get_api_link", "(", "\"wordnik\"", ")", "url", "=", "base_url", ".", "format", "(", "word", "=", "phrase", ".", "lower", "(", ")", ",", "action", "=", "\"definitions\"", ")", "json_obj", "=", "Vocabulary", ".", "__return_json", "(", "url", ")", "if", "not", "json_obj", ":", "return", "False", "result", "=", "[", "]", "for", "idx", ",", "obj", "in", "enumerate", "(", "json_obj", ")", ":", "text", "=", "obj", ".", "get", "(", "'partOfSpeech'", ",", "None", ")", "example", "=", "obj", ".", "get", "(", "'text'", ",", "None", ")", "result", ".", "append", "(", "{", "\"seq\"", ":", "idx", ",", "\"text\"", ":", "text", ",", "\"example\"", ":", "example", "}", ")", "return", "Response", "(", ")", ".", "respond", "(", "result", ",", "format", ")" ]
querrying Wordnik's API for knowing whether the word is a noun, adjective and the like :params phrase: word for which part_of_speech is to be found :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase
[ "querrying", "Wordnik", "s", "API", "for", "knowing", "whether", "the", "word", "is", "a", "noun", "adjective", "and", "the", "like" ]
54403c5981af25dc3457796b57048ae27f09e9be
https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L304-L326
11,433
tasdikrahman/vocabulary
vocabulary/vocabulary.py
Vocabulary.usage_example
def usage_example(phrase, format='json'): """Takes the source phrase and queries it to the urbandictionary API :params phrase: word for which usage_example is to be found :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase """ base_url = Vocabulary.__get_api_link("urbandict") url = base_url.format(action="define", word=phrase) word_examples = {} json_obj = Vocabulary.__return_json(url) if json_obj: examples_list = json_obj["list"] for i, example in enumerate(examples_list): if example["thumbs_up"] > example["thumbs_down"]: word_examples[i] = example["example"].replace("\r", "").replace("\n", "") if word_examples: # reforamatting "word_examples" using "__clean_dict()" # return json.dumps(Vocabulary.__clean_dict(word_examples)) # return Vocabulary.__clean_dict(word_examples) return Response().respond(Vocabulary.__clean_dict(word_examples), format) else: return False else: return False
python
def usage_example(phrase, format='json'): """Takes the source phrase and queries it to the urbandictionary API :params phrase: word for which usage_example is to be found :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase """ base_url = Vocabulary.__get_api_link("urbandict") url = base_url.format(action="define", word=phrase) word_examples = {} json_obj = Vocabulary.__return_json(url) if json_obj: examples_list = json_obj["list"] for i, example in enumerate(examples_list): if example["thumbs_up"] > example["thumbs_down"]: word_examples[i] = example["example"].replace("\r", "").replace("\n", "") if word_examples: # reforamatting "word_examples" using "__clean_dict()" # return json.dumps(Vocabulary.__clean_dict(word_examples)) # return Vocabulary.__clean_dict(word_examples) return Response().respond(Vocabulary.__clean_dict(word_examples), format) else: return False else: return False
[ "def", "usage_example", "(", "phrase", ",", "format", "=", "'json'", ")", ":", "base_url", "=", "Vocabulary", ".", "__get_api_link", "(", "\"urbandict\"", ")", "url", "=", "base_url", ".", "format", "(", "action", "=", "\"define\"", ",", "word", "=", "phrase", ")", "word_examples", "=", "{", "}", "json_obj", "=", "Vocabulary", ".", "__return_json", "(", "url", ")", "if", "json_obj", ":", "examples_list", "=", "json_obj", "[", "\"list\"", "]", "for", "i", ",", "example", "in", "enumerate", "(", "examples_list", ")", ":", "if", "example", "[", "\"thumbs_up\"", "]", ">", "example", "[", "\"thumbs_down\"", "]", ":", "word_examples", "[", "i", "]", "=", "example", "[", "\"example\"", "]", ".", "replace", "(", "\"\\r\"", ",", "\"\"", ")", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", "if", "word_examples", ":", "# reforamatting \"word_examples\" using \"__clean_dict()\"", "# return json.dumps(Vocabulary.__clean_dict(word_examples))", "# return Vocabulary.__clean_dict(word_examples)", "return", "Response", "(", ")", ".", "respond", "(", "Vocabulary", ".", "__clean_dict", "(", "word_examples", ")", ",", "format", ")", "else", ":", "return", "False", "else", ":", "return", "False" ]
Takes the source phrase and queries it to the urbandictionary API :params phrase: word for which usage_example is to be found :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase
[ "Takes", "the", "source", "phrase", "and", "queries", "it", "to", "the", "urbandictionary", "API" ]
54403c5981af25dc3457796b57048ae27f09e9be
https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L329-L353
11,434
tasdikrahman/vocabulary
vocabulary/vocabulary.py
Vocabulary.pronunciation
def pronunciation(phrase, format='json'): """ Gets the pronunciation from the Wordnik API :params phrase: word for which pronunciation is to be found :param format: response structure type. Defaults to: "json" :returns: returns a list object, False if invalid phrase """ base_url = Vocabulary.__get_api_link("wordnik") url = base_url.format(word=phrase.lower(), action="pronunciations") json_obj = Vocabulary.__return_json(url) if json_obj: ''' Refer : http://stackoverflow.com/q/18337407/3834059 ''' ## TODO: Fix the unicode issue mentioned in ## https://github.com/tasdikrahman/vocabulary#181known-issues for idx, obj in enumerate(json_obj): obj['seq'] = idx if sys.version_info[:2] <= (2, 7): ## python2 # return json_obj return Response().respond(json_obj, format) else: # python3 # return json.loads(json.dumps(json_obj, ensure_ascii=False)) return Response().respond(json_obj, format) else: return False
python
def pronunciation(phrase, format='json'): """ Gets the pronunciation from the Wordnik API :params phrase: word for which pronunciation is to be found :param format: response structure type. Defaults to: "json" :returns: returns a list object, False if invalid phrase """ base_url = Vocabulary.__get_api_link("wordnik") url = base_url.format(word=phrase.lower(), action="pronunciations") json_obj = Vocabulary.__return_json(url) if json_obj: ''' Refer : http://stackoverflow.com/q/18337407/3834059 ''' ## TODO: Fix the unicode issue mentioned in ## https://github.com/tasdikrahman/vocabulary#181known-issues for idx, obj in enumerate(json_obj): obj['seq'] = idx if sys.version_info[:2] <= (2, 7): ## python2 # return json_obj return Response().respond(json_obj, format) else: # python3 # return json.loads(json.dumps(json_obj, ensure_ascii=False)) return Response().respond(json_obj, format) else: return False
[ "def", "pronunciation", "(", "phrase", ",", "format", "=", "'json'", ")", ":", "base_url", "=", "Vocabulary", ".", "__get_api_link", "(", "\"wordnik\"", ")", "url", "=", "base_url", ".", "format", "(", "word", "=", "phrase", ".", "lower", "(", ")", ",", "action", "=", "\"pronunciations\"", ")", "json_obj", "=", "Vocabulary", ".", "__return_json", "(", "url", ")", "if", "json_obj", ":", "'''\n Refer : http://stackoverflow.com/q/18337407/3834059\n '''", "## TODO: Fix the unicode issue mentioned in", "## https://github.com/tasdikrahman/vocabulary#181known-issues", "for", "idx", ",", "obj", "in", "enumerate", "(", "json_obj", ")", ":", "obj", "[", "'seq'", "]", "=", "idx", "if", "sys", ".", "version_info", "[", ":", "2", "]", "<=", "(", "2", ",", "7", ")", ":", "## python2", "# return json_obj", "return", "Response", "(", ")", ".", "respond", "(", "json_obj", ",", "format", ")", "else", ":", "# python3", "# return json.loads(json.dumps(json_obj, ensure_ascii=False))", "return", "Response", "(", ")", ".", "respond", "(", "json_obj", ",", "format", ")", "else", ":", "return", "False" ]
Gets the pronunciation from the Wordnik API :params phrase: word for which pronunciation is to be found :param format: response structure type. Defaults to: "json" :returns: returns a list object, False if invalid phrase
[ "Gets", "the", "pronunciation", "from", "the", "Wordnik", "API" ]
54403c5981af25dc3457796b57048ae27f09e9be
https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L356-L383
11,435
tasdikrahman/vocabulary
vocabulary/vocabulary.py
Vocabulary.hyphenation
def hyphenation(phrase, format='json'): """ Returns back the stress points in the "phrase" passed :param phrase: word for which hyphenation is to be found :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase """ base_url = Vocabulary.__get_api_link("wordnik") url = base_url.format(word=phrase.lower(), action="hyphenation") json_obj = Vocabulary.__return_json(url) if json_obj: # return json.dumps(json_obj) # return json_obj return Response().respond(json_obj, format) else: return False
python
def hyphenation(phrase, format='json'): """ Returns back the stress points in the "phrase" passed :param phrase: word for which hyphenation is to be found :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase """ base_url = Vocabulary.__get_api_link("wordnik") url = base_url.format(word=phrase.lower(), action="hyphenation") json_obj = Vocabulary.__return_json(url) if json_obj: # return json.dumps(json_obj) # return json_obj return Response().respond(json_obj, format) else: return False
[ "def", "hyphenation", "(", "phrase", ",", "format", "=", "'json'", ")", ":", "base_url", "=", "Vocabulary", ".", "__get_api_link", "(", "\"wordnik\"", ")", "url", "=", "base_url", ".", "format", "(", "word", "=", "phrase", ".", "lower", "(", ")", ",", "action", "=", "\"hyphenation\"", ")", "json_obj", "=", "Vocabulary", ".", "__return_json", "(", "url", ")", "if", "json_obj", ":", "# return json.dumps(json_obj)", "# return json_obj", "return", "Response", "(", ")", ".", "respond", "(", "json_obj", ",", "format", ")", "else", ":", "return", "False" ]
Returns back the stress points in the "phrase" passed :param phrase: word for which hyphenation is to be found :param format: response structure type. Defaults to: "json" :returns: returns a json object as str, False if invalid phrase
[ "Returns", "back", "the", "stress", "points", "in", "the", "phrase", "passed" ]
54403c5981af25dc3457796b57048ae27f09e9be
https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/vocabulary.py#L386-L402
11,436
tasdikrahman/vocabulary
vocabulary/responselib.py
Response.__respond_with_dict
def __respond_with_dict(self, data): """ Builds a python dictionary from a json object :param data: the json object :returns: a nested dictionary """ response = {} if isinstance(data, list): temp_data, data = data, {} for key, value in enumerate(temp_data): data[key] = value data.pop('seq', None) for index, item in data.items(): values = item if isinstance(item, list) or isinstance(item, dict): values = self.__respond_with_dict(item) if isinstance(values, dict) and len(values) == 1: (key, values), = values.items() response[index] = values return response
python
def __respond_with_dict(self, data): """ Builds a python dictionary from a json object :param data: the json object :returns: a nested dictionary """ response = {} if isinstance(data, list): temp_data, data = data, {} for key, value in enumerate(temp_data): data[key] = value data.pop('seq', None) for index, item in data.items(): values = item if isinstance(item, list) or isinstance(item, dict): values = self.__respond_with_dict(item) if isinstance(values, dict) and len(values) == 1: (key, values), = values.items() response[index] = values return response
[ "def", "__respond_with_dict", "(", "self", ",", "data", ")", ":", "response", "=", "{", "}", "if", "isinstance", "(", "data", ",", "list", ")", ":", "temp_data", ",", "data", "=", "data", ",", "{", "}", "for", "key", ",", "value", "in", "enumerate", "(", "temp_data", ")", ":", "data", "[", "key", "]", "=", "value", "data", ".", "pop", "(", "'seq'", ",", "None", ")", "for", "index", ",", "item", "in", "data", ".", "items", "(", ")", ":", "values", "=", "item", "if", "isinstance", "(", "item", ",", "list", ")", "or", "isinstance", "(", "item", ",", "dict", ")", ":", "values", "=", "self", ".", "__respond_with_dict", "(", "item", ")", "if", "isinstance", "(", "values", ",", "dict", ")", "and", "len", "(", "values", ")", "==", "1", ":", "(", "key", ",", "values", ")", ",", "=", "values", ".", "items", "(", ")", "response", "[", "index", "]", "=", "values", "return", "response" ]
Builds a python dictionary from a json object :param data: the json object :returns: a nested dictionary
[ "Builds", "a", "python", "dictionary", "from", "a", "json", "object" ]
54403c5981af25dc3457796b57048ae27f09e9be
https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/responselib.py#L39-L62
11,437
tasdikrahman/vocabulary
vocabulary/responselib.py
Response.__respond_with_list
def __respond_with_list(self, data): """ Builds a python list from a json object :param data: the json object :returns: a nested list """ response = [] if isinstance(data, dict): data.pop('seq', None) data = list(data.values()) for item in data: values = item if isinstance(item, list) or isinstance(item, dict): values = self.__respond_with_list(item) if isinstance(values, list) and len(values) == 1: response.extend(values) else: response.append(values) return response
python
def __respond_with_list(self, data): """ Builds a python list from a json object :param data: the json object :returns: a nested list """ response = [] if isinstance(data, dict): data.pop('seq', None) data = list(data.values()) for item in data: values = item if isinstance(item, list) or isinstance(item, dict): values = self.__respond_with_list(item) if isinstance(values, list) and len(values) == 1: response.extend(values) else: response.append(values) return response
[ "def", "__respond_with_list", "(", "self", ",", "data", ")", ":", "response", "=", "[", "]", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", ".", "pop", "(", "'seq'", ",", "None", ")", "data", "=", "list", "(", "data", ".", "values", "(", ")", ")", "for", "item", "in", "data", ":", "values", "=", "item", "if", "isinstance", "(", "item", ",", "list", ")", "or", "isinstance", "(", "item", ",", "dict", ")", ":", "values", "=", "self", ".", "__respond_with_list", "(", "item", ")", "if", "isinstance", "(", "values", ",", "list", ")", "and", "len", "(", "values", ")", "==", "1", ":", "response", ".", "extend", "(", "values", ")", "else", ":", "response", ".", "append", "(", "values", ")", "return", "response" ]
Builds a python list from a json object :param data: the json object :returns: a nested list
[ "Builds", "a", "python", "list", "from", "a", "json", "object" ]
54403c5981af25dc3457796b57048ae27f09e9be
https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/responselib.py#L64-L86
11,438
tasdikrahman/vocabulary
vocabulary/responselib.py
Response.respond
def respond(self, data, format='json'): """ Converts a json object to a python datastructure based on specified format :param data: the json object :param format: python datastructure type. Defaults to: "json" :returns: a python specified object """ dispatchers = { "dict": self.__respond_with_dict, "list": self.__respond_with_list } if not dispatchers.get(format, False): return json.dumps(data) return dispatchers[format](data)
python
def respond(self, data, format='json'): """ Converts a json object to a python datastructure based on specified format :param data: the json object :param format: python datastructure type. Defaults to: "json" :returns: a python specified object """ dispatchers = { "dict": self.__respond_with_dict, "list": self.__respond_with_list } if not dispatchers.get(format, False): return json.dumps(data) return dispatchers[format](data)
[ "def", "respond", "(", "self", ",", "data", ",", "format", "=", "'json'", ")", ":", "dispatchers", "=", "{", "\"dict\"", ":", "self", ".", "__respond_with_dict", ",", "\"list\"", ":", "self", ".", "__respond_with_list", "}", "if", "not", "dispatchers", ".", "get", "(", "format", ",", "False", ")", ":", "return", "json", ".", "dumps", "(", "data", ")", "return", "dispatchers", "[", "format", "]", "(", "data", ")" ]
Converts a json object to a python datastructure based on specified format :param data: the json object :param format: python datastructure type. Defaults to: "json" :returns: a python specified object
[ "Converts", "a", "json", "object", "to", "a", "python", "datastructure", "based", "on", "specified", "format" ]
54403c5981af25dc3457796b57048ae27f09e9be
https://github.com/tasdikrahman/vocabulary/blob/54403c5981af25dc3457796b57048ae27f09e9be/vocabulary/responselib.py#L88-L105
11,439
bram85/topydo
topydo/lib/MultiCommand.py
MultiCommand.get_todos
def get_todos(self): """ Gets todo objects from supplied todo IDs. """ if self.is_expression: self.get_todos_from_expr() else: if self.last_argument: numbers = self.args[:-1] else: numbers = self.args for number in numbers: try: self.todos.append(self.todolist.todo(number)) except InvalidTodoException: self.invalid_numbers.append(number)
python
def get_todos(self): """ Gets todo objects from supplied todo IDs. """ if self.is_expression: self.get_todos_from_expr() else: if self.last_argument: numbers = self.args[:-1] else: numbers = self.args for number in numbers: try: self.todos.append(self.todolist.todo(number)) except InvalidTodoException: self.invalid_numbers.append(number)
[ "def", "get_todos", "(", "self", ")", ":", "if", "self", ".", "is_expression", ":", "self", ".", "get_todos_from_expr", "(", ")", "else", ":", "if", "self", ".", "last_argument", ":", "numbers", "=", "self", ".", "args", "[", ":", "-", "1", "]", "else", ":", "numbers", "=", "self", ".", "args", "for", "number", "in", "numbers", ":", "try", ":", "self", ".", "todos", ".", "append", "(", "self", ".", "todolist", ".", "todo", "(", "number", ")", ")", "except", "InvalidTodoException", ":", "self", ".", "invalid_numbers", ".", "append", "(", "number", ")" ]
Gets todo objects from supplied todo IDs.
[ "Gets", "todo", "objects", "from", "supplied", "todo", "IDs", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/MultiCommand.py#L64-L78
11,440
bram85/topydo
topydo/ui/columns/TodoWidget.py
_markup
def _markup(p_todo, p_focus): """ Returns an attribute spec for the colors that correspond to the given todo item. """ pri = p_todo.priority() pri = 'pri_' + pri if pri else PaletteItem.DEFAULT if not p_focus: attr_dict = {None: pri} else: # use '_focus' palette entries instead of standard ones attr_dict = {None: pri + '_focus'} attr_dict[PaletteItem.PROJECT] = PaletteItem.PROJECT_FOCUS attr_dict[PaletteItem.CONTEXT] = PaletteItem.CONTEXT_FOCUS attr_dict[PaletteItem.METADATA] = PaletteItem.METADATA_FOCUS attr_dict[PaletteItem.LINK] = PaletteItem.LINK_FOCUS return attr_dict
python
def _markup(p_todo, p_focus): """ Returns an attribute spec for the colors that correspond to the given todo item. """ pri = p_todo.priority() pri = 'pri_' + pri if pri else PaletteItem.DEFAULT if not p_focus: attr_dict = {None: pri} else: # use '_focus' palette entries instead of standard ones attr_dict = {None: pri + '_focus'} attr_dict[PaletteItem.PROJECT] = PaletteItem.PROJECT_FOCUS attr_dict[PaletteItem.CONTEXT] = PaletteItem.CONTEXT_FOCUS attr_dict[PaletteItem.METADATA] = PaletteItem.METADATA_FOCUS attr_dict[PaletteItem.LINK] = PaletteItem.LINK_FOCUS return attr_dict
[ "def", "_markup", "(", "p_todo", ",", "p_focus", ")", ":", "pri", "=", "p_todo", ".", "priority", "(", ")", "pri", "=", "'pri_'", "+", "pri", "if", "pri", "else", "PaletteItem", ".", "DEFAULT", "if", "not", "p_focus", ":", "attr_dict", "=", "{", "None", ":", "pri", "}", "else", ":", "# use '_focus' palette entries instead of standard ones", "attr_dict", "=", "{", "None", ":", "pri", "+", "'_focus'", "}", "attr_dict", "[", "PaletteItem", ".", "PROJECT", "]", "=", "PaletteItem", ".", "PROJECT_FOCUS", "attr_dict", "[", "PaletteItem", ".", "CONTEXT", "]", "=", "PaletteItem", ".", "CONTEXT_FOCUS", "attr_dict", "[", "PaletteItem", ".", "METADATA", "]", "=", "PaletteItem", ".", "METADATA_FOCUS", "attr_dict", "[", "PaletteItem", ".", "LINK", "]", "=", "PaletteItem", ".", "LINK_FOCUS", "return", "attr_dict" ]
Returns an attribute spec for the colors that correspond to the given todo item.
[ "Returns", "an", "attribute", "spec", "for", "the", "colors", "that", "correspond", "to", "the", "given", "todo", "item", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/TodoWidget.py#L35-L53
11,441
bram85/topydo
topydo/ui/columns/TodoWidget.py
TodoWidget.create
def create(p_class, p_todo, p_id_width=4): """ Creates a TodoWidget instance for the given todo. Widgets are cached, the same object is returned for the same todo item. """ def parent_progress_may_have_changed(p_todo): """ Returns True when a todo's progress should be updated because it is dependent on the parent's progress. """ return p_todo.has_tag('p') and not p_todo.has_tag('due') source = p_todo.source() if source in p_class.cache: widget = p_class.cache[source] if p_todo is not widget.todo: # same source text but different todo instance (could happen # after an edit where a new Todo instance is created with the # same text as before) # simply fix the reference in the stored widget. widget.todo = p_todo if parent_progress_may_have_changed(p_todo): widget.update_progress() else: widget = p_class(p_todo, p_id_width) p_class.cache[source] = widget return widget
python
def create(p_class, p_todo, p_id_width=4): """ Creates a TodoWidget instance for the given todo. Widgets are cached, the same object is returned for the same todo item. """ def parent_progress_may_have_changed(p_todo): """ Returns True when a todo's progress should be updated because it is dependent on the parent's progress. """ return p_todo.has_tag('p') and not p_todo.has_tag('due') source = p_todo.source() if source in p_class.cache: widget = p_class.cache[source] if p_todo is not widget.todo: # same source text but different todo instance (could happen # after an edit where a new Todo instance is created with the # same text as before) # simply fix the reference in the stored widget. widget.todo = p_todo if parent_progress_may_have_changed(p_todo): widget.update_progress() else: widget = p_class(p_todo, p_id_width) p_class.cache[source] = widget return widget
[ "def", "create", "(", "p_class", ",", "p_todo", ",", "p_id_width", "=", "4", ")", ":", "def", "parent_progress_may_have_changed", "(", "p_todo", ")", ":", "\"\"\"\n Returns True when a todo's progress should be updated because it is\n dependent on the parent's progress.\n \"\"\"", "return", "p_todo", ".", "has_tag", "(", "'p'", ")", "and", "not", "p_todo", ".", "has_tag", "(", "'due'", ")", "source", "=", "p_todo", ".", "source", "(", ")", "if", "source", "in", "p_class", ".", "cache", ":", "widget", "=", "p_class", ".", "cache", "[", "source", "]", "if", "p_todo", "is", "not", "widget", ".", "todo", ":", "# same source text but different todo instance (could happen", "# after an edit where a new Todo instance is created with the", "# same text as before)", "# simply fix the reference in the stored widget.", "widget", ".", "todo", "=", "p_todo", "if", "parent_progress_may_have_changed", "(", "p_todo", ")", ":", "widget", ".", "update_progress", "(", ")", "else", ":", "widget", "=", "p_class", "(", "p_todo", ",", "p_id_width", ")", "p_class", ".", "cache", "[", "source", "]", "=", "widget", "return", "widget" ]
Creates a TodoWidget instance for the given todo. Widgets are cached, the same object is returned for the same todo item.
[ "Creates", "a", "TodoWidget", "instance", "for", "the", "given", "todo", ".", "Widgets", "are", "cached", "the", "same", "object", "is", "returned", "for", "the", "same", "todo", "item", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/TodoWidget.py#L164-L195
11,442
bram85/topydo
topydo/ui/columns/CommandLineWidget.py
CommandLineWidget._complete
def _complete(self): """ Main completion function. Gets list of potential completion candidates for currently edited word, completes it to the longest common part, and shows convenient completion widget (if multiple completions are returned) with currently selected candidate highlighted. """ def find_word_start(p_text, p_pos): """ Returns position of the beginning of a word ending in p_pos. """ return p_text.lstrip().rfind(' ', 0, p_pos) + 1 def get_word_before_pos(p_text, p_pos): start = find_word_start(p_text, p_pos) return (p_text[start:p_pos], start) pos = self.edit_pos text = self.edit_text completer = self.completer word_before_cursor, start = get_word_before_pos(text, pos) completions = completer.get_completions(word_before_cursor, start == 0) # store slices before and after place for completion self._surrounding_text = (text[:start], text[pos:]) single_completion = len(completions) == 1 completion_done = single_completion and completions[0] == word_before_cursor if completion_done or not completions: self.completion_mode = False return elif single_completion: replacement = completions[0] else: replacement = commonprefix(completions) zero_candidate = replacement if replacement else word_before_cursor if zero_candidate != completions[0]: completions.insert(0, zero_candidate) self.completion_box.add_completions(completions) self.insert_completion(replacement) self.completion_mode = not single_completion
python
def _complete(self): """ Main completion function. Gets list of potential completion candidates for currently edited word, completes it to the longest common part, and shows convenient completion widget (if multiple completions are returned) with currently selected candidate highlighted. """ def find_word_start(p_text, p_pos): """ Returns position of the beginning of a word ending in p_pos. """ return p_text.lstrip().rfind(' ', 0, p_pos) + 1 def get_word_before_pos(p_text, p_pos): start = find_word_start(p_text, p_pos) return (p_text[start:p_pos], start) pos = self.edit_pos text = self.edit_text completer = self.completer word_before_cursor, start = get_word_before_pos(text, pos) completions = completer.get_completions(word_before_cursor, start == 0) # store slices before and after place for completion self._surrounding_text = (text[:start], text[pos:]) single_completion = len(completions) == 1 completion_done = single_completion and completions[0] == word_before_cursor if completion_done or not completions: self.completion_mode = False return elif single_completion: replacement = completions[0] else: replacement = commonprefix(completions) zero_candidate = replacement if replacement else word_before_cursor if zero_candidate != completions[0]: completions.insert(0, zero_candidate) self.completion_box.add_completions(completions) self.insert_completion(replacement) self.completion_mode = not single_completion
[ "def", "_complete", "(", "self", ")", ":", "def", "find_word_start", "(", "p_text", ",", "p_pos", ")", ":", "\"\"\" Returns position of the beginning of a word ending in p_pos. \"\"\"", "return", "p_text", ".", "lstrip", "(", ")", ".", "rfind", "(", "' '", ",", "0", ",", "p_pos", ")", "+", "1", "def", "get_word_before_pos", "(", "p_text", ",", "p_pos", ")", ":", "start", "=", "find_word_start", "(", "p_text", ",", "p_pos", ")", "return", "(", "p_text", "[", "start", ":", "p_pos", "]", ",", "start", ")", "pos", "=", "self", ".", "edit_pos", "text", "=", "self", ".", "edit_text", "completer", "=", "self", ".", "completer", "word_before_cursor", ",", "start", "=", "get_word_before_pos", "(", "text", ",", "pos", ")", "completions", "=", "completer", ".", "get_completions", "(", "word_before_cursor", ",", "start", "==", "0", ")", "# store slices before and after place for completion", "self", ".", "_surrounding_text", "=", "(", "text", "[", ":", "start", "]", ",", "text", "[", "pos", ":", "]", ")", "single_completion", "=", "len", "(", "completions", ")", "==", "1", "completion_done", "=", "single_completion", "and", "completions", "[", "0", "]", "==", "word_before_cursor", "if", "completion_done", "or", "not", "completions", ":", "self", ".", "completion_mode", "=", "False", "return", "elif", "single_completion", ":", "replacement", "=", "completions", "[", "0", "]", "else", ":", "replacement", "=", "commonprefix", "(", "completions", ")", "zero_candidate", "=", "replacement", "if", "replacement", "else", "word_before_cursor", "if", "zero_candidate", "!=", "completions", "[", "0", "]", ":", "completions", ".", "insert", "(", "0", ",", "zero_candidate", ")", "self", ".", "completion_box", ".", "add_completions", "(", "completions", ")", "self", ".", "insert_completion", "(", "replacement", ")", "self", ".", "completion_mode", "=", "not", "single_completion" ]
Main completion function. Gets list of potential completion candidates for currently edited word, completes it to the longest common part, and shows convenient completion widget (if multiple completions are returned) with currently selected candidate highlighted.
[ "Main", "completion", "function", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/CommandLineWidget.py#L110-L155
11,443
bram85/topydo
topydo/ui/columns/CommandLineWidget.py
CommandLineWidget._home_del
def _home_del(self): """ Deletes the line content before the cursor """ text = self.edit_text[self.edit_pos:] self.set_edit_text(text) self._home()
python
def _home_del(self): """ Deletes the line content before the cursor """ text = self.edit_text[self.edit_pos:] self.set_edit_text(text) self._home()
[ "def", "_home_del", "(", "self", ")", ":", "text", "=", "self", ".", "edit_text", "[", "self", ".", "edit_pos", ":", "]", "self", ".", "set_edit_text", "(", "text", ")", "self", ".", "_home", "(", ")" ]
Deletes the line content before the cursor
[ "Deletes", "the", "line", "content", "before", "the", "cursor" ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/CommandLineWidget.py#L197-L201
11,444
bram85/topydo
topydo/ui/columns/CommandLineWidget.py
CommandLineWidget._end_del
def _end_del(self): """ Deletes the line content after the cursor """ text = self.edit_text[:self.edit_pos] self.set_edit_text(text)
python
def _end_del(self): """ Deletes the line content after the cursor """ text = self.edit_text[:self.edit_pos] self.set_edit_text(text)
[ "def", "_end_del", "(", "self", ")", ":", "text", "=", "self", ".", "edit_text", "[", ":", "self", ".", "edit_pos", "]", "self", ".", "set_edit_text", "(", "text", ")" ]
Deletes the line content after the cursor
[ "Deletes", "the", "line", "content", "after", "the", "cursor" ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/CommandLineWidget.py#L203-L206
11,445
bram85/topydo
topydo/lib/Graph.py
DirectedGraph.add_edge
def add_edge(self, p_from, p_to, p_id=None): """ Adds an edge to the graph. The nodes will be added if they don't exist. The p_id is the id of the edge, if the client wishes to maintain this. """ if not self.has_edge(p_from, p_to): if not self.has_node(p_from): self.add_node(p_from) if not self.has_node(p_to): self.add_node(p_to) self._edges[p_from].add(p_to) self._edge_numbers[(p_from, p_to)] = p_id
python
def add_edge(self, p_from, p_to, p_id=None): """ Adds an edge to the graph. The nodes will be added if they don't exist. The p_id is the id of the edge, if the client wishes to maintain this. """ if not self.has_edge(p_from, p_to): if not self.has_node(p_from): self.add_node(p_from) if not self.has_node(p_to): self.add_node(p_to) self._edges[p_from].add(p_to) self._edge_numbers[(p_from, p_to)] = p_id
[ "def", "add_edge", "(", "self", ",", "p_from", ",", "p_to", ",", "p_id", "=", "None", ")", ":", "if", "not", "self", ".", "has_edge", "(", "p_from", ",", "p_to", ")", ":", "if", "not", "self", ".", "has_node", "(", "p_from", ")", ":", "self", ".", "add_node", "(", "p_from", ")", "if", "not", "self", ".", "has_node", "(", "p_to", ")", ":", "self", ".", "add_node", "(", "p_to", ")", "self", ".", "_edges", "[", "p_from", "]", ".", "add", "(", "p_to", ")", "self", ".", "_edge_numbers", "[", "(", "p_from", ",", "p_to", ")", "]", "=", "p_id" ]
Adds an edge to the graph. The nodes will be added if they don't exist. The p_id is the id of the edge, if the client wishes to maintain this.
[ "Adds", "an", "edge", "to", "the", "graph", ".", "The", "nodes", "will", "be", "added", "if", "they", "don", "t", "exist", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L39-L53
11,446
bram85/topydo
topydo/lib/Graph.py
DirectedGraph.reachable_nodes
def reachable_nodes(self, p_id, p_recursive=True, p_reverse=False): """ Returns the set of all neighbors that the given node can reach. If recursive, it will also return the neighbor's neighbors, etc. If reverse, the arrows are reversed and then the reachable neighbors are located. """ stack = [p_id] visited = set() result = set() while len(stack): current = stack.pop() if current in visited or current not in self._edges: continue visited.add(current) if p_reverse: parents = [node for node, neighbors in self._edges.items() if current in neighbors] stack = stack + parents result = result.union(parents) else: stack = stack + list(self._edges[current]) result = result.union(self._edges[current]) if not p_recursive: break return result
python
def reachable_nodes(self, p_id, p_recursive=True, p_reverse=False): """ Returns the set of all neighbors that the given node can reach. If recursive, it will also return the neighbor's neighbors, etc. If reverse, the arrows are reversed and then the reachable neighbors are located. """ stack = [p_id] visited = set() result = set() while len(stack): current = stack.pop() if current in visited or current not in self._edges: continue visited.add(current) if p_reverse: parents = [node for node, neighbors in self._edges.items() if current in neighbors] stack = stack + parents result = result.union(parents) else: stack = stack + list(self._edges[current]) result = result.union(self._edges[current]) if not p_recursive: break return result
[ "def", "reachable_nodes", "(", "self", ",", "p_id", ",", "p_recursive", "=", "True", ",", "p_reverse", "=", "False", ")", ":", "stack", "=", "[", "p_id", "]", "visited", "=", "set", "(", ")", "result", "=", "set", "(", ")", "while", "len", "(", "stack", ")", ":", "current", "=", "stack", ".", "pop", "(", ")", "if", "current", "in", "visited", "or", "current", "not", "in", "self", ".", "_edges", ":", "continue", "visited", ".", "add", "(", "current", ")", "if", "p_reverse", ":", "parents", "=", "[", "node", "for", "node", ",", "neighbors", "in", "self", ".", "_edges", ".", "items", "(", ")", "if", "current", "in", "neighbors", "]", "stack", "=", "stack", "+", "parents", "result", "=", "result", ".", "union", "(", "parents", ")", "else", ":", "stack", "=", "stack", "+", "list", "(", "self", ".", "_edges", "[", "current", "]", ")", "result", "=", "result", ".", "union", "(", "self", ".", "_edges", "[", "current", "]", ")", "if", "not", "p_recursive", ":", "break", "return", "result" ]
Returns the set of all neighbors that the given node can reach. If recursive, it will also return the neighbor's neighbors, etc. If reverse, the arrows are reversed and then the reachable neighbors are located.
[ "Returns", "the", "set", "of", "all", "neighbors", "that", "the", "given", "node", "can", "reach", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L73-L106
11,447
bram85/topydo
topydo/lib/Graph.py
DirectedGraph.reachable_nodes_reverse
def reachable_nodes_reverse(self, p_id, p_recursive=True): """ Find neighbors in the inverse graph. """ return self.reachable_nodes(p_id, p_recursive, True)
python
def reachable_nodes_reverse(self, p_id, p_recursive=True): """ Find neighbors in the inverse graph. """ return self.reachable_nodes(p_id, p_recursive, True)
[ "def", "reachable_nodes_reverse", "(", "self", ",", "p_id", ",", "p_recursive", "=", "True", ")", ":", "return", "self", ".", "reachable_nodes", "(", "p_id", ",", "p_recursive", ",", "True", ")" ]
Find neighbors in the inverse graph.
[ "Find", "neighbors", "in", "the", "inverse", "graph", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L108-L110
11,448
bram85/topydo
topydo/lib/Graph.py
DirectedGraph.remove_node
def remove_node(self, p_id, remove_unconnected_nodes=True): """ Removes a node from the graph. """ if self.has_node(p_id): for neighbor in self.incoming_neighbors(p_id): self._edges[neighbor].remove(p_id) neighbors = set() if remove_unconnected_nodes: neighbors = self.outgoing_neighbors(p_id) del self._edges[p_id] for neighbor in neighbors: if self.is_isolated(neighbor): self.remove_node(neighbor)
python
def remove_node(self, p_id, remove_unconnected_nodes=True): """ Removes a node from the graph. """ if self.has_node(p_id): for neighbor in self.incoming_neighbors(p_id): self._edges[neighbor].remove(p_id) neighbors = set() if remove_unconnected_nodes: neighbors = self.outgoing_neighbors(p_id) del self._edges[p_id] for neighbor in neighbors: if self.is_isolated(neighbor): self.remove_node(neighbor)
[ "def", "remove_node", "(", "self", ",", "p_id", ",", "remove_unconnected_nodes", "=", "True", ")", ":", "if", "self", ".", "has_node", "(", "p_id", ")", ":", "for", "neighbor", "in", "self", ".", "incoming_neighbors", "(", "p_id", ")", ":", "self", ".", "_edges", "[", "neighbor", "]", ".", "remove", "(", "p_id", ")", "neighbors", "=", "set", "(", ")", "if", "remove_unconnected_nodes", ":", "neighbors", "=", "self", ".", "outgoing_neighbors", "(", "p_id", ")", "del", "self", ".", "_edges", "[", "p_id", "]", "for", "neighbor", "in", "neighbors", ":", "if", "self", ".", "is_isolated", "(", "neighbor", ")", ":", "self", ".", "remove_node", "(", "neighbor", ")" ]
Removes a node from the graph.
[ "Removes", "a", "node", "from", "the", "graph", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L112-L126
11,449
bram85/topydo
topydo/lib/Graph.py
DirectedGraph.is_isolated
def is_isolated(self, p_id): """ Returns True iff the given node has no incoming or outgoing edges. """ return(len(self.incoming_neighbors(p_id)) == 0 and len(self.outgoing_neighbors(p_id)) == 0)
python
def is_isolated(self, p_id): """ Returns True iff the given node has no incoming or outgoing edges. """ return(len(self.incoming_neighbors(p_id)) == 0 and len(self.outgoing_neighbors(p_id)) == 0)
[ "def", "is_isolated", "(", "self", ",", "p_id", ")", ":", "return", "(", "len", "(", "self", ".", "incoming_neighbors", "(", "p_id", ")", ")", "==", "0", "and", "len", "(", "self", ".", "outgoing_neighbors", "(", "p_id", ")", ")", "==", "0", ")" ]
Returns True iff the given node has no incoming or outgoing edges.
[ "Returns", "True", "iff", "the", "given", "node", "has", "no", "incoming", "or", "outgoing", "edges", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L128-L133
11,450
bram85/topydo
topydo/lib/Graph.py
DirectedGraph.has_edge
def has_edge(self, p_from, p_to): """ Returns True when the graph has the given edge. """ return p_from in self._edges and p_to in self._edges[p_from]
python
def has_edge(self, p_from, p_to): """ Returns True when the graph has the given edge. """ return p_from in self._edges and p_to in self._edges[p_from]
[ "def", "has_edge", "(", "self", ",", "p_from", ",", "p_to", ")", ":", "return", "p_from", "in", "self", ".", "_edges", "and", "p_to", "in", "self", ".", "_edges", "[", "p_from", "]" ]
Returns True when the graph has the given edge.
[ "Returns", "True", "when", "the", "graph", "has", "the", "given", "edge", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L135-L137
11,451
bram85/topydo
topydo/lib/Graph.py
DirectedGraph.remove_edge
def remove_edge(self, p_from, p_to, p_remove_unconnected_nodes=True): """ Removes an edge from the graph. When remove_unconnected_nodes is True, then the nodes are also removed if they become isolated. """ if self.has_edge(p_from, p_to): self._edges[p_from].remove(p_to) try: del self._edge_numbers[(p_from, p_to)] except KeyError: return None if p_remove_unconnected_nodes: if self.is_isolated(p_from): self.remove_node(p_from) if self.is_isolated(p_to): self.remove_node(p_to)
python
def remove_edge(self, p_from, p_to, p_remove_unconnected_nodes=True): """ Removes an edge from the graph. When remove_unconnected_nodes is True, then the nodes are also removed if they become isolated. """ if self.has_edge(p_from, p_to): self._edges[p_from].remove(p_to) try: del self._edge_numbers[(p_from, p_to)] except KeyError: return None if p_remove_unconnected_nodes: if self.is_isolated(p_from): self.remove_node(p_from) if self.is_isolated(p_to): self.remove_node(p_to)
[ "def", "remove_edge", "(", "self", ",", "p_from", ",", "p_to", ",", "p_remove_unconnected_nodes", "=", "True", ")", ":", "if", "self", ".", "has_edge", "(", "p_from", ",", "p_to", ")", ":", "self", ".", "_edges", "[", "p_from", "]", ".", "remove", "(", "p_to", ")", "try", ":", "del", "self", ".", "_edge_numbers", "[", "(", "p_from", ",", "p_to", ")", "]", "except", "KeyError", ":", "return", "None", "if", "p_remove_unconnected_nodes", ":", "if", "self", ".", "is_isolated", "(", "p_from", ")", ":", "self", ".", "remove_node", "(", "p_from", ")", "if", "self", ".", "is_isolated", "(", "p_to", ")", ":", "self", ".", "remove_node", "(", "p_to", ")" ]
Removes an edge from the graph. When remove_unconnected_nodes is True, then the nodes are also removed if they become isolated.
[ "Removes", "an", "edge", "from", "the", "graph", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L156-L176
11,452
bram85/topydo
topydo/lib/Graph.py
DirectedGraph.transitively_reduce
def transitively_reduce(self): """ Performs a transitive reduction on the graph. """ removals = set() for from_node, neighbors in self._edges.items(): childpairs = \ [(c1, c2) for c1 in neighbors for c2 in neighbors if c1 != c2] for child1, child2 in childpairs: if self.has_path(child1, child2) \ and not self.has_path(child1, from_node): removals.add((from_node, child2)) for edge in removals: self.remove_edge(edge[0], edge[1])
python
def transitively_reduce(self): """ Performs a transitive reduction on the graph. """ removals = set() for from_node, neighbors in self._edges.items(): childpairs = \ [(c1, c2) for c1 in neighbors for c2 in neighbors if c1 != c2] for child1, child2 in childpairs: if self.has_path(child1, child2) \ and not self.has_path(child1, from_node): removals.add((from_node, child2)) for edge in removals: self.remove_edge(edge[0], edge[1])
[ "def", "transitively_reduce", "(", "self", ")", ":", "removals", "=", "set", "(", ")", "for", "from_node", ",", "neighbors", "in", "self", ".", "_edges", ".", "items", "(", ")", ":", "childpairs", "=", "[", "(", "c1", ",", "c2", ")", "for", "c1", "in", "neighbors", "for", "c2", "in", "neighbors", "if", "c1", "!=", "c2", "]", "for", "child1", ",", "child2", "in", "childpairs", ":", "if", "self", ".", "has_path", "(", "child1", ",", "child2", ")", "and", "not", "self", ".", "has_path", "(", "child1", ",", "from_node", ")", ":", "removals", ".", "add", "(", "(", "from_node", ",", "child2", ")", ")", "for", "edge", "in", "removals", ":", "self", ".", "remove_edge", "(", "edge", "[", "0", "]", ",", "edge", "[", "1", "]", ")" ]
Performs a transitive reduction on the graph.
[ "Performs", "a", "transitive", "reduction", "on", "the", "graph", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L178-L194
11,453
bram85/topydo
topydo/lib/Graph.py
DirectedGraph.dot
def dot(self, p_print_labels=True): """ Prints the graph in Dot format. """ out = 'digraph g {\n' for from_node, neighbors in sorted(self._edges.items()): out += " {}\n".format(from_node) for neighbor in sorted(neighbors): out += " {} -> {}".format(from_node, neighbor) edge_id = self.edge_id(from_node, neighbor) if edge_id and p_print_labels: out += ' [label="{}"]'.format(edge_id) out += "\n" out += '}\n' return out
python
def dot(self, p_print_labels=True): """ Prints the graph in Dot format. """ out = 'digraph g {\n' for from_node, neighbors in sorted(self._edges.items()): out += " {}\n".format(from_node) for neighbor in sorted(neighbors): out += " {} -> {}".format(from_node, neighbor) edge_id = self.edge_id(from_node, neighbor) if edge_id and p_print_labels: out += ' [label="{}"]'.format(edge_id) out += "\n" out += '}\n' return out
[ "def", "dot", "(", "self", ",", "p_print_labels", "=", "True", ")", ":", "out", "=", "'digraph g {\\n'", "for", "from_node", ",", "neighbors", "in", "sorted", "(", "self", ".", "_edges", ".", "items", "(", ")", ")", ":", "out", "+=", "\" {}\\n\"", ".", "format", "(", "from_node", ")", "for", "neighbor", "in", "sorted", "(", "neighbors", ")", ":", "out", "+=", "\" {} -> {}\"", ".", "format", "(", "from_node", ",", "neighbor", ")", "edge_id", "=", "self", ".", "edge_id", "(", "from_node", ",", "neighbor", ")", "if", "edge_id", "and", "p_print_labels", ":", "out", "+=", "' [label=\"{}\"]'", ".", "format", "(", "edge_id", ")", "out", "+=", "\"\\n\"", "out", "+=", "'}\\n'", "return", "out" ]
Prints the graph in Dot format.
[ "Prints", "the", "graph", "in", "Dot", "format", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L196-L213
11,454
bram85/topydo
topydo/commands/ListCommand.py
ListCommand._print
def _print(self): """ Prints the todos in the right format. Defaults to normal text output (with possible colors and other pretty printing). If a format was specified on the commandline, this format is sent to the output. """ if self.printer is None: # create a standard printer with some filters indent = config().list_indent() final_format = ' ' * indent + self.format filters = [] filters.append(PrettyPrinterFormatFilter(self.todolist, final_format)) self.printer = pretty_printer_factory(self.todolist, filters) try: if self.group_expression: self.out(self.printer.print_groups(self._view().groups)) else: self.out(self.printer.print_list(self._view().todos)) except ListFormatError: self.error('Error while parsing format string (list_format config' ' option or -F)')
python
def _print(self): """ Prints the todos in the right format. Defaults to normal text output (with possible colors and other pretty printing). If a format was specified on the commandline, this format is sent to the output. """ if self.printer is None: # create a standard printer with some filters indent = config().list_indent() final_format = ' ' * indent + self.format filters = [] filters.append(PrettyPrinterFormatFilter(self.todolist, final_format)) self.printer = pretty_printer_factory(self.todolist, filters) try: if self.group_expression: self.out(self.printer.print_groups(self._view().groups)) else: self.out(self.printer.print_list(self._view().todos)) except ListFormatError: self.error('Error while parsing format string (list_format config' ' option or -F)')
[ "def", "_print", "(", "self", ")", ":", "if", "self", ".", "printer", "is", "None", ":", "# create a standard printer with some filters", "indent", "=", "config", "(", ")", ".", "list_indent", "(", ")", "final_format", "=", "' '", "*", "indent", "+", "self", ".", "format", "filters", "=", "[", "]", "filters", ".", "append", "(", "PrettyPrinterFormatFilter", "(", "self", ".", "todolist", ",", "final_format", ")", ")", "self", ".", "printer", "=", "pretty_printer_factory", "(", "self", ".", "todolist", ",", "filters", ")", "try", ":", "if", "self", ".", "group_expression", ":", "self", ".", "out", "(", "self", ".", "printer", ".", "print_groups", "(", "self", ".", "_view", "(", ")", ".", "groups", ")", ")", "else", ":", "self", ".", "out", "(", "self", ".", "printer", ".", "print_list", "(", "self", ".", "_view", "(", ")", ".", "todos", ")", ")", "except", "ListFormatError", ":", "self", ".", "error", "(", "'Error while parsing format string (list_format config'", "' option or -F)'", ")" ]
Prints the todos in the right format. Defaults to normal text output (with possible colors and other pretty printing). If a format was specified on the commandline, this format is sent to the output.
[ "Prints", "the", "todos", "in", "the", "right", "format", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/commands/ListCommand.py#L134-L159
11,455
bram85/topydo
topydo/lib/TodoParser.py
parse_line
def parse_line(p_string): """ Parses a single line as can be encountered in a todo.txt file. First checks whether the standard elements are present, such as priority, creation date, completeness check and the completion date. Then the rest of the analyzed for any occurrences of contexts, projects or tags. Returns an dictionary with the default values as shown below. """ result = { 'completed': False, 'completionDate': None, 'priority': None, 'creationDate': None, 'text': "", 'projects': [], 'contexts': [], 'tags': {}, } completed_head = _COMPLETED_HEAD_MATCH.match(p_string) normal_head = _NORMAL_HEAD_MATCH.match(p_string) rest = p_string if completed_head: result['completed'] = True completion_date = completed_head.group('completionDate') try: result['completionDate'] = date_string_to_date(completion_date) except ValueError: pass creation_date = completed_head.group('creationDate') try: result['creationDate'] = date_string_to_date(creation_date) except ValueError: pass rest = completed_head.group('rest') elif normal_head: result['priority'] = normal_head.group('priority') creation_date = normal_head.group('creationDate') try: result['creationDate'] = date_string_to_date(creation_date) except ValueError: pass rest = normal_head.group('rest') for word in rest.split(): project = _PROJECT_MATCH.match(word) if project: result['projects'].append(project.group(1)) context = _CONTEXT_MATCH.match(word) if context: result['contexts'].append(context.group(1)) tag = _TAG_MATCH.match(word) if tag: tag_name = tag.group('tag') tag_value = tag.group('value') try: result['tags'][tag_name].append(tag_value) except KeyError: result['tags'][tag_name] = [tag_value] else: result['text'] += word + ' ' # strip trailing space from resulting text result['text'] = result['text'][:-1] return result
python
def parse_line(p_string): """ Parses a single line as can be encountered in a todo.txt file. First checks whether the standard elements are present, such as priority, creation date, completeness check and the completion date. Then the rest of the analyzed for any occurrences of contexts, projects or tags. Returns an dictionary with the default values as shown below. """ result = { 'completed': False, 'completionDate': None, 'priority': None, 'creationDate': None, 'text': "", 'projects': [], 'contexts': [], 'tags': {}, } completed_head = _COMPLETED_HEAD_MATCH.match(p_string) normal_head = _NORMAL_HEAD_MATCH.match(p_string) rest = p_string if completed_head: result['completed'] = True completion_date = completed_head.group('completionDate') try: result['completionDate'] = date_string_to_date(completion_date) except ValueError: pass creation_date = completed_head.group('creationDate') try: result['creationDate'] = date_string_to_date(creation_date) except ValueError: pass rest = completed_head.group('rest') elif normal_head: result['priority'] = normal_head.group('priority') creation_date = normal_head.group('creationDate') try: result['creationDate'] = date_string_to_date(creation_date) except ValueError: pass rest = normal_head.group('rest') for word in rest.split(): project = _PROJECT_MATCH.match(word) if project: result['projects'].append(project.group(1)) context = _CONTEXT_MATCH.match(word) if context: result['contexts'].append(context.group(1)) tag = _TAG_MATCH.match(word) if tag: tag_name = tag.group('tag') tag_value = tag.group('value') try: result['tags'][tag_name].append(tag_value) except KeyError: result['tags'][tag_name] = [tag_value] else: result['text'] += word + ' ' # strip trailing space from resulting text result['text'] = result['text'][:-1] return result
[ "def", "parse_line", "(", "p_string", ")", ":", "result", "=", "{", "'completed'", ":", "False", ",", "'completionDate'", ":", "None", ",", "'priority'", ":", "None", ",", "'creationDate'", ":", "None", ",", "'text'", ":", "\"\"", ",", "'projects'", ":", "[", "]", ",", "'contexts'", ":", "[", "]", ",", "'tags'", ":", "{", "}", ",", "}", "completed_head", "=", "_COMPLETED_HEAD_MATCH", ".", "match", "(", "p_string", ")", "normal_head", "=", "_NORMAL_HEAD_MATCH", ".", "match", "(", "p_string", ")", "rest", "=", "p_string", "if", "completed_head", ":", "result", "[", "'completed'", "]", "=", "True", "completion_date", "=", "completed_head", ".", "group", "(", "'completionDate'", ")", "try", ":", "result", "[", "'completionDate'", "]", "=", "date_string_to_date", "(", "completion_date", ")", "except", "ValueError", ":", "pass", "creation_date", "=", "completed_head", ".", "group", "(", "'creationDate'", ")", "try", ":", "result", "[", "'creationDate'", "]", "=", "date_string_to_date", "(", "creation_date", ")", "except", "ValueError", ":", "pass", "rest", "=", "completed_head", ".", "group", "(", "'rest'", ")", "elif", "normal_head", ":", "result", "[", "'priority'", "]", "=", "normal_head", ".", "group", "(", "'priority'", ")", "creation_date", "=", "normal_head", ".", "group", "(", "'creationDate'", ")", "try", ":", "result", "[", "'creationDate'", "]", "=", "date_string_to_date", "(", "creation_date", ")", "except", "ValueError", ":", "pass", "rest", "=", "normal_head", ".", "group", "(", "'rest'", ")", "for", "word", "in", "rest", ".", "split", "(", ")", ":", "project", "=", "_PROJECT_MATCH", ".", "match", "(", "word", ")", "if", "project", ":", "result", "[", "'projects'", "]", ".", "append", "(", "project", ".", "group", "(", "1", ")", ")", "context", "=", "_CONTEXT_MATCH", ".", "match", "(", "word", ")", "if", "context", ":", "result", "[", "'contexts'", "]", ".", "append", "(", "context", ".", "group", "(", "1", ")", ")", "tag", "=", "_TAG_MATCH", ".", "match", "(", "word", ")", "if", "tag", ":", "tag_name", "=", "tag", ".", "group", "(", "'tag'", ")", "tag_value", "=", "tag", ".", "group", "(", "'value'", ")", "try", ":", "result", "[", "'tags'", "]", "[", "tag_name", "]", ".", "append", "(", "tag_value", ")", "except", "KeyError", ":", "result", "[", "'tags'", "]", "[", "tag_name", "]", "=", "[", "tag_value", "]", "else", ":", "result", "[", "'text'", "]", "+=", "word", "+", "' '", "# strip trailing space from resulting text", "result", "[", "'text'", "]", "=", "result", "[", "'text'", "]", "[", ":", "-", "1", "]", "return", "result" ]
Parses a single line as can be encountered in a todo.txt file. First checks whether the standard elements are present, such as priority, creation date, completeness check and the completion date. Then the rest of the analyzed for any occurrences of contexts, projects or tags. Returns an dictionary with the default values as shown below.
[ "Parses", "a", "single", "line", "as", "can", "be", "encountered", "in", "a", "todo", ".", "txt", "file", ".", "First", "checks", "whether", "the", "standard", "elements", "are", "present", "such", "as", "priority", "creation", "date", "completeness", "check", "and", "the", "completion", "date", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoParser.py#L41-L120
11,456
bram85/topydo
topydo/ui/prompt/PromptCompleter.py
_dates
def _dates(p_word_before_cursor): """ Generator for date completion. """ to_absolute = lambda s: relative_date_to_date(s).isoformat() start_value_pos = p_word_before_cursor.find(':') + 1 value = p_word_before_cursor[start_value_pos:] for reldate in date_suggestions(): if not reldate.startswith(value): continue yield Completion(reldate, -len(value), display_meta=to_absolute(reldate))
python
def _dates(p_word_before_cursor): """ Generator for date completion. """ to_absolute = lambda s: relative_date_to_date(s).isoformat() start_value_pos = p_word_before_cursor.find(':') + 1 value = p_word_before_cursor[start_value_pos:] for reldate in date_suggestions(): if not reldate.startswith(value): continue yield Completion(reldate, -len(value), display_meta=to_absolute(reldate))
[ "def", "_dates", "(", "p_word_before_cursor", ")", ":", "to_absolute", "=", "lambda", "s", ":", "relative_date_to_date", "(", "s", ")", ".", "isoformat", "(", ")", "start_value_pos", "=", "p_word_before_cursor", ".", "find", "(", "':'", ")", "+", "1", "value", "=", "p_word_before_cursor", "[", "start_value_pos", ":", "]", "for", "reldate", "in", "date_suggestions", "(", ")", ":", "if", "not", "reldate", ".", "startswith", "(", "value", ")", ":", "continue", "yield", "Completion", "(", "reldate", ",", "-", "len", "(", "value", ")", ",", "display_meta", "=", "to_absolute", "(", "reldate", ")", ")" ]
Generator for date completion.
[ "Generator", "for", "date", "completion", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/prompt/PromptCompleter.py#L31-L42
11,457
bram85/topydo
topydo/ui/columns/CompletionBoxWidget.py
CompletionBoxWidget.add_completions
def add_completions(self, p_completions): """ Creates proper urwid.Text widgets for all completion candidates from p_completions list, and populates them into the items attribute. """ palette = PaletteItem.MARKED for completion in p_completions: width = len(completion) if width > self.min_width: self.min_width = width w = urwid.Text(completion) self.items.append(urwid.AttrMap(w, None, focus_map=palette)) self.items.set_focus(0)
python
def add_completions(self, p_completions): """ Creates proper urwid.Text widgets for all completion candidates from p_completions list, and populates them into the items attribute. """ palette = PaletteItem.MARKED for completion in p_completions: width = len(completion) if width > self.min_width: self.min_width = width w = urwid.Text(completion) self.items.append(urwid.AttrMap(w, None, focus_map=palette)) self.items.set_focus(0)
[ "def", "add_completions", "(", "self", ",", "p_completions", ")", ":", "palette", "=", "PaletteItem", ".", "MARKED", "for", "completion", "in", "p_completions", ":", "width", "=", "len", "(", "completion", ")", "if", "width", ">", "self", ".", "min_width", ":", "self", ".", "min_width", "=", "width", "w", "=", "urwid", ".", "Text", "(", "completion", ")", "self", ".", "items", ".", "append", "(", "urwid", ".", "AttrMap", "(", "w", ",", "None", ",", "focus_map", "=", "palette", ")", ")", "self", ".", "items", ".", "set_focus", "(", "0", ")" ]
Creates proper urwid.Text widgets for all completion candidates from p_completions list, and populates them into the items attribute.
[ "Creates", "proper", "urwid", ".", "Text", "widgets", "for", "all", "completion", "candidates", "from", "p_completions", "list", "and", "populates", "them", "into", "the", "items", "attribute", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/CompletionBoxWidget.py#L44-L56
11,458
bram85/topydo
topydo/lib/View.py
View._apply_filters
def _apply_filters(self, p_todos): """ Applies the filters to the list of todo items. """ result = p_todos for _filter in sorted(self._filters, key=lambda f: f.order): result = _filter.filter(result) return result
python
def _apply_filters(self, p_todos): """ Applies the filters to the list of todo items. """ result = p_todos for _filter in sorted(self._filters, key=lambda f: f.order): result = _filter.filter(result) return result
[ "def", "_apply_filters", "(", "self", ",", "p_todos", ")", ":", "result", "=", "p_todos", "for", "_filter", "in", "sorted", "(", "self", ".", "_filters", ",", "key", "=", "lambda", "f", ":", "f", ".", "order", ")", ":", "result", "=", "_filter", ".", "filter", "(", "result", ")", "return", "result" ]
Applies the filters to the list of todo items.
[ "Applies", "the", "filters", "to", "the", "list", "of", "todo", "items", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/View.py#L32-L39
11,459
bram85/topydo
topydo/lib/View.py
View.todos
def todos(self): """ Returns a sorted and filtered list of todos in this view. """ result = self._sorter.sort(self.todolist.todos()) return self._apply_filters(result)
python
def todos(self): """ Returns a sorted and filtered list of todos in this view. """ result = self._sorter.sort(self.todolist.todos()) return self._apply_filters(result)
[ "def", "todos", "(", "self", ")", ":", "result", "=", "self", ".", "_sorter", ".", "sort", "(", "self", ".", "todolist", ".", "todos", "(", ")", ")", "return", "self", ".", "_apply_filters", "(", "result", ")" ]
Returns a sorted and filtered list of todos in this view.
[ "Returns", "a", "sorted", "and", "filtered", "list", "of", "todos", "in", "this", "view", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/View.py#L42-L45
11,460
bram85/topydo
topydo/commands/DoCommand.py
DoCommand.execute_specific
def execute_specific(self, p_todo): """ Actions specific to this command. """ self._handle_recurrence(p_todo) self.execute_specific_core(p_todo) printer = PrettyPrinter() self.out(self.prefix() + printer.print_todo(p_todo))
python
def execute_specific(self, p_todo): """ Actions specific to this command. """ self._handle_recurrence(p_todo) self.execute_specific_core(p_todo) printer = PrettyPrinter() self.out(self.prefix() + printer.print_todo(p_todo))
[ "def", "execute_specific", "(", "self", ",", "p_todo", ")", ":", "self", ".", "_handle_recurrence", "(", "p_todo", ")", "self", ".", "execute_specific_core", "(", "p_todo", ")", "printer", "=", "PrettyPrinter", "(", ")", "self", ".", "out", "(", "self", ".", "prefix", "(", ")", "+", "printer", ".", "print_todo", "(", "p_todo", ")", ")" ]
Actions specific to this command.
[ "Actions", "specific", "to", "this", "command", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/commands/DoCommand.py#L81-L87
11,461
bram85/topydo
topydo/lib/Utils.py
date_string_to_date
def date_string_to_date(p_date): """ Given a date in YYYY-MM-DD, returns a Python date object. Throws a ValueError if the date is invalid. """ result = None if p_date: parsed_date = re.match(r'(\d{4})-(\d{2})-(\d{2})', p_date) if parsed_date: result = date( int(parsed_date.group(1)), # year int(parsed_date.group(2)), # month int(parsed_date.group(3)) # day ) else: raise ValueError return result
python
def date_string_to_date(p_date): """ Given a date in YYYY-MM-DD, returns a Python date object. Throws a ValueError if the date is invalid. """ result = None if p_date: parsed_date = re.match(r'(\d{4})-(\d{2})-(\d{2})', p_date) if parsed_date: result = date( int(parsed_date.group(1)), # year int(parsed_date.group(2)), # month int(parsed_date.group(3)) # day ) else: raise ValueError return result
[ "def", "date_string_to_date", "(", "p_date", ")", ":", "result", "=", "None", "if", "p_date", ":", "parsed_date", "=", "re", ".", "match", "(", "r'(\\d{4})-(\\d{2})-(\\d{2})'", ",", "p_date", ")", "if", "parsed_date", ":", "result", "=", "date", "(", "int", "(", "parsed_date", ".", "group", "(", "1", ")", ")", ",", "# year", "int", "(", "parsed_date", ".", "group", "(", "2", ")", ")", ",", "# month", "int", "(", "parsed_date", ".", "group", "(", "3", ")", ")", "# day", ")", "else", ":", "raise", "ValueError", "return", "result" ]
Given a date in YYYY-MM-DD, returns a Python date object. Throws a ValueError if the date is invalid.
[ "Given", "a", "date", "in", "YYYY", "-", "MM", "-", "DD", "returns", "a", "Python", "date", "object", ".", "Throws", "a", "ValueError", "if", "the", "date", "is", "invalid", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Utils.py#L28-L46
11,462
bram85/topydo
topydo/lib/Utils.py
get_terminal_size
def get_terminal_size(p_getter=None): """ Try to determine terminal size at run time. If that is not possible, returns the default size of 80x24. By default, the size is determined with provided get_terminal_size by shutil. Sometimes an UI may want to specify the desired width, then it can provide a getter that returns a named tuple (columns, lines) with the size. """ try: return get_terminal_size.getter() except AttributeError: if p_getter: get_terminal_size.getter = p_getter else: def inner(): try: # shutil.get_terminal_size was added to the standard # library in Python 3.3 try: from shutil import get_terminal_size as _get_terminal_size # pylint: disable=no-name-in-module except ImportError: from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size # pylint: disable=import-error size = _get_terminal_size() except ValueError: # This can result from the 'underlying buffer being detached', which # occurs during running the unittest on Windows (but not on Linux?) terminal_size = namedtuple('Terminal_Size', 'columns lines') size = terminal_size(80, 24) return size get_terminal_size.getter = inner return get_terminal_size.getter()
python
def get_terminal_size(p_getter=None): """ Try to determine terminal size at run time. If that is not possible, returns the default size of 80x24. By default, the size is determined with provided get_terminal_size by shutil. Sometimes an UI may want to specify the desired width, then it can provide a getter that returns a named tuple (columns, lines) with the size. """ try: return get_terminal_size.getter() except AttributeError: if p_getter: get_terminal_size.getter = p_getter else: def inner(): try: # shutil.get_terminal_size was added to the standard # library in Python 3.3 try: from shutil import get_terminal_size as _get_terminal_size # pylint: disable=no-name-in-module except ImportError: from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size # pylint: disable=import-error size = _get_terminal_size() except ValueError: # This can result from the 'underlying buffer being detached', which # occurs during running the unittest on Windows (but not on Linux?) terminal_size = namedtuple('Terminal_Size', 'columns lines') size = terminal_size(80, 24) return size get_terminal_size.getter = inner return get_terminal_size.getter()
[ "def", "get_terminal_size", "(", "p_getter", "=", "None", ")", ":", "try", ":", "return", "get_terminal_size", ".", "getter", "(", ")", "except", "AttributeError", ":", "if", "p_getter", ":", "get_terminal_size", ".", "getter", "=", "p_getter", "else", ":", "def", "inner", "(", ")", ":", "try", ":", "# shutil.get_terminal_size was added to the standard", "# library in Python 3.3", "try", ":", "from", "shutil", "import", "get_terminal_size", "as", "_get_terminal_size", "# pylint: disable=no-name-in-module", "except", "ImportError", ":", "from", "backports", ".", "shutil_get_terminal_size", "import", "get_terminal_size", "as", "_get_terminal_size", "# pylint: disable=import-error", "size", "=", "_get_terminal_size", "(", ")", "except", "ValueError", ":", "# This can result from the 'underlying buffer being detached', which", "# occurs during running the unittest on Windows (but not on Linux?)", "terminal_size", "=", "namedtuple", "(", "'Terminal_Size'", ",", "'columns lines'", ")", "size", "=", "terminal_size", "(", "80", ",", "24", ")", "return", "size", "get_terminal_size", ".", "getter", "=", "inner", "return", "get_terminal_size", ".", "getter", "(", ")" ]
Try to determine terminal size at run time. If that is not possible, returns the default size of 80x24. By default, the size is determined with provided get_terminal_size by shutil. Sometimes an UI may want to specify the desired width, then it can provide a getter that returns a named tuple (columns, lines) with the size.
[ "Try", "to", "determine", "terminal", "size", "at", "run", "time", ".", "If", "that", "is", "not", "possible", "returns", "the", "default", "size", "of", "80x24", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Utils.py#L59-L95
11,463
bram85/topydo
topydo/lib/Utils.py
translate_key_to_config
def translate_key_to_config(p_key): """ Translates urwid key event to form understandable by topydo config parser. """ if len(p_key) > 1: key = p_key.capitalize() if key.startswith('Ctrl') or key.startswith('Meta'): key = key[0] + '-' + key[5:] key = '<' + key + '>' else: key = p_key return key
python
def translate_key_to_config(p_key): """ Translates urwid key event to form understandable by topydo config parser. """ if len(p_key) > 1: key = p_key.capitalize() if key.startswith('Ctrl') or key.startswith('Meta'): key = key[0] + '-' + key[5:] key = '<' + key + '>' else: key = p_key return key
[ "def", "translate_key_to_config", "(", "p_key", ")", ":", "if", "len", "(", "p_key", ")", ">", "1", ":", "key", "=", "p_key", ".", "capitalize", "(", ")", "if", "key", ".", "startswith", "(", "'Ctrl'", ")", "or", "key", ".", "startswith", "(", "'Meta'", ")", ":", "key", "=", "key", "[", "0", "]", "+", "'-'", "+", "key", "[", "5", ":", "]", "key", "=", "'<'", "+", "key", "+", "'>'", "else", ":", "key", "=", "p_key", "return", "key" ]
Translates urwid key event to form understandable by topydo config parser.
[ "Translates", "urwid", "key", "event", "to", "form", "understandable", "by", "topydo", "config", "parser", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Utils.py#L98-L110
11,464
bram85/topydo
topydo/lib/Utils.py
humanize_date
def humanize_date(p_datetime): """ Returns a relative date string from a datetime object. """ now = arrow.now() _date = now.replace(day=p_datetime.day, month=p_datetime.month, year=p_datetime.year) return _date.humanize(now).replace('just now', 'today')
python
def humanize_date(p_datetime): """ Returns a relative date string from a datetime object. """ now = arrow.now() _date = now.replace(day=p_datetime.day, month=p_datetime.month, year=p_datetime.year) return _date.humanize(now).replace('just now', 'today')
[ "def", "humanize_date", "(", "p_datetime", ")", ":", "now", "=", "arrow", ".", "now", "(", ")", "_date", "=", "now", ".", "replace", "(", "day", "=", "p_datetime", ".", "day", ",", "month", "=", "p_datetime", ".", "month", ",", "year", "=", "p_datetime", ".", "year", ")", "return", "_date", ".", "humanize", "(", "now", ")", ".", "replace", "(", "'just now'", ",", "'today'", ")" ]
Returns a relative date string from a datetime object.
[ "Returns", "a", "relative", "date", "string", "from", "a", "datetime", "object", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Utils.py#L112-L116
11,465
bram85/topydo
topydo/ui/columns/Main.py
UIApplication._check_id_validity
def _check_id_validity(self, p_ids): """ Checks if there are any invalid todo IDs in p_ids list. Returns proper error message if any ID is invalid and None otherwise. """ errors = [] valid_ids = self.todolist.ids() if len(p_ids) == 0: errors.append('No todo item was selected') else: errors = ["Invalid todo ID: {}".format(todo_id) for todo_id in p_ids - valid_ids] errors = '\n'.join(errors) if errors else None return errors
python
def _check_id_validity(self, p_ids): """ Checks if there are any invalid todo IDs in p_ids list. Returns proper error message if any ID is invalid and None otherwise. """ errors = [] valid_ids = self.todolist.ids() if len(p_ids) == 0: errors.append('No todo item was selected') else: errors = ["Invalid todo ID: {}".format(todo_id) for todo_id in p_ids - valid_ids] errors = '\n'.join(errors) if errors else None return errors
[ "def", "_check_id_validity", "(", "self", ",", "p_ids", ")", ":", "errors", "=", "[", "]", "valid_ids", "=", "self", ".", "todolist", ".", "ids", "(", ")", "if", "len", "(", "p_ids", ")", "==", "0", ":", "errors", ".", "append", "(", "'No todo item was selected'", ")", "else", ":", "errors", "=", "[", "\"Invalid todo ID: {}\"", ".", "format", "(", "todo_id", ")", "for", "todo_id", "in", "p_ids", "-", "valid_ids", "]", "errors", "=", "'\\n'", ".", "join", "(", "errors", ")", "if", "errors", "else", "None", "return", "errors" ]
Checks if there are any invalid todo IDs in p_ids list. Returns proper error message if any ID is invalid and None otherwise.
[ "Checks", "if", "there", "are", "any", "invalid", "todo", "IDs", "in", "p_ids", "list", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/Main.py#L286-L302
11,466
bram85/topydo
topydo/ui/columns/Main.py
UIApplication._execute_handler
def _execute_handler(self, p_command, p_todo_id=None, p_output=None): """ Executes a command, given as a string. """ p_output = p_output or self._output self._console_visible = False self._last_cmd = (p_command, p_output == self._output) try: p_command = shlex.split(p_command) except ValueError as verr: self._print_to_console('Error: ' + str(verr)) return try: subcommand, args = get_subcommand(p_command) except ConfigError as cerr: self._print_to_console( 'Error: {}. Check your aliases configuration.'.format(cerr)) return if subcommand is None: self._print_to_console(GENERIC_HELP) return env_args = (self.todolist, p_output, self._output, self._input) ids = None if '{}' in args: if self._has_marked_todos(): ids = self.marked_todos else: ids = {p_todo_id} if p_todo_id else set() invalid_ids = self._check_id_validity(ids) if invalid_ids: self._print_to_console('Error: ' + invalid_ids) return transaction = Transaction(subcommand, env_args, ids) transaction.prepare(args) label = transaction.label self._backup(subcommand, p_label=label) try: if transaction.execute(): post_archive_action = transaction.execute_post_archive_actions self._post_archive_action = post_archive_action self._post_execute() else: self._rollback() except TypeError: # TODO: show error message pass
python
def _execute_handler(self, p_command, p_todo_id=None, p_output=None): """ Executes a command, given as a string. """ p_output = p_output or self._output self._console_visible = False self._last_cmd = (p_command, p_output == self._output) try: p_command = shlex.split(p_command) except ValueError as verr: self._print_to_console('Error: ' + str(verr)) return try: subcommand, args = get_subcommand(p_command) except ConfigError as cerr: self._print_to_console( 'Error: {}. Check your aliases configuration.'.format(cerr)) return if subcommand is None: self._print_to_console(GENERIC_HELP) return env_args = (self.todolist, p_output, self._output, self._input) ids = None if '{}' in args: if self._has_marked_todos(): ids = self.marked_todos else: ids = {p_todo_id} if p_todo_id else set() invalid_ids = self._check_id_validity(ids) if invalid_ids: self._print_to_console('Error: ' + invalid_ids) return transaction = Transaction(subcommand, env_args, ids) transaction.prepare(args) label = transaction.label self._backup(subcommand, p_label=label) try: if transaction.execute(): post_archive_action = transaction.execute_post_archive_actions self._post_archive_action = post_archive_action self._post_execute() else: self._rollback() except TypeError: # TODO: show error message pass
[ "def", "_execute_handler", "(", "self", ",", "p_command", ",", "p_todo_id", "=", "None", ",", "p_output", "=", "None", ")", ":", "p_output", "=", "p_output", "or", "self", ".", "_output", "self", ".", "_console_visible", "=", "False", "self", ".", "_last_cmd", "=", "(", "p_command", ",", "p_output", "==", "self", ".", "_output", ")", "try", ":", "p_command", "=", "shlex", ".", "split", "(", "p_command", ")", "except", "ValueError", "as", "verr", ":", "self", ".", "_print_to_console", "(", "'Error: '", "+", "str", "(", "verr", ")", ")", "return", "try", ":", "subcommand", ",", "args", "=", "get_subcommand", "(", "p_command", ")", "except", "ConfigError", "as", "cerr", ":", "self", ".", "_print_to_console", "(", "'Error: {}. Check your aliases configuration.'", ".", "format", "(", "cerr", ")", ")", "return", "if", "subcommand", "is", "None", ":", "self", ".", "_print_to_console", "(", "GENERIC_HELP", ")", "return", "env_args", "=", "(", "self", ".", "todolist", ",", "p_output", ",", "self", ".", "_output", ",", "self", ".", "_input", ")", "ids", "=", "None", "if", "'{}'", "in", "args", ":", "if", "self", ".", "_has_marked_todos", "(", ")", ":", "ids", "=", "self", ".", "marked_todos", "else", ":", "ids", "=", "{", "p_todo_id", "}", "if", "p_todo_id", "else", "set", "(", ")", "invalid_ids", "=", "self", ".", "_check_id_validity", "(", "ids", ")", "if", "invalid_ids", ":", "self", ".", "_print_to_console", "(", "'Error: '", "+", "invalid_ids", ")", "return", "transaction", "=", "Transaction", "(", "subcommand", ",", "env_args", ",", "ids", ")", "transaction", ".", "prepare", "(", "args", ")", "label", "=", "transaction", ".", "label", "self", ".", "_backup", "(", "subcommand", ",", "p_label", "=", "label", ")", "try", ":", "if", "transaction", ".", "execute", "(", ")", ":", "post_archive_action", "=", "transaction", ".", "execute_post_archive_actions", "self", ".", "_post_archive_action", "=", "post_archive_action", "self", ".", "_post_execute", "(", ")", "else", ":", "self", ".", "_rollback", "(", ")", "except", "TypeError", ":", "# TODO: show error message", "pass" ]
Executes a command, given as a string.
[ "Executes", "a", "command", "given", "as", "a", "string", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/Main.py#L304-L359
11,467
bram85/topydo
topydo/ui/columns/Main.py
UIApplication._viewdata_to_view
def _viewdata_to_view(self, p_data): """ Converts a dictionary describing a view to an actual UIView instance. """ sorter = Sorter(p_data['sortexpr'], p_data['groupexpr']) filters = [] if not p_data['show_all']: filters.append(DependencyFilter(self.todolist)) filters.append(RelevanceFilter()) filters.append(HiddenTagFilter()) filters += get_filter_list(p_data['filterexpr'].split()) return UIView(sorter, filters, self.todolist, p_data)
python
def _viewdata_to_view(self, p_data): """ Converts a dictionary describing a view to an actual UIView instance. """ sorter = Sorter(p_data['sortexpr'], p_data['groupexpr']) filters = [] if not p_data['show_all']: filters.append(DependencyFilter(self.todolist)) filters.append(RelevanceFilter()) filters.append(HiddenTagFilter()) filters += get_filter_list(p_data['filterexpr'].split()) return UIView(sorter, filters, self.todolist, p_data)
[ "def", "_viewdata_to_view", "(", "self", ",", "p_data", ")", ":", "sorter", "=", "Sorter", "(", "p_data", "[", "'sortexpr'", "]", ",", "p_data", "[", "'groupexpr'", "]", ")", "filters", "=", "[", "]", "if", "not", "p_data", "[", "'show_all'", "]", ":", "filters", ".", "append", "(", "DependencyFilter", "(", "self", ".", "todolist", ")", ")", "filters", ".", "append", "(", "RelevanceFilter", "(", ")", ")", "filters", ".", "append", "(", "HiddenTagFilter", "(", ")", ")", "filters", "+=", "get_filter_list", "(", "p_data", "[", "'filterexpr'", "]", ".", "split", "(", ")", ")", "return", "UIView", "(", "sorter", ",", "filters", ",", "self", ".", "todolist", ",", "p_data", ")" ]
Converts a dictionary describing a view to an actual UIView instance.
[ "Converts", "a", "dictionary", "describing", "a", "view", "to", "an", "actual", "UIView", "instance", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/Main.py#L479-L493
11,468
bram85/topydo
topydo/ui/columns/Main.py
UIApplication._update_view
def _update_view(self, p_data): """ Creates a view from the data entered in the view widget. """ view = self._viewdata_to_view(p_data) if self.column_mode == _APPEND_COLUMN or self.column_mode == _COPY_COLUMN: self._add_column(view) elif self.column_mode == _INSERT_COLUMN: self._add_column(view, self.columns.focus_position) elif self.column_mode == _EDIT_COLUMN: current_column = self.columns.focus current_column.title = p_data['title'] current_column.view = view self._viewwidget_visible = False self._blur_commandline()
python
def _update_view(self, p_data): """ Creates a view from the data entered in the view widget. """ view = self._viewdata_to_view(p_data) if self.column_mode == _APPEND_COLUMN or self.column_mode == _COPY_COLUMN: self._add_column(view) elif self.column_mode == _INSERT_COLUMN: self._add_column(view, self.columns.focus_position) elif self.column_mode == _EDIT_COLUMN: current_column = self.columns.focus current_column.title = p_data['title'] current_column.view = view self._viewwidget_visible = False self._blur_commandline()
[ "def", "_update_view", "(", "self", ",", "p_data", ")", ":", "view", "=", "self", ".", "_viewdata_to_view", "(", "p_data", ")", "if", "self", ".", "column_mode", "==", "_APPEND_COLUMN", "or", "self", ".", "column_mode", "==", "_COPY_COLUMN", ":", "self", ".", "_add_column", "(", "view", ")", "elif", "self", ".", "column_mode", "==", "_INSERT_COLUMN", ":", "self", ".", "_add_column", "(", "view", ",", "self", ".", "columns", ".", "focus_position", ")", "elif", "self", ".", "column_mode", "==", "_EDIT_COLUMN", ":", "current_column", "=", "self", ".", "columns", ".", "focus", "current_column", ".", "title", "=", "p_data", "[", "'title'", "]", "current_column", ".", "view", "=", "view", "self", ".", "_viewwidget_visible", "=", "False", "self", ".", "_blur_commandline", "(", ")" ]
Creates a view from the data entered in the view widget.
[ "Creates", "a", "view", "from", "the", "data", "entered", "in", "the", "view", "widget", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/Main.py#L495-L510
11,469
bram85/topydo
topydo/ui/columns/Main.py
UIApplication._add_column
def _add_column(self, p_view, p_pos=None): """ Given an UIView, adds a new column widget with the todos in that view. When no position is given, it is added to the end, otherwise inserted before that position. """ def execute_silent(p_cmd, p_todo_id=None): self._execute_handler(p_cmd, p_todo_id, lambda _: None) todolist = TodoListWidget(p_view, p_view.data['title'], self.keymap) urwid.connect_signal(todolist, 'execute_command_silent', execute_silent) urwid.connect_signal(todolist, 'execute_command', self._execute_handler) urwid.connect_signal(todolist, 'repeat_cmd', self._repeat_last_cmd) urwid.connect_signal(todolist, 'refresh', self.mainloop.screen.clear) urwid.connect_signal(todolist, 'add_pending_action', self._set_alarm) urwid.connect_signal(todolist, 'remove_pending_action', self._remove_alarm) urwid.connect_signal(todolist, 'column_action', self._column_action_handler) urwid.connect_signal(todolist, 'show_keystate', self._print_keystate) urwid.connect_signal(todolist, 'toggle_mark', self._process_mark_toggle) options = self.columns.options( width_type='given', width_amount=config().column_width(), box_widget=True ) item = (todolist, options) if p_pos == None: p_pos = len(self.columns.contents) self.columns.contents.insert(p_pos, item) self.columns.focus_position = p_pos self._blur_commandline()
python
def _add_column(self, p_view, p_pos=None): """ Given an UIView, adds a new column widget with the todos in that view. When no position is given, it is added to the end, otherwise inserted before that position. """ def execute_silent(p_cmd, p_todo_id=None): self._execute_handler(p_cmd, p_todo_id, lambda _: None) todolist = TodoListWidget(p_view, p_view.data['title'], self.keymap) urwid.connect_signal(todolist, 'execute_command_silent', execute_silent) urwid.connect_signal(todolist, 'execute_command', self._execute_handler) urwid.connect_signal(todolist, 'repeat_cmd', self._repeat_last_cmd) urwid.connect_signal(todolist, 'refresh', self.mainloop.screen.clear) urwid.connect_signal(todolist, 'add_pending_action', self._set_alarm) urwid.connect_signal(todolist, 'remove_pending_action', self._remove_alarm) urwid.connect_signal(todolist, 'column_action', self._column_action_handler) urwid.connect_signal(todolist, 'show_keystate', self._print_keystate) urwid.connect_signal(todolist, 'toggle_mark', self._process_mark_toggle) options = self.columns.options( width_type='given', width_amount=config().column_width(), box_widget=True ) item = (todolist, options) if p_pos == None: p_pos = len(self.columns.contents) self.columns.contents.insert(p_pos, item) self.columns.focus_position = p_pos self._blur_commandline()
[ "def", "_add_column", "(", "self", ",", "p_view", ",", "p_pos", "=", "None", ")", ":", "def", "execute_silent", "(", "p_cmd", ",", "p_todo_id", "=", "None", ")", ":", "self", ".", "_execute_handler", "(", "p_cmd", ",", "p_todo_id", ",", "lambda", "_", ":", "None", ")", "todolist", "=", "TodoListWidget", "(", "p_view", ",", "p_view", ".", "data", "[", "'title'", "]", ",", "self", ".", "keymap", ")", "urwid", ".", "connect_signal", "(", "todolist", ",", "'execute_command_silent'", ",", "execute_silent", ")", "urwid", ".", "connect_signal", "(", "todolist", ",", "'execute_command'", ",", "self", ".", "_execute_handler", ")", "urwid", ".", "connect_signal", "(", "todolist", ",", "'repeat_cmd'", ",", "self", ".", "_repeat_last_cmd", ")", "urwid", ".", "connect_signal", "(", "todolist", ",", "'refresh'", ",", "self", ".", "mainloop", ".", "screen", ".", "clear", ")", "urwid", ".", "connect_signal", "(", "todolist", ",", "'add_pending_action'", ",", "self", ".", "_set_alarm", ")", "urwid", ".", "connect_signal", "(", "todolist", ",", "'remove_pending_action'", ",", "self", ".", "_remove_alarm", ")", "urwid", ".", "connect_signal", "(", "todolist", ",", "'column_action'", ",", "self", ".", "_column_action_handler", ")", "urwid", ".", "connect_signal", "(", "todolist", ",", "'show_keystate'", ",", "self", ".", "_print_keystate", ")", "urwid", ".", "connect_signal", "(", "todolist", ",", "'toggle_mark'", ",", "self", ".", "_process_mark_toggle", ")", "options", "=", "self", ".", "columns", ".", "options", "(", "width_type", "=", "'given'", ",", "width_amount", "=", "config", "(", ")", ".", "column_width", "(", ")", ",", "box_widget", "=", "True", ")", "item", "=", "(", "todolist", ",", "options", ")", "if", "p_pos", "==", "None", ":", "p_pos", "=", "len", "(", "self", ".", "columns", ".", "contents", ")", "self", ".", "columns", ".", "contents", ".", "insert", "(", "p_pos", ",", "item", ")", "self", ".", "columns", ".", "focus_position", "=", "p_pos", "self", ".", "_blur_commandline", "(", ")" ]
Given an UIView, adds a new column widget with the todos in that view. When no position is given, it is added to the end, otherwise inserted before that position.
[ "Given", "an", "UIView", "adds", "a", "new", "column", "widget", "with", "the", "todos", "in", "that", "view", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/Main.py#L512-L549
11,470
bram85/topydo
topydo/ui/columns/Main.py
UIApplication._process_mark_toggle
def _process_mark_toggle(self, p_todo_id, p_force=None): """ Adds p_todo_id to marked_todos attribute and returns True if p_todo_id is not already marked. Removes p_todo_id from marked_todos and returns False otherwise. p_force parameter accepting 'mark' or 'unmark' values, if set, can force desired action without checking p_todo_id presence in marked_todos. """ if p_force in ['mark', 'unmark']: action = p_force else: action = 'mark' if p_todo_id not in self.marked_todos else 'unmark' if action == 'mark': self.marked_todos.add(p_todo_id) return True else: self.marked_todos.remove(p_todo_id) return False
python
def _process_mark_toggle(self, p_todo_id, p_force=None): """ Adds p_todo_id to marked_todos attribute and returns True if p_todo_id is not already marked. Removes p_todo_id from marked_todos and returns False otherwise. p_force parameter accepting 'mark' or 'unmark' values, if set, can force desired action without checking p_todo_id presence in marked_todos. """ if p_force in ['mark', 'unmark']: action = p_force else: action = 'mark' if p_todo_id not in self.marked_todos else 'unmark' if action == 'mark': self.marked_todos.add(p_todo_id) return True else: self.marked_todos.remove(p_todo_id) return False
[ "def", "_process_mark_toggle", "(", "self", ",", "p_todo_id", ",", "p_force", "=", "None", ")", ":", "if", "p_force", "in", "[", "'mark'", ",", "'unmark'", "]", ":", "action", "=", "p_force", "else", ":", "action", "=", "'mark'", "if", "p_todo_id", "not", "in", "self", ".", "marked_todos", "else", "'unmark'", "if", "action", "==", "'mark'", ":", "self", ".", "marked_todos", ".", "add", "(", "p_todo_id", ")", "return", "True", "else", ":", "self", ".", "marked_todos", ".", "remove", "(", "p_todo_id", ")", "return", "False" ]
Adds p_todo_id to marked_todos attribute and returns True if p_todo_id is not already marked. Removes p_todo_id from marked_todos and returns False otherwise. p_force parameter accepting 'mark' or 'unmark' values, if set, can force desired action without checking p_todo_id presence in marked_todos.
[ "Adds", "p_todo_id", "to", "marked_todos", "attribute", "and", "returns", "True", "if", "p_todo_id", "is", "not", "already", "marked", ".", "Removes", "p_todo_id", "from", "marked_todos", "and", "returns", "False", "otherwise", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/Main.py#L683-L702
11,471
bram85/topydo
topydo/ui/columns/ViewWidget.py
ViewWidget.reset
def reset(self): """ Resets the form. """ self.titleedit.set_edit_text("") self.sortedit.set_edit_text("") self.filteredit.set_edit_text("") self.relevantradio.set_state(True) self.pile.focus_item = 0
python
def reset(self): """ Resets the form. """ self.titleedit.set_edit_text("") self.sortedit.set_edit_text("") self.filteredit.set_edit_text("") self.relevantradio.set_state(True) self.pile.focus_item = 0
[ "def", "reset", "(", "self", ")", ":", "self", ".", "titleedit", ".", "set_edit_text", "(", "\"\"", ")", "self", ".", "sortedit", ".", "set_edit_text", "(", "\"\"", ")", "self", ".", "filteredit", ".", "set_edit_text", "(", "\"\"", ")", "self", ".", "relevantradio", ".", "set_state", "(", "True", ")", "self", ".", "pile", ".", "focus_item", "=", "0" ]
Resets the form.
[ "Resets", "the", "form", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/ViewWidget.py#L71-L77
11,472
bram85/topydo
topydo/lib/TodoBase.py
TodoBase.has_tag
def has_tag(self, p_key, p_value=""): """ Returns true when there is at least one tag with the given key. If a value is passed, it will only return true when there exists a tag with the given key-value combination. """ tags = self.fields['tags'] return p_key in tags and (p_value == "" or p_value in tags[p_key])
python
def has_tag(self, p_key, p_value=""): """ Returns true when there is at least one tag with the given key. If a value is passed, it will only return true when there exists a tag with the given key-value combination. """ tags = self.fields['tags'] return p_key in tags and (p_value == "" or p_value in tags[p_key])
[ "def", "has_tag", "(", "self", ",", "p_key", ",", "p_value", "=", "\"\"", ")", ":", "tags", "=", "self", ".", "fields", "[", "'tags'", "]", "return", "p_key", "in", "tags", "and", "(", "p_value", "==", "\"\"", "or", "p_value", "in", "tags", "[", "p_key", "]", ")" ]
Returns true when there is at least one tag with the given key. If a value is passed, it will only return true when there exists a tag with the given key-value combination.
[ "Returns", "true", "when", "there", "is", "at", "least", "one", "tag", "with", "the", "given", "key", ".", "If", "a", "value", "is", "passed", "it", "will", "only", "return", "true", "when", "there", "exists", "a", "tag", "with", "the", "given", "key", "-", "value", "combination", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoBase.py#L60-L67
11,473
bram85/topydo
topydo/lib/TodoBase.py
TodoBase._remove_tag_helper
def _remove_tag_helper(self, p_key, p_value): """ Removes a tag from the internal todo dictionary. Only those instances with the given value are removed. If the value is empty, all tags with the given key are removed. """ tags = self.fields['tags'] try: tags[p_key] = [t for t in tags[p_key] if p_value != "" and t != p_value] if len(tags[p_key]) == 0: del tags[p_key] except KeyError: pass
python
def _remove_tag_helper(self, p_key, p_value): """ Removes a tag from the internal todo dictionary. Only those instances with the given value are removed. If the value is empty, all tags with the given key are removed. """ tags = self.fields['tags'] try: tags[p_key] = [t for t in tags[p_key] if p_value != "" and t != p_value] if len(tags[p_key]) == 0: del tags[p_key] except KeyError: pass
[ "def", "_remove_tag_helper", "(", "self", ",", "p_key", ",", "p_value", ")", ":", "tags", "=", "self", ".", "fields", "[", "'tags'", "]", "try", ":", "tags", "[", "p_key", "]", "=", "[", "t", "for", "t", "in", "tags", "[", "p_key", "]", "if", "p_value", "!=", "\"\"", "and", "t", "!=", "p_value", "]", "if", "len", "(", "tags", "[", "p_key", "]", ")", "==", "0", ":", "del", "tags", "[", "p_key", "]", "except", "KeyError", ":", "pass" ]
Removes a tag from the internal todo dictionary. Only those instances with the given value are removed. If the value is empty, all tags with the given key are removed.
[ "Removes", "a", "tag", "from", "the", "internal", "todo", "dictionary", ".", "Only", "those", "instances", "with", "the", "given", "value", "are", "removed", ".", "If", "the", "value", "is", "empty", "all", "tags", "with", "the", "given", "key", "are", "removed", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoBase.py#L73-L86
11,474
bram85/topydo
topydo/lib/TodoBase.py
TodoBase.set_tag
def set_tag(self, p_key, p_value="", p_force_add=False, p_old_value=""): """ Sets a occurrence of the tag identified by p_key. Sets an arbitrary instance of the tag when the todo contains multiple tags with this key. When p_key does not exist, the tag is added. When p_value is not set, the tag will be removed. When p_force_add is true, a tag will always be added to the todo, in case there is already a tag with the given key. When p_old_value is set, all tags having this value will be set to the new value. """ if p_value == "": self.remove_tag(p_key, p_old_value) return tags = self.fields['tags'] value = p_old_value if p_old_value else self.tag_value(p_key) if not p_force_add and value: self._remove_tag_helper(p_key, value) self.src = re.sub( r'\b' + p_key + ':' + value + r'\b', p_key + ':' + p_value, self.src ) else: self.src += ' ' + p_key + ':' + p_value try: tags[p_key].append(p_value) except KeyError: tags[p_key] = [p_value]
python
def set_tag(self, p_key, p_value="", p_force_add=False, p_old_value=""): """ Sets a occurrence of the tag identified by p_key. Sets an arbitrary instance of the tag when the todo contains multiple tags with this key. When p_key does not exist, the tag is added. When p_value is not set, the tag will be removed. When p_force_add is true, a tag will always be added to the todo, in case there is already a tag with the given key. When p_old_value is set, all tags having this value will be set to the new value. """ if p_value == "": self.remove_tag(p_key, p_old_value) return tags = self.fields['tags'] value = p_old_value if p_old_value else self.tag_value(p_key) if not p_force_add and value: self._remove_tag_helper(p_key, value) self.src = re.sub( r'\b' + p_key + ':' + value + r'\b', p_key + ':' + p_value, self.src ) else: self.src += ' ' + p_key + ':' + p_value try: tags[p_key].append(p_value) except KeyError: tags[p_key] = [p_value]
[ "def", "set_tag", "(", "self", ",", "p_key", ",", "p_value", "=", "\"\"", ",", "p_force_add", "=", "False", ",", "p_old_value", "=", "\"\"", ")", ":", "if", "p_value", "==", "\"\"", ":", "self", ".", "remove_tag", "(", "p_key", ",", "p_old_value", ")", "return", "tags", "=", "self", ".", "fields", "[", "'tags'", "]", "value", "=", "p_old_value", "if", "p_old_value", "else", "self", ".", "tag_value", "(", "p_key", ")", "if", "not", "p_force_add", "and", "value", ":", "self", ".", "_remove_tag_helper", "(", "p_key", ",", "value", ")", "self", ".", "src", "=", "re", ".", "sub", "(", "r'\\b'", "+", "p_key", "+", "':'", "+", "value", "+", "r'\\b'", ",", "p_key", "+", "':'", "+", "p_value", ",", "self", ".", "src", ")", "else", ":", "self", ".", "src", "+=", "' '", "+", "p_key", "+", "':'", "+", "p_value", "try", ":", "tags", "[", "p_key", "]", ".", "append", "(", "p_value", ")", "except", "KeyError", ":", "tags", "[", "p_key", "]", "=", "[", "p_value", "]" ]
Sets a occurrence of the tag identified by p_key. Sets an arbitrary instance of the tag when the todo contains multiple tags with this key. When p_key does not exist, the tag is added. When p_value is not set, the tag will be removed. When p_force_add is true, a tag will always be added to the todo, in case there is already a tag with the given key. When p_old_value is set, all tags having this value will be set to the new value.
[ "Sets", "a", "occurrence", "of", "the", "tag", "identified", "by", "p_key", ".", "Sets", "an", "arbitrary", "instance", "of", "the", "tag", "when", "the", "todo", "contains", "multiple", "tags", "with", "this", "key", ".", "When", "p_key", "does", "not", "exist", "the", "tag", "is", "added", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoBase.py#L88-L123
11,475
bram85/topydo
topydo/lib/TodoBase.py
TodoBase.tags
def tags(self): """ Returns a list of tuples with key-value pairs representing tags in this todo item. """ tags = self.fields['tags'] return [(t, v) for t in tags for v in tags[t]]
python
def tags(self): """ Returns a list of tuples with key-value pairs representing tags in this todo item. """ tags = self.fields['tags'] return [(t, v) for t in tags for v in tags[t]]
[ "def", "tags", "(", "self", ")", ":", "tags", "=", "self", ".", "fields", "[", "'tags'", "]", "return", "[", "(", "t", ",", "v", ")", "for", "t", "in", "tags", "for", "v", "in", "tags", "[", "t", "]", "]" ]
Returns a list of tuples with key-value pairs representing tags in this todo item.
[ "Returns", "a", "list", "of", "tuples", "with", "key", "-", "value", "pairs", "representing", "tags", "in", "this", "todo", "item", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoBase.py#L138-L144
11,476
bram85/topydo
topydo/lib/TodoBase.py
TodoBase.set_source_text
def set_source_text(self, p_text): """ Sets the todo source text. The text will be parsed again. """ self.src = p_text.strip() self.fields = parse_line(self.src)
python
def set_source_text(self, p_text): """ Sets the todo source text. The text will be parsed again. """ self.src = p_text.strip() self.fields = parse_line(self.src)
[ "def", "set_source_text", "(", "self", ",", "p_text", ")", ":", "self", ".", "src", "=", "p_text", ".", "strip", "(", ")", "self", ".", "fields", "=", "parse_line", "(", "self", ".", "src", ")" ]
Sets the todo source text. The text will be parsed again.
[ "Sets", "the", "todo", "source", "text", ".", "The", "text", "will", "be", "parsed", "again", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoBase.py#L177-L180
11,477
bram85/topydo
topydo/lib/TodoBase.py
TodoBase.set_completed
def set_completed(self, p_completion_date=date.today()): """ Marks the todo as complete. Sets the completed flag and sets the completion date to today. """ if not self.is_completed(): self.set_priority(None) self.fields['completed'] = True self.fields['completionDate'] = p_completion_date self.src = re.sub(r'^(\([A-Z]\) )?', 'x ' + p_completion_date.isoformat() + ' ', self.src)
python
def set_completed(self, p_completion_date=date.today()): """ Marks the todo as complete. Sets the completed flag and sets the completion date to today. """ if not self.is_completed(): self.set_priority(None) self.fields['completed'] = True self.fields['completionDate'] = p_completion_date self.src = re.sub(r'^(\([A-Z]\) )?', 'x ' + p_completion_date.isoformat() + ' ', self.src)
[ "def", "set_completed", "(", "self", ",", "p_completion_date", "=", "date", ".", "today", "(", ")", ")", ":", "if", "not", "self", ".", "is_completed", "(", ")", ":", "self", ".", "set_priority", "(", "None", ")", "self", ".", "fields", "[", "'completed'", "]", "=", "True", "self", ".", "fields", "[", "'completionDate'", "]", "=", "p_completion_date", "self", ".", "src", "=", "re", ".", "sub", "(", "r'^(\\([A-Z]\\) )?'", ",", "'x '", "+", "p_completion_date", ".", "isoformat", "(", ")", "+", "' '", ",", "self", ".", "src", ")" ]
Marks the todo as complete. Sets the completed flag and sets the completion date to today.
[ "Marks", "the", "todo", "as", "complete", ".", "Sets", "the", "completed", "flag", "and", "sets", "the", "completion", "date", "to", "today", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoBase.py#L201-L214
11,478
bram85/topydo
topydo/lib/TodoBase.py
TodoBase.set_creation_date
def set_creation_date(self, p_date=date.today()): """ Sets the creation date of a todo. Should be passed a date object. """ self.fields['creationDate'] = p_date # not particularly pretty, but inspired by # http://bugs.python.org/issue1519638 non-existent matches trigger # exceptions, hence the lambda self.src = re.sub( r'^(x \d{4}-\d{2}-\d{2} |\([A-Z]\) )?(\d{4}-\d{2}-\d{2} )?(.*)$', lambda m: u"{}{} {}".format(m.group(1) or '', p_date.isoformat(), m.group(3)), self.src)
python
def set_creation_date(self, p_date=date.today()): """ Sets the creation date of a todo. Should be passed a date object. """ self.fields['creationDate'] = p_date # not particularly pretty, but inspired by # http://bugs.python.org/issue1519638 non-existent matches trigger # exceptions, hence the lambda self.src = re.sub( r'^(x \d{4}-\d{2}-\d{2} |\([A-Z]\) )?(\d{4}-\d{2}-\d{2} )?(.*)$', lambda m: u"{}{} {}".format(m.group(1) or '', p_date.isoformat(), m.group(3)), self.src)
[ "def", "set_creation_date", "(", "self", ",", "p_date", "=", "date", ".", "today", "(", ")", ")", ":", "self", ".", "fields", "[", "'creationDate'", "]", "=", "p_date", "# not particularly pretty, but inspired by", "# http://bugs.python.org/issue1519638 non-existent matches trigger", "# exceptions, hence the lambda", "self", ".", "src", "=", "re", ".", "sub", "(", "r'^(x \\d{4}-\\d{2}-\\d{2} |\\([A-Z]\\) )?(\\d{4}-\\d{2}-\\d{2} )?(.*)$'", ",", "lambda", "m", ":", "u\"{}{} {}\"", ".", "format", "(", "m", ".", "group", "(", "1", ")", "or", "''", ",", "p_date", ".", "isoformat", "(", ")", ",", "m", ".", "group", "(", "3", ")", ")", ",", "self", ".", "src", ")" ]
Sets the creation date of a todo. Should be passed a date object.
[ "Sets", "the", "creation", "date", "of", "a", "todo", ".", "Should", "be", "passed", "a", "date", "object", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoBase.py#L216-L229
11,479
bram85/topydo
topydo/ui/columns/TodoListWidget.py
TodoListWidget.update
def update(self): """ Updates the todo list according to the todos in the view associated with this list. """ old_focus_position = self.todolist.focus id_length = max_id_length(self.view.todolist.count()) del self.todolist[:] for group, todos in self.view.groups.items(): if len(self.view.groups) > 1: grouplabel = ", ".join(group) self.todolist.append(urwid.Text(grouplabel)) self.todolist.append(urwid.Divider('-')) for todo in todos: todowidget = TodoWidget.create(todo, id_length) todowidget.number = self.view.todolist.number(todo) self.todolist.append(todowidget) self.todolist.append(urwid.Divider('-')) if old_focus_position: try: self.todolist.set_focus(old_focus_position) except IndexError: # scroll to the bottom if the last item disappeared from column # -2 for the same reason as in self._scroll_to_bottom() self.todolist.set_focus(len(self.todolist) - 2)
python
def update(self): """ Updates the todo list according to the todos in the view associated with this list. """ old_focus_position = self.todolist.focus id_length = max_id_length(self.view.todolist.count()) del self.todolist[:] for group, todos in self.view.groups.items(): if len(self.view.groups) > 1: grouplabel = ", ".join(group) self.todolist.append(urwid.Text(grouplabel)) self.todolist.append(urwid.Divider('-')) for todo in todos: todowidget = TodoWidget.create(todo, id_length) todowidget.number = self.view.todolist.number(todo) self.todolist.append(todowidget) self.todolist.append(urwid.Divider('-')) if old_focus_position: try: self.todolist.set_focus(old_focus_position) except IndexError: # scroll to the bottom if the last item disappeared from column # -2 for the same reason as in self._scroll_to_bottom() self.todolist.set_focus(len(self.todolist) - 2)
[ "def", "update", "(", "self", ")", ":", "old_focus_position", "=", "self", ".", "todolist", ".", "focus", "id_length", "=", "max_id_length", "(", "self", ".", "view", ".", "todolist", ".", "count", "(", ")", ")", "del", "self", ".", "todolist", "[", ":", "]", "for", "group", ",", "todos", "in", "self", ".", "view", ".", "groups", ".", "items", "(", ")", ":", "if", "len", "(", "self", ".", "view", ".", "groups", ")", ">", "1", ":", "grouplabel", "=", "\", \"", ".", "join", "(", "group", ")", "self", ".", "todolist", ".", "append", "(", "urwid", ".", "Text", "(", "grouplabel", ")", ")", "self", ".", "todolist", ".", "append", "(", "urwid", ".", "Divider", "(", "'-'", ")", ")", "for", "todo", "in", "todos", ":", "todowidget", "=", "TodoWidget", ".", "create", "(", "todo", ",", "id_length", ")", "todowidget", ".", "number", "=", "self", ".", "view", ".", "todolist", ".", "number", "(", "todo", ")", "self", ".", "todolist", ".", "append", "(", "todowidget", ")", "self", ".", "todolist", ".", "append", "(", "urwid", ".", "Divider", "(", "'-'", ")", ")", "if", "old_focus_position", ":", "try", ":", "self", ".", "todolist", ".", "set_focus", "(", "old_focus_position", ")", "except", "IndexError", ":", "# scroll to the bottom if the last item disappeared from column", "# -2 for the same reason as in self._scroll_to_bottom()", "self", ".", "todolist", ".", "set_focus", "(", "len", "(", "self", ".", "todolist", ")", "-", "2", ")" ]
Updates the todo list according to the todos in the view associated with this list.
[ "Updates", "the", "todo", "list", "according", "to", "the", "todos", "in", "the", "view", "associated", "with", "this", "list", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/TodoListWidget.py#L87-L115
11,480
bram85/topydo
topydo/ui/columns/TodoListWidget.py
TodoListWidget._execute_on_selected
def _execute_on_selected(self, p_cmd_str, p_execute_signal): """ Executes command specified by p_cmd_str on selected todo item. p_cmd_str should be a string with one replacement field ('{}') which will be substituted by id of the selected todo item. p_execute_signal is the signal name passed to the main loop. It should be one of 'execute_command' or 'execute_command_silent'. """ try: todo = self.listbox.focus.todo todo_id = str(self.view.todolist.number(todo)) urwid.emit_signal(self, p_execute_signal, p_cmd_str, todo_id) # force screen redraw after editing if p_cmd_str.startswith('edit'): urwid.emit_signal(self, 'refresh') except AttributeError: # No todo item selected pass
python
def _execute_on_selected(self, p_cmd_str, p_execute_signal): """ Executes command specified by p_cmd_str on selected todo item. p_cmd_str should be a string with one replacement field ('{}') which will be substituted by id of the selected todo item. p_execute_signal is the signal name passed to the main loop. It should be one of 'execute_command' or 'execute_command_silent'. """ try: todo = self.listbox.focus.todo todo_id = str(self.view.todolist.number(todo)) urwid.emit_signal(self, p_execute_signal, p_cmd_str, todo_id) # force screen redraw after editing if p_cmd_str.startswith('edit'): urwid.emit_signal(self, 'refresh') except AttributeError: # No todo item selected pass
[ "def", "_execute_on_selected", "(", "self", ",", "p_cmd_str", ",", "p_execute_signal", ")", ":", "try", ":", "todo", "=", "self", ".", "listbox", ".", "focus", ".", "todo", "todo_id", "=", "str", "(", "self", ".", "view", ".", "todolist", ".", "number", "(", "todo", ")", ")", "urwid", ".", "emit_signal", "(", "self", ",", "p_execute_signal", ",", "p_cmd_str", ",", "todo_id", ")", "# force screen redraw after editing", "if", "p_cmd_str", ".", "startswith", "(", "'edit'", ")", ":", "urwid", ".", "emit_signal", "(", "self", ",", "'refresh'", ")", "except", "AttributeError", ":", "# No todo item selected", "pass" ]
Executes command specified by p_cmd_str on selected todo item. p_cmd_str should be a string with one replacement field ('{}') which will be substituted by id of the selected todo item. p_execute_signal is the signal name passed to the main loop. It should be one of 'execute_command' or 'execute_command_silent'.
[ "Executes", "command", "specified", "by", "p_cmd_str", "on", "selected", "todo", "item", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/TodoListWidget.py#L233-L254
11,481
bram85/topydo
topydo/ui/columns/TodoListWidget.py
TodoListWidget.execute_builtin_action
def execute_builtin_action(self, p_action_str, p_size=None): """ Executes built-in action specified in p_action_str. Currently supported actions are: 'up', 'down', 'home', 'end', 'first_column', 'last_column', 'prev_column', 'next_column', 'append_column', 'insert_column', 'edit_column', 'delete_column', 'copy_column', swap_right', 'swap_left', 'postpone', 'postpone_s', 'pri', 'mark', 'mark_all, 'reset' and 'repeat'. """ column_actions = ['first_column', 'last_column', 'prev_column', 'next_column', 'append_column', 'insert_column', 'edit_column', 'delete_column', 'copy_column', 'swap_left', 'swap_right', 'reset', ] if p_action_str in column_actions: urwid.emit_signal(self, 'column_action', p_action_str) elif p_action_str in ['up', 'down']: self.listbox.keypress(p_size, p_action_str) elif p_action_str == 'home': self._scroll_to_top(p_size) elif p_action_str == 'end': self._scroll_to_bottom(p_size) elif p_action_str in ['postpone', 'postpone_s']: pass elif p_action_str == 'pri': pass elif p_action_str == 'mark': self._toggle_marked_status() elif p_action_str == 'mark_all': self._mark_all() elif p_action_str == 'repeat': self._repeat_cmd()
python
def execute_builtin_action(self, p_action_str, p_size=None): """ Executes built-in action specified in p_action_str. Currently supported actions are: 'up', 'down', 'home', 'end', 'first_column', 'last_column', 'prev_column', 'next_column', 'append_column', 'insert_column', 'edit_column', 'delete_column', 'copy_column', swap_right', 'swap_left', 'postpone', 'postpone_s', 'pri', 'mark', 'mark_all, 'reset' and 'repeat'. """ column_actions = ['first_column', 'last_column', 'prev_column', 'next_column', 'append_column', 'insert_column', 'edit_column', 'delete_column', 'copy_column', 'swap_left', 'swap_right', 'reset', ] if p_action_str in column_actions: urwid.emit_signal(self, 'column_action', p_action_str) elif p_action_str in ['up', 'down']: self.listbox.keypress(p_size, p_action_str) elif p_action_str == 'home': self._scroll_to_top(p_size) elif p_action_str == 'end': self._scroll_to_bottom(p_size) elif p_action_str in ['postpone', 'postpone_s']: pass elif p_action_str == 'pri': pass elif p_action_str == 'mark': self._toggle_marked_status() elif p_action_str == 'mark_all': self._mark_all() elif p_action_str == 'repeat': self._repeat_cmd()
[ "def", "execute_builtin_action", "(", "self", ",", "p_action_str", ",", "p_size", "=", "None", ")", ":", "column_actions", "=", "[", "'first_column'", ",", "'last_column'", ",", "'prev_column'", ",", "'next_column'", ",", "'append_column'", ",", "'insert_column'", ",", "'edit_column'", ",", "'delete_column'", ",", "'copy_column'", ",", "'swap_left'", ",", "'swap_right'", ",", "'reset'", ",", "]", "if", "p_action_str", "in", "column_actions", ":", "urwid", ".", "emit_signal", "(", "self", ",", "'column_action'", ",", "p_action_str", ")", "elif", "p_action_str", "in", "[", "'up'", ",", "'down'", "]", ":", "self", ".", "listbox", ".", "keypress", "(", "p_size", ",", "p_action_str", ")", "elif", "p_action_str", "==", "'home'", ":", "self", ".", "_scroll_to_top", "(", "p_size", ")", "elif", "p_action_str", "==", "'end'", ":", "self", ".", "_scroll_to_bottom", "(", "p_size", ")", "elif", "p_action_str", "in", "[", "'postpone'", ",", "'postpone_s'", "]", ":", "pass", "elif", "p_action_str", "==", "'pri'", ":", "pass", "elif", "p_action_str", "==", "'mark'", ":", "self", ".", "_toggle_marked_status", "(", ")", "elif", "p_action_str", "==", "'mark_all'", ":", "self", ".", "_mark_all", "(", ")", "elif", "p_action_str", "==", "'repeat'", ":", "self", ".", "_repeat_cmd", "(", ")" ]
Executes built-in action specified in p_action_str. Currently supported actions are: 'up', 'down', 'home', 'end', 'first_column', 'last_column', 'prev_column', 'next_column', 'append_column', 'insert_column', 'edit_column', 'delete_column', 'copy_column', swap_right', 'swap_left', 'postpone', 'postpone_s', 'pri', 'mark', 'mark_all, 'reset' and 'repeat'.
[ "Executes", "built", "-", "in", "action", "specified", "in", "p_action_str", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/TodoListWidget.py#L277-L318
11,482
bram85/topydo
topydo/ui/columns/TodoListWidget.py
TodoListWidget._add_pending_action
def _add_pending_action(self, p_action, p_size): """ Creates action waiting for execution and forwards it to the mainloop. """ def generate_callback(): def callback(*args): self.resolve_action(p_action, p_size) self.keystate = None return callback urwid.emit_signal(self, 'add_pending_action', generate_callback())
python
def _add_pending_action(self, p_action, p_size): """ Creates action waiting for execution and forwards it to the mainloop. """ def generate_callback(): def callback(*args): self.resolve_action(p_action, p_size) self.keystate = None return callback urwid.emit_signal(self, 'add_pending_action', generate_callback())
[ "def", "_add_pending_action", "(", "self", ",", "p_action", ",", "p_size", ")", ":", "def", "generate_callback", "(", ")", ":", "def", "callback", "(", "*", "args", ")", ":", "self", ".", "resolve_action", "(", "p_action", ",", "p_size", ")", "self", ".", "keystate", "=", "None", "return", "callback", "urwid", ".", "emit_signal", "(", "self", ",", "'add_pending_action'", ",", "generate_callback", "(", ")", ")" ]
Creates action waiting for execution and forwards it to the mainloop.
[ "Creates", "action", "waiting", "for", "execution", "and", "forwards", "it", "to", "the", "mainloop", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/TodoListWidget.py#L320-L331
11,483
bram85/topydo
topydo/lib/TodoFile.py
TodoFile.read
def read(self): """ Reads the todo.txt file and returns a list of todo items. """ todos = [] try: todofile = codecs.open(self.path, 'r', encoding="utf-8") todos = todofile.readlines() todofile.close() except IOError: pass return todos
python
def read(self): """ Reads the todo.txt file and returns a list of todo items. """ todos = [] try: todofile = codecs.open(self.path, 'r', encoding="utf-8") todos = todofile.readlines() todofile.close() except IOError: pass return todos
[ "def", "read", "(", "self", ")", ":", "todos", "=", "[", "]", "try", ":", "todofile", "=", "codecs", ".", "open", "(", "self", ".", "path", ",", "'r'", ",", "encoding", "=", "\"utf-8\"", ")", "todos", "=", "todofile", ".", "readlines", "(", ")", "todofile", ".", "close", "(", ")", "except", "IOError", ":", "pass", "return", "todos" ]
Reads the todo.txt file and returns a list of todo items.
[ "Reads", "the", "todo", ".", "txt", "file", "and", "returns", "a", "list", "of", "todo", "items", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoFile.py#L34-L44
11,484
bram85/topydo
topydo/lib/TodoFile.py
TodoFile.write
def write(self, p_todos): """ Writes all the todo items to the todo.txt file. p_todos can be a list of todo items, or a string that is just written to the file. """ todofile = codecs.open(self.path, 'w', encoding="utf-8") if p_todos is list: for todo in p_todos: todofile.write(str(todo)) else: todofile.write(p_todos) todofile.write("\n") todofile.close()
python
def write(self, p_todos): """ Writes all the todo items to the todo.txt file. p_todos can be a list of todo items, or a string that is just written to the file. """ todofile = codecs.open(self.path, 'w', encoding="utf-8") if p_todos is list: for todo in p_todos: todofile.write(str(todo)) else: todofile.write(p_todos) todofile.write("\n") todofile.close()
[ "def", "write", "(", "self", ",", "p_todos", ")", ":", "todofile", "=", "codecs", ".", "open", "(", "self", ".", "path", ",", "'w'", ",", "encoding", "=", "\"utf-8\"", ")", "if", "p_todos", "is", "list", ":", "for", "todo", "in", "p_todos", ":", "todofile", ".", "write", "(", "str", "(", "todo", ")", ")", "else", ":", "todofile", ".", "write", "(", "p_todos", ")", "todofile", ".", "write", "(", "\"\\n\"", ")", "todofile", ".", "close", "(", ")" ]
Writes all the todo items to the todo.txt file. p_todos can be a list of todo items, or a string that is just written to the file.
[ "Writes", "all", "the", "todo", "items", "to", "the", "todo", ".", "txt", "file", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoFile.py#L46-L64
11,485
bram85/topydo
topydo/ui/UILoader.py
main
def main(): """ Main entry point of the CLI. """ try: args = sys.argv[1:] try: _, args = getopt.getopt(args, MAIN_OPTS, MAIN_LONG_OPTS) except getopt.GetoptError as e: error(str(e)) sys.exit(1) if args[0] == 'prompt': try: from topydo.ui.prompt.Prompt import PromptApplication PromptApplication().run() except ImportError: error("Some additional dependencies for prompt mode were not installed, please install with 'pip3 install topydo[prompt]'") elif args[0] == 'columns': try: from topydo.ui.columns.Main import UIApplication UIApplication().run() except ImportError: error("Some additional dependencies for column mode were not installed, please install with 'pip3 install topydo[columns]'") except NameError as err: if _WINDOWS: error("Column mode is not supported on Windows.") else: error("Could not load column mode: {}".format(err)) else: CLIApplication().run() except IndexError: CLIApplication().run()
python
def main(): """ Main entry point of the CLI. """ try: args = sys.argv[1:] try: _, args = getopt.getopt(args, MAIN_OPTS, MAIN_LONG_OPTS) except getopt.GetoptError as e: error(str(e)) sys.exit(1) if args[0] == 'prompt': try: from topydo.ui.prompt.Prompt import PromptApplication PromptApplication().run() except ImportError: error("Some additional dependencies for prompt mode were not installed, please install with 'pip3 install topydo[prompt]'") elif args[0] == 'columns': try: from topydo.ui.columns.Main import UIApplication UIApplication().run() except ImportError: error("Some additional dependencies for column mode were not installed, please install with 'pip3 install topydo[columns]'") except NameError as err: if _WINDOWS: error("Column mode is not supported on Windows.") else: error("Could not load column mode: {}".format(err)) else: CLIApplication().run() except IndexError: CLIApplication().run()
[ "def", "main", "(", ")", ":", "try", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "try", ":", "_", ",", "args", "=", "getopt", ".", "getopt", "(", "args", ",", "MAIN_OPTS", ",", "MAIN_LONG_OPTS", ")", "except", "getopt", ".", "GetoptError", "as", "e", ":", "error", "(", "str", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "args", "[", "0", "]", "==", "'prompt'", ":", "try", ":", "from", "topydo", ".", "ui", ".", "prompt", ".", "Prompt", "import", "PromptApplication", "PromptApplication", "(", ")", ".", "run", "(", ")", "except", "ImportError", ":", "error", "(", "\"Some additional dependencies for prompt mode were not installed, please install with 'pip3 install topydo[prompt]'\"", ")", "elif", "args", "[", "0", "]", "==", "'columns'", ":", "try", ":", "from", "topydo", ".", "ui", ".", "columns", ".", "Main", "import", "UIApplication", "UIApplication", "(", ")", ".", "run", "(", ")", "except", "ImportError", ":", "error", "(", "\"Some additional dependencies for column mode were not installed, please install with 'pip3 install topydo[columns]'\"", ")", "except", "NameError", "as", "err", ":", "if", "_WINDOWS", ":", "error", "(", "\"Column mode is not supported on Windows.\"", ")", "else", ":", "error", "(", "\"Could not load column mode: {}\"", ".", "format", "(", "err", ")", ")", "else", ":", "CLIApplication", "(", ")", ".", "run", "(", ")", "except", "IndexError", ":", "CLIApplication", "(", ")", ".", "run", "(", ")" ]
Main entry point of the CLI.
[ "Main", "entry", "point", "of", "the", "CLI", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/UILoader.py#L33-L64
11,486
bram85/topydo
topydo/lib/Importance.py
importance
def importance(p_todo, p_ignore_weekend=config().ignore_weekends()): """ Calculates the importance of the given task. Returns an importance of zero when the task has been completed. If p_ignore_weekend is True, the importance value of the due date will be calculated as if Friday is immediately followed by Monday. This in case of a todo list at the office and you don't work during the weekends (you don't, right?) """ result = 2 priority = p_todo.priority() result += IMPORTANCE_VALUE[priority] if priority in IMPORTANCE_VALUE else 0 if p_todo.has_tag(config().tag_due()): days_left = p_todo.days_till_due() if days_left >= 7 and days_left < 14: result += 1 elif days_left >= 2 and days_left < 7: result += 2 elif days_left >= 1 and days_left < 2: result += 3 elif days_left >= 0 and days_left < 1: result += 5 elif days_left < 0: result += 6 if p_ignore_weekend and is_due_next_monday(p_todo): result += 1 if p_todo.has_tag(config().tag_star()): result += 1 return result if not p_todo.is_completed() else 0
python
def importance(p_todo, p_ignore_weekend=config().ignore_weekends()): """ Calculates the importance of the given task. Returns an importance of zero when the task has been completed. If p_ignore_weekend is True, the importance value of the due date will be calculated as if Friday is immediately followed by Monday. This in case of a todo list at the office and you don't work during the weekends (you don't, right?) """ result = 2 priority = p_todo.priority() result += IMPORTANCE_VALUE[priority] if priority in IMPORTANCE_VALUE else 0 if p_todo.has_tag(config().tag_due()): days_left = p_todo.days_till_due() if days_left >= 7 and days_left < 14: result += 1 elif days_left >= 2 and days_left < 7: result += 2 elif days_left >= 1 and days_left < 2: result += 3 elif days_left >= 0 and days_left < 1: result += 5 elif days_left < 0: result += 6 if p_ignore_weekend and is_due_next_monday(p_todo): result += 1 if p_todo.has_tag(config().tag_star()): result += 1 return result if not p_todo.is_completed() else 0
[ "def", "importance", "(", "p_todo", ",", "p_ignore_weekend", "=", "config", "(", ")", ".", "ignore_weekends", "(", ")", ")", ":", "result", "=", "2", "priority", "=", "p_todo", ".", "priority", "(", ")", "result", "+=", "IMPORTANCE_VALUE", "[", "priority", "]", "if", "priority", "in", "IMPORTANCE_VALUE", "else", "0", "if", "p_todo", ".", "has_tag", "(", "config", "(", ")", ".", "tag_due", "(", ")", ")", ":", "days_left", "=", "p_todo", ".", "days_till_due", "(", ")", "if", "days_left", ">=", "7", "and", "days_left", "<", "14", ":", "result", "+=", "1", "elif", "days_left", ">=", "2", "and", "days_left", "<", "7", ":", "result", "+=", "2", "elif", "days_left", ">=", "1", "and", "days_left", "<", "2", ":", "result", "+=", "3", "elif", "days_left", ">=", "0", "and", "days_left", "<", "1", ":", "result", "+=", "5", "elif", "days_left", "<", "0", ":", "result", "+=", "6", "if", "p_ignore_weekend", "and", "is_due_next_monday", "(", "p_todo", ")", ":", "result", "+=", "1", "if", "p_todo", ".", "has_tag", "(", "config", "(", ")", ".", "tag_star", "(", ")", ")", ":", "result", "+=", "1", "return", "result", "if", "not", "p_todo", ".", "is_completed", "(", ")", "else", "0" ]
Calculates the importance of the given task. Returns an importance of zero when the task has been completed. If p_ignore_weekend is True, the importance value of the due date will be calculated as if Friday is immediately followed by Monday. This in case of a todo list at the office and you don't work during the weekends (you don't, right?)
[ "Calculates", "the", "importance", "of", "the", "given", "task", ".", "Returns", "an", "importance", "of", "zero", "when", "the", "task", "has", "been", "completed", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Importance.py#L44-L79
11,487
bram85/topydo
topydo/lib/TodoList.py
TodoList._maintain_dep_graph
def _maintain_dep_graph(self, p_todo): """ Makes sure that the dependency graph is consistent according to the given todo. """ dep_id = p_todo.tag_value('id') # maintain dependency graph if dep_id: self._parentdict[dep_id] = p_todo self._depgraph.add_node(hash(p_todo)) # connect all tasks we have in memory so far that refer to this # task for dep in \ [dep for dep in self._todos if dep.has_tag('p', dep_id)]: self._add_edge(p_todo, dep, dep_id) for dep_id in p_todo.tag_values('p'): try: parent = self._parentdict[dep_id] self._add_edge(parent, p_todo, dep_id) except KeyError: pass
python
def _maintain_dep_graph(self, p_todo): """ Makes sure that the dependency graph is consistent according to the given todo. """ dep_id = p_todo.tag_value('id') # maintain dependency graph if dep_id: self._parentdict[dep_id] = p_todo self._depgraph.add_node(hash(p_todo)) # connect all tasks we have in memory so far that refer to this # task for dep in \ [dep for dep in self._todos if dep.has_tag('p', dep_id)]: self._add_edge(p_todo, dep, dep_id) for dep_id in p_todo.tag_values('p'): try: parent = self._parentdict[dep_id] self._add_edge(parent, p_todo, dep_id) except KeyError: pass
[ "def", "_maintain_dep_graph", "(", "self", ",", "p_todo", ")", ":", "dep_id", "=", "p_todo", ".", "tag_value", "(", "'id'", ")", "# maintain dependency graph", "if", "dep_id", ":", "self", ".", "_parentdict", "[", "dep_id", "]", "=", "p_todo", "self", ".", "_depgraph", ".", "add_node", "(", "hash", "(", "p_todo", ")", ")", "# connect all tasks we have in memory so far that refer to this", "# task", "for", "dep", "in", "[", "dep", "for", "dep", "in", "self", ".", "_todos", "if", "dep", ".", "has_tag", "(", "'p'", ",", "dep_id", ")", "]", ":", "self", ".", "_add_edge", "(", "p_todo", ",", "dep", ",", "dep_id", ")", "for", "dep_id", "in", "p_todo", ".", "tag_values", "(", "'p'", ")", ":", "try", ":", "parent", "=", "self", ".", "_parentdict", "[", "dep_id", "]", "self", ".", "_add_edge", "(", "parent", ",", "p_todo", ",", "dep_id", ")", "except", "KeyError", ":", "pass" ]
Makes sure that the dependency graph is consistent according to the given todo.
[ "Makes", "sure", "that", "the", "dependency", "graph", "is", "consistent", "according", "to", "the", "given", "todo", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoList.py#L86-L109
11,488
bram85/topydo
topydo/lib/TodoList.py
TodoList.add_dependency
def add_dependency(self, p_from_todo, p_to_todo): """ Adds a dependency from task 1 to task 2. """ def find_next_id(): """ Find a new unused ID. Unused means that no task has it as an 'id' value or as a 'p' value. """ def id_exists(p_id): """ Returns True if there exists a todo with the given parent ID. """ for todo in self._todos: number = str(p_id) if todo.has_tag('id', number) or todo.has_tag('p', number): return True return False new_id = 1 while id_exists(new_id): new_id += 1 return str(new_id) def append_projects_to_subtodo(): """ Appends projects in the parent todo item that are not present in the sub todo item. """ if config().append_parent_projects(): for project in p_from_todo.projects() - p_to_todo.projects(): self.append(p_to_todo, "+{}".format(project)) def append_contexts_to_subtodo(): """ Appends contexts in the parent todo item that are not present in the sub todo item. """ if config().append_parent_contexts(): for context in p_from_todo.contexts() - p_to_todo.contexts(): self.append(p_to_todo, "@{}".format(context)) if p_from_todo != p_to_todo and not self._depgraph.has_edge( hash(p_from_todo), hash(p_to_todo)): dep_id = None if p_from_todo.has_tag('id'): dep_id = p_from_todo.tag_value('id') else: dep_id = find_next_id() p_from_todo.set_tag('id', dep_id) p_to_todo.add_tag('p', dep_id) self._add_edge(p_from_todo, p_to_todo, dep_id) append_projects_to_subtodo() append_contexts_to_subtodo() self.dirty = True
python
def add_dependency(self, p_from_todo, p_to_todo): """ Adds a dependency from task 1 to task 2. """ def find_next_id(): """ Find a new unused ID. Unused means that no task has it as an 'id' value or as a 'p' value. """ def id_exists(p_id): """ Returns True if there exists a todo with the given parent ID. """ for todo in self._todos: number = str(p_id) if todo.has_tag('id', number) or todo.has_tag('p', number): return True return False new_id = 1 while id_exists(new_id): new_id += 1 return str(new_id) def append_projects_to_subtodo(): """ Appends projects in the parent todo item that are not present in the sub todo item. """ if config().append_parent_projects(): for project in p_from_todo.projects() - p_to_todo.projects(): self.append(p_to_todo, "+{}".format(project)) def append_contexts_to_subtodo(): """ Appends contexts in the parent todo item that are not present in the sub todo item. """ if config().append_parent_contexts(): for context in p_from_todo.contexts() - p_to_todo.contexts(): self.append(p_to_todo, "@{}".format(context)) if p_from_todo != p_to_todo and not self._depgraph.has_edge( hash(p_from_todo), hash(p_to_todo)): dep_id = None if p_from_todo.has_tag('id'): dep_id = p_from_todo.tag_value('id') else: dep_id = find_next_id() p_from_todo.set_tag('id', dep_id) p_to_todo.add_tag('p', dep_id) self._add_edge(p_from_todo, p_to_todo, dep_id) append_projects_to_subtodo() append_contexts_to_subtodo() self.dirty = True
[ "def", "add_dependency", "(", "self", ",", "p_from_todo", ",", "p_to_todo", ")", ":", "def", "find_next_id", "(", ")", ":", "\"\"\"\n Find a new unused ID.\n Unused means that no task has it as an 'id' value or as a 'p'\n value.\n \"\"\"", "def", "id_exists", "(", "p_id", ")", ":", "\"\"\"\n Returns True if there exists a todo with the given parent ID.\n \"\"\"", "for", "todo", "in", "self", ".", "_todos", ":", "number", "=", "str", "(", "p_id", ")", "if", "todo", ".", "has_tag", "(", "'id'", ",", "number", ")", "or", "todo", ".", "has_tag", "(", "'p'", ",", "number", ")", ":", "return", "True", "return", "False", "new_id", "=", "1", "while", "id_exists", "(", "new_id", ")", ":", "new_id", "+=", "1", "return", "str", "(", "new_id", ")", "def", "append_projects_to_subtodo", "(", ")", ":", "\"\"\"\n Appends projects in the parent todo item that are not present in\n the sub todo item.\n \"\"\"", "if", "config", "(", ")", ".", "append_parent_projects", "(", ")", ":", "for", "project", "in", "p_from_todo", ".", "projects", "(", ")", "-", "p_to_todo", ".", "projects", "(", ")", ":", "self", ".", "append", "(", "p_to_todo", ",", "\"+{}\"", ".", "format", "(", "project", ")", ")", "def", "append_contexts_to_subtodo", "(", ")", ":", "\"\"\"\n Appends contexts in the parent todo item that are not present in\n the sub todo item.\n \"\"\"", "if", "config", "(", ")", ".", "append_parent_contexts", "(", ")", ":", "for", "context", "in", "p_from_todo", ".", "contexts", "(", ")", "-", "p_to_todo", ".", "contexts", "(", ")", ":", "self", ".", "append", "(", "p_to_todo", ",", "\"@{}\"", ".", "format", "(", "context", ")", ")", "if", "p_from_todo", "!=", "p_to_todo", "and", "not", "self", ".", "_depgraph", ".", "has_edge", "(", "hash", "(", "p_from_todo", ")", ",", "hash", "(", "p_to_todo", ")", ")", ":", "dep_id", "=", "None", "if", "p_from_todo", ".", "has_tag", "(", "'id'", ")", ":", "dep_id", "=", "p_from_todo", ".", "tag_value", "(", "'id'", ")", "else", ":", "dep_id", "=", "find_next_id", "(", ")", "p_from_todo", ".", "set_tag", "(", "'id'", ",", "dep_id", ")", "p_to_todo", ".", "add_tag", "(", "'p'", ",", "dep_id", ")", "self", ".", "_add_edge", "(", "p_from_todo", ",", "p_to_todo", ",", "dep_id", ")", "append_projects_to_subtodo", "(", ")", "append_contexts_to_subtodo", "(", ")", "self", ".", "dirty", "=", "True" ]
Adds a dependency from task 1 to task 2.
[ "Adds", "a", "dependency", "from", "task", "1", "to", "task", "2", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoList.py#L153-L210
11,489
bram85/topydo
topydo/lib/TodoList.py
TodoList.remove_dependency
def remove_dependency(self, p_from_todo, p_to_todo, p_leave_tags=False): """ Removes a dependency between two todos. """ dep_id = p_from_todo.tag_value('id') if dep_id: self._depgraph.remove_edge(hash(p_from_todo), hash(p_to_todo)) self.dirty = True # clean dangling dependency tags if dep_id and not p_leave_tags: p_to_todo.remove_tag('p', dep_id) if not self.children(p_from_todo, True): p_from_todo.remove_tag('id') del self._parentdict[dep_id]
python
def remove_dependency(self, p_from_todo, p_to_todo, p_leave_tags=False): """ Removes a dependency between two todos. """ dep_id = p_from_todo.tag_value('id') if dep_id: self._depgraph.remove_edge(hash(p_from_todo), hash(p_to_todo)) self.dirty = True # clean dangling dependency tags if dep_id and not p_leave_tags: p_to_todo.remove_tag('p', dep_id) if not self.children(p_from_todo, True): p_from_todo.remove_tag('id') del self._parentdict[dep_id]
[ "def", "remove_dependency", "(", "self", ",", "p_from_todo", ",", "p_to_todo", ",", "p_leave_tags", "=", "False", ")", ":", "dep_id", "=", "p_from_todo", ".", "tag_value", "(", "'id'", ")", "if", "dep_id", ":", "self", ".", "_depgraph", ".", "remove_edge", "(", "hash", "(", "p_from_todo", ")", ",", "hash", "(", "p_to_todo", ")", ")", "self", ".", "dirty", "=", "True", "# clean dangling dependency tags", "if", "dep_id", "and", "not", "p_leave_tags", ":", "p_to_todo", ".", "remove_tag", "(", "'p'", ",", "dep_id", ")", "if", "not", "self", ".", "children", "(", "p_from_todo", ",", "True", ")", ":", "p_from_todo", ".", "remove_tag", "(", "'id'", ")", "del", "self", ".", "_parentdict", "[", "dep_id", "]" ]
Removes a dependency between two todos.
[ "Removes", "a", "dependency", "between", "two", "todos", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoList.py#L213-L227
11,490
bram85/topydo
topydo/lib/TodoList.py
TodoList.clean_dependencies
def clean_dependencies(self): """ Cleans the dependency graph. This is achieved by performing a transitive reduction on the dependency graph and removing unused dependency ids from the graph (in that order). """ def remove_tag(p_todo, p_tag, p_value): """ Removes a tag from a todo item. """ p_todo.remove_tag(p_tag, p_value) self.dirty = True def clean_parent_relations(): """ Remove id: tags for todos without child todo items. """ for todo in [todo for todo in self._todos if todo.has_tag('id')]: value = todo.tag_value('id') if not self._depgraph.has_edge_id(value): remove_tag(todo, 'id', value) del self._parentdict[value] def clean_orphan_relations(): """ Remove p: tags for todos referring to a parent that is not in the dependency graph anymore. """ for todo in [todo for todo in self._todos if todo.has_tag('p')]: for value in todo.tag_values('p'): parent = self.todo_by_dep_id(value) if not self._depgraph.has_edge(hash(parent), hash(todo)): remove_tag(todo, 'p', value) self._depgraph.transitively_reduce() clean_parent_relations() clean_orphan_relations()
python
def clean_dependencies(self): """ Cleans the dependency graph. This is achieved by performing a transitive reduction on the dependency graph and removing unused dependency ids from the graph (in that order). """ def remove_tag(p_todo, p_tag, p_value): """ Removes a tag from a todo item. """ p_todo.remove_tag(p_tag, p_value) self.dirty = True def clean_parent_relations(): """ Remove id: tags for todos without child todo items. """ for todo in [todo for todo in self._todos if todo.has_tag('id')]: value = todo.tag_value('id') if not self._depgraph.has_edge_id(value): remove_tag(todo, 'id', value) del self._parentdict[value] def clean_orphan_relations(): """ Remove p: tags for todos referring to a parent that is not in the dependency graph anymore. """ for todo in [todo for todo in self._todos if todo.has_tag('p')]: for value in todo.tag_values('p'): parent = self.todo_by_dep_id(value) if not self._depgraph.has_edge(hash(parent), hash(todo)): remove_tag(todo, 'p', value) self._depgraph.transitively_reduce() clean_parent_relations() clean_orphan_relations()
[ "def", "clean_dependencies", "(", "self", ")", ":", "def", "remove_tag", "(", "p_todo", ",", "p_tag", ",", "p_value", ")", ":", "\"\"\"\n Removes a tag from a todo item.\n \"\"\"", "p_todo", ".", "remove_tag", "(", "p_tag", ",", "p_value", ")", "self", ".", "dirty", "=", "True", "def", "clean_parent_relations", "(", ")", ":", "\"\"\"\n Remove id: tags for todos without child todo items.\n \"\"\"", "for", "todo", "in", "[", "todo", "for", "todo", "in", "self", ".", "_todos", "if", "todo", ".", "has_tag", "(", "'id'", ")", "]", ":", "value", "=", "todo", ".", "tag_value", "(", "'id'", ")", "if", "not", "self", ".", "_depgraph", ".", "has_edge_id", "(", "value", ")", ":", "remove_tag", "(", "todo", ",", "'id'", ",", "value", ")", "del", "self", ".", "_parentdict", "[", "value", "]", "def", "clean_orphan_relations", "(", ")", ":", "\"\"\"\n Remove p: tags for todos referring to a parent that is not in the\n dependency graph anymore.\n \"\"\"", "for", "todo", "in", "[", "todo", "for", "todo", "in", "self", ".", "_todos", "if", "todo", ".", "has_tag", "(", "'p'", ")", "]", ":", "for", "value", "in", "todo", ".", "tag_values", "(", "'p'", ")", ":", "parent", "=", "self", ".", "todo_by_dep_id", "(", "value", ")", "if", "not", "self", ".", "_depgraph", ".", "has_edge", "(", "hash", "(", "parent", ")", ",", "hash", "(", "todo", ")", ")", ":", "remove_tag", "(", "todo", ",", "'p'", ",", "value", ")", "self", ".", "_depgraph", ".", "transitively_reduce", "(", ")", "clean_parent_relations", "(", ")", "clean_orphan_relations", "(", ")" ]
Cleans the dependency graph. This is achieved by performing a transitive reduction on the dependency graph and removing unused dependency ids from the graph (in that order).
[ "Cleans", "the", "dependency", "graph", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoList.py#L250-L291
11,491
bram85/topydo
topydo/lib/printers/Json.py
_convert_todo
def _convert_todo(p_todo): """ Converts a Todo instance to a dictionary. """ creation_date = p_todo.creation_date() completion_date = p_todo.completion_date() result = { 'source': p_todo.source(), 'text': p_todo.text(), 'priority': p_todo.priority(), 'completed': p_todo.is_completed(), 'tags': p_todo.tags(), 'projects': list(p_todo.projects()), 'contexts': list(p_todo.contexts()), 'creation_date': creation_date.isoformat() if creation_date else None, 'completion_date': completion_date.isoformat() if completion_date else None } return result
python
def _convert_todo(p_todo): """ Converts a Todo instance to a dictionary. """ creation_date = p_todo.creation_date() completion_date = p_todo.completion_date() result = { 'source': p_todo.source(), 'text': p_todo.text(), 'priority': p_todo.priority(), 'completed': p_todo.is_completed(), 'tags': p_todo.tags(), 'projects': list(p_todo.projects()), 'contexts': list(p_todo.contexts()), 'creation_date': creation_date.isoformat() if creation_date else None, 'completion_date': completion_date.isoformat() if completion_date else None } return result
[ "def", "_convert_todo", "(", "p_todo", ")", ":", "creation_date", "=", "p_todo", ".", "creation_date", "(", ")", "completion_date", "=", "p_todo", ".", "completion_date", "(", ")", "result", "=", "{", "'source'", ":", "p_todo", ".", "source", "(", ")", ",", "'text'", ":", "p_todo", ".", "text", "(", ")", ",", "'priority'", ":", "p_todo", ".", "priority", "(", ")", ",", "'completed'", ":", "p_todo", ".", "is_completed", "(", ")", ",", "'tags'", ":", "p_todo", ".", "tags", "(", ")", ",", "'projects'", ":", "list", "(", "p_todo", ".", "projects", "(", ")", ")", ",", "'contexts'", ":", "list", "(", "p_todo", ".", "contexts", "(", ")", ")", ",", "'creation_date'", ":", "creation_date", ".", "isoformat", "(", ")", "if", "creation_date", "else", "None", ",", "'completion_date'", ":", "completion_date", ".", "isoformat", "(", ")", "if", "completion_date", "else", "None", "}", "return", "result" ]
Converts a Todo instance to a dictionary.
[ "Converts", "a", "Todo", "instance", "to", "a", "dictionary", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/printers/Json.py#L27-L46
11,492
bram85/topydo
topydo/lib/ChangeSet.py
get_backup_path
def get_backup_path(): """ Returns full path and filename of backup file """ dirname, filename = path.split(path.splitext(config().todotxt())[0]) filename = '.' + filename + '.bak' return path.join(dirname, filename)
python
def get_backup_path(): """ Returns full path and filename of backup file """ dirname, filename = path.split(path.splitext(config().todotxt())[0]) filename = '.' + filename + '.bak' return path.join(dirname, filename)
[ "def", "get_backup_path", "(", ")", ":", "dirname", ",", "filename", "=", "path", ".", "split", "(", "path", ".", "splitext", "(", "config", "(", ")", ".", "todotxt", "(", ")", ")", "[", "0", "]", ")", "filename", "=", "'.'", "+", "filename", "+", "'.bak'", "return", "path", ".", "join", "(", "dirname", ",", "filename", ")" ]
Returns full path and filename of backup file
[ "Returns", "full", "path", "and", "filename", "of", "backup", "file" ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L36-L41
11,493
bram85/topydo
topydo/lib/ChangeSet.py
ChangeSet._read
def _read(self): """ Reads backup file from json_file property and sets backup_dict property with data decompressed and deserialized from that file. If no usable data is found backup_dict is set to the empty dict. """ self.json_file.seek(0) try: data = zlib.decompress(self.json_file.read()) self.backup_dict = json.loads(data.decode('utf-8')) except (EOFError, zlib.error): self.backup_dict = {}
python
def _read(self): """ Reads backup file from json_file property and sets backup_dict property with data decompressed and deserialized from that file. If no usable data is found backup_dict is set to the empty dict. """ self.json_file.seek(0) try: data = zlib.decompress(self.json_file.read()) self.backup_dict = json.loads(data.decode('utf-8')) except (EOFError, zlib.error): self.backup_dict = {}
[ "def", "_read", "(", "self", ")", ":", "self", ".", "json_file", ".", "seek", "(", "0", ")", "try", ":", "data", "=", "zlib", ".", "decompress", "(", "self", ".", "json_file", ".", "read", "(", ")", ")", "self", ".", "backup_dict", "=", "json", ".", "loads", "(", "data", ".", "decode", "(", "'utf-8'", ")", ")", "except", "(", "EOFError", ",", "zlib", ".", "error", ")", ":", "self", ".", "backup_dict", "=", "{", "}" ]
Reads backup file from json_file property and sets backup_dict property with data decompressed and deserialized from that file. If no usable data is found backup_dict is set to the empty dict.
[ "Reads", "backup", "file", "from", "json_file", "property", "and", "sets", "backup_dict", "property", "with", "data", "decompressed", "and", "deserialized", "from", "that", "file", ".", "If", "no", "usable", "data", "is", "found", "backup_dict", "is", "set", "to", "the", "empty", "dict", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L64-L75
11,494
bram85/topydo
topydo/lib/ChangeSet.py
ChangeSet._write
def _write(self): """ Writes data from backup_dict property in serialized and compressed form to backup file pointed in json_file property. """ self.json_file.seek(0) self.json_file.truncate() dump = json.dumps(self.backup_dict) dump_c = zlib.compress(dump.encode('utf-8')) self.json_file.write(dump_c)
python
def _write(self): """ Writes data from backup_dict property in serialized and compressed form to backup file pointed in json_file property. """ self.json_file.seek(0) self.json_file.truncate() dump = json.dumps(self.backup_dict) dump_c = zlib.compress(dump.encode('utf-8')) self.json_file.write(dump_c)
[ "def", "_write", "(", "self", ")", ":", "self", ".", "json_file", ".", "seek", "(", "0", ")", "self", ".", "json_file", ".", "truncate", "(", ")", "dump", "=", "json", ".", "dumps", "(", "self", ".", "backup_dict", ")", "dump_c", "=", "zlib", ".", "compress", "(", "dump", ".", "encode", "(", "'utf-8'", ")", ")", "self", ".", "json_file", ".", "write", "(", "dump_c", ")" ]
Writes data from backup_dict property in serialized and compressed form to backup file pointed in json_file property.
[ "Writes", "data", "from", "backup_dict", "property", "in", "serialized", "and", "compressed", "form", "to", "backup", "file", "pointed", "in", "json_file", "property", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L77-L86
11,495
bram85/topydo
topydo/lib/ChangeSet.py
ChangeSet.save
def save(self, p_todolist): """ Saves a tuple with archive, todolist and command with its arguments into the backup file with unix timestamp as the key. Tuple is then indexed in backup file with combination of hash calculated from p_todolist and unix timestamp. Backup file is closed afterwards. """ self._trim() current_hash = hash_todolist(p_todolist) list_todo = (self.todolist.print_todos()+'\n').splitlines(True) try: list_archive = (self.archive.print_todos()+'\n').splitlines(True) except AttributeError: list_archive = [] self.backup_dict[self.timestamp] = (list_todo, list_archive, self.label) index = self._get_index() index.insert(0, (self.timestamp, current_hash)) self._save_index(index) self._write() self.close()
python
def save(self, p_todolist): """ Saves a tuple with archive, todolist and command with its arguments into the backup file with unix timestamp as the key. Tuple is then indexed in backup file with combination of hash calculated from p_todolist and unix timestamp. Backup file is closed afterwards. """ self._trim() current_hash = hash_todolist(p_todolist) list_todo = (self.todolist.print_todos()+'\n').splitlines(True) try: list_archive = (self.archive.print_todos()+'\n').splitlines(True) except AttributeError: list_archive = [] self.backup_dict[self.timestamp] = (list_todo, list_archive, self.label) index = self._get_index() index.insert(0, (self.timestamp, current_hash)) self._save_index(index) self._write() self.close()
[ "def", "save", "(", "self", ",", "p_todolist", ")", ":", "self", ".", "_trim", "(", ")", "current_hash", "=", "hash_todolist", "(", "p_todolist", ")", "list_todo", "=", "(", "self", ".", "todolist", ".", "print_todos", "(", ")", "+", "'\\n'", ")", ".", "splitlines", "(", "True", ")", "try", ":", "list_archive", "=", "(", "self", ".", "archive", ".", "print_todos", "(", ")", "+", "'\\n'", ")", ".", "splitlines", "(", "True", ")", "except", "AttributeError", ":", "list_archive", "=", "[", "]", "self", ".", "backup_dict", "[", "self", ".", "timestamp", "]", "=", "(", "list_todo", ",", "list_archive", ",", "self", ".", "label", ")", "index", "=", "self", ".", "_get_index", "(", ")", "index", ".", "insert", "(", "0", ",", "(", "self", ".", "timestamp", ",", "current_hash", ")", ")", "self", ".", "_save_index", "(", "index", ")", "self", ".", "_write", "(", ")", "self", ".", "close", "(", ")" ]
Saves a tuple with archive, todolist and command with its arguments into the backup file with unix timestamp as the key. Tuple is then indexed in backup file with combination of hash calculated from p_todolist and unix timestamp. Backup file is closed afterwards.
[ "Saves", "a", "tuple", "with", "archive", "todolist", "and", "command", "with", "its", "arguments", "into", "the", "backup", "file", "with", "unix", "timestamp", "as", "the", "key", ".", "Tuple", "is", "then", "indexed", "in", "backup", "file", "with", "combination", "of", "hash", "calculated", "from", "p_todolist", "and", "unix", "timestamp", ".", "Backup", "file", "is", "closed", "afterwards", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L96-L119
11,496
bram85/topydo
topydo/lib/ChangeSet.py
ChangeSet.delete
def delete(self, p_timestamp=None, p_write=True): """ Removes backup from the backup file. """ timestamp = p_timestamp or self.timestamp index = self._get_index() try: del self.backup_dict[timestamp] index.remove(index[[change[0] for change in index].index(timestamp)]) self._save_index(index) if p_write: self._write() except KeyError: pass
python
def delete(self, p_timestamp=None, p_write=True): """ Removes backup from the backup file. """ timestamp = p_timestamp or self.timestamp index = self._get_index() try: del self.backup_dict[timestamp] index.remove(index[[change[0] for change in index].index(timestamp)]) self._save_index(index) if p_write: self._write() except KeyError: pass
[ "def", "delete", "(", "self", ",", "p_timestamp", "=", "None", ",", "p_write", "=", "True", ")", ":", "timestamp", "=", "p_timestamp", "or", "self", ".", "timestamp", "index", "=", "self", ".", "_get_index", "(", ")", "try", ":", "del", "self", ".", "backup_dict", "[", "timestamp", "]", "index", ".", "remove", "(", "index", "[", "[", "change", "[", "0", "]", "for", "change", "in", "index", "]", ".", "index", "(", "timestamp", ")", "]", ")", "self", ".", "_save_index", "(", "index", ")", "if", "p_write", ":", "self", ".", "_write", "(", ")", "except", "KeyError", ":", "pass" ]
Removes backup from the backup file.
[ "Removes", "backup", "from", "the", "backup", "file", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L121-L134
11,497
bram85/topydo
topydo/lib/ChangeSet.py
ChangeSet._trim
def _trim(self): """ Removes oldest backups that exceed the limit configured in backup_count option. Does not write back to file system, make sure to call self._write() afterwards. """ index = self._get_index() backup_limit = config().backup_count() - 1 for changeset in index[backup_limit:]: self.delete(changeset[0], p_write=False)
python
def _trim(self): """ Removes oldest backups that exceed the limit configured in backup_count option. Does not write back to file system, make sure to call self._write() afterwards. """ index = self._get_index() backup_limit = config().backup_count() - 1 for changeset in index[backup_limit:]: self.delete(changeset[0], p_write=False)
[ "def", "_trim", "(", "self", ")", ":", "index", "=", "self", ".", "_get_index", "(", ")", "backup_limit", "=", "config", "(", ")", ".", "backup_count", "(", ")", "-", "1", "for", "changeset", "in", "index", "[", "backup_limit", ":", "]", ":", "self", ".", "delete", "(", "changeset", "[", "0", "]", ",", "p_write", "=", "False", ")" ]
Removes oldest backups that exceed the limit configured in backup_count option. Does not write back to file system, make sure to call self._write() afterwards.
[ "Removes", "oldest", "backups", "that", "exceed", "the", "limit", "configured", "in", "backup_count", "option", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L152-L164
11,498
bram85/topydo
topydo/lib/ChangeSet.py
ChangeSet.apply
def apply(self, p_todolist, p_archive): """ Applies backup on supplied p_todolist. """ if self.todolist and p_todolist: p_todolist.replace(self.todolist.todos()) if self.archive and p_archive: p_archive.replace(self.archive.todos())
python
def apply(self, p_todolist, p_archive): """ Applies backup on supplied p_todolist. """ if self.todolist and p_todolist: p_todolist.replace(self.todolist.todos()) if self.archive and p_archive: p_archive.replace(self.archive.todos())
[ "def", "apply", "(", "self", ",", "p_todolist", ",", "p_archive", ")", ":", "if", "self", ".", "todolist", "and", "p_todolist", ":", "p_todolist", ".", "replace", "(", "self", ".", "todolist", ".", "todos", "(", ")", ")", "if", "self", ".", "archive", "and", "p_archive", ":", "p_archive", ".", "replace", "(", "self", ".", "archive", ".", "todos", "(", ")", ")" ]
Applies backup on supplied p_todolist.
[ "Applies", "backup", "on", "supplied", "p_todolist", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L185-L191
11,499
bram85/topydo
topydo/lib/printers/PrettyPrinter.py
pretty_printer_factory
def pretty_printer_factory(p_todolist, p_additional_filters=None): """ Returns a pretty printer suitable for the ls and dep subcommands. """ p_additional_filters = p_additional_filters or [] printer = PrettyPrinter() printer.add_filter(PrettyPrinterNumbers(p_todolist)) for ppf in p_additional_filters: printer.add_filter(ppf) # apply colors at the last step, the ANSI codes may confuse the # preceding filters. printer.add_filter(PrettyPrinterColorFilter()) return printer
python
def pretty_printer_factory(p_todolist, p_additional_filters=None): """ Returns a pretty printer suitable for the ls and dep subcommands. """ p_additional_filters = p_additional_filters or [] printer = PrettyPrinter() printer.add_filter(PrettyPrinterNumbers(p_todolist)) for ppf in p_additional_filters: printer.add_filter(ppf) # apply colors at the last step, the ANSI codes may confuse the # preceding filters. printer.add_filter(PrettyPrinterColorFilter()) return printer
[ "def", "pretty_printer_factory", "(", "p_todolist", ",", "p_additional_filters", "=", "None", ")", ":", "p_additional_filters", "=", "p_additional_filters", "or", "[", "]", "printer", "=", "PrettyPrinter", "(", ")", "printer", ".", "add_filter", "(", "PrettyPrinterNumbers", "(", "p_todolist", ")", ")", "for", "ppf", "in", "p_additional_filters", ":", "printer", ".", "add_filter", "(", "ppf", ")", "# apply colors at the last step, the ANSI codes may confuse the", "# preceding filters.", "printer", ".", "add_filter", "(", "PrettyPrinterColorFilter", "(", ")", ")", "return", "printer" ]
Returns a pretty printer suitable for the ls and dep subcommands.
[ "Returns", "a", "pretty", "printer", "suitable", "for", "the", "ls", "and", "dep", "subcommands", "." ]
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/printers/PrettyPrinter.py#L113-L127