repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
devassistant/devassistant
devassistant/dapi/dapicli.py
_get_from_dapi_or_mirror
def _get_from_dapi_or_mirror(link): '''Tries to get the link form DAPI or the mirror''' exception = False try: req = requests.get(_api_url() + link, timeout=5) except requests.exceptions.RequestException: exception = True attempts = 1 while exception or str(req.status_code).startswith('5'): if attempts > 5: raise DapiCommError('Could not connect to the API endpoint, sorry.') exception = False try: # Every second attempt, use the mirror req = requests.get(_api_url(attempts % 2) + link, timeout=5*attempts) except requests.exceptions.RequestException: exception = True attempts += 1 return req
python
def _get_from_dapi_or_mirror(link): '''Tries to get the link form DAPI or the mirror''' exception = False try: req = requests.get(_api_url() + link, timeout=5) except requests.exceptions.RequestException: exception = True attempts = 1 while exception or str(req.status_code).startswith('5'): if attempts > 5: raise DapiCommError('Could not connect to the API endpoint, sorry.') exception = False try: # Every second attempt, use the mirror req = requests.get(_api_url(attempts % 2) + link, timeout=5*attempts) except requests.exceptions.RequestException: exception = True attempts += 1 return req
[ "def", "_get_from_dapi_or_mirror", "(", "link", ")", ":", "exception", "=", "False", "try", ":", "req", "=", "requests", ".", "get", "(", "_api_url", "(", ")", "+", "link", ",", "timeout", "=", "5", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "exception", "=", "True", "attempts", "=", "1", "while", "exception", "or", "str", "(", "req", ".", "status_code", ")", ".", "startswith", "(", "'5'", ")", ":", "if", "attempts", ">", "5", ":", "raise", "DapiCommError", "(", "'Could not connect to the API endpoint, sorry.'", ")", "exception", "=", "False", "try", ":", "# Every second attempt, use the mirror", "req", "=", "requests", ".", "get", "(", "_api_url", "(", "attempts", "%", "2", ")", "+", "link", ",", "timeout", "=", "5", "*", "attempts", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "exception", "=", "True", "attempts", "+=", "1", "return", "req" ]
Tries to get the link form DAPI or the mirror
[ "Tries", "to", "get", "the", "link", "form", "DAPI", "or", "the", "mirror" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L63-L83
train
devassistant/devassistant
devassistant/dapi/dapicli.py
_remove_api_url_from_link
def _remove_api_url_from_link(link): '''Remove the API URL from the link if it is there''' if link.startswith(_api_url()): link = link[len(_api_url()):] if link.startswith(_api_url(mirror=True)): link = link[len(_api_url(mirror=True)):] return link
python
def _remove_api_url_from_link(link): '''Remove the API URL from the link if it is there''' if link.startswith(_api_url()): link = link[len(_api_url()):] if link.startswith(_api_url(mirror=True)): link = link[len(_api_url(mirror=True)):] return link
[ "def", "_remove_api_url_from_link", "(", "link", ")", ":", "if", "link", ".", "startswith", "(", "_api_url", "(", ")", ")", ":", "link", "=", "link", "[", "len", "(", "_api_url", "(", ")", ")", ":", "]", "if", "link", ".", "startswith", "(", "_api_url", "(", "mirror", "=", "True", ")", ")", ":", "link", "=", "link", "[", "len", "(", "_api_url", "(", "mirror", "=", "True", ")", ")", ":", "]", "return", "link" ]
Remove the API URL from the link if it is there
[ "Remove", "the", "API", "URL", "from", "the", "link", "if", "it", "is", "there" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L86-L92
train
devassistant/devassistant
devassistant/dapi/dapicli.py
data
def data(link): '''Returns a dictionary from requested link''' link = _remove_api_url_from_link(link) req = _get_from_dapi_or_mirror(link) return _process_req(req)
python
def data(link): '''Returns a dictionary from requested link''' link = _remove_api_url_from_link(link) req = _get_from_dapi_or_mirror(link) return _process_req(req)
[ "def", "data", "(", "link", ")", ":", "link", "=", "_remove_api_url_from_link", "(", "link", ")", "req", "=", "_get_from_dapi_or_mirror", "(", "link", ")", "return", "_process_req", "(", "req", ")" ]
Returns a dictionary from requested link
[ "Returns", "a", "dictionary", "from", "requested", "link" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L95-L99
train
devassistant/devassistant
devassistant/dapi/dapicli.py
_unpaginated
def _unpaginated(what): '''Returns a dictionary with all <what>, unpaginated''' page = data(what) results = page['results'] count = page['count'] while page['next']: page = data(page['next']) results += page['results'] count += page['count'] return {'results': results, 'count': count}
python
def _unpaginated(what): '''Returns a dictionary with all <what>, unpaginated''' page = data(what) results = page['results'] count = page['count'] while page['next']: page = data(page['next']) results += page['results'] count += page['count'] return {'results': results, 'count': count}
[ "def", "_unpaginated", "(", "what", ")", ":", "page", "=", "data", "(", "what", ")", "results", "=", "page", "[", "'results'", "]", "count", "=", "page", "[", "'count'", "]", "while", "page", "[", "'next'", "]", ":", "page", "=", "data", "(", "page", "[", "'next'", "]", ")", "results", "+=", "page", "[", "'results'", "]", "count", "+=", "page", "[", "'count'", "]", "return", "{", "'results'", ":", "results", ",", "'count'", ":", "count", "}" ]
Returns a dictionary with all <what>, unpaginated
[ "Returns", "a", "dictionary", "with", "all", "<what", ">", "unpaginated" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L102-L111
train
devassistant/devassistant
devassistant/dapi/dapicli.py
search
def search(q, **kwargs): '''Returns a dictionary with the search results''' data = {'q': q} for key, value in kwargs.items(): if value: if type(value) == bool: data[key] = 'on' else: data[key] = value return _unpaginated('search/?' + urlencode(data))
python
def search(q, **kwargs): '''Returns a dictionary with the search results''' data = {'q': q} for key, value in kwargs.items(): if value: if type(value) == bool: data[key] = 'on' else: data[key] = value return _unpaginated('search/?' + urlencode(data))
[ "def", "search", "(", "q", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'q'", ":", "q", "}", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "value", ":", "if", "type", "(", "value", ")", "==", "bool", ":", "data", "[", "key", "]", "=", "'on'", "else", ":", "data", "[", "key", "]", "=", "value", "return", "_unpaginated", "(", "'search/?'", "+", "urlencode", "(", "data", ")", ")" ]
Returns a dictionary with the search results
[ "Returns", "a", "dictionary", "with", "the", "search", "results" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L146-L155
train
devassistant/devassistant
devassistant/dapi/dapicli.py
format_users
def format_users(): '''Formats a list of users available on Dapi''' lines = [] u = users() count = u['count'] if not count: raise DapiCommError('Could not find any users on DAPI.') for user in u['results']: line = user['username'] if user['full_name']: line += ' (' + user['full_name'] + ')' lines.append(line) return lines
python
def format_users(): '''Formats a list of users available on Dapi''' lines = [] u = users() count = u['count'] if not count: raise DapiCommError('Could not find any users on DAPI.') for user in u['results']: line = user['username'] if user['full_name']: line += ' (' + user['full_name'] + ')' lines.append(line) return lines
[ "def", "format_users", "(", ")", ":", "lines", "=", "[", "]", "u", "=", "users", "(", ")", "count", "=", "u", "[", "'count'", "]", "if", "not", "count", ":", "raise", "DapiCommError", "(", "'Could not find any users on DAPI.'", ")", "for", "user", "in", "u", "[", "'results'", "]", ":", "line", "=", "user", "[", "'username'", "]", "if", "user", "[", "'full_name'", "]", ":", "line", "+=", "' ('", "+", "user", "[", "'full_name'", "]", "+", "')'", "lines", ".", "append", "(", "line", ")", "return", "lines" ]
Formats a list of users available on Dapi
[ "Formats", "a", "list", "of", "users", "available", "on", "Dapi" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L167-L179
train
devassistant/devassistant
devassistant/dapi/dapicli.py
format_daps
def format_daps(simple=False, skip_installed=False): '''Formats a list of metadaps available on Dapi''' lines= [] m = metadaps() if not m['count']: logger.info('Could not find any daps') return for mdap in sorted(m['results'], key=lambda mdap: mdap['package_name']): if skip_installed and mdap['package_name'] in get_installed_daps(): continue if simple: logger.info(mdap['package_name']) else: for line in _format_dap_with_description(mdap): lines.append(line) return lines
python
def format_daps(simple=False, skip_installed=False): '''Formats a list of metadaps available on Dapi''' lines= [] m = metadaps() if not m['count']: logger.info('Could not find any daps') return for mdap in sorted(m['results'], key=lambda mdap: mdap['package_name']): if skip_installed and mdap['package_name'] in get_installed_daps(): continue if simple: logger.info(mdap['package_name']) else: for line in _format_dap_with_description(mdap): lines.append(line) return lines
[ "def", "format_daps", "(", "simple", "=", "False", ",", "skip_installed", "=", "False", ")", ":", "lines", "=", "[", "]", "m", "=", "metadaps", "(", ")", "if", "not", "m", "[", "'count'", "]", ":", "logger", ".", "info", "(", "'Could not find any daps'", ")", "return", "for", "mdap", "in", "sorted", "(", "m", "[", "'results'", "]", ",", "key", "=", "lambda", "mdap", ":", "mdap", "[", "'package_name'", "]", ")", ":", "if", "skip_installed", "and", "mdap", "[", "'package_name'", "]", "in", "get_installed_daps", "(", ")", ":", "continue", "if", "simple", ":", "logger", ".", "info", "(", "mdap", "[", "'package_name'", "]", ")", "else", ":", "for", "line", "in", "_format_dap_with_description", "(", "mdap", ")", ":", "lines", ".", "append", "(", "line", ")", "return", "lines" ]
Formats a list of metadaps available on Dapi
[ "Formats", "a", "list", "of", "metadaps", "available", "on", "Dapi" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L182-L197
train
devassistant/devassistant
devassistant/dapi/dapicli.py
_get_metadap_dap
def _get_metadap_dap(name, version=''): '''Return data for dap of given or latest version.''' m = metadap(name) if not m: raise DapiCommError('DAP {dap} not found.'.format(dap=name)) if not version: d = m['latest_stable'] or m['latest'] if d: d = data(d) else: d = dap(name, version) if not d: raise DapiCommError( 'DAP {dap} doesn\'t have version {version}.'.format(dap=name, version=version)) return m, d
python
def _get_metadap_dap(name, version=''): '''Return data for dap of given or latest version.''' m = metadap(name) if not m: raise DapiCommError('DAP {dap} not found.'.format(dap=name)) if not version: d = m['latest_stable'] or m['latest'] if d: d = data(d) else: d = dap(name, version) if not d: raise DapiCommError( 'DAP {dap} doesn\'t have version {version}.'.format(dap=name, version=version)) return m, d
[ "def", "_get_metadap_dap", "(", "name", ",", "version", "=", "''", ")", ":", "m", "=", "metadap", "(", "name", ")", "if", "not", "m", ":", "raise", "DapiCommError", "(", "'DAP {dap} not found.'", ".", "format", "(", "dap", "=", "name", ")", ")", "if", "not", "version", ":", "d", "=", "m", "[", "'latest_stable'", "]", "or", "m", "[", "'latest'", "]", "if", "d", ":", "d", "=", "data", "(", "d", ")", "else", ":", "d", "=", "dap", "(", "name", ",", "version", ")", "if", "not", "d", ":", "raise", "DapiCommError", "(", "'DAP {dap} doesn\\'t have version {version}.'", ".", "format", "(", "dap", "=", "name", ",", "version", "=", "version", ")", ")", "return", "m", ",", "d" ]
Return data for dap of given or latest version.
[ "Return", "data", "for", "dap", "of", "given", "or", "latest", "version", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L200-L214
train
devassistant/devassistant
devassistant/dapi/dapicli.py
format_dap_from_dapi
def format_dap_from_dapi(name, version='', full=False): '''Formats information about given DAP from DAPI in a human readable form to list of lines''' lines = [] m, d = _get_metadap_dap(name, version) if d: # Determining label width labels = BASIC_LABELS + ['average_rank'] # average_rank comes from m, not d if full: labels.extend(EXTRA_LABELS) label_width = dapi.DapFormatter.calculate_offset(labels) # Metadata lines += dapi.DapFormatter.format_meta_lines(d, labels=labels, offset=label_width) lines.append(dapi.DapFormatter.format_dapi_score(m, offset=label_width)) if 'assistants' in d: # Assistants assistants = sorted([a for a in d['assistants'] if a.startswith('assistants')]) lines.append('') for line in dapi.DapFormatter.format_assistants_lines(assistants): lines.append(line) # Snippets if full: snippets = sorted([a for a in d['assistants'] if a.startswith('snippets')]) lines.append('') lines += dapi.DapFormatter.format_snippets(snippets) # Supported platforms if d.get('supported_platforms', ''): lines.append('') lines += dapi.DapFormatter.format_platforms(d['supported_platforms']) lines.append('') return lines
python
def format_dap_from_dapi(name, version='', full=False): '''Formats information about given DAP from DAPI in a human readable form to list of lines''' lines = [] m, d = _get_metadap_dap(name, version) if d: # Determining label width labels = BASIC_LABELS + ['average_rank'] # average_rank comes from m, not d if full: labels.extend(EXTRA_LABELS) label_width = dapi.DapFormatter.calculate_offset(labels) # Metadata lines += dapi.DapFormatter.format_meta_lines(d, labels=labels, offset=label_width) lines.append(dapi.DapFormatter.format_dapi_score(m, offset=label_width)) if 'assistants' in d: # Assistants assistants = sorted([a for a in d['assistants'] if a.startswith('assistants')]) lines.append('') for line in dapi.DapFormatter.format_assistants_lines(assistants): lines.append(line) # Snippets if full: snippets = sorted([a for a in d['assistants'] if a.startswith('snippets')]) lines.append('') lines += dapi.DapFormatter.format_snippets(snippets) # Supported platforms if d.get('supported_platforms', ''): lines.append('') lines += dapi.DapFormatter.format_platforms(d['supported_platforms']) lines.append('') return lines
[ "def", "format_dap_from_dapi", "(", "name", ",", "version", "=", "''", ",", "full", "=", "False", ")", ":", "lines", "=", "[", "]", "m", ",", "d", "=", "_get_metadap_dap", "(", "name", ",", "version", ")", "if", "d", ":", "# Determining label width", "labels", "=", "BASIC_LABELS", "+", "[", "'average_rank'", "]", "# average_rank comes from m, not d", "if", "full", ":", "labels", ".", "extend", "(", "EXTRA_LABELS", ")", "label_width", "=", "dapi", ".", "DapFormatter", ".", "calculate_offset", "(", "labels", ")", "# Metadata", "lines", "+=", "dapi", ".", "DapFormatter", ".", "format_meta_lines", "(", "d", ",", "labels", "=", "labels", ",", "offset", "=", "label_width", ")", "lines", ".", "append", "(", "dapi", ".", "DapFormatter", ".", "format_dapi_score", "(", "m", ",", "offset", "=", "label_width", ")", ")", "if", "'assistants'", "in", "d", ":", "# Assistants", "assistants", "=", "sorted", "(", "[", "a", "for", "a", "in", "d", "[", "'assistants'", "]", "if", "a", ".", "startswith", "(", "'assistants'", ")", "]", ")", "lines", ".", "append", "(", "''", ")", "for", "line", "in", "dapi", ".", "DapFormatter", ".", "format_assistants_lines", "(", "assistants", ")", ":", "lines", ".", "append", "(", "line", ")", "# Snippets", "if", "full", ":", "snippets", "=", "sorted", "(", "[", "a", "for", "a", "in", "d", "[", "'assistants'", "]", "if", "a", ".", "startswith", "(", "'snippets'", ")", "]", ")", "lines", ".", "append", "(", "''", ")", "lines", "+=", "dapi", ".", "DapFormatter", ".", "format_snippets", "(", "snippets", ")", "# Supported platforms", "if", "d", ".", "get", "(", "'supported_platforms'", ",", "''", ")", ":", "lines", ".", "append", "(", "''", ")", "lines", "+=", "dapi", ".", "DapFormatter", ".", "format_platforms", "(", "d", "[", "'supported_platforms'", "]", ")", "lines", ".", "append", "(", "''", ")", "return", "lines" ]
Formats information about given DAP from DAPI in a human readable form to list of lines
[ "Formats", "information", "about", "given", "DAP", "from", "DAPI", "in", "a", "human", "readable", "form", "to", "list", "of", "lines" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L217-L252
train
devassistant/devassistant
devassistant/dapi/dapicli.py
format_local_dap
def format_local_dap(dap, full=False, **kwargs): '''Formaqts information about the given local DAP in a human readable form to list of lines''' lines = [] # Determining label width label_width = dapi.DapFormatter.calculate_offset(BASIC_LABELS) # Metadata lines.append(dapi.DapFormatter.format_meta(dap.meta, labels=BASIC_LABELS, offset=label_width, **kwargs)) # Assistants lines.append('') lines.append(dapi.DapFormatter.format_assistants(dap.assistants)) # Snippets if full: lines.append('') lines.append(dapi.DapFormatter.format_snippets(dap.snippets)) # Supported platforms if 'supported_platforms' in dap.meta: lines.append('') lines.append(dapi.DapFormatter.format_platforms(dap.meta['supported_platforms'])) lines.append() return lines
python
def format_local_dap(dap, full=False, **kwargs): '''Formaqts information about the given local DAP in a human readable form to list of lines''' lines = [] # Determining label width label_width = dapi.DapFormatter.calculate_offset(BASIC_LABELS) # Metadata lines.append(dapi.DapFormatter.format_meta(dap.meta, labels=BASIC_LABELS, offset=label_width, **kwargs)) # Assistants lines.append('') lines.append(dapi.DapFormatter.format_assistants(dap.assistants)) # Snippets if full: lines.append('') lines.append(dapi.DapFormatter.format_snippets(dap.snippets)) # Supported platforms if 'supported_platforms' in dap.meta: lines.append('') lines.append(dapi.DapFormatter.format_platforms(dap.meta['supported_platforms'])) lines.append() return lines
[ "def", "format_local_dap", "(", "dap", ",", "full", "=", "False", ",", "*", "*", "kwargs", ")", ":", "lines", "=", "[", "]", "# Determining label width", "label_width", "=", "dapi", ".", "DapFormatter", ".", "calculate_offset", "(", "BASIC_LABELS", ")", "# Metadata", "lines", ".", "append", "(", "dapi", ".", "DapFormatter", ".", "format_meta", "(", "dap", ".", "meta", ",", "labels", "=", "BASIC_LABELS", ",", "offset", "=", "label_width", ",", "*", "*", "kwargs", ")", ")", "# Assistants", "lines", ".", "append", "(", "''", ")", "lines", ".", "append", "(", "dapi", ".", "DapFormatter", ".", "format_assistants", "(", "dap", ".", "assistants", ")", ")", "# Snippets", "if", "full", ":", "lines", ".", "append", "(", "''", ")", "lines", ".", "append", "(", "dapi", ".", "DapFormatter", ".", "format_snippets", "(", "dap", ".", "snippets", ")", ")", "# Supported platforms", "if", "'supported_platforms'", "in", "dap", ".", "meta", ":", "lines", ".", "append", "(", "''", ")", "lines", ".", "append", "(", "dapi", ".", "DapFormatter", ".", "format_platforms", "(", "dap", ".", "meta", "[", "'supported_platforms'", "]", ")", ")", "lines", ".", "append", "(", ")", "return", "lines" ]
Formaqts information about the given local DAP in a human readable form to list of lines
[ "Formaqts", "information", "about", "the", "given", "local", "DAP", "in", "a", "human", "readable", "form", "to", "list", "of", "lines" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L255-L281
train
devassistant/devassistant
devassistant/dapi/dapicli.py
format_installed_dap
def format_installed_dap(name, full=False): '''Formats information about an installed DAP in a human readable form to list of lines''' dap_data = get_installed_daps_detailed().get(name) if not dap_data: raise DapiLocalError('DAP "{dap}" is not installed, can not query for info.'.format(dap=name)) locations = [os.path.join(data['location'], '') for data in dap_data] for location in locations: dap = dapi.Dap(None, fake=True, mimic_filename=name) meta_path = os.path.join(location, 'meta', name + '.yaml') with open(meta_path, 'r') as fh: dap.meta = dap._load_meta(fh) dap.files = _get_assistants_snippets(location, name) dap._find_bad_meta() format_local_dap(dap, full=full, custom_location=os.path.dirname(location))
python
def format_installed_dap(name, full=False): '''Formats information about an installed DAP in a human readable form to list of lines''' dap_data = get_installed_daps_detailed().get(name) if not dap_data: raise DapiLocalError('DAP "{dap}" is not installed, can not query for info.'.format(dap=name)) locations = [os.path.join(data['location'], '') for data in dap_data] for location in locations: dap = dapi.Dap(None, fake=True, mimic_filename=name) meta_path = os.path.join(location, 'meta', name + '.yaml') with open(meta_path, 'r') as fh: dap.meta = dap._load_meta(fh) dap.files = _get_assistants_snippets(location, name) dap._find_bad_meta() format_local_dap(dap, full=full, custom_location=os.path.dirname(location))
[ "def", "format_installed_dap", "(", "name", ",", "full", "=", "False", ")", ":", "dap_data", "=", "get_installed_daps_detailed", "(", ")", ".", "get", "(", "name", ")", "if", "not", "dap_data", ":", "raise", "DapiLocalError", "(", "'DAP \"{dap}\" is not installed, can not query for info.'", ".", "format", "(", "dap", "=", "name", ")", ")", "locations", "=", "[", "os", ".", "path", ".", "join", "(", "data", "[", "'location'", "]", ",", "''", ")", "for", "data", "in", "dap_data", "]", "for", "location", "in", "locations", ":", "dap", "=", "dapi", ".", "Dap", "(", "None", ",", "fake", "=", "True", ",", "mimic_filename", "=", "name", ")", "meta_path", "=", "os", ".", "path", ".", "join", "(", "location", ",", "'meta'", ",", "name", "+", "'.yaml'", ")", "with", "open", "(", "meta_path", ",", "'r'", ")", "as", "fh", ":", "dap", ".", "meta", "=", "dap", ".", "_load_meta", "(", "fh", ")", "dap", ".", "files", "=", "_get_assistants_snippets", "(", "location", ",", "name", ")", "dap", ".", "_find_bad_meta", "(", ")", "format_local_dap", "(", "dap", ",", "full", "=", "full", ",", "custom_location", "=", "os", ".", "path", ".", "dirname", "(", "location", ")", ")" ]
Formats information about an installed DAP in a human readable form to list of lines
[ "Formats", "information", "about", "an", "installed", "DAP", "in", "a", "human", "readable", "form", "to", "list", "of", "lines" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L284-L299
train
devassistant/devassistant
devassistant/dapi/dapicli.py
format_installed_dap_list
def format_installed_dap_list(simple=False): '''Formats all installed DAPs in a human readable form to list of lines''' lines = [] if simple: for pkg in sorted(get_installed_daps()): lines.append(pkg) else: for pkg, instances in sorted(get_installed_daps_detailed().items()): versions = [] for instance in instances: location = utils.unexpanduser(instance['location']) version = instance['version'] if not versions: # if this is the first version = utils.bold(version) versions.append('{v}:{p}'.format(v=version, p=location)) pkg = utils.bold(pkg) lines.append('{pkg} ({versions})'.format(pkg=pkg, versions=' '.join(versions))) return lines
python
def format_installed_dap_list(simple=False): '''Formats all installed DAPs in a human readable form to list of lines''' lines = [] if simple: for pkg in sorted(get_installed_daps()): lines.append(pkg) else: for pkg, instances in sorted(get_installed_daps_detailed().items()): versions = [] for instance in instances: location = utils.unexpanduser(instance['location']) version = instance['version'] if not versions: # if this is the first version = utils.bold(version) versions.append('{v}:{p}'.format(v=version, p=location)) pkg = utils.bold(pkg) lines.append('{pkg} ({versions})'.format(pkg=pkg, versions=' '.join(versions))) return lines
[ "def", "format_installed_dap_list", "(", "simple", "=", "False", ")", ":", "lines", "=", "[", "]", "if", "simple", ":", "for", "pkg", "in", "sorted", "(", "get_installed_daps", "(", ")", ")", ":", "lines", ".", "append", "(", "pkg", ")", "else", ":", "for", "pkg", ",", "instances", "in", "sorted", "(", "get_installed_daps_detailed", "(", ")", ".", "items", "(", ")", ")", ":", "versions", "=", "[", "]", "for", "instance", "in", "instances", ":", "location", "=", "utils", ".", "unexpanduser", "(", "instance", "[", "'location'", "]", ")", "version", "=", "instance", "[", "'version'", "]", "if", "not", "versions", ":", "# if this is the first", "version", "=", "utils", ".", "bold", "(", "version", ")", "versions", ".", "append", "(", "'{v}:{p}'", ".", "format", "(", "v", "=", "version", ",", "p", "=", "location", ")", ")", "pkg", "=", "utils", ".", "bold", "(", "pkg", ")", "lines", ".", "append", "(", "'{pkg} ({versions})'", ".", "format", "(", "pkg", "=", "pkg", ",", "versions", "=", "' '", ".", "join", "(", "versions", ")", ")", ")", "return", "lines" ]
Formats all installed DAPs in a human readable form to list of lines
[ "Formats", "all", "installed", "DAPs", "in", "a", "human", "readable", "form", "to", "list", "of", "lines" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L302-L319
train
devassistant/devassistant
devassistant/dapi/dapicli.py
_get_assistants_snippets
def _get_assistants_snippets(path, name): '''Get Assistants and Snippets for a given DAP name on a given path''' result = [] subdirs = {'assistants': 2, 'snippets': 1} # Values used for stripping leading path tokens for loc in subdirs: for root, dirs, files in os.walk(os.path.join(path, loc)): for filename in [utils.strip_prefix(os.path.join(root, f), path) for f in files]: stripped = os.path.sep.join(filename.split(os.path.sep)[subdirs[loc]:]) if stripped.startswith(os.path.join(name, '')) or stripped == name + '.yaml': result.append(os.path.join('fakeroot', filename)) return result
python
def _get_assistants_snippets(path, name): '''Get Assistants and Snippets for a given DAP name on a given path''' result = [] subdirs = {'assistants': 2, 'snippets': 1} # Values used for stripping leading path tokens for loc in subdirs: for root, dirs, files in os.walk(os.path.join(path, loc)): for filename in [utils.strip_prefix(os.path.join(root, f), path) for f in files]: stripped = os.path.sep.join(filename.split(os.path.sep)[subdirs[loc]:]) if stripped.startswith(os.path.join(name, '')) or stripped == name + '.yaml': result.append(os.path.join('fakeroot', filename)) return result
[ "def", "_get_assistants_snippets", "(", "path", ",", "name", ")", ":", "result", "=", "[", "]", "subdirs", "=", "{", "'assistants'", ":", "2", ",", "'snippets'", ":", "1", "}", "# Values used for stripping leading path tokens", "for", "loc", "in", "subdirs", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "join", "(", "path", ",", "loc", ")", ")", ":", "for", "filename", "in", "[", "utils", ".", "strip_prefix", "(", "os", ".", "path", ".", "join", "(", "root", ",", "f", ")", ",", "path", ")", "for", "f", "in", "files", "]", ":", "stripped", "=", "os", ".", "path", ".", "sep", ".", "join", "(", "filename", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "[", "subdirs", "[", "loc", "]", ":", "]", ")", "if", "stripped", ".", "startswith", "(", "os", ".", "path", ".", "join", "(", "name", ",", "''", ")", ")", "or", "stripped", "==", "name", "+", "'.yaml'", ":", "result", ".", "append", "(", "os", ".", "path", ".", "join", "(", "'fakeroot'", ",", "filename", ")", ")", "return", "result" ]
Get Assistants and Snippets for a given DAP name on a given path
[ "Get", "Assistants", "and", "Snippets", "for", "a", "given", "DAP", "name", "on", "a", "given", "path" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L322-L334
train
devassistant/devassistant
devassistant/dapi/dapicli.py
format_search
def format_search(q, **kwargs): '''Formats the results of a search''' m = search(q, **kwargs) count = m['count'] if not count: raise DapiCommError('Could not find any DAP packages for your query.') return for mdap in m['results']: mdap = mdap['content_object'] return _format_dap_with_description(mdap)
python
def format_search(q, **kwargs): '''Formats the results of a search''' m = search(q, **kwargs) count = m['count'] if not count: raise DapiCommError('Could not find any DAP packages for your query.') return for mdap in m['results']: mdap = mdap['content_object'] return _format_dap_with_description(mdap)
[ "def", "format_search", "(", "q", ",", "*", "*", "kwargs", ")", ":", "m", "=", "search", "(", "q", ",", "*", "*", "kwargs", ")", "count", "=", "m", "[", "'count'", "]", "if", "not", "count", ":", "raise", "DapiCommError", "(", "'Could not find any DAP packages for your query.'", ")", "return", "for", "mdap", "in", "m", "[", "'results'", "]", ":", "mdap", "=", "mdap", "[", "'content_object'", "]", "return", "_format_dap_with_description", "(", "mdap", ")" ]
Formats the results of a search
[ "Formats", "the", "results", "of", "a", "search" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L337-L346
train
devassistant/devassistant
devassistant/dapi/dapicli.py
get_installed_daps
def get_installed_daps(location=None, skip_distro=False): '''Returns a set of all installed daps Either in the given location or in all of them''' if location: locations = [location] else: locations = _data_dirs() s = set() for loc in locations: if skip_distro and loc == DISTRO_DIRECTORY: continue g = glob.glob('{d}/meta/*.yaml'.format(d=loc)) for meta in g: s.add(meta.split('/')[-1][:-len('.yaml')]) return s
python
def get_installed_daps(location=None, skip_distro=False): '''Returns a set of all installed daps Either in the given location or in all of them''' if location: locations = [location] else: locations = _data_dirs() s = set() for loc in locations: if skip_distro and loc == DISTRO_DIRECTORY: continue g = glob.glob('{d}/meta/*.yaml'.format(d=loc)) for meta in g: s.add(meta.split('/')[-1][:-len('.yaml')]) return s
[ "def", "get_installed_daps", "(", "location", "=", "None", ",", "skip_distro", "=", "False", ")", ":", "if", "location", ":", "locations", "=", "[", "location", "]", "else", ":", "locations", "=", "_data_dirs", "(", ")", "s", "=", "set", "(", ")", "for", "loc", "in", "locations", ":", "if", "skip_distro", "and", "loc", "==", "DISTRO_DIRECTORY", ":", "continue", "g", "=", "glob", ".", "glob", "(", "'{d}/meta/*.yaml'", ".", "format", "(", "d", "=", "loc", ")", ")", "for", "meta", "in", "g", ":", "s", ".", "add", "(", "meta", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "[", ":", "-", "len", "(", "'.yaml'", ")", "]", ")", "return", "s" ]
Returns a set of all installed daps Either in the given location or in all of them
[ "Returns", "a", "set", "of", "all", "installed", "daps", "Either", "in", "the", "given", "location", "or", "in", "all", "of", "them" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L349-L363
train
devassistant/devassistant
devassistant/dapi/dapicli.py
get_installed_daps_detailed
def get_installed_daps_detailed(): '''Returns a dictionary with all installed daps and their versions and locations First version and location in the dap's list is the one that is preferred''' daps = {} for loc in _data_dirs(): s = get_installed_daps(loc) for dap in s: if dap not in daps: daps[dap] = [] daps[dap].append({'version': get_installed_version_of(dap, loc), 'location': loc}) return daps
python
def get_installed_daps_detailed(): '''Returns a dictionary with all installed daps and their versions and locations First version and location in the dap's list is the one that is preferred''' daps = {} for loc in _data_dirs(): s = get_installed_daps(loc) for dap in s: if dap not in daps: daps[dap] = [] daps[dap].append({'version': get_installed_version_of(dap, loc), 'location': loc}) return daps
[ "def", "get_installed_daps_detailed", "(", ")", ":", "daps", "=", "{", "}", "for", "loc", "in", "_data_dirs", "(", ")", ":", "s", "=", "get_installed_daps", "(", "loc", ")", "for", "dap", "in", "s", ":", "if", "dap", "not", "in", "daps", ":", "daps", "[", "dap", "]", "=", "[", "]", "daps", "[", "dap", "]", ".", "append", "(", "{", "'version'", ":", "get_installed_version_of", "(", "dap", ",", "loc", ")", ",", "'location'", ":", "loc", "}", ")", "return", "daps" ]
Returns a dictionary with all installed daps and their versions and locations First version and location in the dap's list is the one that is preferred
[ "Returns", "a", "dictionary", "with", "all", "installed", "daps", "and", "their", "versions", "and", "locations", "First", "version", "and", "location", "in", "the", "dap", "s", "list", "is", "the", "one", "that", "is", "preferred" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L366-L376
train
devassistant/devassistant
devassistant/dapi/dapicli.py
download_dap
def download_dap(name, version='', d='', directory=''): '''Download a dap to a given or temporary directory Return a path to that file together with information if the directory should be later deleted ''' if not d: m, d = _get_metadap_dap(name, version) if directory: _dir = directory else: _dir = tempfile.mkdtemp() try: url = d['download'] except TypeError: raise DapiCommError('DAP {dap} has no version to download.'.format(dap=name)) filename = url.split('/')[-1] path = os.path.join(_dir, filename) urllib.request.urlretrieve(url, path) dapisum = d['sha256sum'] downloadedsum = hashlib.sha256(open(path, 'rb').read()).hexdigest() if dapisum != downloadedsum: os.remove(path) raise DapiLocalError( 'DAP {dap} has incorrect sha256sum (DAPI: {dapi}, downloaded: {downloaded})'. format(dap=name, dapi=dapisum, downloaded=downloadedsum)) return path, not bool(directory)
python
def download_dap(name, version='', d='', directory=''): '''Download a dap to a given or temporary directory Return a path to that file together with information if the directory should be later deleted ''' if not d: m, d = _get_metadap_dap(name, version) if directory: _dir = directory else: _dir = tempfile.mkdtemp() try: url = d['download'] except TypeError: raise DapiCommError('DAP {dap} has no version to download.'.format(dap=name)) filename = url.split('/')[-1] path = os.path.join(_dir, filename) urllib.request.urlretrieve(url, path) dapisum = d['sha256sum'] downloadedsum = hashlib.sha256(open(path, 'rb').read()).hexdigest() if dapisum != downloadedsum: os.remove(path) raise DapiLocalError( 'DAP {dap} has incorrect sha256sum (DAPI: {dapi}, downloaded: {downloaded})'. format(dap=name, dapi=dapisum, downloaded=downloadedsum)) return path, not bool(directory)
[ "def", "download_dap", "(", "name", ",", "version", "=", "''", ",", "d", "=", "''", ",", "directory", "=", "''", ")", ":", "if", "not", "d", ":", "m", ",", "d", "=", "_get_metadap_dap", "(", "name", ",", "version", ")", "if", "directory", ":", "_dir", "=", "directory", "else", ":", "_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "url", "=", "d", "[", "'download'", "]", "except", "TypeError", ":", "raise", "DapiCommError", "(", "'DAP {dap} has no version to download.'", ".", "format", "(", "dap", "=", "name", ")", ")", "filename", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "path", "=", "os", ".", "path", ".", "join", "(", "_dir", ",", "filename", ")", "urllib", ".", "request", ".", "urlretrieve", "(", "url", ",", "path", ")", "dapisum", "=", "d", "[", "'sha256sum'", "]", "downloadedsum", "=", "hashlib", ".", "sha256", "(", "open", "(", "path", ",", "'rb'", ")", ".", "read", "(", ")", ")", ".", "hexdigest", "(", ")", "if", "dapisum", "!=", "downloadedsum", ":", "os", ".", "remove", "(", "path", ")", "raise", "DapiLocalError", "(", "'DAP {dap} has incorrect sha256sum (DAPI: {dapi}, downloaded: {downloaded})'", ".", "format", "(", "dap", "=", "name", ",", "dapi", "=", "dapisum", ",", "downloaded", "=", "downloadedsum", ")", ")", "return", "path", ",", "not", "bool", "(", "directory", ")" ]
Download a dap to a given or temporary directory Return a path to that file together with information if the directory should be later deleted
[ "Download", "a", "dap", "to", "a", "given", "or", "temporary", "directory", "Return", "a", "path", "to", "that", "file", "together", "with", "information", "if", "the", "directory", "should", "be", "later", "deleted" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L448-L472
train
devassistant/devassistant
devassistant/dapi/dapicli.py
install_dap_from_path
def install_dap_from_path(path, update=False, update_allpaths=False, first=True, force=False, nodeps=False, reinstall=False, __ui__=''): '''Installs a dap from a given path''' will_uninstall = False dap_obj = dapi.Dap(path) name = dap_obj.meta['package_name'] if name in get_installed_daps(): if not update and not reinstall: raise DapiLocalError( 'DAP {name} is already installed. ' 'Run `da pkg list` to see it\'s location, or use --reinstall to ignore this check.' .format(name=name)) elif not update_allpaths and name in get_installed_daps(_install_path()): will_uninstall = True elif update_allpaths and name in get_installed_daps(): will_uninstall = True if update and update_allpaths: install_locations = [] for pair in get_installed_daps_detailed()[name]: install_locations.append(pair['location']) else: install_locations = [_install_path()] # This should not happen unless someone did it on purpose for location in install_locations: if os.path.isfile(location): raise DapiLocalError( '{i} is a file, not a directory.'.format(i=_install_path())) _dir = tempfile.mkdtemp() old_level = logger.getEffectiveLevel() logger.setLevel(logging.ERROR) ok = dapi.DapChecker.check(dap_obj) logger.setLevel(old_level) if not ok: raise DapiLocalError('The DAP you want to install has errors, not installing.') installed = [] if first: if not force and not _is_supported_here(dap_obj.meta): raise DapiLocalError( '{0} is not supported on this platform (use --force to suppress this check)'. format(name)) deps = set() if 'dependencies' in dap_obj.meta and not nodeps: for dep in dap_obj.meta['dependencies']: dep = _strip_version_from_dependency(dep) if dep not in get_installed_daps(): deps |= _get_all_dependencies_of(dep, force=force) for dep in deps: if dep not in get_installed_daps(): installed += install_dap(dep, first=False, __ui__=__ui__) dap_obj.extract(_dir) if will_uninstall: uninstall_dap(name, allpaths=update_allpaths, __ui__=__ui__) _dapdir = os.path.join(_dir, name + '-' + dap_obj.meta['version']) if not os.path.isdir(_install_path()): os.makedirs(_install_path()) os.mkdir(os.path.join(_dapdir, 'meta')) os.rename(os.path.join(_dapdir, 'meta.yaml'), os.path.join(_dapdir, 'meta', name + '.yaml')) for location in install_locations: for f in glob.glob(_dapdir + '/*'): dst = os.path.join(location, os.path.basename(f)) if os.path.isdir(f): if not os.path.exists(dst): os.mkdir(dst) for src_dir, dirs, files in os.walk(f): dst_dir = src_dir.replace(f, dst) if not os.path.exists(dst_dir): os.mkdir(dst_dir) for file_ in files: src_file = os.path.join(src_dir, file_) dst_file = os.path.join(dst_dir, file_) shutil.copyfile(src_file, dst_file) else: shutil.copyfile(f, dst) try: shutil.rmtree(_dir) except: pass return [name] + installed
python
def install_dap_from_path(path, update=False, update_allpaths=False, first=True, force=False, nodeps=False, reinstall=False, __ui__=''): '''Installs a dap from a given path''' will_uninstall = False dap_obj = dapi.Dap(path) name = dap_obj.meta['package_name'] if name in get_installed_daps(): if not update and not reinstall: raise DapiLocalError( 'DAP {name} is already installed. ' 'Run `da pkg list` to see it\'s location, or use --reinstall to ignore this check.' .format(name=name)) elif not update_allpaths and name in get_installed_daps(_install_path()): will_uninstall = True elif update_allpaths and name in get_installed_daps(): will_uninstall = True if update and update_allpaths: install_locations = [] for pair in get_installed_daps_detailed()[name]: install_locations.append(pair['location']) else: install_locations = [_install_path()] # This should not happen unless someone did it on purpose for location in install_locations: if os.path.isfile(location): raise DapiLocalError( '{i} is a file, not a directory.'.format(i=_install_path())) _dir = tempfile.mkdtemp() old_level = logger.getEffectiveLevel() logger.setLevel(logging.ERROR) ok = dapi.DapChecker.check(dap_obj) logger.setLevel(old_level) if not ok: raise DapiLocalError('The DAP you want to install has errors, not installing.') installed = [] if first: if not force and not _is_supported_here(dap_obj.meta): raise DapiLocalError( '{0} is not supported on this platform (use --force to suppress this check)'. format(name)) deps = set() if 'dependencies' in dap_obj.meta and not nodeps: for dep in dap_obj.meta['dependencies']: dep = _strip_version_from_dependency(dep) if dep not in get_installed_daps(): deps |= _get_all_dependencies_of(dep, force=force) for dep in deps: if dep not in get_installed_daps(): installed += install_dap(dep, first=False, __ui__=__ui__) dap_obj.extract(_dir) if will_uninstall: uninstall_dap(name, allpaths=update_allpaths, __ui__=__ui__) _dapdir = os.path.join(_dir, name + '-' + dap_obj.meta['version']) if not os.path.isdir(_install_path()): os.makedirs(_install_path()) os.mkdir(os.path.join(_dapdir, 'meta')) os.rename(os.path.join(_dapdir, 'meta.yaml'), os.path.join(_dapdir, 'meta', name + '.yaml')) for location in install_locations: for f in glob.glob(_dapdir + '/*'): dst = os.path.join(location, os.path.basename(f)) if os.path.isdir(f): if not os.path.exists(dst): os.mkdir(dst) for src_dir, dirs, files in os.walk(f): dst_dir = src_dir.replace(f, dst) if not os.path.exists(dst_dir): os.mkdir(dst_dir) for file_ in files: src_file = os.path.join(src_dir, file_) dst_file = os.path.join(dst_dir, file_) shutil.copyfile(src_file, dst_file) else: shutil.copyfile(f, dst) try: shutil.rmtree(_dir) except: pass return [name] + installed
[ "def", "install_dap_from_path", "(", "path", ",", "update", "=", "False", ",", "update_allpaths", "=", "False", ",", "first", "=", "True", ",", "force", "=", "False", ",", "nodeps", "=", "False", ",", "reinstall", "=", "False", ",", "__ui__", "=", "''", ")", ":", "will_uninstall", "=", "False", "dap_obj", "=", "dapi", ".", "Dap", "(", "path", ")", "name", "=", "dap_obj", ".", "meta", "[", "'package_name'", "]", "if", "name", "in", "get_installed_daps", "(", ")", ":", "if", "not", "update", "and", "not", "reinstall", ":", "raise", "DapiLocalError", "(", "'DAP {name} is already installed. '", "'Run `da pkg list` to see it\\'s location, or use --reinstall to ignore this check.'", ".", "format", "(", "name", "=", "name", ")", ")", "elif", "not", "update_allpaths", "and", "name", "in", "get_installed_daps", "(", "_install_path", "(", ")", ")", ":", "will_uninstall", "=", "True", "elif", "update_allpaths", "and", "name", "in", "get_installed_daps", "(", ")", ":", "will_uninstall", "=", "True", "if", "update", "and", "update_allpaths", ":", "install_locations", "=", "[", "]", "for", "pair", "in", "get_installed_daps_detailed", "(", ")", "[", "name", "]", ":", "install_locations", ".", "append", "(", "pair", "[", "'location'", "]", ")", "else", ":", "install_locations", "=", "[", "_install_path", "(", ")", "]", "# This should not happen unless someone did it on purpose", "for", "location", "in", "install_locations", ":", "if", "os", ".", "path", ".", "isfile", "(", "location", ")", ":", "raise", "DapiLocalError", "(", "'{i} is a file, not a directory.'", ".", "format", "(", "i", "=", "_install_path", "(", ")", ")", ")", "_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "old_level", "=", "logger", ".", "getEffectiveLevel", "(", ")", "logger", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "ok", "=", "dapi", ".", "DapChecker", ".", "check", "(", "dap_obj", ")", "logger", ".", "setLevel", "(", "old_level", ")", "if", "not", "ok", ":", "raise", "DapiLocalError", "(", "'The DAP you want to install has errors, not installing.'", ")", "installed", "=", "[", "]", "if", "first", ":", "if", "not", "force", "and", "not", "_is_supported_here", "(", "dap_obj", ".", "meta", ")", ":", "raise", "DapiLocalError", "(", "'{0} is not supported on this platform (use --force to suppress this check)'", ".", "format", "(", "name", ")", ")", "deps", "=", "set", "(", ")", "if", "'dependencies'", "in", "dap_obj", ".", "meta", "and", "not", "nodeps", ":", "for", "dep", "in", "dap_obj", ".", "meta", "[", "'dependencies'", "]", ":", "dep", "=", "_strip_version_from_dependency", "(", "dep", ")", "if", "dep", "not", "in", "get_installed_daps", "(", ")", ":", "deps", "|=", "_get_all_dependencies_of", "(", "dep", ",", "force", "=", "force", ")", "for", "dep", "in", "deps", ":", "if", "dep", "not", "in", "get_installed_daps", "(", ")", ":", "installed", "+=", "install_dap", "(", "dep", ",", "first", "=", "False", ",", "__ui__", "=", "__ui__", ")", "dap_obj", ".", "extract", "(", "_dir", ")", "if", "will_uninstall", ":", "uninstall_dap", "(", "name", ",", "allpaths", "=", "update_allpaths", ",", "__ui__", "=", "__ui__", ")", "_dapdir", "=", "os", ".", "path", ".", "join", "(", "_dir", ",", "name", "+", "'-'", "+", "dap_obj", ".", "meta", "[", "'version'", "]", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "_install_path", "(", ")", ")", ":", "os", ".", "makedirs", "(", "_install_path", "(", ")", ")", "os", ".", "mkdir", "(", "os", ".", "path", ".", "join", "(", "_dapdir", ",", "'meta'", ")", ")", "os", ".", "rename", "(", "os", ".", "path", ".", "join", "(", "_dapdir", ",", "'meta.yaml'", ")", ",", "os", ".", "path", ".", "join", "(", "_dapdir", ",", "'meta'", ",", "name", "+", "'.yaml'", ")", ")", "for", "location", "in", "install_locations", ":", "for", "f", "in", "glob", ".", "glob", "(", "_dapdir", "+", "'/*'", ")", ":", "dst", "=", "os", ".", "path", ".", "join", "(", "location", ",", "os", ".", "path", ".", "basename", "(", "f", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "f", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dst", ")", ":", "os", ".", "mkdir", "(", "dst", ")", "for", "src_dir", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "f", ")", ":", "dst_dir", "=", "src_dir", ".", "replace", "(", "f", ",", "dst", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dst_dir", ")", ":", "os", ".", "mkdir", "(", "dst_dir", ")", "for", "file_", "in", "files", ":", "src_file", "=", "os", ".", "path", ".", "join", "(", "src_dir", ",", "file_", ")", "dst_file", "=", "os", ".", "path", ".", "join", "(", "dst_dir", ",", "file_", ")", "shutil", ".", "copyfile", "(", "src_file", ",", "dst_file", ")", "else", ":", "shutil", ".", "copyfile", "(", "f", ",", "dst", ")", "try", ":", "shutil", ".", "rmtree", "(", "_dir", ")", "except", ":", "pass", "return", "[", "name", "]", "+", "installed" ]
Installs a dap from a given path
[ "Installs", "a", "dap", "from", "a", "given", "path" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L475-L568
train
devassistant/devassistant
devassistant/dapi/dapicli.py
_strip_version_from_dependency
def _strip_version_from_dependency(dep): '''For given dependency string, return only the package name''' usedmark = '' for mark in '< > ='.split(): split = dep.split(mark) if len(split) > 1: usedmark = mark break if usedmark: return split[0].strip() else: return dep.strip()
python
def _strip_version_from_dependency(dep): '''For given dependency string, return only the package name''' usedmark = '' for mark in '< > ='.split(): split = dep.split(mark) if len(split) > 1: usedmark = mark break if usedmark: return split[0].strip() else: return dep.strip()
[ "def", "_strip_version_from_dependency", "(", "dep", ")", ":", "usedmark", "=", "''", "for", "mark", "in", "'< > ='", ".", "split", "(", ")", ":", "split", "=", "dep", ".", "split", "(", "mark", ")", "if", "len", "(", "split", ")", ">", "1", ":", "usedmark", "=", "mark", "break", "if", "usedmark", ":", "return", "split", "[", "0", "]", ".", "strip", "(", ")", "else", ":", "return", "dep", ".", "strip", "(", ")" ]
For given dependency string, return only the package name
[ "For", "given", "dependency", "string", "return", "only", "the", "package", "name" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L571-L582
train
devassistant/devassistant
devassistant/dapi/dapicli.py
get_installed_version_of
def get_installed_version_of(name, location=None): '''Gets the installed version of the given dap or None if not installed Searches in all dirs by default, otherwise in the given one''' if location: locations = [location] else: locations = _data_dirs() for loc in locations: if name not in get_installed_daps(loc): continue meta = '{d}/meta/{dap}.yaml'.format(d=loc, dap=name) data = yaml.load(open(meta), Loader=Loader) return str(data['version']) return None
python
def get_installed_version_of(name, location=None): '''Gets the installed version of the given dap or None if not installed Searches in all dirs by default, otherwise in the given one''' if location: locations = [location] else: locations = _data_dirs() for loc in locations: if name not in get_installed_daps(loc): continue meta = '{d}/meta/{dap}.yaml'.format(d=loc, dap=name) data = yaml.load(open(meta), Loader=Loader) return str(data['version']) return None
[ "def", "get_installed_version_of", "(", "name", ",", "location", "=", "None", ")", ":", "if", "location", ":", "locations", "=", "[", "location", "]", "else", ":", "locations", "=", "_data_dirs", "(", ")", "for", "loc", "in", "locations", ":", "if", "name", "not", "in", "get_installed_daps", "(", "loc", ")", ":", "continue", "meta", "=", "'{d}/meta/{dap}.yaml'", ".", "format", "(", "d", "=", "loc", ",", "dap", "=", "name", ")", "data", "=", "yaml", ".", "load", "(", "open", "(", "meta", ")", ",", "Loader", "=", "Loader", ")", "return", "str", "(", "data", "[", "'version'", "]", ")", "return", "None" ]
Gets the installed version of the given dap or None if not installed Searches in all dirs by default, otherwise in the given one
[ "Gets", "the", "installed", "version", "of", "the", "given", "dap", "or", "None", "if", "not", "installed", "Searches", "in", "all", "dirs", "by", "default", "otherwise", "in", "the", "given", "one" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L585-L599
train
devassistant/devassistant
devassistant/dapi/dapicli.py
_get_dependencies_of
def _get_dependencies_of(name, location=None): ''' Returns list of first level dependencies of the given installed dap or dap from Dapi if not installed If a location is specified, this only checks for dap installed in that path and return [] if the dap is not located there ''' if not location: detailed_dap_list = get_installed_daps_detailed() if name not in detailed_dap_list: return _get_api_dependencies_of(name) location = detailed_dap_list[name][0]['location'] meta = '{d}/meta/{dap}.yaml'.format(d=location, dap=name) try: data = yaml.load(open(meta), Loader=Loader) except IOError: return [] return data.get('dependencies', [])
python
def _get_dependencies_of(name, location=None): ''' Returns list of first level dependencies of the given installed dap or dap from Dapi if not installed If a location is specified, this only checks for dap installed in that path and return [] if the dap is not located there ''' if not location: detailed_dap_list = get_installed_daps_detailed() if name not in detailed_dap_list: return _get_api_dependencies_of(name) location = detailed_dap_list[name][0]['location'] meta = '{d}/meta/{dap}.yaml'.format(d=location, dap=name) try: data = yaml.load(open(meta), Loader=Loader) except IOError: return [] return data.get('dependencies', [])
[ "def", "_get_dependencies_of", "(", "name", ",", "location", "=", "None", ")", ":", "if", "not", "location", ":", "detailed_dap_list", "=", "get_installed_daps_detailed", "(", ")", "if", "name", "not", "in", "detailed_dap_list", ":", "return", "_get_api_dependencies_of", "(", "name", ")", "location", "=", "detailed_dap_list", "[", "name", "]", "[", "0", "]", "[", "'location'", "]", "meta", "=", "'{d}/meta/{dap}.yaml'", ".", "format", "(", "d", "=", "location", ",", "dap", "=", "name", ")", "try", ":", "data", "=", "yaml", ".", "load", "(", "open", "(", "meta", ")", ",", "Loader", "=", "Loader", ")", "except", "IOError", ":", "return", "[", "]", "return", "data", ".", "get", "(", "'dependencies'", ",", "[", "]", ")" ]
Returns list of first level dependencies of the given installed dap or dap from Dapi if not installed If a location is specified, this only checks for dap installed in that path and return [] if the dap is not located there
[ "Returns", "list", "of", "first", "level", "dependencies", "of", "the", "given", "installed", "dap", "or", "dap", "from", "Dapi", "if", "not", "installed", "If", "a", "location", "is", "specified", "this", "only", "checks", "for", "dap", "installed", "in", "that", "path", "and", "return", "[]", "if", "the", "dap", "is", "not", "located", "there" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L610-L628
train
devassistant/devassistant
devassistant/dapi/dapicli.py
_get_all_dependencies_of
def _get_all_dependencies_of(name, deps=set(), force=False): '''Returns list of dependencies of the given dap from Dapi recursively''' first_deps = _get_api_dependencies_of(name, force=force) for dep in first_deps: dep = _strip_version_from_dependency(dep) if dep in deps: continue # we do the following not to resolve the dependencies of already installed daps if dap in get_installed_daps(): continue deps |= _get_all_dependencies_of(dep, deps) return deps | set([name])
python
def _get_all_dependencies_of(name, deps=set(), force=False): '''Returns list of dependencies of the given dap from Dapi recursively''' first_deps = _get_api_dependencies_of(name, force=force) for dep in first_deps: dep = _strip_version_from_dependency(dep) if dep in deps: continue # we do the following not to resolve the dependencies of already installed daps if dap in get_installed_daps(): continue deps |= _get_all_dependencies_of(dep, deps) return deps | set([name])
[ "def", "_get_all_dependencies_of", "(", "name", ",", "deps", "=", "set", "(", ")", ",", "force", "=", "False", ")", ":", "first_deps", "=", "_get_api_dependencies_of", "(", "name", ",", "force", "=", "force", ")", "for", "dep", "in", "first_deps", ":", "dep", "=", "_strip_version_from_dependency", "(", "dep", ")", "if", "dep", "in", "deps", ":", "continue", "# we do the following not to resolve the dependencies of already installed daps", "if", "dap", "in", "get_installed_daps", "(", ")", ":", "continue", "deps", "|=", "_get_all_dependencies_of", "(", "dep", ",", "deps", ")", "return", "deps", "|", "set", "(", "[", "name", "]", ")" ]
Returns list of dependencies of the given dap from Dapi recursively
[ "Returns", "list", "of", "dependencies", "of", "the", "given", "dap", "from", "Dapi", "recursively" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L631-L642
train
devassistant/devassistant
devassistant/dapi/dapicli.py
_get_api_dependencies_of
def _get_api_dependencies_of(name, version='', force=False): '''Returns list of first level dependencies of the given dap from Dapi''' m, d = _get_metadap_dap(name, version=version) # We need the dependencies to install the dap, # if the dap is unsupported, raise an exception here if not force and not _is_supported_here(d): raise DapiLocalError( '{0} is not supported on this platform (use --force to suppress this check).'. format(name)) return d.get('dependencies', [])
python
def _get_api_dependencies_of(name, version='', force=False): '''Returns list of first level dependencies of the given dap from Dapi''' m, d = _get_metadap_dap(name, version=version) # We need the dependencies to install the dap, # if the dap is unsupported, raise an exception here if not force and not _is_supported_here(d): raise DapiLocalError( '{0} is not supported on this platform (use --force to suppress this check).'. format(name)) return d.get('dependencies', [])
[ "def", "_get_api_dependencies_of", "(", "name", ",", "version", "=", "''", ",", "force", "=", "False", ")", ":", "m", ",", "d", "=", "_get_metadap_dap", "(", "name", ",", "version", "=", "version", ")", "# We need the dependencies to install the dap,", "# if the dap is unsupported, raise an exception here", "if", "not", "force", "and", "not", "_is_supported_here", "(", "d", ")", ":", "raise", "DapiLocalError", "(", "'{0} is not supported on this platform (use --force to suppress this check).'", ".", "format", "(", "name", ")", ")", "return", "d", ".", "get", "(", "'dependencies'", ",", "[", "]", ")" ]
Returns list of first level dependencies of the given dap from Dapi
[ "Returns", "list", "of", "first", "level", "dependencies", "of", "the", "given", "dap", "from", "Dapi" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L645-L654
train
devassistant/devassistant
devassistant/dapi/dapicli.py
install_dap
def install_dap(name, version='', update=False, update_allpaths=False, first=True, force=False, nodeps=False, reinstall=False, __ui__=''): '''Install a dap from dapi If update is True, it will remove previously installed daps of the same name''' m, d = _get_metadap_dap(name, version) if update: available = d['version'] current = get_installed_version_of(name) if not current: raise DapiLocalError('Cannot update not yet installed DAP.') if dapver.compare(available, current) <= 0: return [] path, remove_dir = download_dap(name, d=d) ret = install_dap_from_path(path, update=update, update_allpaths=update_allpaths, first=first, force=force, nodeps=nodeps, reinstall=reinstall, __ui__=__ui__) try: if remove_dir: shutil.rmtree(os.dirname(path)) else: os.remove(path) except: pass return ret
python
def install_dap(name, version='', update=False, update_allpaths=False, first=True, force=False, nodeps=False, reinstall=False, __ui__=''): '''Install a dap from dapi If update is True, it will remove previously installed daps of the same name''' m, d = _get_metadap_dap(name, version) if update: available = d['version'] current = get_installed_version_of(name) if not current: raise DapiLocalError('Cannot update not yet installed DAP.') if dapver.compare(available, current) <= 0: return [] path, remove_dir = download_dap(name, d=d) ret = install_dap_from_path(path, update=update, update_allpaths=update_allpaths, first=first, force=force, nodeps=nodeps, reinstall=reinstall, __ui__=__ui__) try: if remove_dir: shutil.rmtree(os.dirname(path)) else: os.remove(path) except: pass return ret
[ "def", "install_dap", "(", "name", ",", "version", "=", "''", ",", "update", "=", "False", ",", "update_allpaths", "=", "False", ",", "first", "=", "True", ",", "force", "=", "False", ",", "nodeps", "=", "False", ",", "reinstall", "=", "False", ",", "__ui__", "=", "''", ")", ":", "m", ",", "d", "=", "_get_metadap_dap", "(", "name", ",", "version", ")", "if", "update", ":", "available", "=", "d", "[", "'version'", "]", "current", "=", "get_installed_version_of", "(", "name", ")", "if", "not", "current", ":", "raise", "DapiLocalError", "(", "'Cannot update not yet installed DAP.'", ")", "if", "dapver", ".", "compare", "(", "available", ",", "current", ")", "<=", "0", ":", "return", "[", "]", "path", ",", "remove_dir", "=", "download_dap", "(", "name", ",", "d", "=", "d", ")", "ret", "=", "install_dap_from_path", "(", "path", ",", "update", "=", "update", ",", "update_allpaths", "=", "update_allpaths", ",", "first", "=", "first", ",", "force", "=", "force", ",", "nodeps", "=", "nodeps", ",", "reinstall", "=", "reinstall", ",", "__ui__", "=", "__ui__", ")", "try", ":", "if", "remove_dir", ":", "shutil", ".", "rmtree", "(", "os", ".", "dirname", "(", "path", ")", ")", "else", ":", "os", ".", "remove", "(", "path", ")", "except", ":", "pass", "return", "ret" ]
Install a dap from dapi If update is True, it will remove previously installed daps of the same name
[ "Install", "a", "dap", "from", "dapi", "If", "update", "is", "True", "it", "will", "remove", "previously", "installed", "daps", "of", "the", "same", "name" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L657-L682
train
devassistant/devassistant
devassistant/dapi/dapicli.py
get_dependency_metadata
def get_dependency_metadata(): '''Returns list of strings with dependency metadata from Dapi''' link = os.path.join(_api_url(), 'meta.txt') return _process_req_txt(requests.get(link)).split('\n')
python
def get_dependency_metadata(): '''Returns list of strings with dependency metadata from Dapi''' link = os.path.join(_api_url(), 'meta.txt') return _process_req_txt(requests.get(link)).split('\n')
[ "def", "get_dependency_metadata", "(", ")", ":", "link", "=", "os", ".", "path", ".", "join", "(", "_api_url", "(", ")", ",", "'meta.txt'", ")", "return", "_process_req_txt", "(", "requests", ".", "get", "(", "link", ")", ")", ".", "split", "(", "'\\n'", ")" ]
Returns list of strings with dependency metadata from Dapi
[ "Returns", "list", "of", "strings", "with", "dependency", "metadata", "from", "Dapi" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L685-L688
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_frame
def create_frame(self): """ This function creates a frame """ frame = Gtk.Frame() frame.set_shadow_type(Gtk.ShadowType.IN) return frame
python
def create_frame(self): """ This function creates a frame """ frame = Gtk.Frame() frame.set_shadow_type(Gtk.ShadowType.IN) return frame
[ "def", "create_frame", "(", "self", ")", ":", "frame", "=", "Gtk", ".", "Frame", "(", ")", "frame", ".", "set_shadow_type", "(", "Gtk", ".", "ShadowType", ".", "IN", ")", "return", "frame" ]
This function creates a frame
[ "This", "function", "creates", "a", "frame" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L22-L28
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_box
def create_box(self, orientation=Gtk.Orientation.HORIZONTAL, spacing=0): """ Function creates box. Based on orientation it can be either HORIZONTAL or VERTICAL """ h_box = Gtk.Box(orientation=orientation, spacing=spacing) h_box.set_homogeneous(False) return h_box
python
def create_box(self, orientation=Gtk.Orientation.HORIZONTAL, spacing=0): """ Function creates box. Based on orientation it can be either HORIZONTAL or VERTICAL """ h_box = Gtk.Box(orientation=orientation, spacing=spacing) h_box.set_homogeneous(False) return h_box
[ "def", "create_box", "(", "self", ",", "orientation", "=", "Gtk", ".", "Orientation", ".", "HORIZONTAL", ",", "spacing", "=", "0", ")", ":", "h_box", "=", "Gtk", ".", "Box", "(", "orientation", "=", "orientation", ",", "spacing", "=", "spacing", ")", "h_box", ".", "set_homogeneous", "(", "False", ")", "return", "h_box" ]
Function creates box. Based on orientation it can be either HORIZONTAL or VERTICAL
[ "Function", "creates", "box", ".", "Based", "on", "orientation", "it", "can", "be", "either", "HORIZONTAL", "or", "VERTICAL" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L30-L37
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.button_with_label
def button_with_label(self, description, assistants=None): """ Function creates a button with lave. If assistant is specified then text is aligned """ btn = self.create_button() label = self.create_label(description) if assistants is not None: h_box = self.create_box(orientation=Gtk.Orientation.VERTICAL) h_box.pack_start(label, False, False, 0) label_ass = self.create_label( assistants, justify=Gtk.Justification.LEFT ) label_ass.set_alignment(0, 0) h_box.pack_start(label_ass, False, False, 12) btn.add(h_box) else: btn.add(label) return btn
python
def button_with_label(self, description, assistants=None): """ Function creates a button with lave. If assistant is specified then text is aligned """ btn = self.create_button() label = self.create_label(description) if assistants is not None: h_box = self.create_box(orientation=Gtk.Orientation.VERTICAL) h_box.pack_start(label, False, False, 0) label_ass = self.create_label( assistants, justify=Gtk.Justification.LEFT ) label_ass.set_alignment(0, 0) h_box.pack_start(label_ass, False, False, 12) btn.add(h_box) else: btn.add(label) return btn
[ "def", "button_with_label", "(", "self", ",", "description", ",", "assistants", "=", "None", ")", ":", "btn", "=", "self", ".", "create_button", "(", ")", "label", "=", "self", ".", "create_label", "(", "description", ")", "if", "assistants", "is", "not", "None", ":", "h_box", "=", "self", ".", "create_box", "(", "orientation", "=", "Gtk", ".", "Orientation", ".", "VERTICAL", ")", "h_box", ".", "pack_start", "(", "label", ",", "False", ",", "False", ",", "0", ")", "label_ass", "=", "self", ".", "create_label", "(", "assistants", ",", "justify", "=", "Gtk", ".", "Justification", ".", "LEFT", ")", "label_ass", ".", "set_alignment", "(", "0", ",", "0", ")", "h_box", ".", "pack_start", "(", "label_ass", ",", "False", ",", "False", ",", "12", ")", "btn", ".", "add", "(", "h_box", ")", "else", ":", "btn", ".", "add", "(", "label", ")", "return", "btn" ]
Function creates a button with lave. If assistant is specified then text is aligned
[ "Function", "creates", "a", "button", "with", "lave", ".", "If", "assistant", "is", "specified", "then", "text", "is", "aligned" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L39-L57
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_image
def create_image(self, image_name=None, scale_ratio=1, window=None): """ The function creates a image from name defined in image_name """ size = 48 * scale_ratio pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(image_name, -1, size, True) image = Gtk.Image() # Creating the cairo surface is necessary for proper scaling on HiDPI try: surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale_ratio, window) image.set_from_surface(surface) # Fallback for GTK+ older than 3.10 except AttributeError: image.set_from_pixbuf(pixbuf) return image
python
def create_image(self, image_name=None, scale_ratio=1, window=None): """ The function creates a image from name defined in image_name """ size = 48 * scale_ratio pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(image_name, -1, size, True) image = Gtk.Image() # Creating the cairo surface is necessary for proper scaling on HiDPI try: surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale_ratio, window) image.set_from_surface(surface) # Fallback for GTK+ older than 3.10 except AttributeError: image.set_from_pixbuf(pixbuf) return image
[ "def", "create_image", "(", "self", ",", "image_name", "=", "None", ",", "scale_ratio", "=", "1", ",", "window", "=", "None", ")", ":", "size", "=", "48", "*", "scale_ratio", "pixbuf", "=", "GdkPixbuf", ".", "Pixbuf", ".", "new_from_file_at_scale", "(", "image_name", ",", "-", "1", ",", "size", ",", "True", ")", "image", "=", "Gtk", ".", "Image", "(", ")", "# Creating the cairo surface is necessary for proper scaling on HiDPI", "try", ":", "surface", "=", "Gdk", ".", "cairo_surface_create_from_pixbuf", "(", "pixbuf", ",", "scale_ratio", ",", "window", ")", "image", ".", "set_from_surface", "(", "surface", ")", "# Fallback for GTK+ older than 3.10", "except", "AttributeError", ":", "image", ".", "set_from_pixbuf", "(", "pixbuf", ")", "return", "image" ]
The function creates a image from name defined in image_name
[ "The", "function", "creates", "a", "image", "from", "name", "defined", "in", "image_name" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L59-L76
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.button_with_image
def button_with_image(self, description, image=None, sensitive=True): """ The function creates a button with image """ btn = self.create_button() btn.set_sensitive(sensitive) h_box = self.create_box() try: img = self.create_image(image_name=image, scale_ratio=btn.get_scale_factor(), window=btn.get_window()) except: # Older GTK+ than 3.10 img = self.create_image(image_name=image) h_box.pack_start(img, False, False, 12) label = self.create_label(description) h_box.pack_start(label, False, False, 0) btn.add(h_box) return btn
python
def button_with_image(self, description, image=None, sensitive=True): """ The function creates a button with image """ btn = self.create_button() btn.set_sensitive(sensitive) h_box = self.create_box() try: img = self.create_image(image_name=image, scale_ratio=btn.get_scale_factor(), window=btn.get_window()) except: # Older GTK+ than 3.10 img = self.create_image(image_name=image) h_box.pack_start(img, False, False, 12) label = self.create_label(description) h_box.pack_start(label, False, False, 0) btn.add(h_box) return btn
[ "def", "button_with_image", "(", "self", ",", "description", ",", "image", "=", "None", ",", "sensitive", "=", "True", ")", ":", "btn", "=", "self", ".", "create_button", "(", ")", "btn", ".", "set_sensitive", "(", "sensitive", ")", "h_box", "=", "self", ".", "create_box", "(", ")", "try", ":", "img", "=", "self", ".", "create_image", "(", "image_name", "=", "image", ",", "scale_ratio", "=", "btn", ".", "get_scale_factor", "(", ")", ",", "window", "=", "btn", ".", "get_window", "(", ")", ")", "except", ":", "# Older GTK+ than 3.10", "img", "=", "self", ".", "create_image", "(", "image_name", "=", "image", ")", "h_box", ".", "pack_start", "(", "img", ",", "False", ",", "False", ",", "12", ")", "label", "=", "self", ".", "create_label", "(", "description", ")", "h_box", ".", "pack_start", "(", "label", ",", "False", ",", "False", ",", "0", ")", "btn", ".", "add", "(", "h_box", ")", "return", "btn" ]
The function creates a button with image
[ "The", "function", "creates", "a", "button", "with", "image" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L78-L95
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.checkbutton_with_label
def checkbutton_with_label(self, description): """ The function creates a checkbutton with label """ act_btn = Gtk.CheckButton(description) align = self.create_alignment() act_btn.add(align) return align
python
def checkbutton_with_label(self, description): """ The function creates a checkbutton with label """ act_btn = Gtk.CheckButton(description) align = self.create_alignment() act_btn.add(align) return align
[ "def", "checkbutton_with_label", "(", "self", ",", "description", ")", ":", "act_btn", "=", "Gtk", ".", "CheckButton", "(", "description", ")", "align", "=", "self", ".", "create_alignment", "(", ")", "act_btn", ".", "add", "(", "align", ")", "return", "align" ]
The function creates a checkbutton with label
[ "The", "function", "creates", "a", "checkbutton", "with", "label" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L97-L104
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_checkbox
def create_checkbox(self, name, margin=10): """ Function creates a checkbox with his name """ chk_btn = Gtk.CheckButton(name) chk_btn.set_margin_right(margin) return chk_btn
python
def create_checkbox(self, name, margin=10): """ Function creates a checkbox with his name """ chk_btn = Gtk.CheckButton(name) chk_btn.set_margin_right(margin) return chk_btn
[ "def", "create_checkbox", "(", "self", ",", "name", ",", "margin", "=", "10", ")", ":", "chk_btn", "=", "Gtk", ".", "CheckButton", "(", "name", ")", "chk_btn", ".", "set_margin_right", "(", "margin", ")", "return", "chk_btn" ]
Function creates a checkbox with his name
[ "Function", "creates", "a", "checkbox", "with", "his", "name" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L113-L119
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_entry
def create_entry(self, text="", sensitive="False"): """ Function creates an Entry with corresponding text """ text_entry = Gtk.Entry() text_entry.set_sensitive(sensitive) text_entry.set_text(text) return text_entry
python
def create_entry(self, text="", sensitive="False"): """ Function creates an Entry with corresponding text """ text_entry = Gtk.Entry() text_entry.set_sensitive(sensitive) text_entry.set_text(text) return text_entry
[ "def", "create_entry", "(", "self", ",", "text", "=", "\"\"", ",", "sensitive", "=", "\"False\"", ")", ":", "text_entry", "=", "Gtk", ".", "Entry", "(", ")", "text_entry", ".", "set_sensitive", "(", "sensitive", ")", "text_entry", ".", "set_text", "(", "text", ")", "return", "text_entry" ]
Function creates an Entry with corresponding text
[ "Function", "creates", "an", "Entry", "with", "corresponding", "text" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L121-L128
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_link_button
def create_link_button(self, text="None", uri="None"): """ Function creates a link button with corresponding text and URI reference """ link_btn = Gtk.LinkButton(uri, text) return link_btn
python
def create_link_button(self, text="None", uri="None"): """ Function creates a link button with corresponding text and URI reference """ link_btn = Gtk.LinkButton(uri, text) return link_btn
[ "def", "create_link_button", "(", "self", ",", "text", "=", "\"None\"", ",", "uri", "=", "\"None\"", ")", ":", "link_btn", "=", "Gtk", ".", "LinkButton", "(", "uri", ",", "text", ")", "return", "link_btn" ]
Function creates a link button with corresponding text and URI reference
[ "Function", "creates", "a", "link", "button", "with", "corresponding", "text", "and", "URI", "reference" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L130-L136
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_button
def create_button(self, style=Gtk.ReliefStyle.NORMAL): """ This is generalized method for creating Gtk.Button """ btn = Gtk.Button() btn.set_relief(style) return btn
python
def create_button(self, style=Gtk.ReliefStyle.NORMAL): """ This is generalized method for creating Gtk.Button """ btn = Gtk.Button() btn.set_relief(style) return btn
[ "def", "create_button", "(", "self", ",", "style", "=", "Gtk", ".", "ReliefStyle", ".", "NORMAL", ")", ":", "btn", "=", "Gtk", ".", "Button", "(", ")", "btn", ".", "set_relief", "(", "style", ")", "return", "btn" ]
This is generalized method for creating Gtk.Button
[ "This", "is", "generalized", "method", "for", "creating", "Gtk", ".", "Button" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L138-L144
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_image_menu_item
def create_image_menu_item(self, text, image_name): """ Function creates a menu item with an image """ menu_item = Gtk.ImageMenuItem(text) img = self.create_image(image_name) menu_item.set_image(img) return menu_item
python
def create_image_menu_item(self, text, image_name): """ Function creates a menu item with an image """ menu_item = Gtk.ImageMenuItem(text) img = self.create_image(image_name) menu_item.set_image(img) return menu_item
[ "def", "create_image_menu_item", "(", "self", ",", "text", ",", "image_name", ")", ":", "menu_item", "=", "Gtk", ".", "ImageMenuItem", "(", "text", ")", "img", "=", "self", ".", "create_image", "(", "image_name", ")", "menu_item", ".", "set_image", "(", "img", ")", "return", "menu_item" ]
Function creates a menu item with an image
[ "Function", "creates", "a", "menu", "item", "with", "an", "image" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L153-L160
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_label
def create_label(self, name, justify=Gtk.Justification.CENTER, wrap_mode=True, tooltip=None): """ The function is used for creating lable with HTML text """ label = Gtk.Label() name = name.replace('|', '\n') label.set_markup(name) label.set_justify(justify) label.set_line_wrap(wrap_mode) if tooltip is not None: label.set_has_tooltip(True) label.connect("query-tooltip", self.parent.tooltip_queries, tooltip) return label
python
def create_label(self, name, justify=Gtk.Justification.CENTER, wrap_mode=True, tooltip=None): """ The function is used for creating lable with HTML text """ label = Gtk.Label() name = name.replace('|', '\n') label.set_markup(name) label.set_justify(justify) label.set_line_wrap(wrap_mode) if tooltip is not None: label.set_has_tooltip(True) label.connect("query-tooltip", self.parent.tooltip_queries, tooltip) return label
[ "def", "create_label", "(", "self", ",", "name", ",", "justify", "=", "Gtk", ".", "Justification", ".", "CENTER", ",", "wrap_mode", "=", "True", ",", "tooltip", "=", "None", ")", ":", "label", "=", "Gtk", ".", "Label", "(", ")", "name", "=", "name", ".", "replace", "(", "'|'", ",", "'\\n'", ")", "label", ".", "set_markup", "(", "name", ")", "label", ".", "set_justify", "(", "justify", ")", "label", ".", "set_line_wrap", "(", "wrap_mode", ")", "if", "tooltip", "is", "not", "None", ":", "label", ".", "set_has_tooltip", "(", "True", ")", "label", ".", "connect", "(", "\"query-tooltip\"", ",", "self", ".", "parent", ".", "tooltip_queries", ",", "tooltip", ")", "return", "label" ]
The function is used for creating lable with HTML text
[ "The", "function", "is", "used", "for", "creating", "lable", "with", "HTML", "text" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L162-L174
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.add_button
def add_button(self, grid_lang, ass, row, column): """ The function is used for creating button with all features like signal on tooltip and signal on clicked The function does not have any menu. Button is add to the Gtk.Grid on specific row and column """ #print "gui_helper add_button" image_name = ass[0].icon_path label = "<b>" + ass[0].fullname + "</b>" if not image_name: btn = self.button_with_label(label) else: btn = self.button_with_image(label, image=ass[0].icon_path) #print "Dependencies button",ass[0]._dependencies if ass[0].description: btn.set_has_tooltip(True) btn.connect("query-tooltip", self.parent.tooltip_queries, self.get_formatted_description(ass[0].description) ) btn.connect("clicked", self.parent.btn_clicked, ass[0].name) if row == 0 and column == 0: grid_lang.add(btn) else: grid_lang.attach(btn, column, row, 1, 1) return btn
python
def add_button(self, grid_lang, ass, row, column): """ The function is used for creating button with all features like signal on tooltip and signal on clicked The function does not have any menu. Button is add to the Gtk.Grid on specific row and column """ #print "gui_helper add_button" image_name = ass[0].icon_path label = "<b>" + ass[0].fullname + "</b>" if not image_name: btn = self.button_with_label(label) else: btn = self.button_with_image(label, image=ass[0].icon_path) #print "Dependencies button",ass[0]._dependencies if ass[0].description: btn.set_has_tooltip(True) btn.connect("query-tooltip", self.parent.tooltip_queries, self.get_formatted_description(ass[0].description) ) btn.connect("clicked", self.parent.btn_clicked, ass[0].name) if row == 0 and column == 0: grid_lang.add(btn) else: grid_lang.attach(btn, column, row, 1, 1) return btn
[ "def", "add_button", "(", "self", ",", "grid_lang", ",", "ass", ",", "row", ",", "column", ")", ":", "#print \"gui_helper add_button\"", "image_name", "=", "ass", "[", "0", "]", ".", "icon_path", "label", "=", "\"<b>\"", "+", "ass", "[", "0", "]", ".", "fullname", "+", "\"</b>\"", "if", "not", "image_name", ":", "btn", "=", "self", ".", "button_with_label", "(", "label", ")", "else", ":", "btn", "=", "self", ".", "button_with_image", "(", "label", ",", "image", "=", "ass", "[", "0", "]", ".", "icon_path", ")", "#print \"Dependencies button\",ass[0]._dependencies", "if", "ass", "[", "0", "]", ".", "description", ":", "btn", ".", "set_has_tooltip", "(", "True", ")", "btn", ".", "connect", "(", "\"query-tooltip\"", ",", "self", ".", "parent", ".", "tooltip_queries", ",", "self", ".", "get_formatted_description", "(", "ass", "[", "0", "]", ".", "description", ")", ")", "btn", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "parent", ".", "btn_clicked", ",", "ass", "[", "0", "]", ".", "name", ")", "if", "row", "==", "0", "and", "column", "==", "0", ":", "grid_lang", ".", "add", "(", "btn", ")", "else", ":", "grid_lang", ".", "attach", "(", "btn", ",", "column", ",", "row", ",", "1", ",", "1", ")", "return", "btn" ]
The function is used for creating button with all features like signal on tooltip and signal on clicked The function does not have any menu. Button is add to the Gtk.Grid on specific row and column
[ "The", "function", "is", "used", "for", "creating", "button", "with", "all", "features", "like", "signal", "on", "tooltip", "and", "signal", "on", "clicked", "The", "function", "does", "not", "have", "any", "menu", ".", "Button", "is", "add", "to", "the", "Gtk", ".", "Grid", "on", "specific", "row", "and", "column" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L176-L202
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.add_install_button
def add_install_button(self, grid_lang, row, column): """ Add button that opens the window for installing more assistants """ btn = self.button_with_label('<b>Install more...</b>') if row == 0 and column == 0: grid_lang.add(btn) else: grid_lang.attach(btn, column, row, 1, 1) btn.connect("clicked", self.parent.install_btn_clicked) return btn
python
def add_install_button(self, grid_lang, row, column): """ Add button that opens the window for installing more assistants """ btn = self.button_with_label('<b>Install more...</b>') if row == 0 and column == 0: grid_lang.add(btn) else: grid_lang.attach(btn, column, row, 1, 1) btn.connect("clicked", self.parent.install_btn_clicked) return btn
[ "def", "add_install_button", "(", "self", ",", "grid_lang", ",", "row", ",", "column", ")", ":", "btn", "=", "self", ".", "button_with_label", "(", "'<b>Install more...</b>'", ")", "if", "row", "==", "0", "and", "column", "==", "0", ":", "grid_lang", ".", "add", "(", "btn", ")", "else", ":", "grid_lang", ".", "attach", "(", "btn", ",", "column", ",", "row", ",", "1", ",", "1", ")", "btn", ".", "connect", "(", "\"clicked\"", ",", "self", ".", "parent", ".", "install_btn_clicked", ")", "return", "btn" ]
Add button that opens the window for installing more assistants
[ "Add", "button", "that", "opens", "the", "window", "for", "installing", "more", "assistants" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L204-L214
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.menu_item
def menu_item(self, sub_assistant, path): """ The function creates a menu item and assigns signal like select and button-press-event for manipulation with menu_item. sub_assistant and path """ if not sub_assistant[0].icon_path: menu_item = self.create_menu_item(sub_assistant[0].fullname) else: menu_item = self.create_image_menu_item( sub_assistant[0].fullname, sub_assistant[0].icon_path ) if sub_assistant[0].description: menu_item.set_has_tooltip(True) menu_item.connect("query-tooltip", self.parent.tooltip_queries, self.get_formatted_description(sub_assistant[0].description), ) menu_item.connect("select", self.parent.sub_menu_select, path) menu_item.connect("button-press-event", self.parent.sub_menu_pressed) menu_item.show() return menu_item
python
def menu_item(self, sub_assistant, path): """ The function creates a menu item and assigns signal like select and button-press-event for manipulation with menu_item. sub_assistant and path """ if not sub_assistant[0].icon_path: menu_item = self.create_menu_item(sub_assistant[0].fullname) else: menu_item = self.create_image_menu_item( sub_assistant[0].fullname, sub_assistant[0].icon_path ) if sub_assistant[0].description: menu_item.set_has_tooltip(True) menu_item.connect("query-tooltip", self.parent.tooltip_queries, self.get_formatted_description(sub_assistant[0].description), ) menu_item.connect("select", self.parent.sub_menu_select, path) menu_item.connect("button-press-event", self.parent.sub_menu_pressed) menu_item.show() return menu_item
[ "def", "menu_item", "(", "self", ",", "sub_assistant", ",", "path", ")", ":", "if", "not", "sub_assistant", "[", "0", "]", ".", "icon_path", ":", "menu_item", "=", "self", ".", "create_menu_item", "(", "sub_assistant", "[", "0", "]", ".", "fullname", ")", "else", ":", "menu_item", "=", "self", ".", "create_image_menu_item", "(", "sub_assistant", "[", "0", "]", ".", "fullname", ",", "sub_assistant", "[", "0", "]", ".", "icon_path", ")", "if", "sub_assistant", "[", "0", "]", ".", "description", ":", "menu_item", ".", "set_has_tooltip", "(", "True", ")", "menu_item", ".", "connect", "(", "\"query-tooltip\"", ",", "self", ".", "parent", ".", "tooltip_queries", ",", "self", ".", "get_formatted_description", "(", "sub_assistant", "[", "0", "]", ".", "description", ")", ",", ")", "menu_item", ".", "connect", "(", "\"select\"", ",", "self", ".", "parent", ".", "sub_menu_select", ",", "path", ")", "menu_item", ".", "connect", "(", "\"button-press-event\"", ",", "self", ".", "parent", ".", "sub_menu_pressed", ")", "menu_item", ".", "show", "(", ")", "return", "menu_item" ]
The function creates a menu item and assigns signal like select and button-press-event for manipulation with menu_item. sub_assistant and path
[ "The", "function", "creates", "a", "menu", "item", "and", "assigns", "signal", "like", "select", "and", "button", "-", "press", "-", "event", "for", "manipulation", "with", "menu_item", ".", "sub_assistant", "and", "path" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L224-L245
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.generate_menu
def generate_menu(self, ass, text, path=None, level=0): """ Function generates menu from based on ass parameter """ menu = self.create_menu() for index, sub in enumerate(sorted(ass[1], key=lambda y: y[0].fullname.lower())): if index != 0: text += "|" text += "- " + sub[0].fullname new_path = list(path) if level == 0: new_path.append(ass[0].name) new_path.append(sub[0].name) menu_item = self.menu_item(sub, new_path) if sub[1]: # If assistant has subassistants (sub_menu, txt) = self.generate_menu(sub, text, new_path, level=level + 1) menu_item.set_submenu(sub_menu) menu.append(menu_item) return menu, text
python
def generate_menu(self, ass, text, path=None, level=0): """ Function generates menu from based on ass parameter """ menu = self.create_menu() for index, sub in enumerate(sorted(ass[1], key=lambda y: y[0].fullname.lower())): if index != 0: text += "|" text += "- " + sub[0].fullname new_path = list(path) if level == 0: new_path.append(ass[0].name) new_path.append(sub[0].name) menu_item = self.menu_item(sub, new_path) if sub[1]: # If assistant has subassistants (sub_menu, txt) = self.generate_menu(sub, text, new_path, level=level + 1) menu_item.set_submenu(sub_menu) menu.append(menu_item) return menu, text
[ "def", "generate_menu", "(", "self", ",", "ass", ",", "text", ",", "path", "=", "None", ",", "level", "=", "0", ")", ":", "menu", "=", "self", ".", "create_menu", "(", ")", "for", "index", ",", "sub", "in", "enumerate", "(", "sorted", "(", "ass", "[", "1", "]", ",", "key", "=", "lambda", "y", ":", "y", "[", "0", "]", ".", "fullname", ".", "lower", "(", ")", ")", ")", ":", "if", "index", "!=", "0", ":", "text", "+=", "\"|\"", "text", "+=", "\"- \"", "+", "sub", "[", "0", "]", ".", "fullname", "new_path", "=", "list", "(", "path", ")", "if", "level", "==", "0", ":", "new_path", ".", "append", "(", "ass", "[", "0", "]", ".", "name", ")", "new_path", ".", "append", "(", "sub", "[", "0", "]", ".", "name", ")", "menu_item", "=", "self", ".", "menu_item", "(", "sub", ",", "new_path", ")", "if", "sub", "[", "1", "]", ":", "# If assistant has subassistants", "(", "sub_menu", ",", "txt", ")", "=", "self", ".", "generate_menu", "(", "sub", ",", "text", ",", "new_path", ",", "level", "=", "level", "+", "1", ")", "menu_item", ".", "set_submenu", "(", "sub_menu", ")", "menu", ".", "append", "(", "menu_item", ")", "return", "menu", ",", "text" ]
Function generates menu from based on ass parameter
[ "Function", "generates", "menu", "from", "based", "on", "ass", "parameter" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L247-L266
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.add_submenu
def add_submenu(self, grid_lang, ass, row, column): """ The function is used for creating button with menu and submenu. Also signal on tooltip and signal on clicked are specified Button is add to the Gtk.Grid """ text = "Available subassistants:\n" # Generate menus path = [] (menu, text) = self.generate_menu(ass, text, path=path) menu.show_all() if ass[0].description: description = self.get_formatted_description(ass[0].description) + "\n\n" else: description = "" description += text.replace('|', '\n') image_name = ass[0].icon_path lbl_text = "<b>" + ass[0].fullname + "</b>" if not image_name: btn = self.button_with_label(lbl_text) else: btn = self.button_with_image(lbl_text, image=image_name) btn.set_has_tooltip(True) btn.connect("query-tooltip", self.parent.tooltip_queries, description ) btn.connect_object("event", self.parent.btn_press_event, menu) if row == 0 and column == 0: grid_lang.add(btn) else: grid_lang.attach(btn, column, row, 1, 1)
python
def add_submenu(self, grid_lang, ass, row, column): """ The function is used for creating button with menu and submenu. Also signal on tooltip and signal on clicked are specified Button is add to the Gtk.Grid """ text = "Available subassistants:\n" # Generate menus path = [] (menu, text) = self.generate_menu(ass, text, path=path) menu.show_all() if ass[0].description: description = self.get_formatted_description(ass[0].description) + "\n\n" else: description = "" description += text.replace('|', '\n') image_name = ass[0].icon_path lbl_text = "<b>" + ass[0].fullname + "</b>" if not image_name: btn = self.button_with_label(lbl_text) else: btn = self.button_with_image(lbl_text, image=image_name) btn.set_has_tooltip(True) btn.connect("query-tooltip", self.parent.tooltip_queries, description ) btn.connect_object("event", self.parent.btn_press_event, menu) if row == 0 and column == 0: grid_lang.add(btn) else: grid_lang.attach(btn, column, row, 1, 1)
[ "def", "add_submenu", "(", "self", ",", "grid_lang", ",", "ass", ",", "row", ",", "column", ")", ":", "text", "=", "\"Available subassistants:\\n\"", "# Generate menus", "path", "=", "[", "]", "(", "menu", ",", "text", ")", "=", "self", ".", "generate_menu", "(", "ass", ",", "text", ",", "path", "=", "path", ")", "menu", ".", "show_all", "(", ")", "if", "ass", "[", "0", "]", ".", "description", ":", "description", "=", "self", ".", "get_formatted_description", "(", "ass", "[", "0", "]", ".", "description", ")", "+", "\"\\n\\n\"", "else", ":", "description", "=", "\"\"", "description", "+=", "text", ".", "replace", "(", "'|'", ",", "'\\n'", ")", "image_name", "=", "ass", "[", "0", "]", ".", "icon_path", "lbl_text", "=", "\"<b>\"", "+", "ass", "[", "0", "]", ".", "fullname", "+", "\"</b>\"", "if", "not", "image_name", ":", "btn", "=", "self", ".", "button_with_label", "(", "lbl_text", ")", "else", ":", "btn", "=", "self", ".", "button_with_image", "(", "lbl_text", ",", "image", "=", "image_name", ")", "btn", ".", "set_has_tooltip", "(", "True", ")", "btn", ".", "connect", "(", "\"query-tooltip\"", ",", "self", ".", "parent", ".", "tooltip_queries", ",", "description", ")", "btn", ".", "connect_object", "(", "\"event\"", ",", "self", ".", "parent", ".", "btn_press_event", ",", "menu", ")", "if", "row", "==", "0", "and", "column", "==", "0", ":", "grid_lang", ".", "add", "(", "btn", ")", "else", ":", "grid_lang", ".", "attach", "(", "btn", ",", "column", ",", "row", ",", "1", ",", "1", ")" ]
The function is used for creating button with menu and submenu. Also signal on tooltip and signal on clicked are specified Button is add to the Gtk.Grid
[ "The", "function", "is", "used", "for", "creating", "button", "with", "menu", "and", "submenu", ".", "Also", "signal", "on", "tooltip", "and", "signal", "on", "clicked", "are", "specified", "Button", "is", "add", "to", "the", "Gtk", ".", "Grid" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L268-L299
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_scrolled_window
def create_scrolled_window(self, layout_manager, horizontal=Gtk.PolicyType.NEVER, vertical=Gtk.PolicyType.ALWAYS): """ Function creates a scrolled window with layout manager """ scrolled_window = Gtk.ScrolledWindow() scrolled_window.add(layout_manager) scrolled_window.set_policy(horizontal, vertical) return scrolled_window
python
def create_scrolled_window(self, layout_manager, horizontal=Gtk.PolicyType.NEVER, vertical=Gtk.PolicyType.ALWAYS): """ Function creates a scrolled window with layout manager """ scrolled_window = Gtk.ScrolledWindow() scrolled_window.add(layout_manager) scrolled_window.set_policy(horizontal, vertical) return scrolled_window
[ "def", "create_scrolled_window", "(", "self", ",", "layout_manager", ",", "horizontal", "=", "Gtk", ".", "PolicyType", ".", "NEVER", ",", "vertical", "=", "Gtk", ".", "PolicyType", ".", "ALWAYS", ")", ":", "scrolled_window", "=", "Gtk", ".", "ScrolledWindow", "(", ")", "scrolled_window", ".", "add", "(", "layout_manager", ")", "scrolled_window", ".", "set_policy", "(", "horizontal", ",", "vertical", ")", "return", "scrolled_window" ]
Function creates a scrolled window with layout manager
[ "Function", "creates", "a", "scrolled", "window", "with", "layout", "manager" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L328-L335
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_gtk_grid
def create_gtk_grid(self, row_spacing=6, col_spacing=6, row_homogenous=False, col_homogenous=True): """ Function creates a Gtk Grid with spacing and homogeous tags """ grid_lang = Gtk.Grid() grid_lang.set_column_spacing(row_spacing) grid_lang.set_row_spacing(col_spacing) grid_lang.set_border_width(12) grid_lang.set_row_homogeneous(row_homogenous) grid_lang.set_column_homogeneous(col_homogenous) return grid_lang
python
def create_gtk_grid(self, row_spacing=6, col_spacing=6, row_homogenous=False, col_homogenous=True): """ Function creates a Gtk Grid with spacing and homogeous tags """ grid_lang = Gtk.Grid() grid_lang.set_column_spacing(row_spacing) grid_lang.set_row_spacing(col_spacing) grid_lang.set_border_width(12) grid_lang.set_row_homogeneous(row_homogenous) grid_lang.set_column_homogeneous(col_homogenous) return grid_lang
[ "def", "create_gtk_grid", "(", "self", ",", "row_spacing", "=", "6", ",", "col_spacing", "=", "6", ",", "row_homogenous", "=", "False", ",", "col_homogenous", "=", "True", ")", ":", "grid_lang", "=", "Gtk", ".", "Grid", "(", ")", "grid_lang", ".", "set_column_spacing", "(", "row_spacing", ")", "grid_lang", ".", "set_row_spacing", "(", "col_spacing", ")", "grid_lang", ".", "set_border_width", "(", "12", ")", "grid_lang", ".", "set_row_homogeneous", "(", "row_homogenous", ")", "grid_lang", ".", "set_column_homogeneous", "(", "col_homogenous", ")", "return", "grid_lang" ]
Function creates a Gtk Grid with spacing and homogeous tags
[ "Function", "creates", "a", "Gtk", "Grid", "with", "spacing", "and", "homogeous", "tags" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L337-L348
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_notebook
def create_notebook(self, position=Gtk.PositionType.TOP): """ Function creates a notebook """ notebook = Gtk.Notebook() notebook.set_tab_pos(position) notebook.set_show_border(True) return notebook
python
def create_notebook(self, position=Gtk.PositionType.TOP): """ Function creates a notebook """ notebook = Gtk.Notebook() notebook.set_tab_pos(position) notebook.set_show_border(True) return notebook
[ "def", "create_notebook", "(", "self", ",", "position", "=", "Gtk", ".", "PositionType", ".", "TOP", ")", ":", "notebook", "=", "Gtk", ".", "Notebook", "(", ")", "notebook", ".", "set_tab_pos", "(", "position", ")", "notebook", ".", "set_show_border", "(", "True", ")", "return", "notebook" ]
Function creates a notebook
[ "Function", "creates", "a", "notebook" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L350-L357
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_message_dialog
def create_message_dialog(self, text, buttons=Gtk.ButtonsType.CLOSE, icon=Gtk.MessageType.WARNING): """ Function creates a message dialog with text and relevant buttons """ dialog = Gtk.MessageDialog(None, Gtk.DialogFlags.DESTROY_WITH_PARENT, icon, buttons, text ) return dialog
python
def create_message_dialog(self, text, buttons=Gtk.ButtonsType.CLOSE, icon=Gtk.MessageType.WARNING): """ Function creates a message dialog with text and relevant buttons """ dialog = Gtk.MessageDialog(None, Gtk.DialogFlags.DESTROY_WITH_PARENT, icon, buttons, text ) return dialog
[ "def", "create_message_dialog", "(", "self", ",", "text", ",", "buttons", "=", "Gtk", ".", "ButtonsType", ".", "CLOSE", ",", "icon", "=", "Gtk", ".", "MessageType", ".", "WARNING", ")", ":", "dialog", "=", "Gtk", ".", "MessageDialog", "(", "None", ",", "Gtk", ".", "DialogFlags", ".", "DESTROY_WITH_PARENT", ",", "icon", ",", "buttons", ",", "text", ")", "return", "dialog" ]
Function creates a message dialog with text and relevant buttons
[ "Function", "creates", "a", "message", "dialog", "with", "text", "and", "relevant", "buttons" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L359-L370
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_question_dialog
def create_question_dialog(self, text, second_text): """ Function creates a question dialog with title text and second_text """ dialog = self.create_message_dialog( text, buttons=Gtk.ButtonsType.YES_NO, icon=Gtk.MessageType.QUESTION ) dialog.format_secondary_text(second_text) response = dialog.run() dialog.destroy() return response
python
def create_question_dialog(self, text, second_text): """ Function creates a question dialog with title text and second_text """ dialog = self.create_message_dialog( text, buttons=Gtk.ButtonsType.YES_NO, icon=Gtk.MessageType.QUESTION ) dialog.format_secondary_text(second_text) response = dialog.run() dialog.destroy() return response
[ "def", "create_question_dialog", "(", "self", ",", "text", ",", "second_text", ")", ":", "dialog", "=", "self", ".", "create_message_dialog", "(", "text", ",", "buttons", "=", "Gtk", ".", "ButtonsType", ".", "YES_NO", ",", "icon", "=", "Gtk", ".", "MessageType", ".", "QUESTION", ")", "dialog", ".", "format_secondary_text", "(", "second_text", ")", "response", "=", "dialog", ".", "run", "(", ")", "dialog", ".", "destroy", "(", ")", "return", "response" ]
Function creates a question dialog with title text and second_text
[ "Function", "creates", "a", "question", "dialog", "with", "title", "text", "and", "second_text" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L372-L383
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.execute_dialog
def execute_dialog(self, title): """ Function executes a dialog """ msg_dlg = self.create_message_dialog(title) msg_dlg.run() msg_dlg.destroy() return
python
def execute_dialog(self, title): """ Function executes a dialog """ msg_dlg = self.create_message_dialog(title) msg_dlg.run() msg_dlg.destroy() return
[ "def", "execute_dialog", "(", "self", ",", "title", ")", ":", "msg_dlg", "=", "self", ".", "create_message_dialog", "(", "title", ")", "msg_dlg", ".", "run", "(", ")", "msg_dlg", ".", "destroy", "(", ")", "return" ]
Function executes a dialog
[ "Function", "executes", "a", "dialog" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L385-L392
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_file_chooser_dialog
def create_file_chooser_dialog(self, text, parent, name=Gtk.STOCK_OPEN): """ Function creates a file chooser dialog with title text """ text = None dialog = Gtk.FileChooserDialog( text, parent, Gtk.FileChooserAction.SELECT_FOLDER, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, name, Gtk.ResponseType.OK) ) response = dialog.run() if response == Gtk.ResponseType.OK: text = dialog.get_filename() dialog.destroy() return text
python
def create_file_chooser_dialog(self, text, parent, name=Gtk.STOCK_OPEN): """ Function creates a file chooser dialog with title text """ text = None dialog = Gtk.FileChooserDialog( text, parent, Gtk.FileChooserAction.SELECT_FOLDER, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, name, Gtk.ResponseType.OK) ) response = dialog.run() if response == Gtk.ResponseType.OK: text = dialog.get_filename() dialog.destroy() return text
[ "def", "create_file_chooser_dialog", "(", "self", ",", "text", ",", "parent", ",", "name", "=", "Gtk", ".", "STOCK_OPEN", ")", ":", "text", "=", "None", "dialog", "=", "Gtk", ".", "FileChooserDialog", "(", "text", ",", "parent", ",", "Gtk", ".", "FileChooserAction", ".", "SELECT_FOLDER", ",", "(", "Gtk", ".", "STOCK_CANCEL", ",", "Gtk", ".", "ResponseType", ".", "CANCEL", ",", "name", ",", "Gtk", ".", "ResponseType", ".", "OK", ")", ")", "response", "=", "dialog", ".", "run", "(", ")", "if", "response", "==", "Gtk", ".", "ResponseType", ".", "OK", ":", "text", "=", "dialog", ".", "get_filename", "(", ")", "dialog", ".", "destroy", "(", ")", "return", "text" ]
Function creates a file chooser dialog with title text
[ "Function", "creates", "a", "file", "chooser", "dialog", "with", "title", "text" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L394-L408
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_alignment
def create_alignment(self, x_align=0, y_align=0, x_scale=0, y_scale=0): """ Function creates an alignment """ align = Gtk.Alignment() align.set(x_align, y_align, x_scale, y_scale) return align
python
def create_alignment(self, x_align=0, y_align=0, x_scale=0, y_scale=0): """ Function creates an alignment """ align = Gtk.Alignment() align.set(x_align, y_align, x_scale, y_scale) return align
[ "def", "create_alignment", "(", "self", ",", "x_align", "=", "0", ",", "y_align", "=", "0", ",", "x_scale", "=", "0", ",", "y_scale", "=", "0", ")", ":", "align", "=", "Gtk", ".", "Alignment", "(", ")", "align", ".", "set", "(", "x_align", ",", "y_align", ",", "x_scale", ",", "y_scale", ")", "return", "align" ]
Function creates an alignment
[ "Function", "creates", "an", "alignment" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L410-L416
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_textview
def create_textview(self, wrap_mode=Gtk.WrapMode.WORD_CHAR, justify=Gtk.Justification.LEFT, visible=True, editable=True): """ Function creates a text view with wrap_mode and justification """ text_view = Gtk.TextView() text_view.set_wrap_mode(wrap_mode) text_view.set_editable(editable) if not editable: text_view.set_cursor_visible(False) else: text_view.set_cursor_visible(visible) text_view.set_justification(justify) return text_view
python
def create_textview(self, wrap_mode=Gtk.WrapMode.WORD_CHAR, justify=Gtk.Justification.LEFT, visible=True, editable=True): """ Function creates a text view with wrap_mode and justification """ text_view = Gtk.TextView() text_view.set_wrap_mode(wrap_mode) text_view.set_editable(editable) if not editable: text_view.set_cursor_visible(False) else: text_view.set_cursor_visible(visible) text_view.set_justification(justify) return text_view
[ "def", "create_textview", "(", "self", ",", "wrap_mode", "=", "Gtk", ".", "WrapMode", ".", "WORD_CHAR", ",", "justify", "=", "Gtk", ".", "Justification", ".", "LEFT", ",", "visible", "=", "True", ",", "editable", "=", "True", ")", ":", "text_view", "=", "Gtk", ".", "TextView", "(", ")", "text_view", ".", "set_wrap_mode", "(", "wrap_mode", ")", "text_view", ".", "set_editable", "(", "editable", ")", "if", "not", "editable", ":", "text_view", ".", "set_cursor_visible", "(", "False", ")", "else", ":", "text_view", ".", "set_cursor_visible", "(", "visible", ")", "text_view", ".", "set_justification", "(", "justify", ")", "return", "text_view" ]
Function creates a text view with wrap_mode and justification
[ "Function", "creates", "a", "text", "view", "with", "wrap_mode", "and", "justification" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L418-L431
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_tree_view
def create_tree_view(self, model=None): """ Function creates a tree_view with model """ tree_view = Gtk.TreeView() if model is not None: tree_view.set_model(model) return tree_view
python
def create_tree_view(self, model=None): """ Function creates a tree_view with model """ tree_view = Gtk.TreeView() if model is not None: tree_view.set_model(model) return tree_view
[ "def", "create_tree_view", "(", "self", ",", "model", "=", "None", ")", ":", "tree_view", "=", "Gtk", ".", "TreeView", "(", ")", "if", "model", "is", "not", "None", ":", "tree_view", ".", "set_model", "(", "model", ")", "return", "tree_view" ]
Function creates a tree_view with model
[ "Function", "creates", "a", "tree_view", "with", "model" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L433-L440
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_cell_renderer_text
def create_cell_renderer_text(self, tree_view, title="title", assign=0, editable=False): """ Function creates a CellRendererText with title """ renderer = Gtk.CellRendererText() renderer.set_property('editable', editable) column = Gtk.TreeViewColumn(title, renderer, text=assign) tree_view.append_column(column)
python
def create_cell_renderer_text(self, tree_view, title="title", assign=0, editable=False): """ Function creates a CellRendererText with title """ renderer = Gtk.CellRendererText() renderer.set_property('editable', editable) column = Gtk.TreeViewColumn(title, renderer, text=assign) tree_view.append_column(column)
[ "def", "create_cell_renderer_text", "(", "self", ",", "tree_view", ",", "title", "=", "\"title\"", ",", "assign", "=", "0", ",", "editable", "=", "False", ")", ":", "renderer", "=", "Gtk", ".", "CellRendererText", "(", ")", "renderer", ".", "set_property", "(", "'editable'", ",", "editable", ")", "column", "=", "Gtk", ".", "TreeViewColumn", "(", "title", ",", "renderer", ",", "text", "=", "assign", ")", "tree_view", ".", "append_column", "(", "column", ")" ]
Function creates a CellRendererText with title
[ "Function", "creates", "a", "CellRendererText", "with", "title" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L442-L449
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_cell_renderer_combo
def create_cell_renderer_combo(self, tree_view, title="title", assign=0, editable=False, model=None, function=None): """' Function creates a CellRendererCombo with title, model """ renderer_combo = Gtk.CellRendererCombo() renderer_combo.set_property('editable', editable) if model: renderer_combo.set_property('model', model) if function: renderer_combo.connect("edited", function) renderer_combo.set_property("text-column", 0) renderer_combo.set_property("has-entry", False) column = Gtk.TreeViewColumn(title, renderer_combo, text=assign) tree_view.append_column(column)
python
def create_cell_renderer_combo(self, tree_view, title="title", assign=0, editable=False, model=None, function=None): """' Function creates a CellRendererCombo with title, model """ renderer_combo = Gtk.CellRendererCombo() renderer_combo.set_property('editable', editable) if model: renderer_combo.set_property('model', model) if function: renderer_combo.connect("edited", function) renderer_combo.set_property("text-column", 0) renderer_combo.set_property("has-entry", False) column = Gtk.TreeViewColumn(title, renderer_combo, text=assign) tree_view.append_column(column)
[ "def", "create_cell_renderer_combo", "(", "self", ",", "tree_view", ",", "title", "=", "\"title\"", ",", "assign", "=", "0", ",", "editable", "=", "False", ",", "model", "=", "None", ",", "function", "=", "None", ")", ":", "renderer_combo", "=", "Gtk", ".", "CellRendererCombo", "(", ")", "renderer_combo", ".", "set_property", "(", "'editable'", ",", "editable", ")", "if", "model", ":", "renderer_combo", ".", "set_property", "(", "'model'", ",", "model", ")", "if", "function", ":", "renderer_combo", ".", "connect", "(", "\"edited\"", ",", "function", ")", "renderer_combo", ".", "set_property", "(", "\"text-column\"", ",", "0", ")", "renderer_combo", ".", "set_property", "(", "\"has-entry\"", ",", "False", ")", "column", "=", "Gtk", ".", "TreeViewColumn", "(", "title", ",", "renderer_combo", ",", "text", "=", "assign", ")", "tree_view", ".", "append_column", "(", "column", ")" ]
Function creates a CellRendererCombo with title, model
[ "Function", "creates", "a", "CellRendererCombo", "with", "title", "model" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L451-L464
train
devassistant/devassistant
devassistant/gui/gui_helper.py
GuiHelper.create_clipboard
def create_clipboard(self, text, selection=Gdk.SELECTION_CLIPBOARD): """ Function creates a clipboard """ clipboard = Gtk.Clipboard.get(selection) clipboard.set_text('\n'.join(text), -1) clipboard.store() return clipboard
python
def create_clipboard(self, text, selection=Gdk.SELECTION_CLIPBOARD): """ Function creates a clipboard """ clipboard = Gtk.Clipboard.get(selection) clipboard.set_text('\n'.join(text), -1) clipboard.store() return clipboard
[ "def", "create_clipboard", "(", "self", ",", "text", ",", "selection", "=", "Gdk", ".", "SELECTION_CLIPBOARD", ")", ":", "clipboard", "=", "Gtk", ".", "Clipboard", ".", "get", "(", "selection", ")", "clipboard", ".", "set_text", "(", "'\\n'", ".", "join", "(", "text", ")", ",", "-", "1", ")", "clipboard", ".", "store", "(", ")", "return", "clipboard" ]
Function creates a clipboard
[ "Function", "creates", "a", "clipboard" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/gui_helper.py#L466-L473
train
devassistant/devassistant
devassistant/command_helpers.py
ClHelper.run_command
def run_command(cls, cmd_str, log_level=logging.DEBUG, ignore_sigint=False, output_callback=None, as_user=None, log_secret=False, env=None): """Runs a command from string, e.g. "cp foo bar" Args: cmd_str: the command to run as string log_level: level at which to log command output (DEBUG by default) ignore_sigint: should we ignore sigint during this command (False by default) output_callback: function that gets called with every line of output as argument as_user: run as specified user (the best way to do this will be deduced by DA) runs as current user if as_user == None log_secret: if True, the command invocation will only be logged as "LOGGING PREVENTED FOR SECURITY REASONS", no output will be logged env: if not None, pass to subprocess as shell environment; else use original DevAssistant environment """ # run format processors on cmd_str for name, cmd_proc in cls.command_processors.items(): cmd_str = cmd_proc(cmd_str) # TODO: how to do cd with as_user? if as_user and not cmd_str.startswith('cd '): cmd_str = cls.format_for_another_user(cmd_str, as_user) cls.log(log_level, cmd_str, 'cmd_call', log_secret) if cmd_str.startswith('cd '): # special-case cd to behave like shell cd and stay in the directory try: directory = cmd_str[3:] # delete any quotes, os.chdir doesn't split words like sh does if directory[0] == directory[-1] == '"': directory = directory[1:-1] os.chdir(directory) except OSError as e: raise exceptions.ClException(cmd_str, 1, six.text_type(e)) return '' stdin_pipe = None stdout_pipe = subprocess.PIPE stderr_pipe = subprocess.STDOUT preexec_fn = cls.ignore_sigint if ignore_sigint else None env = os.environ if env is None else env proc = subprocess.Popen(cmd_str, stdin=stdin_pipe, stdout=stdout_pipe, stderr=stderr_pipe, shell=True, preexec_fn=preexec_fn, env=env) # register process to cls.subprocesses cls.subprocesses[proc.pid] = proc stdout = [] while proc.poll() is None: try: output = proc.stdout.readline().decode(utils.defenc) if output: output = output.strip() stdout.append(output) cls.log(log_level, output, 'cmd_out', log_secret) if output_callback: output_callback(output) except IOError as e: if e.errno == errno.EINTR: # Interrupted system call in Python 2.6 sys.stderr.write('Can\'t interrupt this process!\n') else: raise e # remove process from cls.subprocesses cls.subprocesses.pop(proc.pid) # add a newline to the end - if there is more output in output_rest, we'll be appending # it line by line; if there's no more output, we strip anyway stdout = '\n'.join(stdout) + '\n' # there may be some remains not read after exiting the previous loop output_rest = proc.stdout.read().strip().decode(utils.defenc) # we want to log lines separately, not as one big chunk output_rest_lines = output_rest.splitlines() for i, l in enumerate(output_rest_lines): cls.log(log_level, l, 'cmd_out', log_secret) # add newline for every line - for last line, only add it if it was originally present if i != len(output_rest_lines) - 1 or output_rest.endswith('\n'): l += '\n' stdout += l if output_callback: output_callback(l) # log return code always on debug level cls.log(logging.DEBUG, proc.returncode, 'cmd_retcode', log_secret) stdout = stdout.strip() if proc.returncode == 0: return stdout else: raise exceptions.ClException(cmd_str, proc.returncode, stdout)
python
def run_command(cls, cmd_str, log_level=logging.DEBUG, ignore_sigint=False, output_callback=None, as_user=None, log_secret=False, env=None): """Runs a command from string, e.g. "cp foo bar" Args: cmd_str: the command to run as string log_level: level at which to log command output (DEBUG by default) ignore_sigint: should we ignore sigint during this command (False by default) output_callback: function that gets called with every line of output as argument as_user: run as specified user (the best way to do this will be deduced by DA) runs as current user if as_user == None log_secret: if True, the command invocation will only be logged as "LOGGING PREVENTED FOR SECURITY REASONS", no output will be logged env: if not None, pass to subprocess as shell environment; else use original DevAssistant environment """ # run format processors on cmd_str for name, cmd_proc in cls.command_processors.items(): cmd_str = cmd_proc(cmd_str) # TODO: how to do cd with as_user? if as_user and not cmd_str.startswith('cd '): cmd_str = cls.format_for_another_user(cmd_str, as_user) cls.log(log_level, cmd_str, 'cmd_call', log_secret) if cmd_str.startswith('cd '): # special-case cd to behave like shell cd and stay in the directory try: directory = cmd_str[3:] # delete any quotes, os.chdir doesn't split words like sh does if directory[0] == directory[-1] == '"': directory = directory[1:-1] os.chdir(directory) except OSError as e: raise exceptions.ClException(cmd_str, 1, six.text_type(e)) return '' stdin_pipe = None stdout_pipe = subprocess.PIPE stderr_pipe = subprocess.STDOUT preexec_fn = cls.ignore_sigint if ignore_sigint else None env = os.environ if env is None else env proc = subprocess.Popen(cmd_str, stdin=stdin_pipe, stdout=stdout_pipe, stderr=stderr_pipe, shell=True, preexec_fn=preexec_fn, env=env) # register process to cls.subprocesses cls.subprocesses[proc.pid] = proc stdout = [] while proc.poll() is None: try: output = proc.stdout.readline().decode(utils.defenc) if output: output = output.strip() stdout.append(output) cls.log(log_level, output, 'cmd_out', log_secret) if output_callback: output_callback(output) except IOError as e: if e.errno == errno.EINTR: # Interrupted system call in Python 2.6 sys.stderr.write('Can\'t interrupt this process!\n') else: raise e # remove process from cls.subprocesses cls.subprocesses.pop(proc.pid) # add a newline to the end - if there is more output in output_rest, we'll be appending # it line by line; if there's no more output, we strip anyway stdout = '\n'.join(stdout) + '\n' # there may be some remains not read after exiting the previous loop output_rest = proc.stdout.read().strip().decode(utils.defenc) # we want to log lines separately, not as one big chunk output_rest_lines = output_rest.splitlines() for i, l in enumerate(output_rest_lines): cls.log(log_level, l, 'cmd_out', log_secret) # add newline for every line - for last line, only add it if it was originally present if i != len(output_rest_lines) - 1 or output_rest.endswith('\n'): l += '\n' stdout += l if output_callback: output_callback(l) # log return code always on debug level cls.log(logging.DEBUG, proc.returncode, 'cmd_retcode', log_secret) stdout = stdout.strip() if proc.returncode == 0: return stdout else: raise exceptions.ClException(cmd_str, proc.returncode, stdout)
[ "def", "run_command", "(", "cls", ",", "cmd_str", ",", "log_level", "=", "logging", ".", "DEBUG", ",", "ignore_sigint", "=", "False", ",", "output_callback", "=", "None", ",", "as_user", "=", "None", ",", "log_secret", "=", "False", ",", "env", "=", "None", ")", ":", "# run format processors on cmd_str", "for", "name", ",", "cmd_proc", "in", "cls", ".", "command_processors", ".", "items", "(", ")", ":", "cmd_str", "=", "cmd_proc", "(", "cmd_str", ")", "# TODO: how to do cd with as_user?", "if", "as_user", "and", "not", "cmd_str", ".", "startswith", "(", "'cd '", ")", ":", "cmd_str", "=", "cls", ".", "format_for_another_user", "(", "cmd_str", ",", "as_user", ")", "cls", ".", "log", "(", "log_level", ",", "cmd_str", ",", "'cmd_call'", ",", "log_secret", ")", "if", "cmd_str", ".", "startswith", "(", "'cd '", ")", ":", "# special-case cd to behave like shell cd and stay in the directory", "try", ":", "directory", "=", "cmd_str", "[", "3", ":", "]", "# delete any quotes, os.chdir doesn't split words like sh does", "if", "directory", "[", "0", "]", "==", "directory", "[", "-", "1", "]", "==", "'\"'", ":", "directory", "=", "directory", "[", "1", ":", "-", "1", "]", "os", ".", "chdir", "(", "directory", ")", "except", "OSError", "as", "e", ":", "raise", "exceptions", ".", "ClException", "(", "cmd_str", ",", "1", ",", "six", ".", "text_type", "(", "e", ")", ")", "return", "''", "stdin_pipe", "=", "None", "stdout_pipe", "=", "subprocess", ".", "PIPE", "stderr_pipe", "=", "subprocess", ".", "STDOUT", "preexec_fn", "=", "cls", ".", "ignore_sigint", "if", "ignore_sigint", "else", "None", "env", "=", "os", ".", "environ", "if", "env", "is", "None", "else", "env", "proc", "=", "subprocess", ".", "Popen", "(", "cmd_str", ",", "stdin", "=", "stdin_pipe", ",", "stdout", "=", "stdout_pipe", ",", "stderr", "=", "stderr_pipe", ",", "shell", "=", "True", ",", "preexec_fn", "=", "preexec_fn", ",", "env", "=", "env", ")", "# register process to cls.subprocesses", "cls", ".", "subprocesses", "[", "proc", ".", "pid", "]", "=", "proc", "stdout", "=", "[", "]", "while", "proc", ".", "poll", "(", ")", "is", "None", ":", "try", ":", "output", "=", "proc", ".", "stdout", ".", "readline", "(", ")", ".", "decode", "(", "utils", ".", "defenc", ")", "if", "output", ":", "output", "=", "output", ".", "strip", "(", ")", "stdout", ".", "append", "(", "output", ")", "cls", ".", "log", "(", "log_level", ",", "output", ",", "'cmd_out'", ",", "log_secret", ")", "if", "output_callback", ":", "output_callback", "(", "output", ")", "except", "IOError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "EINTR", ":", "# Interrupted system call in Python 2.6", "sys", ".", "stderr", ".", "write", "(", "'Can\\'t interrupt this process!\\n'", ")", "else", ":", "raise", "e", "# remove process from cls.subprocesses", "cls", ".", "subprocesses", ".", "pop", "(", "proc", ".", "pid", ")", "# add a newline to the end - if there is more output in output_rest, we'll be appending", "# it line by line; if there's no more output, we strip anyway", "stdout", "=", "'\\n'", ".", "join", "(", "stdout", ")", "+", "'\\n'", "# there may be some remains not read after exiting the previous loop", "output_rest", "=", "proc", ".", "stdout", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "decode", "(", "utils", ".", "defenc", ")", "# we want to log lines separately, not as one big chunk", "output_rest_lines", "=", "output_rest", ".", "splitlines", "(", ")", "for", "i", ",", "l", "in", "enumerate", "(", "output_rest_lines", ")", ":", "cls", ".", "log", "(", "log_level", ",", "l", ",", "'cmd_out'", ",", "log_secret", ")", "# add newline for every line - for last line, only add it if it was originally present", "if", "i", "!=", "len", "(", "output_rest_lines", ")", "-", "1", "or", "output_rest", ".", "endswith", "(", "'\\n'", ")", ":", "l", "+=", "'\\n'", "stdout", "+=", "l", "if", "output_callback", ":", "output_callback", "(", "l", ")", "# log return code always on debug level", "cls", ".", "log", "(", "logging", ".", "DEBUG", ",", "proc", ".", "returncode", ",", "'cmd_retcode'", ",", "log_secret", ")", "stdout", "=", "stdout", ".", "strip", "(", ")", "if", "proc", ".", "returncode", "==", "0", ":", "return", "stdout", "else", ":", "raise", "exceptions", ".", "ClException", "(", "cmd_str", ",", "proc", ".", "returncode", ",", "stdout", ")" ]
Runs a command from string, e.g. "cp foo bar" Args: cmd_str: the command to run as string log_level: level at which to log command output (DEBUG by default) ignore_sigint: should we ignore sigint during this command (False by default) output_callback: function that gets called with every line of output as argument as_user: run as specified user (the best way to do this will be deduced by DA) runs as current user if as_user == None log_secret: if True, the command invocation will only be logged as "LOGGING PREVENTED FOR SECURITY REASONS", no output will be logged env: if not None, pass to subprocess as shell environment; else use original DevAssistant environment
[ "Runs", "a", "command", "from", "string", "e", ".", "g", ".", "cp", "foo", "bar", "Args", ":", "cmd_str", ":", "the", "command", "to", "run", "as", "string", "log_level", ":", "level", "at", "which", "to", "log", "command", "output", "(", "DEBUG", "by", "default", ")", "ignore_sigint", ":", "should", "we", "ignore", "sigint", "during", "this", "command", "(", "False", "by", "default", ")", "output_callback", ":", "function", "that", "gets", "called", "with", "every", "line", "of", "output", "as", "argument", "as_user", ":", "run", "as", "specified", "user", "(", "the", "best", "way", "to", "do", "this", "will", "be", "deduced", "by", "DA", ")", "runs", "as", "current", "user", "if", "as_user", "==", "None", "log_secret", ":", "if", "True", "the", "command", "invocation", "will", "only", "be", "logged", "as", "LOGGING", "PREVENTED", "FOR", "SECURITY", "REASONS", "no", "output", "will", "be", "logged", "env", ":", "if", "not", "None", "pass", "to", "subprocess", "as", "shell", "environment", ";", "else", "use", "original", "DevAssistant", "environment" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/command_helpers.py#L32-L133
train
devassistant/devassistant
devassistant/command_helpers.py
DialogHelper.ask_for_password
def ask_for_password(cls, ui, prompt='Provide your password:', **options): """Returns the password typed by user as a string or None if user cancels the request (e.g. presses Ctrl + D on commandline or presses Cancel in GUI. """ # optionally set title, that may be used by some helpers like zenity return cls.get_appropriate_helper(ui).ask_for_password(prompt, title=options.get('title', prompt))
python
def ask_for_password(cls, ui, prompt='Provide your password:', **options): """Returns the password typed by user as a string or None if user cancels the request (e.g. presses Ctrl + D on commandline or presses Cancel in GUI. """ # optionally set title, that may be used by some helpers like zenity return cls.get_appropriate_helper(ui).ask_for_password(prompt, title=options.get('title', prompt))
[ "def", "ask_for_password", "(", "cls", ",", "ui", ",", "prompt", "=", "'Provide your password:'", ",", "*", "*", "options", ")", ":", "# optionally set title, that may be used by some helpers like zenity", "return", "cls", ".", "get_appropriate_helper", "(", "ui", ")", ".", "ask_for_password", "(", "prompt", ",", "title", "=", "options", ".", "get", "(", "'title'", ",", "prompt", ")", ")" ]
Returns the password typed by user as a string or None if user cancels the request (e.g. presses Ctrl + D on commandline or presses Cancel in GUI.
[ "Returns", "the", "password", "typed", "by", "user", "as", "a", "string", "or", "None", "if", "user", "cancels", "the", "request", "(", "e", ".", "g", ".", "presses", "Ctrl", "+", "D", "on", "commandline", "or", "presses", "Cancel", "in", "GUI", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/command_helpers.py#L226-L232
train
devassistant/devassistant
devassistant/command_helpers.py
DialogHelper.ask_for_confirm_with_message
def ask_for_confirm_with_message(cls, ui, prompt='Do you agree?', message='', **options): """Returns True if user agrees, False otherwise""" return cls.get_appropriate_helper(ui).ask_for_confirm_with_message(prompt, message)
python
def ask_for_confirm_with_message(cls, ui, prompt='Do you agree?', message='', **options): """Returns True if user agrees, False otherwise""" return cls.get_appropriate_helper(ui).ask_for_confirm_with_message(prompt, message)
[ "def", "ask_for_confirm_with_message", "(", "cls", ",", "ui", ",", "prompt", "=", "'Do you agree?'", ",", "message", "=", "''", ",", "*", "*", "options", ")", ":", "return", "cls", ".", "get_appropriate_helper", "(", "ui", ")", ".", "ask_for_confirm_with_message", "(", "prompt", ",", "message", ")" ]
Returns True if user agrees, False otherwise
[ "Returns", "True", "if", "user", "agrees", "False", "otherwise" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/command_helpers.py#L235-L237
train
devassistant/devassistant
devassistant/command_helpers.py
DialogHelper.ask_for_input_with_prompt
def ask_for_input_with_prompt(cls, ui, prompt='', **options): """Ask user for written input with prompt""" return cls.get_appropriate_helper(ui).ask_for_input_with_prompt(prompt=prompt, **options)
python
def ask_for_input_with_prompt(cls, ui, prompt='', **options): """Ask user for written input with prompt""" return cls.get_appropriate_helper(ui).ask_for_input_with_prompt(prompt=prompt, **options)
[ "def", "ask_for_input_with_prompt", "(", "cls", ",", "ui", ",", "prompt", "=", "''", ",", "*", "*", "options", ")", ":", "return", "cls", ".", "get_appropriate_helper", "(", "ui", ")", ".", "ask_for_input_with_prompt", "(", "prompt", "=", "prompt", ",", "*", "*", "options", ")" ]
Ask user for written input with prompt
[ "Ask", "user", "for", "written", "input", "with", "prompt" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/command_helpers.py#L250-L252
train
devassistant/devassistant
devassistant/argument.py
Argument.add_argument_to
def add_argument_to(self, parser): """Used by cli to add this as an argument to argparse parser. Args: parser: parser to add this argument to """ from devassistant.cli.devassistant_argparse import DefaultIffUsedActionFactory if isinstance(self.kwargs.get('action', ''), list): # see documentation of DefaultIffUsedActionFactory to see why this is necessary if self.kwargs['action'][0] == 'default_iff_used': self.kwargs['action'] = DefaultIffUsedActionFactory.generate_action( self.kwargs['action'][1]) # In cli 'preserved' is not supported. # It needs to be removed because it is unknown for argparse. self.kwargs.pop('preserved', None) try: parser.add_argument(*self.flags, **self.kwargs) except Exception as ex: problem = "Error while adding argument '{name}': {error}".\ format(name=self.name, error=repr(ex)) raise exceptions.ExecutionException(problem)
python
def add_argument_to(self, parser): """Used by cli to add this as an argument to argparse parser. Args: parser: parser to add this argument to """ from devassistant.cli.devassistant_argparse import DefaultIffUsedActionFactory if isinstance(self.kwargs.get('action', ''), list): # see documentation of DefaultIffUsedActionFactory to see why this is necessary if self.kwargs['action'][0] == 'default_iff_used': self.kwargs['action'] = DefaultIffUsedActionFactory.generate_action( self.kwargs['action'][1]) # In cli 'preserved' is not supported. # It needs to be removed because it is unknown for argparse. self.kwargs.pop('preserved', None) try: parser.add_argument(*self.flags, **self.kwargs) except Exception as ex: problem = "Error while adding argument '{name}': {error}".\ format(name=self.name, error=repr(ex)) raise exceptions.ExecutionException(problem)
[ "def", "add_argument_to", "(", "self", ",", "parser", ")", ":", "from", "devassistant", ".", "cli", ".", "devassistant_argparse", "import", "DefaultIffUsedActionFactory", "if", "isinstance", "(", "self", ".", "kwargs", ".", "get", "(", "'action'", ",", "''", ")", ",", "list", ")", ":", "# see documentation of DefaultIffUsedActionFactory to see why this is necessary", "if", "self", ".", "kwargs", "[", "'action'", "]", "[", "0", "]", "==", "'default_iff_used'", ":", "self", ".", "kwargs", "[", "'action'", "]", "=", "DefaultIffUsedActionFactory", ".", "generate_action", "(", "self", ".", "kwargs", "[", "'action'", "]", "[", "1", "]", ")", "# In cli 'preserved' is not supported.", "# It needs to be removed because it is unknown for argparse.", "self", ".", "kwargs", ".", "pop", "(", "'preserved'", ",", "None", ")", "try", ":", "parser", ".", "add_argument", "(", "*", "self", ".", "flags", ",", "*", "*", "self", ".", "kwargs", ")", "except", "Exception", "as", "ex", ":", "problem", "=", "\"Error while adding argument '{name}': {error}\"", ".", "format", "(", "name", "=", "self", ".", "name", ",", "error", "=", "repr", "(", "ex", ")", ")", "raise", "exceptions", ".", "ExecutionException", "(", "problem", ")" ]
Used by cli to add this as an argument to argparse parser. Args: parser: parser to add this argument to
[ "Used", "by", "cli", "to", "add", "this", "as", "an", "argument", "to", "argparse", "parser", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/argument.py#L34-L54
train
devassistant/devassistant
devassistant/argument.py
Argument.get_gui_hint
def get_gui_hint(self, hint): """Returns the value for specified gui hint (or a sensible default value, if this argument doesn't specify the hint). Args: hint: name of the hint to get value for Returns: value of the hint specified in yaml or a sensible default """ if hint == 'type': # 'self.kwargs.get('nargs') == 0' is there for default_iff_used, which may # have nargs: 0, so that it works similarly to 'store_const' if self.kwargs.get('action') == 'store_true' or self.kwargs.get('nargs') == 0: return 'bool' # store_const is represented by checkbox, but computes default differently elif self.kwargs.get('action') == 'store_const': return 'const' return self.gui_hints.get('type', 'str') elif hint == 'default': hint_type = self.get_gui_hint('type') hint_default = self.gui_hints.get('default', None) arg_default = self.kwargs.get('default', None) preserved_value = None if 'preserved' in self.kwargs: preserved_value = config_manager.get_config_value(self.kwargs['preserved']) if hint_type == 'path': if preserved_value is not None: default = preserved_value elif hint_default is not None: default = hint_default.replace('$(pwd)', utils.get_cwd_or_homedir()) else: default = arg_default or '~' return os.path.abspath(os.path.expanduser(default)) elif hint_type == 'bool': return hint_default or arg_default or False elif hint_type == 'const': return hint_default or arg_default else: if hint_default == '$(whoami)': hint_default = getpass.getuser() return preserved_value or hint_default or arg_default or ''
python
def get_gui_hint(self, hint): """Returns the value for specified gui hint (or a sensible default value, if this argument doesn't specify the hint). Args: hint: name of the hint to get value for Returns: value of the hint specified in yaml or a sensible default """ if hint == 'type': # 'self.kwargs.get('nargs') == 0' is there for default_iff_used, which may # have nargs: 0, so that it works similarly to 'store_const' if self.kwargs.get('action') == 'store_true' or self.kwargs.get('nargs') == 0: return 'bool' # store_const is represented by checkbox, but computes default differently elif self.kwargs.get('action') == 'store_const': return 'const' return self.gui_hints.get('type', 'str') elif hint == 'default': hint_type = self.get_gui_hint('type') hint_default = self.gui_hints.get('default', None) arg_default = self.kwargs.get('default', None) preserved_value = None if 'preserved' in self.kwargs: preserved_value = config_manager.get_config_value(self.kwargs['preserved']) if hint_type == 'path': if preserved_value is not None: default = preserved_value elif hint_default is not None: default = hint_default.replace('$(pwd)', utils.get_cwd_or_homedir()) else: default = arg_default or '~' return os.path.abspath(os.path.expanduser(default)) elif hint_type == 'bool': return hint_default or arg_default or False elif hint_type == 'const': return hint_default or arg_default else: if hint_default == '$(whoami)': hint_default = getpass.getuser() return preserved_value or hint_default or arg_default or ''
[ "def", "get_gui_hint", "(", "self", ",", "hint", ")", ":", "if", "hint", "==", "'type'", ":", "# 'self.kwargs.get('nargs') == 0' is there for default_iff_used, which may", "# have nargs: 0, so that it works similarly to 'store_const'", "if", "self", ".", "kwargs", ".", "get", "(", "'action'", ")", "==", "'store_true'", "or", "self", ".", "kwargs", ".", "get", "(", "'nargs'", ")", "==", "0", ":", "return", "'bool'", "# store_const is represented by checkbox, but computes default differently", "elif", "self", ".", "kwargs", ".", "get", "(", "'action'", ")", "==", "'store_const'", ":", "return", "'const'", "return", "self", ".", "gui_hints", ".", "get", "(", "'type'", ",", "'str'", ")", "elif", "hint", "==", "'default'", ":", "hint_type", "=", "self", ".", "get_gui_hint", "(", "'type'", ")", "hint_default", "=", "self", ".", "gui_hints", ".", "get", "(", "'default'", ",", "None", ")", "arg_default", "=", "self", ".", "kwargs", ".", "get", "(", "'default'", ",", "None", ")", "preserved_value", "=", "None", "if", "'preserved'", "in", "self", ".", "kwargs", ":", "preserved_value", "=", "config_manager", ".", "get_config_value", "(", "self", ".", "kwargs", "[", "'preserved'", "]", ")", "if", "hint_type", "==", "'path'", ":", "if", "preserved_value", "is", "not", "None", ":", "default", "=", "preserved_value", "elif", "hint_default", "is", "not", "None", ":", "default", "=", "hint_default", ".", "replace", "(", "'$(pwd)'", ",", "utils", ".", "get_cwd_or_homedir", "(", ")", ")", "else", ":", "default", "=", "arg_default", "or", "'~'", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "default", ")", ")", "elif", "hint_type", "==", "'bool'", ":", "return", "hint_default", "or", "arg_default", "or", "False", "elif", "hint_type", "==", "'const'", ":", "return", "hint_default", "or", "arg_default", "else", ":", "if", "hint_default", "==", "'$(whoami)'", ":", "hint_default", "=", "getpass", ".", "getuser", "(", ")", "return", "preserved_value", "or", "hint_default", "or", "arg_default", "or", "''" ]
Returns the value for specified gui hint (or a sensible default value, if this argument doesn't specify the hint). Args: hint: name of the hint to get value for Returns: value of the hint specified in yaml or a sensible default
[ "Returns", "the", "value", "for", "specified", "gui", "hint", "(", "or", "a", "sensible", "default", "value", "if", "this", "argument", "doesn", "t", "specify", "the", "hint", ")", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/argument.py#L67-L108
train
devassistant/devassistant
devassistant/argument.py
Argument.construct_arg
def construct_arg(cls, name, params): """Construct an argument from name, and params (dict loaded from assistant/snippet). """ use_snippet = params.pop('use', None) if use_snippet: # if snippet is used, take this parameter from snippet and update # it with current params, if any try: problem = None snippet = yaml_snippet_loader.YamlSnippetLoader.get_snippet_by_name(use_snippet) # this works much like snippet.args.pop(arg_name).update(arg_params), # but unlike it, this actually returns the updated dict params = dict(snippet.args.pop(name), **params) # if there is SnippetNotFoundException, just let it be raised except KeyError: # snippet doesn't have the requested argument problem = 'Couldn\'t find arg {arg} in snippet {snip}.'.\ format(arg=name, snip=snippet.name) raise exceptions.ExecutionException(problem) if 'flags' not in params: msg = 'Couldn\'t find "flags" in arg {arg}'.format(arg=name) raise exceptions.ExecutionException(msg) return cls(name, *params.pop('flags'), **params)
python
def construct_arg(cls, name, params): """Construct an argument from name, and params (dict loaded from assistant/snippet). """ use_snippet = params.pop('use', None) if use_snippet: # if snippet is used, take this parameter from snippet and update # it with current params, if any try: problem = None snippet = yaml_snippet_loader.YamlSnippetLoader.get_snippet_by_name(use_snippet) # this works much like snippet.args.pop(arg_name).update(arg_params), # but unlike it, this actually returns the updated dict params = dict(snippet.args.pop(name), **params) # if there is SnippetNotFoundException, just let it be raised except KeyError: # snippet doesn't have the requested argument problem = 'Couldn\'t find arg {arg} in snippet {snip}.'.\ format(arg=name, snip=snippet.name) raise exceptions.ExecutionException(problem) if 'flags' not in params: msg = 'Couldn\'t find "flags" in arg {arg}'.format(arg=name) raise exceptions.ExecutionException(msg) return cls(name, *params.pop('flags'), **params)
[ "def", "construct_arg", "(", "cls", ",", "name", ",", "params", ")", ":", "use_snippet", "=", "params", ".", "pop", "(", "'use'", ",", "None", ")", "if", "use_snippet", ":", "# if snippet is used, take this parameter from snippet and update", "# it with current params, if any", "try", ":", "problem", "=", "None", "snippet", "=", "yaml_snippet_loader", ".", "YamlSnippetLoader", ".", "get_snippet_by_name", "(", "use_snippet", ")", "# this works much like snippet.args.pop(arg_name).update(arg_params),", "# but unlike it, this actually returns the updated dict", "params", "=", "dict", "(", "snippet", ".", "args", ".", "pop", "(", "name", ")", ",", "*", "*", "params", ")", "# if there is SnippetNotFoundException, just let it be raised", "except", "KeyError", ":", "# snippet doesn't have the requested argument", "problem", "=", "'Couldn\\'t find arg {arg} in snippet {snip}.'", ".", "format", "(", "arg", "=", "name", ",", "snip", "=", "snippet", ".", "name", ")", "raise", "exceptions", ".", "ExecutionException", "(", "problem", ")", "if", "'flags'", "not", "in", "params", ":", "msg", "=", "'Couldn\\'t find \"flags\" in arg {arg}'", ".", "format", "(", "arg", "=", "name", ")", "raise", "exceptions", ".", "ExecutionException", "(", "msg", ")", "return", "cls", "(", "name", ",", "*", "params", ".", "pop", "(", "'flags'", ")", ",", "*", "*", "params", ")" ]
Construct an argument from name, and params (dict loaded from assistant/snippet).
[ "Construct", "an", "argument", "from", "name", "and", "params", "(", "dict", "loaded", "from", "assistant", "/", "snippet", ")", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/argument.py#L111-L133
train
devassistant/devassistant
devassistant/assistant_base.py
AssistantBase.get_subassistants
def get_subassistants(self): """Return list of instantiated subassistants. Usually, this needs not be overriden in subclasses, you should just override get_subassistant_classes Returns: list of instantiated subassistants """ if not hasattr(self, '_subassistants'): self._subassistants = [] # we want to know, if type(self) defines 'get_subassistant_classes', # we don't want to inherit it from superclass (would cause recursion) if 'get_subassistant_classes' in vars(type(self)): for a in self.get_subassistant_classes(): self._subassistants.append(a()) return self._subassistants
python
def get_subassistants(self): """Return list of instantiated subassistants. Usually, this needs not be overriden in subclasses, you should just override get_subassistant_classes Returns: list of instantiated subassistants """ if not hasattr(self, '_subassistants'): self._subassistants = [] # we want to know, if type(self) defines 'get_subassistant_classes', # we don't want to inherit it from superclass (would cause recursion) if 'get_subassistant_classes' in vars(type(self)): for a in self.get_subassistant_classes(): self._subassistants.append(a()) return self._subassistants
[ "def", "get_subassistants", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_subassistants'", ")", ":", "self", ".", "_subassistants", "=", "[", "]", "# we want to know, if type(self) defines 'get_subassistant_classes',", "# we don't want to inherit it from superclass (would cause recursion)", "if", "'get_subassistant_classes'", "in", "vars", "(", "type", "(", "self", ")", ")", ":", "for", "a", "in", "self", ".", "get_subassistant_classes", "(", ")", ":", "self", ".", "_subassistants", ".", "append", "(", "a", "(", ")", ")", "return", "self", ".", "_subassistants" ]
Return list of instantiated subassistants. Usually, this needs not be overriden in subclasses, you should just override get_subassistant_classes Returns: list of instantiated subassistants
[ "Return", "list", "of", "instantiated", "subassistants", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/assistant_base.py#L33-L49
train
devassistant/devassistant
devassistant/assistant_base.py
AssistantBase.get_subassistant_tree
def get_subassistant_tree(self): """Returns a tree-like structure representing the assistant hierarchy going down from this assistant to leaf assistants. For example: [(<This Assistant>, [(<Subassistant 1>, [...]), (<Subassistant 2>, [...])] )] Returns: a tree-like structure (see above) representing assistant hierarchy going down from this assistant to leaf assistants """ if '_tree' not in dir(self): subassistant_tree = [] subassistants = self.get_subassistants() for subassistant in subassistants: subassistant_tree.append(subassistant.get_subassistant_tree()) self._tree = (self, subassistant_tree) return self._tree
python
def get_subassistant_tree(self): """Returns a tree-like structure representing the assistant hierarchy going down from this assistant to leaf assistants. For example: [(<This Assistant>, [(<Subassistant 1>, [...]), (<Subassistant 2>, [...])] )] Returns: a tree-like structure (see above) representing assistant hierarchy going down from this assistant to leaf assistants """ if '_tree' not in dir(self): subassistant_tree = [] subassistants = self.get_subassistants() for subassistant in subassistants: subassistant_tree.append(subassistant.get_subassistant_tree()) self._tree = (self, subassistant_tree) return self._tree
[ "def", "get_subassistant_tree", "(", "self", ")", ":", "if", "'_tree'", "not", "in", "dir", "(", "self", ")", ":", "subassistant_tree", "=", "[", "]", "subassistants", "=", "self", ".", "get_subassistants", "(", ")", "for", "subassistant", "in", "subassistants", ":", "subassistant_tree", ".", "append", "(", "subassistant", ".", "get_subassistant_tree", "(", ")", ")", "self", ".", "_tree", "=", "(", "self", ",", "subassistant_tree", ")", "return", "self", ".", "_tree" ]
Returns a tree-like structure representing the assistant hierarchy going down from this assistant to leaf assistants. For example: [(<This Assistant>, [(<Subassistant 1>, [...]), (<Subassistant 2>, [...])] )] Returns: a tree-like structure (see above) representing assistant hierarchy going down from this assistant to leaf assistants
[ "Returns", "a", "tree", "-", "like", "structure", "representing", "the", "assistant", "hierarchy", "going", "down", "from", "this", "assistant", "to", "leaf", "assistants", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/assistant_base.py#L51-L69
train
devassistant/devassistant
devassistant/assistant_base.py
AssistantBase.get_selected_subassistant_path
def get_selected_subassistant_path(self, **kwargs): """Recursively searches self._tree - has format of (Assistant: [list_of_subassistants]) - for specific path from first to last selected subassistants. Args: kwargs: arguments containing names of the given assistants in form of subassistant_0 = 'name', subassistant_1 = 'another_name', ... Returns: list of subassistants objects from tree sorted from first to last """ path = [self] previous_subas_list = None currently_searching = self.get_subassistant_tree()[1] # len(path) - 1 always points to next subassistant_N, so we can use it to control iteration while settings.SUBASSISTANT_N_STRING.format(len(path) - 1) in kwargs and \ kwargs[settings.SUBASSISTANT_N_STRING.format(len(path) - 1)]: for sa, subas_list in currently_searching: if sa.name == kwargs[settings.SUBASSISTANT_N_STRING.format(len(path) - 1)]: currently_searching = subas_list path.append(sa) break # sorry if you shed a tear ;) if subas_list == previous_subas_list: raise exceptions.AssistantNotFoundException( 'No assistant {n} after path {p}.'.format( n=kwargs[settings.SUBASSISTANT_N_STRING.format(len(path) - 1)], p=path)) previous_subas_list = subas_list return path
python
def get_selected_subassistant_path(self, **kwargs): """Recursively searches self._tree - has format of (Assistant: [list_of_subassistants]) - for specific path from first to last selected subassistants. Args: kwargs: arguments containing names of the given assistants in form of subassistant_0 = 'name', subassistant_1 = 'another_name', ... Returns: list of subassistants objects from tree sorted from first to last """ path = [self] previous_subas_list = None currently_searching = self.get_subassistant_tree()[1] # len(path) - 1 always points to next subassistant_N, so we can use it to control iteration while settings.SUBASSISTANT_N_STRING.format(len(path) - 1) in kwargs and \ kwargs[settings.SUBASSISTANT_N_STRING.format(len(path) - 1)]: for sa, subas_list in currently_searching: if sa.name == kwargs[settings.SUBASSISTANT_N_STRING.format(len(path) - 1)]: currently_searching = subas_list path.append(sa) break # sorry if you shed a tear ;) if subas_list == previous_subas_list: raise exceptions.AssistantNotFoundException( 'No assistant {n} after path {p}.'.format( n=kwargs[settings.SUBASSISTANT_N_STRING.format(len(path) - 1)], p=path)) previous_subas_list = subas_list return path
[ "def", "get_selected_subassistant_path", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "[", "self", "]", "previous_subas_list", "=", "None", "currently_searching", "=", "self", ".", "get_subassistant_tree", "(", ")", "[", "1", "]", "# len(path) - 1 always points to next subassistant_N, so we can use it to control iteration", "while", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "len", "(", "path", ")", "-", "1", ")", "in", "kwargs", "and", "kwargs", "[", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "len", "(", "path", ")", "-", "1", ")", "]", ":", "for", "sa", ",", "subas_list", "in", "currently_searching", ":", "if", "sa", ".", "name", "==", "kwargs", "[", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "len", "(", "path", ")", "-", "1", ")", "]", ":", "currently_searching", "=", "subas_list", "path", ".", "append", "(", "sa", ")", "break", "# sorry if you shed a tear ;)", "if", "subas_list", "==", "previous_subas_list", ":", "raise", "exceptions", ".", "AssistantNotFoundException", "(", "'No assistant {n} after path {p}.'", ".", "format", "(", "n", "=", "kwargs", "[", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "len", "(", "path", ")", "-", "1", ")", "]", ",", "p", "=", "path", ")", ")", "previous_subas_list", "=", "subas_list", "return", "path" ]
Recursively searches self._tree - has format of (Assistant: [list_of_subassistants]) - for specific path from first to last selected subassistants. Args: kwargs: arguments containing names of the given assistants in form of subassistant_0 = 'name', subassistant_1 = 'another_name', ... Returns: list of subassistants objects from tree sorted from first to last
[ "Recursively", "searches", "self", ".", "_tree", "-", "has", "format", "of", "(", "Assistant", ":", "[", "list_of_subassistants", "]", ")", "-", "for", "specific", "path", "from", "first", "to", "last", "selected", "subassistants", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/assistant_base.py#L71-L101
train
devassistant/devassistant
devassistant/assistant_base.py
AssistantBase.is_run_as_leaf
def is_run_as_leaf(self, **kwargs): """Returns True if this assistant was run as last in path, False otherwise.""" # find the last subassistant_N i = 0 while i < len(kwargs): # len(kwargs) is maximum of subassistant_N keys if settings.SUBASSISTANT_N_STRING.format(i) in kwargs: leaf_name = kwargs[settings.SUBASSISTANT_N_STRING.format(i)] i += 1 return self.name == leaf_name
python
def is_run_as_leaf(self, **kwargs): """Returns True if this assistant was run as last in path, False otherwise.""" # find the last subassistant_N i = 0 while i < len(kwargs): # len(kwargs) is maximum of subassistant_N keys if settings.SUBASSISTANT_N_STRING.format(i) in kwargs: leaf_name = kwargs[settings.SUBASSISTANT_N_STRING.format(i)] i += 1 return self.name == leaf_name
[ "def", "is_run_as_leaf", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# find the last subassistant_N", "i", "=", "0", "while", "i", "<", "len", "(", "kwargs", ")", ":", "# len(kwargs) is maximum of subassistant_N keys", "if", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "i", ")", "in", "kwargs", ":", "leaf_name", "=", "kwargs", "[", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "i", ")", "]", "i", "+=", "1", "return", "self", ".", "name", "==", "leaf_name" ]
Returns True if this assistant was run as last in path, False otherwise.
[ "Returns", "True", "if", "this", "assistant", "was", "run", "as", "last", "in", "path", "False", "otherwise", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/assistant_base.py#L103-L112
train
devassistant/devassistant
devassistant/yaml_loader.py
YamlLoader.load_all_yamls
def load_all_yamls(cls, directories): """Loads yaml files from all given directories. Args: directories: list of directories to search Returns: dict of {fullpath: loaded_yaml_structure} """ yaml_files = [] loaded_yamls = {} for d in directories: if d.startswith('/home') and not os.path.exists(d): os.makedirs(d) for dirname, subdirs, files in os.walk(d): yaml_files.extend(map(lambda x: os.path.join(dirname, x), filter(lambda x: x.endswith('.yaml'), files))) for f in yaml_files: loaded_yamls[f] = cls.load_yaml_by_path(f) return loaded_yamls
python
def load_all_yamls(cls, directories): """Loads yaml files from all given directories. Args: directories: list of directories to search Returns: dict of {fullpath: loaded_yaml_structure} """ yaml_files = [] loaded_yamls = {} for d in directories: if d.startswith('/home') and not os.path.exists(d): os.makedirs(d) for dirname, subdirs, files in os.walk(d): yaml_files.extend(map(lambda x: os.path.join(dirname, x), filter(lambda x: x.endswith('.yaml'), files))) for f in yaml_files: loaded_yamls[f] = cls.load_yaml_by_path(f) return loaded_yamls
[ "def", "load_all_yamls", "(", "cls", ",", "directories", ")", ":", "yaml_files", "=", "[", "]", "loaded_yamls", "=", "{", "}", "for", "d", "in", "directories", ":", "if", "d", ".", "startswith", "(", "'/home'", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "d", ")", ":", "os", ".", "makedirs", "(", "d", ")", "for", "dirname", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "d", ")", ":", "yaml_files", ".", "extend", "(", "map", "(", "lambda", "x", ":", "os", ".", "path", ".", "join", "(", "dirname", ",", "x", ")", ",", "filter", "(", "lambda", "x", ":", "x", ".", "endswith", "(", "'.yaml'", ")", ",", "files", ")", ")", ")", "for", "f", "in", "yaml_files", ":", "loaded_yamls", "[", "f", "]", "=", "cls", ".", "load_yaml_by_path", "(", "f", ")", "return", "loaded_yamls" ]
Loads yaml files from all given directories. Args: directories: list of directories to search Returns: dict of {fullpath: loaded_yaml_structure}
[ "Loads", "yaml", "files", "from", "all", "given", "directories", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_loader.py#L17-L38
train
devassistant/devassistant
devassistant/yaml_loader.py
YamlLoader.load_yaml_by_relpath
def load_yaml_by_relpath(cls, directories, rel_path, log_debug=False): """Load a yaml file with path that is relative to one of given directories. Args: directories: list of directories to search name: relative path of the yaml file to load log_debug: log all messages as debug Returns: tuple (fullpath, loaded yaml structure) or None if not found """ for d in directories: if d.startswith(os.path.expanduser('~')) and not os.path.exists(d): os.makedirs(d) possible_path = os.path.join(d, rel_path) if os.path.exists(possible_path): loaded = cls.load_yaml_by_path(possible_path, log_debug=log_debug) if loaded is not None: return (possible_path, cls.load_yaml_by_path(possible_path)) return None
python
def load_yaml_by_relpath(cls, directories, rel_path, log_debug=False): """Load a yaml file with path that is relative to one of given directories. Args: directories: list of directories to search name: relative path of the yaml file to load log_debug: log all messages as debug Returns: tuple (fullpath, loaded yaml structure) or None if not found """ for d in directories: if d.startswith(os.path.expanduser('~')) and not os.path.exists(d): os.makedirs(d) possible_path = os.path.join(d, rel_path) if os.path.exists(possible_path): loaded = cls.load_yaml_by_path(possible_path, log_debug=log_debug) if loaded is not None: return (possible_path, cls.load_yaml_by_path(possible_path)) return None
[ "def", "load_yaml_by_relpath", "(", "cls", ",", "directories", ",", "rel_path", ",", "log_debug", "=", "False", ")", ":", "for", "d", "in", "directories", ":", "if", "d", ".", "startswith", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "d", ")", ":", "os", ".", "makedirs", "(", "d", ")", "possible_path", "=", "os", ".", "path", ".", "join", "(", "d", ",", "rel_path", ")", "if", "os", ".", "path", ".", "exists", "(", "possible_path", ")", ":", "loaded", "=", "cls", ".", "load_yaml_by_path", "(", "possible_path", ",", "log_debug", "=", "log_debug", ")", "if", "loaded", "is", "not", "None", ":", "return", "(", "possible_path", ",", "cls", ".", "load_yaml_by_path", "(", "possible_path", ")", ")", "return", "None" ]
Load a yaml file with path that is relative to one of given directories. Args: directories: list of directories to search name: relative path of the yaml file to load log_debug: log all messages as debug Returns: tuple (fullpath, loaded yaml structure) or None if not found
[ "Load", "a", "yaml", "file", "with", "path", "that", "is", "relative", "to", "one", "of", "given", "directories", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_loader.py#L41-L60
train
devassistant/devassistant
devassistant/yaml_loader.py
YamlLoader.load_yaml_by_path
def load_yaml_by_path(cls, path, log_debug=False): """Load a yaml file that is at given path, if the path is not a string, it is assumed it's a file-like object""" try: if isinstance(path, six.string_types): return yaml.load(open(path, 'r'), Loader=Loader) or {} else: return yaml.load(path, Loader=Loader) or {} except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: log_level = logging.DEBUG if log_debug else logging.WARNING logger.log(log_level, 'Yaml error in {path} (line {ln}, column {col}): {err}'. format(path=path, ln=e.problem_mark.line, col=e.problem_mark.column, err=e.problem)) return None
python
def load_yaml_by_path(cls, path, log_debug=False): """Load a yaml file that is at given path, if the path is not a string, it is assumed it's a file-like object""" try: if isinstance(path, six.string_types): return yaml.load(open(path, 'r'), Loader=Loader) or {} else: return yaml.load(path, Loader=Loader) or {} except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: log_level = logging.DEBUG if log_debug else logging.WARNING logger.log(log_level, 'Yaml error in {path} (line {ln}, column {col}): {err}'. format(path=path, ln=e.problem_mark.line, col=e.problem_mark.column, err=e.problem)) return None
[ "def", "load_yaml_by_path", "(", "cls", ",", "path", ",", "log_debug", "=", "False", ")", ":", "try", ":", "if", "isinstance", "(", "path", ",", "six", ".", "string_types", ")", ":", "return", "yaml", ".", "load", "(", "open", "(", "path", ",", "'r'", ")", ",", "Loader", "=", "Loader", ")", "or", "{", "}", "else", ":", "return", "yaml", ".", "load", "(", "path", ",", "Loader", "=", "Loader", ")", "or", "{", "}", "except", "(", "yaml", ".", "scanner", ".", "ScannerError", ",", "yaml", ".", "parser", ".", "ParserError", ")", "as", "e", ":", "log_level", "=", "logging", ".", "DEBUG", "if", "log_debug", "else", "logging", ".", "WARNING", "logger", ".", "log", "(", "log_level", ",", "'Yaml error in {path} (line {ln}, column {col}): {err}'", ".", "format", "(", "path", "=", "path", ",", "ln", "=", "e", ".", "problem_mark", ".", "line", ",", "col", "=", "e", ".", "problem_mark", ".", "column", ",", "err", "=", "e", ".", "problem", ")", ")", "return", "None" ]
Load a yaml file that is at given path, if the path is not a string, it is assumed it's a file-like object
[ "Load", "a", "yaml", "file", "that", "is", "at", "given", "path", "if", "the", "path", "is", "not", "a", "string", "it", "is", "assumed", "it", "s", "a", "file", "-", "like", "object" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_loader.py#L63-L78
train
devassistant/devassistant
devassistant/path_runner.py
PathRunner._run_path_dependencies
def _run_path_dependencies(self, parsed_args): """Installs dependencies from the leaf assistant. Raises: devassistant.exceptions.DependencyException with a cause if something goes wrong """ deps = self.path[-1].dependencies(parsed_args) lang.Command('dependencies', deps, parsed_args).run()
python
def _run_path_dependencies(self, parsed_args): """Installs dependencies from the leaf assistant. Raises: devassistant.exceptions.DependencyException with a cause if something goes wrong """ deps = self.path[-1].dependencies(parsed_args) lang.Command('dependencies', deps, parsed_args).run()
[ "def", "_run_path_dependencies", "(", "self", ",", "parsed_args", ")", ":", "deps", "=", "self", ".", "path", "[", "-", "1", "]", ".", "dependencies", "(", "parsed_args", ")", "lang", ".", "Command", "(", "'dependencies'", ",", "deps", ",", "parsed_args", ")", ".", "run", "(", ")" ]
Installs dependencies from the leaf assistant. Raises: devassistant.exceptions.DependencyException with a cause if something goes wrong
[ "Installs", "dependencies", "from", "the", "leaf", "assistant", ".", "Raises", ":", "devassistant", ".", "exceptions", ".", "DependencyException", "with", "a", "cause", "if", "something", "goes", "wrong" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/path_runner.py#L19-L26
train
devassistant/devassistant
devassistant/path_runner.py
PathRunner.run
def run(self): """Runs all errors, dependencies and run methods of all *Assistant objects in self.path. Raises: devassistant.exceptions.ExecutionException with a cause if something goes wrong """ error = None # run 'pre_run', 'logging', 'dependencies' and 'run' try: # serve as a central place for error logging self._logging(self.parsed_args) if 'deps_only' not in self.parsed_args: self._run_path_run('pre', self.parsed_args) self._run_path_dependencies(self.parsed_args) if 'deps_only' not in self.parsed_args: self._run_path_run('', self.parsed_args) except exceptions.ExecutionException as e: error = self._log_if_not_logged(e) if isinstance(e, exceptions.YamlError): # if there's a yaml error, just shut down raise e # in any case, run post_run try: # serve as a central place for error logging self._run_path_run('post', self.parsed_args) except exceptions.ExecutionException as e: error = self._log_if_not_logged(e) # exitfuncs are run all regardless of exceptions; if there is an exception in one # of them, this function will raise it at the end try: utils.run_exitfuncs() except exceptions.ExecutionException as e: error = self._log_if_not_logged(e) if error: raise error
python
def run(self): """Runs all errors, dependencies and run methods of all *Assistant objects in self.path. Raises: devassistant.exceptions.ExecutionException with a cause if something goes wrong """ error = None # run 'pre_run', 'logging', 'dependencies' and 'run' try: # serve as a central place for error logging self._logging(self.parsed_args) if 'deps_only' not in self.parsed_args: self._run_path_run('pre', self.parsed_args) self._run_path_dependencies(self.parsed_args) if 'deps_only' not in self.parsed_args: self._run_path_run('', self.parsed_args) except exceptions.ExecutionException as e: error = self._log_if_not_logged(e) if isinstance(e, exceptions.YamlError): # if there's a yaml error, just shut down raise e # in any case, run post_run try: # serve as a central place for error logging self._run_path_run('post', self.parsed_args) except exceptions.ExecutionException as e: error = self._log_if_not_logged(e) # exitfuncs are run all regardless of exceptions; if there is an exception in one # of them, this function will raise it at the end try: utils.run_exitfuncs() except exceptions.ExecutionException as e: error = self._log_if_not_logged(e) if error: raise error
[ "def", "run", "(", "self", ")", ":", "error", "=", "None", "# run 'pre_run', 'logging', 'dependencies' and 'run'", "try", ":", "# serve as a central place for error logging", "self", ".", "_logging", "(", "self", ".", "parsed_args", ")", "if", "'deps_only'", "not", "in", "self", ".", "parsed_args", ":", "self", ".", "_run_path_run", "(", "'pre'", ",", "self", ".", "parsed_args", ")", "self", ".", "_run_path_dependencies", "(", "self", ".", "parsed_args", ")", "if", "'deps_only'", "not", "in", "self", ".", "parsed_args", ":", "self", ".", "_run_path_run", "(", "''", ",", "self", ".", "parsed_args", ")", "except", "exceptions", ".", "ExecutionException", "as", "e", ":", "error", "=", "self", ".", "_log_if_not_logged", "(", "e", ")", "if", "isinstance", "(", "e", ",", "exceptions", ".", "YamlError", ")", ":", "# if there's a yaml error, just shut down", "raise", "e", "# in any case, run post_run", "try", ":", "# serve as a central place for error logging", "self", ".", "_run_path_run", "(", "'post'", ",", "self", ".", "parsed_args", ")", "except", "exceptions", ".", "ExecutionException", "as", "e", ":", "error", "=", "self", ".", "_log_if_not_logged", "(", "e", ")", "# exitfuncs are run all regardless of exceptions; if there is an exception in one", "# of them, this function will raise it at the end", "try", ":", "utils", ".", "run_exitfuncs", "(", ")", "except", "exceptions", ".", "ExecutionException", "as", "e", ":", "error", "=", "self", ".", "_log_if_not_logged", "(", "e", ")", "if", "error", ":", "raise", "error" ]
Runs all errors, dependencies and run methods of all *Assistant objects in self.path. Raises: devassistant.exceptions.ExecutionException with a cause if something goes wrong
[ "Runs", "all", "errors", "dependencies", "and", "run", "methods", "of", "all", "*", "Assistant", "objects", "in", "self", ".", "path", ".", "Raises", ":", "devassistant", ".", "exceptions", ".", "ExecutionException", "with", "a", "cause", "if", "something", "goes", "wrong" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/path_runner.py#L42-L75
train
devassistant/devassistant
devassistant/dapi/__init__.py
DapFormatter.calculate_offset
def calculate_offset(cls, labels): '''Return the maximum length of the provided strings that have a nice variant in DapFormatter._nice_strings''' used_strings = set(cls._nice_strings.keys()) & set(labels) return max([len(cls._nice_strings[s]) for s in used_strings])
python
def calculate_offset(cls, labels): '''Return the maximum length of the provided strings that have a nice variant in DapFormatter._nice_strings''' used_strings = set(cls._nice_strings.keys()) & set(labels) return max([len(cls._nice_strings[s]) for s in used_strings])
[ "def", "calculate_offset", "(", "cls", ",", "labels", ")", ":", "used_strings", "=", "set", "(", "cls", ".", "_nice_strings", ".", "keys", "(", ")", ")", "&", "set", "(", "labels", ")", "return", "max", "(", "[", "len", "(", "cls", ".", "_nice_strings", "[", "s", "]", ")", "for", "s", "in", "used_strings", "]", ")" ]
Return the maximum length of the provided strings that have a nice variant in DapFormatter._nice_strings
[ "Return", "the", "maximum", "length", "of", "the", "provided", "strings", "that", "have", "a", "nice", "variant", "in", "DapFormatter", ".", "_nice_strings" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L57-L61
train
devassistant/devassistant
devassistant/dapi/__init__.py
DapFormatter.format_dapi_score
def format_dapi_score(cls, meta, offset): '''Format the line with DAPI user rating and number of votes''' if 'average_rank' and 'rank_count' in meta: label = (cls._nice_strings['average_rank'] + ':').ljust(offset + 2) score = cls._format_field(meta['average_rank']) votes = ' ({num} votes)'.format(num=meta['rank_count']) return label + score + votes else: return ''
python
def format_dapi_score(cls, meta, offset): '''Format the line with DAPI user rating and number of votes''' if 'average_rank' and 'rank_count' in meta: label = (cls._nice_strings['average_rank'] + ':').ljust(offset + 2) score = cls._format_field(meta['average_rank']) votes = ' ({num} votes)'.format(num=meta['rank_count']) return label + score + votes else: return ''
[ "def", "format_dapi_score", "(", "cls", ",", "meta", ",", "offset", ")", ":", "if", "'average_rank'", "and", "'rank_count'", "in", "meta", ":", "label", "=", "(", "cls", ".", "_nice_strings", "[", "'average_rank'", "]", "+", "':'", ")", ".", "ljust", "(", "offset", "+", "2", ")", "score", "=", "cls", ".", "_format_field", "(", "meta", "[", "'average_rank'", "]", ")", "votes", "=", "' ({num} votes)'", ".", "format", "(", "num", "=", "meta", "[", "'rank_count'", "]", ")", "return", "label", "+", "score", "+", "votes", "else", ":", "return", "''" ]
Format the line with DAPI user rating and number of votes
[ "Format", "the", "line", "with", "DAPI", "user", "rating", "and", "number", "of", "votes" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L64-L72
train
devassistant/devassistant
devassistant/dapi/__init__.py
DapFormatter.format_meta_lines
def format_meta_lines(cls, meta, labels, offset, **kwargs): '''Return all information from a given meta dictionary in a list of lines''' lines = [] # Name and underline name = meta['package_name'] if 'version' in meta: name += '-' + meta['version'] if 'custom_location' in kwargs: name += ' ({loc})'.format(loc=kwargs['custom_location']) lines.append(name) lines.append(len(name)*'=') lines.append('') # Summary lines.extend(meta['summary'].splitlines()) lines.append('') # Description if meta.get('description', ''): lines.extend(meta['description'].splitlines()) lines.append('') # Other metadata data = [] for item in labels: if meta.get(item, '') != '': # We want to process False and 0 label = (cls._nice_strings[item] + ':').ljust(offset + 2) data.append(label + cls._format_field(meta[item])) lines.extend(data) return lines
python
def format_meta_lines(cls, meta, labels, offset, **kwargs): '''Return all information from a given meta dictionary in a list of lines''' lines = [] # Name and underline name = meta['package_name'] if 'version' in meta: name += '-' + meta['version'] if 'custom_location' in kwargs: name += ' ({loc})'.format(loc=kwargs['custom_location']) lines.append(name) lines.append(len(name)*'=') lines.append('') # Summary lines.extend(meta['summary'].splitlines()) lines.append('') # Description if meta.get('description', ''): lines.extend(meta['description'].splitlines()) lines.append('') # Other metadata data = [] for item in labels: if meta.get(item, '') != '': # We want to process False and 0 label = (cls._nice_strings[item] + ':').ljust(offset + 2) data.append(label + cls._format_field(meta[item])) lines.extend(data) return lines
[ "def", "format_meta_lines", "(", "cls", ",", "meta", ",", "labels", ",", "offset", ",", "*", "*", "kwargs", ")", ":", "lines", "=", "[", "]", "# Name and underline", "name", "=", "meta", "[", "'package_name'", "]", "if", "'version'", "in", "meta", ":", "name", "+=", "'-'", "+", "meta", "[", "'version'", "]", "if", "'custom_location'", "in", "kwargs", ":", "name", "+=", "' ({loc})'", ".", "format", "(", "loc", "=", "kwargs", "[", "'custom_location'", "]", ")", "lines", ".", "append", "(", "name", ")", "lines", ".", "append", "(", "len", "(", "name", ")", "*", "'='", ")", "lines", ".", "append", "(", "''", ")", "# Summary", "lines", ".", "extend", "(", "meta", "[", "'summary'", "]", ".", "splitlines", "(", ")", ")", "lines", ".", "append", "(", "''", ")", "# Description", "if", "meta", ".", "get", "(", "'description'", ",", "''", ")", ":", "lines", ".", "extend", "(", "meta", "[", "'description'", "]", ".", "splitlines", "(", ")", ")", "lines", ".", "append", "(", "''", ")", "# Other metadata", "data", "=", "[", "]", "for", "item", "in", "labels", ":", "if", "meta", ".", "get", "(", "item", ",", "''", ")", "!=", "''", ":", "# We want to process False and 0", "label", "=", "(", "cls", ".", "_nice_strings", "[", "item", "]", "+", "':'", ")", ".", "ljust", "(", "offset", "+", "2", ")", "data", ".", "append", "(", "label", "+", "cls", ".", "_format_field", "(", "meta", "[", "item", "]", ")", ")", "lines", ".", "extend", "(", "data", ")", "return", "lines" ]
Return all information from a given meta dictionary in a list of lines
[ "Return", "all", "information", "from", "a", "given", "meta", "dictionary", "in", "a", "list", "of", "lines" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L75-L109
train
devassistant/devassistant
devassistant/dapi/__init__.py
DapFormatter._format_files
def _format_files(cls, files, kind): '''Format the list of files (e. g. assistants or snippets''' lines = [] if files: lines.append('The following {kind} are contained in this DAP:'.format(kind=kind.title())) for f in files: lines.append('* ' + strip_prefix(f, kind).replace(os.path.sep, ' ').strip()) return lines else: return ['No {kind} are contained in this DAP'.format(kind=kind.title())]
python
def _format_files(cls, files, kind): '''Format the list of files (e. g. assistants or snippets''' lines = [] if files: lines.append('The following {kind} are contained in this DAP:'.format(kind=kind.title())) for f in files: lines.append('* ' + strip_prefix(f, kind).replace(os.path.sep, ' ').strip()) return lines else: return ['No {kind} are contained in this DAP'.format(kind=kind.title())]
[ "def", "_format_files", "(", "cls", ",", "files", ",", "kind", ")", ":", "lines", "=", "[", "]", "if", "files", ":", "lines", ".", "append", "(", "'The following {kind} are contained in this DAP:'", ".", "format", "(", "kind", "=", "kind", ".", "title", "(", ")", ")", ")", "for", "f", "in", "files", ":", "lines", ".", "append", "(", "'* '", "+", "strip_prefix", "(", "f", ",", "kind", ")", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "' '", ")", ".", "strip", "(", ")", ")", "return", "lines", "else", ":", "return", "[", "'No {kind} are contained in this DAP'", ".", "format", "(", "kind", "=", "kind", ".", "title", "(", ")", ")", "]" ]
Format the list of files (e. g. assistants or snippets
[ "Format", "the", "list", "of", "files", "(", "e", ".", "g", ".", "assistants", "or", "snippets" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L112-L121
train
devassistant/devassistant
devassistant/dapi/__init__.py
DapFormatter.format_assistants_lines
def format_assistants_lines(cls, assistants): '''Return formatted assistants from the given list in human readable form.''' lines = cls._format_files(assistants, 'assistants') # Assistant help if assistants: lines.append('') assistant = strip_prefix(random.choice(assistants), 'assistants').replace(os.path.sep, ' ').strip() if len(assistants) == 1: strings = ['After you install this DAP, you can find help about the Assistant', 'by running "da {a} -h" .'] else: strings = ['After you install this DAP, you can find help, for example about the Assistant', '"{a}", by running "da {a} -h".'] lines.extend([l.format(a=assistant) for l in strings]) return lines
python
def format_assistants_lines(cls, assistants): '''Return formatted assistants from the given list in human readable form.''' lines = cls._format_files(assistants, 'assistants') # Assistant help if assistants: lines.append('') assistant = strip_prefix(random.choice(assistants), 'assistants').replace(os.path.sep, ' ').strip() if len(assistants) == 1: strings = ['After you install this DAP, you can find help about the Assistant', 'by running "da {a} -h" .'] else: strings = ['After you install this DAP, you can find help, for example about the Assistant', '"{a}", by running "da {a} -h".'] lines.extend([l.format(a=assistant) for l in strings]) return lines
[ "def", "format_assistants_lines", "(", "cls", ",", "assistants", ")", ":", "lines", "=", "cls", ".", "_format_files", "(", "assistants", ",", "'assistants'", ")", "# Assistant help", "if", "assistants", ":", "lines", ".", "append", "(", "''", ")", "assistant", "=", "strip_prefix", "(", "random", ".", "choice", "(", "assistants", ")", ",", "'assistants'", ")", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "' '", ")", ".", "strip", "(", ")", "if", "len", "(", "assistants", ")", "==", "1", ":", "strings", "=", "[", "'After you install this DAP, you can find help about the Assistant'", ",", "'by running \"da {a} -h\" .'", "]", "else", ":", "strings", "=", "[", "'After you install this DAP, you can find help, for example about the Assistant'", ",", "'\"{a}\", by running \"da {a} -h\".'", "]", "lines", ".", "extend", "(", "[", "l", ".", "format", "(", "a", "=", "assistant", ")", "for", "l", "in", "strings", "]", ")", "return", "lines" ]
Return formatted assistants from the given list in human readable form.
[ "Return", "formatted", "assistants", "from", "the", "given", "list", "in", "human", "readable", "form", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L124-L140
train
devassistant/devassistant
devassistant/dapi/__init__.py
DapFormatter.format_platforms
def format_platforms(cls, platforms): '''Formats supported platforms in human readable form''' lines = [] if platforms: lines.append('This DAP is only supported on the following platforms:') lines.extend([' * ' + platform for platform in platforms]) return lines
python
def format_platforms(cls, platforms): '''Formats supported platforms in human readable form''' lines = [] if platforms: lines.append('This DAP is only supported on the following platforms:') lines.extend([' * ' + platform for platform in platforms]) return lines
[ "def", "format_platforms", "(", "cls", ",", "platforms", ")", ":", "lines", "=", "[", "]", "if", "platforms", ":", "lines", ".", "append", "(", "'This DAP is only supported on the following platforms:'", ")", "lines", ".", "extend", "(", "[", "' * '", "+", "platform", "for", "platform", "in", "platforms", "]", ")", "return", "lines" ]
Formats supported platforms in human readable form
[ "Formats", "supported", "platforms", "in", "human", "readable", "form" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L148-L154
train
devassistant/devassistant
devassistant/dapi/__init__.py
DapChecker.check
def check(cls, dap, network=False, yamls=True, raises=False, logger=logger): '''Checks if the dap is valid, reports problems Parameters: network -- whether to run checks that requires network connection output -- where to write() problems, might be None raises -- whether to raise an exception immediately after problem is detected''' dap._check_raises = raises dap._problematic = False dap._logger = logger problems = list() problems += cls.check_meta(dap) problems += cls.check_no_self_dependency(dap) problems += cls.check_topdir(dap) problems += cls.check_files(dap) if yamls: problems += cls.check_yamls(dap) if network: problems += cls.check_name_not_on_dapi(dap) for problem in problems: dap._report_problem(problem.message, problem.level) del dap._check_raises return not dap._problematic
python
def check(cls, dap, network=False, yamls=True, raises=False, logger=logger): '''Checks if the dap is valid, reports problems Parameters: network -- whether to run checks that requires network connection output -- where to write() problems, might be None raises -- whether to raise an exception immediately after problem is detected''' dap._check_raises = raises dap._problematic = False dap._logger = logger problems = list() problems += cls.check_meta(dap) problems += cls.check_no_self_dependency(dap) problems += cls.check_topdir(dap) problems += cls.check_files(dap) if yamls: problems += cls.check_yamls(dap) if network: problems += cls.check_name_not_on_dapi(dap) for problem in problems: dap._report_problem(problem.message, problem.level) del dap._check_raises return not dap._problematic
[ "def", "check", "(", "cls", ",", "dap", ",", "network", "=", "False", ",", "yamls", "=", "True", ",", "raises", "=", "False", ",", "logger", "=", "logger", ")", ":", "dap", ".", "_check_raises", "=", "raises", "dap", ".", "_problematic", "=", "False", "dap", ".", "_logger", "=", "logger", "problems", "=", "list", "(", ")", "problems", "+=", "cls", ".", "check_meta", "(", "dap", ")", "problems", "+=", "cls", ".", "check_no_self_dependency", "(", "dap", ")", "problems", "+=", "cls", ".", "check_topdir", "(", "dap", ")", "problems", "+=", "cls", ".", "check_files", "(", "dap", ")", "if", "yamls", ":", "problems", "+=", "cls", ".", "check_yamls", "(", "dap", ")", "if", "network", ":", "problems", "+=", "cls", ".", "check_name_not_on_dapi", "(", "dap", ")", "for", "problem", "in", "problems", ":", "dap", ".", "_report_problem", "(", "problem", ".", "message", ",", "problem", ".", "level", ")", "del", "dap", ".", "_check_raises", "return", "not", "dap", ".", "_problematic" ]
Checks if the dap is valid, reports problems Parameters: network -- whether to run checks that requires network connection output -- where to write() problems, might be None raises -- whether to raise an exception immediately after problem is detected
[ "Checks", "if", "the", "dap", "is", "valid", "reports", "problems" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L160-L187
train
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", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L190-L225
train
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", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L228-L257
train
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", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L260-L288
train
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", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L291-L303
train
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", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L306-L394
train
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", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L397-L414
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L511-L513
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L521-L523
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L526-L528
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L535-L541
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L543-L552
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L582-L590
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L592-L602
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L604-L611
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L613-L618
train
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", ")" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L620-L649
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L651-L653
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/__init__.py#L655-L668
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/config_manager.py#L22-L43
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/config_manager.py#L45-L69
train
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", "." ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/config_manager.py#L77-L91
train
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" ]
2dbfeaa666a64127263664d18969c55d19ecc83e
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/gui/main_window.py#L110-L115
train