repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
devassistant/devassistant
devassistant/dapi/__init__.py
DapChecker.check_meta
def check_meta(cls, dap): '''Check the meta.yaml in the dap. Return a list of DapProblems.''' problems = list() # Check for non array-like metadata for datatype in (Dap._required_meta | Dap._optional_meta) - Dap._array_meta: if not dap._isvalid(datatype): msg = datatype + ' is not valid (or required and unspecified)' problems.append(DapProblem(msg)) # Check for the array-like metadata for datatype in Dap._array_meta: ok, bads = dap._arevalid(datatype) if not ok: if not bads: msg = datatype + ' is not a valid non-empty list' problems.append(DapProblem(msg)) else: for bad in bads: msg = bad + ' in ' + datatype + ' is not valid or is a duplicate' problems.append(DapProblem(msg)) # Check that there is no unknown metadata leftovers = set(dap.meta.keys()) - (Dap._required_meta | Dap._optional_meta) if leftovers: msg = 'Unknown metadata: ' + str(leftovers) problems.append(DapProblem(msg)) # Check that package_name is not longer than 200 characters if len(dap.meta.get('package_name', '')) > 200: msg = 'Package name is too long. It must not exceed 200 characters.' problems.append(DapProblem(msg)) return problems
python
def check_meta(cls, dap): '''Check the meta.yaml in the dap. Return a list of DapProblems.''' problems = list() # Check for non array-like metadata for datatype in (Dap._required_meta | Dap._optional_meta) - Dap._array_meta: if not dap._isvalid(datatype): msg = datatype + ' is not valid (or required and unspecified)' problems.append(DapProblem(msg)) # Check for the array-like metadata for datatype in Dap._array_meta: ok, bads = dap._arevalid(datatype) if not ok: if not bads: msg = datatype + ' is not a valid non-empty list' problems.append(DapProblem(msg)) else: for bad in bads: msg = bad + ' in ' + datatype + ' is not valid or is a duplicate' problems.append(DapProblem(msg)) # Check that there is no unknown metadata leftovers = set(dap.meta.keys()) - (Dap._required_meta | Dap._optional_meta) if leftovers: msg = 'Unknown metadata: ' + str(leftovers) problems.append(DapProblem(msg)) # Check that package_name is not longer than 200 characters if len(dap.meta.get('package_name', '')) > 200: msg = 'Package name is too long. It must not exceed 200 characters.' problems.append(DapProblem(msg)) return problems
[ "def", "check_meta", "(", "cls", ",", "dap", ")", ":", "problems", "=", "list", "(", ")", "# Check for non array-like metadata", "for", "datatype", "in", "(", "Dap", ".", "_required_meta", "|", "Dap", ".", "_optional_meta", ")", "-", "Dap", ".", "_array_meta", ":", "if", "not", "dap", ".", "_isvalid", "(", "datatype", ")", ":", "msg", "=", "datatype", "+", "' is not valid (or required and unspecified)'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "# Check for the array-like metadata", "for", "datatype", "in", "Dap", ".", "_array_meta", ":", "ok", ",", "bads", "=", "dap", ".", "_arevalid", "(", "datatype", ")", "if", "not", "ok", ":", "if", "not", "bads", ":", "msg", "=", "datatype", "+", "' is not a valid non-empty list'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "else", ":", "for", "bad", "in", "bads", ":", "msg", "=", "bad", "+", "' in '", "+", "datatype", "+", "' is not valid or is a duplicate'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "# Check that there is no unknown metadata", "leftovers", "=", "set", "(", "dap", ".", "meta", ".", "keys", "(", ")", ")", "-", "(", "Dap", ".", "_required_meta", "|", "Dap", ".", "_optional_meta", ")", "if", "leftovers", ":", "msg", "=", "'Unknown metadata: '", "+", "str", "(", "leftovers", ")", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "# Check that package_name is not longer than 200 characters", "if", "len", "(", "dap", ".", "meta", ".", "get", "(", "'package_name'", ",", "''", ")", ")", ">", "200", ":", "msg", "=", "'Package name is too long. It must not exceed 200 characters.'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "return", "problems" ]
Check the meta.yaml in the dap. Return a list of DapProblems.
[ "Check", "the", "meta", ".", "yaml", "in", "the", "dap", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L190-L225
devassistant/devassistant
devassistant/dapi/__init__.py
DapChecker.check_topdir
def check_topdir(cls, dap): '''Check that everything is in the correct top-level directory. Return a list of DapProblems''' problems = list() dirname = os.path.dirname(dap._meta_location) if not dirname: msg = 'meta.yaml is not in top-level directory' problems.append(DapProblem(msg)) else: for path in dap.files: if not path.startswith(dirname): msg = path + ' is outside of ' + dirname + ' top-level directory' problems.append(DapProblem(msg)) if dap.meta['package_name'] and dap.meta['version']: desired_dirname = dap._dirname() desired_filename = desired_dirname + '.dap' if dirname and dirname != desired_dirname: msg = 'Top-level directory with meta.yaml is not named ' + desired_dirname problems.append(DapProblem(msg)) if dap.basename != desired_filename: msg = 'The dap filename is not ' + desired_filename problems.append(DapProblem(msg)) return problems
python
def check_topdir(cls, dap): '''Check that everything is in the correct top-level directory. Return a list of DapProblems''' problems = list() dirname = os.path.dirname(dap._meta_location) if not dirname: msg = 'meta.yaml is not in top-level directory' problems.append(DapProblem(msg)) else: for path in dap.files: if not path.startswith(dirname): msg = path + ' is outside of ' + dirname + ' top-level directory' problems.append(DapProblem(msg)) if dap.meta['package_name'] and dap.meta['version']: desired_dirname = dap._dirname() desired_filename = desired_dirname + '.dap' if dirname and dirname != desired_dirname: msg = 'Top-level directory with meta.yaml is not named ' + desired_dirname problems.append(DapProblem(msg)) if dap.basename != desired_filename: msg = 'The dap filename is not ' + desired_filename problems.append(DapProblem(msg)) return problems
[ "def", "check_topdir", "(", "cls", ",", "dap", ")", ":", "problems", "=", "list", "(", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "dap", ".", "_meta_location", ")", "if", "not", "dirname", ":", "msg", "=", "'meta.yaml is not in top-level directory'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "else", ":", "for", "path", "in", "dap", ".", "files", ":", "if", "not", "path", ".", "startswith", "(", "dirname", ")", ":", "msg", "=", "path", "+", "' is outside of '", "+", "dirname", "+", "' top-level directory'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "if", "dap", ".", "meta", "[", "'package_name'", "]", "and", "dap", ".", "meta", "[", "'version'", "]", ":", "desired_dirname", "=", "dap", ".", "_dirname", "(", ")", "desired_filename", "=", "desired_dirname", "+", "'.dap'", "if", "dirname", "and", "dirname", "!=", "desired_dirname", ":", "msg", "=", "'Top-level directory with meta.yaml is not named '", "+", "desired_dirname", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "if", "dap", ".", "basename", "!=", "desired_filename", ":", "msg", "=", "'The dap filename is not '", "+", "desired_filename", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "return", "problems" ]
Check that everything is in the correct top-level directory. Return a list of DapProblems
[ "Check", "that", "everything", "is", "in", "the", "correct", "top", "-", "level", "directory", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L228-L257
devassistant/devassistant
devassistant/dapi/__init__.py
DapChecker.check_no_self_dependency
def check_no_self_dependency(cls, dap): '''Check that the package does not depend on itself. Return a list of problems.''' problems = list() if 'package_name' in dap.meta and 'dependencies' in dap.meta: dependencies = set() for dependency in dap.meta['dependencies']: if 'dependencies' in dap._badmeta and dependency in dap._badmeta['dependencies']: continue # No version specified if not re.search(r'[<=>]', dependency): dependencies.add(dependency) # Version specified for mark in ['==', '>=', '<=', '<', '>']: dep = dependency.split(mark) if len(dep) == 2: dependencies.add(dep[0].strip()) break if dap.meta['package_name'] in dependencies: msg = 'Depends on dap with the same name as itself' problems.append(DapProblem(msg)) return problems
python
def check_no_self_dependency(cls, dap): '''Check that the package does not depend on itself. Return a list of problems.''' problems = list() if 'package_name' in dap.meta and 'dependencies' in dap.meta: dependencies = set() for dependency in dap.meta['dependencies']: if 'dependencies' in dap._badmeta and dependency in dap._badmeta['dependencies']: continue # No version specified if not re.search(r'[<=>]', dependency): dependencies.add(dependency) # Version specified for mark in ['==', '>=', '<=', '<', '>']: dep = dependency.split(mark) if len(dep) == 2: dependencies.add(dep[0].strip()) break if dap.meta['package_name'] in dependencies: msg = 'Depends on dap with the same name as itself' problems.append(DapProblem(msg)) return problems
[ "def", "check_no_self_dependency", "(", "cls", ",", "dap", ")", ":", "problems", "=", "list", "(", ")", "if", "'package_name'", "in", "dap", ".", "meta", "and", "'dependencies'", "in", "dap", ".", "meta", ":", "dependencies", "=", "set", "(", ")", "for", "dependency", "in", "dap", ".", "meta", "[", "'dependencies'", "]", ":", "if", "'dependencies'", "in", "dap", ".", "_badmeta", "and", "dependency", "in", "dap", ".", "_badmeta", "[", "'dependencies'", "]", ":", "continue", "# No version specified", "if", "not", "re", ".", "search", "(", "r'[<=>]'", ",", "dependency", ")", ":", "dependencies", ".", "add", "(", "dependency", ")", "# Version specified", "for", "mark", "in", "[", "'=='", ",", "'>='", ",", "'<='", ",", "'<'", ",", "'>'", "]", ":", "dep", "=", "dependency", ".", "split", "(", "mark", ")", "if", "len", "(", "dep", ")", "==", "2", ":", "dependencies", ".", "add", "(", "dep", "[", "0", "]", ".", "strip", "(", ")", ")", "break", "if", "dap", ".", "meta", "[", "'package_name'", "]", "in", "dependencies", ":", "msg", "=", "'Depends on dap with the same name as itself'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "return", "problems" ]
Check that the package does not depend on itself. Return a list of problems.
[ "Check", "that", "the", "package", "does", "not", "depend", "on", "itself", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L260-L288
devassistant/devassistant
devassistant/dapi/__init__.py
DapChecker.check_name_not_on_dapi
def check_name_not_on_dapi(cls, dap): '''Check that the package_name is not registered on Dapi. Return list of problems.''' problems = list() if dap.meta['package_name']: from . import dapicli d = dapicli.metadap(dap.meta['package_name']) if d: problems.append(DapProblem('This dap name is already registered on Dapi', level=logging.WARNING)) return problems
python
def check_name_not_on_dapi(cls, dap): '''Check that the package_name is not registered on Dapi. Return list of problems.''' problems = list() if dap.meta['package_name']: from . import dapicli d = dapicli.metadap(dap.meta['package_name']) if d: problems.append(DapProblem('This dap name is already registered on Dapi', level=logging.WARNING)) return problems
[ "def", "check_name_not_on_dapi", "(", "cls", ",", "dap", ")", ":", "problems", "=", "list", "(", ")", "if", "dap", ".", "meta", "[", "'package_name'", "]", ":", "from", ".", "import", "dapicli", "d", "=", "dapicli", ".", "metadap", "(", "dap", ".", "meta", "[", "'package_name'", "]", ")", "if", "d", ":", "problems", ".", "append", "(", "DapProblem", "(", "'This dap name is already registered on Dapi'", ",", "level", "=", "logging", ".", "WARNING", ")", ")", "return", "problems" ]
Check that the package_name is not registered on Dapi. Return list of problems.
[ "Check", "that", "the", "package_name", "is", "not", "registered", "on", "Dapi", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L291-L303
devassistant/devassistant
devassistant/dapi/__init__.py
DapChecker.check_files
def check_files(cls, dap): '''Check that there are only those files the standard accepts. Return list of DapProblems.''' problems = list() dirname = os.path.dirname(dap._meta_location) if dirname: dirname += '/' files = [f for f in dap.files if f.startswith(dirname)] if len(files) == 1: msg = 'Only meta.yaml in dap' problems.append(DapProblem(msg, level=logging.WARNING)) return problems files.remove(dirname + 'meta.yaml') # Report and remove empty directories until no more are found emptydirs = dap._get_emptydirs(files) while emptydirs: for ed in emptydirs: msg = ed + ' is empty directory (may be nested)' problems.append(DapProblem(msg, logging.WARNING)) files.remove(ed) emptydirs = dap._get_emptydirs(files) if dap.meta['package_name']: name = dap.meta['package_name'] dirs = re.compile('^' + dirname + '((assistants(/(crt|twk|prep|extra))?|snippets)(/' + name + ')?|icons(/(crt|twk|prep|extra|snippets)(/' + name + ')?)?|files|(files/(crt|twk|prep|extra|snippets)|doc)(/' + name + '(/.+)?)?)$') regs = re.compile('^' + dirname + '((assistants(/(crt|twk|prep|extra))|snippets)/' + name + r'(/[^/]+)?\.yaml|icons/(crt|twk|prep|extra|snippets)/' + name + r'(/[^/]+)?\.(' + Dap._icons_ext + ')|(files/(crt|twk|prep|extra|snippets)|doc)/' + name + '/.+)$') to_remove = [] for f in files: if dap._is_dir(f) and not dirs.match(f): msg = f + '/ is not allowed directory' problems.append(DapProblem(msg)) to_remove.append(f) elif not dap._is_dir(f) and not regs.match(f): msg = f + ' is not allowed file' problems.append(DapProblem(msg)) to_remove.append(f) for r in to_remove: files.remove(r) # Subdir yamls need a chief for directory in ['assistants/' + t for t in 'crt twk prep extra'.split()] + \ ['snippets']: prefix = dirname + directory + '/' for f in files: if f.startswith(prefix) and dap._is_dir(f) and f + '.yaml' not in files: msg = f + '/ present, but ' + f + '.yaml missing' problems.append(DapProblem(msg)) # Missing assistants and/or snippets if not dap.assistants_and_snippets: msg = 'No Assistants or Snippets found' problems.append(DapProblem(msg, level=logging.WARNING)) # Icons icons = [dap._strip_leading_dirname(i) for i in dap.icons(strip_ext=True)] # we need to report duplicates assistants = set([dap._strip_leading_dirname(a) for a in dap.assistants]) # duplicates are fine here duplicates = set([i for i in icons if icons.count(i) > 1]) for d in duplicates: msg = 'Duplicate icon for ' + f problems.append(DapProblem(msg, level=logging.WARNING)) icons = set(icons) for i in icons - assistants: msg = 'Useless icon for non-exisiting assistant ' + i problems.append(DapProblem(msg, level=logging.WARNING)) for a in assistants - icons: msg = 'Missing icon for assistant ' + a problems.append(DapProblem(msg, level=logging.WARNING)) # Source files for f in cls._get_files_without_assistants(dap, dirname, files): msg = 'Useless files for non-exisiting assistant ' + f problems.append(DapProblem(msg, level=logging.WARNING)) return problems
python
def check_files(cls, dap): '''Check that there are only those files the standard accepts. Return list of DapProblems.''' problems = list() dirname = os.path.dirname(dap._meta_location) if dirname: dirname += '/' files = [f for f in dap.files if f.startswith(dirname)] if len(files) == 1: msg = 'Only meta.yaml in dap' problems.append(DapProblem(msg, level=logging.WARNING)) return problems files.remove(dirname + 'meta.yaml') # Report and remove empty directories until no more are found emptydirs = dap._get_emptydirs(files) while emptydirs: for ed in emptydirs: msg = ed + ' is empty directory (may be nested)' problems.append(DapProblem(msg, logging.WARNING)) files.remove(ed) emptydirs = dap._get_emptydirs(files) if dap.meta['package_name']: name = dap.meta['package_name'] dirs = re.compile('^' + dirname + '((assistants(/(crt|twk|prep|extra))?|snippets)(/' + name + ')?|icons(/(crt|twk|prep|extra|snippets)(/' + name + ')?)?|files|(files/(crt|twk|prep|extra|snippets)|doc)(/' + name + '(/.+)?)?)$') regs = re.compile('^' + dirname + '((assistants(/(crt|twk|prep|extra))|snippets)/' + name + r'(/[^/]+)?\.yaml|icons/(crt|twk|prep|extra|snippets)/' + name + r'(/[^/]+)?\.(' + Dap._icons_ext + ')|(files/(crt|twk|prep|extra|snippets)|doc)/' + name + '/.+)$') to_remove = [] for f in files: if dap._is_dir(f) and not dirs.match(f): msg = f + '/ is not allowed directory' problems.append(DapProblem(msg)) to_remove.append(f) elif not dap._is_dir(f) and not regs.match(f): msg = f + ' is not allowed file' problems.append(DapProblem(msg)) to_remove.append(f) for r in to_remove: files.remove(r) # Subdir yamls need a chief for directory in ['assistants/' + t for t in 'crt twk prep extra'.split()] + \ ['snippets']: prefix = dirname + directory + '/' for f in files: if f.startswith(prefix) and dap._is_dir(f) and f + '.yaml' not in files: msg = f + '/ present, but ' + f + '.yaml missing' problems.append(DapProblem(msg)) # Missing assistants and/or snippets if not dap.assistants_and_snippets: msg = 'No Assistants or Snippets found' problems.append(DapProblem(msg, level=logging.WARNING)) # Icons icons = [dap._strip_leading_dirname(i) for i in dap.icons(strip_ext=True)] # we need to report duplicates assistants = set([dap._strip_leading_dirname(a) for a in dap.assistants]) # duplicates are fine here duplicates = set([i for i in icons if icons.count(i) > 1]) for d in duplicates: msg = 'Duplicate icon for ' + f problems.append(DapProblem(msg, level=logging.WARNING)) icons = set(icons) for i in icons - assistants: msg = 'Useless icon for non-exisiting assistant ' + i problems.append(DapProblem(msg, level=logging.WARNING)) for a in assistants - icons: msg = 'Missing icon for assistant ' + a problems.append(DapProblem(msg, level=logging.WARNING)) # Source files for f in cls._get_files_without_assistants(dap, dirname, files): msg = 'Useless files for non-exisiting assistant ' + f problems.append(DapProblem(msg, level=logging.WARNING)) return problems
[ "def", "check_files", "(", "cls", ",", "dap", ")", ":", "problems", "=", "list", "(", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "dap", ".", "_meta_location", ")", "if", "dirname", ":", "dirname", "+=", "'/'", "files", "=", "[", "f", "for", "f", "in", "dap", ".", "files", "if", "f", ".", "startswith", "(", "dirname", ")", "]", "if", "len", "(", "files", ")", "==", "1", ":", "msg", "=", "'Only meta.yaml in dap'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ",", "level", "=", "logging", ".", "WARNING", ")", ")", "return", "problems", "files", ".", "remove", "(", "dirname", "+", "'meta.yaml'", ")", "# Report and remove empty directories until no more are found", "emptydirs", "=", "dap", ".", "_get_emptydirs", "(", "files", ")", "while", "emptydirs", ":", "for", "ed", "in", "emptydirs", ":", "msg", "=", "ed", "+", "' is empty directory (may be nested)'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ",", "logging", ".", "WARNING", ")", ")", "files", ".", "remove", "(", "ed", ")", "emptydirs", "=", "dap", ".", "_get_emptydirs", "(", "files", ")", "if", "dap", ".", "meta", "[", "'package_name'", "]", ":", "name", "=", "dap", ".", "meta", "[", "'package_name'", "]", "dirs", "=", "re", ".", "compile", "(", "'^'", "+", "dirname", "+", "'((assistants(/(crt|twk|prep|extra))?|snippets)(/'", "+", "name", "+", "')?|icons(/(crt|twk|prep|extra|snippets)(/'", "+", "name", "+", "')?)?|files|(files/(crt|twk|prep|extra|snippets)|doc)(/'", "+", "name", "+", "'(/.+)?)?)$'", ")", "regs", "=", "re", ".", "compile", "(", "'^'", "+", "dirname", "+", "'((assistants(/(crt|twk|prep|extra))|snippets)/'", "+", "name", "+", "r'(/[^/]+)?\\.yaml|icons/(crt|twk|prep|extra|snippets)/'", "+", "name", "+", "r'(/[^/]+)?\\.('", "+", "Dap", ".", "_icons_ext", "+", "')|(files/(crt|twk|prep|extra|snippets)|doc)/'", "+", "name", "+", "'/.+)$'", ")", "to_remove", "=", "[", "]", "for", "f", "in", "files", ":", "if", "dap", ".", "_is_dir", "(", "f", ")", "and", "not", "dirs", ".", "match", "(", "f", ")", ":", "msg", "=", "f", "+", "'/ is not allowed directory'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "to_remove", ".", "append", "(", "f", ")", "elif", "not", "dap", ".", "_is_dir", "(", "f", ")", "and", "not", "regs", ".", "match", "(", "f", ")", ":", "msg", "=", "f", "+", "' is not allowed file'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "to_remove", ".", "append", "(", "f", ")", "for", "r", "in", "to_remove", ":", "files", ".", "remove", "(", "r", ")", "# Subdir yamls need a chief", "for", "directory", "in", "[", "'assistants/'", "+", "t", "for", "t", "in", "'crt twk prep extra'", ".", "split", "(", ")", "]", "+", "[", "'snippets'", "]", ":", "prefix", "=", "dirname", "+", "directory", "+", "'/'", "for", "f", "in", "files", ":", "if", "f", ".", "startswith", "(", "prefix", ")", "and", "dap", ".", "_is_dir", "(", "f", ")", "and", "f", "+", "'.yaml'", "not", "in", "files", ":", "msg", "=", "f", "+", "'/ present, but '", "+", "f", "+", "'.yaml missing'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ")", ")", "# Missing assistants and/or snippets", "if", "not", "dap", ".", "assistants_and_snippets", ":", "msg", "=", "'No Assistants or Snippets found'", "problems", ".", "append", "(", "DapProblem", "(", "msg", ",", "level", "=", "logging", ".", "WARNING", ")", ")", "# Icons", "icons", "=", "[", "dap", ".", "_strip_leading_dirname", "(", "i", ")", "for", "i", "in", "dap", ".", "icons", "(", "strip_ext", "=", "True", ")", "]", "# we need to report duplicates", "assistants", "=", "set", "(", "[", "dap", ".", "_strip_leading_dirname", "(", "a", ")", "for", "a", "in", "dap", ".", "assistants", "]", ")", "# duplicates are fine here", "duplicates", "=", "set", "(", "[", "i", "for", "i", "in", "icons", "if", "icons", ".", "count", "(", "i", ")", ">", "1", "]", ")", "for", "d", "in", "duplicates", ":", "msg", "=", "'Duplicate icon for '", "+", "f", "problems", ".", "append", "(", "DapProblem", "(", "msg", ",", "level", "=", "logging", ".", "WARNING", ")", ")", "icons", "=", "set", "(", "icons", ")", "for", "i", "in", "icons", "-", "assistants", ":", "msg", "=", "'Useless icon for non-exisiting assistant '", "+", "i", "problems", ".", "append", "(", "DapProblem", "(", "msg", ",", "level", "=", "logging", ".", "WARNING", ")", ")", "for", "a", "in", "assistants", "-", "icons", ":", "msg", "=", "'Missing icon for assistant '", "+", "a", "problems", ".", "append", "(", "DapProblem", "(", "msg", ",", "level", "=", "logging", ".", "WARNING", ")", ")", "# Source files", "for", "f", "in", "cls", ".", "_get_files_without_assistants", "(", "dap", ",", "dirname", ",", "files", ")", ":", "msg", "=", "'Useless files for non-exisiting assistant '", "+", "f", "problems", ".", "append", "(", "DapProblem", "(", "msg", ",", "level", "=", "logging", ".", "WARNING", ")", ")", "return", "problems" ]
Check that there are only those files the standard accepts. Return list of DapProblems.
[ "Check", "that", "there", "are", "only", "those", "files", "the", "standard", "accepts", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L306-L394
devassistant/devassistant
devassistant/dapi/__init__.py
DapChecker.check_yamls
def check_yamls(cls, dap): '''Check that all assistants and snippets are valid. Return list of DapProblems.''' problems = list() for yaml in dap.assistants_and_snippets: path = yaml + '.yaml' parsed_yaml = YamlLoader.load_yaml_by_path(dap._get_file(path, prepend=True)) if parsed_yaml: try: yaml_checker.check(path, parsed_yaml) except YamlError as e: problems.append(DapProblem(exc_as_decoded_string(e), level=logging.ERROR)) else: problems.append(DapProblem('Empty YAML ' + path, level=logging.WARNING)) return problems
python
def check_yamls(cls, dap): '''Check that all assistants and snippets are valid. Return list of DapProblems.''' problems = list() for yaml in dap.assistants_and_snippets: path = yaml + '.yaml' parsed_yaml = YamlLoader.load_yaml_by_path(dap._get_file(path, prepend=True)) if parsed_yaml: try: yaml_checker.check(path, parsed_yaml) except YamlError as e: problems.append(DapProblem(exc_as_decoded_string(e), level=logging.ERROR)) else: problems.append(DapProblem('Empty YAML ' + path, level=logging.WARNING)) return problems
[ "def", "check_yamls", "(", "cls", ",", "dap", ")", ":", "problems", "=", "list", "(", ")", "for", "yaml", "in", "dap", ".", "assistants_and_snippets", ":", "path", "=", "yaml", "+", "'.yaml'", "parsed_yaml", "=", "YamlLoader", ".", "load_yaml_by_path", "(", "dap", ".", "_get_file", "(", "path", ",", "prepend", "=", "True", ")", ")", "if", "parsed_yaml", ":", "try", ":", "yaml_checker", ".", "check", "(", "path", ",", "parsed_yaml", ")", "except", "YamlError", "as", "e", ":", "problems", ".", "append", "(", "DapProblem", "(", "exc_as_decoded_string", "(", "e", ")", ",", "level", "=", "logging", ".", "ERROR", ")", ")", "else", ":", "problems", ".", "append", "(", "DapProblem", "(", "'Empty YAML '", "+", "path", ",", "level", "=", "logging", ".", "WARNING", ")", ")", "return", "problems" ]
Check that all assistants and snippets are valid. Return list of DapProblems.
[ "Check", "that", "all", "assistants", "and", "snippets", "are", "valid", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L397-L414
devassistant/devassistant
devassistant/dapi/__init__.py
Dap._strip_leading_dirname
def _strip_leading_dirname(self, path): '''Strip leading directory name from the given path''' return os.path.sep.join(path.split(os.path.sep)[1:])
python
def _strip_leading_dirname(self, path): '''Strip leading directory name from the given path''' return os.path.sep.join(path.split(os.path.sep)[1:])
[ "def", "_strip_leading_dirname", "(", "self", ",", "path", ")", ":", "return", "os", ".", "path", ".", "sep", ".", "join", "(", "path", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "[", "1", ":", "]", ")" ]
Strip leading directory name from the given path
[ "Strip", "leading", "directory", "name", "from", "the", "given", "path" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L511-L513
devassistant/devassistant
devassistant/dapi/__init__.py
Dap.assistants
def assistants(self): '''Get all assistants in this DAP''' return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._assistants_pattern.match(f)]
python
def assistants(self): '''Get all assistants in this DAP''' return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._assistants_pattern.match(f)]
[ "def", "assistants", "(", "self", ")", ":", "return", "[", "strip_suffix", "(", "f", ",", "'.yaml'", ")", "for", "f", "in", "self", ".", "_stripped_files", "if", "self", ".", "_assistants_pattern", ".", "match", "(", "f", ")", "]" ]
Get all assistants in this DAP
[ "Get", "all", "assistants", "in", "this", "DAP" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L521-L523
devassistant/devassistant
devassistant/dapi/__init__.py
Dap.snippets
def snippets(self): '''Get all snippets in this DAP''' return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._snippets_pattern.match(f)]
python
def snippets(self): '''Get all snippets in this DAP''' return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._snippets_pattern.match(f)]
[ "def", "snippets", "(", "self", ")", ":", "return", "[", "strip_suffix", "(", "f", ",", "'.yaml'", ")", "for", "f", "in", "self", ".", "_stripped_files", "if", "self", ".", "_snippets_pattern", ".", "match", "(", "f", ")", "]" ]
Get all snippets in this DAP
[ "Get", "all", "snippets", "in", "this", "DAP" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L526-L528
devassistant/devassistant
devassistant/dapi/__init__.py
Dap.icons
def icons(self, strip_ext=False): '''Get all icons in this DAP, optionally strip extensions''' result = [f for f in self._stripped_files if self._icons_pattern.match(f)] if strip_ext: result = [strip_suffix(f, '\.({ext})'.format(ext=self._icons_ext), regex=True) for f in result] return result
python
def icons(self, strip_ext=False): '''Get all icons in this DAP, optionally strip extensions''' result = [f for f in self._stripped_files if self._icons_pattern.match(f)] if strip_ext: result = [strip_suffix(f, '\.({ext})'.format(ext=self._icons_ext), regex=True) for f in result] return result
[ "def", "icons", "(", "self", ",", "strip_ext", "=", "False", ")", ":", "result", "=", "[", "f", "for", "f", "in", "self", ".", "_stripped_files", "if", "self", ".", "_icons_pattern", ".", "match", "(", "f", ")", "]", "if", "strip_ext", ":", "result", "=", "[", "strip_suffix", "(", "f", ",", "'\\.({ext})'", ".", "format", "(", "ext", "=", "self", ".", "_icons_ext", ")", ",", "regex", "=", "True", ")", "for", "f", "in", "result", "]", "return", "result" ]
Get all icons in this DAP, optionally strip extensions
[ "Get", "all", "icons", "in", "this", "DAP", "optionally", "strip", "extensions" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L535-L541
devassistant/devassistant
devassistant/dapi/__init__.py
Dap._find_bad_meta
def _find_bad_meta(self): '''Fill self._badmeta with meta datatypes that are invalid''' self._badmeta = dict() for datatype in self.meta: for item in self.meta[datatype]: if not Dap._meta_valid[datatype].match(item): if datatype not in self._badmeta: self._badmeta[datatype] = [] self._badmeta[datatype].append(item)
python
def _find_bad_meta(self): '''Fill self._badmeta with meta datatypes that are invalid''' self._badmeta = dict() for datatype in self.meta: for item in self.meta[datatype]: if not Dap._meta_valid[datatype].match(item): if datatype not in self._badmeta: self._badmeta[datatype] = [] self._badmeta[datatype].append(item)
[ "def", "_find_bad_meta", "(", "self", ")", ":", "self", ".", "_badmeta", "=", "dict", "(", ")", "for", "datatype", "in", "self", ".", "meta", ":", "for", "item", "in", "self", ".", "meta", "[", "datatype", "]", ":", "if", "not", "Dap", ".", "_meta_valid", "[", "datatype", "]", ".", "match", "(", "item", ")", ":", "if", "datatype", "not", "in", "self", ".", "_badmeta", ":", "self", ".", "_badmeta", "[", "datatype", "]", "=", "[", "]", "self", ".", "_badmeta", "[", "datatype", "]", ".", "append", "(", "item", ")" ]
Fill self._badmeta with meta datatypes that are invalid
[ "Fill", "self", ".", "_badmeta", "with", "meta", "datatypes", "that", "are", "invalid" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L543-L552
devassistant/devassistant
devassistant/dapi/__init__.py
Dap._get_file
def _get_file(self, path, prepend=False): '''Extracts a file from dap to a file-like object''' if prepend: path = os.path.join(self._dirname(), path) extracted = self._tar.extractfile(path) if extracted: return extracted raise DapFileError(('Could not read %s from %s, maybe it\'s a directory,' + 'bad link or the dap file is corrupted') % (path, self.basename))
python
def _get_file(self, path, prepend=False): '''Extracts a file from dap to a file-like object''' if prepend: path = os.path.join(self._dirname(), path) extracted = self._tar.extractfile(path) if extracted: return extracted raise DapFileError(('Could not read %s from %s, maybe it\'s a directory,' + 'bad link or the dap file is corrupted') % (path, self.basename))
[ "def", "_get_file", "(", "self", ",", "path", ",", "prepend", "=", "False", ")", ":", "if", "prepend", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_dirname", "(", ")", ",", "path", ")", "extracted", "=", "self", ".", "_tar", ".", "extractfile", "(", "path", ")", "if", "extracted", ":", "return", "extracted", "raise", "DapFileError", "(", "(", "'Could not read %s from %s, maybe it\\'s a directory,'", "+", "'bad link or the dap file is corrupted'", ")", "%", "(", "path", ",", "self", ".", "basename", ")", ")" ]
Extracts a file from dap to a file-like object
[ "Extracts", "a", "file", "from", "dap", "to", "a", "file", "-", "like", "object" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L582-L590
devassistant/devassistant
devassistant/dapi/__init__.py
Dap._load_meta
def _load_meta(self, meta): '''Load data from meta.yaml to a dictionary''' meta = yaml.load(meta, Loader=Loader) # Versions are often specified in a format that is convertible to an # int or a float, so we want to make sure it is interpreted as a str. # Fix for the bug #300. if 'version' in meta: meta['version'] = str(meta['version']) return meta
python
def _load_meta(self, meta): '''Load data from meta.yaml to a dictionary''' meta = yaml.load(meta, Loader=Loader) # Versions are often specified in a format that is convertible to an # int or a float, so we want to make sure it is interpreted as a str. # Fix for the bug #300. if 'version' in meta: meta['version'] = str(meta['version']) return meta
[ "def", "_load_meta", "(", "self", ",", "meta", ")", ":", "meta", "=", "yaml", ".", "load", "(", "meta", ",", "Loader", "=", "Loader", ")", "# Versions are often specified in a format that is convertible to an", "# int or a float, so we want to make sure it is interpreted as a str.", "# Fix for the bug #300.", "if", "'version'", "in", "meta", ":", "meta", "[", "'version'", "]", "=", "str", "(", "meta", "[", "'version'", "]", ")", "return", "meta" ]
Load data from meta.yaml to a dictionary
[ "Load", "data", "from", "meta", ".", "yaml", "to", "a", "dictionary" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L592-L602
devassistant/devassistant
devassistant/dapi/__init__.py
Dap._report_problem
def _report_problem(self, problem, level=logging.ERROR): '''Report a given problem''' problem = self.basename + ': ' + problem if self._logger.isEnabledFor(level): self._problematic = True if self._check_raises: raise DapInvalid(problem) self._logger.log(level, problem)
python
def _report_problem(self, problem, level=logging.ERROR): '''Report a given problem''' problem = self.basename + ': ' + problem if self._logger.isEnabledFor(level): self._problematic = True if self._check_raises: raise DapInvalid(problem) self._logger.log(level, problem)
[ "def", "_report_problem", "(", "self", ",", "problem", ",", "level", "=", "logging", ".", "ERROR", ")", ":", "problem", "=", "self", ".", "basename", "+", "': '", "+", "problem", "if", "self", ".", "_logger", ".", "isEnabledFor", "(", "level", ")", ":", "self", ".", "_problematic", "=", "True", "if", "self", ".", "_check_raises", ":", "raise", "DapInvalid", "(", "problem", ")", "self", ".", "_logger", ".", "log", "(", "level", ",", "problem", ")" ]
Report a given problem
[ "Report", "a", "given", "problem" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L604-L611
devassistant/devassistant
devassistant/dapi/__init__.py
Dap._isvalid
def _isvalid(self, datatype): '''Checks if the given datatype is valid in meta''' if datatype in self.meta: return bool(Dap._meta_valid[datatype].match(self.meta[datatype])) else: return datatype in Dap._optional_meta
python
def _isvalid(self, datatype): '''Checks if the given datatype is valid in meta''' if datatype in self.meta: return bool(Dap._meta_valid[datatype].match(self.meta[datatype])) else: return datatype in Dap._optional_meta
[ "def", "_isvalid", "(", "self", ",", "datatype", ")", ":", "if", "datatype", "in", "self", ".", "meta", ":", "return", "bool", "(", "Dap", ".", "_meta_valid", "[", "datatype", "]", ".", "match", "(", "self", ".", "meta", "[", "datatype", "]", ")", ")", "else", ":", "return", "datatype", "in", "Dap", ".", "_optional_meta" ]
Checks if the given datatype is valid in meta
[ "Checks", "if", "the", "given", "datatype", "is", "valid", "in", "meta" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L613-L618
devassistant/devassistant
devassistant/dapi/__init__.py
Dap._arevalid
def _arevalid(self, datatype): '''Checks if the given datatype is valid in meta (for array-like types)''' # Datatype not specified if datatype not in self.meta: return datatype in Dap._optional_meta, [] # Required datatype empty if datatype in self._required_meta and not self.meta[datatype]: return False, [] # Datatype not a list if not isinstance(self.meta[datatype], list): return False, [] # Duplicates found duplicates = set([x for x in self.meta[datatype] if self.meta[datatype].count(x) > 1]) if duplicates: return False, list(duplicates) if datatype in self._badmeta: return False, self._badmeta[datatype] else: return True, [] # Checking if all items are valid bad = [] for item in self.meta[datatype]: if not Dap._meta_valid[datatype].match(item): bad.append(item) return len(bad) == 0, bad
python
def _arevalid(self, datatype): '''Checks if the given datatype is valid in meta (for array-like types)''' # Datatype not specified if datatype not in self.meta: return datatype in Dap._optional_meta, [] # Required datatype empty if datatype in self._required_meta and not self.meta[datatype]: return False, [] # Datatype not a list if not isinstance(self.meta[datatype], list): return False, [] # Duplicates found duplicates = set([x for x in self.meta[datatype] if self.meta[datatype].count(x) > 1]) if duplicates: return False, list(duplicates) if datatype in self._badmeta: return False, self._badmeta[datatype] else: return True, [] # Checking if all items are valid bad = [] for item in self.meta[datatype]: if not Dap._meta_valid[datatype].match(item): bad.append(item) return len(bad) == 0, bad
[ "def", "_arevalid", "(", "self", ",", "datatype", ")", ":", "# Datatype not specified", "if", "datatype", "not", "in", "self", ".", "meta", ":", "return", "datatype", "in", "Dap", ".", "_optional_meta", ",", "[", "]", "# Required datatype empty", "if", "datatype", "in", "self", ".", "_required_meta", "and", "not", "self", ".", "meta", "[", "datatype", "]", ":", "return", "False", ",", "[", "]", "# Datatype not a list", "if", "not", "isinstance", "(", "self", ".", "meta", "[", "datatype", "]", ",", "list", ")", ":", "return", "False", ",", "[", "]", "# Duplicates found", "duplicates", "=", "set", "(", "[", "x", "for", "x", "in", "self", ".", "meta", "[", "datatype", "]", "if", "self", ".", "meta", "[", "datatype", "]", ".", "count", "(", "x", ")", ">", "1", "]", ")", "if", "duplicates", ":", "return", "False", ",", "list", "(", "duplicates", ")", "if", "datatype", "in", "self", ".", "_badmeta", ":", "return", "False", ",", "self", ".", "_badmeta", "[", "datatype", "]", "else", ":", "return", "True", ",", "[", "]", "# Checking if all items are valid", "bad", "=", "[", "]", "for", "item", "in", "self", ".", "meta", "[", "datatype", "]", ":", "if", "not", "Dap", ".", "_meta_valid", "[", "datatype", "]", ".", "match", "(", "item", ")", ":", "bad", ".", "append", "(", "item", ")", "return", "len", "(", "bad", ")", "==", "0", ",", "bad" ]
Checks if the given datatype is valid in meta (for array-like types)
[ "Checks", "if", "the", "given", "datatype", "is", "valid", "in", "meta", "(", "for", "array", "-", "like", "types", ")" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L620-L649
devassistant/devassistant
devassistant/dapi/__init__.py
Dap._is_dir
def _is_dir(self, f): '''Check if the given in-dap file is a directory''' return self._tar.getmember(f).type == tarfile.DIRTYPE
python
def _is_dir(self, f): '''Check if the given in-dap file is a directory''' return self._tar.getmember(f).type == tarfile.DIRTYPE
[ "def", "_is_dir", "(", "self", ",", "f", ")", ":", "return", "self", ".", "_tar", ".", "getmember", "(", "f", ")", ".", "type", "==", "tarfile", ".", "DIRTYPE" ]
Check if the given in-dap file is a directory
[ "Check", "if", "the", "given", "in", "-", "dap", "file", "is", "a", "directory" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L651-L653
devassistant/devassistant
devassistant/dapi/__init__.py
Dap._get_emptydirs
def _get_emptydirs(self, files): '''Find empty directories and return them Only works for actual files in dap''' emptydirs = [] for f in files: if self._is_dir(f): empty = True for ff in files: if ff.startswith(f + '/'): empty = False break if empty: emptydirs.append(f) return emptydirs
python
def _get_emptydirs(self, files): '''Find empty directories and return them Only works for actual files in dap''' emptydirs = [] for f in files: if self._is_dir(f): empty = True for ff in files: if ff.startswith(f + '/'): empty = False break if empty: emptydirs.append(f) return emptydirs
[ "def", "_get_emptydirs", "(", "self", ",", "files", ")", ":", "emptydirs", "=", "[", "]", "for", "f", "in", "files", ":", "if", "self", ".", "_is_dir", "(", "f", ")", ":", "empty", "=", "True", "for", "ff", "in", "files", ":", "if", "ff", ".", "startswith", "(", "f", "+", "'/'", ")", ":", "empty", "=", "False", "break", "if", "empty", ":", "emptydirs", ".", "append", "(", "f", ")", "return", "emptydirs" ]
Find empty directories and return them Only works for actual files in dap
[ "Find", "empty", "directories", "and", "return", "them", "Only", "works", "for", "actual", "files", "in", "dap" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L655-L668
devassistant/devassistant
devassistant/config_manager.py
ConfigManager.load_configuration_file
def load_configuration_file(self): """ Load all configuration from file """ if not os.path.exists(self.config_file): return try: with open(self.config_file, 'r') as file: csvreader = csv.reader(file, delimiter='=', escapechar='\\', quoting=csv.QUOTE_NONE) for line in csvreader: if len(line) == 2: key, value = line self.config_dict[key] = value else: self.config_dict = dict() self.logger.warning("Malformed configuration file {0}, ignoring it.". format(self.config_file)) return except (OSError, IOError) as e: self.logger.warning("Could not load configuration file: {0}".\ format(utils.exc_as_decoded_string(e)))
python
def load_configuration_file(self): """ Load all configuration from file """ if not os.path.exists(self.config_file): return try: with open(self.config_file, 'r') as file: csvreader = csv.reader(file, delimiter='=', escapechar='\\', quoting=csv.QUOTE_NONE) for line in csvreader: if len(line) == 2: key, value = line self.config_dict[key] = value else: self.config_dict = dict() self.logger.warning("Malformed configuration file {0}, ignoring it.". format(self.config_file)) return except (OSError, IOError) as e: self.logger.warning("Could not load configuration file: {0}".\ format(utils.exc_as_decoded_string(e)))
[ "def", "load_configuration_file", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "config_file", ")", ":", "return", "try", ":", "with", "open", "(", "self", ".", "config_file", ",", "'r'", ")", "as", "file", ":", "csvreader", "=", "csv", ".", "reader", "(", "file", ",", "delimiter", "=", "'='", ",", "escapechar", "=", "'\\\\'", ",", "quoting", "=", "csv", ".", "QUOTE_NONE", ")", "for", "line", "in", "csvreader", ":", "if", "len", "(", "line", ")", "==", "2", ":", "key", ",", "value", "=", "line", "self", ".", "config_dict", "[", "key", "]", "=", "value", "else", ":", "self", ".", "config_dict", "=", "dict", "(", ")", "self", ".", "logger", ".", "warning", "(", "\"Malformed configuration file {0}, ignoring it.\"", ".", "format", "(", "self", ".", "config_file", ")", ")", "return", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "self", ".", "logger", ".", "warning", "(", "\"Could not load configuration file: {0}\"", ".", "format", "(", "utils", ".", "exc_as_decoded_string", "(", "e", ")", ")", ")" ]
Load all configuration from file
[ "Load", "all", "configuration", "from", "file" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/config_manager.py#L22-L43
devassistant/devassistant
devassistant/config_manager.py
ConfigManager.save_configuration_file
def save_configuration_file(self): """ Save all configuration into file Only if config file does not yet exist or configuration was changed """ if os.path.exists(self.config_file) and not self.config_changed: return dirname = os.path.dirname(self.config_file) try: if not os.path.exists(dirname): os.makedirs(dirname) except (OSError, IOError) as e: self.logger.warning("Could not make directory for configuration file: {0}". format(utils.exc_as_decoded_string(e))) return try: with open(self.config_file, 'w') as file: csvwriter = csv.writer(file, delimiter='=', escapechar='\\', lineterminator='\n', quoting=csv.QUOTE_NONE) for key, value in self.config_dict.items(): csvwriter.writerow([key, value]) self.config_changed = False except (OSError, IOError) as e: self.logger.warning("Could not save configuration file: {0}".\ format(utils.exc_as_decoded_string(e)))
python
def save_configuration_file(self): """ Save all configuration into file Only if config file does not yet exist or configuration was changed """ if os.path.exists(self.config_file) and not self.config_changed: return dirname = os.path.dirname(self.config_file) try: if not os.path.exists(dirname): os.makedirs(dirname) except (OSError, IOError) as e: self.logger.warning("Could not make directory for configuration file: {0}". format(utils.exc_as_decoded_string(e))) return try: with open(self.config_file, 'w') as file: csvwriter = csv.writer(file, delimiter='=', escapechar='\\', lineterminator='\n', quoting=csv.QUOTE_NONE) for key, value in self.config_dict.items(): csvwriter.writerow([key, value]) self.config_changed = False except (OSError, IOError) as e: self.logger.warning("Could not save configuration file: {0}".\ format(utils.exc_as_decoded_string(e)))
[ "def", "save_configuration_file", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "config_file", ")", "and", "not", "self", ".", "config_changed", ":", "return", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "config_file", ")", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "self", ".", "logger", ".", "warning", "(", "\"Could not make directory for configuration file: {0}\"", ".", "format", "(", "utils", ".", "exc_as_decoded_string", "(", "e", ")", ")", ")", "return", "try", ":", "with", "open", "(", "self", ".", "config_file", ",", "'w'", ")", "as", "file", ":", "csvwriter", "=", "csv", ".", "writer", "(", "file", ",", "delimiter", "=", "'='", ",", "escapechar", "=", "'\\\\'", ",", "lineterminator", "=", "'\\n'", ",", "quoting", "=", "csv", ".", "QUOTE_NONE", ")", "for", "key", ",", "value", "in", "self", ".", "config_dict", ".", "items", "(", ")", ":", "csvwriter", ".", "writerow", "(", "[", "key", ",", "value", "]", ")", "self", ".", "config_changed", "=", "False", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "self", ".", "logger", ".", "warning", "(", "\"Could not save configuration file: {0}\"", ".", "format", "(", "utils", ".", "exc_as_decoded_string", "(", "e", ")", ")", ")" ]
Save all configuration into file Only if config file does not yet exist or configuration was changed
[ "Save", "all", "configuration", "into", "file", "Only", "if", "config", "file", "does", "not", "yet", "exist", "or", "configuration", "was", "changed" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/config_manager.py#L45-L69
devassistant/devassistant
devassistant/config_manager.py
ConfigManager.set_config_value
def set_config_value(self, name, value): """ Set configuration value with given name. Value can be string or boolean type. """ if value is True: value = "True" elif value is False: if name in self.config_dict: del self.config_dict[name] self.config_changed = True return if name not in self.config_dict or self.config_dict[name] != value: self.config_changed = True self.config_dict[name] = value
python
def set_config_value(self, name, value): """ Set configuration value with given name. Value can be string or boolean type. """ if value is True: value = "True" elif value is False: if name in self.config_dict: del self.config_dict[name] self.config_changed = True return if name not in self.config_dict or self.config_dict[name] != value: self.config_changed = True self.config_dict[name] = value
[ "def", "set_config_value", "(", "self", ",", "name", ",", "value", ")", ":", "if", "value", "is", "True", ":", "value", "=", "\"True\"", "elif", "value", "is", "False", ":", "if", "name", "in", "self", ".", "config_dict", ":", "del", "self", ".", "config_dict", "[", "name", "]", "self", ".", "config_changed", "=", "True", "return", "if", "name", "not", "in", "self", ".", "config_dict", "or", "self", ".", "config_dict", "[", "name", "]", "!=", "value", ":", "self", ".", "config_changed", "=", "True", "self", ".", "config_dict", "[", "name", "]", "=", "value" ]
Set configuration value with given name. Value can be string or boolean type.
[ "Set", "configuration", "value", "with", "given", "name", ".", "Value", "can", "be", "string", "or", "boolean", "type", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/config_manager.py#L77-L91
devassistant/devassistant
devassistant/gui/main_window.py
MainWindow.tooltip_queries
def tooltip_queries(self, item, x_coord, y_coord, key_mode, tooltip, text): """ The function is used for setting tooltip on menus and submenus """ tooltip.set_text(text) return True
python
def tooltip_queries(self, item, x_coord, y_coord, key_mode, tooltip, text): """ The function is used for setting tooltip on menus and submenus """ tooltip.set_text(text) return True
[ "def", "tooltip_queries", "(", "self", ",", "item", ",", "x_coord", ",", "y_coord", ",", "key_mode", ",", "tooltip", ",", "text", ")", ":", "tooltip", ".", "set_text", "(", "text", ")", "return", "True" ]
The function is used for setting tooltip on menus and submenus
[ "The", "function", "is", "used", "for", "setting", "tooltip", "on", "menus", "and", "submenus" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L110-L115
devassistant/devassistant
devassistant/gui/main_window.py
MainWindow._create_notebook_page
def _create_notebook_page(self, assistant): """ This function is used for create tab page for notebook. Input arguments are: assistant - used for collecting all info about assistants and subassistants """ #frame = self._create_frame() grid_lang = self.gui_helper.create_gtk_grid() scrolled_window = self.gui_helper.create_scrolled_window(grid_lang) row = 0 column = 0 scrolled_window.main_assistant, sub_as = assistant.get_subassistant_tree() for ass in sorted(sub_as, key=lambda x: x[0].fullname.lower()): if column > 2: row += 1 column = 0 if not ass[1]: # If assistant has not any subassistant then create only button self.gui_helper.add_button(grid_lang, ass, row, column) else: # If assistant has more subassistants then create button with menu self.gui_helper.add_submenu(grid_lang, ass, row, column) column += 1 # Install More Assistants button if column > 2: row += 1 column = 0 self.gui_helper.add_install_button(grid_lang, row, column) column += 1 if row == 0 and len(sub_as) < 3: while column < 3: btn = self.gui_helper.create_button(style=Gtk.ReliefStyle.NONE) btn.set_sensitive(False) btn.hide() grid_lang.attach(btn, column, row, 1, 1) column += 1 return scrolled_window
python
def _create_notebook_page(self, assistant): """ This function is used for create tab page for notebook. Input arguments are: assistant - used for collecting all info about assistants and subassistants """ #frame = self._create_frame() grid_lang = self.gui_helper.create_gtk_grid() scrolled_window = self.gui_helper.create_scrolled_window(grid_lang) row = 0 column = 0 scrolled_window.main_assistant, sub_as = assistant.get_subassistant_tree() for ass in sorted(sub_as, key=lambda x: x[0].fullname.lower()): if column > 2: row += 1 column = 0 if not ass[1]: # If assistant has not any subassistant then create only button self.gui_helper.add_button(grid_lang, ass, row, column) else: # If assistant has more subassistants then create button with menu self.gui_helper.add_submenu(grid_lang, ass, row, column) column += 1 # Install More Assistants button if column > 2: row += 1 column = 0 self.gui_helper.add_install_button(grid_lang, row, column) column += 1 if row == 0 and len(sub_as) < 3: while column < 3: btn = self.gui_helper.create_button(style=Gtk.ReliefStyle.NONE) btn.set_sensitive(False) btn.hide() grid_lang.attach(btn, column, row, 1, 1) column += 1 return scrolled_window
[ "def", "_create_notebook_page", "(", "self", ",", "assistant", ")", ":", "#frame = self._create_frame()", "grid_lang", "=", "self", ".", "gui_helper", ".", "create_gtk_grid", "(", ")", "scrolled_window", "=", "self", ".", "gui_helper", ".", "create_scrolled_window", "(", "grid_lang", ")", "row", "=", "0", "column", "=", "0", "scrolled_window", ".", "main_assistant", ",", "sub_as", "=", "assistant", ".", "get_subassistant_tree", "(", ")", "for", "ass", "in", "sorted", "(", "sub_as", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "fullname", ".", "lower", "(", ")", ")", ":", "if", "column", ">", "2", ":", "row", "+=", "1", "column", "=", "0", "if", "not", "ass", "[", "1", "]", ":", "# If assistant has not any subassistant then create only button", "self", ".", "gui_helper", ".", "add_button", "(", "grid_lang", ",", "ass", ",", "row", ",", "column", ")", "else", ":", "# If assistant has more subassistants then create button with menu", "self", ".", "gui_helper", ".", "add_submenu", "(", "grid_lang", ",", "ass", ",", "row", ",", "column", ")", "column", "+=", "1", "# Install More Assistants button", "if", "column", ">", "2", ":", "row", "+=", "1", "column", "=", "0", "self", ".", "gui_helper", ".", "add_install_button", "(", "grid_lang", ",", "row", ",", "column", ")", "column", "+=", "1", "if", "row", "==", "0", "and", "len", "(", "sub_as", ")", "<", "3", ":", "while", "column", "<", "3", ":", "btn", "=", "self", ".", "gui_helper", ".", "create_button", "(", "style", "=", "Gtk", ".", "ReliefStyle", ".", "NONE", ")", "btn", ".", "set_sensitive", "(", "False", ")", "btn", ".", "hide", "(", ")", "grid_lang", ".", "attach", "(", "btn", ",", "column", ",", "row", ",", "1", ",", "1", ")", "column", "+=", "1", "return", "scrolled_window" ]
This function is used for create tab page for notebook. Input arguments are: assistant - used for collecting all info about assistants and subassistants
[ "This", "function", "is", "used", "for", "create", "tab", "page", "for", "notebook", ".", "Input", "arguments", "are", ":", "assistant", "-", "used", "for", "collecting", "all", "info", "about", "assistants", "and", "subassistants" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L117-L155
devassistant/devassistant
devassistant/gui/main_window.py
MainWindow._open_path_window
def _open_path_window(self): """ Hides this window and opens path window. Passes all needed data and kwargs. """ self.data['top_assistant'] = self.top_assistant self.data['current_main_assistant'] = self.get_current_main_assistant() self.data['kwargs'] = self.kwargs self.path_window.open_window(self.data) self.main_win.hide()
python
def _open_path_window(self): """ Hides this window and opens path window. Passes all needed data and kwargs. """ self.data['top_assistant'] = self.top_assistant self.data['current_main_assistant'] = self.get_current_main_assistant() self.data['kwargs'] = self.kwargs self.path_window.open_window(self.data) self.main_win.hide()
[ "def", "_open_path_window", "(", "self", ")", ":", "self", ".", "data", "[", "'top_assistant'", "]", "=", "self", ".", "top_assistant", "self", ".", "data", "[", "'current_main_assistant'", "]", "=", "self", ".", "get_current_main_assistant", "(", ")", "self", ".", "data", "[", "'kwargs'", "]", "=", "self", ".", "kwargs", "self", ".", "path_window", ".", "open_window", "(", "self", ".", "data", ")", "self", ".", "main_win", ".", "hide", "(", ")" ]
Hides this window and opens path window. Passes all needed data and kwargs.
[ "Hides", "this", "window", "and", "opens", "path", "window", ".", "Passes", "all", "needed", "data", "and", "kwargs", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L163-L172
devassistant/devassistant
devassistant/gui/main_window.py
MainWindow.sub_menu_pressed
def sub_menu_pressed(self, widget, event): """ Function serves for getting full assistant path and collects the information from GUI """ for index, data in enumerate(self.dev_assistant_path): index += 1 if settings.SUBASSISTANT_N_STRING.format(index) in self.kwargs: del self.kwargs[settings.SUBASSISTANT_N_STRING.format(index)] self.kwargs[settings.SUBASSISTANT_N_STRING.format(index)] = data self.kwargs['subassistant_0'] = self.get_current_main_assistant().name self._open_path_window()
python
def sub_menu_pressed(self, widget, event): """ Function serves for getting full assistant path and collects the information from GUI """ for index, data in enumerate(self.dev_assistant_path): index += 1 if settings.SUBASSISTANT_N_STRING.format(index) in self.kwargs: del self.kwargs[settings.SUBASSISTANT_N_STRING.format(index)] self.kwargs[settings.SUBASSISTANT_N_STRING.format(index)] = data self.kwargs['subassistant_0'] = self.get_current_main_assistant().name self._open_path_window()
[ "def", "sub_menu_pressed", "(", "self", ",", "widget", ",", "event", ")", ":", "for", "index", ",", "data", "in", "enumerate", "(", "self", ".", "dev_assistant_path", ")", ":", "index", "+=", "1", "if", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "index", ")", "in", "self", ".", "kwargs", ":", "del", "self", ".", "kwargs", "[", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "index", ")", "]", "self", ".", "kwargs", "[", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "index", ")", "]", "=", "data", "self", ".", "kwargs", "[", "'subassistant_0'", "]", "=", "self", ".", "get_current_main_assistant", "(", ")", ".", "name", "self", ".", "_open_path_window", "(", ")" ]
Function serves for getting full assistant path and collects the information from GUI
[ "Function", "serves", "for", "getting", "full", "assistant", "path", "and", "collects", "the", "information", "from", "GUI" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L174-L185
devassistant/devassistant
devassistant/gui/main_window.py
MainWindow.get_current_main_assistant
def get_current_main_assistant(self): """ Function return current assistant """ current_page = self.notebook.get_nth_page(self.notebook.get_current_page()) return current_page.main_assistant
python
def get_current_main_assistant(self): """ Function return current assistant """ current_page = self.notebook.get_nth_page(self.notebook.get_current_page()) return current_page.main_assistant
[ "def", "get_current_main_assistant", "(", "self", ")", ":", "current_page", "=", "self", ".", "notebook", ".", "get_nth_page", "(", "self", ".", "notebook", ".", "get_current_page", "(", ")", ")", "return", "current_page", ".", "main_assistant" ]
Function return current assistant
[ "Function", "return", "current", "assistant" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L187-L192
devassistant/devassistant
devassistant/gui/main_window.py
MainWindow.btn_clicked
def btn_clicked(self, widget, data=None): """ Function is used for case that assistant does not have any subassistants """ self.kwargs['subassistant_0'] = self.get_current_main_assistant().name self.kwargs['subassistant_1'] = data if 'subassistant_2' in self.kwargs: del self.kwargs['subassistant_2'] self._open_path_window()
python
def btn_clicked(self, widget, data=None): """ Function is used for case that assistant does not have any subassistants """ self.kwargs['subassistant_0'] = self.get_current_main_assistant().name self.kwargs['subassistant_1'] = data if 'subassistant_2' in self.kwargs: del self.kwargs['subassistant_2'] self._open_path_window()
[ "def", "btn_clicked", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "self", ".", "kwargs", "[", "'subassistant_0'", "]", "=", "self", ".", "get_current_main_assistant", "(", ")", ".", "name", "self", ".", "kwargs", "[", "'subassistant_1'", "]", "=", "data", "if", "'subassistant_2'", "in", "self", ".", "kwargs", ":", "del", "self", ".", "kwargs", "[", "'subassistant_2'", "]", "self", ".", "_open_path_window", "(", ")" ]
Function is used for case that assistant does not have any subassistants
[ "Function", "is", "used", "for", "case", "that", "assistant", "does", "not", "have", "any", "subassistants" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L194-L203
devassistant/devassistant
devassistant/gui/main_window.py
MainWindow.open_window
def open_window(self, widget, data=None): """ Function opens Main Window and in case of previously created project is switches to /home directory This is fix in case that da creats a project and project was deleted and GUI was not closed yet """ if data is not None: self.data = data os.chdir(os.path.expanduser('~')) self.kwargs = dict() self.main_win.show_all()
python
def open_window(self, widget, data=None): """ Function opens Main Window and in case of previously created project is switches to /home directory This is fix in case that da creats a project and project was deleted and GUI was not closed yet """ if data is not None: self.data = data os.chdir(os.path.expanduser('~')) self.kwargs = dict() self.main_win.show_all()
[ "def", "open_window", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "if", "data", "is", "not", "None", ":", "self", ".", "data", "=", "data", "os", ".", "chdir", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ")", "self", ".", "kwargs", "=", "dict", "(", ")", "self", ".", "main_win", ".", "show_all", "(", ")" ]
Function opens Main Window and in case of previously created project is switches to /home directory This is fix in case that da creats a project and project was deleted and GUI was not closed yet
[ "Function", "opens", "Main", "Window", "and", "in", "case", "of", "previously", "created", "project", "is", "switches", "to", "/", "home", "directory", "This", "is", "fix", "in", "case", "that", "da", "creats", "a", "project", "and", "project", "was", "deleted", "and", "GUI", "was", "not", "closed", "yet" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L224-L235
devassistant/devassistant
devassistant/gui/main_window.py
MainWindow.btn_press_event
def btn_press_event(self, widget, event): """ Function is used for showing Popup menu """ if event.type == Gdk.EventType.BUTTON_PRESS: if event.button.button == 1: widget.popup(None, None, None, None, event.button.button, event.time) return True return False
python
def btn_press_event(self, widget, event): """ Function is used for showing Popup menu """ if event.type == Gdk.EventType.BUTTON_PRESS: if event.button.button == 1: widget.popup(None, None, None, None, event.button.button, event.time) return True return False
[ "def", "btn_press_event", "(", "self", ",", "widget", ",", "event", ")", ":", "if", "event", ".", "type", "==", "Gdk", ".", "EventType", ".", "BUTTON_PRESS", ":", "if", "event", ".", "button", ".", "button", "==", "1", ":", "widget", ".", "popup", "(", "None", ",", "None", ",", "None", ",", "None", ",", "event", ".", "button", ".", "button", ",", "event", ".", "time", ")", "return", "True", "return", "False" ]
Function is used for showing Popup menu
[ "Function", "is", "used", "for", "showing", "Popup", "menu" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L237-L246
devassistant/devassistant
devassistant/gui/__init__.py
run_gui
def run_gui(): """ Function for running DevAssistant GUI """ try: from gi.repository import Gtk except ImportError as ie: pass except RuntimeError as e: sys.stderr.write(GUI_MESSAGE) sys.stderr.write("%s: %r" % (e.__class__.__name__, utils.exc_as_decoded_string(e))) sys.stderr.flush() sys.exit(1) if not os.environ.get('DISPLAY'): sys.stderr.write("%s %s" % (GUI_MESSAGE, GUI_MESSAGE_DISPLAY)) sys.stderr.flush() sys.exit(1) # For GNOME 3 icon: # because this is invoked as da-gui and the desktop file is called devassistant try: from gi.repository import GLib GLib.set_prgname(PRGNAME) except ImportError: pass parser = argparse.ArgumentParser(description='Run DevAssistant GUI.') utils.add_no_cache_argument(parser) # now we only have "--no-cache" argument, which we don't actually need to remember, # see add_no_cache_argument help; so we only run parse_args to determine if # the invocation was correct parser.parse_args() settings.USE_CACHE = False if '--no-cache' in sys.argv else True from devassistant.gui import main_window main_window.MainWindow()
python
def run_gui(): """ Function for running DevAssistant GUI """ try: from gi.repository import Gtk except ImportError as ie: pass except RuntimeError as e: sys.stderr.write(GUI_MESSAGE) sys.stderr.write("%s: %r" % (e.__class__.__name__, utils.exc_as_decoded_string(e))) sys.stderr.flush() sys.exit(1) if not os.environ.get('DISPLAY'): sys.stderr.write("%s %s" % (GUI_MESSAGE, GUI_MESSAGE_DISPLAY)) sys.stderr.flush() sys.exit(1) # For GNOME 3 icon: # because this is invoked as da-gui and the desktop file is called devassistant try: from gi.repository import GLib GLib.set_prgname(PRGNAME) except ImportError: pass parser = argparse.ArgumentParser(description='Run DevAssistant GUI.') utils.add_no_cache_argument(parser) # now we only have "--no-cache" argument, which we don't actually need to remember, # see add_no_cache_argument help; so we only run parse_args to determine if # the invocation was correct parser.parse_args() settings.USE_CACHE = False if '--no-cache' in sys.argv else True from devassistant.gui import main_window main_window.MainWindow()
[ "def", "run_gui", "(", ")", ":", "try", ":", "from", "gi", ".", "repository", "import", "Gtk", "except", "ImportError", "as", "ie", ":", "pass", "except", "RuntimeError", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "GUI_MESSAGE", ")", "sys", ".", "stderr", ".", "write", "(", "\"%s: %r\"", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "utils", ".", "exc_as_decoded_string", "(", "e", ")", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "sys", ".", "exit", "(", "1", ")", "if", "not", "os", ".", "environ", ".", "get", "(", "'DISPLAY'", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"%s %s\"", "%", "(", "GUI_MESSAGE", ",", "GUI_MESSAGE_DISPLAY", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "sys", ".", "exit", "(", "1", ")", "# For GNOME 3 icon:", "# because this is invoked as da-gui and the desktop file is called devassistant", "try", ":", "from", "gi", ".", "repository", "import", "GLib", "GLib", ".", "set_prgname", "(", "PRGNAME", ")", "except", "ImportError", ":", "pass", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Run DevAssistant GUI.'", ")", "utils", ".", "add_no_cache_argument", "(", "parser", ")", "# now we only have \"--no-cache\" argument, which we don't actually need to remember,", "# see add_no_cache_argument help; so we only run parse_args to determine if", "# the invocation was correct", "parser", ".", "parse_args", "(", ")", "settings", ".", "USE_CACHE", "=", "False", "if", "'--no-cache'", "in", "sys", ".", "argv", "else", "True", "from", "devassistant", ".", "gui", "import", "main_window", "main_window", ".", "MainWindow", "(", ")" ]
Function for running DevAssistant GUI
[ "Function", "for", "running", "DevAssistant", "GUI" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/__init__.py#L14-L50
devassistant/devassistant
devassistant/yaml_assistant.py
needs_fully_loaded
def needs_fully_loaded(method): """Wraps all publicly callable methods of YamlAssistant. If the assistant was loaded from cache, this decorator will fully load it first time a publicly callable method is used. """ @functools.wraps(method) def inner(self, *args, **kwargs): if not self.fully_loaded: loaded_yaml = yaml_loader.YamlLoader.load_yaml_by_path(self.path) self.parsed_yaml = loaded_yaml self.fully_loaded = True return method(self, *args, **kwargs) return inner
python
def needs_fully_loaded(method): """Wraps all publicly callable methods of YamlAssistant. If the assistant was loaded from cache, this decorator will fully load it first time a publicly callable method is used. """ @functools.wraps(method) def inner(self, *args, **kwargs): if not self.fully_loaded: loaded_yaml = yaml_loader.YamlLoader.load_yaml_by_path(self.path) self.parsed_yaml = loaded_yaml self.fully_loaded = True return method(self, *args, **kwargs) return inner
[ "def", "needs_fully_loaded", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "inner", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "fully_loaded", ":", "loaded_yaml", "=", "yaml_loader", ".", "YamlLoader", ".", "load_yaml_by_path", "(", "self", ".", "path", ")", "self", ".", "parsed_yaml", "=", "loaded_yaml", "self", ".", "fully_loaded", "=", "True", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "inner" ]
Wraps all publicly callable methods of YamlAssistant. If the assistant was loaded from cache, this decorator will fully load it first time a publicly callable method is used.
[ "Wraps", "all", "publicly", "callable", "methods", "of", "YamlAssistant", ".", "If", "the", "assistant", "was", "loaded", "from", "cache", "this", "decorator", "will", "fully", "load", "it", "first", "time", "a", "publicly", "callable", "method", "is", "used", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_assistant.py#L19-L32
devassistant/devassistant
devassistant/yaml_assistant.py
YamlAssistant.default_icon_path
def default_icon_path(self): """Returns default path to icon of this assistant. Assuming self.path == "/foo/assistants/crt/python/django.yaml" For image format in [png, svg]: 1) Take the path of this assistant and strip it of load path (=> "crt/python/django.yaml") 2) Substitute its extension for <image format> (=> "crt/python/django.<image format>") 3) Prepend self.load_path + 'icons' (=> "/foo/icons/crt/python/django.<image format>") 4) If file from 3) exists, return it Return empty string if no icon found. """ supported_exts = ['.png', '.svg'] stripped = self.path.replace(os.path.join(self.load_path, 'assistants'), '').strip(os.sep) for ext in supported_exts: icon_with_ext = os.path.splitext(stripped)[0] + ext icon_fullpath = os.path.join(self.load_path, 'icons', icon_with_ext) if os.path.exists(icon_fullpath): return icon_fullpath return ''
python
def default_icon_path(self): """Returns default path to icon of this assistant. Assuming self.path == "/foo/assistants/crt/python/django.yaml" For image format in [png, svg]: 1) Take the path of this assistant and strip it of load path (=> "crt/python/django.yaml") 2) Substitute its extension for <image format> (=> "crt/python/django.<image format>") 3) Prepend self.load_path + 'icons' (=> "/foo/icons/crt/python/django.<image format>") 4) If file from 3) exists, return it Return empty string if no icon found. """ supported_exts = ['.png', '.svg'] stripped = self.path.replace(os.path.join(self.load_path, 'assistants'), '').strip(os.sep) for ext in supported_exts: icon_with_ext = os.path.splitext(stripped)[0] + ext icon_fullpath = os.path.join(self.load_path, 'icons', icon_with_ext) if os.path.exists(icon_fullpath): return icon_fullpath return ''
[ "def", "default_icon_path", "(", "self", ")", ":", "supported_exts", "=", "[", "'.png'", ",", "'.svg'", "]", "stripped", "=", "self", ".", "path", ".", "replace", "(", "os", ".", "path", ".", "join", "(", "self", ".", "load_path", ",", "'assistants'", ")", ",", "''", ")", ".", "strip", "(", "os", ".", "sep", ")", "for", "ext", "in", "supported_exts", ":", "icon_with_ext", "=", "os", ".", "path", ".", "splitext", "(", "stripped", ")", "[", "0", "]", "+", "ext", "icon_fullpath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "load_path", ",", "'icons'", ",", "icon_with_ext", ")", "if", "os", ".", "path", ".", "exists", "(", "icon_fullpath", ")", ":", "return", "icon_fullpath", "return", "''" ]
Returns default path to icon of this assistant. Assuming self.path == "/foo/assistants/crt/python/django.yaml" For image format in [png, svg]: 1) Take the path of this assistant and strip it of load path (=> "crt/python/django.yaml") 2) Substitute its extension for <image format> (=> "crt/python/django.<image format>") 3) Prepend self.load_path + 'icons' (=> "/foo/icons/crt/python/django.<image format>") 4) If file from 3) exists, return it Return empty string if no icon found.
[ "Returns", "default", "path", "to", "icon", "of", "this", "assistant", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_assistant.py#L95-L116
devassistant/devassistant
devassistant/yaml_assistant.py
YamlAssistant.proper_kwargs
def proper_kwargs(self, section, kwargs): """Returns kwargs updated with proper meta variables (like __assistant__). If this method is run repeatedly with the same section and the same kwargs, it always modifies kwargs in the same way. """ kwargs['__section__'] = section kwargs['__assistant__'] = self kwargs['__env__'] = copy.deepcopy(os.environ) kwargs['__files__'] = [self._files] kwargs['__files_dir__'] = [self.files_dir] kwargs['__sourcefiles__'] = [self.path] # if any of the following fails, DA should keep running for i in ['system_name', 'system_version', 'distro_name', 'distro_version']: try: val = getattr(utils, 'get_' + i)() except: val = '' kwargs['__' + i + '__'] = val
python
def proper_kwargs(self, section, kwargs): """Returns kwargs updated with proper meta variables (like __assistant__). If this method is run repeatedly with the same section and the same kwargs, it always modifies kwargs in the same way. """ kwargs['__section__'] = section kwargs['__assistant__'] = self kwargs['__env__'] = copy.deepcopy(os.environ) kwargs['__files__'] = [self._files] kwargs['__files_dir__'] = [self.files_dir] kwargs['__sourcefiles__'] = [self.path] # if any of the following fails, DA should keep running for i in ['system_name', 'system_version', 'distro_name', 'distro_version']: try: val = getattr(utils, 'get_' + i)() except: val = '' kwargs['__' + i + '__'] = val
[ "def", "proper_kwargs", "(", "self", ",", "section", ",", "kwargs", ")", ":", "kwargs", "[", "'__section__'", "]", "=", "section", "kwargs", "[", "'__assistant__'", "]", "=", "self", "kwargs", "[", "'__env__'", "]", "=", "copy", ".", "deepcopy", "(", "os", ".", "environ", ")", "kwargs", "[", "'__files__'", "]", "=", "[", "self", ".", "_files", "]", "kwargs", "[", "'__files_dir__'", "]", "=", "[", "self", ".", "files_dir", "]", "kwargs", "[", "'__sourcefiles__'", "]", "=", "[", "self", ".", "path", "]", "# if any of the following fails, DA should keep running", "for", "i", "in", "[", "'system_name'", ",", "'system_version'", ",", "'distro_name'", ",", "'distro_version'", "]", ":", "try", ":", "val", "=", "getattr", "(", "utils", ",", "'get_'", "+", "i", ")", "(", ")", "except", ":", "val", "=", "''", "kwargs", "[", "'__'", "+", "i", "+", "'__'", "]", "=", "val" ]
Returns kwargs updated with proper meta variables (like __assistant__). If this method is run repeatedly with the same section and the same kwargs, it always modifies kwargs in the same way.
[ "Returns", "kwargs", "updated", "with", "proper", "meta", "variables", "(", "like", "__assistant__", ")", ".", "If", "this", "method", "is", "run", "repeatedly", "with", "the", "same", "section", "and", "the", "same", "kwargs", "it", "always", "modifies", "kwargs", "in", "the", "same", "way", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_assistant.py#L141-L158
devassistant/devassistant
devassistant/yaml_assistant.py
YamlAssistant.dependencies
def dependencies(self, kwargs=None, expand_only=False): """Returns all dependencies of this assistant with regards to specified kwargs. If expand_only == False, this method returns list of mappings of dependency types to actual dependencies (keeps order, types can repeat), e.g. Example: [{'rpm', ['rubygems']}, {'gem', ['mygem']}, {'rpm', ['spam']}, ...] If expand_only == True, this method returns a structure that can be used as "dependencies" section and has all the "use: foo" commands expanded (but conditions are left untouched and variables are not substituted). """ # we can't use {} as a default for kwargs, as that initializes the dict only once in Python # and uses the same dict in all subsequent calls of this method if not kwargs: kwargs = {} self.proper_kwargs('dependencies', kwargs) sections = self._get_dependency_sections_to_use(kwargs) deps = [] for sect in sections: if expand_only: deps.extend(lang.expand_dependencies_section(sect, kwargs)) else: deps.extend(lang.dependencies_section(sect, kwargs, runner=self)) return deps
python
def dependencies(self, kwargs=None, expand_only=False): """Returns all dependencies of this assistant with regards to specified kwargs. If expand_only == False, this method returns list of mappings of dependency types to actual dependencies (keeps order, types can repeat), e.g. Example: [{'rpm', ['rubygems']}, {'gem', ['mygem']}, {'rpm', ['spam']}, ...] If expand_only == True, this method returns a structure that can be used as "dependencies" section and has all the "use: foo" commands expanded (but conditions are left untouched and variables are not substituted). """ # we can't use {} as a default for kwargs, as that initializes the dict only once in Python # and uses the same dict in all subsequent calls of this method if not kwargs: kwargs = {} self.proper_kwargs('dependencies', kwargs) sections = self._get_dependency_sections_to_use(kwargs) deps = [] for sect in sections: if expand_only: deps.extend(lang.expand_dependencies_section(sect, kwargs)) else: deps.extend(lang.dependencies_section(sect, kwargs, runner=self)) return deps
[ "def", "dependencies", "(", "self", ",", "kwargs", "=", "None", ",", "expand_only", "=", "False", ")", ":", "# we can't use {} as a default for kwargs, as that initializes the dict only once in Python", "# and uses the same dict in all subsequent calls of this method", "if", "not", "kwargs", ":", "kwargs", "=", "{", "}", "self", ".", "proper_kwargs", "(", "'dependencies'", ",", "kwargs", ")", "sections", "=", "self", ".", "_get_dependency_sections_to_use", "(", "kwargs", ")", "deps", "=", "[", "]", "for", "sect", "in", "sections", ":", "if", "expand_only", ":", "deps", ".", "extend", "(", "lang", ".", "expand_dependencies_section", "(", "sect", ",", "kwargs", ")", ")", "else", ":", "deps", ".", "extend", "(", "lang", ".", "dependencies_section", "(", "sect", ",", "kwargs", ",", "runner", "=", "self", ")", ")", "return", "deps" ]
Returns all dependencies of this assistant with regards to specified kwargs. If expand_only == False, this method returns list of mappings of dependency types to actual dependencies (keeps order, types can repeat), e.g. Example: [{'rpm', ['rubygems']}, {'gem', ['mygem']}, {'rpm', ['spam']}, ...] If expand_only == True, this method returns a structure that can be used as "dependencies" section and has all the "use: foo" commands expanded (but conditions are left untouched and variables are not substituted).
[ "Returns", "all", "dependencies", "of", "this", "assistant", "with", "regards", "to", "specified", "kwargs", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_assistant.py#L202-L228
devassistant/devassistant
devassistant/package_managers.py
PackageManager.get_perm_prompt
def get_perm_prompt(cls, package_list): """ Return text for prompt (do you want to install...), to install given packages. """ if cls == PackageManager: raise NotImplementedError() ln = len(package_list) plural = 's' if ln > 1 else '' return cls.permission_prompt.format(num=ln, plural=plural)
python
def get_perm_prompt(cls, package_list): """ Return text for prompt (do you want to install...), to install given packages. """ if cls == PackageManager: raise NotImplementedError() ln = len(package_list) plural = 's' if ln > 1 else '' return cls.permission_prompt.format(num=ln, plural=plural)
[ "def", "get_perm_prompt", "(", "cls", ",", "package_list", ")", ":", "if", "cls", "==", "PackageManager", ":", "raise", "NotImplementedError", "(", ")", "ln", "=", "len", "(", "package_list", ")", "plural", "=", "'s'", "if", "ln", ">", "1", "else", "''", "return", "cls", ".", "permission_prompt", ".", "format", "(", "num", "=", "ln", ",", "plural", "=", "plural", ")" ]
Return text for prompt (do you want to install...), to install given packages.
[ "Return", "text", "for", "prompt", "(", "do", "you", "want", "to", "install", "...", ")", "to", "install", "given", "packages", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/package_managers.py#L56-L64
devassistant/devassistant
devassistant/package_managers.py
GentooPackageManager._try_get_current_manager
def _try_get_current_manager(cls): """ Try to detect a package manager used in a current Gentoo system. """ if utils.get_distro_name().find('gentoo') == -1: return None if 'PACKAGE_MANAGER' in os.environ: pm = os.environ['PACKAGE_MANAGER'] if pm == 'paludis': # Try to import paludis module try: import paludis return GentooPackageManager.PALUDIS except ImportError: # TODO Environment tells that paludis must be used, but # it seems latter was build w/o USE=python... # Need to report an error!!?? cls._debug_doesnt_work('can\'t import paludis', name='PaludisPackageManager') return None elif pm == 'portage': # Fallback to default: portage pass else: # ATTENTION Some unknown package manager?! Which one? return None # Try to import portage module try: import portage return GentooPackageManager.PORTAGE except ImportError: cls._debug_doesnt_work('can\'t import portage', name='EmergePackageManager') return None
python
def _try_get_current_manager(cls): """ Try to detect a package manager used in a current Gentoo system. """ if utils.get_distro_name().find('gentoo') == -1: return None if 'PACKAGE_MANAGER' in os.environ: pm = os.environ['PACKAGE_MANAGER'] if pm == 'paludis': # Try to import paludis module try: import paludis return GentooPackageManager.PALUDIS except ImportError: # TODO Environment tells that paludis must be used, but # it seems latter was build w/o USE=python... # Need to report an error!!?? cls._debug_doesnt_work('can\'t import paludis', name='PaludisPackageManager') return None elif pm == 'portage': # Fallback to default: portage pass else: # ATTENTION Some unknown package manager?! Which one? return None # Try to import portage module try: import portage return GentooPackageManager.PORTAGE except ImportError: cls._debug_doesnt_work('can\'t import portage', name='EmergePackageManager') return None
[ "def", "_try_get_current_manager", "(", "cls", ")", ":", "if", "utils", ".", "get_distro_name", "(", ")", ".", "find", "(", "'gentoo'", ")", "==", "-", "1", ":", "return", "None", "if", "'PACKAGE_MANAGER'", "in", "os", ".", "environ", ":", "pm", "=", "os", ".", "environ", "[", "'PACKAGE_MANAGER'", "]", "if", "pm", "==", "'paludis'", ":", "# Try to import paludis module", "try", ":", "import", "paludis", "return", "GentooPackageManager", ".", "PALUDIS", "except", "ImportError", ":", "# TODO Environment tells that paludis must be used, but", "# it seems latter was build w/o USE=python...", "# Need to report an error!!??", "cls", ".", "_debug_doesnt_work", "(", "'can\\'t import paludis'", ",", "name", "=", "'PaludisPackageManager'", ")", "return", "None", "elif", "pm", "==", "'portage'", ":", "# Fallback to default: portage", "pass", "else", ":", "# ATTENTION Some unknown package manager?! Which one?", "return", "None", "# Try to import portage module", "try", ":", "import", "portage", "return", "GentooPackageManager", ".", "PORTAGE", "except", "ImportError", ":", "cls", ".", "_debug_doesnt_work", "(", "'can\\'t import portage'", ",", "name", "=", "'EmergePackageManager'", ")", "return", "None" ]
Try to detect a package manager used in a current Gentoo system.
[ "Try", "to", "detect", "a", "package", "manager", "used", "in", "a", "current", "Gentoo", "system", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/package_managers.py#L607-L637
devassistant/devassistant
devassistant/package_managers.py
GentooPackageManager.is_current_manager_equals_to
def is_current_manager_equals_to(cls, pm): """Returns True if this package manager is usable, False otherwise.""" if hasattr(cls, 'works_result'): return cls.works_result is_ok = bool(cls._try_get_current_manager() == pm) setattr(cls, 'works_result', is_ok) return is_ok
python
def is_current_manager_equals_to(cls, pm): """Returns True if this package manager is usable, False otherwise.""" if hasattr(cls, 'works_result'): return cls.works_result is_ok = bool(cls._try_get_current_manager() == pm) setattr(cls, 'works_result', is_ok) return is_ok
[ "def", "is_current_manager_equals_to", "(", "cls", ",", "pm", ")", ":", "if", "hasattr", "(", "cls", ",", "'works_result'", ")", ":", "return", "cls", ".", "works_result", "is_ok", "=", "bool", "(", "cls", ".", "_try_get_current_manager", "(", ")", "==", "pm", ")", "setattr", "(", "cls", ",", "'works_result'", ",", "is_ok", ")", "return", "is_ok" ]
Returns True if this package manager is usable, False otherwise.
[ "Returns", "True", "if", "this", "package", "manager", "is", "usable", "False", "otherwise", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/package_managers.py#L640-L646
devassistant/devassistant
devassistant/package_managers.py
DependencyInstaller.get_package_manager
def get_package_manager(self, dep_t): """Choose proper package manager and return it.""" mgrs = managers.get(dep_t, []) for manager in mgrs: if manager.works(): return manager if not mgrs: err = 'No package manager for dependency type "{dep_t}"'.format(dep_t=dep_t) raise exceptions.NoPackageManagerException(err) else: mgrs_nice = ', '.join([mgr.__name__ for mgr in mgrs]) err = 'No working package manager for "{dep_t}" in: {mgrs}'.format(dep_t=dep_t, mgrs=mgrs_nice) raise exceptions.NoPackageManagerOperationalException(err)
python
def get_package_manager(self, dep_t): """Choose proper package manager and return it.""" mgrs = managers.get(dep_t, []) for manager in mgrs: if manager.works(): return manager if not mgrs: err = 'No package manager for dependency type "{dep_t}"'.format(dep_t=dep_t) raise exceptions.NoPackageManagerException(err) else: mgrs_nice = ', '.join([mgr.__name__ for mgr in mgrs]) err = 'No working package manager for "{dep_t}" in: {mgrs}'.format(dep_t=dep_t, mgrs=mgrs_nice) raise exceptions.NoPackageManagerOperationalException(err)
[ "def", "get_package_manager", "(", "self", ",", "dep_t", ")", ":", "mgrs", "=", "managers", ".", "get", "(", "dep_t", ",", "[", "]", ")", "for", "manager", "in", "mgrs", ":", "if", "manager", ".", "works", "(", ")", ":", "return", "manager", "if", "not", "mgrs", ":", "err", "=", "'No package manager for dependency type \"{dep_t}\"'", ".", "format", "(", "dep_t", "=", "dep_t", ")", "raise", "exceptions", ".", "NoPackageManagerException", "(", "err", ")", "else", ":", "mgrs_nice", "=", "', '", ".", "join", "(", "[", "mgr", ".", "__name__", "for", "mgr", "in", "mgrs", "]", ")", "err", "=", "'No working package manager for \"{dep_t}\" in: {mgrs}'", ".", "format", "(", "dep_t", "=", "dep_t", ",", "mgrs", "=", "mgrs_nice", ")", "raise", "exceptions", ".", "NoPackageManagerOperationalException", "(", "err", ")" ]
Choose proper package manager and return it.
[ "Choose", "proper", "package", "manager", "and", "return", "it", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/package_managers.py#L836-L849
devassistant/devassistant
devassistant/package_managers.py
DependencyInstaller._process_dependency
def _process_dependency(self, dep_t, dep_l): """Add dependencies into self.dependencies, possibly also adding system packages that contain non-distro package managers (e.g. if someone wants to install dependencies with pip and pip is not present, it will get installed through RPM on RPM based systems, etc. Skips dependencies that are supposed to be installed by system manager that is not native to this system. """ if dep_t not in managers: err = 'No package manager for dependency type "{dep_t}"'.format(dep_t=dep_t) raise exceptions.NoPackageManagerException(err) # try to get list of distros where the dependency type is system type distros = settings.SYSTEM_DEPTYPES_SHORTCUTS.get(dep_t, None) if not distros: # non-distro dependency type sysdep_t = self.get_system_deptype_shortcut() # for now, just take the first manager that can install dep_t and install this manager self._process_dependency(sysdep_t, managers[dep_t][0].get_distro_dependencies(sysdep_t)) else: local_distro = utils.get_distro_name() found = False for distro in distros: if distro in local_distro: found = True break if not found: # distro dependency type, but for another distro return self.__add_dependencies(dep_t, dep_l)
python
def _process_dependency(self, dep_t, dep_l): """Add dependencies into self.dependencies, possibly also adding system packages that contain non-distro package managers (e.g. if someone wants to install dependencies with pip and pip is not present, it will get installed through RPM on RPM based systems, etc. Skips dependencies that are supposed to be installed by system manager that is not native to this system. """ if dep_t not in managers: err = 'No package manager for dependency type "{dep_t}"'.format(dep_t=dep_t) raise exceptions.NoPackageManagerException(err) # try to get list of distros where the dependency type is system type distros = settings.SYSTEM_DEPTYPES_SHORTCUTS.get(dep_t, None) if not distros: # non-distro dependency type sysdep_t = self.get_system_deptype_shortcut() # for now, just take the first manager that can install dep_t and install this manager self._process_dependency(sysdep_t, managers[dep_t][0].get_distro_dependencies(sysdep_t)) else: local_distro = utils.get_distro_name() found = False for distro in distros: if distro in local_distro: found = True break if not found: # distro dependency type, but for another distro return self.__add_dependencies(dep_t, dep_l)
[ "def", "_process_dependency", "(", "self", ",", "dep_t", ",", "dep_l", ")", ":", "if", "dep_t", "not", "in", "managers", ":", "err", "=", "'No package manager for dependency type \"{dep_t}\"'", ".", "format", "(", "dep_t", "=", "dep_t", ")", "raise", "exceptions", ".", "NoPackageManagerException", "(", "err", ")", "# try to get list of distros where the dependency type is system type", "distros", "=", "settings", ".", "SYSTEM_DEPTYPES_SHORTCUTS", ".", "get", "(", "dep_t", ",", "None", ")", "if", "not", "distros", ":", "# non-distro dependency type", "sysdep_t", "=", "self", ".", "get_system_deptype_shortcut", "(", ")", "# for now, just take the first manager that can install dep_t and install this manager", "self", ".", "_process_dependency", "(", "sysdep_t", ",", "managers", "[", "dep_t", "]", "[", "0", "]", ".", "get_distro_dependencies", "(", "sysdep_t", ")", ")", "else", ":", "local_distro", "=", "utils", ".", "get_distro_name", "(", ")", "found", "=", "False", "for", "distro", "in", "distros", ":", "if", "distro", "in", "local_distro", ":", "found", "=", "True", "break", "if", "not", "found", ":", "# distro dependency type, but for another distro", "return", "self", ".", "__add_dependencies", "(", "dep_t", ",", "dep_l", ")" ]
Add dependencies into self.dependencies, possibly also adding system packages that contain non-distro package managers (e.g. if someone wants to install dependencies with pip and pip is not present, it will get installed through RPM on RPM based systems, etc. Skips dependencies that are supposed to be installed by system manager that is not native to this system.
[ "Add", "dependencies", "into", "self", ".", "dependencies", "possibly", "also", "adding", "system", "packages", "that", "contain", "non", "-", "distro", "package", "managers", "(", "e", ".", "g", ".", "if", "someone", "wants", "to", "install", "dependencies", "with", "pip", "and", "pip", "is", "not", "present", "it", "will", "get", "installed", "through", "RPM", "on", "RPM", "based", "systems", "etc", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/package_managers.py#L851-L879
devassistant/devassistant
devassistant/package_managers.py
DependencyInstaller._ask_to_confirm
def _ask_to_confirm(self, ui, pac_man, *to_install): """ Return True if user wants to install packages, False otherwise """ ret = DialogHelper.ask_for_package_list_confirm( ui, prompt=pac_man.get_perm_prompt(to_install), package_list=to_install, ) return bool(ret)
python
def _ask_to_confirm(self, ui, pac_man, *to_install): """ Return True if user wants to install packages, False otherwise """ ret = DialogHelper.ask_for_package_list_confirm( ui, prompt=pac_man.get_perm_prompt(to_install), package_list=to_install, ) return bool(ret)
[ "def", "_ask_to_confirm", "(", "self", ",", "ui", ",", "pac_man", ",", "*", "to_install", ")", ":", "ret", "=", "DialogHelper", ".", "ask_for_package_list_confirm", "(", "ui", ",", "prompt", "=", "pac_man", ".", "get_perm_prompt", "(", "to_install", ")", ",", "package_list", "=", "to_install", ",", ")", "return", "bool", "(", "ret", ")" ]
Return True if user wants to install packages, False otherwise
[ "Return", "True", "if", "user", "wants", "to", "install", "packages", "False", "otherwise" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/package_managers.py#L881-L887
devassistant/devassistant
devassistant/package_managers.py
DependencyInstaller._install_dependencies
def _install_dependencies(self, ui, debug): """Install missing dependencies""" for dep_t, dep_l in self.dependencies: if not dep_l: continue pkg_mgr = self.get_package_manager(dep_t) pkg_mgr.works() to_resolve = [] for dep in dep_l: if not pkg_mgr.is_pkg_installed(dep): to_resolve.append(dep) if not to_resolve: # nothing to install, let's move on continue to_install = pkg_mgr.resolve(*to_resolve) confirm = self._ask_to_confirm(ui, pkg_mgr, *to_install) if not confirm: msg = 'List of packages denied by user, exiting.' raise exceptions.DependencyException(msg) type(self).install_lock = True # TODO: we should do this more systematically (send signal to cl/gui?) logger.info('Installing dependencies, sit back and relax ...', extra={'event_type': 'dep_installation_start'}) if ui == 'cli' and not debug: # TODO: maybe let every manager to decide when to start event = threading.Event() t = EndlessProgressThread(event) t.start() installed = pkg_mgr.install(*to_install) if ui == 'cli' and not debug: event.set() t.join() if installed: logger.info(' Done.') else: logger.error(' Failed.') type(self).install_lock = False log_extra = {'event_type': 'dep_installation_end'} if not installed: msg = 'Failed to install dependencies, exiting.' logger.error(msg, extra=log_extra) raise exceptions.DependencyException(msg) else: logger.info('Successfully installed dependencies!', extra=log_extra)
python
def _install_dependencies(self, ui, debug): """Install missing dependencies""" for dep_t, dep_l in self.dependencies: if not dep_l: continue pkg_mgr = self.get_package_manager(dep_t) pkg_mgr.works() to_resolve = [] for dep in dep_l: if not pkg_mgr.is_pkg_installed(dep): to_resolve.append(dep) if not to_resolve: # nothing to install, let's move on continue to_install = pkg_mgr.resolve(*to_resolve) confirm = self._ask_to_confirm(ui, pkg_mgr, *to_install) if not confirm: msg = 'List of packages denied by user, exiting.' raise exceptions.DependencyException(msg) type(self).install_lock = True # TODO: we should do this more systematically (send signal to cl/gui?) logger.info('Installing dependencies, sit back and relax ...', extra={'event_type': 'dep_installation_start'}) if ui == 'cli' and not debug: # TODO: maybe let every manager to decide when to start event = threading.Event() t = EndlessProgressThread(event) t.start() installed = pkg_mgr.install(*to_install) if ui == 'cli' and not debug: event.set() t.join() if installed: logger.info(' Done.') else: logger.error(' Failed.') type(self).install_lock = False log_extra = {'event_type': 'dep_installation_end'} if not installed: msg = 'Failed to install dependencies, exiting.' logger.error(msg, extra=log_extra) raise exceptions.DependencyException(msg) else: logger.info('Successfully installed dependencies!', extra=log_extra)
[ "def", "_install_dependencies", "(", "self", ",", "ui", ",", "debug", ")", ":", "for", "dep_t", ",", "dep_l", "in", "self", ".", "dependencies", ":", "if", "not", "dep_l", ":", "continue", "pkg_mgr", "=", "self", ".", "get_package_manager", "(", "dep_t", ")", "pkg_mgr", ".", "works", "(", ")", "to_resolve", "=", "[", "]", "for", "dep", "in", "dep_l", ":", "if", "not", "pkg_mgr", ".", "is_pkg_installed", "(", "dep", ")", ":", "to_resolve", ".", "append", "(", "dep", ")", "if", "not", "to_resolve", ":", "# nothing to install, let's move on", "continue", "to_install", "=", "pkg_mgr", ".", "resolve", "(", "*", "to_resolve", ")", "confirm", "=", "self", ".", "_ask_to_confirm", "(", "ui", ",", "pkg_mgr", ",", "*", "to_install", ")", "if", "not", "confirm", ":", "msg", "=", "'List of packages denied by user, exiting.'", "raise", "exceptions", ".", "DependencyException", "(", "msg", ")", "type", "(", "self", ")", ".", "install_lock", "=", "True", "# TODO: we should do this more systematically (send signal to cl/gui?)", "logger", ".", "info", "(", "'Installing dependencies, sit back and relax ...'", ",", "extra", "=", "{", "'event_type'", ":", "'dep_installation_start'", "}", ")", "if", "ui", "==", "'cli'", "and", "not", "debug", ":", "# TODO: maybe let every manager to decide when to start", "event", "=", "threading", ".", "Event", "(", ")", "t", "=", "EndlessProgressThread", "(", "event", ")", "t", ".", "start", "(", ")", "installed", "=", "pkg_mgr", ".", "install", "(", "*", "to_install", ")", "if", "ui", "==", "'cli'", "and", "not", "debug", ":", "event", ".", "set", "(", ")", "t", ".", "join", "(", ")", "if", "installed", ":", "logger", ".", "info", "(", "' Done.'", ")", "else", ":", "logger", ".", "error", "(", "' Failed.'", ")", "type", "(", "self", ")", ".", "install_lock", "=", "False", "log_extra", "=", "{", "'event_type'", ":", "'dep_installation_end'", "}", "if", "not", "installed", ":", "msg", "=", "'Failed to install dependencies, exiting.'", "logger", ".", "error", "(", "msg", ",", "extra", "=", "log_extra", ")", "raise", "exceptions", ".", "DependencyException", "(", "msg", ")", "else", ":", "logger", ".", "info", "(", "'Successfully installed dependencies!'", ",", "extra", "=", "log_extra", ")" ]
Install missing dependencies
[ "Install", "missing", "dependencies" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/package_managers.py#L889-L933
devassistant/devassistant
devassistant/package_managers.py
DependencyInstaller.install
def install(self, struct, ui, debug=False): """ This is the only method that should be called from outside. Call it like: `DependencyInstaller(struct)` and it will install packages which are not present on system (it uses package managers specified by `struct` structure) """ # the system dependencies should always go first self.__add_dependencies(self.get_system_deptype_shortcut(), []) for dep_dict in struct: for dep_t, dep_l in dep_dict.items(): self._process_dependency(dep_t, dep_l) if self.dependencies: self._install_dependencies(ui, debug)
python
def install(self, struct, ui, debug=False): """ This is the only method that should be called from outside. Call it like: `DependencyInstaller(struct)` and it will install packages which are not present on system (it uses package managers specified by `struct` structure) """ # the system dependencies should always go first self.__add_dependencies(self.get_system_deptype_shortcut(), []) for dep_dict in struct: for dep_t, dep_l in dep_dict.items(): self._process_dependency(dep_t, dep_l) if self.dependencies: self._install_dependencies(ui, debug)
[ "def", "install", "(", "self", ",", "struct", ",", "ui", ",", "debug", "=", "False", ")", ":", "# the system dependencies should always go first", "self", ".", "__add_dependencies", "(", "self", ".", "get_system_deptype_shortcut", "(", ")", ",", "[", "]", ")", "for", "dep_dict", "in", "struct", ":", "for", "dep_t", ",", "dep_l", "in", "dep_dict", ".", "items", "(", ")", ":", "self", ".", "_process_dependency", "(", "dep_t", ",", "dep_l", ")", "if", "self", ".", "dependencies", ":", "self", ".", "_install_dependencies", "(", "ui", ",", "debug", ")" ]
This is the only method that should be called from outside. Call it like: `DependencyInstaller(struct)` and it will install packages which are not present on system (it uses package managers specified by `struct` structure)
[ "This", "is", "the", "only", "method", "that", "should", "be", "called", "from", "outside", ".", "Call", "it", "like", ":", "DependencyInstaller", "(", "struct", ")", "and", "it", "will", "install", "packages", "which", "are", "not", "present", "on", "system", "(", "it", "uses", "package", "managers", "specified", "by", "struct", "structure", ")" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/package_managers.py#L935-L949
devassistant/devassistant
devassistant/cache.py
Cache.refresh_role
def refresh_role(self, role, file_hierarchy): """Checks and refreshes (if needed) all assistants with given role. Args: role: role of assistants to refresh file_hierarchy: hierarchy as returned by devassistant.yaml_assistant_loader.\ YamlAssistantLoader.get_assistants_file_hierarchy """ if role not in self.cache: self.cache[role] = {} was_change = self._refresh_hierarchy_recursive(self.cache[role], file_hierarchy) if was_change: cf = open(self.cache_file, 'w') yaml.dump(self.cache, cf, Dumper=Dumper) cf.close()
python
def refresh_role(self, role, file_hierarchy): """Checks and refreshes (if needed) all assistants with given role. Args: role: role of assistants to refresh file_hierarchy: hierarchy as returned by devassistant.yaml_assistant_loader.\ YamlAssistantLoader.get_assistants_file_hierarchy """ if role not in self.cache: self.cache[role] = {} was_change = self._refresh_hierarchy_recursive(self.cache[role], file_hierarchy) if was_change: cf = open(self.cache_file, 'w') yaml.dump(self.cache, cf, Dumper=Dumper) cf.close()
[ "def", "refresh_role", "(", "self", ",", "role", ",", "file_hierarchy", ")", ":", "if", "role", "not", "in", "self", ".", "cache", ":", "self", ".", "cache", "[", "role", "]", "=", "{", "}", "was_change", "=", "self", ".", "_refresh_hierarchy_recursive", "(", "self", ".", "cache", "[", "role", "]", ",", "file_hierarchy", ")", "if", "was_change", ":", "cf", "=", "open", "(", "self", ".", "cache_file", ",", "'w'", ")", "yaml", ".", "dump", "(", "self", ".", "cache", ",", "cf", ",", "Dumper", "=", "Dumper", ")", "cf", ".", "close", "(", ")" ]
Checks and refreshes (if needed) all assistants with given role. Args: role: role of assistants to refresh file_hierarchy: hierarchy as returned by devassistant.yaml_assistant_loader.\ YamlAssistantLoader.get_assistants_file_hierarchy
[ "Checks", "and", "refreshes", "(", "if", "needed", ")", "all", "assistants", "with", "given", "role", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cache.py#L78-L92
devassistant/devassistant
devassistant/cache.py
Cache._refresh_hierarchy_recursive
def _refresh_hierarchy_recursive(self, cached_hierarchy, file_hierarchy): """Recursively goes through given corresponding hierarchies from cache and filesystem and adds/refreshes/removes added/changed/removed assistants. Args: cached_hierarchy: the respective hierarchy part from current cache (for format see Cache class docstring) file_hierarchy: the respective hierarchy part from filesystem (for format see what refresh_role accepts) Returns: True if self.cache has been changed, False otherwise (doesn't write anything to cache file) """ was_change = False cached_ass = set(cached_hierarchy.keys()) new_ass = set(file_hierarchy.keys()) to_add = new_ass - cached_ass to_remove = cached_ass - new_ass to_check = cached_ass - to_remove if to_add or to_remove: was_change = True for ass in to_add: cached_hierarchy[ass] = self._new_ass_hierarchy(file_hierarchy[ass]) for ass in to_remove: del cached_hierarchy[ass] for ass in to_check: needs_refresh = False try: needs_refresh = self._ass_needs_refresh(cached_hierarchy[ass], file_hierarchy[ass]) except: needs_refresh = True if needs_refresh: self._ass_refresh_attrs(cached_hierarchy[ass], file_hierarchy[ass]) was_change = True was_change |= self._refresh_hierarchy_recursive( cached_hierarchy[ass]['subhierarchy'], file_hierarchy[ass]['subhierarchy']) return was_change
python
def _refresh_hierarchy_recursive(self, cached_hierarchy, file_hierarchy): """Recursively goes through given corresponding hierarchies from cache and filesystem and adds/refreshes/removes added/changed/removed assistants. Args: cached_hierarchy: the respective hierarchy part from current cache (for format see Cache class docstring) file_hierarchy: the respective hierarchy part from filesystem (for format see what refresh_role accepts) Returns: True if self.cache has been changed, False otherwise (doesn't write anything to cache file) """ was_change = False cached_ass = set(cached_hierarchy.keys()) new_ass = set(file_hierarchy.keys()) to_add = new_ass - cached_ass to_remove = cached_ass - new_ass to_check = cached_ass - to_remove if to_add or to_remove: was_change = True for ass in to_add: cached_hierarchy[ass] = self._new_ass_hierarchy(file_hierarchy[ass]) for ass in to_remove: del cached_hierarchy[ass] for ass in to_check: needs_refresh = False try: needs_refresh = self._ass_needs_refresh(cached_hierarchy[ass], file_hierarchy[ass]) except: needs_refresh = True if needs_refresh: self._ass_refresh_attrs(cached_hierarchy[ass], file_hierarchy[ass]) was_change = True was_change |= self._refresh_hierarchy_recursive( cached_hierarchy[ass]['subhierarchy'], file_hierarchy[ass]['subhierarchy']) return was_change
[ "def", "_refresh_hierarchy_recursive", "(", "self", ",", "cached_hierarchy", ",", "file_hierarchy", ")", ":", "was_change", "=", "False", "cached_ass", "=", "set", "(", "cached_hierarchy", ".", "keys", "(", ")", ")", "new_ass", "=", "set", "(", "file_hierarchy", ".", "keys", "(", ")", ")", "to_add", "=", "new_ass", "-", "cached_ass", "to_remove", "=", "cached_ass", "-", "new_ass", "to_check", "=", "cached_ass", "-", "to_remove", "if", "to_add", "or", "to_remove", ":", "was_change", "=", "True", "for", "ass", "in", "to_add", ":", "cached_hierarchy", "[", "ass", "]", "=", "self", ".", "_new_ass_hierarchy", "(", "file_hierarchy", "[", "ass", "]", ")", "for", "ass", "in", "to_remove", ":", "del", "cached_hierarchy", "[", "ass", "]", "for", "ass", "in", "to_check", ":", "needs_refresh", "=", "False", "try", ":", "needs_refresh", "=", "self", ".", "_ass_needs_refresh", "(", "cached_hierarchy", "[", "ass", "]", ",", "file_hierarchy", "[", "ass", "]", ")", "except", ":", "needs_refresh", "=", "True", "if", "needs_refresh", ":", "self", ".", "_ass_refresh_attrs", "(", "cached_hierarchy", "[", "ass", "]", ",", "file_hierarchy", "[", "ass", "]", ")", "was_change", "=", "True", "was_change", "|=", "self", ".", "_refresh_hierarchy_recursive", "(", "cached_hierarchy", "[", "ass", "]", "[", "'subhierarchy'", "]", ",", "file_hierarchy", "[", "ass", "]", "[", "'subhierarchy'", "]", ")", "return", "was_change" ]
Recursively goes through given corresponding hierarchies from cache and filesystem and adds/refreshes/removes added/changed/removed assistants. Args: cached_hierarchy: the respective hierarchy part from current cache (for format see Cache class docstring) file_hierarchy: the respective hierarchy part from filesystem (for format see what refresh_role accepts) Returns: True if self.cache has been changed, False otherwise (doesn't write anything to cache file)
[ "Recursively", "goes", "through", "given", "corresponding", "hierarchies", "from", "cache", "and", "filesystem", "and", "adds", "/", "refreshes", "/", "removes", "added", "/", "changed", "/", "removed", "assistants", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cache.py#L94-L139
devassistant/devassistant
devassistant/cache.py
Cache._ass_needs_refresh
def _ass_needs_refresh(self, cached_ass, file_ass): """Checks if assistant needs refresh. Assistant needs refresh iff any of following conditions is True: - stored source file is different than given source file - stored assistant ctime is lower than current source file ctime - stored list of subassistants is different than given list of subassistants - stored ctime of any of the snippets that this assistant uses to compose args is lower than current ctime of that snippet Args: cached_ass: an assistant from cache hierarchy (for format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy (for format see what refresh_role accepts) """ if cached_ass['source'] != file_ass['source']: return True if os.path.getctime(file_ass['source']) > cached_ass.get('ctime', 0.0): return True if set(cached_ass['subhierarchy'].keys()) != set(set(file_ass['subhierarchy'].keys())): return True for snip_name, snip_ctime in cached_ass['snippets'].items(): if self._get_snippet_ctime(snip_name) > snip_ctime: return True return False
python
def _ass_needs_refresh(self, cached_ass, file_ass): """Checks if assistant needs refresh. Assistant needs refresh iff any of following conditions is True: - stored source file is different than given source file - stored assistant ctime is lower than current source file ctime - stored list of subassistants is different than given list of subassistants - stored ctime of any of the snippets that this assistant uses to compose args is lower than current ctime of that snippet Args: cached_ass: an assistant from cache hierarchy (for format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy (for format see what refresh_role accepts) """ if cached_ass['source'] != file_ass['source']: return True if os.path.getctime(file_ass['source']) > cached_ass.get('ctime', 0.0): return True if set(cached_ass['subhierarchy'].keys()) != set(set(file_ass['subhierarchy'].keys())): return True for snip_name, snip_ctime in cached_ass['snippets'].items(): if self._get_snippet_ctime(snip_name) > snip_ctime: return True return False
[ "def", "_ass_needs_refresh", "(", "self", ",", "cached_ass", ",", "file_ass", ")", ":", "if", "cached_ass", "[", "'source'", "]", "!=", "file_ass", "[", "'source'", "]", ":", "return", "True", "if", "os", ".", "path", ".", "getctime", "(", "file_ass", "[", "'source'", "]", ")", ">", "cached_ass", ".", "get", "(", "'ctime'", ",", "0.0", ")", ":", "return", "True", "if", "set", "(", "cached_ass", "[", "'subhierarchy'", "]", ".", "keys", "(", ")", ")", "!=", "set", "(", "set", "(", "file_ass", "[", "'subhierarchy'", "]", ".", "keys", "(", ")", ")", ")", ":", "return", "True", "for", "snip_name", ",", "snip_ctime", "in", "cached_ass", "[", "'snippets'", "]", ".", "items", "(", ")", ":", "if", "self", ".", "_get_snippet_ctime", "(", "snip_name", ")", ">", "snip_ctime", ":", "return", "True", "return", "False" ]
Checks if assistant needs refresh. Assistant needs refresh iff any of following conditions is True: - stored source file is different than given source file - stored assistant ctime is lower than current source file ctime - stored list of subassistants is different than given list of subassistants - stored ctime of any of the snippets that this assistant uses to compose args is lower than current ctime of that snippet Args: cached_ass: an assistant from cache hierarchy (for format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy (for format see what refresh_role accepts)
[ "Checks", "if", "assistant", "needs", "refresh", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cache.py#L141-L167
devassistant/devassistant
devassistant/cache.py
Cache._ass_refresh_attrs
def _ass_refresh_attrs(self, cached_ass, file_ass): """Completely refreshes cached assistant from file. Args: cached_ass: an assistant from cache hierarchy (for format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy (for format see what refresh_role accepts) """ # we need to process assistant in custom way to see unexpanded args, etc. loaded_ass = yaml_loader.YamlLoader.load_yaml_by_path(file_ass['source'], log_debug=True) attrs = loaded_ass yaml_checker.check(file_ass['source'], attrs) cached_ass['source'] = file_ass['source'] cached_ass['ctime'] = os.path.getctime(file_ass['source']) cached_ass['attrs'] = {} cached_ass['snippets'] = {} # only cache these attributes if they're actually found in assistant # we do this to specify the default values for them just in one place # which is currently YamlAssistant.parsed_yaml property setter for a in ['fullname', 'description', 'icon_path']: if a in attrs: cached_ass['attrs'][a] = attrs.get(a) # args have different processing, we can't just take them from assistant if 'args' in attrs: cached_ass['attrs']['args'] = {} for argname, argparams in attrs.get('args', {}).items(): if 'use' in argparams or 'snippet' in argparams: snippet_name = argparams.pop('use', None) or argparams.pop('snippet') snippet = yaml_snippet_loader.YamlSnippetLoader.get_snippet_by_name(snippet_name) cached_ass['attrs']['args'][argname] = snippet.get_arg_by_name(argname) cached_ass['attrs']['args'][argname].update(argparams) cached_ass['snippets'][snippet.name] = self._get_snippet_ctime(snippet.name) else: cached_ass['attrs']['args'][argname] = argparams
python
def _ass_refresh_attrs(self, cached_ass, file_ass): """Completely refreshes cached assistant from file. Args: cached_ass: an assistant from cache hierarchy (for format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy (for format see what refresh_role accepts) """ # we need to process assistant in custom way to see unexpanded args, etc. loaded_ass = yaml_loader.YamlLoader.load_yaml_by_path(file_ass['source'], log_debug=True) attrs = loaded_ass yaml_checker.check(file_ass['source'], attrs) cached_ass['source'] = file_ass['source'] cached_ass['ctime'] = os.path.getctime(file_ass['source']) cached_ass['attrs'] = {} cached_ass['snippets'] = {} # only cache these attributes if they're actually found in assistant # we do this to specify the default values for them just in one place # which is currently YamlAssistant.parsed_yaml property setter for a in ['fullname', 'description', 'icon_path']: if a in attrs: cached_ass['attrs'][a] = attrs.get(a) # args have different processing, we can't just take them from assistant if 'args' in attrs: cached_ass['attrs']['args'] = {} for argname, argparams in attrs.get('args', {}).items(): if 'use' in argparams or 'snippet' in argparams: snippet_name = argparams.pop('use', None) or argparams.pop('snippet') snippet = yaml_snippet_loader.YamlSnippetLoader.get_snippet_by_name(snippet_name) cached_ass['attrs']['args'][argname] = snippet.get_arg_by_name(argname) cached_ass['attrs']['args'][argname].update(argparams) cached_ass['snippets'][snippet.name] = self._get_snippet_ctime(snippet.name) else: cached_ass['attrs']['args'][argname] = argparams
[ "def", "_ass_refresh_attrs", "(", "self", ",", "cached_ass", ",", "file_ass", ")", ":", "# we need to process assistant in custom way to see unexpanded args, etc.", "loaded_ass", "=", "yaml_loader", ".", "YamlLoader", ".", "load_yaml_by_path", "(", "file_ass", "[", "'source'", "]", ",", "log_debug", "=", "True", ")", "attrs", "=", "loaded_ass", "yaml_checker", ".", "check", "(", "file_ass", "[", "'source'", "]", ",", "attrs", ")", "cached_ass", "[", "'source'", "]", "=", "file_ass", "[", "'source'", "]", "cached_ass", "[", "'ctime'", "]", "=", "os", ".", "path", ".", "getctime", "(", "file_ass", "[", "'source'", "]", ")", "cached_ass", "[", "'attrs'", "]", "=", "{", "}", "cached_ass", "[", "'snippets'", "]", "=", "{", "}", "# only cache these attributes if they're actually found in assistant", "# we do this to specify the default values for them just in one place", "# which is currently YamlAssistant.parsed_yaml property setter", "for", "a", "in", "[", "'fullname'", ",", "'description'", ",", "'icon_path'", "]", ":", "if", "a", "in", "attrs", ":", "cached_ass", "[", "'attrs'", "]", "[", "a", "]", "=", "attrs", ".", "get", "(", "a", ")", "# args have different processing, we can't just take them from assistant", "if", "'args'", "in", "attrs", ":", "cached_ass", "[", "'attrs'", "]", "[", "'args'", "]", "=", "{", "}", "for", "argname", ",", "argparams", "in", "attrs", ".", "get", "(", "'args'", ",", "{", "}", ")", ".", "items", "(", ")", ":", "if", "'use'", "in", "argparams", "or", "'snippet'", "in", "argparams", ":", "snippet_name", "=", "argparams", ".", "pop", "(", "'use'", ",", "None", ")", "or", "argparams", ".", "pop", "(", "'snippet'", ")", "snippet", "=", "yaml_snippet_loader", ".", "YamlSnippetLoader", ".", "get_snippet_by_name", "(", "snippet_name", ")", "cached_ass", "[", "'attrs'", "]", "[", "'args'", "]", "[", "argname", "]", "=", "snippet", ".", "get_arg_by_name", "(", "argname", ")", "cached_ass", "[", "'attrs'", "]", "[", "'args'", "]", "[", "argname", "]", ".", "update", "(", "argparams", ")", "cached_ass", "[", "'snippets'", "]", "[", "snippet", ".", "name", "]", "=", "self", ".", "_get_snippet_ctime", "(", "snippet", ".", "name", ")", "else", ":", "cached_ass", "[", "'attrs'", "]", "[", "'args'", "]", "[", "argname", "]", "=", "argparams" ]
Completely refreshes cached assistant from file. Args: cached_ass: an assistant from cache hierarchy (for format see Cache class docstring) file_ass: the respective assistant from filesystem hierarchy (for format see what refresh_role accepts)
[ "Completely", "refreshes", "cached", "assistant", "from", "file", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cache.py#L169-L203
devassistant/devassistant
devassistant/cache.py
Cache._new_ass_hierarchy
def _new_ass_hierarchy(self, file_ass): """Returns a completely new cache hierarchy for given assistant file. Args: file_ass: the assistant from filesystem hierarchy to create cache hierarchy for (for format see what refresh_role accepts) Returns: the newly created cache hierarchy """ ret_struct = {'source': '', 'subhierarchy': {}, 'attrs': {}, 'snippets': {}} ret_struct['source'] = file_ass['source'] self._ass_refresh_attrs(ret_struct, file_ass) for name, subhierarchy in file_ass['subhierarchy'].items(): ret_struct['subhierarchy'][name] = self._new_ass_hierarchy(subhierarchy) return ret_struct
python
def _new_ass_hierarchy(self, file_ass): """Returns a completely new cache hierarchy for given assistant file. Args: file_ass: the assistant from filesystem hierarchy to create cache hierarchy for (for format see what refresh_role accepts) Returns: the newly created cache hierarchy """ ret_struct = {'source': '', 'subhierarchy': {}, 'attrs': {}, 'snippets': {}} ret_struct['source'] = file_ass['source'] self._ass_refresh_attrs(ret_struct, file_ass) for name, subhierarchy in file_ass['subhierarchy'].items(): ret_struct['subhierarchy'][name] = self._new_ass_hierarchy(subhierarchy) return ret_struct
[ "def", "_new_ass_hierarchy", "(", "self", ",", "file_ass", ")", ":", "ret_struct", "=", "{", "'source'", ":", "''", ",", "'subhierarchy'", ":", "{", "}", ",", "'attrs'", ":", "{", "}", ",", "'snippets'", ":", "{", "}", "}", "ret_struct", "[", "'source'", "]", "=", "file_ass", "[", "'source'", "]", "self", ".", "_ass_refresh_attrs", "(", "ret_struct", ",", "file_ass", ")", "for", "name", ",", "subhierarchy", "in", "file_ass", "[", "'subhierarchy'", "]", ".", "items", "(", ")", ":", "ret_struct", "[", "'subhierarchy'", "]", "[", "name", "]", "=", "self", ".", "_new_ass_hierarchy", "(", "subhierarchy", ")", "return", "ret_struct" ]
Returns a completely new cache hierarchy for given assistant file. Args: file_ass: the assistant from filesystem hierarchy to create cache hierarchy for (for format see what refresh_role accepts) Returns: the newly created cache hierarchy
[ "Returns", "a", "completely", "new", "cache", "hierarchy", "for", "given", "assistant", "file", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cache.py#L205-L224
devassistant/devassistant
devassistant/cache.py
Cache._get_snippet_ctime
def _get_snippet_ctime(self, snip_name): """Returns and remembers (during this DevAssistant invocation) last ctime of given snippet. Calling ctime costs lost of time and some snippets, like common_args, are used widely, so we don't want to call ctime bazillion times on them during one invocation. Args: snip_name: name of snippet to get ctime for Returns: ctime of the snippet """ if snip_name not in self.snip_ctimes: snippet = yaml_snippet_loader.YamlSnippetLoader.get_snippet_by_name(snip_name) self.snip_ctimes[snip_name] = os.path.getctime(snippet.path) return self.snip_ctimes[snip_name]
python
def _get_snippet_ctime(self, snip_name): """Returns and remembers (during this DevAssistant invocation) last ctime of given snippet. Calling ctime costs lost of time and some snippets, like common_args, are used widely, so we don't want to call ctime bazillion times on them during one invocation. Args: snip_name: name of snippet to get ctime for Returns: ctime of the snippet """ if snip_name not in self.snip_ctimes: snippet = yaml_snippet_loader.YamlSnippetLoader.get_snippet_by_name(snip_name) self.snip_ctimes[snip_name] = os.path.getctime(snippet.path) return self.snip_ctimes[snip_name]
[ "def", "_get_snippet_ctime", "(", "self", ",", "snip_name", ")", ":", "if", "snip_name", "not", "in", "self", ".", "snip_ctimes", ":", "snippet", "=", "yaml_snippet_loader", ".", "YamlSnippetLoader", ".", "get_snippet_by_name", "(", "snip_name", ")", "self", ".", "snip_ctimes", "[", "snip_name", "]", "=", "os", ".", "path", ".", "getctime", "(", "snippet", ".", "path", ")", "return", "self", ".", "snip_ctimes", "[", "snip_name", "]" ]
Returns and remembers (during this DevAssistant invocation) last ctime of given snippet. Calling ctime costs lost of time and some snippets, like common_args, are used widely, so we don't want to call ctime bazillion times on them during one invocation. Args: snip_name: name of snippet to get ctime for Returns: ctime of the snippet
[ "Returns", "and", "remembers", "(", "during", "this", "DevAssistant", "invocation", ")", "last", "ctime", "of", "given", "snippet", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cache.py#L226-L241
devassistant/devassistant
devassistant/lang.py
expand_dependencies_section
def expand_dependencies_section(section, kwargs): """Expands dependency section, e.g. substitues "use: foo" for its contents, but doesn't evaluate conditions nor substitue variables.""" deps = [] for dep in section: for dep_type, dep_list in dep.items(): if dep_type in ['call', 'use']: deps.extend(Command(dep_type, dep_list, kwargs).run()) elif dep_type.startswith('if ') or dep_type == 'else': deps.append({dep_type: expand_dependencies_section(dep_list, kwargs)}) else: deps.append({dep_type: dep_list}) return deps
python
def expand_dependencies_section(section, kwargs): """Expands dependency section, e.g. substitues "use: foo" for its contents, but doesn't evaluate conditions nor substitue variables.""" deps = [] for dep in section: for dep_type, dep_list in dep.items(): if dep_type in ['call', 'use']: deps.extend(Command(dep_type, dep_list, kwargs).run()) elif dep_type.startswith('if ') or dep_type == 'else': deps.append({dep_type: expand_dependencies_section(dep_list, kwargs)}) else: deps.append({dep_type: dep_list}) return deps
[ "def", "expand_dependencies_section", "(", "section", ",", "kwargs", ")", ":", "deps", "=", "[", "]", "for", "dep", "in", "section", ":", "for", "dep_type", ",", "dep_list", "in", "dep", ".", "items", "(", ")", ":", "if", "dep_type", "in", "[", "'call'", ",", "'use'", "]", ":", "deps", ".", "extend", "(", "Command", "(", "dep_type", ",", "dep_list", ",", "kwargs", ")", ".", "run", "(", ")", ")", "elif", "dep_type", ".", "startswith", "(", "'if '", ")", "or", "dep_type", "==", "'else'", ":", "deps", ".", "append", "(", "{", "dep_type", ":", "expand_dependencies_section", "(", "dep_list", ",", "kwargs", ")", "}", ")", "else", ":", "deps", ".", "append", "(", "{", "dep_type", ":", "dep_list", "}", ")", "return", "deps" ]
Expands dependency section, e.g. substitues "use: foo" for its contents, but doesn't evaluate conditions nor substitue variables.
[ "Expands", "dependency", "section", "e", ".", "g", ".", "substitues", "use", ":", "foo", "for", "its", "contents", "but", "doesn", "t", "evaluate", "conditions", "nor", "substitue", "variables", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L125-L139
devassistant/devassistant
devassistant/lang.py
parse_for
def parse_for(control_line): """Returns name of loop control variable(s), iteration type (in/word_in) and expression to iterate on. For example: - given "for $i in $foo", returns (['i'], '$foo') - given "for ${i} in $(ls $foo)", returns (['i'], '$(ls $foo)') - given "for $k, $v in $foo", returns (['k', 'v'], '$foo') """ error = 'For loop call must be in form \'for $var in expression\', got: ' + control_line regex = re.compile(r'for\s+(\${?\S+}?)(?:\s*,\s+(\${?\S+}?))?\s+(in|word_in)\s+(\S.+)') res = regex.match(control_line) if not res: raise exceptions.YamlSyntaxError(error) groups = res.groups() control_vars = [] control_vars.append(get_var_name(groups[0])) if groups[1]: control_vars.append(get_var_name(groups[1])) iter_type = groups[2] expr = groups[3] return (control_vars, iter_type, expr)
python
def parse_for(control_line): """Returns name of loop control variable(s), iteration type (in/word_in) and expression to iterate on. For example: - given "for $i in $foo", returns (['i'], '$foo') - given "for ${i} in $(ls $foo)", returns (['i'], '$(ls $foo)') - given "for $k, $v in $foo", returns (['k', 'v'], '$foo') """ error = 'For loop call must be in form \'for $var in expression\', got: ' + control_line regex = re.compile(r'for\s+(\${?\S+}?)(?:\s*,\s+(\${?\S+}?))?\s+(in|word_in)\s+(\S.+)') res = regex.match(control_line) if not res: raise exceptions.YamlSyntaxError(error) groups = res.groups() control_vars = [] control_vars.append(get_var_name(groups[0])) if groups[1]: control_vars.append(get_var_name(groups[1])) iter_type = groups[2] expr = groups[3] return (control_vars, iter_type, expr)
[ "def", "parse_for", "(", "control_line", ")", ":", "error", "=", "'For loop call must be in form \\'for $var in expression\\', got: '", "+", "control_line", "regex", "=", "re", ".", "compile", "(", "r'for\\s+(\\${?\\S+}?)(?:\\s*,\\s+(\\${?\\S+}?))?\\s+(in|word_in)\\s+(\\S.+)'", ")", "res", "=", "regex", ".", "match", "(", "control_line", ")", "if", "not", "res", ":", "raise", "exceptions", ".", "YamlSyntaxError", "(", "error", ")", "groups", "=", "res", ".", "groups", "(", ")", "control_vars", "=", "[", "]", "control_vars", ".", "append", "(", "get_var_name", "(", "groups", "[", "0", "]", ")", ")", "if", "groups", "[", "1", "]", ":", "control_vars", ".", "append", "(", "get_var_name", "(", "groups", "[", "1", "]", ")", ")", "iter_type", "=", "groups", "[", "2", "]", "expr", "=", "groups", "[", "3", "]", "return", "(", "control_vars", ",", "iter_type", ",", "expr", ")" ]
Returns name of loop control variable(s), iteration type (in/word_in) and expression to iterate on. For example: - given "for $i in $foo", returns (['i'], '$foo') - given "for ${i} in $(ls $foo)", returns (['i'], '$(ls $foo)') - given "for $k, $v in $foo", returns (['k', 'v'], '$foo')
[ "Returns", "name", "of", "loop", "control", "variable", "(", "s", ")", "iteration", "type", "(", "in", "/", "word_in", ")", "and", "expression", "to", "iterate", "on", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L260-L283
devassistant/devassistant
devassistant/lang.py
get_for_control_var_and_eval_expr
def get_for_control_var_and_eval_expr(comm_type, kwargs): """Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $foo' it returns (['i', 'j'], [('foo', 'bar')]) """ # let possible exceptions bubble up control_vars, iter_type, expression = parse_for(comm_type) eval_expression = evaluate_expression(expression, kwargs)[1] iterval = [] if len(control_vars) == 2: if not isinstance(eval_expression, dict): raise exceptions.YamlSyntaxError('Can\'t expand {t} to two control variables.'. format(t=type(eval_expression))) else: iterval = list(eval_expression.items()) elif isinstance(eval_expression, six.string_types): if iter_type == 'word_in': iterval = eval_expression.split() else: iterval = eval_expression else: iterval = eval_expression return control_vars, iterval
python
def get_for_control_var_and_eval_expr(comm_type, kwargs): """Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $foo' it returns (['i', 'j'], [('foo', 'bar')]) """ # let possible exceptions bubble up control_vars, iter_type, expression = parse_for(comm_type) eval_expression = evaluate_expression(expression, kwargs)[1] iterval = [] if len(control_vars) == 2: if not isinstance(eval_expression, dict): raise exceptions.YamlSyntaxError('Can\'t expand {t} to two control variables.'. format(t=type(eval_expression))) else: iterval = list(eval_expression.items()) elif isinstance(eval_expression, six.string_types): if iter_type == 'word_in': iterval = eval_expression.split() else: iterval = eval_expression else: iterval = eval_expression return control_vars, iterval
[ "def", "get_for_control_var_and_eval_expr", "(", "comm_type", ",", "kwargs", ")", ":", "# let possible exceptions bubble up", "control_vars", ",", "iter_type", ",", "expression", "=", "parse_for", "(", "comm_type", ")", "eval_expression", "=", "evaluate_expression", "(", "expression", ",", "kwargs", ")", "[", "1", "]", "iterval", "=", "[", "]", "if", "len", "(", "control_vars", ")", "==", "2", ":", "if", "not", "isinstance", "(", "eval_expression", ",", "dict", ")", ":", "raise", "exceptions", ".", "YamlSyntaxError", "(", "'Can\\'t expand {t} to two control variables.'", ".", "format", "(", "t", "=", "type", "(", "eval_expression", ")", ")", ")", "else", ":", "iterval", "=", "list", "(", "eval_expression", ".", "items", "(", ")", ")", "elif", "isinstance", "(", "eval_expression", ",", "six", ".", "string_types", ")", ":", "if", "iter_type", "==", "'word_in'", ":", "iterval", "=", "eval_expression", ".", "split", "(", ")", "else", ":", "iterval", "=", "eval_expression", "else", ":", "iterval", "=", "eval_expression", "return", "control_vars", ",", "iterval" ]
Returns tuple that consists of control variable name and iterable that is result of evaluated expression of given for loop. For example: - given 'for $i in $(echo "foo bar")' it returns (['i'], ['foo', 'bar']) - given 'for $i, $j in $foo' it returns (['i', 'j'], [('foo', 'bar')])
[ "Returns", "tuple", "that", "consists", "of", "control", "variable", "name", "and", "iterable", "that", "is", "result", "of", "evaluated", "expression", "of", "given", "for", "loop", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L286-L313
devassistant/devassistant
devassistant/lang.py
get_section_from_condition
def get_section_from_condition(if_section, else_section, kwargs): """Returns section that should be used from given if/else sections by evaluating given condition. Args: if_section - section with if clause else_section - section that *may* be else clause (just next section after if_section, this method will check if it really is else); possibly None if not present Returns: tuple (<0 or 1>, <True or False>, section), where - the first member says whether we're going to "if" section (0) or else section (1) - the second member says whether we should skip next section during further evaluation (True or False - either we have else to skip, or we don't) - the third member is the appropriate section to run or None if there is only "if" clause and condition evaluates to False """ # check if else section is really else skip = True if else_section is not None and else_section[0] == 'else' else False if evaluate_expression(if_section[0][2:].strip(), kwargs)[0]: return (0, skip, if_section[1]) else: return (1, skip, else_section[1]) if skip else (1, skip, None)
python
def get_section_from_condition(if_section, else_section, kwargs): """Returns section that should be used from given if/else sections by evaluating given condition. Args: if_section - section with if clause else_section - section that *may* be else clause (just next section after if_section, this method will check if it really is else); possibly None if not present Returns: tuple (<0 or 1>, <True or False>, section), where - the first member says whether we're going to "if" section (0) or else section (1) - the second member says whether we should skip next section during further evaluation (True or False - either we have else to skip, or we don't) - the third member is the appropriate section to run or None if there is only "if" clause and condition evaluates to False """ # check if else section is really else skip = True if else_section is not None and else_section[0] == 'else' else False if evaluate_expression(if_section[0][2:].strip(), kwargs)[0]: return (0, skip, if_section[1]) else: return (1, skip, else_section[1]) if skip else (1, skip, None)
[ "def", "get_section_from_condition", "(", "if_section", ",", "else_section", ",", "kwargs", ")", ":", "# check if else section is really else", "skip", "=", "True", "if", "else_section", "is", "not", "None", "and", "else_section", "[", "0", "]", "==", "'else'", "else", "False", "if", "evaluate_expression", "(", "if_section", "[", "0", "]", "[", "2", ":", "]", ".", "strip", "(", ")", ",", "kwargs", ")", "[", "0", "]", ":", "return", "(", "0", ",", "skip", ",", "if_section", "[", "1", "]", ")", "else", ":", "return", "(", "1", ",", "skip", ",", "else_section", "[", "1", "]", ")", "if", "skip", "else", "(", "1", ",", "skip", ",", "None", ")" ]
Returns section that should be used from given if/else sections by evaluating given condition. Args: if_section - section with if clause else_section - section that *may* be else clause (just next section after if_section, this method will check if it really is else); possibly None if not present Returns: tuple (<0 or 1>, <True or False>, section), where - the first member says whether we're going to "if" section (0) or else section (1) - the second member says whether we should skip next section during further evaluation (True or False - either we have else to skip, or we don't) - the third member is the appropriate section to run or None if there is only "if" clause and condition evaluates to False
[ "Returns", "section", "that", "should", "be", "used", "from", "given", "if", "/", "else", "sections", "by", "evaluating", "given", "condition", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L316-L338
devassistant/devassistant
devassistant/lang.py
get_catch_vars
def get_catch_vars(catch): """Returns 2-tuple with names of catch control vars, e.g. for "catch $was_exc, $exc" it returns ('was_exc', 'err'). Args: catch: the whole catch line Returns: 2-tuple with names of catch control variables Raises: exceptions.YamlSyntaxError if the catch line is malformed """ catch_re = re.compile(r'catch\s+(\${?\S+}?),\s*(\${?\S+}?)') res = catch_re.match(catch) if res is None: err = 'Catch must have format "catch $x, $y", got "{0}"'.format(catch) raise exceptions.YamlSyntaxError(err) return get_var_name(res.group(1)), get_var_name(res.group(2))
python
def get_catch_vars(catch): """Returns 2-tuple with names of catch control vars, e.g. for "catch $was_exc, $exc" it returns ('was_exc', 'err'). Args: catch: the whole catch line Returns: 2-tuple with names of catch control variables Raises: exceptions.YamlSyntaxError if the catch line is malformed """ catch_re = re.compile(r'catch\s+(\${?\S+}?),\s*(\${?\S+}?)') res = catch_re.match(catch) if res is None: err = 'Catch must have format "catch $x, $y", got "{0}"'.format(catch) raise exceptions.YamlSyntaxError(err) return get_var_name(res.group(1)), get_var_name(res.group(2))
[ "def", "get_catch_vars", "(", "catch", ")", ":", "catch_re", "=", "re", ".", "compile", "(", "r'catch\\s+(\\${?\\S+}?),\\s*(\\${?\\S+}?)'", ")", "res", "=", "catch_re", ".", "match", "(", "catch", ")", "if", "res", "is", "None", ":", "err", "=", "'Catch must have format \"catch $x, $y\", got \"{0}\"'", ".", "format", "(", "catch", ")", "raise", "exceptions", ".", "YamlSyntaxError", "(", "err", ")", "return", "get_var_name", "(", "res", ".", "group", "(", "1", ")", ")", ",", "get_var_name", "(", "res", ".", "group", "(", "2", ")", ")" ]
Returns 2-tuple with names of catch control vars, e.g. for "catch $was_exc, $exc" it returns ('was_exc', 'err'). Args: catch: the whole catch line Returns: 2-tuple with names of catch control variables Raises: exceptions.YamlSyntaxError if the catch line is malformed
[ "Returns", "2", "-", "tuple", "with", "names", "of", "catch", "control", "vars", "e", ".", "g", ".", "for", "catch", "$was_exc", "$exc", "it", "returns", "(", "was_exc", "err", ")", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L341-L359
devassistant/devassistant
devassistant/lang.py
assign_variable
def assign_variable(variable, log_res, res, kwargs): """Assigns given result (resp. logical result and result) to a variable (resp. to two variables). log_res and res are already computed result of an exec/input section. For example: $foo~: $spam and $eggs $log_res, $foo~: $spam and $eggs $foo: some: struct $log_res, $foo: some: other: struct Args: variable: variable (or two variables separated by ",") to assign to log_res: logical result of evaluated section res: result of evaluated section Raises: YamlSyntaxError: if there are more than two variables """ if variable.endswith('~'): variable = variable[:-1] comma_count = variable.count(',') if comma_count > 1: raise exceptions.YamlSyntaxError('Max two variables allowed on left side.') if comma_count == 1: var1, var2 = map(lambda v: get_var_name(v), variable.split(',')) kwargs[var1] = log_res else: var2 = get_var_name(variable) kwargs[var2] = res return log_res, res
python
def assign_variable(variable, log_res, res, kwargs): """Assigns given result (resp. logical result and result) to a variable (resp. to two variables). log_res and res are already computed result of an exec/input section. For example: $foo~: $spam and $eggs $log_res, $foo~: $spam and $eggs $foo: some: struct $log_res, $foo: some: other: struct Args: variable: variable (or two variables separated by ",") to assign to log_res: logical result of evaluated section res: result of evaluated section Raises: YamlSyntaxError: if there are more than two variables """ if variable.endswith('~'): variable = variable[:-1] comma_count = variable.count(',') if comma_count > 1: raise exceptions.YamlSyntaxError('Max two variables allowed on left side.') if comma_count == 1: var1, var2 = map(lambda v: get_var_name(v), variable.split(',')) kwargs[var1] = log_res else: var2 = get_var_name(variable) kwargs[var2] = res return log_res, res
[ "def", "assign_variable", "(", "variable", ",", "log_res", ",", "res", ",", "kwargs", ")", ":", "if", "variable", ".", "endswith", "(", "'~'", ")", ":", "variable", "=", "variable", "[", ":", "-", "1", "]", "comma_count", "=", "variable", ".", "count", "(", "','", ")", "if", "comma_count", ">", "1", ":", "raise", "exceptions", ".", "YamlSyntaxError", "(", "'Max two variables allowed on left side.'", ")", "if", "comma_count", "==", "1", ":", "var1", ",", "var2", "=", "map", "(", "lambda", "v", ":", "get_var_name", "(", "v", ")", ",", "variable", ".", "split", "(", "','", ")", ")", "kwargs", "[", "var1", "]", "=", "log_res", "else", ":", "var2", "=", "get_var_name", "(", "variable", ")", "kwargs", "[", "var2", "]", "=", "res", "return", "log_res", ",", "res" ]
Assigns given result (resp. logical result and result) to a variable (resp. to two variables). log_res and res are already computed result of an exec/input section. For example: $foo~: $spam and $eggs $log_res, $foo~: $spam and $eggs $foo: some: struct $log_res, $foo: some: other: struct Args: variable: variable (or two variables separated by ",") to assign to log_res: logical result of evaluated section res: result of evaluated section Raises: YamlSyntaxError: if there are more than two variables
[ "Assigns", "given", "result", "(", "resp", ".", "logical", "result", "and", "result", ")", "to", "a", "variable", "(", "resp", ".", "to", "two", "variables", ")", ".", "log_res", "and", "res", "are", "already", "computed", "result", "of", "an", "exec", "/", "input", "section", ".", "For", "example", ":" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L362-L397
devassistant/devassistant
devassistant/lang.py
Interpreter.symbol
def symbol(self, id, bp=0): """ Adds symbol 'id' to symbol_table if it does not exist already, if it does it merely updates its binding power and returns it's symbol class """ try: s = self.symbol_table[id] except KeyError: class s(self.symbol_base): pass s.id = id s.lbp = bp self.symbol_table[id] = s else: s.lbp = max(bp, s.lbp) return s
python
def symbol(self, id, bp=0): """ Adds symbol 'id' to symbol_table if it does not exist already, if it does it merely updates its binding power and returns it's symbol class """ try: s = self.symbol_table[id] except KeyError: class s(self.symbol_base): pass s.id = id s.lbp = bp self.symbol_table[id] = s else: s.lbp = max(bp, s.lbp) return s
[ "def", "symbol", "(", "self", ",", "id", ",", "bp", "=", "0", ")", ":", "try", ":", "s", "=", "self", ".", "symbol_table", "[", "id", "]", "except", "KeyError", ":", "class", "s", "(", "self", ".", "symbol_base", ")", ":", "pass", "s", ".", "id", "=", "id", "s", ".", "lbp", "=", "bp", "self", ".", "symbol_table", "[", "id", "]", "=", "s", "else", ":", "s", ".", "lbp", "=", "max", "(", "bp", ",", "s", ".", "lbp", ")", "return", "s" ]
Adds symbol 'id' to symbol_table if it does not exist already, if it does it merely updates its binding power and returns it's symbol class
[ "Adds", "symbol", "id", "to", "symbol_table", "if", "it", "does", "not", "exist", "already", "if", "it", "does", "it", "merely", "updates", "its", "binding", "power", "and", "returns", "it", "s", "symbol", "class" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L451-L468
devassistant/devassistant
devassistant/lang.py
Interpreter.advance
def advance(self, id=None): """ Advance to next token, optionally check that current token is 'id' """ if id and self.token.id != id: raise SyntaxError("Expected {0}".format(id)) self.token = self.next()
python
def advance(self, id=None): """ Advance to next token, optionally check that current token is 'id' """ if id and self.token.id != id: raise SyntaxError("Expected {0}".format(id)) self.token = self.next()
[ "def", "advance", "(", "self", ",", "id", "=", "None", ")", ":", "if", "id", "and", "self", ".", "token", ".", "id", "!=", "id", ":", "raise", "SyntaxError", "(", "\"Expected {0}\"", ".", "format", "(", "id", ")", ")", "self", ".", "token", "=", "self", ".", "next", "(", ")" ]
Advance to next token, optionally check that current token is 'id'
[ "Advance", "to", "next", "token", "optionally", "check", "that", "current", "token", "is", "id" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L470-L477
devassistant/devassistant
devassistant/lang.py
Interpreter.method
def method(self, symbol_name): """ A decorator - adds the decorated method to symbol 'symbol_name' """ s = self.symbol(symbol_name) def bind(fn): setattr(s, fn.__name__, fn) return bind
python
def method(self, symbol_name): """ A decorator - adds the decorated method to symbol 'symbol_name' """ s = self.symbol(symbol_name) def bind(fn): setattr(s, fn.__name__, fn) return bind
[ "def", "method", "(", "self", ",", "symbol_name", ")", ":", "s", "=", "self", ".", "symbol", "(", "symbol_name", ")", "def", "bind", "(", "fn", ")", ":", "setattr", "(", "s", ",", "fn", ".", "__name__", ",", "fn", ")", "return", "bind" ]
A decorator - adds the decorated method to symbol 'symbol_name'
[ "A", "decorator", "-", "adds", "the", "decorated", "method", "to", "symbol", "symbol_name" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L479-L488
devassistant/devassistant
devassistant/lang.py
Interpreter.parse
def parse(self, expression): """ Evaluates 'expression' and returns it's value(s) """ if isinstance(expression, (list, dict)): return (True if expression else False, expression) if sys.version_info[0] > 2: self.next = self.tokenize(expression).__next__ else: self.next = self.tokenize(expression).next self.token = self.next() return self.expression()
python
def parse(self, expression): """ Evaluates 'expression' and returns it's value(s) """ if isinstance(expression, (list, dict)): return (True if expression else False, expression) if sys.version_info[0] > 2: self.next = self.tokenize(expression).__next__ else: self.next = self.tokenize(expression).next self.token = self.next() return self.expression()
[ "def", "parse", "(", "self", ",", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "(", "list", ",", "dict", ")", ")", ":", "return", "(", "True", "if", "expression", "else", "False", ",", "expression", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "self", ".", "next", "=", "self", ".", "tokenize", "(", "expression", ")", ".", "__next__", "else", ":", "self", ".", "next", "=", "self", ".", "tokenize", "(", "expression", ")", ".", "next", "self", ".", "token", "=", "self", ".", "next", "(", ")", "return", "self", ".", "expression", "(", ")" ]
Evaluates 'expression' and returns it's value(s)
[ "Evaluates", "expression", "and", "returns", "it", "s", "value", "(", "s", ")" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/lang.py#L534-L545
devassistant/devassistant
devassistant/dapi/platforms.py
get_platforms_set
def get_platforms_set(): '''Returns set of all possible platforms''' # arch and mageia are not in Py2 _supported_dists, so we add them manually # Ubuntu adds itself to the list on Ubuntu platforms = set([x.lower() for x in platform._supported_dists]) platforms |= set(['darwin', 'arch', 'mageia', 'ubuntu']) return platforms
python
def get_platforms_set(): '''Returns set of all possible platforms''' # arch and mageia are not in Py2 _supported_dists, so we add them manually # Ubuntu adds itself to the list on Ubuntu platforms = set([x.lower() for x in platform._supported_dists]) platforms |= set(['darwin', 'arch', 'mageia', 'ubuntu']) return platforms
[ "def", "get_platforms_set", "(", ")", ":", "# arch and mageia are not in Py2 _supported_dists, so we add them manually", "# Ubuntu adds itself to the list on Ubuntu", "platforms", "=", "set", "(", "[", "x", ".", "lower", "(", ")", "for", "x", "in", "platform", ".", "_supported_dists", "]", ")", "platforms", "|=", "set", "(", "[", "'darwin'", ",", "'arch'", ",", "'mageia'", ",", "'ubuntu'", "]", ")", "return", "platforms" ]
Returns set of all possible platforms
[ "Returns", "set", "of", "all", "possible", "platforms" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/platforms.py#L4-L10
devassistant/devassistant
devassistant/utils.py
find_file_in_load_dirs
def find_file_in_load_dirs(relpath): """If given relative path exists in one of DevAssistant load paths, return its full path. Args: relpath: a relative path, e.g. "assitants/crt/test.yaml" Returns: absolute path of the file, e.g. "/home/x/.devassistant/assistanta/crt/test.yaml or None if file is not found """ if relpath.startswith(os.path.sep): relpath = relpath.lstrip(os.path.sep) for ld in settings.DATA_DIRECTORIES: possible_path = os.path.join(ld, relpath) if os.path.exists(possible_path): return possible_path
python
def find_file_in_load_dirs(relpath): """If given relative path exists in one of DevAssistant load paths, return its full path. Args: relpath: a relative path, e.g. "assitants/crt/test.yaml" Returns: absolute path of the file, e.g. "/home/x/.devassistant/assistanta/crt/test.yaml or None if file is not found """ if relpath.startswith(os.path.sep): relpath = relpath.lstrip(os.path.sep) for ld in settings.DATA_DIRECTORIES: possible_path = os.path.join(ld, relpath) if os.path.exists(possible_path): return possible_path
[ "def", "find_file_in_load_dirs", "(", "relpath", ")", ":", "if", "relpath", ".", "startswith", "(", "os", ".", "path", ".", "sep", ")", ":", "relpath", "=", "relpath", ".", "lstrip", "(", "os", ".", "path", ".", "sep", ")", "for", "ld", "in", "settings", ".", "DATA_DIRECTORIES", ":", "possible_path", "=", "os", ".", "path", ".", "join", "(", "ld", ",", "relpath", ")", "if", "os", ".", "path", ".", "exists", "(", "possible_path", ")", ":", "return", "possible_path" ]
If given relative path exists in one of DevAssistant load paths, return its full path. Args: relpath: a relative path, e.g. "assitants/crt/test.yaml" Returns: absolute path of the file, e.g. "/home/x/.devassistant/assistanta/crt/test.yaml or None if file is not found
[ "If", "given", "relative", "path", "exists", "in", "one", "of", "DevAssistant", "load", "paths", "return", "its", "full", "path", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/utils.py#L109-L126
devassistant/devassistant
devassistant/utils.py
run_exitfuncs
def run_exitfuncs(): """Function that behaves exactly like Python's atexit, but runs atexit functions in the order in which they were registered, not reversed. """ exc_info = None for func, targs, kargs in _exithandlers: try: func(*targs, **kargs) except SystemExit: exc_info = sys.exc_info() except: exc_info = sys.exc_info() if exc_info is not None: six.reraise(exc_info[0], exc_info[1], exc_info[2])
python
def run_exitfuncs(): """Function that behaves exactly like Python's atexit, but runs atexit functions in the order in which they were registered, not reversed. """ exc_info = None for func, targs, kargs in _exithandlers: try: func(*targs, **kargs) except SystemExit: exc_info = sys.exc_info() except: exc_info = sys.exc_info() if exc_info is not None: six.reraise(exc_info[0], exc_info[1], exc_info[2])
[ "def", "run_exitfuncs", "(", ")", ":", "exc_info", "=", "None", "for", "func", ",", "targs", ",", "kargs", "in", "_exithandlers", ":", "try", ":", "func", "(", "*", "targs", ",", "*", "*", "kargs", ")", "except", "SystemExit", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "except", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "if", "exc_info", "is", "not", "None", ":", "six", ".", "reraise", "(", "exc_info", "[", "0", "]", ",", "exc_info", "[", "1", "]", ",", "exc_info", "[", "2", "]", ")" ]
Function that behaves exactly like Python's atexit, but runs atexit functions in the order in which they were registered, not reversed.
[ "Function", "that", "behaves", "exactly", "like", "Python", "s", "atexit", "but", "runs", "atexit", "functions", "in", "the", "order", "in", "which", "they", "were", "registered", "not", "reversed", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/utils.py#L149-L163
devassistant/devassistant
devassistant/utils.py
strip_prefix
def strip_prefix(string, prefix, regex=False): """Strip the prefix from the string If 'regex' is specified, prefix is understood as a regular expression.""" if not isinstance(string, six.string_types) or not isinstance(prefix, six.string_types): msg = 'Arguments to strip_prefix must be string types. Are: {s}, {p}'\ .format(s=type(string), p=type(prefix)) raise TypeError(msg) if not regex: prefix = re.escape(prefix) if not prefix.startswith('^'): prefix = '^({s})'.format(s=prefix) return _strip(string, prefix)
python
def strip_prefix(string, prefix, regex=False): """Strip the prefix from the string If 'regex' is specified, prefix is understood as a regular expression.""" if not isinstance(string, six.string_types) or not isinstance(prefix, six.string_types): msg = 'Arguments to strip_prefix must be string types. Are: {s}, {p}'\ .format(s=type(string), p=type(prefix)) raise TypeError(msg) if not regex: prefix = re.escape(prefix) if not prefix.startswith('^'): prefix = '^({s})'.format(s=prefix) return _strip(string, prefix)
[ "def", "strip_prefix", "(", "string", ",", "prefix", ",", "regex", "=", "False", ")", ":", "if", "not", "isinstance", "(", "string", ",", "six", ".", "string_types", ")", "or", "not", "isinstance", "(", "prefix", ",", "six", ".", "string_types", ")", ":", "msg", "=", "'Arguments to strip_prefix must be string types. Are: {s}, {p}'", ".", "format", "(", "s", "=", "type", "(", "string", ")", ",", "p", "=", "type", "(", "prefix", ")", ")", "raise", "TypeError", "(", "msg", ")", "if", "not", "regex", ":", "prefix", "=", "re", ".", "escape", "(", "prefix", ")", "if", "not", "prefix", ".", "startswith", "(", "'^'", ")", ":", "prefix", "=", "'^({s})'", ".", "format", "(", "s", "=", "prefix", ")", "return", "_strip", "(", "string", ",", "prefix", ")" ]
Strip the prefix from the string If 'regex' is specified, prefix is understood as a regular expression.
[ "Strip", "the", "prefix", "from", "the", "string" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/utils.py#L190-L203
devassistant/devassistant
devassistant/utils.py
strip_suffix
def strip_suffix(string, suffix, regex=False): """Strip the suffix from the string. If 'regex' is specified, suffix is understood as a regular expression.""" if not isinstance(string, six.string_types) or not isinstance(suffix, six.string_types): msg = 'Arguments to strip_suffix must be string types. Are: {s}, {p}'\ .format(s=type(string), p=type(suffix)) raise TypeError(msg) if not regex: suffix = re.escape(suffix) if not suffix.endswith('$'): suffix = '({s})$'.format(s=suffix) return _strip(string, suffix)
python
def strip_suffix(string, suffix, regex=False): """Strip the suffix from the string. If 'regex' is specified, suffix is understood as a regular expression.""" if not isinstance(string, six.string_types) or not isinstance(suffix, six.string_types): msg = 'Arguments to strip_suffix must be string types. Are: {s}, {p}'\ .format(s=type(string), p=type(suffix)) raise TypeError(msg) if not regex: suffix = re.escape(suffix) if not suffix.endswith('$'): suffix = '({s})$'.format(s=suffix) return _strip(string, suffix)
[ "def", "strip_suffix", "(", "string", ",", "suffix", ",", "regex", "=", "False", ")", ":", "if", "not", "isinstance", "(", "string", ",", "six", ".", "string_types", ")", "or", "not", "isinstance", "(", "suffix", ",", "six", ".", "string_types", ")", ":", "msg", "=", "'Arguments to strip_suffix must be string types. Are: {s}, {p}'", ".", "format", "(", "s", "=", "type", "(", "string", ")", ",", "p", "=", "type", "(", "suffix", ")", ")", "raise", "TypeError", "(", "msg", ")", "if", "not", "regex", ":", "suffix", "=", "re", ".", "escape", "(", "suffix", ")", "if", "not", "suffix", ".", "endswith", "(", "'$'", ")", ":", "suffix", "=", "'({s})$'", ".", "format", "(", "s", "=", "suffix", ")", "return", "_strip", "(", "string", ",", "suffix", ")" ]
Strip the suffix from the string. If 'regex' is specified, suffix is understood as a regular expression.
[ "Strip", "the", "suffix", "from", "the", "string", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/utils.py#L206-L219
devassistant/devassistant
devassistant/utils.py
_strip
def _strip(string, pattern): """Return complement of pattern in string""" m = re.compile(pattern).search(string) if m: return string[0:m.start()] + string[m.end():len(string)] else: return string
python
def _strip(string, pattern): """Return complement of pattern in string""" m = re.compile(pattern).search(string) if m: return string[0:m.start()] + string[m.end():len(string)] else: return string
[ "def", "_strip", "(", "string", ",", "pattern", ")", ":", "m", "=", "re", ".", "compile", "(", "pattern", ")", ".", "search", "(", "string", ")", "if", "m", ":", "return", "string", "[", "0", ":", "m", ".", "start", "(", ")", "]", "+", "string", "[", "m", ".", "end", "(", ")", ":", "len", "(", "string", ")", "]", "else", ":", "return", "string" ]
Return complement of pattern in string
[ "Return", "complement", "of", "pattern", "in", "string" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/utils.py#L222-L229
devassistant/devassistant
devassistant/cli/cli_runner.py
CliRunner.register_console_logging_handler
def register_console_logging_handler(cls, lgr, level=logging.INFO): """Registers console logging handler to given logger.""" console_handler = logger.DevassistantClHandler(sys.stdout) if console_handler.stream.isatty(): console_handler.setFormatter(logger.DevassistantClColorFormatter()) else: console_handler.setFormatter(logger.DevassistantClFormatter()) console_handler.setLevel(level) cls.cur_handler = console_handler lgr.addHandler(console_handler)
python
def register_console_logging_handler(cls, lgr, level=logging.INFO): """Registers console logging handler to given logger.""" console_handler = logger.DevassistantClHandler(sys.stdout) if console_handler.stream.isatty(): console_handler.setFormatter(logger.DevassistantClColorFormatter()) else: console_handler.setFormatter(logger.DevassistantClFormatter()) console_handler.setLevel(level) cls.cur_handler = console_handler lgr.addHandler(console_handler)
[ "def", "register_console_logging_handler", "(", "cls", ",", "lgr", ",", "level", "=", "logging", ".", "INFO", ")", ":", "console_handler", "=", "logger", ".", "DevassistantClHandler", "(", "sys", ".", "stdout", ")", "if", "console_handler", ".", "stream", ".", "isatty", "(", ")", ":", "console_handler", ".", "setFormatter", "(", "logger", ".", "DevassistantClColorFormatter", "(", ")", ")", "else", ":", "console_handler", ".", "setFormatter", "(", "logger", ".", "DevassistantClFormatter", "(", ")", ")", "console_handler", ".", "setLevel", "(", "level", ")", "cls", ".", "cur_handler", "=", "console_handler", "lgr", ".", "addHandler", "(", "console_handler", ")" ]
Registers console logging handler to given logger.
[ "Registers", "console", "logging", "handler", "to", "given", "logger", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cli/cli_runner.py#L21-L30
devassistant/devassistant
devassistant/cli/cli_runner.py
CliRunner.run
def run(cls): """Runs the whole cli: 1. Registers console logging handler 2. Creates argparser from all assistants and actions 3. Parses args and decides what to run 4. Runs a proper assistant or action """ sigint_handler.override() # set settings.USE_CACHE before constructing parser, since constructing # parser requires loaded assistants settings.USE_CACHE = False if '--no-cache' in sys.argv else True cls.register_console_logging_handler(logger.logger) is_log_file = logger.add_log_file_handler(settings.LOG_FILE) if not is_log_file: logger.logger.warning("Could not create log file '{0}'.".format(settings.LOG_FILE)) cls.inform_of_short_bin_name(sys.argv[0]) top_assistant = bin.TopAssistant() tree = top_assistant.get_subassistant_tree() argparser = argparse_generator.ArgparseGenerator.\ generate_argument_parser(tree, actions=actions.actions) parsed_args = vars(argparser.parse_args()) parsed_args_decoded = dict() for k, v in parsed_args.items(): parsed_args_decoded[k] = \ v.decode(utils.defenc) if not six.PY3 and isinstance(v, str) else v parsed_args_decoded['__ui__'] = 'cli' if parsed_args.get('da_debug'): cls.change_logging_level(logging.DEBUG) # Prepare Action/PathRunner if actions.is_action_run(**parsed_args_decoded): to_run = actions.get_action_to_run(**parsed_args_decoded)(**parsed_args_decoded) else: parsed_args = cls.transform_executable_assistant_alias(parsed_args_decoded) path = top_assistant.get_selected_subassistant_path(**parsed_args_decoded) to_run = path_runner.PathRunner(path, parsed_args_decoded) try: to_run.run() except exceptions.ExecutionException: # error is already logged, just catch it and silently exit here sys.exit(1)
python
def run(cls): """Runs the whole cli: 1. Registers console logging handler 2. Creates argparser from all assistants and actions 3. Parses args and decides what to run 4. Runs a proper assistant or action """ sigint_handler.override() # set settings.USE_CACHE before constructing parser, since constructing # parser requires loaded assistants settings.USE_CACHE = False if '--no-cache' in sys.argv else True cls.register_console_logging_handler(logger.logger) is_log_file = logger.add_log_file_handler(settings.LOG_FILE) if not is_log_file: logger.logger.warning("Could not create log file '{0}'.".format(settings.LOG_FILE)) cls.inform_of_short_bin_name(sys.argv[0]) top_assistant = bin.TopAssistant() tree = top_assistant.get_subassistant_tree() argparser = argparse_generator.ArgparseGenerator.\ generate_argument_parser(tree, actions=actions.actions) parsed_args = vars(argparser.parse_args()) parsed_args_decoded = dict() for k, v in parsed_args.items(): parsed_args_decoded[k] = \ v.decode(utils.defenc) if not six.PY3 and isinstance(v, str) else v parsed_args_decoded['__ui__'] = 'cli' if parsed_args.get('da_debug'): cls.change_logging_level(logging.DEBUG) # Prepare Action/PathRunner if actions.is_action_run(**parsed_args_decoded): to_run = actions.get_action_to_run(**parsed_args_decoded)(**parsed_args_decoded) else: parsed_args = cls.transform_executable_assistant_alias(parsed_args_decoded) path = top_assistant.get_selected_subassistant_path(**parsed_args_decoded) to_run = path_runner.PathRunner(path, parsed_args_decoded) try: to_run.run() except exceptions.ExecutionException: # error is already logged, just catch it and silently exit here sys.exit(1)
[ "def", "run", "(", "cls", ")", ":", "sigint_handler", ".", "override", "(", ")", "# set settings.USE_CACHE before constructing parser, since constructing", "# parser requires loaded assistants", "settings", ".", "USE_CACHE", "=", "False", "if", "'--no-cache'", "in", "sys", ".", "argv", "else", "True", "cls", ".", "register_console_logging_handler", "(", "logger", ".", "logger", ")", "is_log_file", "=", "logger", ".", "add_log_file_handler", "(", "settings", ".", "LOG_FILE", ")", "if", "not", "is_log_file", ":", "logger", ".", "logger", ".", "warning", "(", "\"Could not create log file '{0}'.\"", ".", "format", "(", "settings", ".", "LOG_FILE", ")", ")", "cls", ".", "inform_of_short_bin_name", "(", "sys", ".", "argv", "[", "0", "]", ")", "top_assistant", "=", "bin", ".", "TopAssistant", "(", ")", "tree", "=", "top_assistant", ".", "get_subassistant_tree", "(", ")", "argparser", "=", "argparse_generator", ".", "ArgparseGenerator", ".", "generate_argument_parser", "(", "tree", ",", "actions", "=", "actions", ".", "actions", ")", "parsed_args", "=", "vars", "(", "argparser", ".", "parse_args", "(", ")", ")", "parsed_args_decoded", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "parsed_args", ".", "items", "(", ")", ":", "parsed_args_decoded", "[", "k", "]", "=", "v", ".", "decode", "(", "utils", ".", "defenc", ")", "if", "not", "six", ".", "PY3", "and", "isinstance", "(", "v", ",", "str", ")", "else", "v", "parsed_args_decoded", "[", "'__ui__'", "]", "=", "'cli'", "if", "parsed_args", ".", "get", "(", "'da_debug'", ")", ":", "cls", ".", "change_logging_level", "(", "logging", ".", "DEBUG", ")", "# Prepare Action/PathRunner", "if", "actions", ".", "is_action_run", "(", "*", "*", "parsed_args_decoded", ")", ":", "to_run", "=", "actions", ".", "get_action_to_run", "(", "*", "*", "parsed_args_decoded", ")", "(", "*", "*", "parsed_args_decoded", ")", "else", ":", "parsed_args", "=", "cls", ".", "transform_executable_assistant_alias", "(", "parsed_args_decoded", ")", "path", "=", "top_assistant", ".", "get_selected_subassistant_path", "(", "*", "*", "parsed_args_decoded", ")", "to_run", "=", "path_runner", ".", "PathRunner", "(", "path", ",", "parsed_args_decoded", ")", "try", ":", "to_run", ".", "run", "(", ")", "except", "exceptions", ".", "ExecutionException", ":", "# error is already logged, just catch it and silently exit here", "sys", ".", "exit", "(", "1", ")" ]
Runs the whole cli: 1. Registers console logging handler 2. Creates argparser from all assistants and actions 3. Parses args and decides what to run 4. Runs a proper assistant or action
[ "Runs", "the", "whole", "cli", ":" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cli/cli_runner.py#L37-L81
devassistant/devassistant
devassistant/cli/cli_runner.py
CliRunner.inform_of_short_bin_name
def inform_of_short_bin_name(cls, binary): """Historically, we had "devassistant" binary, but we chose to go with shorter "da". We still allow "devassistant", but we recommend using "da". """ binary = os.path.splitext(os.path.basename(binary))[0] if binary != 'da': msg = '"da" is the preffered way of running "{binary}".'.format(binary=binary) logger.logger.info('*' * len(msg)) logger.logger.info(msg) logger.logger.info('*' * len(msg))
python
def inform_of_short_bin_name(cls, binary): """Historically, we had "devassistant" binary, but we chose to go with shorter "da". We still allow "devassistant", but we recommend using "da". """ binary = os.path.splitext(os.path.basename(binary))[0] if binary != 'da': msg = '"da" is the preffered way of running "{binary}".'.format(binary=binary) logger.logger.info('*' * len(msg)) logger.logger.info(msg) logger.logger.info('*' * len(msg))
[ "def", "inform_of_short_bin_name", "(", "cls", ",", "binary", ")", ":", "binary", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "binary", ")", ")", "[", "0", "]", "if", "binary", "!=", "'da'", ":", "msg", "=", "'\"da\" is the preffered way of running \"{binary}\".'", ".", "format", "(", "binary", "=", "binary", ")", "logger", ".", "logger", ".", "info", "(", "'*'", "*", "len", "(", "msg", ")", ")", "logger", ".", "logger", ".", "info", "(", "msg", ")", "logger", ".", "logger", ".", "info", "(", "'*'", "*", "len", "(", "msg", ")", ")" ]
Historically, we had "devassistant" binary, but we chose to go with shorter "da". We still allow "devassistant", but we recommend using "da".
[ "Historically", "we", "had", "devassistant", "binary", "but", "we", "chose", "to", "go", "with", "shorter", "da", ".", "We", "still", "allow", "devassistant", "but", "we", "recommend", "using", "da", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cli/cli_runner.py#L84-L93
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow.get_full_dir_name
def get_full_dir_name(self): """ Function returns a full dir name """ return os.path.join(self.dir_name.get_text(), self.entry_project_name.get_text())
python
def get_full_dir_name(self): """ Function returns a full dir name """ return os.path.join(self.dir_name.get_text(), self.entry_project_name.get_text())
[ "def", "get_full_dir_name", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "dir_name", ".", "get_text", "(", ")", ",", "self", ".", "entry_project_name", ".", "get_text", "(", ")", ")" ]
Function returns a full dir name
[ "Function", "returns", "a", "full", "dir", "name" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L65-L69
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow.next_window
def next_window(self, widget, data=None): """ Function opens the run Window who executes the assistant project creation """ # check whether deps-only is selected deps_only = ('deps_only' in self.args and self.args['deps_only']['checkbox'].get_active()) # preserve argument value if it is needed to be preserved for arg_dict in [x for x in self.args.values() if 'preserved' in x['arg'].kwargs]: preserve_key = arg_dict['arg'].kwargs['preserved'] # preserve entry text (string value) if 'entry' in arg_dict: if self.arg_is_selected(arg_dict): config_manager.set_config_value(preserve_key, arg_dict['entry'].get_text()) # preserve if checkbox is ticked (boolean value) else: config_manager.set_config_value(preserve_key, self.arg_is_selected(arg_dict)) # save configuration into file config_manager.save_configuration_file() # get project directory and name project_dir = self.dir_name.get_text() full_name = self.get_full_dir_name() # check whether project directory and name is properly set if not deps_only and self.current_main_assistant.name == 'crt': if project_dir == "": return self.gui_helper.execute_dialog("Specify directory for project") else: # check whether directory is existing if not os.path.isdir(project_dir): response = self.gui_helper.create_question_dialog( "Directory {0} does not exists".format(project_dir), "Do you want to create them?" ) if response == Gtk.ResponseType.NO: # User do not want to create a directory return else: # Create directory try: os.makedirs(project_dir) except OSError as os_err: return self.gui_helper.execute_dialog("{0}".format(os_err)) elif os.path.isdir(full_name): return self.check_for_directory(full_name) if not self._build_flags(): return if not deps_only and self.current_main_assistant.name == 'crt': self.kwargs['name'] = full_name self.kwargs['__ui__'] = 'gui_gtk+' self.data['kwargs'] = self.kwargs self.data['top_assistant'] = self.top_assistant self.data['current_main_assistant'] = self.current_main_assistant self.parent.run_window.open_window(widget, self.data) self.path_window.hide()
python
def next_window(self, widget, data=None): """ Function opens the run Window who executes the assistant project creation """ # check whether deps-only is selected deps_only = ('deps_only' in self.args and self.args['deps_only']['checkbox'].get_active()) # preserve argument value if it is needed to be preserved for arg_dict in [x for x in self.args.values() if 'preserved' in x['arg'].kwargs]: preserve_key = arg_dict['arg'].kwargs['preserved'] # preserve entry text (string value) if 'entry' in arg_dict: if self.arg_is_selected(arg_dict): config_manager.set_config_value(preserve_key, arg_dict['entry'].get_text()) # preserve if checkbox is ticked (boolean value) else: config_manager.set_config_value(preserve_key, self.arg_is_selected(arg_dict)) # save configuration into file config_manager.save_configuration_file() # get project directory and name project_dir = self.dir_name.get_text() full_name = self.get_full_dir_name() # check whether project directory and name is properly set if not deps_only and self.current_main_assistant.name == 'crt': if project_dir == "": return self.gui_helper.execute_dialog("Specify directory for project") else: # check whether directory is existing if not os.path.isdir(project_dir): response = self.gui_helper.create_question_dialog( "Directory {0} does not exists".format(project_dir), "Do you want to create them?" ) if response == Gtk.ResponseType.NO: # User do not want to create a directory return else: # Create directory try: os.makedirs(project_dir) except OSError as os_err: return self.gui_helper.execute_dialog("{0}".format(os_err)) elif os.path.isdir(full_name): return self.check_for_directory(full_name) if not self._build_flags(): return if not deps_only and self.current_main_assistant.name == 'crt': self.kwargs['name'] = full_name self.kwargs['__ui__'] = 'gui_gtk+' self.data['kwargs'] = self.kwargs self.data['top_assistant'] = self.top_assistant self.data['current_main_assistant'] = self.current_main_assistant self.parent.run_window.open_window(widget, self.data) self.path_window.hide()
[ "def", "next_window", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "# check whether deps-only is selected", "deps_only", "=", "(", "'deps_only'", "in", "self", ".", "args", "and", "self", ".", "args", "[", "'deps_only'", "]", "[", "'checkbox'", "]", ".", "get_active", "(", ")", ")", "# preserve argument value if it is needed to be preserved", "for", "arg_dict", "in", "[", "x", "for", "x", "in", "self", ".", "args", ".", "values", "(", ")", "if", "'preserved'", "in", "x", "[", "'arg'", "]", ".", "kwargs", "]", ":", "preserve_key", "=", "arg_dict", "[", "'arg'", "]", ".", "kwargs", "[", "'preserved'", "]", "# preserve entry text (string value)", "if", "'entry'", "in", "arg_dict", ":", "if", "self", ".", "arg_is_selected", "(", "arg_dict", ")", ":", "config_manager", ".", "set_config_value", "(", "preserve_key", ",", "arg_dict", "[", "'entry'", "]", ".", "get_text", "(", ")", ")", "# preserve if checkbox is ticked (boolean value)", "else", ":", "config_manager", ".", "set_config_value", "(", "preserve_key", ",", "self", ".", "arg_is_selected", "(", "arg_dict", ")", ")", "# save configuration into file", "config_manager", ".", "save_configuration_file", "(", ")", "# get project directory and name", "project_dir", "=", "self", ".", "dir_name", ".", "get_text", "(", ")", "full_name", "=", "self", ".", "get_full_dir_name", "(", ")", "# check whether project directory and name is properly set", "if", "not", "deps_only", "and", "self", ".", "current_main_assistant", ".", "name", "==", "'crt'", ":", "if", "project_dir", "==", "\"\"", ":", "return", "self", ".", "gui_helper", ".", "execute_dialog", "(", "\"Specify directory for project\"", ")", "else", ":", "# check whether directory is existing", "if", "not", "os", ".", "path", ".", "isdir", "(", "project_dir", ")", ":", "response", "=", "self", ".", "gui_helper", ".", "create_question_dialog", "(", "\"Directory {0} does not exists\"", ".", "format", "(", "project_dir", ")", ",", "\"Do you want to create them?\"", ")", "if", "response", "==", "Gtk", ".", "ResponseType", ".", "NO", ":", "# User do not want to create a directory", "return", "else", ":", "# Create directory", "try", ":", "os", ".", "makedirs", "(", "project_dir", ")", "except", "OSError", "as", "os_err", ":", "return", "self", ".", "gui_helper", ".", "execute_dialog", "(", "\"{0}\"", ".", "format", "(", "os_err", ")", ")", "elif", "os", ".", "path", ".", "isdir", "(", "full_name", ")", ":", "return", "self", ".", "check_for_directory", "(", "full_name", ")", "if", "not", "self", ".", "_build_flags", "(", ")", ":", "return", "if", "not", "deps_only", "and", "self", ".", "current_main_assistant", ".", "name", "==", "'crt'", ":", "self", ".", "kwargs", "[", "'name'", "]", "=", "full_name", "self", ".", "kwargs", "[", "'__ui__'", "]", "=", "'gui_gtk+'", "self", ".", "data", "[", "'kwargs'", "]", "=", "self", ".", "kwargs", "self", ".", "data", "[", "'top_assistant'", "]", "=", "self", ".", "top_assistant", "self", ".", "data", "[", "'current_main_assistant'", "]", "=", "self", ".", "current_main_assistant", "self", ".", "parent", ".", "run_window", ".", "open_window", "(", "widget", ",", "self", ".", "data", ")", "self", ".", "path_window", ".", "hide", "(", ")" ]
Function opens the run Window who executes the assistant project creation
[ "Function", "opens", "the", "run", "Window", "who", "executes", "the", "assistant", "project", "creation" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L71-L130
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow._build_flags
def _build_flags(self): """ Function builds kwargs variable for run_window """ # Check if all entries for selected arguments are nonempty for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: if 'entry' in arg_dict and not arg_dict['entry'].get_text(): self.gui_helper.execute_dialog("Entry {0} is empty".format(arg_dict['label'])) return False # Check for active CheckButtons for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'entry' in arg_dict: self.kwargs[arg_name] = arg_dict['entry'].get_text() else: if arg_dict['arg'].get_gui_hint('type') == 'const': self.kwargs[arg_name] = arg_dict['arg'].kwargs['const'] else: self.kwargs[arg_name] = True # Check for non active CheckButtons but with defaults flag for arg_dict in [x for x in self.args.values() if not self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'default' in arg_dict['arg'].kwargs: self.kwargs[arg_name] = arg_dict['arg'].get_gui_hint('default') elif arg_name in self.kwargs: del self.kwargs[arg_name] return True
python
def _build_flags(self): """ Function builds kwargs variable for run_window """ # Check if all entries for selected arguments are nonempty for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: if 'entry' in arg_dict and not arg_dict['entry'].get_text(): self.gui_helper.execute_dialog("Entry {0} is empty".format(arg_dict['label'])) return False # Check for active CheckButtons for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'entry' in arg_dict: self.kwargs[arg_name] = arg_dict['entry'].get_text() else: if arg_dict['arg'].get_gui_hint('type') == 'const': self.kwargs[arg_name] = arg_dict['arg'].kwargs['const'] else: self.kwargs[arg_name] = True # Check for non active CheckButtons but with defaults flag for arg_dict in [x for x in self.args.values() if not self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'default' in arg_dict['arg'].kwargs: self.kwargs[arg_name] = arg_dict['arg'].get_gui_hint('default') elif arg_name in self.kwargs: del self.kwargs[arg_name] return True
[ "def", "_build_flags", "(", "self", ")", ":", "# Check if all entries for selected arguments are nonempty", "for", "arg_dict", "in", "[", "x", "for", "x", "in", "self", ".", "args", ".", "values", "(", ")", "if", "self", ".", "arg_is_selected", "(", "x", ")", "]", ":", "if", "'entry'", "in", "arg_dict", "and", "not", "arg_dict", "[", "'entry'", "]", ".", "get_text", "(", ")", ":", "self", ".", "gui_helper", ".", "execute_dialog", "(", "\"Entry {0} is empty\"", ".", "format", "(", "arg_dict", "[", "'label'", "]", ")", ")", "return", "False", "# Check for active CheckButtons", "for", "arg_dict", "in", "[", "x", "for", "x", "in", "self", ".", "args", ".", "values", "(", ")", "if", "self", ".", "arg_is_selected", "(", "x", ")", "]", ":", "arg_name", "=", "arg_dict", "[", "'arg'", "]", ".", "get_dest", "(", ")", "if", "'entry'", "in", "arg_dict", ":", "self", ".", "kwargs", "[", "arg_name", "]", "=", "arg_dict", "[", "'entry'", "]", ".", "get_text", "(", ")", "else", ":", "if", "arg_dict", "[", "'arg'", "]", ".", "get_gui_hint", "(", "'type'", ")", "==", "'const'", ":", "self", ".", "kwargs", "[", "arg_name", "]", "=", "arg_dict", "[", "'arg'", "]", ".", "kwargs", "[", "'const'", "]", "else", ":", "self", ".", "kwargs", "[", "arg_name", "]", "=", "True", "# Check for non active CheckButtons but with defaults flag", "for", "arg_dict", "in", "[", "x", "for", "x", "in", "self", ".", "args", ".", "values", "(", ")", "if", "not", "self", ".", "arg_is_selected", "(", "x", ")", "]", ":", "arg_name", "=", "arg_dict", "[", "'arg'", "]", ".", "get_dest", "(", ")", "if", "'default'", "in", "arg_dict", "[", "'arg'", "]", ".", "kwargs", ":", "self", ".", "kwargs", "[", "arg_name", "]", "=", "arg_dict", "[", "'arg'", "]", ".", "get_gui_hint", "(", "'default'", ")", "elif", "arg_name", "in", "self", ".", "kwargs", ":", "del", "self", ".", "kwargs", "[", "arg_name", "]", "return", "True" ]
Function builds kwargs variable for run_window
[ "Function", "builds", "kwargs", "variable", "for", "run_window" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L132-L161
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow.open_window
def open_window(self, data=None): """ Function opens the Options dialog """ self.args = dict() if data is not None: self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assistant', None) self.kwargs = data.get('kwargs', None) self.data['debugging'] = data.get('debugging', False) project_dir = self.get_default_project_dir() self.dir_name.set_text(project_dir) self.label_full_prj_dir.set_text(project_dir) self.dir_name.set_sensitive(True) self.dir_name_browse_btn.set_sensitive(True) self._remove_widget_items() if self.current_main_assistant.name != 'crt' and self.project_name_shown: self.box6.remove(self.box_project) self.project_name_shown = False elif self.current_main_assistant.name == 'crt' and not self.project_name_shown: self.box6.remove(self.box_path_main) self.box6.pack_start(self.box_project, False, False, 0) self.box6.pack_end(self.box_path_main, False, False, 0) self.project_name_shown = True caption_text = "Project: " row = 0 # get selectected assistants, but without TopAssistant itself path = self.top_assistant.get_selected_subassistant_path(**self.kwargs)[1:] caption_parts = [] # Finds any dependencies found_deps = [x for x in path if x.dependencies()] # This bool variable is used for showing text "Available options:" any_options = False for assistant in path: caption_parts.append("<b>" + assistant.fullname + "</b>") for arg in sorted([x for x in assistant.args if not '--name' in x.flags], key=lambda y: y.flags): if not (arg.name == "deps_only" and not found_deps): row = self._add_table_row(arg, len(arg.flags) - 1, row) + 1 any_options = True if not any_options: self.title.set_text("") else: self.title.set_text("Available options:") caption_text += ' -> '.join(caption_parts) self.label_caption.set_markup(caption_text) self.path_window.show_all() self.entry_project_name.set_text(os.path.basename(self.kwargs.get('name', ''))) self.entry_project_name.set_sensitive(True) self.run_btn.set_sensitive(not self.project_name_shown or self.entry_project_name.get_text() != "") if 'name' in self.kwargs: self.dir_name.set_text(os.path.dirname(self.kwargs.get('name', ''))) for arg_name, arg_dict in [(k, v) for (k, v) in self.args.items() if self.kwargs.get(k)]: if 'checkbox' in arg_dict: arg_dict['checkbox'].set_active(True) if 'entry' in arg_dict: arg_dict['entry'].set_sensitive(True) arg_dict['entry'].set_text(self.kwargs[arg_name]) if 'browse_btn' in arg_dict: arg_dict['browse_btn'].set_sensitive(True)
python
def open_window(self, data=None): """ Function opens the Options dialog """ self.args = dict() if data is not None: self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assistant', None) self.kwargs = data.get('kwargs', None) self.data['debugging'] = data.get('debugging', False) project_dir = self.get_default_project_dir() self.dir_name.set_text(project_dir) self.label_full_prj_dir.set_text(project_dir) self.dir_name.set_sensitive(True) self.dir_name_browse_btn.set_sensitive(True) self._remove_widget_items() if self.current_main_assistant.name != 'crt' and self.project_name_shown: self.box6.remove(self.box_project) self.project_name_shown = False elif self.current_main_assistant.name == 'crt' and not self.project_name_shown: self.box6.remove(self.box_path_main) self.box6.pack_start(self.box_project, False, False, 0) self.box6.pack_end(self.box_path_main, False, False, 0) self.project_name_shown = True caption_text = "Project: " row = 0 # get selectected assistants, but without TopAssistant itself path = self.top_assistant.get_selected_subassistant_path(**self.kwargs)[1:] caption_parts = [] # Finds any dependencies found_deps = [x for x in path if x.dependencies()] # This bool variable is used for showing text "Available options:" any_options = False for assistant in path: caption_parts.append("<b>" + assistant.fullname + "</b>") for arg in sorted([x for x in assistant.args if not '--name' in x.flags], key=lambda y: y.flags): if not (arg.name == "deps_only" and not found_deps): row = self._add_table_row(arg, len(arg.flags) - 1, row) + 1 any_options = True if not any_options: self.title.set_text("") else: self.title.set_text("Available options:") caption_text += ' -> '.join(caption_parts) self.label_caption.set_markup(caption_text) self.path_window.show_all() self.entry_project_name.set_text(os.path.basename(self.kwargs.get('name', ''))) self.entry_project_name.set_sensitive(True) self.run_btn.set_sensitive(not self.project_name_shown or self.entry_project_name.get_text() != "") if 'name' in self.kwargs: self.dir_name.set_text(os.path.dirname(self.kwargs.get('name', ''))) for arg_name, arg_dict in [(k, v) for (k, v) in self.args.items() if self.kwargs.get(k)]: if 'checkbox' in arg_dict: arg_dict['checkbox'].set_active(True) if 'entry' in arg_dict: arg_dict['entry'].set_sensitive(True) arg_dict['entry'].set_text(self.kwargs[arg_name]) if 'browse_btn' in arg_dict: arg_dict['browse_btn'].set_sensitive(True)
[ "def", "open_window", "(", "self", ",", "data", "=", "None", ")", ":", "self", ".", "args", "=", "dict", "(", ")", "if", "data", "is", "not", "None", ":", "self", ".", "top_assistant", "=", "data", ".", "get", "(", "'top_assistant'", ",", "None", ")", "self", ".", "current_main_assistant", "=", "data", ".", "get", "(", "'current_main_assistant'", ",", "None", ")", "self", ".", "kwargs", "=", "data", ".", "get", "(", "'kwargs'", ",", "None", ")", "self", ".", "data", "[", "'debugging'", "]", "=", "data", ".", "get", "(", "'debugging'", ",", "False", ")", "project_dir", "=", "self", ".", "get_default_project_dir", "(", ")", "self", ".", "dir_name", ".", "set_text", "(", "project_dir", ")", "self", ".", "label_full_prj_dir", ".", "set_text", "(", "project_dir", ")", "self", ".", "dir_name", ".", "set_sensitive", "(", "True", ")", "self", ".", "dir_name_browse_btn", ".", "set_sensitive", "(", "True", ")", "self", ".", "_remove_widget_items", "(", ")", "if", "self", ".", "current_main_assistant", ".", "name", "!=", "'crt'", "and", "self", ".", "project_name_shown", ":", "self", ".", "box6", ".", "remove", "(", "self", ".", "box_project", ")", "self", ".", "project_name_shown", "=", "False", "elif", "self", ".", "current_main_assistant", ".", "name", "==", "'crt'", "and", "not", "self", ".", "project_name_shown", ":", "self", ".", "box6", ".", "remove", "(", "self", ".", "box_path_main", ")", "self", ".", "box6", ".", "pack_start", "(", "self", ".", "box_project", ",", "False", ",", "False", ",", "0", ")", "self", ".", "box6", ".", "pack_end", "(", "self", ".", "box_path_main", ",", "False", ",", "False", ",", "0", ")", "self", ".", "project_name_shown", "=", "True", "caption_text", "=", "\"Project: \"", "row", "=", "0", "# get selectected assistants, but without TopAssistant itself", "path", "=", "self", ".", "top_assistant", ".", "get_selected_subassistant_path", "(", "*", "*", "self", ".", "kwargs", ")", "[", "1", ":", "]", "caption_parts", "=", "[", "]", "# Finds any dependencies", "found_deps", "=", "[", "x", "for", "x", "in", "path", "if", "x", ".", "dependencies", "(", ")", "]", "# This bool variable is used for showing text \"Available options:\"", "any_options", "=", "False", "for", "assistant", "in", "path", ":", "caption_parts", ".", "append", "(", "\"<b>\"", "+", "assistant", ".", "fullname", "+", "\"</b>\"", ")", "for", "arg", "in", "sorted", "(", "[", "x", "for", "x", "in", "assistant", ".", "args", "if", "not", "'--name'", "in", "x", ".", "flags", "]", ",", "key", "=", "lambda", "y", ":", "y", ".", "flags", ")", ":", "if", "not", "(", "arg", ".", "name", "==", "\"deps_only\"", "and", "not", "found_deps", ")", ":", "row", "=", "self", ".", "_add_table_row", "(", "arg", ",", "len", "(", "arg", ".", "flags", ")", "-", "1", ",", "row", ")", "+", "1", "any_options", "=", "True", "if", "not", "any_options", ":", "self", ".", "title", ".", "set_text", "(", "\"\"", ")", "else", ":", "self", ".", "title", ".", "set_text", "(", "\"Available options:\"", ")", "caption_text", "+=", "' -> '", ".", "join", "(", "caption_parts", ")", "self", ".", "label_caption", ".", "set_markup", "(", "caption_text", ")", "self", ".", "path_window", ".", "show_all", "(", ")", "self", ".", "entry_project_name", ".", "set_text", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "kwargs", ".", "get", "(", "'name'", ",", "''", ")", ")", ")", "self", ".", "entry_project_name", ".", "set_sensitive", "(", "True", ")", "self", ".", "run_btn", ".", "set_sensitive", "(", "not", "self", ".", "project_name_shown", "or", "self", ".", "entry_project_name", ".", "get_text", "(", ")", "!=", "\"\"", ")", "if", "'name'", "in", "self", ".", "kwargs", ":", "self", ".", "dir_name", ".", "set_text", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "kwargs", ".", "get", "(", "'name'", ",", "''", ")", ")", ")", "for", "arg_name", ",", "arg_dict", "in", "[", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "self", ".", "args", ".", "items", "(", ")", "if", "self", ".", "kwargs", ".", "get", "(", "k", ")", "]", ":", "if", "'checkbox'", "in", "arg_dict", ":", "arg_dict", "[", "'checkbox'", "]", ".", "set_active", "(", "True", ")", "if", "'entry'", "in", "arg_dict", ":", "arg_dict", "[", "'entry'", "]", ".", "set_sensitive", "(", "True", ")", "arg_dict", "[", "'entry'", "]", ".", "set_text", "(", "self", ".", "kwargs", "[", "arg_name", "]", ")", "if", "'browse_btn'", "in", "arg_dict", ":", "arg_dict", "[", "'browse_btn'", "]", ".", "set_sensitive", "(", "True", ")" ]
Function opens the Options dialog
[ "Function", "opens", "the", "Options", "dialog" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L177-L236
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow._check_box_toggled
def _check_box_toggled(self, widget, data=None): """ Function manipulates with entries and buttons. """ active = widget.get_active() arg_name = data if 'entry' in self.args[arg_name]: self.args[arg_name]['entry'].set_sensitive(active) if 'browse_btn' in self.args[arg_name]: self.args[arg_name]['browse_btn'].set_sensitive(active) self.path_window.show_all()
python
def _check_box_toggled(self, widget, data=None): """ Function manipulates with entries and buttons. """ active = widget.get_active() arg_name = data if 'entry' in self.args[arg_name]: self.args[arg_name]['entry'].set_sensitive(active) if 'browse_btn' in self.args[arg_name]: self.args[arg_name]['browse_btn'].set_sensitive(active) self.path_window.show_all()
[ "def", "_check_box_toggled", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "active", "=", "widget", ".", "get_active", "(", ")", "arg_name", "=", "data", "if", "'entry'", "in", "self", ".", "args", "[", "arg_name", "]", ":", "self", ".", "args", "[", "arg_name", "]", "[", "'entry'", "]", ".", "set_sensitive", "(", "active", ")", "if", "'browse_btn'", "in", "self", ".", "args", "[", "arg_name", "]", ":", "self", ".", "args", "[", "arg_name", "]", "[", "'browse_btn'", "]", ".", "set_sensitive", "(", "active", ")", "self", ".", "path_window", ".", "show_all", "(", ")" ]
Function manipulates with entries and buttons.
[ "Function", "manipulates", "with", "entries", "and", "buttons", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L238-L250
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow._deps_only_toggled
def _deps_only_toggled(self, widget, data=None): """ Function deactivate options in case of deps_only and opposite """ active = widget.get_active() self.dir_name.set_sensitive(not active) self.entry_project_name.set_sensitive(not active) self.dir_name_browse_btn.set_sensitive(not active) self.run_btn.set_sensitive(active or not self.project_name_shown or self.entry_project_name.get_text() != "")
python
def _deps_only_toggled(self, widget, data=None): """ Function deactivate options in case of deps_only and opposite """ active = widget.get_active() self.dir_name.set_sensitive(not active) self.entry_project_name.set_sensitive(not active) self.dir_name_browse_btn.set_sensitive(not active) self.run_btn.set_sensitive(active or not self.project_name_shown or self.entry_project_name.get_text() != "")
[ "def", "_deps_only_toggled", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "active", "=", "widget", ".", "get_active", "(", ")", "self", ".", "dir_name", ".", "set_sensitive", "(", "not", "active", ")", "self", ".", "entry_project_name", ".", "set_sensitive", "(", "not", "active", ")", "self", ".", "dir_name_browse_btn", ".", "set_sensitive", "(", "not", "active", ")", "self", ".", "run_btn", ".", "set_sensitive", "(", "active", "or", "not", "self", ".", "project_name_shown", "or", "self", ".", "entry_project_name", ".", "get_text", "(", ")", "!=", "\"\"", ")" ]
Function deactivate options in case of deps_only and opposite
[ "Function", "deactivate", "options", "in", "case", "of", "deps_only", "and", "opposite" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L252-L260
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow.prev_window
def prev_window(self, widget, data=None): """ Function returns to Main Window """ self.path_window.hide() self.parent.open_window(widget, self.data)
python
def prev_window(self, widget, data=None): """ Function returns to Main Window """ self.path_window.hide() self.parent.open_window(widget, self.data)
[ "def", "prev_window", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "self", ".", "path_window", ".", "hide", "(", ")", "self", ".", "parent", ".", "open_window", "(", "widget", ",", "self", ".", "data", ")" ]
Function returns to Main Window
[ "Function", "returns", "to", "Main", "Window" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L262-L267
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow.browse_path
def browse_path(self, window): """ Function opens the file chooser dialog for settings project dir """ text = self.gui_helper.create_file_chooser_dialog("Choose project directory", self.path_window, name="Select") if text is not None: self.dir_name.set_text(text)
python
def browse_path(self, window): """ Function opens the file chooser dialog for settings project dir """ text = self.gui_helper.create_file_chooser_dialog("Choose project directory", self.path_window, name="Select") if text is not None: self.dir_name.set_text(text)
[ "def", "browse_path", "(", "self", ",", "window", ")", ":", "text", "=", "self", ".", "gui_helper", ".", "create_file_chooser_dialog", "(", "\"Choose project directory\"", ",", "self", ".", "path_window", ",", "name", "=", "\"Select\"", ")", "if", "text", "is", "not", "None", ":", "self", ".", "dir_name", ".", "set_text", "(", "text", ")" ]
Function opens the file chooser dialog for settings project dir
[ "Function", "opens", "the", "file", "chooser", "dialog", "for", "settings", "project", "dir" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L275-L281
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow._add_table_row
def _add_table_row(self, arg, number, row): """ Function adds options to a grid """ self.args[arg.name] = dict() self.args[arg.name]['arg'] = arg check_box_title = arg.flags[number][2:].title() self.args[arg.name]['label'] = check_box_title align = self.gui_helper.create_alignment() if arg.kwargs.get('required'): # If argument is required then red star instead of checkbox star_label = self.gui_helper.create_label('<span color="#FF0000">*</span>') star_label.set_padding(0, 3) label = self.gui_helper.create_label(check_box_title) box = self.gui_helper.create_box() box.pack_start(star_label, False, False, 6) box.pack_start(label, False, False, 6) align.add(box) else: chbox = self.gui_helper.create_checkbox(check_box_title) chbox.set_alignment(0, 0) if arg.name == "deps_only": chbox.connect("clicked", self._deps_only_toggled) else: chbox.connect("clicked", self._check_box_toggled, arg.name) align.add(chbox) self.args[arg.name]['checkbox'] = chbox if row == 0: self.grid.add(align) else: self.grid.attach(align, 0, row, 1, 1) label = self.gui_helper.create_label(arg.kwargs['help'], justify=Gtk.Justification.LEFT) label.set_alignment(0, 0) label.set_padding(0, 3) self.grid.attach(label, 1, row, 1, 1) label_check_box = self.gui_helper.create_label(name="") self.grid.attach(label_check_box, 0, row, 1, 1) if arg.get_gui_hint('type') not in ['bool', 'const']: new_box = self.gui_helper.create_box(spacing=6) entry = self.gui_helper.create_entry(text="") align = self.gui_helper.create_alignment() align.add(entry) new_box.pack_start(align, False, False, 6) align_btn = self.gui_helper.create_alignment() ''' If a button is needed please add there and in function _check_box_toggled Also do not forget to create a function for that button This can not be done by any automatic tool from those reasons Some fields needs a input user like user name for GitHub and some fields needs to have interaction from user like selecting directory ''' entry.set_text(arg.get_gui_hint('default')) entry.set_sensitive(arg.kwargs.get('required') == True) if arg.get_gui_hint('type') == 'path': browse_btn = self.gui_helper.button_with_label("Browse") browse_btn.connect("clicked", self.browse_clicked, entry) browse_btn.set_sensitive(arg.kwargs.get('required') == True) align_btn.add(browse_btn) self.args[arg.name]['browse_btn'] = browse_btn elif arg.get_gui_hint('type') == 'str': if arg.name == 'github' or arg.name == 'github-login': link_button = self.gui_helper.create_link_button(text="For registration visit GitHub Homepage", uri="https://www.github.com") align_btn.add(link_button) new_box.pack_start(align_btn, False, False, 6) row += 1 self.args[arg.name]['entry'] = entry self.grid.attach(new_box, 1, row, 1, 1) else: if 'preserved' in arg.kwargs and config_manager.get_config_value(arg.kwargs['preserved']): if 'checkbox' in self.args[arg.name]: self.args[arg.name]['checkbox'].set_active(True) return row
python
def _add_table_row(self, arg, number, row): """ Function adds options to a grid """ self.args[arg.name] = dict() self.args[arg.name]['arg'] = arg check_box_title = arg.flags[number][2:].title() self.args[arg.name]['label'] = check_box_title align = self.gui_helper.create_alignment() if arg.kwargs.get('required'): # If argument is required then red star instead of checkbox star_label = self.gui_helper.create_label('<span color="#FF0000">*</span>') star_label.set_padding(0, 3) label = self.gui_helper.create_label(check_box_title) box = self.gui_helper.create_box() box.pack_start(star_label, False, False, 6) box.pack_start(label, False, False, 6) align.add(box) else: chbox = self.gui_helper.create_checkbox(check_box_title) chbox.set_alignment(0, 0) if arg.name == "deps_only": chbox.connect("clicked", self._deps_only_toggled) else: chbox.connect("clicked", self._check_box_toggled, arg.name) align.add(chbox) self.args[arg.name]['checkbox'] = chbox if row == 0: self.grid.add(align) else: self.grid.attach(align, 0, row, 1, 1) label = self.gui_helper.create_label(arg.kwargs['help'], justify=Gtk.Justification.LEFT) label.set_alignment(0, 0) label.set_padding(0, 3) self.grid.attach(label, 1, row, 1, 1) label_check_box = self.gui_helper.create_label(name="") self.grid.attach(label_check_box, 0, row, 1, 1) if arg.get_gui_hint('type') not in ['bool', 'const']: new_box = self.gui_helper.create_box(spacing=6) entry = self.gui_helper.create_entry(text="") align = self.gui_helper.create_alignment() align.add(entry) new_box.pack_start(align, False, False, 6) align_btn = self.gui_helper.create_alignment() ''' If a button is needed please add there and in function _check_box_toggled Also do not forget to create a function for that button This can not be done by any automatic tool from those reasons Some fields needs a input user like user name for GitHub and some fields needs to have interaction from user like selecting directory ''' entry.set_text(arg.get_gui_hint('default')) entry.set_sensitive(arg.kwargs.get('required') == True) if arg.get_gui_hint('type') == 'path': browse_btn = self.gui_helper.button_with_label("Browse") browse_btn.connect("clicked", self.browse_clicked, entry) browse_btn.set_sensitive(arg.kwargs.get('required') == True) align_btn.add(browse_btn) self.args[arg.name]['browse_btn'] = browse_btn elif arg.get_gui_hint('type') == 'str': if arg.name == 'github' or arg.name == 'github-login': link_button = self.gui_helper.create_link_button(text="For registration visit GitHub Homepage", uri="https://www.github.com") align_btn.add(link_button) new_box.pack_start(align_btn, False, False, 6) row += 1 self.args[arg.name]['entry'] = entry self.grid.attach(new_box, 1, row, 1, 1) else: if 'preserved' in arg.kwargs and config_manager.get_config_value(arg.kwargs['preserved']): if 'checkbox' in self.args[arg.name]: self.args[arg.name]['checkbox'].set_active(True) return row
[ "def", "_add_table_row", "(", "self", ",", "arg", ",", "number", ",", "row", ")", ":", "self", ".", "args", "[", "arg", ".", "name", "]", "=", "dict", "(", ")", "self", ".", "args", "[", "arg", ".", "name", "]", "[", "'arg'", "]", "=", "arg", "check_box_title", "=", "arg", ".", "flags", "[", "number", "]", "[", "2", ":", "]", ".", "title", "(", ")", "self", ".", "args", "[", "arg", ".", "name", "]", "[", "'label'", "]", "=", "check_box_title", "align", "=", "self", ".", "gui_helper", ".", "create_alignment", "(", ")", "if", "arg", ".", "kwargs", ".", "get", "(", "'required'", ")", ":", "# If argument is required then red star instead of checkbox", "star_label", "=", "self", ".", "gui_helper", ".", "create_label", "(", "'<span color=\"#FF0000\">*</span>'", ")", "star_label", ".", "set_padding", "(", "0", ",", "3", ")", "label", "=", "self", ".", "gui_helper", ".", "create_label", "(", "check_box_title", ")", "box", "=", "self", ".", "gui_helper", ".", "create_box", "(", ")", "box", ".", "pack_start", "(", "star_label", ",", "False", ",", "False", ",", "6", ")", "box", ".", "pack_start", "(", "label", ",", "False", ",", "False", ",", "6", ")", "align", ".", "add", "(", "box", ")", "else", ":", "chbox", "=", "self", ".", "gui_helper", ".", "create_checkbox", "(", "check_box_title", ")", "chbox", ".", "set_alignment", "(", "0", ",", "0", ")", "if", "arg", ".", "name", "==", "\"deps_only\"", ":", "chbox", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "_deps_only_toggled", ")", "else", ":", "chbox", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "_check_box_toggled", ",", "arg", ".", "name", ")", "align", ".", "add", "(", "chbox", ")", "self", ".", "args", "[", "arg", ".", "name", "]", "[", "'checkbox'", "]", "=", "chbox", "if", "row", "==", "0", ":", "self", ".", "grid", ".", "add", "(", "align", ")", "else", ":", "self", ".", "grid", ".", "attach", "(", "align", ",", "0", ",", "row", ",", "1", ",", "1", ")", "label", "=", "self", ".", "gui_helper", ".", "create_label", "(", "arg", ".", "kwargs", "[", "'help'", "]", ",", "justify", "=", "Gtk", ".", "Justification", ".", "LEFT", ")", "label", ".", "set_alignment", "(", "0", ",", "0", ")", "label", ".", "set_padding", "(", "0", ",", "3", ")", "self", ".", "grid", ".", "attach", "(", "label", ",", "1", ",", "row", ",", "1", ",", "1", ")", "label_check_box", "=", "self", ".", "gui_helper", ".", "create_label", "(", "name", "=", "\"\"", ")", "self", ".", "grid", ".", "attach", "(", "label_check_box", ",", "0", ",", "row", ",", "1", ",", "1", ")", "if", "arg", ".", "get_gui_hint", "(", "'type'", ")", "not", "in", "[", "'bool'", ",", "'const'", "]", ":", "new_box", "=", "self", ".", "gui_helper", ".", "create_box", "(", "spacing", "=", "6", ")", "entry", "=", "self", ".", "gui_helper", ".", "create_entry", "(", "text", "=", "\"\"", ")", "align", "=", "self", ".", "gui_helper", ".", "create_alignment", "(", ")", "align", ".", "add", "(", "entry", ")", "new_box", ".", "pack_start", "(", "align", ",", "False", ",", "False", ",", "6", ")", "align_btn", "=", "self", ".", "gui_helper", ".", "create_alignment", "(", ")", "''' If a button is needed please add there and in function\n _check_box_toggled\n Also do not forget to create a function for that button\n This can not be done by any automatic tool from those reasons\n Some fields needs a input user like user name for GitHub\n and some fields needs to have interaction from user like selecting directory\n '''", "entry", ".", "set_text", "(", "arg", ".", "get_gui_hint", "(", "'default'", ")", ")", "entry", ".", "set_sensitive", "(", "arg", ".", "kwargs", ".", "get", "(", "'required'", ")", "==", "True", ")", "if", "arg", ".", "get_gui_hint", "(", "'type'", ")", "==", "'path'", ":", "browse_btn", "=", "self", ".", "gui_helper", ".", "button_with_label", "(", "\"Browse\"", ")", "browse_btn", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "browse_clicked", ",", "entry", ")", "browse_btn", ".", "set_sensitive", "(", "arg", ".", "kwargs", ".", "get", "(", "'required'", ")", "==", "True", ")", "align_btn", ".", "add", "(", "browse_btn", ")", "self", ".", "args", "[", "arg", ".", "name", "]", "[", "'browse_btn'", "]", "=", "browse_btn", "elif", "arg", ".", "get_gui_hint", "(", "'type'", ")", "==", "'str'", ":", "if", "arg", ".", "name", "==", "'github'", "or", "arg", ".", "name", "==", "'github-login'", ":", "link_button", "=", "self", ".", "gui_helper", ".", "create_link_button", "(", "text", "=", "\"For registration visit GitHub Homepage\"", ",", "uri", "=", "\"https://www.github.com\"", ")", "align_btn", ".", "add", "(", "link_button", ")", "new_box", ".", "pack_start", "(", "align_btn", ",", "False", ",", "False", ",", "6", ")", "row", "+=", "1", "self", ".", "args", "[", "arg", ".", "name", "]", "[", "'entry'", "]", "=", "entry", "self", ".", "grid", ".", "attach", "(", "new_box", ",", "1", ",", "row", ",", "1", ",", "1", ")", "else", ":", "if", "'preserved'", "in", "arg", ".", "kwargs", "and", "config_manager", ".", "get_config_value", "(", "arg", ".", "kwargs", "[", "'preserved'", "]", ")", ":", "if", "'checkbox'", "in", "self", ".", "args", "[", "arg", ".", "name", "]", ":", "self", ".", "args", "[", "arg", ".", "name", "]", "[", "'checkbox'", "]", ".", "set_active", "(", "True", ")", "return", "row" ]
Function adds options to a grid
[ "Function", "adds", "options", "to", "a", "grid" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L283-L356
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow.browse_clicked
def browse_clicked(self, widget, data=None): """ Function sets the directory to entry """ text = self.gui_helper.create_file_chooser_dialog("Please select directory", self.path_window) if text is not None: data.set_text(text)
python
def browse_clicked(self, widget, data=None): """ Function sets the directory to entry """ text = self.gui_helper.create_file_chooser_dialog("Please select directory", self.path_window) if text is not None: data.set_text(text)
[ "def", "browse_clicked", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "text", "=", "self", ".", "gui_helper", ".", "create_file_chooser_dialog", "(", "\"Please select directory\"", ",", "self", ".", "path_window", ")", "if", "text", "is", "not", "None", ":", "data", ".", "set_text", "(", "text", ")" ]
Function sets the directory to entry
[ "Function", "sets", "the", "directory", "to", "entry" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L358-L364
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow.project_name_changed
def project_name_changed(self, widget, data=None): """ Function controls whether run button is enabled """ if widget.get_text() != "": self.run_btn.set_sensitive(True) else: self.run_btn.set_sensitive(False) self.update_full_label()
python
def project_name_changed(self, widget, data=None): """ Function controls whether run button is enabled """ if widget.get_text() != "": self.run_btn.set_sensitive(True) else: self.run_btn.set_sensitive(False) self.update_full_label()
[ "def", "project_name_changed", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "if", "widget", ".", "get_text", "(", ")", "!=", "\"\"", ":", "self", ".", "run_btn", ".", "set_sensitive", "(", "True", ")", "else", ":", "self", ".", "run_btn", ".", "set_sensitive", "(", "False", ")", "self", ".", "update_full_label", "(", ")" ]
Function controls whether run button is enabled
[ "Function", "controls", "whether", "run", "button", "is", "enabled" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L373-L381
devassistant/devassistant
devassistant/gui/path_window.py
PathWindow.dir_name_changed
def dir_name_changed(self, widget, data=None): """ Function is used for controlling label Full Directory project name and storing current project directory in configuration manager """ config_manager.set_config_value("da.project_dir", self.dir_name.get_text()) self.update_full_label()
python
def dir_name_changed(self, widget, data=None): """ Function is used for controlling label Full Directory project name and storing current project directory in configuration manager """ config_manager.set_config_value("da.project_dir", self.dir_name.get_text()) self.update_full_label()
[ "def", "dir_name_changed", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "config_manager", ".", "set_config_value", "(", "\"da.project_dir\"", ",", "self", ".", "dir_name", ".", "get_text", "(", ")", ")", "self", ".", "update_full_label", "(", ")" ]
Function is used for controlling label Full Directory project name and storing current project directory in configuration manager
[ "Function", "is", "used", "for", "controlling", "label", "Full", "Directory", "project", "name", "and", "storing", "current", "project", "directory", "in", "configuration", "manager" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/path_window.py#L383-L391
devassistant/devassistant
devassistant/yaml_checker.py
YamlChecker.check
def check(self): """Checks whether loaded yaml is well-formed according to syntax defined for version 0.9.0 and later. Raises: YamlError: (containing a meaningful message) when the loaded Yaml is not well formed """ if not isinstance(self.parsed_yaml, dict): msg = 'In {0}:\n'.format(self.sourcefile) msg += 'Assistants and snippets must be Yaml mappings, not "{0}"!'.\ format(self.parsed_yaml) raise exceptions.YamlTypeError(msg) self._check_fullname(self.sourcefile) self._check_description(self.sourcefile) self._check_section_names(self.sourcefile) self._check_project_type(self.sourcefile) self._check_args(self.sourcefile) self._check_files(self.sourcefile) self._check_dependencies(self.sourcefile) self._check_run(self.sourcefile)
python
def check(self): """Checks whether loaded yaml is well-formed according to syntax defined for version 0.9.0 and later. Raises: YamlError: (containing a meaningful message) when the loaded Yaml is not well formed """ if not isinstance(self.parsed_yaml, dict): msg = 'In {0}:\n'.format(self.sourcefile) msg += 'Assistants and snippets must be Yaml mappings, not "{0}"!'.\ format(self.parsed_yaml) raise exceptions.YamlTypeError(msg) self._check_fullname(self.sourcefile) self._check_description(self.sourcefile) self._check_section_names(self.sourcefile) self._check_project_type(self.sourcefile) self._check_args(self.sourcefile) self._check_files(self.sourcefile) self._check_dependencies(self.sourcefile) self._check_run(self.sourcefile)
[ "def", "check", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "parsed_yaml", ",", "dict", ")", ":", "msg", "=", "'In {0}:\\n'", ".", "format", "(", "self", ".", "sourcefile", ")", "msg", "+=", "'Assistants and snippets must be Yaml mappings, not \"{0}\"!'", ".", "format", "(", "self", ".", "parsed_yaml", ")", "raise", "exceptions", ".", "YamlTypeError", "(", "msg", ")", "self", ".", "_check_fullname", "(", "self", ".", "sourcefile", ")", "self", ".", "_check_description", "(", "self", ".", "sourcefile", ")", "self", ".", "_check_section_names", "(", "self", ".", "sourcefile", ")", "self", ".", "_check_project_type", "(", "self", ".", "sourcefile", ")", "self", ".", "_check_args", "(", "self", ".", "sourcefile", ")", "self", ".", "_check_files", "(", "self", ".", "sourcefile", ")", "self", ".", "_check_dependencies", "(", "self", ".", "sourcefile", ")", "self", ".", "_check_run", "(", "self", ".", "sourcefile", ")" ]
Checks whether loaded yaml is well-formed according to syntax defined for version 0.9.0 and later. Raises: YamlError: (containing a meaningful message) when the loaded Yaml is not well formed
[ "Checks", "whether", "loaded", "yaml", "is", "well", "-", "formed", "according", "to", "syntax", "defined", "for", "version", "0", ".", "9", ".", "0", "and", "later", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_checker.py#L34-L54
devassistant/devassistant
devassistant/yaml_checker.py
YamlChecker._check_args
def _check_args(self, source): '''Validate the argument section. Args may be either a dict or a list (to allow multiple positional args). ''' path = [source] args = self.parsed_yaml.get('args', {}) self._assert_struct_type(args, 'args', (dict, list), path) path.append('args') if isinstance(args, dict): for argn, argattrs in args.items(): self._check_one_arg(path, argn, argattrs) else: # must be list - already asserted struct type for argdict in args: self._assert_command_dict(argdict, '[list-item]', path) argn, argattrs = list(argdict.items())[0] # safe - length asserted on previous line self._check_one_arg(path, argn, argattrs)
python
def _check_args(self, source): '''Validate the argument section. Args may be either a dict or a list (to allow multiple positional args). ''' path = [source] args = self.parsed_yaml.get('args', {}) self._assert_struct_type(args, 'args', (dict, list), path) path.append('args') if isinstance(args, dict): for argn, argattrs in args.items(): self._check_one_arg(path, argn, argattrs) else: # must be list - already asserted struct type for argdict in args: self._assert_command_dict(argdict, '[list-item]', path) argn, argattrs = list(argdict.items())[0] # safe - length asserted on previous line self._check_one_arg(path, argn, argattrs)
[ "def", "_check_args", "(", "self", ",", "source", ")", ":", "path", "=", "[", "source", "]", "args", "=", "self", ".", "parsed_yaml", ".", "get", "(", "'args'", ",", "{", "}", ")", "self", ".", "_assert_struct_type", "(", "args", ",", "'args'", ",", "(", "dict", ",", "list", ")", ",", "path", ")", "path", ".", "append", "(", "'args'", ")", "if", "isinstance", "(", "args", ",", "dict", ")", ":", "for", "argn", ",", "argattrs", "in", "args", ".", "items", "(", ")", ":", "self", ".", "_check_one_arg", "(", "path", ",", "argn", ",", "argattrs", ")", "else", ":", "# must be list - already asserted struct type", "for", "argdict", "in", "args", ":", "self", ".", "_assert_command_dict", "(", "argdict", ",", "'[list-item]'", ",", "path", ")", "argn", ",", "argattrs", "=", "list", "(", "argdict", ".", "items", "(", ")", ")", "[", "0", "]", "# safe - length asserted on previous line", "self", ".", "_check_one_arg", "(", "path", ",", "argn", ",", "argattrs", ")" ]
Validate the argument section. Args may be either a dict or a list (to allow multiple positional args).
[ "Validate", "the", "argument", "section", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_checker.py#L80-L96
devassistant/devassistant
devassistant/yaml_checker.py
YamlChecker._assert_command_dict
def _assert_command_dict(self, struct, name, path=None, extra_info=None): """Checks whether struct is a command dict (e.g. it's a dict and has 1 key-value pair.""" self._assert_dict(struct, name, path, extra_info) if len(struct) != 1: err = [self._format_error_path(path + [name])] err.append('Commands of run, dependencies, and argument sections must be mapping with ' 'exactly 1 key-value pair, got {0}: {1}'.format(len(struct), struct)) if extra_info: err.append(extra_info) raise exceptions.YamlSyntaxError('\n'.join(err))
python
def _assert_command_dict(self, struct, name, path=None, extra_info=None): """Checks whether struct is a command dict (e.g. it's a dict and has 1 key-value pair.""" self._assert_dict(struct, name, path, extra_info) if len(struct) != 1: err = [self._format_error_path(path + [name])] err.append('Commands of run, dependencies, and argument sections must be mapping with ' 'exactly 1 key-value pair, got {0}: {1}'.format(len(struct), struct)) if extra_info: err.append(extra_info) raise exceptions.YamlSyntaxError('\n'.join(err))
[ "def", "_assert_command_dict", "(", "self", ",", "struct", ",", "name", ",", "path", "=", "None", ",", "extra_info", "=", "None", ")", ":", "self", ".", "_assert_dict", "(", "struct", ",", "name", ",", "path", ",", "extra_info", ")", "if", "len", "(", "struct", ")", "!=", "1", ":", "err", "=", "[", "self", ".", "_format_error_path", "(", "path", "+", "[", "name", "]", ")", "]", "err", ".", "append", "(", "'Commands of run, dependencies, and argument sections must be mapping with '", "'exactly 1 key-value pair, got {0}: {1}'", ".", "format", "(", "len", "(", "struct", ")", ",", "struct", ")", ")", "if", "extra_info", ":", "err", ".", "append", "(", "extra_info", ")", "raise", "exceptions", ".", "YamlSyntaxError", "(", "'\\n'", ".", "join", "(", "err", ")", ")" ]
Checks whether struct is a command dict (e.g. it's a dict and has 1 key-value pair.
[ "Checks", "whether", "struct", "is", "a", "command", "dict", "(", "e", ".", "g", ".", "it", "s", "a", "dict", "and", "has", "1", "key", "-", "value", "pair", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_checker.py#L221-L230
devassistant/devassistant
devassistant/yaml_checker.py
YamlChecker._assert_struct_type
def _assert_struct_type(self, struct, name, types, path=None, extra_info=None): """Asserts that given structure is of any of given types. Args: struct: structure to check name: displayable name of the checked structure (e.g. "run_foo" for section run_foo) types: list/tuple of types that are allowed for given struct path: list with a source file as a first element and previous names (as in name argument to this method) as other elements extra_info: extra information to print if error is found (e.g. hint how to fix this) Raises: YamlTypeError: if given struct is not of any given type; error message contains source file and a "path" (e.g. args -> somearg -> flags) specifying where the problem is """ wanted_yaml_typenames = set() for t in types: wanted_yaml_typenames.add(self._get_yaml_typename(t)) wanted_yaml_typenames = ' or '.join(wanted_yaml_typenames) actual_yaml_typename = self._get_yaml_typename(type(struct)) if not isinstance(struct, types): err = [] if path: err.append(self._format_error_path(path + [name])) err.append(' Expected {w} value for "{n}", got value of type {a}: "{v}"'. format(w=wanted_yaml_typenames, n=name, a=actual_yaml_typename, v=struct)) if extra_info: err.append('Tip: ' + extra_info) raise exceptions.YamlTypeError('\n'.join(err))
python
def _assert_struct_type(self, struct, name, types, path=None, extra_info=None): """Asserts that given structure is of any of given types. Args: struct: structure to check name: displayable name of the checked structure (e.g. "run_foo" for section run_foo) types: list/tuple of types that are allowed for given struct path: list with a source file as a first element and previous names (as in name argument to this method) as other elements extra_info: extra information to print if error is found (e.g. hint how to fix this) Raises: YamlTypeError: if given struct is not of any given type; error message contains source file and a "path" (e.g. args -> somearg -> flags) specifying where the problem is """ wanted_yaml_typenames = set() for t in types: wanted_yaml_typenames.add(self._get_yaml_typename(t)) wanted_yaml_typenames = ' or '.join(wanted_yaml_typenames) actual_yaml_typename = self._get_yaml_typename(type(struct)) if not isinstance(struct, types): err = [] if path: err.append(self._format_error_path(path + [name])) err.append(' Expected {w} value for "{n}", got value of type {a}: "{v}"'. format(w=wanted_yaml_typenames, n=name, a=actual_yaml_typename, v=struct)) if extra_info: err.append('Tip: ' + extra_info) raise exceptions.YamlTypeError('\n'.join(err))
[ "def", "_assert_struct_type", "(", "self", ",", "struct", ",", "name", ",", "types", ",", "path", "=", "None", ",", "extra_info", "=", "None", ")", ":", "wanted_yaml_typenames", "=", "set", "(", ")", "for", "t", "in", "types", ":", "wanted_yaml_typenames", ".", "add", "(", "self", ".", "_get_yaml_typename", "(", "t", ")", ")", "wanted_yaml_typenames", "=", "' or '", ".", "join", "(", "wanted_yaml_typenames", ")", "actual_yaml_typename", "=", "self", ".", "_get_yaml_typename", "(", "type", "(", "struct", ")", ")", "if", "not", "isinstance", "(", "struct", ",", "types", ")", ":", "err", "=", "[", "]", "if", "path", ":", "err", ".", "append", "(", "self", ".", "_format_error_path", "(", "path", "+", "[", "name", "]", ")", ")", "err", ".", "append", "(", "' Expected {w} value for \"{n}\", got value of type {a}: \"{v}\"'", ".", "format", "(", "w", "=", "wanted_yaml_typenames", ",", "n", "=", "name", ",", "a", "=", "actual_yaml_typename", ",", "v", "=", "struct", ")", ")", "if", "extra_info", ":", "err", ".", "append", "(", "'Tip: '", "+", "extra_info", ")", "raise", "exceptions", ".", "YamlTypeError", "(", "'\\n'", ".", "join", "(", "err", ")", ")" ]
Asserts that given structure is of any of given types. Args: struct: structure to check name: displayable name of the checked structure (e.g. "run_foo" for section run_foo) types: list/tuple of types that are allowed for given struct path: list with a source file as a first element and previous names (as in name argument to this method) as other elements extra_info: extra information to print if error is found (e.g. hint how to fix this) Raises: YamlTypeError: if given struct is not of any given type; error message contains source file and a "path" (e.g. args -> somearg -> flags) specifying where the problem is
[ "Asserts", "that", "given", "structure", "is", "of", "any", "of", "given", "types", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_checker.py#L242-L273
devassistant/devassistant
devassistant/dapi/licenses.py
_split_license
def _split_license(license): '''Returns all individual licenses in the input''' return (x.strip() for x in (l for l in _regex.split(license) if l))
python
def _split_license(license): '''Returns all individual licenses in the input''' return (x.strip() for x in (l for l in _regex.split(license) if l))
[ "def", "_split_license", "(", "license", ")", ":", "return", "(", "x", ".", "strip", "(", ")", "for", "x", "in", "(", "l", "for", "l", "in", "_regex", ".", "split", "(", "license", ")", "if", "l", ")", ")" ]
Returns all individual licenses in the input
[ "Returns", "all", "individual", "licenses", "in", "the", "input" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/licenses.py#L47-L49
devassistant/devassistant
devassistant/dapi/licenses.py
match
def match(license): '''Returns True if given license field is correct Taken from rpmlint. It's named match() to mimic a compiled regexp.''' if license not in VALID_LICENSES: for l1 in _split_license(license): if l1 in VALID_LICENSES: continue for l2 in _split_license(l1): if l2 not in VALID_LICENSES: return False valid_license = False return True
python
def match(license): '''Returns True if given license field is correct Taken from rpmlint. It's named match() to mimic a compiled regexp.''' if license not in VALID_LICENSES: for l1 in _split_license(license): if l1 in VALID_LICENSES: continue for l2 in _split_license(l1): if l2 not in VALID_LICENSES: return False valid_license = False return True
[ "def", "match", "(", "license", ")", ":", "if", "license", "not", "in", "VALID_LICENSES", ":", "for", "l1", "in", "_split_license", "(", "license", ")", ":", "if", "l1", "in", "VALID_LICENSES", ":", "continue", "for", "l2", "in", "_split_license", "(", "l1", ")", ":", "if", "l2", "not", "in", "VALID_LICENSES", ":", "return", "False", "valid_license", "=", "False", "return", "True" ]
Returns True if given license field is correct Taken from rpmlint. It's named match() to mimic a compiled regexp.
[ "Returns", "True", "if", "given", "license", "field", "is", "correct", "Taken", "from", "rpmlint", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/licenses.py#L52-L65
devassistant/devassistant
devassistant/command_runners.py
register_command_runner
def register_command_runner(arg): """Decorator that registers a command runner. Accepts either: - CommandRunner directly or - String prefix to register a command runner under (returning a decorator) """ if isinstance(arg, str): def inner(command_runner): command_runners.setdefault(arg, []) command_runners[arg].append(command_runner) return command_runner return inner elif issubclass(arg, CommandRunner): command_runners.setdefault('', []) command_runners[''].append(arg) return arg else: msg = 'register_command_runner expects str or CommandRunner as argument, got: {0}'.\ format(arg) raise ValueError(msg)
python
def register_command_runner(arg): """Decorator that registers a command runner. Accepts either: - CommandRunner directly or - String prefix to register a command runner under (returning a decorator) """ if isinstance(arg, str): def inner(command_runner): command_runners.setdefault(arg, []) command_runners[arg].append(command_runner) return command_runner return inner elif issubclass(arg, CommandRunner): command_runners.setdefault('', []) command_runners[''].append(arg) return arg else: msg = 'register_command_runner expects str or CommandRunner as argument, got: {0}'.\ format(arg) raise ValueError(msg)
[ "def", "register_command_runner", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "str", ")", ":", "def", "inner", "(", "command_runner", ")", ":", "command_runners", ".", "setdefault", "(", "arg", ",", "[", "]", ")", "command_runners", "[", "arg", "]", ".", "append", "(", "command_runner", ")", "return", "command_runner", "return", "inner", "elif", "issubclass", "(", "arg", ",", "CommandRunner", ")", ":", "command_runners", ".", "setdefault", "(", "''", ",", "[", "]", ")", "command_runners", "[", "''", "]", ".", "append", "(", "arg", ")", "return", "arg", "else", ":", "msg", "=", "'register_command_runner expects str or CommandRunner as argument, got: {0}'", ".", "format", "(", "arg", ")", "raise", "ValueError", "(", "msg", ")" ]
Decorator that registers a command runner. Accepts either: - CommandRunner directly or - String prefix to register a command runner under (returning a decorator)
[ "Decorator", "that", "registers", "a", "command", "runner", ".", "Accepts", "either", ":" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/command_runners.py#L42-L61
devassistant/devassistant
devassistant/dapi/dapver.py
compare
def compare(ver1, ver2): '''Version comparing, returns 0 if are the same, returns >0 if first is bigger, <0 if first is smaller, excepts valid version''' if ver1 == ver2: return 0 ver1 = _cut(ver1) ver2 = _cut(ver2) # magic multiplier m = 1 # if the first one is shorter, replace them if len(ver1) < len(ver2): ver1, ver2 = ver2, ver1 # and reverse magic multiplier m = -1 # compare all items that both have for i, part in enumerate(ver2): if ver1[i] > ver2[i]: return m * 1 if ver1[i] < ver2[i]: return m * -1 # if the first "extra" item is not negative, it's bigger if ver1[len(ver2)] >= 0: return m * 1 else: return m * -1
python
def compare(ver1, ver2): '''Version comparing, returns 0 if are the same, returns >0 if first is bigger, <0 if first is smaller, excepts valid version''' if ver1 == ver2: return 0 ver1 = _cut(ver1) ver2 = _cut(ver2) # magic multiplier m = 1 # if the first one is shorter, replace them if len(ver1) < len(ver2): ver1, ver2 = ver2, ver1 # and reverse magic multiplier m = -1 # compare all items that both have for i, part in enumerate(ver2): if ver1[i] > ver2[i]: return m * 1 if ver1[i] < ver2[i]: return m * -1 # if the first "extra" item is not negative, it's bigger if ver1[len(ver2)] >= 0: return m * 1 else: return m * -1
[ "def", "compare", "(", "ver1", ",", "ver2", ")", ":", "if", "ver1", "==", "ver2", ":", "return", "0", "ver1", "=", "_cut", "(", "ver1", ")", "ver2", "=", "_cut", "(", "ver2", ")", "# magic multiplier", "m", "=", "1", "# if the first one is shorter, replace them", "if", "len", "(", "ver1", ")", "<", "len", "(", "ver2", ")", ":", "ver1", ",", "ver2", "=", "ver2", ",", "ver1", "# and reverse magic multiplier", "m", "=", "-", "1", "# compare all items that both have", "for", "i", ",", "part", "in", "enumerate", "(", "ver2", ")", ":", "if", "ver1", "[", "i", "]", ">", "ver2", "[", "i", "]", ":", "return", "m", "*", "1", "if", "ver1", "[", "i", "]", "<", "ver2", "[", "i", "]", ":", "return", "m", "*", "-", "1", "# if the first \"extra\" item is not negative, it's bigger", "if", "ver1", "[", "len", "(", "ver2", ")", "]", ">=", "0", ":", "return", "m", "*", "1", "else", ":", "return", "m", "*", "-", "1" ]
Version comparing, returns 0 if are the same, returns >0 if first is bigger, <0 if first is smaller, excepts valid version
[ "Version", "comparing", "returns", "0", "if", "are", "the", "same", "returns", ">", "0", "if", "first", "is", "bigger", "<0", "if", "first", "is", "smaller", "excepts", "valid", "version" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapver.py#L1-L26
devassistant/devassistant
devassistant/dapi/dapver.py
_cut
def _cut(ver): '''Cuts the version to array, excepts valid version''' ver = ver.split('.') for i, part in enumerate(ver): try: ver[i] = int(part) except: if part[-len('dev'):] == 'dev': ver[i] = int(part[:-len('dev')]) ver.append(-3) else: ver[i] = int(part[:-len('a')]) if part[-len('a'):] == 'a': ver.append(-2) else: ver.append(-1) return ver
python
def _cut(ver): '''Cuts the version to array, excepts valid version''' ver = ver.split('.') for i, part in enumerate(ver): try: ver[i] = int(part) except: if part[-len('dev'):] == 'dev': ver[i] = int(part[:-len('dev')]) ver.append(-3) else: ver[i] = int(part[:-len('a')]) if part[-len('a'):] == 'a': ver.append(-2) else: ver.append(-1) return ver
[ "def", "_cut", "(", "ver", ")", ":", "ver", "=", "ver", ".", "split", "(", "'.'", ")", "for", "i", ",", "part", "in", "enumerate", "(", "ver", ")", ":", "try", ":", "ver", "[", "i", "]", "=", "int", "(", "part", ")", "except", ":", "if", "part", "[", "-", "len", "(", "'dev'", ")", ":", "]", "==", "'dev'", ":", "ver", "[", "i", "]", "=", "int", "(", "part", "[", ":", "-", "len", "(", "'dev'", ")", "]", ")", "ver", ".", "append", "(", "-", "3", ")", "else", ":", "ver", "[", "i", "]", "=", "int", "(", "part", "[", ":", "-", "len", "(", "'a'", ")", "]", ")", "if", "part", "[", "-", "len", "(", "'a'", ")", ":", "]", "==", "'a'", ":", "ver", ".", "append", "(", "-", "2", ")", "else", ":", "ver", ".", "append", "(", "-", "1", ")", "return", "ver" ]
Cuts the version to array, excepts valid version
[ "Cuts", "the", "version", "to", "array", "excepts", "valid", "version" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapver.py#L29-L45
devassistant/devassistant
devassistant/cli/argparse_generator.py
ArgparseGenerator.generate_argument_parser
def generate_argument_parser(cls, tree, actions={}): """Generates argument parser for given assistant tree and actions. Args: tree: assistant tree as returned by devassistant.assistant_base.AssistantBase.get_subassistant_tree actions: dict mapping actions (devassistant.actions.Action subclasses) to their subaction dicts Returns: instance of devassistant_argparse.ArgumentParser (subclass of argparse.ArgumentParser) """ cur_as, cur_subas = tree parser = devassistant_argparse.ArgumentParser(argument_default=argparse.SUPPRESS, usage=argparse.SUPPRESS, add_help=False) cls.add_default_arguments_to(parser) # add any arguments of the top assistant for arg in cur_as.args: arg.add_argument_to(parser) if cur_subas or actions: # then add the subassistants as arguments subparsers = cls._add_subparsers_required(parser, dest=settings.SUBASSISTANT_N_STRING.format('0')) for subas in sorted(cur_subas, key=lambda x: x[0].name): for alias in [subas[0].name] + getattr(subas[0], 'aliases', []): cls.add_subassistants_to(subparsers, subas, level=1, alias=alias) for action, subactions in sorted(actions.items(), key=lambda x: x[0].name): cls.add_action_to(subparsers, action, subactions, level=1) return parser
python
def generate_argument_parser(cls, tree, actions={}): """Generates argument parser for given assistant tree and actions. Args: tree: assistant tree as returned by devassistant.assistant_base.AssistantBase.get_subassistant_tree actions: dict mapping actions (devassistant.actions.Action subclasses) to their subaction dicts Returns: instance of devassistant_argparse.ArgumentParser (subclass of argparse.ArgumentParser) """ cur_as, cur_subas = tree parser = devassistant_argparse.ArgumentParser(argument_default=argparse.SUPPRESS, usage=argparse.SUPPRESS, add_help=False) cls.add_default_arguments_to(parser) # add any arguments of the top assistant for arg in cur_as.args: arg.add_argument_to(parser) if cur_subas or actions: # then add the subassistants as arguments subparsers = cls._add_subparsers_required(parser, dest=settings.SUBASSISTANT_N_STRING.format('0')) for subas in sorted(cur_subas, key=lambda x: x[0].name): for alias in [subas[0].name] + getattr(subas[0], 'aliases', []): cls.add_subassistants_to(subparsers, subas, level=1, alias=alias) for action, subactions in sorted(actions.items(), key=lambda x: x[0].name): cls.add_action_to(subparsers, action, subactions, level=1) return parser
[ "def", "generate_argument_parser", "(", "cls", ",", "tree", ",", "actions", "=", "{", "}", ")", ":", "cur_as", ",", "cur_subas", "=", "tree", "parser", "=", "devassistant_argparse", ".", "ArgumentParser", "(", "argument_default", "=", "argparse", ".", "SUPPRESS", ",", "usage", "=", "argparse", ".", "SUPPRESS", ",", "add_help", "=", "False", ")", "cls", ".", "add_default_arguments_to", "(", "parser", ")", "# add any arguments of the top assistant", "for", "arg", "in", "cur_as", ".", "args", ":", "arg", ".", "add_argument_to", "(", "parser", ")", "if", "cur_subas", "or", "actions", ":", "# then add the subassistants as arguments", "subparsers", "=", "cls", ".", "_add_subparsers_required", "(", "parser", ",", "dest", "=", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "'0'", ")", ")", "for", "subas", "in", "sorted", "(", "cur_subas", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "name", ")", ":", "for", "alias", "in", "[", "subas", "[", "0", "]", ".", "name", "]", "+", "getattr", "(", "subas", "[", "0", "]", ",", "'aliases'", ",", "[", "]", ")", ":", "cls", ".", "add_subassistants_to", "(", "subparsers", ",", "subas", ",", "level", "=", "1", ",", "alias", "=", "alias", ")", "for", "action", ",", "subactions", "in", "sorted", "(", "actions", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "name", ")", ":", "cls", ".", "add_action_to", "(", "subparsers", ",", "action", ",", "subactions", ",", "level", "=", "1", ")", "return", "parser" ]
Generates argument parser for given assistant tree and actions. Args: tree: assistant tree as returned by devassistant.assistant_base.AssistantBase.get_subassistant_tree actions: dict mapping actions (devassistant.actions.Action subclasses) to their subaction dicts Returns: instance of devassistant_argparse.ArgumentParser (subclass of argparse.ArgumentParser)
[ "Generates", "argument", "parser", "for", "given", "assistant", "tree", "and", "actions", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cli/argparse_generator.py#L15-L48
devassistant/devassistant
devassistant/cli/argparse_generator.py
ArgparseGenerator.add_subassistants_to
def add_subassistants_to(cls, parser, assistant_tuple, level, alias=None): """Adds assistant from given part of assistant tree and all its subassistants to a given argument parser. Args: parser: instance of devassistant_argparse.ArgumentParser assistant_tuple: part of assistant tree (see generate_argument_parser doc) level: level of subassistants that given assistant is at """ name = alias or assistant_tuple[0].name p = parser.add_parser(name, description=assistant_tuple[0].description, argument_default=argparse.SUPPRESS) for arg in assistant_tuple[0].args: arg.add_argument_to(p) if len(assistant_tuple[1]) > 0: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subparsers_str, description=cls.subparsers_desc) for subas_tuple in sorted(assistant_tuple[1], key=lambda x: x[0].name): cls.add_subassistants_to(subparsers, subas_tuple, level + 1) elif level == 1: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subparsers_str, description=devassistant_argparse.ArgumentParser.no_assistants_msg)
python
def add_subassistants_to(cls, parser, assistant_tuple, level, alias=None): """Adds assistant from given part of assistant tree and all its subassistants to a given argument parser. Args: parser: instance of devassistant_argparse.ArgumentParser assistant_tuple: part of assistant tree (see generate_argument_parser doc) level: level of subassistants that given assistant is at """ name = alias or assistant_tuple[0].name p = parser.add_parser(name, description=assistant_tuple[0].description, argument_default=argparse.SUPPRESS) for arg in assistant_tuple[0].args: arg.add_argument_to(p) if len(assistant_tuple[1]) > 0: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subparsers_str, description=cls.subparsers_desc) for subas_tuple in sorted(assistant_tuple[1], key=lambda x: x[0].name): cls.add_subassistants_to(subparsers, subas_tuple, level + 1) elif level == 1: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subparsers_str, description=devassistant_argparse.ArgumentParser.no_assistants_msg)
[ "def", "add_subassistants_to", "(", "cls", ",", "parser", ",", "assistant_tuple", ",", "level", ",", "alias", "=", "None", ")", ":", "name", "=", "alias", "or", "assistant_tuple", "[", "0", "]", ".", "name", "p", "=", "parser", ".", "add_parser", "(", "name", ",", "description", "=", "assistant_tuple", "[", "0", "]", ".", "description", ",", "argument_default", "=", "argparse", ".", "SUPPRESS", ")", "for", "arg", "in", "assistant_tuple", "[", "0", "]", ".", "args", ":", "arg", ".", "add_argument_to", "(", "p", ")", "if", "len", "(", "assistant_tuple", "[", "1", "]", ")", ">", "0", ":", "subparsers", "=", "cls", ".", "_add_subparsers_required", "(", "p", ",", "dest", "=", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "level", ")", ",", "title", "=", "cls", ".", "subparsers_str", ",", "description", "=", "cls", ".", "subparsers_desc", ")", "for", "subas_tuple", "in", "sorted", "(", "assistant_tuple", "[", "1", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "name", ")", ":", "cls", ".", "add_subassistants_to", "(", "subparsers", ",", "subas_tuple", ",", "level", "+", "1", ")", "elif", "level", "==", "1", ":", "subparsers", "=", "cls", ".", "_add_subparsers_required", "(", "p", ",", "dest", "=", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "level", ")", ",", "title", "=", "cls", ".", "subparsers_str", ",", "description", "=", "devassistant_argparse", ".", "ArgumentParser", ".", "no_assistants_msg", ")" ]
Adds assistant from given part of assistant tree and all its subassistants to a given argument parser. Args: parser: instance of devassistant_argparse.ArgumentParser assistant_tuple: part of assistant tree (see generate_argument_parser doc) level: level of subassistants that given assistant is at
[ "Adds", "assistant", "from", "given", "part", "of", "assistant", "tree", "and", "all", "its", "subassistants", "to", "a", "given", "argument", "parser", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cli/argparse_generator.py#L61-L88
devassistant/devassistant
devassistant/cli/argparse_generator.py
ArgparseGenerator.add_action_to
def add_action_to(cls, parser, action, subactions, level): """Adds given action to given parser Args: parser: instance of devassistant_argparse.ArgumentParser action: devassistant.actions.Action subclass subactions: dict with subactions - {SubA: {SubB: {}}, SubC: {}} """ p = parser.add_parser(action.name, description=action.description, argument_default=argparse.SUPPRESS) for arg in action.args: arg.add_argument_to(p) if subactions: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subactions_str, description=cls.subactions_desc) for subact, subsubacts in sorted(subactions.items(), key=lambda x: x[0].name): cls.add_action_to(subparsers, subact, subsubacts, level + 1)
python
def add_action_to(cls, parser, action, subactions, level): """Adds given action to given parser Args: parser: instance of devassistant_argparse.ArgumentParser action: devassistant.actions.Action subclass subactions: dict with subactions - {SubA: {SubB: {}}, SubC: {}} """ p = parser.add_parser(action.name, description=action.description, argument_default=argparse.SUPPRESS) for arg in action.args: arg.add_argument_to(p) if subactions: subparsers = cls._add_subparsers_required(p, dest=settings.SUBASSISTANT_N_STRING.format(level), title=cls.subactions_str, description=cls.subactions_desc) for subact, subsubacts in sorted(subactions.items(), key=lambda x: x[0].name): cls.add_action_to(subparsers, subact, subsubacts, level + 1)
[ "def", "add_action_to", "(", "cls", ",", "parser", ",", "action", ",", "subactions", ",", "level", ")", ":", "p", "=", "parser", ".", "add_parser", "(", "action", ".", "name", ",", "description", "=", "action", ".", "description", ",", "argument_default", "=", "argparse", ".", "SUPPRESS", ")", "for", "arg", "in", "action", ".", "args", ":", "arg", ".", "add_argument_to", "(", "p", ")", "if", "subactions", ":", "subparsers", "=", "cls", ".", "_add_subparsers_required", "(", "p", ",", "dest", "=", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "level", ")", ",", "title", "=", "cls", ".", "subactions_str", ",", "description", "=", "cls", ".", "subactions_desc", ")", "for", "subact", ",", "subsubacts", "in", "sorted", "(", "subactions", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "name", ")", ":", "cls", ".", "add_action_to", "(", "subparsers", ",", "subact", ",", "subsubacts", ",", "level", "+", "1", ")" ]
Adds given action to given parser Args: parser: instance of devassistant_argparse.ArgumentParser action: devassistant.actions.Action subclass subactions: dict with subactions - {SubA: {SubB: {}}, SubC: {}}
[ "Adds", "given", "action", "to", "given", "parser" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/cli/argparse_generator.py#L91-L111
devassistant/devassistant
devassistant/gui/run_window.py
format_entry
def format_entry(record, show_level=False, colorize=False): """ Format a log entry according to its level and context """ if show_level: log_str = u'{}: {}'.format(record.levelname, record.getMessage()) else: log_str = record.getMessage() if colorize and record.levelname in LOG_COLORS: log_str = u'<span color="{}">'.format(LOG_COLORS[record.levelname]) + log_str + u'</span>' return log_str
python
def format_entry(record, show_level=False, colorize=False): """ Format a log entry according to its level and context """ if show_level: log_str = u'{}: {}'.format(record.levelname, record.getMessage()) else: log_str = record.getMessage() if colorize and record.levelname in LOG_COLORS: log_str = u'<span color="{}">'.format(LOG_COLORS[record.levelname]) + log_str + u'</span>' return log_str
[ "def", "format_entry", "(", "record", ",", "show_level", "=", "False", ",", "colorize", "=", "False", ")", ":", "if", "show_level", ":", "log_str", "=", "u'{}: {}'", ".", "format", "(", "record", ".", "levelname", ",", "record", ".", "getMessage", "(", ")", ")", "else", ":", "log_str", "=", "record", ".", "getMessage", "(", ")", "if", "colorize", "and", "record", ".", "levelname", "in", "LOG_COLORS", ":", "log_str", "=", "u'<span color=\"{}\">'", ".", "format", "(", "LOG_COLORS", "[", "record", ".", "levelname", "]", ")", "+", "log_str", "+", "u'</span>'", "return", "log_str" ]
Format a log entry according to its level and context
[ "Format", "a", "log", "entry", "according", "to", "its", "level", "and", "context" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/run_window.py#L28-L40
devassistant/devassistant
devassistant/gui/run_window.py
switch_cursor
def switch_cursor(cursor_type, parent_window): """ Functions switches the cursor to cursor type """ watch = Gdk.Cursor(cursor_type) window = parent_window.get_root_window() window.set_cursor(watch)
python
def switch_cursor(cursor_type, parent_window): """ Functions switches the cursor to cursor type """ watch = Gdk.Cursor(cursor_type) window = parent_window.get_root_window() window.set_cursor(watch)
[ "def", "switch_cursor", "(", "cursor_type", ",", "parent_window", ")", ":", "watch", "=", "Gdk", ".", "Cursor", "(", "cursor_type", ")", "window", "=", "parent_window", ".", "get_root_window", "(", ")", "window", ".", "set_cursor", "(", "watch", ")" ]
Functions switches the cursor to cursor type
[ "Functions", "switches", "the", "cursor", "to", "cursor", "type" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/run_window.py#L42-L48
devassistant/devassistant
devassistant/gui/run_window.py
RunLoggingHandler.emit
def emit(self, record): """ Function inserts log messages to list_view """ msg = record.getMessage() list_store = self.list_view.get_model() Gdk.threads_enter() if msg: # Underline URLs in the record message msg = replace_markup_chars(record.getMessage()) record.msg = URL_FINDER.sub(r'<u>\1</u>', msg) self.parent.debug_logs['logs'].append(record) # During execution if level is bigger then DEBUG # then GUI shows the message. event_type = getattr(record, 'event_type', '') if event_type: if event_type == 'dep_installation_start': switch_cursor(Gdk.CursorType.WATCH, self.parent.run_window) list_store.append([format_entry(record)]) if event_type == 'dep_installation_end': switch_cursor(Gdk.CursorType.ARROW, self.parent.run_window) if not self.parent.debugging: # We will show only INFO messages and messages who have no dep_ event_type if int(record.levelno) > 10: if event_type == "dep_check" or event_type == "dep_found": list_store.append([format_entry(record)]) elif not event_type.startswith("dep_"): list_store.append([format_entry(record, colorize=True)]) if self.parent.debugging: if event_type != "cmd_retcode": list_store.append([format_entry(record, show_level=True, colorize=True)]) Gdk.threads_leave()
python
def emit(self, record): """ Function inserts log messages to list_view """ msg = record.getMessage() list_store = self.list_view.get_model() Gdk.threads_enter() if msg: # Underline URLs in the record message msg = replace_markup_chars(record.getMessage()) record.msg = URL_FINDER.sub(r'<u>\1</u>', msg) self.parent.debug_logs['logs'].append(record) # During execution if level is bigger then DEBUG # then GUI shows the message. event_type = getattr(record, 'event_type', '') if event_type: if event_type == 'dep_installation_start': switch_cursor(Gdk.CursorType.WATCH, self.parent.run_window) list_store.append([format_entry(record)]) if event_type == 'dep_installation_end': switch_cursor(Gdk.CursorType.ARROW, self.parent.run_window) if not self.parent.debugging: # We will show only INFO messages and messages who have no dep_ event_type if int(record.levelno) > 10: if event_type == "dep_check" or event_type == "dep_found": list_store.append([format_entry(record)]) elif not event_type.startswith("dep_"): list_store.append([format_entry(record, colorize=True)]) if self.parent.debugging: if event_type != "cmd_retcode": list_store.append([format_entry(record, show_level=True, colorize=True)]) Gdk.threads_leave()
[ "def", "emit", "(", "self", ",", "record", ")", ":", "msg", "=", "record", ".", "getMessage", "(", ")", "list_store", "=", "self", ".", "list_view", ".", "get_model", "(", ")", "Gdk", ".", "threads_enter", "(", ")", "if", "msg", ":", "# Underline URLs in the record message", "msg", "=", "replace_markup_chars", "(", "record", ".", "getMessage", "(", ")", ")", "record", ".", "msg", "=", "URL_FINDER", ".", "sub", "(", "r'<u>\\1</u>'", ",", "msg", ")", "self", ".", "parent", ".", "debug_logs", "[", "'logs'", "]", ".", "append", "(", "record", ")", "# During execution if level is bigger then DEBUG", "# then GUI shows the message.", "event_type", "=", "getattr", "(", "record", ",", "'event_type'", ",", "''", ")", "if", "event_type", ":", "if", "event_type", "==", "'dep_installation_start'", ":", "switch_cursor", "(", "Gdk", ".", "CursorType", ".", "WATCH", ",", "self", ".", "parent", ".", "run_window", ")", "list_store", ".", "append", "(", "[", "format_entry", "(", "record", ")", "]", ")", "if", "event_type", "==", "'dep_installation_end'", ":", "switch_cursor", "(", "Gdk", ".", "CursorType", ".", "ARROW", ",", "self", ".", "parent", ".", "run_window", ")", "if", "not", "self", ".", "parent", ".", "debugging", ":", "# We will show only INFO messages and messages who have no dep_ event_type", "if", "int", "(", "record", ".", "levelno", ")", ">", "10", ":", "if", "event_type", "==", "\"dep_check\"", "or", "event_type", "==", "\"dep_found\"", ":", "list_store", ".", "append", "(", "[", "format_entry", "(", "record", ")", "]", ")", "elif", "not", "event_type", ".", "startswith", "(", "\"dep_\"", ")", ":", "list_store", ".", "append", "(", "[", "format_entry", "(", "record", ",", "colorize", "=", "True", ")", "]", ")", "if", "self", ".", "parent", ".", "debugging", ":", "if", "event_type", "!=", "\"cmd_retcode\"", ":", "list_store", ".", "append", "(", "[", "format_entry", "(", "record", ",", "show_level", "=", "True", ",", "colorize", "=", "True", ")", "]", ")", "Gdk", ".", "threads_leave", "(", ")" ]
Function inserts log messages to list_view
[ "Function", "inserts", "log", "messages", "to", "list_view" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/run_window.py#L62-L93
devassistant/devassistant
devassistant/gui/run_window.py
RunWindow.open_window
def open_window(self, widget, data=None): """ Function opens the run window """ if data is not None: self.kwargs = data.get('kwargs', None) self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assistant', None) self.debugging = data.get('debugging', False) if not self.debugging: self.debug_btn.set_label('Debug logs') else: self.debug_btn.set_label('Info logs') self.store.clear() self.debug_logs = dict() self.debug_logs['logs'] = list() self.thread = threading.Thread(target=self.dev_assistant_start) # We need only project name for github project_name = self.parent.path_window.get_data()[1] if self.kwargs.get('github'): self.link = self.gui_helper.create_link_button( "Link to project on Github", "http://www.github.com/{0}/{1}".format(self.kwargs.get('github'), project_name)) self.link.set_border_width(6) self.link.set_sensitive(False) self.info_box.pack_start(self.link, False, False, 12) self.run_list_view.connect('size-allocate', self.list_view_changed) # We need to be in /home directory before each project creations os.chdir(os.path.expanduser('~')) self.run_window.show_all() self.disable_buttons() self.thread.start()
python
def open_window(self, widget, data=None): """ Function opens the run window """ if data is not None: self.kwargs = data.get('kwargs', None) self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assistant', None) self.debugging = data.get('debugging', False) if not self.debugging: self.debug_btn.set_label('Debug logs') else: self.debug_btn.set_label('Info logs') self.store.clear() self.debug_logs = dict() self.debug_logs['logs'] = list() self.thread = threading.Thread(target=self.dev_assistant_start) # We need only project name for github project_name = self.parent.path_window.get_data()[1] if self.kwargs.get('github'): self.link = self.gui_helper.create_link_button( "Link to project on Github", "http://www.github.com/{0}/{1}".format(self.kwargs.get('github'), project_name)) self.link.set_border_width(6) self.link.set_sensitive(False) self.info_box.pack_start(self.link, False, False, 12) self.run_list_view.connect('size-allocate', self.list_view_changed) # We need to be in /home directory before each project creations os.chdir(os.path.expanduser('~')) self.run_window.show_all() self.disable_buttons() self.thread.start()
[ "def", "open_window", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "if", "data", "is", "not", "None", ":", "self", ".", "kwargs", "=", "data", ".", "get", "(", "'kwargs'", ",", "None", ")", "self", ".", "top_assistant", "=", "data", ".", "get", "(", "'top_assistant'", ",", "None", ")", "self", ".", "current_main_assistant", "=", "data", ".", "get", "(", "'current_main_assistant'", ",", "None", ")", "self", ".", "debugging", "=", "data", ".", "get", "(", "'debugging'", ",", "False", ")", "if", "not", "self", ".", "debugging", ":", "self", ".", "debug_btn", ".", "set_label", "(", "'Debug logs'", ")", "else", ":", "self", ".", "debug_btn", ".", "set_label", "(", "'Info logs'", ")", "self", ".", "store", ".", "clear", "(", ")", "self", ".", "debug_logs", "=", "dict", "(", ")", "self", ".", "debug_logs", "[", "'logs'", "]", "=", "list", "(", ")", "self", ".", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "dev_assistant_start", ")", "# We need only project name for github", "project_name", "=", "self", ".", "parent", ".", "path_window", ".", "get_data", "(", ")", "[", "1", "]", "if", "self", ".", "kwargs", ".", "get", "(", "'github'", ")", ":", "self", ".", "link", "=", "self", ".", "gui_helper", ".", "create_link_button", "(", "\"Link to project on Github\"", ",", "\"http://www.github.com/{0}/{1}\"", ".", "format", "(", "self", ".", "kwargs", ".", "get", "(", "'github'", ")", ",", "project_name", ")", ")", "self", ".", "link", ".", "set_border_width", "(", "6", ")", "self", ".", "link", ".", "set_sensitive", "(", "False", ")", "self", ".", "info_box", ".", "pack_start", "(", "self", ".", "link", ",", "False", ",", "False", ",", "12", ")", "self", ".", "run_list_view", ".", "connect", "(", "'size-allocate'", ",", "self", ".", "list_view_changed", ")", "# We need to be in /home directory before each project creations", "os", ".", "chdir", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ")", "self", ".", "run_window", ".", "show_all", "(", ")", "self", ".", "disable_buttons", "(", ")", "self", ".", "thread", ".", "start", "(", ")" ]
Function opens the run window
[ "Function", "opens", "the", "run", "window" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/run_window.py#L144-L175
devassistant/devassistant
devassistant/gui/run_window.py
RunWindow.remove_link_button
def remove_link_button(self): """ Function removes link button from Run Window """ if self.link is not None: self.info_box.remove(self.link) self.link.destroy() self.link = None
python
def remove_link_button(self): """ Function removes link button from Run Window """ if self.link is not None: self.info_box.remove(self.link) self.link.destroy() self.link = None
[ "def", "remove_link_button", "(", "self", ")", ":", "if", "self", ".", "link", "is", "not", "None", ":", "self", ".", "info_box", ".", "remove", "(", "self", ".", "link", ")", "self", ".", "link", ".", "destroy", "(", ")", "self", ".", "link", "=", "None" ]
Function removes link button from Run Window
[ "Function", "removes", "link", "button", "from", "Run", "Window" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/run_window.py#L183-L190
devassistant/devassistant
devassistant/gui/run_window.py
RunWindow.delete_event
def delete_event(self, widget, event, data=None): """ Event cancels the project creation """ if not self.close_win: if self.thread.isAlive(): dlg = self.gui_helper.create_message_dialog("Do you want to cancel project creation?", buttons=Gtk.ButtonsType.YES_NO) response = dlg.run() if response == Gtk.ResponseType.YES: if self.thread.isAlive(): self.info_label.set_label('<span color="#FFA500">Cancelling...</span>') self.dev_assistant_runner.stop() self.project_canceled = True else: self.info_label.set_label('<span color="#008000">Done</span>') self.allow_close_window() dlg.destroy() return True else: return False
python
def delete_event(self, widget, event, data=None): """ Event cancels the project creation """ if not self.close_win: if self.thread.isAlive(): dlg = self.gui_helper.create_message_dialog("Do you want to cancel project creation?", buttons=Gtk.ButtonsType.YES_NO) response = dlg.run() if response == Gtk.ResponseType.YES: if self.thread.isAlive(): self.info_label.set_label('<span color="#FFA500">Cancelling...</span>') self.dev_assistant_runner.stop() self.project_canceled = True else: self.info_label.set_label('<span color="#008000">Done</span>') self.allow_close_window() dlg.destroy() return True else: return False
[ "def", "delete_event", "(", "self", ",", "widget", ",", "event", ",", "data", "=", "None", ")", ":", "if", "not", "self", ".", "close_win", ":", "if", "self", ".", "thread", ".", "isAlive", "(", ")", ":", "dlg", "=", "self", ".", "gui_helper", ".", "create_message_dialog", "(", "\"Do you want to cancel project creation?\"", ",", "buttons", "=", "Gtk", ".", "ButtonsType", ".", "YES_NO", ")", "response", "=", "dlg", ".", "run", "(", ")", "if", "response", "==", "Gtk", ".", "ResponseType", ".", "YES", ":", "if", "self", ".", "thread", ".", "isAlive", "(", ")", ":", "self", ".", "info_label", ".", "set_label", "(", "'<span color=\"#FFA500\">Cancelling...</span>'", ")", "self", ".", "dev_assistant_runner", ".", "stop", "(", ")", "self", ".", "project_canceled", "=", "True", "else", ":", "self", ".", "info_label", ".", "set_label", "(", "'<span color=\"#008000\">Done</span>'", ")", "self", ".", "allow_close_window", "(", ")", "dlg", ".", "destroy", "(", ")", "return", "True", "else", ":", "return", "False" ]
Event cancels the project creation
[ "Event", "cancels", "the", "project", "creation" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/run_window.py#L192-L212
devassistant/devassistant
devassistant/gui/run_window.py
RunWindow.list_view_changed
def list_view_changed(self, widget, event, data=None): """ Function shows last rows. """ adj = self.scrolled_window.get_vadjustment() adj.set_value(adj.get_upper() - adj.get_page_size())
python
def list_view_changed(self, widget, event, data=None): """ Function shows last rows. """ adj = self.scrolled_window.get_vadjustment() adj.set_value(adj.get_upper() - adj.get_page_size())
[ "def", "list_view_changed", "(", "self", ",", "widget", ",", "event", ",", "data", "=", "None", ")", ":", "adj", "=", "self", ".", "scrolled_window", ".", "get_vadjustment", "(", ")", "adj", ".", "set_value", "(", "adj", ".", "get_upper", "(", ")", "-", "adj", ".", "get_page_size", "(", ")", ")" ]
Function shows last rows.
[ "Function", "shows", "last", "rows", "." ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/run_window.py#L214-L219
devassistant/devassistant
devassistant/gui/run_window.py
RunWindow.disable_buttons
def disable_buttons(self): """ Function disables buttons """ self.main_btn.set_sensitive(False) self.back_btn.hide() self.info_label.set_label('<span color="#FFA500">In progress...</span>') self.disable_close_window() if self.link is not None: self.link.hide()
python
def disable_buttons(self): """ Function disables buttons """ self.main_btn.set_sensitive(False) self.back_btn.hide() self.info_label.set_label('<span color="#FFA500">In progress...</span>') self.disable_close_window() if self.link is not None: self.link.hide()
[ "def", "disable_buttons", "(", "self", ")", ":", "self", ".", "main_btn", ".", "set_sensitive", "(", "False", ")", "self", ".", "back_btn", ".", "hide", "(", ")", "self", ".", "info_label", ".", "set_label", "(", "'<span color=\"#FFA500\">In progress...</span>'", ")", "self", ".", "disable_close_window", "(", ")", "if", "self", ".", "link", "is", "not", "None", ":", "self", ".", "link", ".", "hide", "(", ")" ]
Function disables buttons
[ "Function", "disables", "buttons" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/run_window.py#L233-L242
devassistant/devassistant
devassistant/gui/run_window.py
RunWindow.allow_buttons
def allow_buttons(self, message="", link=True, back=True): """ Function allows buttons """ self.info_label.set_label(message) self.allow_close_window() if link and self.link is not None: self.link.set_sensitive(True) self.link.show_all() if back: self.back_btn.show() self.main_btn.set_sensitive(True)
python
def allow_buttons(self, message="", link=True, back=True): """ Function allows buttons """ self.info_label.set_label(message) self.allow_close_window() if link and self.link is not None: self.link.set_sensitive(True) self.link.show_all() if back: self.back_btn.show() self.main_btn.set_sensitive(True)
[ "def", "allow_buttons", "(", "self", ",", "message", "=", "\"\"", ",", "link", "=", "True", ",", "back", "=", "True", ")", ":", "self", ".", "info_label", ".", "set_label", "(", "message", ")", "self", ".", "allow_close_window", "(", ")", "if", "link", "and", "self", ".", "link", "is", "not", "None", ":", "self", ".", "link", ".", "set_sensitive", "(", "True", ")", "self", ".", "link", ".", "show_all", "(", ")", "if", "back", ":", "self", ".", "back_btn", ".", "show", "(", ")", "self", ".", "main_btn", ".", "set_sensitive", "(", "True", ")" ]
Function allows buttons
[ "Function", "allows", "buttons" ]
train
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/run_window.py#L244-L255