repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
aitjcize/cppman | cppman/util.py | get_width | def get_width():
"""Get terminal width"""
# Get terminal size
ws = struct.pack("HHHH", 0, 0, 0, 0)
ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)
lines, columns, x, y = struct.unpack("HHHH", ws)
width = min(columns * 39 // 40, columns - 2)
return width | python | def get_width():
"""Get terminal width"""
# Get terminal size
ws = struct.pack("HHHH", 0, 0, 0, 0)
ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)
lines, columns, x, y = struct.unpack("HHHH", ws)
width = min(columns * 39 // 40, columns - 2)
return width | [
"def",
"get_width",
"(",
")",
":",
"# Get terminal size",
"ws",
"=",
"struct",
".",
"pack",
"(",
"\"HHHH\"",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"ws",
"=",
"fcntl",
".",
"ioctl",
"(",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
",",
"termios",
".",
"TIOCGWINSZ",
",",
"ws",
")",
"lines",
",",
"columns",
",",
"x",
",",
"y",
"=",
"struct",
".",
"unpack",
"(",
"\"HHHH\"",
",",
"ws",
")",
"width",
"=",
"min",
"(",
"columns",
"*",
"39",
"//",
"40",
",",
"columns",
"-",
"2",
")",
"return",
"width"
] | Get terminal width | [
"Get",
"terminal",
"width"
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/util.py#L83-L90 | train |
aitjcize/cppman | cppman/util.py | groff2man | def groff2man(data):
"""Read groff-formatted text and output man pages."""
width = get_width()
cmd = 'groff -t -Tascii -m man -rLL=%dn -rLT=%dn' % (width, width)
handle = subprocess.Popen(
cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
man_text, stderr = handle.communicate(data)
return man_text | python | def groff2man(data):
"""Read groff-formatted text and output man pages."""
width = get_width()
cmd = 'groff -t -Tascii -m man -rLL=%dn -rLT=%dn' % (width, width)
handle = subprocess.Popen(
cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
man_text, stderr = handle.communicate(data)
return man_text | [
"def",
"groff2man",
"(",
"data",
")",
":",
"width",
"=",
"get_width",
"(",
")",
"cmd",
"=",
"'groff -t -Tascii -m man -rLL=%dn -rLT=%dn'",
"%",
"(",
"width",
",",
"width",
")",
"handle",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"man_text",
",",
"stderr",
"=",
"handle",
".",
"communicate",
"(",
"data",
")",
"return",
"man_text"
] | Read groff-formatted text and output man pages. | [
"Read",
"groff",
"-",
"formatted",
"text",
"and",
"output",
"man",
"pages",
"."
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/util.py#L93-L102 | train |
aitjcize/cppman | cppman/main.py | Cppman.extract_name | def extract_name(self, data):
"""Extract man page name from web page."""
name = re.search('<h1[^>]*>(.+?)</h1>', data).group(1)
name = re.sub(r'<([^>]+)>', r'', name)
name = re.sub(r'>', r'>', name)
name = re.sub(r'<', r'<', name)
return name | python | def extract_name(self, data):
"""Extract man page name from web page."""
name = re.search('<h1[^>]*>(.+?)</h1>', data).group(1)
name = re.sub(r'<([^>]+)>', r'', name)
name = re.sub(r'>', r'>', name)
name = re.sub(r'<', r'<', name)
return name | [
"def",
"extract_name",
"(",
"self",
",",
"data",
")",
":",
"name",
"=",
"re",
".",
"search",
"(",
"'<h1[^>]*>(.+?)</h1>'",
",",
"data",
")",
".",
"group",
"(",
"1",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"r'<([^>]+)>'",
",",
"r''",
",",
"name",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"r'>'",
",",
"r'>'",
",",
"name",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"r'<'",
",",
"r'<'",
",",
"name",
")",
"return",
"name"
] | Extract man page name from web page. | [
"Extract",
"man",
"page",
"name",
"from",
"web",
"page",
"."
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/main.py#L56-L62 | train |
aitjcize/cppman | cppman/main.py | Cppman.cache_all | def cache_all(self):
"""Cache all available man pages"""
respond = input(
'By default, cppman fetches pages on-the-fly if corresponding '
'page is not found in the cache. The "cache-all" option is only '
'useful if you want to view man pages offline. '
'Caching all contents will take several minutes, '
'do you want to continue [y/N]? ')
if not (respond and 'yes'.startswith(respond.lower())):
raise KeyboardInterrupt
try:
os.makedirs(environ.cache_dir)
except:
pass
self.success_count = 0
self.failure_count = 0
if not os.path.exists(environ.index_db):
raise RuntimeError("can't find index.db")
conn = sqlite3.connect(environ.index_db)
cursor = conn.cursor()
source = environ.config.source
print('Caching manpages from %s ...' % source)
data = cursor.execute('SELECT * FROM "%s"' % source).fetchall()
for name, url, _ in data:
print('Caching %s ...' % name)
retries = 3
while retries > 0:
try:
self.cache_man_page(source, url, name)
except Exception:
print('Retrying ...')
retries -= 1
else:
self.success_count += 1
break
else:
print('Error caching %s ...' % name)
self.failure_count += 1
conn.close()
print('\n%d manual pages cached successfully.' % self.success_count)
print('%d manual pages failed to cache.' % self.failure_count)
self.update_mandb(False) | python | def cache_all(self):
"""Cache all available man pages"""
respond = input(
'By default, cppman fetches pages on-the-fly if corresponding '
'page is not found in the cache. The "cache-all" option is only '
'useful if you want to view man pages offline. '
'Caching all contents will take several minutes, '
'do you want to continue [y/N]? ')
if not (respond and 'yes'.startswith(respond.lower())):
raise KeyboardInterrupt
try:
os.makedirs(environ.cache_dir)
except:
pass
self.success_count = 0
self.failure_count = 0
if not os.path.exists(environ.index_db):
raise RuntimeError("can't find index.db")
conn = sqlite3.connect(environ.index_db)
cursor = conn.cursor()
source = environ.config.source
print('Caching manpages from %s ...' % source)
data = cursor.execute('SELECT * FROM "%s"' % source).fetchall()
for name, url, _ in data:
print('Caching %s ...' % name)
retries = 3
while retries > 0:
try:
self.cache_man_page(source, url, name)
except Exception:
print('Retrying ...')
retries -= 1
else:
self.success_count += 1
break
else:
print('Error caching %s ...' % name)
self.failure_count += 1
conn.close()
print('\n%d manual pages cached successfully.' % self.success_count)
print('%d manual pages failed to cache.' % self.failure_count)
self.update_mandb(False) | [
"def",
"cache_all",
"(",
"self",
")",
":",
"respond",
"=",
"input",
"(",
"'By default, cppman fetches pages on-the-fly if corresponding '",
"'page is not found in the cache. The \"cache-all\" option is only '",
"'useful if you want to view man pages offline. '",
"'Caching all contents will take several minutes, '",
"'do you want to continue [y/N]? '",
")",
"if",
"not",
"(",
"respond",
"and",
"'yes'",
".",
"startswith",
"(",
"respond",
".",
"lower",
"(",
")",
")",
")",
":",
"raise",
"KeyboardInterrupt",
"try",
":",
"os",
".",
"makedirs",
"(",
"environ",
".",
"cache_dir",
")",
"except",
":",
"pass",
"self",
".",
"success_count",
"=",
"0",
"self",
".",
"failure_count",
"=",
"0",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"environ",
".",
"index_db",
")",
":",
"raise",
"RuntimeError",
"(",
"\"can't find index.db\"",
")",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"environ",
".",
"index_db",
")",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"source",
"=",
"environ",
".",
"config",
".",
"source",
"print",
"(",
"'Caching manpages from %s ...'",
"%",
"source",
")",
"data",
"=",
"cursor",
".",
"execute",
"(",
"'SELECT * FROM \"%s\"'",
"%",
"source",
")",
".",
"fetchall",
"(",
")",
"for",
"name",
",",
"url",
",",
"_",
"in",
"data",
":",
"print",
"(",
"'Caching %s ...'",
"%",
"name",
")",
"retries",
"=",
"3",
"while",
"retries",
">",
"0",
":",
"try",
":",
"self",
".",
"cache_man_page",
"(",
"source",
",",
"url",
",",
"name",
")",
"except",
"Exception",
":",
"print",
"(",
"'Retrying ...'",
")",
"retries",
"-=",
"1",
"else",
":",
"self",
".",
"success_count",
"+=",
"1",
"break",
"else",
":",
"print",
"(",
"'Error caching %s ...'",
"%",
"name",
")",
"self",
".",
"failure_count",
"+=",
"1",
"conn",
".",
"close",
"(",
")",
"print",
"(",
"'\\n%d manual pages cached successfully.'",
"%",
"self",
".",
"success_count",
")",
"print",
"(",
"'%d manual pages failed to cache.'",
"%",
"self",
".",
"failure_count",
")",
"self",
".",
"update_mandb",
"(",
"False",
")"
] | Cache all available man pages | [
"Cache",
"all",
"available",
"man",
"pages"
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/main.py#L204-L254 | train |
aitjcize/cppman | cppman/main.py | Cppman.cache_man_page | def cache_man_page(self, source, url, name):
"""callback to cache new man page"""
# Skip if already exists, override if forced flag is true
outname = self.get_page_path(source, name)
if os.path.exists(outname) and not self.forced:
return
try:
os.makedirs(os.path.join(environ.cache_dir, source))
except OSError:
pass
# There are often some errors in the HTML, for example: missing closing
# tag. We use fixupHTML to fix this.
data = util.fixupHTML(urllib.request.urlopen(url).read())
formatter = importlib.import_module('cppman.formatter.%s' % source[:-4])
groff_text = formatter.html2groff(data, name)
with gzip.open(outname, 'w') as f:
f.write(groff_text.encode('utf-8')) | python | def cache_man_page(self, source, url, name):
"""callback to cache new man page"""
# Skip if already exists, override if forced flag is true
outname = self.get_page_path(source, name)
if os.path.exists(outname) and not self.forced:
return
try:
os.makedirs(os.path.join(environ.cache_dir, source))
except OSError:
pass
# There are often some errors in the HTML, for example: missing closing
# tag. We use fixupHTML to fix this.
data = util.fixupHTML(urllib.request.urlopen(url).read())
formatter = importlib.import_module('cppman.formatter.%s' % source[:-4])
groff_text = formatter.html2groff(data, name)
with gzip.open(outname, 'w') as f:
f.write(groff_text.encode('utf-8')) | [
"def",
"cache_man_page",
"(",
"self",
",",
"source",
",",
"url",
",",
"name",
")",
":",
"# Skip if already exists, override if forced flag is true",
"outname",
"=",
"self",
".",
"get_page_path",
"(",
"source",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"outname",
")",
"and",
"not",
"self",
".",
"forced",
":",
"return",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"environ",
".",
"cache_dir",
",",
"source",
")",
")",
"except",
"OSError",
":",
"pass",
"# There are often some errors in the HTML, for example: missing closing",
"# tag. We use fixupHTML to fix this.",
"data",
"=",
"util",
".",
"fixupHTML",
"(",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"url",
")",
".",
"read",
"(",
")",
")",
"formatter",
"=",
"importlib",
".",
"import_module",
"(",
"'cppman.formatter.%s'",
"%",
"source",
"[",
":",
"-",
"4",
"]",
")",
"groff_text",
"=",
"formatter",
".",
"html2groff",
"(",
"data",
",",
"name",
")",
"with",
"gzip",
".",
"open",
"(",
"outname",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"groff_text",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] | callback to cache new man page | [
"callback",
"to",
"cache",
"new",
"man",
"page"
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/main.py#L256-L276 | train |
aitjcize/cppman | cppman/main.py | Cppman.man | def man(self, pattern):
"""Call viewer.sh to view man page"""
try:
avail = os.listdir(os.path.join(environ.cache_dir, environ.source))
except OSError:
avail = []
if not os.path.exists(environ.index_db):
raise RuntimeError("can't find index.db")
conn = sqlite3.connect(environ.index_db)
cursor = conn.cursor()
# Try direct match
try:
page_name, url = cursor.execute(
'SELECT name,url FROM "%s" '
'WHERE name="%s" ORDER BY LENGTH(name)'
% (environ.source, pattern)).fetchone()
except TypeError:
# Try standard library
try:
page_name, url = cursor.execute(
'SELECT name,url FROM "%s" '
'WHERE name="std::%s" ORDER BY LENGTH(name)'
% (environ.source, pattern)).fetchone()
except TypeError:
try:
page_name, url = cursor.execute(
'SELECT name,url FROM "%s" '
'WHERE name LIKE "%%%s%%" ORDER BY LENGTH(name)'
% (environ.source, pattern)).fetchone()
except TypeError:
raise RuntimeError('No manual entry for ' + pattern)
finally:
conn.close()
page_filename = self.get_normalized_page_name(page_name)
if self.forced or page_filename + '.3.gz' not in avail:
self.cache_man_page(environ.source, url, page_name)
pager_type = environ.pager if sys.stdout.isatty() else 'pipe'
# Call viewer
columns = (util.get_width() if self.force_columns == -1 else
self.force_columns)
pid = os.fork()
if pid == 0:
os.execl('/bin/sh', '/bin/sh', environ.pager_script, pager_type,
self.get_page_path(environ.source, page_name),
str(columns), environ.pager_config, page_name)
return pid | python | def man(self, pattern):
"""Call viewer.sh to view man page"""
try:
avail = os.listdir(os.path.join(environ.cache_dir, environ.source))
except OSError:
avail = []
if not os.path.exists(environ.index_db):
raise RuntimeError("can't find index.db")
conn = sqlite3.connect(environ.index_db)
cursor = conn.cursor()
# Try direct match
try:
page_name, url = cursor.execute(
'SELECT name,url FROM "%s" '
'WHERE name="%s" ORDER BY LENGTH(name)'
% (environ.source, pattern)).fetchone()
except TypeError:
# Try standard library
try:
page_name, url = cursor.execute(
'SELECT name,url FROM "%s" '
'WHERE name="std::%s" ORDER BY LENGTH(name)'
% (environ.source, pattern)).fetchone()
except TypeError:
try:
page_name, url = cursor.execute(
'SELECT name,url FROM "%s" '
'WHERE name LIKE "%%%s%%" ORDER BY LENGTH(name)'
% (environ.source, pattern)).fetchone()
except TypeError:
raise RuntimeError('No manual entry for ' + pattern)
finally:
conn.close()
page_filename = self.get_normalized_page_name(page_name)
if self.forced or page_filename + '.3.gz' not in avail:
self.cache_man_page(environ.source, url, page_name)
pager_type = environ.pager if sys.stdout.isatty() else 'pipe'
# Call viewer
columns = (util.get_width() if self.force_columns == -1 else
self.force_columns)
pid = os.fork()
if pid == 0:
os.execl('/bin/sh', '/bin/sh', environ.pager_script, pager_type,
self.get_page_path(environ.source, page_name),
str(columns), environ.pager_config, page_name)
return pid | [
"def",
"man",
"(",
"self",
",",
"pattern",
")",
":",
"try",
":",
"avail",
"=",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"environ",
".",
"cache_dir",
",",
"environ",
".",
"source",
")",
")",
"except",
"OSError",
":",
"avail",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"environ",
".",
"index_db",
")",
":",
"raise",
"RuntimeError",
"(",
"\"can't find index.db\"",
")",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"environ",
".",
"index_db",
")",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"# Try direct match",
"try",
":",
"page_name",
",",
"url",
"=",
"cursor",
".",
"execute",
"(",
"'SELECT name,url FROM \"%s\" '",
"'WHERE name=\"%s\" ORDER BY LENGTH(name)'",
"%",
"(",
"environ",
".",
"source",
",",
"pattern",
")",
")",
".",
"fetchone",
"(",
")",
"except",
"TypeError",
":",
"# Try standard library",
"try",
":",
"page_name",
",",
"url",
"=",
"cursor",
".",
"execute",
"(",
"'SELECT name,url FROM \"%s\" '",
"'WHERE name=\"std::%s\" ORDER BY LENGTH(name)'",
"%",
"(",
"environ",
".",
"source",
",",
"pattern",
")",
")",
".",
"fetchone",
"(",
")",
"except",
"TypeError",
":",
"try",
":",
"page_name",
",",
"url",
"=",
"cursor",
".",
"execute",
"(",
"'SELECT name,url FROM \"%s\" '",
"'WHERE name LIKE \"%%%s%%\" ORDER BY LENGTH(name)'",
"%",
"(",
"environ",
".",
"source",
",",
"pattern",
")",
")",
".",
"fetchone",
"(",
")",
"except",
"TypeError",
":",
"raise",
"RuntimeError",
"(",
"'No manual entry for '",
"+",
"pattern",
")",
"finally",
":",
"conn",
".",
"close",
"(",
")",
"page_filename",
"=",
"self",
".",
"get_normalized_page_name",
"(",
"page_name",
")",
"if",
"self",
".",
"forced",
"or",
"page_filename",
"+",
"'.3.gz'",
"not",
"in",
"avail",
":",
"self",
".",
"cache_man_page",
"(",
"environ",
".",
"source",
",",
"url",
",",
"page_name",
")",
"pager_type",
"=",
"environ",
".",
"pager",
"if",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
"else",
"'pipe'",
"# Call viewer",
"columns",
"=",
"(",
"util",
".",
"get_width",
"(",
")",
"if",
"self",
".",
"force_columns",
"==",
"-",
"1",
"else",
"self",
".",
"force_columns",
")",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
"==",
"0",
":",
"os",
".",
"execl",
"(",
"'/bin/sh'",
",",
"'/bin/sh'",
",",
"environ",
".",
"pager_script",
",",
"pager_type",
",",
"self",
".",
"get_page_path",
"(",
"environ",
".",
"source",
",",
"page_name",
")",
",",
"str",
"(",
"columns",
")",
",",
"environ",
".",
"pager_config",
",",
"page_name",
")",
"return",
"pid"
] | Call viewer.sh to view man page | [
"Call",
"viewer",
".",
"sh",
"to",
"view",
"man",
"page"
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/main.py#L282-L333 | train |
aitjcize/cppman | cppman/main.py | Cppman.find | def find(self, pattern):
"""Find pages in database."""
if not os.path.exists(environ.index_db):
raise RuntimeError("can't find index.db")
conn = sqlite3.connect(environ.index_db)
cursor = conn.cursor()
selected = cursor.execute(
'SELECT * FROM "%s" WHERE name '
'LIKE "%%%s%%" ORDER BY LENGTH(name)'
% (environ.source, pattern)).fetchall()
pat = re.compile('(%s)' % re.escape(pattern), re.I)
if selected:
for name, url, std in selected:
if os.isatty(sys.stdout.fileno()):
print(pat.sub(r'\033[1;31m\1\033[0m', name) +
(' \033[1;33m[%s]\033[0m' % std if std else ''))
else:
print(name + (' [%s]' % std if std else ''))
else:
raise RuntimeError('%s: nothing appropriate.' % pattern) | python | def find(self, pattern):
"""Find pages in database."""
if not os.path.exists(environ.index_db):
raise RuntimeError("can't find index.db")
conn = sqlite3.connect(environ.index_db)
cursor = conn.cursor()
selected = cursor.execute(
'SELECT * FROM "%s" WHERE name '
'LIKE "%%%s%%" ORDER BY LENGTH(name)'
% (environ.source, pattern)).fetchall()
pat = re.compile('(%s)' % re.escape(pattern), re.I)
if selected:
for name, url, std in selected:
if os.isatty(sys.stdout.fileno()):
print(pat.sub(r'\033[1;31m\1\033[0m', name) +
(' \033[1;33m[%s]\033[0m' % std if std else ''))
else:
print(name + (' [%s]' % std if std else ''))
else:
raise RuntimeError('%s: nothing appropriate.' % pattern) | [
"def",
"find",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"environ",
".",
"index_db",
")",
":",
"raise",
"RuntimeError",
"(",
"\"can't find index.db\"",
")",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"environ",
".",
"index_db",
")",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"selected",
"=",
"cursor",
".",
"execute",
"(",
"'SELECT * FROM \"%s\" WHERE name '",
"'LIKE \"%%%s%%\" ORDER BY LENGTH(name)'",
"%",
"(",
"environ",
".",
"source",
",",
"pattern",
")",
")",
".",
"fetchall",
"(",
")",
"pat",
"=",
"re",
".",
"compile",
"(",
"'(%s)'",
"%",
"re",
".",
"escape",
"(",
"pattern",
")",
",",
"re",
".",
"I",
")",
"if",
"selected",
":",
"for",
"name",
",",
"url",
",",
"std",
"in",
"selected",
":",
"if",
"os",
".",
"isatty",
"(",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
")",
":",
"print",
"(",
"pat",
".",
"sub",
"(",
"r'\\033[1;31m\\1\\033[0m'",
",",
"name",
")",
"+",
"(",
"' \\033[1;33m[%s]\\033[0m'",
"%",
"std",
"if",
"std",
"else",
"''",
")",
")",
"else",
":",
"print",
"(",
"name",
"+",
"(",
"' [%s]'",
"%",
"std",
"if",
"std",
"else",
"''",
")",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'%s: nothing appropriate.'",
"%",
"pattern",
")"
] | Find pages in database. | [
"Find",
"pages",
"in",
"database",
"."
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/main.py#L335-L358 | train |
aitjcize/cppman | cppman/main.py | Cppman.update_mandb | def update_mandb(self, quiet=True):
"""Update mandb."""
if not environ.config.UpdateManPath:
return
print('\nrunning mandb...')
cmd = 'mandb %s' % (' -q' if quiet else '')
subprocess.Popen(cmd, shell=True).wait() | python | def update_mandb(self, quiet=True):
"""Update mandb."""
if not environ.config.UpdateManPath:
return
print('\nrunning mandb...')
cmd = 'mandb %s' % (' -q' if quiet else '')
subprocess.Popen(cmd, shell=True).wait() | [
"def",
"update_mandb",
"(",
"self",
",",
"quiet",
"=",
"True",
")",
":",
"if",
"not",
"environ",
".",
"config",
".",
"UpdateManPath",
":",
"return",
"print",
"(",
"'\\nrunning mandb...'",
")",
"cmd",
"=",
"'mandb %s'",
"%",
"(",
"' -q'",
"if",
"quiet",
"else",
"''",
")",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
")",
".",
"wait",
"(",
")"
] | Update mandb. | [
"Update",
"mandb",
"."
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/main.py#L360-L366 | train |
aitjcize/cppman | cppman/config.py | Config.set_default | def set_default(self):
"""Set config to default."""
try:
os.makedirs(os.path.dirname(self._configfile))
except:
pass
self._config = configparser.RawConfigParser()
self._config.add_section('Settings')
for key, val in self.DEFAULTS.items():
self._config.set('Settings', key, val)
with open(self._configfile, 'w') as f:
self._config.write(f) | python | def set_default(self):
"""Set config to default."""
try:
os.makedirs(os.path.dirname(self._configfile))
except:
pass
self._config = configparser.RawConfigParser()
self._config.add_section('Settings')
for key, val in self.DEFAULTS.items():
self._config.set('Settings', key, val)
with open(self._configfile, 'w') as f:
self._config.write(f) | [
"def",
"set_default",
"(",
"self",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"_configfile",
")",
")",
"except",
":",
"pass",
"self",
".",
"_config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"self",
".",
"_config",
".",
"add_section",
"(",
"'Settings'",
")",
"for",
"key",
",",
"val",
"in",
"self",
".",
"DEFAULTS",
".",
"items",
"(",
")",
":",
"self",
".",
"_config",
".",
"set",
"(",
"'Settings'",
",",
"key",
",",
"val",
")",
"with",
"open",
"(",
"self",
".",
"_configfile",
",",
"'w'",
")",
"as",
"f",
":",
"self",
".",
"_config",
".",
"write",
"(",
"f",
")"
] | Set config to default. | [
"Set",
"config",
"to",
"default",
"."
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/config.py#L64-L78 | train |
aitjcize/cppman | cppman/config.py | Config.save | def save(self):
"""Store config back to file."""
try:
os.makedirs(os.path.dirname(self._configfile))
except:
pass
with open(self._configfile, 'w') as f:
self._config.write(f) | python | def save(self):
"""Store config back to file."""
try:
os.makedirs(os.path.dirname(self._configfile))
except:
pass
with open(self._configfile, 'w') as f:
self._config.write(f) | [
"def",
"save",
"(",
"self",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"_configfile",
")",
")",
"except",
":",
"pass",
"with",
"open",
"(",
"self",
".",
"_configfile",
",",
"'w'",
")",
"as",
"f",
":",
"self",
".",
"_config",
".",
"write",
"(",
"f",
")"
] | Store config back to file. | [
"Store",
"config",
"back",
"to",
"file",
"."
] | 7b48e81b2cd3baa912d73dfe977ecbaff945a93c | https://github.com/aitjcize/cppman/blob/7b48e81b2cd3baa912d73dfe977ecbaff945a93c/cppman/config.py#L80-L88 | train |
fbcotter/py3nvml | py3nvml/utils.py | get_free_gpus | def get_free_gpus(max_procs=0):
"""
Checks the number of processes running on your GPUs.
Parameters
----------
max_procs : int
Maximum number of procs allowed to run on a gpu for it to be considered
'available'
Returns
-------
availabilities : list(bool)
List of length N for an N-gpu system. The nth value will be true, if the
nth gpu had at most max_procs processes running on it. Set to 0 to look
for gpus with no procs on it.
Note
----
If function can't query the driver will return an empty list rather than raise an
Exception.
"""
# Try connect with NVIDIA drivers
logger = logging.getLogger(__name__)
try:
py3nvml.nvmlInit()
except:
str_ = """Couldn't connect to nvml drivers. Check they are installed correctly."""
warnings.warn(str_, RuntimeWarning)
logger.warn(str_)
return []
num_gpus = py3nvml.nvmlDeviceGetCount()
gpu_free = [False]*num_gpus
for i in range(num_gpus):
try:
h = py3nvml.nvmlDeviceGetHandleByIndex(i)
except:
continue
procs = try_get_info(py3nvml.nvmlDeviceGetComputeRunningProcesses, h,
['something'])
if len(procs) <= max_procs:
gpu_free[i] = True
py3nvml.nvmlShutdown()
return gpu_free | python | def get_free_gpus(max_procs=0):
"""
Checks the number of processes running on your GPUs.
Parameters
----------
max_procs : int
Maximum number of procs allowed to run on a gpu for it to be considered
'available'
Returns
-------
availabilities : list(bool)
List of length N for an N-gpu system. The nth value will be true, if the
nth gpu had at most max_procs processes running on it. Set to 0 to look
for gpus with no procs on it.
Note
----
If function can't query the driver will return an empty list rather than raise an
Exception.
"""
# Try connect with NVIDIA drivers
logger = logging.getLogger(__name__)
try:
py3nvml.nvmlInit()
except:
str_ = """Couldn't connect to nvml drivers. Check they are installed correctly."""
warnings.warn(str_, RuntimeWarning)
logger.warn(str_)
return []
num_gpus = py3nvml.nvmlDeviceGetCount()
gpu_free = [False]*num_gpus
for i in range(num_gpus):
try:
h = py3nvml.nvmlDeviceGetHandleByIndex(i)
except:
continue
procs = try_get_info(py3nvml.nvmlDeviceGetComputeRunningProcesses, h,
['something'])
if len(procs) <= max_procs:
gpu_free[i] = True
py3nvml.nvmlShutdown()
return gpu_free | [
"def",
"get_free_gpus",
"(",
"max_procs",
"=",
"0",
")",
":",
"# Try connect with NVIDIA drivers",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"try",
":",
"py3nvml",
".",
"nvmlInit",
"(",
")",
"except",
":",
"str_",
"=",
"\"\"\"Couldn't connect to nvml drivers. Check they are installed correctly.\"\"\"",
"warnings",
".",
"warn",
"(",
"str_",
",",
"RuntimeWarning",
")",
"logger",
".",
"warn",
"(",
"str_",
")",
"return",
"[",
"]",
"num_gpus",
"=",
"py3nvml",
".",
"nvmlDeviceGetCount",
"(",
")",
"gpu_free",
"=",
"[",
"False",
"]",
"*",
"num_gpus",
"for",
"i",
"in",
"range",
"(",
"num_gpus",
")",
":",
"try",
":",
"h",
"=",
"py3nvml",
".",
"nvmlDeviceGetHandleByIndex",
"(",
"i",
")",
"except",
":",
"continue",
"procs",
"=",
"try_get_info",
"(",
"py3nvml",
".",
"nvmlDeviceGetComputeRunningProcesses",
",",
"h",
",",
"[",
"'something'",
"]",
")",
"if",
"len",
"(",
"procs",
")",
"<=",
"max_procs",
":",
"gpu_free",
"[",
"i",
"]",
"=",
"True",
"py3nvml",
".",
"nvmlShutdown",
"(",
")",
"return",
"gpu_free"
] | Checks the number of processes running on your GPUs.
Parameters
----------
max_procs : int
Maximum number of procs allowed to run on a gpu for it to be considered
'available'
Returns
-------
availabilities : list(bool)
List of length N for an N-gpu system. The nth value will be true, if the
nth gpu had at most max_procs processes running on it. Set to 0 to look
for gpus with no procs on it.
Note
----
If function can't query the driver will return an empty list rather than raise an
Exception. | [
"Checks",
"the",
"number",
"of",
"processes",
"running",
"on",
"your",
"GPUs",
"."
] | 47f0f2c0eee56dec4e4beebec26b734e01d357b7 | https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/utils.py#L170-L216 | train |
fbcotter/py3nvml | py3nvml/utils.py | get_num_procs | def get_num_procs():
""" Gets the number of processes running on each gpu
Returns
-------
num_procs : list(int)
Number of processes running on each gpu
Note
----
If function can't query the driver will return an empty list rather than raise an
Exception.
Note
----
If function can't get the info from the gpu will return -1 in that gpu's place
"""
# Try connect with NVIDIA drivers
logger = logging.getLogger(__name__)
try:
py3nvml.nvmlInit()
except:
str_ = """Couldn't connect to nvml drivers. Check they are installed correctly."""
warnings.warn(str_, RuntimeWarning)
logger.warn(str_)
return []
num_gpus = py3nvml.nvmlDeviceGetCount()
gpu_procs = [-1]*num_gpus
for i in range(num_gpus):
try:
h = py3nvml.nvmlDeviceGetHandleByIndex(i)
except:
continue
procs = try_get_info(py3nvml.nvmlDeviceGetComputeRunningProcesses, h,
['something'])
gpu_procs[i] = len(procs)
py3nvml.nvmlShutdown()
return gpu_procs | python | def get_num_procs():
""" Gets the number of processes running on each gpu
Returns
-------
num_procs : list(int)
Number of processes running on each gpu
Note
----
If function can't query the driver will return an empty list rather than raise an
Exception.
Note
----
If function can't get the info from the gpu will return -1 in that gpu's place
"""
# Try connect with NVIDIA drivers
logger = logging.getLogger(__name__)
try:
py3nvml.nvmlInit()
except:
str_ = """Couldn't connect to nvml drivers. Check they are installed correctly."""
warnings.warn(str_, RuntimeWarning)
logger.warn(str_)
return []
num_gpus = py3nvml.nvmlDeviceGetCount()
gpu_procs = [-1]*num_gpus
for i in range(num_gpus):
try:
h = py3nvml.nvmlDeviceGetHandleByIndex(i)
except:
continue
procs = try_get_info(py3nvml.nvmlDeviceGetComputeRunningProcesses, h,
['something'])
gpu_procs[i] = len(procs)
py3nvml.nvmlShutdown()
return gpu_procs | [
"def",
"get_num_procs",
"(",
")",
":",
"# Try connect with NVIDIA drivers",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"try",
":",
"py3nvml",
".",
"nvmlInit",
"(",
")",
"except",
":",
"str_",
"=",
"\"\"\"Couldn't connect to nvml drivers. Check they are installed correctly.\"\"\"",
"warnings",
".",
"warn",
"(",
"str_",
",",
"RuntimeWarning",
")",
"logger",
".",
"warn",
"(",
"str_",
")",
"return",
"[",
"]",
"num_gpus",
"=",
"py3nvml",
".",
"nvmlDeviceGetCount",
"(",
")",
"gpu_procs",
"=",
"[",
"-",
"1",
"]",
"*",
"num_gpus",
"for",
"i",
"in",
"range",
"(",
"num_gpus",
")",
":",
"try",
":",
"h",
"=",
"py3nvml",
".",
"nvmlDeviceGetHandleByIndex",
"(",
"i",
")",
"except",
":",
"continue",
"procs",
"=",
"try_get_info",
"(",
"py3nvml",
".",
"nvmlDeviceGetComputeRunningProcesses",
",",
"h",
",",
"[",
"'something'",
"]",
")",
"gpu_procs",
"[",
"i",
"]",
"=",
"len",
"(",
"procs",
")",
"py3nvml",
".",
"nvmlShutdown",
"(",
")",
"return",
"gpu_procs"
] | Gets the number of processes running on each gpu
Returns
-------
num_procs : list(int)
Number of processes running on each gpu
Note
----
If function can't query the driver will return an empty list rather than raise an
Exception.
Note
----
If function can't get the info from the gpu will return -1 in that gpu's place | [
"Gets",
"the",
"number",
"of",
"processes",
"running",
"on",
"each",
"gpu"
] | 47f0f2c0eee56dec4e4beebec26b734e01d357b7 | https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/utils.py#L219-L258 | train |
fbcotter/py3nvml | py3nvml/py3nvml.py | _extractNVMLErrorsAsClasses | def _extractNVMLErrorsAsClasses():
"""
Generates a hierarchy of classes on top of NVMLError class.
Each NVML Error gets a new NVMLError subclass. This way try,except blocks
can filter appropriate exceptions more easily.
NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass. e.g.
NVML_ERROR_ALREADY_INITIALIZED will be turned into
NVMLError_AlreadyInitialized
"""
this_module = sys.modules[__name__]
nvmlErrorsNames = [x for x in dir(this_module) if x.startswith("NVML_ERROR_")]
for err_name in nvmlErrorsNames:
# e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized
class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "")
err_val = getattr(this_module, err_name)
def gen_new(val):
def new(typ):
obj = NVMLError.__new__(typ, val)
return obj
return new
new_error_class = type(class_name, (NVMLError,), {'__new__': gen_new(err_val)})
new_error_class.__module__ = __name__
setattr(this_module, class_name, new_error_class)
NVMLError._valClassMapping[err_val] = new_error_class | python | def _extractNVMLErrorsAsClasses():
"""
Generates a hierarchy of classes on top of NVMLError class.
Each NVML Error gets a new NVMLError subclass. This way try,except blocks
can filter appropriate exceptions more easily.
NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass. e.g.
NVML_ERROR_ALREADY_INITIALIZED will be turned into
NVMLError_AlreadyInitialized
"""
this_module = sys.modules[__name__]
nvmlErrorsNames = [x for x in dir(this_module) if x.startswith("NVML_ERROR_")]
for err_name in nvmlErrorsNames:
# e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized
class_name = "NVMLError_" + string.capwords(err_name.replace("NVML_ERROR_", ""), "_").replace("_", "")
err_val = getattr(this_module, err_name)
def gen_new(val):
def new(typ):
obj = NVMLError.__new__(typ, val)
return obj
return new
new_error_class = type(class_name, (NVMLError,), {'__new__': gen_new(err_val)})
new_error_class.__module__ = __name__
setattr(this_module, class_name, new_error_class)
NVMLError._valClassMapping[err_val] = new_error_class | [
"def",
"_extractNVMLErrorsAsClasses",
"(",
")",
":",
"this_module",
"=",
"sys",
".",
"modules",
"[",
"__name__",
"]",
"nvmlErrorsNames",
"=",
"[",
"x",
"for",
"x",
"in",
"dir",
"(",
"this_module",
")",
"if",
"x",
".",
"startswith",
"(",
"\"NVML_ERROR_\"",
")",
"]",
"for",
"err_name",
"in",
"nvmlErrorsNames",
":",
"# e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyInitialized",
"class_name",
"=",
"\"NVMLError_\"",
"+",
"string",
".",
"capwords",
"(",
"err_name",
".",
"replace",
"(",
"\"NVML_ERROR_\"",
",",
"\"\"",
")",
",",
"\"_\"",
")",
".",
"replace",
"(",
"\"_\"",
",",
"\"\"",
")",
"err_val",
"=",
"getattr",
"(",
"this_module",
",",
"err_name",
")",
"def",
"gen_new",
"(",
"val",
")",
":",
"def",
"new",
"(",
"typ",
")",
":",
"obj",
"=",
"NVMLError",
".",
"__new__",
"(",
"typ",
",",
"val",
")",
"return",
"obj",
"return",
"new",
"new_error_class",
"=",
"type",
"(",
"class_name",
",",
"(",
"NVMLError",
",",
")",
",",
"{",
"'__new__'",
":",
"gen_new",
"(",
"err_val",
")",
"}",
")",
"new_error_class",
".",
"__module__",
"=",
"__name__",
"setattr",
"(",
"this_module",
",",
"class_name",
",",
"new_error_class",
")",
"NVMLError",
".",
"_valClassMapping",
"[",
"err_val",
"]",
"=",
"new_error_class"
] | Generates a hierarchy of classes on top of NVMLError class.
Each NVML Error gets a new NVMLError subclass. This way try,except blocks
can filter appropriate exceptions more easily.
NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass. e.g.
NVML_ERROR_ALREADY_INITIALIZED will be turned into
NVMLError_AlreadyInitialized | [
"Generates",
"a",
"hierarchy",
"of",
"classes",
"on",
"top",
"of",
"NVMLError",
"class",
"."
] | 47f0f2c0eee56dec4e4beebec26b734e01d357b7 | https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L686-L711 | train |
fbcotter/py3nvml | py3nvml/py3nvml.py | _LoadNvmlLibrary | def _LoadNvmlLibrary():
"""
Load the library if it isn't loaded already
"""
global nvmlLib
if (nvmlLib is None):
# lock to ensure only one caller loads the library
libLoadLock.acquire()
try:
# ensure the library still isn't loaded
if (nvmlLib is None):
try:
if (sys.platform[:3] == "win"):
searchPaths = [
os.path.join(os.getenv("ProgramFiles", r"C:\Program Files"), r"NVIDIA Corporation\NVSMI\nvml.dll"),
os.path.join(os.getenv("WinDir", r"C:\Windows"), r"System32\nvml.dll"),
]
nvmlPath = next((x for x in searchPaths if os.path.isfile(x)), None)
if (nvmlPath == None):
_nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
else:
# cdecl calling convention
nvmlLib = CDLL(nvmlPath)
else:
# assume linux
nvmlLib = CDLL("libnvidia-ml.so.1")
except OSError as ose:
_nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
if (nvmlLib == None):
_nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
finally:
# lock is always freed
libLoadLock.release() | python | def _LoadNvmlLibrary():
"""
Load the library if it isn't loaded already
"""
global nvmlLib
if (nvmlLib is None):
# lock to ensure only one caller loads the library
libLoadLock.acquire()
try:
# ensure the library still isn't loaded
if (nvmlLib is None):
try:
if (sys.platform[:3] == "win"):
searchPaths = [
os.path.join(os.getenv("ProgramFiles", r"C:\Program Files"), r"NVIDIA Corporation\NVSMI\nvml.dll"),
os.path.join(os.getenv("WinDir", r"C:\Windows"), r"System32\nvml.dll"),
]
nvmlPath = next((x for x in searchPaths if os.path.isfile(x)), None)
if (nvmlPath == None):
_nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
else:
# cdecl calling convention
nvmlLib = CDLL(nvmlPath)
else:
# assume linux
nvmlLib = CDLL("libnvidia-ml.so.1")
except OSError as ose:
_nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
if (nvmlLib == None):
_nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
finally:
# lock is always freed
libLoadLock.release() | [
"def",
"_LoadNvmlLibrary",
"(",
")",
":",
"global",
"nvmlLib",
"if",
"(",
"nvmlLib",
"is",
"None",
")",
":",
"# lock to ensure only one caller loads the library",
"libLoadLock",
".",
"acquire",
"(",
")",
"try",
":",
"# ensure the library still isn't loaded",
"if",
"(",
"nvmlLib",
"is",
"None",
")",
":",
"try",
":",
"if",
"(",
"sys",
".",
"platform",
"[",
":",
"3",
"]",
"==",
"\"win\"",
")",
":",
"searchPaths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getenv",
"(",
"\"ProgramFiles\"",
",",
"r\"C:\\Program Files\"",
")",
",",
"r\"NVIDIA Corporation\\NVSMI\\nvml.dll\"",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getenv",
"(",
"\"WinDir\"",
",",
"r\"C:\\Windows\"",
")",
",",
"r\"System32\\nvml.dll\"",
")",
",",
"]",
"nvmlPath",
"=",
"next",
"(",
"(",
"x",
"for",
"x",
"in",
"searchPaths",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"x",
")",
")",
",",
"None",
")",
"if",
"(",
"nvmlPath",
"==",
"None",
")",
":",
"_nvmlCheckReturn",
"(",
"NVML_ERROR_LIBRARY_NOT_FOUND",
")",
"else",
":",
"# cdecl calling convention",
"nvmlLib",
"=",
"CDLL",
"(",
"nvmlPath",
")",
"else",
":",
"# assume linux",
"nvmlLib",
"=",
"CDLL",
"(",
"\"libnvidia-ml.so.1\"",
")",
"except",
"OSError",
"as",
"ose",
":",
"_nvmlCheckReturn",
"(",
"NVML_ERROR_LIBRARY_NOT_FOUND",
")",
"if",
"(",
"nvmlLib",
"==",
"None",
")",
":",
"_nvmlCheckReturn",
"(",
"NVML_ERROR_LIBRARY_NOT_FOUND",
")",
"finally",
":",
"# lock is always freed",
"libLoadLock",
".",
"release",
"(",
")"
] | Load the library if it isn't loaded already | [
"Load",
"the",
"library",
"if",
"it",
"isn",
"t",
"loaded",
"already"
] | 47f0f2c0eee56dec4e4beebec26b734e01d357b7 | https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L1104-L1138 | train |
samuraisam/pyapns | pyapns/server.py | encode_notifications | def encode_notifications(tokens, notifications):
""" Returns the encoded bytes of tokens and notifications
tokens a list of tokens or a string of only one token
notifications a list of notifications or a dictionary of only one
"""
fmt = "!BH32sH%ds"
structify = lambda t, p: struct.pack(fmt % len(p), 0, 32, t, len(p), p)
binaryify = lambda t: t.decode('hex')
if type(notifications) is dict and type(tokens) in (str, unicode):
tokens, notifications = ([tokens], [notifications])
if type(notifications) is list and type(tokens) is list:
return ''.join(map(lambda y: structify(*y), ((binaryify(t), json.dumps(p, separators=(',',':'), ensure_ascii=False).encode('utf-8'))
for t, p in zip(tokens, notifications)))) | python | def encode_notifications(tokens, notifications):
""" Returns the encoded bytes of tokens and notifications
tokens a list of tokens or a string of only one token
notifications a list of notifications or a dictionary of only one
"""
fmt = "!BH32sH%ds"
structify = lambda t, p: struct.pack(fmt % len(p), 0, 32, t, len(p), p)
binaryify = lambda t: t.decode('hex')
if type(notifications) is dict and type(tokens) in (str, unicode):
tokens, notifications = ([tokens], [notifications])
if type(notifications) is list and type(tokens) is list:
return ''.join(map(lambda y: structify(*y), ((binaryify(t), json.dumps(p, separators=(',',':'), ensure_ascii=False).encode('utf-8'))
for t, p in zip(tokens, notifications)))) | [
"def",
"encode_notifications",
"(",
"tokens",
",",
"notifications",
")",
":",
"fmt",
"=",
"\"!BH32sH%ds\"",
"structify",
"=",
"lambda",
"t",
",",
"p",
":",
"struct",
".",
"pack",
"(",
"fmt",
"%",
"len",
"(",
"p",
")",
",",
"0",
",",
"32",
",",
"t",
",",
"len",
"(",
"p",
")",
",",
"p",
")",
"binaryify",
"=",
"lambda",
"t",
":",
"t",
".",
"decode",
"(",
"'hex'",
")",
"if",
"type",
"(",
"notifications",
")",
"is",
"dict",
"and",
"type",
"(",
"tokens",
")",
"in",
"(",
"str",
",",
"unicode",
")",
":",
"tokens",
",",
"notifications",
"=",
"(",
"[",
"tokens",
"]",
",",
"[",
"notifications",
"]",
")",
"if",
"type",
"(",
"notifications",
")",
"is",
"list",
"and",
"type",
"(",
"tokens",
")",
"is",
"list",
":",
"return",
"''",
".",
"join",
"(",
"map",
"(",
"lambda",
"y",
":",
"structify",
"(",
"*",
"y",
")",
",",
"(",
"(",
"binaryify",
"(",
"t",
")",
",",
"json",
".",
"dumps",
"(",
"p",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
",",
"ensure_ascii",
"=",
"False",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"for",
"t",
",",
"p",
"in",
"zip",
"(",
"tokens",
",",
"notifications",
")",
")",
")",
")"
] | Returns the encoded bytes of tokens and notifications
tokens a list of tokens or a string of only one token
notifications a list of notifications or a dictionary of only one | [
"Returns",
"the",
"encoded",
"bytes",
"of",
"tokens",
"and",
"notifications",
"tokens",
"a",
"list",
"of",
"tokens",
"or",
"a",
"string",
"of",
"only",
"one",
"token",
"notifications",
"a",
"list",
"of",
"notifications",
"or",
"a",
"dictionary",
"of",
"only",
"one"
] | 78c1875f28f8af51c7dd7f60d4436a8b282b0394 | https://github.com/samuraisam/pyapns/blob/78c1875f28f8af51c7dd7f60d4436a8b282b0394/pyapns/server.py#L317-L331 | train |
samuraisam/pyapns | pyapns/server.py | APNSService.write | def write(self, notifications):
"Connect to the APNS service and send notifications"
if not self.factory:
log.msg('APNSService write (connecting)')
server, port = ((APNS_SERVER_SANDBOX_HOSTNAME
if self.environment == 'sandbox'
else APNS_SERVER_HOSTNAME), APNS_SERVER_PORT)
self.factory = self.clientProtocolFactory()
context = self.getContextFactory()
reactor.connectSSL(server, port, self.factory, context)
client = self.factory.clientProtocol
if client:
return client.sendMessage(notifications)
else:
d = self.factory.deferred
timeout = reactor.callLater(self.timeout,
lambda: d.called or d.errback(
Exception('Notification timed out after %i seconds' % self.timeout)))
def cancel_timeout(r):
try: timeout.cancel()
except: pass
return r
d.addCallback(lambda p: p.sendMessage(notifications))
d.addErrback(log_errback('apns-service-write'))
d.addBoth(cancel_timeout)
return d | python | def write(self, notifications):
"Connect to the APNS service and send notifications"
if not self.factory:
log.msg('APNSService write (connecting)')
server, port = ((APNS_SERVER_SANDBOX_HOSTNAME
if self.environment == 'sandbox'
else APNS_SERVER_HOSTNAME), APNS_SERVER_PORT)
self.factory = self.clientProtocolFactory()
context = self.getContextFactory()
reactor.connectSSL(server, port, self.factory, context)
client = self.factory.clientProtocol
if client:
return client.sendMessage(notifications)
else:
d = self.factory.deferred
timeout = reactor.callLater(self.timeout,
lambda: d.called or d.errback(
Exception('Notification timed out after %i seconds' % self.timeout)))
def cancel_timeout(r):
try: timeout.cancel()
except: pass
return r
d.addCallback(lambda p: p.sendMessage(notifications))
d.addErrback(log_errback('apns-service-write'))
d.addBoth(cancel_timeout)
return d | [
"def",
"write",
"(",
"self",
",",
"notifications",
")",
":",
"if",
"not",
"self",
".",
"factory",
":",
"log",
".",
"msg",
"(",
"'APNSService write (connecting)'",
")",
"server",
",",
"port",
"=",
"(",
"(",
"APNS_SERVER_SANDBOX_HOSTNAME",
"if",
"self",
".",
"environment",
"==",
"'sandbox'",
"else",
"APNS_SERVER_HOSTNAME",
")",
",",
"APNS_SERVER_PORT",
")",
"self",
".",
"factory",
"=",
"self",
".",
"clientProtocolFactory",
"(",
")",
"context",
"=",
"self",
".",
"getContextFactory",
"(",
")",
"reactor",
".",
"connectSSL",
"(",
"server",
",",
"port",
",",
"self",
".",
"factory",
",",
"context",
")",
"client",
"=",
"self",
".",
"factory",
".",
"clientProtocol",
"if",
"client",
":",
"return",
"client",
".",
"sendMessage",
"(",
"notifications",
")",
"else",
":",
"d",
"=",
"self",
".",
"factory",
".",
"deferred",
"timeout",
"=",
"reactor",
".",
"callLater",
"(",
"self",
".",
"timeout",
",",
"lambda",
":",
"d",
".",
"called",
"or",
"d",
".",
"errback",
"(",
"Exception",
"(",
"'Notification timed out after %i seconds'",
"%",
"self",
".",
"timeout",
")",
")",
")",
"def",
"cancel_timeout",
"(",
"r",
")",
":",
"try",
":",
"timeout",
".",
"cancel",
"(",
")",
"except",
":",
"pass",
"return",
"r",
"d",
".",
"addCallback",
"(",
"lambda",
"p",
":",
"p",
".",
"sendMessage",
"(",
"notifications",
")",
")",
"d",
".",
"addErrback",
"(",
"log_errback",
"(",
"'apns-service-write'",
")",
")",
"d",
".",
"addBoth",
"(",
"cancel_timeout",
")",
"return",
"d"
] | Connect to the APNS service and send notifications | [
"Connect",
"to",
"the",
"APNS",
"service",
"and",
"send",
"notifications"
] | 78c1875f28f8af51c7dd7f60d4436a8b282b0394 | https://github.com/samuraisam/pyapns/blob/78c1875f28f8af51c7dd7f60d4436a8b282b0394/pyapns/server.py#L186-L213 | train |
samuraisam/pyapns | pyapns/server.py | APNSService.read | def read(self):
"Connect to the feedback service and read all data."
log.msg('APNSService read (connecting)')
try:
server, port = ((FEEDBACK_SERVER_SANDBOX_HOSTNAME
if self.environment == 'sandbox'
else FEEDBACK_SERVER_HOSTNAME), FEEDBACK_SERVER_PORT)
factory = self.feedbackProtocolFactory()
context = self.getContextFactory()
reactor.connectSSL(server, port, factory, context)
factory.deferred.addErrback(log_errback('apns-feedback-read'))
timeout = reactor.callLater(self.timeout,
lambda: factory.deferred.called or factory.deferred.errback(
Exception('Feedbcak fetch timed out after %i seconds' % self.timeout)))
def cancel_timeout(r):
try: timeout.cancel()
except: pass
return r
factory.deferred.addBoth(cancel_timeout)
except Exception, e:
log.err('APNService feedback error initializing: %s' % str(e))
raise
return factory.deferred | python | def read(self):
"Connect to the feedback service and read all data."
log.msg('APNSService read (connecting)')
try:
server, port = ((FEEDBACK_SERVER_SANDBOX_HOSTNAME
if self.environment == 'sandbox'
else FEEDBACK_SERVER_HOSTNAME), FEEDBACK_SERVER_PORT)
factory = self.feedbackProtocolFactory()
context = self.getContextFactory()
reactor.connectSSL(server, port, factory, context)
factory.deferred.addErrback(log_errback('apns-feedback-read'))
timeout = reactor.callLater(self.timeout,
lambda: factory.deferred.called or factory.deferred.errback(
Exception('Feedbcak fetch timed out after %i seconds' % self.timeout)))
def cancel_timeout(r):
try: timeout.cancel()
except: pass
return r
factory.deferred.addBoth(cancel_timeout)
except Exception, e:
log.err('APNService feedback error initializing: %s' % str(e))
raise
return factory.deferred | [
"def",
"read",
"(",
"self",
")",
":",
"log",
".",
"msg",
"(",
"'APNSService read (connecting)'",
")",
"try",
":",
"server",
",",
"port",
"=",
"(",
"(",
"FEEDBACK_SERVER_SANDBOX_HOSTNAME",
"if",
"self",
".",
"environment",
"==",
"'sandbox'",
"else",
"FEEDBACK_SERVER_HOSTNAME",
")",
",",
"FEEDBACK_SERVER_PORT",
")",
"factory",
"=",
"self",
".",
"feedbackProtocolFactory",
"(",
")",
"context",
"=",
"self",
".",
"getContextFactory",
"(",
")",
"reactor",
".",
"connectSSL",
"(",
"server",
",",
"port",
",",
"factory",
",",
"context",
")",
"factory",
".",
"deferred",
".",
"addErrback",
"(",
"log_errback",
"(",
"'apns-feedback-read'",
")",
")",
"timeout",
"=",
"reactor",
".",
"callLater",
"(",
"self",
".",
"timeout",
",",
"lambda",
":",
"factory",
".",
"deferred",
".",
"called",
"or",
"factory",
".",
"deferred",
".",
"errback",
"(",
"Exception",
"(",
"'Feedbcak fetch timed out after %i seconds'",
"%",
"self",
".",
"timeout",
")",
")",
")",
"def",
"cancel_timeout",
"(",
"r",
")",
":",
"try",
":",
"timeout",
".",
"cancel",
"(",
")",
"except",
":",
"pass",
"return",
"r",
"factory",
".",
"deferred",
".",
"addBoth",
"(",
"cancel_timeout",
")",
"except",
"Exception",
",",
"e",
":",
"log",
".",
"err",
"(",
"'APNService feedback error initializing: %s'",
"%",
"str",
"(",
"e",
")",
")",
"raise",
"return",
"factory",
".",
"deferred"
] | Connect to the feedback service and read all data. | [
"Connect",
"to",
"the",
"feedback",
"service",
"and",
"read",
"all",
"data",
"."
] | 78c1875f28f8af51c7dd7f60d4436a8b282b0394 | https://github.com/samuraisam/pyapns/blob/78c1875f28f8af51c7dd7f60d4436a8b282b0394/pyapns/server.py#L215-L239 | train |
samuraisam/pyapns | pyapns/client.py | reprovision_and_retry | def reprovision_and_retry(func):
"""
Wraps the `errback` callback of the API functions, automatically trying to
re-provision if the app ID can not be found during the operation. If that's
unsuccessful, it will raise the UnknownAppID error.
"""
@functools.wraps(func)
def wrapper(*a, **kw):
errback = kw.get('errback', None)
if errback is None:
def errback(e):
raise e
def errback_wrapper(e):
if isinstance(e, UnknownAppID) and 'INITIAL' in OPTIONS:
try:
for initial in OPTIONS['INITIAL']:
provision(*initial) # retry provisioning the initial setup
func(*a, **kw) # and try the function once more
except Exception, new_exc:
errback(new_exc) # throwing the new exception
else:
errback(e) # not an instance of UnknownAppID - nothing we can do here
kw['errback'] = errback_wrapper
return func(*a, **kw)
return wrapper | python | def reprovision_and_retry(func):
"""
Wraps the `errback` callback of the API functions, automatically trying to
re-provision if the app ID can not be found during the operation. If that's
unsuccessful, it will raise the UnknownAppID error.
"""
@functools.wraps(func)
def wrapper(*a, **kw):
errback = kw.get('errback', None)
if errback is None:
def errback(e):
raise e
def errback_wrapper(e):
if isinstance(e, UnknownAppID) and 'INITIAL' in OPTIONS:
try:
for initial in OPTIONS['INITIAL']:
provision(*initial) # retry provisioning the initial setup
func(*a, **kw) # and try the function once more
except Exception, new_exc:
errback(new_exc) # throwing the new exception
else:
errback(e) # not an instance of UnknownAppID - nothing we can do here
kw['errback'] = errback_wrapper
return func(*a, **kw)
return wrapper | [
"def",
"reprovision_and_retry",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"errback",
"=",
"kw",
".",
"get",
"(",
"'errback'",
",",
"None",
")",
"if",
"errback",
"is",
"None",
":",
"def",
"errback",
"(",
"e",
")",
":",
"raise",
"e",
"def",
"errback_wrapper",
"(",
"e",
")",
":",
"if",
"isinstance",
"(",
"e",
",",
"UnknownAppID",
")",
"and",
"'INITIAL'",
"in",
"OPTIONS",
":",
"try",
":",
"for",
"initial",
"in",
"OPTIONS",
"[",
"'INITIAL'",
"]",
":",
"provision",
"(",
"*",
"initial",
")",
"# retry provisioning the initial setup",
"func",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
"# and try the function once more",
"except",
"Exception",
",",
"new_exc",
":",
"errback",
"(",
"new_exc",
")",
"# throwing the new exception",
"else",
":",
"errback",
"(",
"e",
")",
"# not an instance of UnknownAppID - nothing we can do here",
"kw",
"[",
"'errback'",
"]",
"=",
"errback_wrapper",
"return",
"func",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
"return",
"wrapper"
] | Wraps the `errback` callback of the API functions, automatically trying to
re-provision if the app ID can not be found during the operation. If that's
unsuccessful, it will raise the UnknownAppID error. | [
"Wraps",
"the",
"errback",
"callback",
"of",
"the",
"API",
"functions",
"automatically",
"trying",
"to",
"re",
"-",
"provision",
"if",
"the",
"app",
"ID",
"can",
"not",
"be",
"found",
"during",
"the",
"operation",
".",
"If",
"that",
"s",
"unsuccessful",
"it",
"will",
"raise",
"the",
"UnknownAppID",
"error",
"."
] | 78c1875f28f8af51c7dd7f60d4436a8b282b0394 | https://github.com/samuraisam/pyapns/blob/78c1875f28f8af51c7dd7f60d4436a8b282b0394/pyapns/client.py#L44-L68 | train |
timothycrosley/jiphy | jiphy/parser.py | Parser.pop | def pop(self):
"""removes the current character then moves to the next one, returning the current character"""
char = self.code[self.index]
self.index += 1
return char | python | def pop(self):
"""removes the current character then moves to the next one, returning the current character"""
char = self.code[self.index]
self.index += 1
return char | [
"def",
"pop",
"(",
"self",
")",
":",
"char",
"=",
"self",
".",
"code",
"[",
"self",
".",
"index",
"]",
"self",
".",
"index",
"+=",
"1",
"return",
"char"
] | removes the current character then moves to the next one, returning the current character | [
"removes",
"the",
"current",
"character",
"then",
"moves",
"to",
"the",
"next",
"one",
"returning",
"the",
"current",
"character"
] | 6e09be9c3496ca40901df70fc9b14d2ca3ec2e04 | https://github.com/timothycrosley/jiphy/blob/6e09be9c3496ca40901df70fc9b14d2ca3ec2e04/jiphy/parser.py#L83-L87 | train |
timothycrosley/jiphy | jiphy/parser.py | Parser.characters | def characters(self, numberOfCharacters):
"""Returns characters at index + number of characters"""
return self.code[self.index:self.index + numberOfCharacters] | python | def characters(self, numberOfCharacters):
"""Returns characters at index + number of characters"""
return self.code[self.index:self.index + numberOfCharacters] | [
"def",
"characters",
"(",
"self",
",",
"numberOfCharacters",
")",
":",
"return",
"self",
".",
"code",
"[",
"self",
".",
"index",
":",
"self",
".",
"index",
"+",
"numberOfCharacters",
"]"
] | Returns characters at index + number of characters | [
"Returns",
"characters",
"at",
"index",
"+",
"number",
"of",
"characters"
] | 6e09be9c3496ca40901df70fc9b14d2ca3ec2e04 | https://github.com/timothycrosley/jiphy/blob/6e09be9c3496ca40901df70fc9b14d2ca3ec2e04/jiphy/parser.py#L89-L91 | train |
timothycrosley/jiphy | jiphy/parser.py | Parser.next_content | def next_content(self, start, amount=1):
"""Returns the next non-whitespace characters"""
while start < len(self.code) and self.code[start] in (' ', '\t', '\n'):
start += 1
return self.code[start: start + amount] | python | def next_content(self, start, amount=1):
"""Returns the next non-whitespace characters"""
while start < len(self.code) and self.code[start] in (' ', '\t', '\n'):
start += 1
return self.code[start: start + amount] | [
"def",
"next_content",
"(",
"self",
",",
"start",
",",
"amount",
"=",
"1",
")",
":",
"while",
"start",
"<",
"len",
"(",
"self",
".",
"code",
")",
"and",
"self",
".",
"code",
"[",
"start",
"]",
"in",
"(",
"' '",
",",
"'\\t'",
",",
"'\\n'",
")",
":",
"start",
"+=",
"1",
"return",
"self",
".",
"code",
"[",
"start",
":",
"start",
"+",
"amount",
"]"
] | Returns the next non-whitespace characters | [
"Returns",
"the",
"next",
"non",
"-",
"whitespace",
"characters"
] | 6e09be9c3496ca40901df70fc9b14d2ca3ec2e04 | https://github.com/timothycrosley/jiphy/blob/6e09be9c3496ca40901df70fc9b14d2ca3ec2e04/jiphy/parser.py#L117-L122 | train |
timothycrosley/jiphy | jiphy/parser.py | Parser.prev_content | def prev_content(self, start, amount=1):
"""Returns the prev non-whitespace characters"""
while start > 0 and self.code[start] in (' ', '\t', '\n'):
start -= 1
return self.code[(start or amount) - amount: start] | python | def prev_content(self, start, amount=1):
"""Returns the prev non-whitespace characters"""
while start > 0 and self.code[start] in (' ', '\t', '\n'):
start -= 1
return self.code[(start or amount) - amount: start] | [
"def",
"prev_content",
"(",
"self",
",",
"start",
",",
"amount",
"=",
"1",
")",
":",
"while",
"start",
">",
"0",
"and",
"self",
".",
"code",
"[",
"start",
"]",
"in",
"(",
"' '",
",",
"'\\t'",
",",
"'\\n'",
")",
":",
"start",
"-=",
"1",
"return",
"self",
".",
"code",
"[",
"(",
"start",
"or",
"amount",
")",
"-",
"amount",
":",
"start",
"]"
] | Returns the prev non-whitespace characters | [
"Returns",
"the",
"prev",
"non",
"-",
"whitespace",
"characters"
] | 6e09be9c3496ca40901df70fc9b14d2ca3ec2e04 | https://github.com/timothycrosley/jiphy/blob/6e09be9c3496ca40901df70fc9b14d2ca3ec2e04/jiphy/parser.py#L124-L129 | train |
languitar/pass-git-helper | passgithelper.py | parse_mapping | def parse_mapping(mapping_file: Optional[str]) -> configparser.ConfigParser:
"""
Parse the file containing the mappings from hosts to pass entries.
Args:
mapping_file:
Name of the file to parse. If ``None``, the default file from the
XDG location is used.
"""
LOGGER.debug('Parsing mapping file. Command line: %s', mapping_file)
def parse(mapping_file):
config = configparser.ConfigParser()
config.read_file(mapping_file)
return config
# give precedence to the user-specified file
if mapping_file is not None:
LOGGER.debug('Parsing command line mapping file')
return parse(mapping_file)
# fall back on XDG config location
xdg_config_dir = xdg.BaseDirectory.load_first_config('pass-git-helper')
if xdg_config_dir is None:
raise RuntimeError(
'No mapping configured so far at any XDG config location. '
'Please create {config_file}'.format(
config_file=DEFAULT_CONFIG_FILE))
mapping_file = os.path.join(xdg_config_dir, CONFIG_FILE_NAME)
LOGGER.debug('Parsing mapping file %s', mapping_file)
with open(mapping_file, 'r') as file_handle:
return parse(file_handle) | python | def parse_mapping(mapping_file: Optional[str]) -> configparser.ConfigParser:
"""
Parse the file containing the mappings from hosts to pass entries.
Args:
mapping_file:
Name of the file to parse. If ``None``, the default file from the
XDG location is used.
"""
LOGGER.debug('Parsing mapping file. Command line: %s', mapping_file)
def parse(mapping_file):
config = configparser.ConfigParser()
config.read_file(mapping_file)
return config
# give precedence to the user-specified file
if mapping_file is not None:
LOGGER.debug('Parsing command line mapping file')
return parse(mapping_file)
# fall back on XDG config location
xdg_config_dir = xdg.BaseDirectory.load_first_config('pass-git-helper')
if xdg_config_dir is None:
raise RuntimeError(
'No mapping configured so far at any XDG config location. '
'Please create {config_file}'.format(
config_file=DEFAULT_CONFIG_FILE))
mapping_file = os.path.join(xdg_config_dir, CONFIG_FILE_NAME)
LOGGER.debug('Parsing mapping file %s', mapping_file)
with open(mapping_file, 'r') as file_handle:
return parse(file_handle) | [
"def",
"parse_mapping",
"(",
"mapping_file",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"configparser",
".",
"ConfigParser",
":",
"LOGGER",
".",
"debug",
"(",
"'Parsing mapping file. Command line: %s'",
",",
"mapping_file",
")",
"def",
"parse",
"(",
"mapping_file",
")",
":",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read_file",
"(",
"mapping_file",
")",
"return",
"config",
"# give precedence to the user-specified file",
"if",
"mapping_file",
"is",
"not",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'Parsing command line mapping file'",
")",
"return",
"parse",
"(",
"mapping_file",
")",
"# fall back on XDG config location",
"xdg_config_dir",
"=",
"xdg",
".",
"BaseDirectory",
".",
"load_first_config",
"(",
"'pass-git-helper'",
")",
"if",
"xdg_config_dir",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'No mapping configured so far at any XDG config location. '",
"'Please create {config_file}'",
".",
"format",
"(",
"config_file",
"=",
"DEFAULT_CONFIG_FILE",
")",
")",
"mapping_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"xdg_config_dir",
",",
"CONFIG_FILE_NAME",
")",
"LOGGER",
".",
"debug",
"(",
"'Parsing mapping file %s'",
",",
"mapping_file",
")",
"with",
"open",
"(",
"mapping_file",
",",
"'r'",
")",
"as",
"file_handle",
":",
"return",
"parse",
"(",
"file_handle",
")"
] | Parse the file containing the mappings from hosts to pass entries.
Args:
mapping_file:
Name of the file to parse. If ``None``, the default file from the
XDG location is used. | [
"Parse",
"the",
"file",
"containing",
"the",
"mappings",
"from",
"hosts",
"to",
"pass",
"entries",
"."
] | f84376d9ed6f7c47454a499da103da6fc2575a25 | https://github.com/languitar/pass-git-helper/blob/f84376d9ed6f7c47454a499da103da6fc2575a25/passgithelper.py#L73-L104 | train |
languitar/pass-git-helper | passgithelper.py | parse_request | def parse_request() -> Dict[str, str]:
"""
Parse the request of the git credential API from stdin.
Returns:
A dictionary with all key-value pairs of the request
"""
in_lines = sys.stdin.readlines()
LOGGER.debug('Received request "%s"', in_lines)
request = {}
for line in in_lines:
# skip empty lines to be a bit resilient against protocol errors
if not line.strip():
continue
parts = line.split('=', 1)
assert len(parts) == 2
request[parts[0].strip()] = parts[1].strip()
return request | python | def parse_request() -> Dict[str, str]:
"""
Parse the request of the git credential API from stdin.
Returns:
A dictionary with all key-value pairs of the request
"""
in_lines = sys.stdin.readlines()
LOGGER.debug('Received request "%s"', in_lines)
request = {}
for line in in_lines:
# skip empty lines to be a bit resilient against protocol errors
if not line.strip():
continue
parts = line.split('=', 1)
assert len(parts) == 2
request[parts[0].strip()] = parts[1].strip()
return request | [
"def",
"parse_request",
"(",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"in_lines",
"=",
"sys",
".",
"stdin",
".",
"readlines",
"(",
")",
"LOGGER",
".",
"debug",
"(",
"'Received request \"%s\"'",
",",
"in_lines",
")",
"request",
"=",
"{",
"}",
"for",
"line",
"in",
"in_lines",
":",
"# skip empty lines to be a bit resilient against protocol errors",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"continue",
"parts",
"=",
"line",
".",
"split",
"(",
"'='",
",",
"1",
")",
"assert",
"len",
"(",
"parts",
")",
"==",
"2",
"request",
"[",
"parts",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"]",
"=",
"parts",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"return",
"request"
] | Parse the request of the git credential API from stdin.
Returns:
A dictionary with all key-value pairs of the request | [
"Parse",
"the",
"request",
"of",
"the",
"git",
"credential",
"API",
"from",
"stdin",
"."
] | f84376d9ed6f7c47454a499da103da6fc2575a25 | https://github.com/languitar/pass-git-helper/blob/f84376d9ed6f7c47454a499da103da6fc2575a25/passgithelper.py#L107-L127 | train |
languitar/pass-git-helper | passgithelper.py | get_password | def get_password(request, mapping) -> None:
"""
Resolve the given credential request in the provided mapping definition.
The result is printed automatically.
Args:
request:
The credential request specified as a dict of key-value pairs.
mapping:
The mapping configuration as a ConfigParser instance.
"""
LOGGER.debug('Received request "%s"', request)
if 'host' not in request:
LOGGER.error('host= entry missing in request. '
'Cannot query without a host')
return
host = request['host']
if 'path' in request:
host = '/'.join([host, request['path']])
def skip(line, skip):
return line[skip:]
LOGGER.debug('Iterating mapping to match against host "%s"', host)
for section in mapping.sections():
if fnmatch.fnmatch(host, section):
LOGGER.debug('Section "%s" matches requested host "%s"',
section, host)
# TODO handle exceptions
pass_target = mapping.get(section, 'target').replace(
"${host}", request['host'])
password_extractor = SpecificLineExtractor(
0, 0, option_suffix='_password')
password_extractor.configure(mapping[section])
# username_extractor = SpecificLineExtractor(
# 1, 0, option_suffix='_username')
username_extractor = _username_extractors[mapping[section].get(
'username_extractor', fallback=_line_extractor_name)]
username_extractor.configure(mapping[section])
LOGGER.debug('Requesting entry "%s" from pass', pass_target)
output = subprocess.check_output(
['pass', 'show', pass_target]).decode('utf-8')
lines = output.splitlines()
password = password_extractor.get_value(pass_target, lines)
username = username_extractor.get_value(pass_target, lines)
if password:
print('password={password}'.format( # noqa: T001
password=password))
if 'username' not in request and username:
print('username={username}'.format( # noqa: T001
username=username))
return
LOGGER.warning('No mapping matched')
sys.exit(1) | python | def get_password(request, mapping) -> None:
"""
Resolve the given credential request in the provided mapping definition.
The result is printed automatically.
Args:
request:
The credential request specified as a dict of key-value pairs.
mapping:
The mapping configuration as a ConfigParser instance.
"""
LOGGER.debug('Received request "%s"', request)
if 'host' not in request:
LOGGER.error('host= entry missing in request. '
'Cannot query without a host')
return
host = request['host']
if 'path' in request:
host = '/'.join([host, request['path']])
def skip(line, skip):
return line[skip:]
LOGGER.debug('Iterating mapping to match against host "%s"', host)
for section in mapping.sections():
if fnmatch.fnmatch(host, section):
LOGGER.debug('Section "%s" matches requested host "%s"',
section, host)
# TODO handle exceptions
pass_target = mapping.get(section, 'target').replace(
"${host}", request['host'])
password_extractor = SpecificLineExtractor(
0, 0, option_suffix='_password')
password_extractor.configure(mapping[section])
# username_extractor = SpecificLineExtractor(
# 1, 0, option_suffix='_username')
username_extractor = _username_extractors[mapping[section].get(
'username_extractor', fallback=_line_extractor_name)]
username_extractor.configure(mapping[section])
LOGGER.debug('Requesting entry "%s" from pass', pass_target)
output = subprocess.check_output(
['pass', 'show', pass_target]).decode('utf-8')
lines = output.splitlines()
password = password_extractor.get_value(pass_target, lines)
username = username_extractor.get_value(pass_target, lines)
if password:
print('password={password}'.format( # noqa: T001
password=password))
if 'username' not in request and username:
print('username={username}'.format( # noqa: T001
username=username))
return
LOGGER.warning('No mapping matched')
sys.exit(1) | [
"def",
"get_password",
"(",
"request",
",",
"mapping",
")",
"->",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'Received request \"%s\"'",
",",
"request",
")",
"if",
"'host'",
"not",
"in",
"request",
":",
"LOGGER",
".",
"error",
"(",
"'host= entry missing in request. '",
"'Cannot query without a host'",
")",
"return",
"host",
"=",
"request",
"[",
"'host'",
"]",
"if",
"'path'",
"in",
"request",
":",
"host",
"=",
"'/'",
".",
"join",
"(",
"[",
"host",
",",
"request",
"[",
"'path'",
"]",
"]",
")",
"def",
"skip",
"(",
"line",
",",
"skip",
")",
":",
"return",
"line",
"[",
"skip",
":",
"]",
"LOGGER",
".",
"debug",
"(",
"'Iterating mapping to match against host \"%s\"'",
",",
"host",
")",
"for",
"section",
"in",
"mapping",
".",
"sections",
"(",
")",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"host",
",",
"section",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Section \"%s\" matches requested host \"%s\"'",
",",
"section",
",",
"host",
")",
"# TODO handle exceptions",
"pass_target",
"=",
"mapping",
".",
"get",
"(",
"section",
",",
"'target'",
")",
".",
"replace",
"(",
"\"${host}\"",
",",
"request",
"[",
"'host'",
"]",
")",
"password_extractor",
"=",
"SpecificLineExtractor",
"(",
"0",
",",
"0",
",",
"option_suffix",
"=",
"'_password'",
")",
"password_extractor",
".",
"configure",
"(",
"mapping",
"[",
"section",
"]",
")",
"# username_extractor = SpecificLineExtractor(",
"# 1, 0, option_suffix='_username')",
"username_extractor",
"=",
"_username_extractors",
"[",
"mapping",
"[",
"section",
"]",
".",
"get",
"(",
"'username_extractor'",
",",
"fallback",
"=",
"_line_extractor_name",
")",
"]",
"username_extractor",
".",
"configure",
"(",
"mapping",
"[",
"section",
"]",
")",
"LOGGER",
".",
"debug",
"(",
"'Requesting entry \"%s\" from pass'",
",",
"pass_target",
")",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'pass'",
",",
"'show'",
",",
"pass_target",
"]",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"lines",
"=",
"output",
".",
"splitlines",
"(",
")",
"password",
"=",
"password_extractor",
".",
"get_value",
"(",
"pass_target",
",",
"lines",
")",
"username",
"=",
"username_extractor",
".",
"get_value",
"(",
"pass_target",
",",
"lines",
")",
"if",
"password",
":",
"print",
"(",
"'password={password}'",
".",
"format",
"(",
"# noqa: T001",
"password",
"=",
"password",
")",
")",
"if",
"'username'",
"not",
"in",
"request",
"and",
"username",
":",
"print",
"(",
"'username={username}'",
".",
"format",
"(",
"# noqa: T001",
"username",
"=",
"username",
")",
")",
"return",
"LOGGER",
".",
"warning",
"(",
"'No mapping matched'",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Resolve the given credential request in the provided mapping definition.
The result is printed automatically.
Args:
request:
The credential request specified as a dict of key-value pairs.
mapping:
The mapping configuration as a ConfigParser instance. | [
"Resolve",
"the",
"given",
"credential",
"request",
"in",
"the",
"provided",
"mapping",
"definition",
"."
] | f84376d9ed6f7c47454a499da103da6fc2575a25 | https://github.com/languitar/pass-git-helper/blob/f84376d9ed6f7c47454a499da103da6fc2575a25/passgithelper.py#L324-L383 | train |
languitar/pass-git-helper | passgithelper.py | main | def main(argv: Optional[Sequence[str]] = None) -> None:
"""
Start the pass-git-helper script.
Args:
argv:
If not ``None``, use the provided command line arguments for
parsing. Otherwise, extract them automatically.
"""
args = parse_arguments(argv=argv)
if args.logging:
logging.basicConfig(level=logging.DEBUG)
handle_skip()
action = args.action
request = parse_request()
LOGGER.debug('Received action %s with request:\n%s',
action, request)
try:
mapping = parse_mapping(args.mapping)
except Exception as error:
LOGGER.critical('Unable to parse mapping file', exc_info=True)
print( # noqa: P101
'Unable to parse mapping file: {error}'.format(
error=error),
file=sys.stderr)
sys.exit(1)
if action == 'get':
get_password(request, mapping)
else:
LOGGER.info('Action %s is currently not supported', action)
sys.exit(1) | python | def main(argv: Optional[Sequence[str]] = None) -> None:
"""
Start the pass-git-helper script.
Args:
argv:
If not ``None``, use the provided command line arguments for
parsing. Otherwise, extract them automatically.
"""
args = parse_arguments(argv=argv)
if args.logging:
logging.basicConfig(level=logging.DEBUG)
handle_skip()
action = args.action
request = parse_request()
LOGGER.debug('Received action %s with request:\n%s',
action, request)
try:
mapping = parse_mapping(args.mapping)
except Exception as error:
LOGGER.critical('Unable to parse mapping file', exc_info=True)
print( # noqa: P101
'Unable to parse mapping file: {error}'.format(
error=error),
file=sys.stderr)
sys.exit(1)
if action == 'get':
get_password(request, mapping)
else:
LOGGER.info('Action %s is currently not supported', action)
sys.exit(1) | [
"def",
"main",
"(",
"argv",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"None",
":",
"args",
"=",
"parse_arguments",
"(",
"argv",
"=",
"argv",
")",
"if",
"args",
".",
"logging",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"handle_skip",
"(",
")",
"action",
"=",
"args",
".",
"action",
"request",
"=",
"parse_request",
"(",
")",
"LOGGER",
".",
"debug",
"(",
"'Received action %s with request:\\n%s'",
",",
"action",
",",
"request",
")",
"try",
":",
"mapping",
"=",
"parse_mapping",
"(",
"args",
".",
"mapping",
")",
"except",
"Exception",
"as",
"error",
":",
"LOGGER",
".",
"critical",
"(",
"'Unable to parse mapping file'",
",",
"exc_info",
"=",
"True",
")",
"print",
"(",
"# noqa: P101",
"'Unable to parse mapping file: {error}'",
".",
"format",
"(",
"error",
"=",
"error",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"action",
"==",
"'get'",
":",
"get_password",
"(",
"request",
",",
"mapping",
")",
"else",
":",
"LOGGER",
".",
"info",
"(",
"'Action %s is currently not supported'",
",",
"action",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Start the pass-git-helper script.
Args:
argv:
If not ``None``, use the provided command line arguments for
parsing. Otherwise, extract them automatically. | [
"Start",
"the",
"pass",
"-",
"git",
"-",
"helper",
"script",
"."
] | f84376d9ed6f7c47454a499da103da6fc2575a25 | https://github.com/languitar/pass-git-helper/blob/f84376d9ed6f7c47454a499da103da6fc2575a25/passgithelper.py#L394-L429 | train |
languitar/pass-git-helper | passgithelper.py | SkippingDataExtractor.configure | def configure(self, config):
"""Configure the amount of characters to skip."""
self._prefix_length = config.getint(
'skip{suffix}'.format(suffix=self._option_suffix),
fallback=self._prefix_length) | python | def configure(self, config):
"""Configure the amount of characters to skip."""
self._prefix_length = config.getint(
'skip{suffix}'.format(suffix=self._option_suffix),
fallback=self._prefix_length) | [
"def",
"configure",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"_prefix_length",
"=",
"config",
".",
"getint",
"(",
"'skip{suffix}'",
".",
"format",
"(",
"suffix",
"=",
"self",
".",
"_option_suffix",
")",
",",
"fallback",
"=",
"self",
".",
"_prefix_length",
")"
] | Configure the amount of characters to skip. | [
"Configure",
"the",
"amount",
"of",
"characters",
"to",
"skip",
"."
] | f84376d9ed6f7c47454a499da103da6fc2575a25 | https://github.com/languitar/pass-git-helper/blob/f84376d9ed6f7c47454a499da103da6fc2575a25/passgithelper.py#L194-L198 | train |
asottile/git-code-debt | git_code_debt/write_logic.py | insert_metric_changes | def insert_metric_changes(db, metrics, metric_mapping, commit):
"""Insert into the metric_changes tables.
:param metrics: `list` of `Metric` objects
:param dict metric_mapping: Maps metric names to ids
:param Commit commit:
"""
values = [
[commit.sha, metric_mapping[metric.name], metric.value]
for metric in metrics
if metric.value != 0
]
db.executemany(
'INSERT INTO metric_changes (sha, metric_id, value) VALUES (?, ?, ?)',
values,
) | python | def insert_metric_changes(db, metrics, metric_mapping, commit):
"""Insert into the metric_changes tables.
:param metrics: `list` of `Metric` objects
:param dict metric_mapping: Maps metric names to ids
:param Commit commit:
"""
values = [
[commit.sha, metric_mapping[metric.name], metric.value]
for metric in metrics
if metric.value != 0
]
db.executemany(
'INSERT INTO metric_changes (sha, metric_id, value) VALUES (?, ?, ?)',
values,
) | [
"def",
"insert_metric_changes",
"(",
"db",
",",
"metrics",
",",
"metric_mapping",
",",
"commit",
")",
":",
"values",
"=",
"[",
"[",
"commit",
".",
"sha",
",",
"metric_mapping",
"[",
"metric",
".",
"name",
"]",
",",
"metric",
".",
"value",
"]",
"for",
"metric",
"in",
"metrics",
"if",
"metric",
".",
"value",
"!=",
"0",
"]",
"db",
".",
"executemany",
"(",
"'INSERT INTO metric_changes (sha, metric_id, value) VALUES (?, ?, ?)'",
",",
"values",
",",
")"
] | Insert into the metric_changes tables.
:param metrics: `list` of `Metric` objects
:param dict metric_mapping: Maps metric names to ids
:param Commit commit: | [
"Insert",
"into",
"the",
"metric_changes",
"tables",
"."
] | 31b41e2510063e9739de7987cdca95eaccaecbd6 | https://github.com/asottile/git-code-debt/blob/31b41e2510063e9739de7987cdca95eaccaecbd6/git_code_debt/write_logic.py#L18-L33 | train |
asottile/git-code-debt | git_code_debt/repo_parser.py | RepoParser.get_commits | def get_commits(self, since_sha=None):
"""Returns a list of Commit objects.
Args:
since_sha - (optional) A sha to search from
"""
assert self.tempdir
cmd = ['git', 'log', '--first-parent', '--reverse', COMMIT_FORMAT]
if since_sha:
commits = [self.get_commit(since_sha)]
cmd.append('{}..HEAD'.format(since_sha))
else:
commits = []
cmd.append('HEAD')
output = cmd_output(*cmd, cwd=self.tempdir)
for sha, date in chunk_iter(output.splitlines(), 2):
commits.append(Commit(sha, int(date)))
return commits | python | def get_commits(self, since_sha=None):
"""Returns a list of Commit objects.
Args:
since_sha - (optional) A sha to search from
"""
assert self.tempdir
cmd = ['git', 'log', '--first-parent', '--reverse', COMMIT_FORMAT]
if since_sha:
commits = [self.get_commit(since_sha)]
cmd.append('{}..HEAD'.format(since_sha))
else:
commits = []
cmd.append('HEAD')
output = cmd_output(*cmd, cwd=self.tempdir)
for sha, date in chunk_iter(output.splitlines(), 2):
commits.append(Commit(sha, int(date)))
return commits | [
"def",
"get_commits",
"(",
"self",
",",
"since_sha",
"=",
"None",
")",
":",
"assert",
"self",
".",
"tempdir",
"cmd",
"=",
"[",
"'git'",
",",
"'log'",
",",
"'--first-parent'",
",",
"'--reverse'",
",",
"COMMIT_FORMAT",
"]",
"if",
"since_sha",
":",
"commits",
"=",
"[",
"self",
".",
"get_commit",
"(",
"since_sha",
")",
"]",
"cmd",
".",
"append",
"(",
"'{}..HEAD'",
".",
"format",
"(",
"since_sha",
")",
")",
"else",
":",
"commits",
"=",
"[",
"]",
"cmd",
".",
"append",
"(",
"'HEAD'",
")",
"output",
"=",
"cmd_output",
"(",
"*",
"cmd",
",",
"cwd",
"=",
"self",
".",
"tempdir",
")",
"for",
"sha",
",",
"date",
"in",
"chunk_iter",
"(",
"output",
".",
"splitlines",
"(",
")",
",",
"2",
")",
":",
"commits",
".",
"append",
"(",
"Commit",
"(",
"sha",
",",
"int",
"(",
"date",
")",
")",
")",
"return",
"commits"
] | Returns a list of Commit objects.
Args:
since_sha - (optional) A sha to search from | [
"Returns",
"a",
"list",
"of",
"Commit",
"objects",
"."
] | 31b41e2510063e9739de7987cdca95eaccaecbd6 | https://github.com/asottile/git-code-debt/blob/31b41e2510063e9739de7987cdca95eaccaecbd6/git_code_debt/repo_parser.py#L49-L70 | train |
asottile/git-code-debt | git_code_debt/util/discovery.py | discover | def discover(package, cls_match_func):
"""Returns a set of classes in the directory matched by cls_match_func
Args:
path - A Python package
cls_match_func - Function taking a class and returning true if the
class is to be included in the output.
"""
matched_classes = set()
for _, module_name, _ in pkgutil.walk_packages(
package.__path__,
prefix=package.__name__ + '.',
):
module = __import__(module_name, fromlist=[str('__trash')], level=0)
# Check all the classes in that module
for _, imported_class in inspect.getmembers(module, inspect.isclass):
# Don't include things that are only there due to a side-effect of
# importing
if imported_class.__module__ != module.__name__:
continue
if cls_match_func(imported_class):
matched_classes.add(imported_class)
return matched_classes | python | def discover(package, cls_match_func):
"""Returns a set of classes in the directory matched by cls_match_func
Args:
path - A Python package
cls_match_func - Function taking a class and returning true if the
class is to be included in the output.
"""
matched_classes = set()
for _, module_name, _ in pkgutil.walk_packages(
package.__path__,
prefix=package.__name__ + '.',
):
module = __import__(module_name, fromlist=[str('__trash')], level=0)
# Check all the classes in that module
for _, imported_class in inspect.getmembers(module, inspect.isclass):
# Don't include things that are only there due to a side-effect of
# importing
if imported_class.__module__ != module.__name__:
continue
if cls_match_func(imported_class):
matched_classes.add(imported_class)
return matched_classes | [
"def",
"discover",
"(",
"package",
",",
"cls_match_func",
")",
":",
"matched_classes",
"=",
"set",
"(",
")",
"for",
"_",
",",
"module_name",
",",
"_",
"in",
"pkgutil",
".",
"walk_packages",
"(",
"package",
".",
"__path__",
",",
"prefix",
"=",
"package",
".",
"__name__",
"+",
"'.'",
",",
")",
":",
"module",
"=",
"__import__",
"(",
"module_name",
",",
"fromlist",
"=",
"[",
"str",
"(",
"'__trash'",
")",
"]",
",",
"level",
"=",
"0",
")",
"# Check all the classes in that module",
"for",
"_",
",",
"imported_class",
"in",
"inspect",
".",
"getmembers",
"(",
"module",
",",
"inspect",
".",
"isclass",
")",
":",
"# Don't include things that are only there due to a side-effect of",
"# importing",
"if",
"imported_class",
".",
"__module__",
"!=",
"module",
".",
"__name__",
":",
"continue",
"if",
"cls_match_func",
"(",
"imported_class",
")",
":",
"matched_classes",
".",
"add",
"(",
"imported_class",
")",
"return",
"matched_classes"
] | Returns a set of classes in the directory matched by cls_match_func
Args:
path - A Python package
cls_match_func - Function taking a class and returning true if the
class is to be included in the output. | [
"Returns",
"a",
"set",
"of",
"classes",
"in",
"the",
"directory",
"matched",
"by",
"cls_match_func"
] | 31b41e2510063e9739de7987cdca95eaccaecbd6 | https://github.com/asottile/git-code-debt/blob/31b41e2510063e9739de7987cdca95eaccaecbd6/git_code_debt/util/discovery.py#L8-L34 | train |
asottile/git-code-debt | git_code_debt/util/iter.py | chunk_iter | def chunk_iter(iterable, n):
"""Yields an iterator in chunks
For example you can do
for a, b in chunk_iter([1, 2, 3, 4, 5, 6], 2):
print('{} {}'.format(a, b))
# Prints
# 1 2
# 3 4
# 5 6
Args:
iterable - Some iterable
n - Chunk size (must be greater than 0)
"""
assert n > 0
iterable = iter(iterable)
chunk = tuple(itertools.islice(iterable, n))
while chunk:
yield chunk
chunk = tuple(itertools.islice(iterable, n)) | python | def chunk_iter(iterable, n):
"""Yields an iterator in chunks
For example you can do
for a, b in chunk_iter([1, 2, 3, 4, 5, 6], 2):
print('{} {}'.format(a, b))
# Prints
# 1 2
# 3 4
# 5 6
Args:
iterable - Some iterable
n - Chunk size (must be greater than 0)
"""
assert n > 0
iterable = iter(iterable)
chunk = tuple(itertools.islice(iterable, n))
while chunk:
yield chunk
chunk = tuple(itertools.islice(iterable, n)) | [
"def",
"chunk_iter",
"(",
"iterable",
",",
"n",
")",
":",
"assert",
"n",
">",
"0",
"iterable",
"=",
"iter",
"(",
"iterable",
")",
"chunk",
"=",
"tuple",
"(",
"itertools",
".",
"islice",
"(",
"iterable",
",",
"n",
")",
")",
"while",
"chunk",
":",
"yield",
"chunk",
"chunk",
"=",
"tuple",
"(",
"itertools",
".",
"islice",
"(",
"iterable",
",",
"n",
")",
")"
] | Yields an iterator in chunks
For example you can do
for a, b in chunk_iter([1, 2, 3, 4, 5, 6], 2):
print('{} {}'.format(a, b))
# Prints
# 1 2
# 3 4
# 5 6
Args:
iterable - Some iterable
n - Chunk size (must be greater than 0) | [
"Yields",
"an",
"iterator",
"in",
"chunks"
] | 31b41e2510063e9739de7987cdca95eaccaecbd6 | https://github.com/asottile/git-code-debt/blob/31b41e2510063e9739de7987cdca95eaccaecbd6/git_code_debt/util/iter.py#L7-L30 | train |
asottile/git-code-debt | git_code_debt/discovery.py | get_metric_parsers | def get_metric_parsers(metric_packages=tuple(), include_defaults=True):
"""Gets all of the metric parsers.
Args:
metric_packages - Defaults to no extra packages. An iterable of
metric containing packages. A metric inherits DiffParserBase
and does not have __metric__ = False
A metric package must be imported using import a.b.c
include_defaults - Whether to include the generic metric parsers
"""
metric_parsers = set()
if include_defaults:
import git_code_debt.metrics
metric_parsers.update(discover(git_code_debt.metrics, is_metric_cls))
for metric_package in metric_packages:
metric_parsers.update(discover(metric_package, is_metric_cls))
return metric_parsers | python | def get_metric_parsers(metric_packages=tuple(), include_defaults=True):
"""Gets all of the metric parsers.
Args:
metric_packages - Defaults to no extra packages. An iterable of
metric containing packages. A metric inherits DiffParserBase
and does not have __metric__ = False
A metric package must be imported using import a.b.c
include_defaults - Whether to include the generic metric parsers
"""
metric_parsers = set()
if include_defaults:
import git_code_debt.metrics
metric_parsers.update(discover(git_code_debt.metrics, is_metric_cls))
for metric_package in metric_packages:
metric_parsers.update(discover(metric_package, is_metric_cls))
return metric_parsers | [
"def",
"get_metric_parsers",
"(",
"metric_packages",
"=",
"tuple",
"(",
")",
",",
"include_defaults",
"=",
"True",
")",
":",
"metric_parsers",
"=",
"set",
"(",
")",
"if",
"include_defaults",
":",
"import",
"git_code_debt",
".",
"metrics",
"metric_parsers",
".",
"update",
"(",
"discover",
"(",
"git_code_debt",
".",
"metrics",
",",
"is_metric_cls",
")",
")",
"for",
"metric_package",
"in",
"metric_packages",
":",
"metric_parsers",
".",
"update",
"(",
"discover",
"(",
"metric_package",
",",
"is_metric_cls",
")",
")",
"return",
"metric_parsers"
] | Gets all of the metric parsers.
Args:
metric_packages - Defaults to no extra packages. An iterable of
metric containing packages. A metric inherits DiffParserBase
and does not have __metric__ = False
A metric package must be imported using import a.b.c
include_defaults - Whether to include the generic metric parsers | [
"Gets",
"all",
"of",
"the",
"metric",
"parsers",
"."
] | 31b41e2510063e9739de7987cdca95eaccaecbd6 | https://github.com/asottile/git-code-debt/blob/31b41e2510063e9739de7987cdca95eaccaecbd6/git_code_debt/discovery.py#L22-L40 | train |
hustcc/timeago | src/timeago/locales/__init__.py | timeago_template | def timeago_template(locale, index, ago_in):
'''
simple locale implement
'''
try:
LOCALE = __import__('timeago.locales.' + locale)
LOCALE = locale_module(LOCALE, locale)
except:
locale = setting.DEFAULT_LOCALE
LOCALE = __import__('timeago.locales.' + locale)
LOCALE = locale_module(LOCALE, locale)
if isinstance(LOCALE, list):
return LOCALE[index][ago_in]
else:
return LOCALE(index, ago_in) | python | def timeago_template(locale, index, ago_in):
'''
simple locale implement
'''
try:
LOCALE = __import__('timeago.locales.' + locale)
LOCALE = locale_module(LOCALE, locale)
except:
locale = setting.DEFAULT_LOCALE
LOCALE = __import__('timeago.locales.' + locale)
LOCALE = locale_module(LOCALE, locale)
if isinstance(LOCALE, list):
return LOCALE[index][ago_in]
else:
return LOCALE(index, ago_in) | [
"def",
"timeago_template",
"(",
"locale",
",",
"index",
",",
"ago_in",
")",
":",
"try",
":",
"LOCALE",
"=",
"__import__",
"(",
"'timeago.locales.'",
"+",
"locale",
")",
"LOCALE",
"=",
"locale_module",
"(",
"LOCALE",
",",
"locale",
")",
"except",
":",
"locale",
"=",
"setting",
".",
"DEFAULT_LOCALE",
"LOCALE",
"=",
"__import__",
"(",
"'timeago.locales.'",
"+",
"locale",
")",
"LOCALE",
"=",
"locale_module",
"(",
"LOCALE",
",",
"locale",
")",
"if",
"isinstance",
"(",
"LOCALE",
",",
"list",
")",
":",
"return",
"LOCALE",
"[",
"index",
"]",
"[",
"ago_in",
"]",
"else",
":",
"return",
"LOCALE",
"(",
"index",
",",
"ago_in",
")"
] | simple locale implement | [
"simple",
"locale",
"implement"
] | 819fc6efefeccea2a39e6c1cb2f20b5d2cc9f613 | https://github.com/hustcc/timeago/blob/819fc6efefeccea2a39e6c1cb2f20b5d2cc9f613/src/timeago/locales/__init__.py#L20-L35 | train |
hustcc/timeago | src/timeago/parser.py | parse | def parse(input):
'''
parse input to datetime
'''
if isinstance(input, datetime):
return input
if isinstance(input, date):
return date_to_datetime(input)
if isinstance(input, time):
return time_to_datetime(input)
if isinstance(input, (int, float)):
return timestamp_to_datetime(input)
if isinstance(input, (str)):
return string_to_data_time(input)
return None | python | def parse(input):
'''
parse input to datetime
'''
if isinstance(input, datetime):
return input
if isinstance(input, date):
return date_to_datetime(input)
if isinstance(input, time):
return time_to_datetime(input)
if isinstance(input, (int, float)):
return timestamp_to_datetime(input)
if isinstance(input, (str)):
return string_to_data_time(input)
return None | [
"def",
"parse",
"(",
"input",
")",
":",
"if",
"isinstance",
"(",
"input",
",",
"datetime",
")",
":",
"return",
"input",
"if",
"isinstance",
"(",
"input",
",",
"date",
")",
":",
"return",
"date_to_datetime",
"(",
"input",
")",
"if",
"isinstance",
"(",
"input",
",",
"time",
")",
":",
"return",
"time_to_datetime",
"(",
"input",
")",
"if",
"isinstance",
"(",
"input",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"timestamp_to_datetime",
"(",
"input",
")",
"if",
"isinstance",
"(",
"input",
",",
"(",
"str",
")",
")",
":",
"return",
"string_to_data_time",
"(",
"input",
")",
"return",
"None"
] | parse input to datetime | [
"parse",
"input",
"to",
"datetime"
] | 819fc6efefeccea2a39e6c1cb2f20b5d2cc9f613 | https://github.com/hustcc/timeago/blob/819fc6efefeccea2a39e6c1cb2f20b5d2cc9f613/src/timeago/parser.py#L16-L30 | train |
hustcc/timeago | src/timeago/__init__.py | format | def format(date, now=None, locale='en'):
'''
the entry method
'''
if not isinstance(date, timedelta):
if now is None:
now = datetime.now()
date = parser.parse(date)
now = parser.parse(now)
if date is None:
raise ParameterUnvalid('the parameter `date` should be datetime '
'/ timedelta, or datetime formated string.')
if now is None:
raise ParameterUnvalid('the parameter `now` should be datetime, '
'or datetime formated string.')
date = now - date
# the gap sec
diff_seconds = int(total_seconds(date))
# is ago or in
ago_in = 0
if diff_seconds < 0:
ago_in = 1 # date is later then now, is the time in future
diff_seconds *= -1 # chango to positive
tmp = 0
i = 0
while i < SEC_ARRAY_LEN:
tmp = SEC_ARRAY[i]
if diff_seconds >= tmp:
i += 1
diff_seconds /= tmp
else:
break
diff_seconds = int(diff_seconds)
i *= 2
if diff_seconds > (i == 0 and 9 or 1):
i += 1
if locale is None:
locale = DEFAULT_LOCALE
tmp = timeago_template(locale, i, ago_in)
if hasattr(tmp, '__call__'):
tmp = tmp(diff_seconds)
return '%s' in tmp and tmp % diff_seconds or tmp | python | def format(date, now=None, locale='en'):
'''
the entry method
'''
if not isinstance(date, timedelta):
if now is None:
now = datetime.now()
date = parser.parse(date)
now = parser.parse(now)
if date is None:
raise ParameterUnvalid('the parameter `date` should be datetime '
'/ timedelta, or datetime formated string.')
if now is None:
raise ParameterUnvalid('the parameter `now` should be datetime, '
'or datetime formated string.')
date = now - date
# the gap sec
diff_seconds = int(total_seconds(date))
# is ago or in
ago_in = 0
if diff_seconds < 0:
ago_in = 1 # date is later then now, is the time in future
diff_seconds *= -1 # chango to positive
tmp = 0
i = 0
while i < SEC_ARRAY_LEN:
tmp = SEC_ARRAY[i]
if diff_seconds >= tmp:
i += 1
diff_seconds /= tmp
else:
break
diff_seconds = int(diff_seconds)
i *= 2
if diff_seconds > (i == 0 and 9 or 1):
i += 1
if locale is None:
locale = DEFAULT_LOCALE
tmp = timeago_template(locale, i, ago_in)
if hasattr(tmp, '__call__'):
tmp = tmp(diff_seconds)
return '%s' in tmp and tmp % diff_seconds or tmp | [
"def",
"format",
"(",
"date",
",",
"now",
"=",
"None",
",",
"locale",
"=",
"'en'",
")",
":",
"if",
"not",
"isinstance",
"(",
"date",
",",
"timedelta",
")",
":",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"date",
"=",
"parser",
".",
"parse",
"(",
"date",
")",
"now",
"=",
"parser",
".",
"parse",
"(",
"now",
")",
"if",
"date",
"is",
"None",
":",
"raise",
"ParameterUnvalid",
"(",
"'the parameter `date` should be datetime '",
"'/ timedelta, or datetime formated string.'",
")",
"if",
"now",
"is",
"None",
":",
"raise",
"ParameterUnvalid",
"(",
"'the parameter `now` should be datetime, '",
"'or datetime formated string.'",
")",
"date",
"=",
"now",
"-",
"date",
"# the gap sec",
"diff_seconds",
"=",
"int",
"(",
"total_seconds",
"(",
"date",
")",
")",
"# is ago or in",
"ago_in",
"=",
"0",
"if",
"diff_seconds",
"<",
"0",
":",
"ago_in",
"=",
"1",
"# date is later then now, is the time in future",
"diff_seconds",
"*=",
"-",
"1",
"# chango to positive",
"tmp",
"=",
"0",
"i",
"=",
"0",
"while",
"i",
"<",
"SEC_ARRAY_LEN",
":",
"tmp",
"=",
"SEC_ARRAY",
"[",
"i",
"]",
"if",
"diff_seconds",
">=",
"tmp",
":",
"i",
"+=",
"1",
"diff_seconds",
"/=",
"tmp",
"else",
":",
"break",
"diff_seconds",
"=",
"int",
"(",
"diff_seconds",
")",
"i",
"*=",
"2",
"if",
"diff_seconds",
">",
"(",
"i",
"==",
"0",
"and",
"9",
"or",
"1",
")",
":",
"i",
"+=",
"1",
"if",
"locale",
"is",
"None",
":",
"locale",
"=",
"DEFAULT_LOCALE",
"tmp",
"=",
"timeago_template",
"(",
"locale",
",",
"i",
",",
"ago_in",
")",
"if",
"hasattr",
"(",
"tmp",
",",
"'__call__'",
")",
":",
"tmp",
"=",
"tmp",
"(",
"diff_seconds",
")",
"return",
"'%s'",
"in",
"tmp",
"and",
"tmp",
"%",
"diff_seconds",
"or",
"tmp"
] | the entry method | [
"the",
"entry",
"method"
] | 819fc6efefeccea2a39e6c1cb2f20b5d2cc9f613 | https://github.com/hustcc/timeago/blob/819fc6efefeccea2a39e6c1cb2f20b5d2cc9f613/src/timeago/__init__.py#L36-L83 | train |
coldfix/udiskie | udiskie/mount.py | _is_parent_of | def _is_parent_of(parent, child):
"""Check whether the first device is the parent of the second device."""
if child.is_partition:
return child.partition_slave == parent
if child.is_toplevel:
return child.drive == parent and child != parent
return False | python | def _is_parent_of(parent, child):
"""Check whether the first device is the parent of the second device."""
if child.is_partition:
return child.partition_slave == parent
if child.is_toplevel:
return child.drive == parent and child != parent
return False | [
"def",
"_is_parent_of",
"(",
"parent",
",",
"child",
")",
":",
"if",
"child",
".",
"is_partition",
":",
"return",
"child",
".",
"partition_slave",
"==",
"parent",
"if",
"child",
".",
"is_toplevel",
":",
"return",
"child",
".",
"drive",
"==",
"parent",
"and",
"child",
"!=",
"parent",
"return",
"False"
] | Check whether the first device is the parent of the second device. | [
"Check",
"whether",
"the",
"first",
"device",
"is",
"the",
"parent",
"of",
"the",
"second",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L36-L42 | train |
coldfix/udiskie | udiskie/mount.py | prune_empty_node | def prune_empty_node(node, seen):
"""
Recursively remove empty branches and return whether this makes the node
itself empty.
The ``seen`` parameter is used to avoid infinite recursion due to cycles
(you never know).
"""
if node.methods:
return False
if id(node) in seen:
return True
seen = seen | {id(node)}
for branch in list(node.branches):
if prune_empty_node(branch, seen):
node.branches.remove(branch)
else:
return False
return True | python | def prune_empty_node(node, seen):
"""
Recursively remove empty branches and return whether this makes the node
itself empty.
The ``seen`` parameter is used to avoid infinite recursion due to cycles
(you never know).
"""
if node.methods:
return False
if id(node) in seen:
return True
seen = seen | {id(node)}
for branch in list(node.branches):
if prune_empty_node(branch, seen):
node.branches.remove(branch)
else:
return False
return True | [
"def",
"prune_empty_node",
"(",
"node",
",",
"seen",
")",
":",
"if",
"node",
".",
"methods",
":",
"return",
"False",
"if",
"id",
"(",
"node",
")",
"in",
"seen",
":",
"return",
"True",
"seen",
"=",
"seen",
"|",
"{",
"id",
"(",
"node",
")",
"}",
"for",
"branch",
"in",
"list",
"(",
"node",
".",
"branches",
")",
":",
"if",
"prune_empty_node",
"(",
"branch",
",",
"seen",
")",
":",
"node",
".",
"branches",
".",
"remove",
"(",
"branch",
")",
"else",
":",
"return",
"False",
"return",
"True"
] | Recursively remove empty branches and return whether this makes the node
itself empty.
The ``seen`` parameter is used to avoid infinite recursion due to cycles
(you never know). | [
"Recursively",
"remove",
"empty",
"branches",
"and",
"return",
"whether",
"this",
"makes",
"the",
"node",
"itself",
"empty",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L844-L862 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.browse | async def browse(self, device):
"""
Launch file manager on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched.
"""
device = self._find_device(device)
if not device.is_mounted:
self._log.error(_("not browsing {0}: not mounted", device))
return False
if not self._browser:
self._log.error(_("not browsing {0}: no program", device))
return False
self._log.debug(_('opening {0} on {0.mount_paths[0]}', device))
self._browser(device.mount_paths[0])
self._log.info(_('opened {0} on {0.mount_paths[0]}', device))
return True | python | async def browse(self, device):
"""
Launch file manager on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched.
"""
device = self._find_device(device)
if not device.is_mounted:
self._log.error(_("not browsing {0}: not mounted", device))
return False
if not self._browser:
self._log.error(_("not browsing {0}: no program", device))
return False
self._log.debug(_('opening {0} on {0.mount_paths[0]}', device))
self._browser(device.mount_paths[0])
self._log.info(_('opened {0} on {0.mount_paths[0]}', device))
return True | [
"async",
"def",
"browse",
"(",
"self",
",",
"device",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"device",
".",
"is_mounted",
":",
"self",
".",
"_log",
".",
"error",
"(",
"_",
"(",
"\"not browsing {0}: not mounted\"",
",",
"device",
")",
")",
"return",
"False",
"if",
"not",
"self",
".",
"_browser",
":",
"self",
".",
"_log",
".",
"error",
"(",
"_",
"(",
"\"not browsing {0}: no program\"",
",",
"device",
")",
")",
"return",
"False",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'opening {0} on {0.mount_paths[0]}'",
",",
"device",
")",
")",
"self",
".",
"_browser",
"(",
"device",
".",
"mount_paths",
"[",
"0",
"]",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'opened {0} on {0.mount_paths[0]}'",
",",
"device",
")",
")",
"return",
"True"
] | Launch file manager on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched. | [
"Launch",
"file",
"manager",
"on",
"the",
"mount",
"path",
"of",
"the",
"specified",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L109-L126 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.terminal | async def terminal(self, device):
"""
Launch terminal on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched.
"""
device = self._find_device(device)
if not device.is_mounted:
self._log.error(_("not opening terminal {0}: not mounted", device))
return False
if not self._terminal:
self._log.error(_("not opening terminal {0}: no program", device))
return False
self._log.debug(_('opening {0} on {0.mount_paths[0]}', device))
self._terminal(device.mount_paths[0])
self._log.info(_('opened {0} on {0.mount_paths[0]}', device))
return True | python | async def terminal(self, device):
"""
Launch terminal on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched.
"""
device = self._find_device(device)
if not device.is_mounted:
self._log.error(_("not opening terminal {0}: not mounted", device))
return False
if not self._terminal:
self._log.error(_("not opening terminal {0}: no program", device))
return False
self._log.debug(_('opening {0} on {0.mount_paths[0]}', device))
self._terminal(device.mount_paths[0])
self._log.info(_('opened {0} on {0.mount_paths[0]}', device))
return True | [
"async",
"def",
"terminal",
"(",
"self",
",",
"device",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"device",
".",
"is_mounted",
":",
"self",
".",
"_log",
".",
"error",
"(",
"_",
"(",
"\"not opening terminal {0}: not mounted\"",
",",
"device",
")",
")",
"return",
"False",
"if",
"not",
"self",
".",
"_terminal",
":",
"self",
".",
"_log",
".",
"error",
"(",
"_",
"(",
"\"not opening terminal {0}: no program\"",
",",
"device",
")",
")",
"return",
"False",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'opening {0} on {0.mount_paths[0]}'",
",",
"device",
")",
")",
"self",
".",
"_terminal",
"(",
"device",
".",
"mount_paths",
"[",
"0",
"]",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'opened {0} on {0.mount_paths[0]}'",
",",
"device",
")",
")",
"return",
"True"
] | Launch terminal on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched. | [
"Launch",
"terminal",
"on",
"the",
"mount",
"path",
"of",
"the",
"specified",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L129-L146 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.mount | async def mount(self, device):
"""
Mount the device if not already mounted.
:param device: device object, block device path or mount path
:returns: whether the device is mounted.
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_filesystem:
self._log.warn(_('not mounting {0}: unhandled device', device))
return False
if device.is_mounted:
self._log.info(_('not mounting {0}: already mounted', device))
return True
options = match_config(self._config, device, 'options', None)
kwargs = dict(options=options)
self._log.debug(_('mounting {0} with {1}', device, kwargs))
self._check_device_before_mount(device)
mount_path = await device.mount(**kwargs)
self._log.info(_('mounted {0} on {1}', device, mount_path))
return True | python | async def mount(self, device):
"""
Mount the device if not already mounted.
:param device: device object, block device path or mount path
:returns: whether the device is mounted.
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_filesystem:
self._log.warn(_('not mounting {0}: unhandled device', device))
return False
if device.is_mounted:
self._log.info(_('not mounting {0}: already mounted', device))
return True
options = match_config(self._config, device, 'options', None)
kwargs = dict(options=options)
self._log.debug(_('mounting {0} with {1}', device, kwargs))
self._check_device_before_mount(device)
mount_path = await device.mount(**kwargs)
self._log.info(_('mounted {0} on {1}', device, mount_path))
return True | [
"async",
"def",
"mount",
"(",
"self",
",",
"device",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
"or",
"not",
"device",
".",
"is_filesystem",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not mounting {0}: unhandled device'",
",",
"device",
")",
")",
"return",
"False",
"if",
"device",
".",
"is_mounted",
":",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'not mounting {0}: already mounted'",
",",
"device",
")",
")",
"return",
"True",
"options",
"=",
"match_config",
"(",
"self",
".",
"_config",
",",
"device",
",",
"'options'",
",",
"None",
")",
"kwargs",
"=",
"dict",
"(",
"options",
"=",
"options",
")",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'mounting {0} with {1}'",
",",
"device",
",",
"kwargs",
")",
")",
"self",
".",
"_check_device_before_mount",
"(",
"device",
")",
"mount_path",
"=",
"await",
"device",
".",
"mount",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'mounted {0} on {1}'",
",",
"device",
",",
"mount_path",
")",
")",
"return",
"True"
] | Mount the device if not already mounted.
:param device: device object, block device path or mount path
:returns: whether the device is mounted. | [
"Mount",
"the",
"device",
"if",
"not",
"already",
"mounted",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L150-L170 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.unmount | async def unmount(self, device):
"""
Unmount a Device if mounted.
:param device: device object, block device path or mount path
:returns: whether the device is unmounted
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_filesystem:
self._log.warn(_('not unmounting {0}: unhandled device', device))
return False
if not device.is_mounted:
self._log.info(_('not unmounting {0}: not mounted', device))
return True
self._log.debug(_('unmounting {0}', device))
await device.unmount()
self._log.info(_('unmounted {0}', device))
return True | python | async def unmount(self, device):
"""
Unmount a Device if mounted.
:param device: device object, block device path or mount path
:returns: whether the device is unmounted
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_filesystem:
self._log.warn(_('not unmounting {0}: unhandled device', device))
return False
if not device.is_mounted:
self._log.info(_('not unmounting {0}: not mounted', device))
return True
self._log.debug(_('unmounting {0}', device))
await device.unmount()
self._log.info(_('unmounted {0}', device))
return True | [
"async",
"def",
"unmount",
"(",
"self",
",",
"device",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
"or",
"not",
"device",
".",
"is_filesystem",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not unmounting {0}: unhandled device'",
",",
"device",
")",
")",
"return",
"False",
"if",
"not",
"device",
".",
"is_mounted",
":",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'not unmounting {0}: not mounted'",
",",
"device",
")",
")",
"return",
"True",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'unmounting {0}'",
",",
"device",
")",
")",
"await",
"device",
".",
"unmount",
"(",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'unmounted {0}'",
",",
"device",
")",
")",
"return",
"True"
] | Unmount a Device if mounted.
:param device: device object, block device path or mount path
:returns: whether the device is unmounted | [
"Unmount",
"a",
"Device",
"if",
"mounted",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L180-L197 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.unlock | async def unlock(self, device):
"""
Unlock the device if not already unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is unlocked
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_crypto:
self._log.warn(_('not unlocking {0}: unhandled device', device))
return False
if device.is_unlocked:
self._log.info(_('not unlocking {0}: already unlocked', device))
return True
if not self._prompt:
self._log.error(_('not unlocking {0}: no password prompt', device))
return False
unlocked = await self._unlock_from_cache(device)
if unlocked:
return True
unlocked = await self._unlock_from_keyfile(device)
if unlocked:
return True
options = dict(allow_keyfile=self.udisks.keyfile_support,
allow_cache=self._cache is not None,
cache_hint=self._cache_hint)
password = await self._prompt(device, options)
# password can be: None, str, or udiskie.prompt.PasswordResult
cache_hint = getattr(password, 'cache_hint', self._cache_hint)
password = getattr(password, 'password', password)
if password is None:
self._log.debug(_('not unlocking {0}: cancelled by user', device))
return False
if isinstance(password, bytes):
self._log.debug(_('unlocking {0} using keyfile', device))
await device.unlock_keyfile(password)
else:
self._log.debug(_('unlocking {0}', device))
await device.unlock(password)
self._update_cache(device, password, cache_hint)
self._log.info(_('unlocked {0}', device))
return True | python | async def unlock(self, device):
"""
Unlock the device if not already unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is unlocked
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_crypto:
self._log.warn(_('not unlocking {0}: unhandled device', device))
return False
if device.is_unlocked:
self._log.info(_('not unlocking {0}: already unlocked', device))
return True
if not self._prompt:
self._log.error(_('not unlocking {0}: no password prompt', device))
return False
unlocked = await self._unlock_from_cache(device)
if unlocked:
return True
unlocked = await self._unlock_from_keyfile(device)
if unlocked:
return True
options = dict(allow_keyfile=self.udisks.keyfile_support,
allow_cache=self._cache is not None,
cache_hint=self._cache_hint)
password = await self._prompt(device, options)
# password can be: None, str, or udiskie.prompt.PasswordResult
cache_hint = getattr(password, 'cache_hint', self._cache_hint)
password = getattr(password, 'password', password)
if password is None:
self._log.debug(_('not unlocking {0}: cancelled by user', device))
return False
if isinstance(password, bytes):
self._log.debug(_('unlocking {0} using keyfile', device))
await device.unlock_keyfile(password)
else:
self._log.debug(_('unlocking {0}', device))
await device.unlock(password)
self._update_cache(device, password, cache_hint)
self._log.info(_('unlocked {0}', device))
return True | [
"async",
"def",
"unlock",
"(",
"self",
",",
"device",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
"or",
"not",
"device",
".",
"is_crypto",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not unlocking {0}: unhandled device'",
",",
"device",
")",
")",
"return",
"False",
"if",
"device",
".",
"is_unlocked",
":",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'not unlocking {0}: already unlocked'",
",",
"device",
")",
")",
"return",
"True",
"if",
"not",
"self",
".",
"_prompt",
":",
"self",
".",
"_log",
".",
"error",
"(",
"_",
"(",
"'not unlocking {0}: no password prompt'",
",",
"device",
")",
")",
"return",
"False",
"unlocked",
"=",
"await",
"self",
".",
"_unlock_from_cache",
"(",
"device",
")",
"if",
"unlocked",
":",
"return",
"True",
"unlocked",
"=",
"await",
"self",
".",
"_unlock_from_keyfile",
"(",
"device",
")",
"if",
"unlocked",
":",
"return",
"True",
"options",
"=",
"dict",
"(",
"allow_keyfile",
"=",
"self",
".",
"udisks",
".",
"keyfile_support",
",",
"allow_cache",
"=",
"self",
".",
"_cache",
"is",
"not",
"None",
",",
"cache_hint",
"=",
"self",
".",
"_cache_hint",
")",
"password",
"=",
"await",
"self",
".",
"_prompt",
"(",
"device",
",",
"options",
")",
"# password can be: None, str, or udiskie.prompt.PasswordResult",
"cache_hint",
"=",
"getattr",
"(",
"password",
",",
"'cache_hint'",
",",
"self",
".",
"_cache_hint",
")",
"password",
"=",
"getattr",
"(",
"password",
",",
"'password'",
",",
"password",
")",
"if",
"password",
"is",
"None",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'not unlocking {0}: cancelled by user'",
",",
"device",
")",
")",
"return",
"False",
"if",
"isinstance",
"(",
"password",
",",
"bytes",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'unlocking {0} using keyfile'",
",",
"device",
")",
")",
"await",
"device",
".",
"unlock_keyfile",
"(",
"password",
")",
"else",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'unlocking {0}'",
",",
"device",
")",
")",
"await",
"device",
".",
"unlock",
"(",
"password",
")",
"self",
".",
"_update_cache",
"(",
"device",
",",
"password",
",",
"cache_hint",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'unlocked {0}'",
",",
"device",
")",
")",
"return",
"True"
] | Unlock the device if not already unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is unlocked | [
"Unlock",
"the",
"device",
"if",
"not",
"already",
"unlocked",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L201-L242 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.lock | async def lock(self, device):
"""
Lock device if unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is locked
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_crypto:
self._log.warn(_('not locking {0}: unhandled device', device))
return False
if not device.is_unlocked:
self._log.info(_('not locking {0}: not unlocked', device))
return True
self._log.debug(_('locking {0}', device))
await device.lock()
self._log.info(_('locked {0}', device))
return True | python | async def lock(self, device):
"""
Lock device if unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is locked
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_crypto:
self._log.warn(_('not locking {0}: unhandled device', device))
return False
if not device.is_unlocked:
self._log.info(_('not locking {0}: not unlocked', device))
return True
self._log.debug(_('locking {0}', device))
await device.lock()
self._log.info(_('locked {0}', device))
return True | [
"async",
"def",
"lock",
"(",
"self",
",",
"device",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
"or",
"not",
"device",
".",
"is_crypto",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not locking {0}: unhandled device'",
",",
"device",
")",
")",
"return",
"False",
"if",
"not",
"device",
".",
"is_unlocked",
":",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'not locking {0}: not unlocked'",
",",
"device",
")",
")",
"return",
"True",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'locking {0}'",
",",
"device",
")",
")",
"await",
"device",
".",
"lock",
"(",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'locked {0}'",
",",
"device",
")",
")",
"return",
"True"
] | Lock device if unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is locked | [
"Lock",
"device",
"if",
"unlocked",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L299-L316 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.add | async def add(self, device, recursive=None):
"""
Mount or unlock the device depending on its type.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded
"""
device, created = await self._find_device_losetup(device)
if created and recursive is False:
return device
if device.is_filesystem:
success = await self.mount(device)
elif device.is_crypto:
success = await self.unlock(device)
if success and recursive:
await self.udisks._sync()
device = self.udisks[device.object_path]
success = await self.add(
device.luks_cleartext_holder,
recursive=True)
elif (recursive
and device.is_partition_table
and self.is_handleable(device)):
tasks = [
self.add(dev, recursive=True)
for dev in self.get_all_handleable()
if dev.is_partition and dev.partition_slave == device
]
results = await gather(*tasks)
success = all(results)
else:
self._log.info(_('not adding {0}: unhandled device', device))
return False
return success | python | async def add(self, device, recursive=None):
"""
Mount or unlock the device depending on its type.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded
"""
device, created = await self._find_device_losetup(device)
if created and recursive is False:
return device
if device.is_filesystem:
success = await self.mount(device)
elif device.is_crypto:
success = await self.unlock(device)
if success and recursive:
await self.udisks._sync()
device = self.udisks[device.object_path]
success = await self.add(
device.luks_cleartext_holder,
recursive=True)
elif (recursive
and device.is_partition_table
and self.is_handleable(device)):
tasks = [
self.add(dev, recursive=True)
for dev in self.get_all_handleable()
if dev.is_partition and dev.partition_slave == device
]
results = await gather(*tasks)
success = all(results)
else:
self._log.info(_('not adding {0}: unhandled device', device))
return False
return success | [
"async",
"def",
"add",
"(",
"self",
",",
"device",
",",
"recursive",
"=",
"None",
")",
":",
"device",
",",
"created",
"=",
"await",
"self",
".",
"_find_device_losetup",
"(",
"device",
")",
"if",
"created",
"and",
"recursive",
"is",
"False",
":",
"return",
"device",
"if",
"device",
".",
"is_filesystem",
":",
"success",
"=",
"await",
"self",
".",
"mount",
"(",
"device",
")",
"elif",
"device",
".",
"is_crypto",
":",
"success",
"=",
"await",
"self",
".",
"unlock",
"(",
"device",
")",
"if",
"success",
"and",
"recursive",
":",
"await",
"self",
".",
"udisks",
".",
"_sync",
"(",
")",
"device",
"=",
"self",
".",
"udisks",
"[",
"device",
".",
"object_path",
"]",
"success",
"=",
"await",
"self",
".",
"add",
"(",
"device",
".",
"luks_cleartext_holder",
",",
"recursive",
"=",
"True",
")",
"elif",
"(",
"recursive",
"and",
"device",
".",
"is_partition_table",
"and",
"self",
".",
"is_handleable",
"(",
"device",
")",
")",
":",
"tasks",
"=",
"[",
"self",
".",
"add",
"(",
"dev",
",",
"recursive",
"=",
"True",
")",
"for",
"dev",
"in",
"self",
".",
"get_all_handleable",
"(",
")",
"if",
"dev",
".",
"is_partition",
"and",
"dev",
".",
"partition_slave",
"==",
"device",
"]",
"results",
"=",
"await",
"gather",
"(",
"*",
"tasks",
")",
"success",
"=",
"all",
"(",
"results",
")",
"else",
":",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'not adding {0}: unhandled device'",
",",
"device",
")",
")",
"return",
"False",
"return",
"success"
] | Mount or unlock the device depending on its type.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded | [
"Mount",
"or",
"unlock",
"the",
"device",
"depending",
"on",
"its",
"type",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L320-L354 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.auto_add | async def auto_add(self, device, recursive=None, automount=True):
"""
Automatically attempt to mount or unlock a device, but be quiet if the
device is not supported.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded
"""
device, created = await self._find_device_losetup(device)
if created and recursive is False:
return device
if device.is_luks_cleartext and self.udisks.version_info >= (2, 7, 0):
await sleep(1.5) # temporary workaround for #153, unreliable
success = True
if not self.is_automount(device, automount):
pass
elif device.is_filesystem:
if not device.is_mounted:
success = await self.mount(device)
elif device.is_crypto:
if self._prompt and not device.is_unlocked:
success = await self.unlock(device)
if success and recursive:
await self.udisks._sync()
device = self.udisks[device.object_path]
success = await self.auto_add(
device.luks_cleartext_holder,
recursive=True)
elif recursive and device.is_partition_table:
tasks = [
self.auto_add(dev, recursive=True)
for dev in self.get_all_handleable()
if dev.is_partition and dev.partition_slave == device
]
results = await gather(*tasks)
success = all(results)
else:
self._log.debug(_('not adding {0}: unhandled device', device))
return success | python | async def auto_add(self, device, recursive=None, automount=True):
"""
Automatically attempt to mount or unlock a device, but be quiet if the
device is not supported.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded
"""
device, created = await self._find_device_losetup(device)
if created and recursive is False:
return device
if device.is_luks_cleartext and self.udisks.version_info >= (2, 7, 0):
await sleep(1.5) # temporary workaround for #153, unreliable
success = True
if not self.is_automount(device, automount):
pass
elif device.is_filesystem:
if not device.is_mounted:
success = await self.mount(device)
elif device.is_crypto:
if self._prompt and not device.is_unlocked:
success = await self.unlock(device)
if success and recursive:
await self.udisks._sync()
device = self.udisks[device.object_path]
success = await self.auto_add(
device.luks_cleartext_holder,
recursive=True)
elif recursive and device.is_partition_table:
tasks = [
self.auto_add(dev, recursive=True)
for dev in self.get_all_handleable()
if dev.is_partition and dev.partition_slave == device
]
results = await gather(*tasks)
success = all(results)
else:
self._log.debug(_('not adding {0}: unhandled device', device))
return success | [
"async",
"def",
"auto_add",
"(",
"self",
",",
"device",
",",
"recursive",
"=",
"None",
",",
"automount",
"=",
"True",
")",
":",
"device",
",",
"created",
"=",
"await",
"self",
".",
"_find_device_losetup",
"(",
"device",
")",
"if",
"created",
"and",
"recursive",
"is",
"False",
":",
"return",
"device",
"if",
"device",
".",
"is_luks_cleartext",
"and",
"self",
".",
"udisks",
".",
"version_info",
">=",
"(",
"2",
",",
"7",
",",
"0",
")",
":",
"await",
"sleep",
"(",
"1.5",
")",
"# temporary workaround for #153, unreliable",
"success",
"=",
"True",
"if",
"not",
"self",
".",
"is_automount",
"(",
"device",
",",
"automount",
")",
":",
"pass",
"elif",
"device",
".",
"is_filesystem",
":",
"if",
"not",
"device",
".",
"is_mounted",
":",
"success",
"=",
"await",
"self",
".",
"mount",
"(",
"device",
")",
"elif",
"device",
".",
"is_crypto",
":",
"if",
"self",
".",
"_prompt",
"and",
"not",
"device",
".",
"is_unlocked",
":",
"success",
"=",
"await",
"self",
".",
"unlock",
"(",
"device",
")",
"if",
"success",
"and",
"recursive",
":",
"await",
"self",
".",
"udisks",
".",
"_sync",
"(",
")",
"device",
"=",
"self",
".",
"udisks",
"[",
"device",
".",
"object_path",
"]",
"success",
"=",
"await",
"self",
".",
"auto_add",
"(",
"device",
".",
"luks_cleartext_holder",
",",
"recursive",
"=",
"True",
")",
"elif",
"recursive",
"and",
"device",
".",
"is_partition_table",
":",
"tasks",
"=",
"[",
"self",
".",
"auto_add",
"(",
"dev",
",",
"recursive",
"=",
"True",
")",
"for",
"dev",
"in",
"self",
".",
"get_all_handleable",
"(",
")",
"if",
"dev",
".",
"is_partition",
"and",
"dev",
".",
"partition_slave",
"==",
"device",
"]",
"results",
"=",
"await",
"gather",
"(",
"*",
"tasks",
")",
"success",
"=",
"all",
"(",
"results",
")",
"else",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'not adding {0}: unhandled device'",
",",
"device",
")",
")",
"return",
"success"
] | Automatically attempt to mount or unlock a device, but be quiet if the
device is not supported.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded | [
"Automatically",
"attempt",
"to",
"mount",
"or",
"unlock",
"a",
"device",
"but",
"be",
"quiet",
"if",
"the",
"device",
"is",
"not",
"supported",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L357-L396 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.remove | async def remove(self, device, force=False, detach=False, eject=False,
lock=False):
"""
Unmount or lock the device depending on device type.
:param device: device object, block device path or mount path
:param bool force: recursively remove all child devices
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lock: lock the associated LUKS cleartext slave
:returns: whether all attempted operations succeeded
"""
device = self._find_device(device)
if device.is_filesystem:
if device.is_mounted or not device.is_loop or detach is False:
success = await self.unmount(device)
elif device.is_crypto:
if force and device.is_unlocked:
await self.auto_remove(device.luks_cleartext_holder, force=True)
success = await self.lock(device)
elif (force
and (device.is_partition_table or device.is_drive)
and self.is_handleable(device)):
kw = dict(force=True, detach=detach, eject=eject, lock=lock)
tasks = [
self.auto_remove(child, **kw)
for child in self.get_all_handleable()
if _is_parent_of(device, child)
]
results = await gather(*tasks)
success = all(results)
else:
self._log.info(_('not removing {0}: unhandled device', device))
success = False
# if these operations work, everything is fine, we can return True:
if lock and device.is_luks_cleartext:
device = device.luks_cleartext_slave
if self.is_handleable(device):
success = await self.lock(device)
if eject:
success = await self.eject(device)
if (detach or detach is None) and device.is_loop:
success = await self.delete(device, remove=False)
elif detach:
success = await self.detach(device)
return success | python | async def remove(self, device, force=False, detach=False, eject=False,
lock=False):
"""
Unmount or lock the device depending on device type.
:param device: device object, block device path or mount path
:param bool force: recursively remove all child devices
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lock: lock the associated LUKS cleartext slave
:returns: whether all attempted operations succeeded
"""
device = self._find_device(device)
if device.is_filesystem:
if device.is_mounted or not device.is_loop or detach is False:
success = await self.unmount(device)
elif device.is_crypto:
if force and device.is_unlocked:
await self.auto_remove(device.luks_cleartext_holder, force=True)
success = await self.lock(device)
elif (force
and (device.is_partition_table or device.is_drive)
and self.is_handleable(device)):
kw = dict(force=True, detach=detach, eject=eject, lock=lock)
tasks = [
self.auto_remove(child, **kw)
for child in self.get_all_handleable()
if _is_parent_of(device, child)
]
results = await gather(*tasks)
success = all(results)
else:
self._log.info(_('not removing {0}: unhandled device', device))
success = False
# if these operations work, everything is fine, we can return True:
if lock and device.is_luks_cleartext:
device = device.luks_cleartext_slave
if self.is_handleable(device):
success = await self.lock(device)
if eject:
success = await self.eject(device)
if (detach or detach is None) and device.is_loop:
success = await self.delete(device, remove=False)
elif detach:
success = await self.detach(device)
return success | [
"async",
"def",
"remove",
"(",
"self",
",",
"device",
",",
"force",
"=",
"False",
",",
"detach",
"=",
"False",
",",
"eject",
"=",
"False",
",",
"lock",
"=",
"False",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"device",
".",
"is_filesystem",
":",
"if",
"device",
".",
"is_mounted",
"or",
"not",
"device",
".",
"is_loop",
"or",
"detach",
"is",
"False",
":",
"success",
"=",
"await",
"self",
".",
"unmount",
"(",
"device",
")",
"elif",
"device",
".",
"is_crypto",
":",
"if",
"force",
"and",
"device",
".",
"is_unlocked",
":",
"await",
"self",
".",
"auto_remove",
"(",
"device",
".",
"luks_cleartext_holder",
",",
"force",
"=",
"True",
")",
"success",
"=",
"await",
"self",
".",
"lock",
"(",
"device",
")",
"elif",
"(",
"force",
"and",
"(",
"device",
".",
"is_partition_table",
"or",
"device",
".",
"is_drive",
")",
"and",
"self",
".",
"is_handleable",
"(",
"device",
")",
")",
":",
"kw",
"=",
"dict",
"(",
"force",
"=",
"True",
",",
"detach",
"=",
"detach",
",",
"eject",
"=",
"eject",
",",
"lock",
"=",
"lock",
")",
"tasks",
"=",
"[",
"self",
".",
"auto_remove",
"(",
"child",
",",
"*",
"*",
"kw",
")",
"for",
"child",
"in",
"self",
".",
"get_all_handleable",
"(",
")",
"if",
"_is_parent_of",
"(",
"device",
",",
"child",
")",
"]",
"results",
"=",
"await",
"gather",
"(",
"*",
"tasks",
")",
"success",
"=",
"all",
"(",
"results",
")",
"else",
":",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'not removing {0}: unhandled device'",
",",
"device",
")",
")",
"success",
"=",
"False",
"# if these operations work, everything is fine, we can return True:",
"if",
"lock",
"and",
"device",
".",
"is_luks_cleartext",
":",
"device",
"=",
"device",
".",
"luks_cleartext_slave",
"if",
"self",
".",
"is_handleable",
"(",
"device",
")",
":",
"success",
"=",
"await",
"self",
".",
"lock",
"(",
"device",
")",
"if",
"eject",
":",
"success",
"=",
"await",
"self",
".",
"eject",
"(",
"device",
")",
"if",
"(",
"detach",
"or",
"detach",
"is",
"None",
")",
"and",
"device",
".",
"is_loop",
":",
"success",
"=",
"await",
"self",
".",
"delete",
"(",
"device",
",",
"remove",
"=",
"False",
")",
"elif",
"detach",
":",
"success",
"=",
"await",
"self",
".",
"detach",
"(",
"device",
")",
"return",
"success"
] | Unmount or lock the device depending on device type.
:param device: device object, block device path or mount path
:param bool force: recursively remove all child devices
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lock: lock the associated LUKS cleartext slave
:returns: whether all attempted operations succeeded | [
"Unmount",
"or",
"lock",
"the",
"device",
"depending",
"on",
"device",
"type",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L399-L444 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.eject | async def eject(self, device, force=False):
"""
Eject a device after unmounting all its mounted filesystems.
:param device: device object, block device path or mount path
:param bool force: remove child devices before trying to eject
:returns: whether the operation succeeded
"""
device = self._find_device(device)
if not self.is_handleable(device):
self._log.warn(_('not ejecting {0}: unhandled device'))
return False
drive = device.drive
if not (drive.is_drive and drive.is_ejectable):
self._log.warn(_('not ejecting {0}: drive not ejectable', drive))
return False
if force:
# Can't autoremove 'device.drive', because that will be filtered
# due to block=False:
await self.auto_remove(device.root, force=True)
self._log.debug(_('ejecting {0}', device))
await drive.eject()
self._log.info(_('ejected {0}', device))
return True | python | async def eject(self, device, force=False):
"""
Eject a device after unmounting all its mounted filesystems.
:param device: device object, block device path or mount path
:param bool force: remove child devices before trying to eject
:returns: whether the operation succeeded
"""
device = self._find_device(device)
if not self.is_handleable(device):
self._log.warn(_('not ejecting {0}: unhandled device'))
return False
drive = device.drive
if not (drive.is_drive and drive.is_ejectable):
self._log.warn(_('not ejecting {0}: drive not ejectable', drive))
return False
if force:
# Can't autoremove 'device.drive', because that will be filtered
# due to block=False:
await self.auto_remove(device.root, force=True)
self._log.debug(_('ejecting {0}', device))
await drive.eject()
self._log.info(_('ejected {0}', device))
return True | [
"async",
"def",
"eject",
"(",
"self",
",",
"device",
",",
"force",
"=",
"False",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not ejecting {0}: unhandled device'",
")",
")",
"return",
"False",
"drive",
"=",
"device",
".",
"drive",
"if",
"not",
"(",
"drive",
".",
"is_drive",
"and",
"drive",
".",
"is_ejectable",
")",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not ejecting {0}: drive not ejectable'",
",",
"drive",
")",
")",
"return",
"False",
"if",
"force",
":",
"# Can't autoremove 'device.drive', because that will be filtered",
"# due to block=False:",
"await",
"self",
".",
"auto_remove",
"(",
"device",
".",
"root",
",",
"force",
"=",
"True",
")",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'ejecting {0}'",
",",
"device",
")",
")",
"await",
"drive",
".",
"eject",
"(",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'ejected {0}'",
",",
"device",
")",
")",
"return",
"True"
] | Eject a device after unmounting all its mounted filesystems.
:param device: device object, block device path or mount path
:param bool force: remove child devices before trying to eject
:returns: whether the operation succeeded | [
"Eject",
"a",
"device",
"after",
"unmounting",
"all",
"its",
"mounted",
"filesystems",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L496-L519 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.detach | async def detach(self, device, force=False):
"""
Detach a device after unmounting all its mounted filesystems.
:param device: device object, block device path or mount path
:param bool force: remove child devices before trying to detach
:returns: whether the operation succeeded
"""
device = self._find_device(device)
if not self.is_handleable(device):
self._log.warn(_('not detaching {0}: unhandled device', device))
return False
drive = device.root
if not drive.is_detachable:
self._log.warn(_('not detaching {0}: drive not detachable', drive))
return False
if force:
await self.auto_remove(drive, force=True)
self._log.debug(_('detaching {0}', device))
await drive.detach()
self._log.info(_('detached {0}', device))
return True | python | async def detach(self, device, force=False):
"""
Detach a device after unmounting all its mounted filesystems.
:param device: device object, block device path or mount path
:param bool force: remove child devices before trying to detach
:returns: whether the operation succeeded
"""
device = self._find_device(device)
if not self.is_handleable(device):
self._log.warn(_('not detaching {0}: unhandled device', device))
return False
drive = device.root
if not drive.is_detachable:
self._log.warn(_('not detaching {0}: drive not detachable', drive))
return False
if force:
await self.auto_remove(drive, force=True)
self._log.debug(_('detaching {0}', device))
await drive.detach()
self._log.info(_('detached {0}', device))
return True | [
"async",
"def",
"detach",
"(",
"self",
",",
"device",
",",
"force",
"=",
"False",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not detaching {0}: unhandled device'",
",",
"device",
")",
")",
"return",
"False",
"drive",
"=",
"device",
".",
"root",
"if",
"not",
"drive",
".",
"is_detachable",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not detaching {0}: drive not detachable'",
",",
"drive",
")",
")",
"return",
"False",
"if",
"force",
":",
"await",
"self",
".",
"auto_remove",
"(",
"drive",
",",
"force",
"=",
"True",
")",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'detaching {0}'",
",",
"device",
")",
")",
"await",
"drive",
".",
"detach",
"(",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'detached {0}'",
",",
"device",
")",
")",
"return",
"True"
] | Detach a device after unmounting all its mounted filesystems.
:param device: device object, block device path or mount path
:param bool force: remove child devices before trying to detach
:returns: whether the operation succeeded | [
"Detach",
"a",
"device",
"after",
"unmounting",
"all",
"its",
"mounted",
"filesystems",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L522-L543 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.add_all | async def add_all(self, recursive=False):
"""
Add all handleable devices that available at start.
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded
"""
tasks = [self.auto_add(device, recursive=recursive)
for device in self.get_all_handleable_leaves()]
results = await gather(*tasks)
success = all(results)
return success | python | async def add_all(self, recursive=False):
"""
Add all handleable devices that available at start.
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded
"""
tasks = [self.auto_add(device, recursive=recursive)
for device in self.get_all_handleable_leaves()]
results = await gather(*tasks)
success = all(results)
return success | [
"async",
"def",
"add_all",
"(",
"self",
",",
"recursive",
"=",
"False",
")",
":",
"tasks",
"=",
"[",
"self",
".",
"auto_add",
"(",
"device",
",",
"recursive",
"=",
"recursive",
")",
"for",
"device",
"in",
"self",
".",
"get_all_handleable_leaves",
"(",
")",
"]",
"results",
"=",
"await",
"gather",
"(",
"*",
"tasks",
")",
"success",
"=",
"all",
"(",
"results",
")",
"return",
"success"
] | Add all handleable devices that available at start.
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded | [
"Add",
"all",
"handleable",
"devices",
"that",
"available",
"at",
"start",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L546-L557 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.remove_all | async def remove_all(self, detach=False, eject=False, lock=False):
"""
Remove all filesystems handleable by udiskie.
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lock: lock the associated LUKS cleartext slave
:returns: whether all attempted operations succeeded
"""
kw = dict(force=True, detach=detach, eject=eject, lock=lock)
tasks = [self.auto_remove(device, **kw)
for device in self.get_all_handleable_roots()]
results = await gather(*tasks)
success = all(results)
return success | python | async def remove_all(self, detach=False, eject=False, lock=False):
"""
Remove all filesystems handleable by udiskie.
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lock: lock the associated LUKS cleartext slave
:returns: whether all attempted operations succeeded
"""
kw = dict(force=True, detach=detach, eject=eject, lock=lock)
tasks = [self.auto_remove(device, **kw)
for device in self.get_all_handleable_roots()]
results = await gather(*tasks)
success = all(results)
return success | [
"async",
"def",
"remove_all",
"(",
"self",
",",
"detach",
"=",
"False",
",",
"eject",
"=",
"False",
",",
"lock",
"=",
"False",
")",
":",
"kw",
"=",
"dict",
"(",
"force",
"=",
"True",
",",
"detach",
"=",
"detach",
",",
"eject",
"=",
"eject",
",",
"lock",
"=",
"lock",
")",
"tasks",
"=",
"[",
"self",
".",
"auto_remove",
"(",
"device",
",",
"*",
"*",
"kw",
")",
"for",
"device",
"in",
"self",
".",
"get_all_handleable_roots",
"(",
")",
"]",
"results",
"=",
"await",
"gather",
"(",
"*",
"tasks",
")",
"success",
"=",
"all",
"(",
"results",
")",
"return",
"success"
] | Remove all filesystems handleable by udiskie.
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lock: lock the associated LUKS cleartext slave
:returns: whether all attempted operations succeeded | [
"Remove",
"all",
"filesystems",
"handleable",
"by",
"udiskie",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L559-L573 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.losetup | async def losetup(self, image, read_only=True, offset=None, size=None,
no_part_scan=None):
"""
Setup a loop device.
:param str image: path of the image file
:param bool read_only:
:param int offset:
:param int size:
:param bool no_part_scan:
:returns: the device object for the loop device
"""
try:
device = self.udisks.find(image)
except FileNotFoundError:
pass
else:
self._log.info(_('not setting up {0}: already up', device))
return device
if not os.path.isfile(image):
self._log.error(_('not setting up {0}: not a file', image))
return None
self._log.debug(_('setting up {0}', image))
fd = os.open(image, os.O_RDONLY)
device = await self.udisks.loop_setup(fd, {
'offset': offset,
'size': size,
'read-only': read_only,
'no-part-scan': no_part_scan,
})
self._log.info(_('set up {0} as {1}', image,
device.device_presentation))
return device | python | async def losetup(self, image, read_only=True, offset=None, size=None,
no_part_scan=None):
"""
Setup a loop device.
:param str image: path of the image file
:param bool read_only:
:param int offset:
:param int size:
:param bool no_part_scan:
:returns: the device object for the loop device
"""
try:
device = self.udisks.find(image)
except FileNotFoundError:
pass
else:
self._log.info(_('not setting up {0}: already up', device))
return device
if not os.path.isfile(image):
self._log.error(_('not setting up {0}: not a file', image))
return None
self._log.debug(_('setting up {0}', image))
fd = os.open(image, os.O_RDONLY)
device = await self.udisks.loop_setup(fd, {
'offset': offset,
'size': size,
'read-only': read_only,
'no-part-scan': no_part_scan,
})
self._log.info(_('set up {0} as {1}', image,
device.device_presentation))
return device | [
"async",
"def",
"losetup",
"(",
"self",
",",
"image",
",",
"read_only",
"=",
"True",
",",
"offset",
"=",
"None",
",",
"size",
"=",
"None",
",",
"no_part_scan",
"=",
"None",
")",
":",
"try",
":",
"device",
"=",
"self",
".",
"udisks",
".",
"find",
"(",
"image",
")",
"except",
"FileNotFoundError",
":",
"pass",
"else",
":",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'not setting up {0}: already up'",
",",
"device",
")",
")",
"return",
"device",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"image",
")",
":",
"self",
".",
"_log",
".",
"error",
"(",
"_",
"(",
"'not setting up {0}: not a file'",
",",
"image",
")",
")",
"return",
"None",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'setting up {0}'",
",",
"image",
")",
")",
"fd",
"=",
"os",
".",
"open",
"(",
"image",
",",
"os",
".",
"O_RDONLY",
")",
"device",
"=",
"await",
"self",
".",
"udisks",
".",
"loop_setup",
"(",
"fd",
",",
"{",
"'offset'",
":",
"offset",
",",
"'size'",
":",
"size",
",",
"'read-only'",
":",
"read_only",
",",
"'no-part-scan'",
":",
"no_part_scan",
",",
"}",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'set up {0} as {1}'",
",",
"image",
",",
"device",
".",
"device_presentation",
")",
")",
"return",
"device"
] | Setup a loop device.
:param str image: path of the image file
:param bool read_only:
:param int offset:
:param int size:
:param bool no_part_scan:
:returns: the device object for the loop device | [
"Setup",
"a",
"loop",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L576-L608 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.delete | async def delete(self, device, remove=True):
"""
Detach the loop device.
:param device: device object, block device path or mount path
:param bool remove: whether to unmount the partition etc.
:returns: whether the loop device is deleted
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_loop:
self._log.warn(_('not deleting {0}: unhandled device', device))
return False
if remove:
await self.auto_remove(device, force=True)
self._log.debug(_('deleting {0}', device))
await device.delete()
self._log.info(_('deleted {0}', device))
return True | python | async def delete(self, device, remove=True):
"""
Detach the loop device.
:param device: device object, block device path or mount path
:param bool remove: whether to unmount the partition etc.
:returns: whether the loop device is deleted
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_loop:
self._log.warn(_('not deleting {0}: unhandled device', device))
return False
if remove:
await self.auto_remove(device, force=True)
self._log.debug(_('deleting {0}', device))
await device.delete()
self._log.info(_('deleted {0}', device))
return True | [
"async",
"def",
"delete",
"(",
"self",
",",
"device",
",",
"remove",
"=",
"True",
")",
":",
"device",
"=",
"self",
".",
"_find_device",
"(",
"device",
")",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
"or",
"not",
"device",
".",
"is_loop",
":",
"self",
".",
"_log",
".",
"warn",
"(",
"_",
"(",
"'not deleting {0}: unhandled device'",
",",
"device",
")",
")",
"return",
"False",
"if",
"remove",
":",
"await",
"self",
".",
"auto_remove",
"(",
"device",
",",
"force",
"=",
"True",
")",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'deleting {0}'",
",",
"device",
")",
")",
"await",
"device",
".",
"delete",
"(",
")",
"self",
".",
"_log",
".",
"info",
"(",
"_",
"(",
"'deleted {0}'",
",",
"device",
")",
")",
"return",
"True"
] | Detach the loop device.
:param device: device object, block device path or mount path
:param bool remove: whether to unmount the partition etc.
:returns: whether the loop device is deleted | [
"Detach",
"the",
"loop",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L611-L628 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.is_handleable | def is_handleable(self, device):
# TODO: handle pathes in first argument
"""
Check whether this device should be handled by udiskie.
:param device: device object, block device path or mount path
:returns: handleability
Currently this just means that the device is removable and holds a
filesystem or the device is a LUKS encrypted volume.
"""
ignored = self._ignore_device(device)
# propagate handleability of parent devices:
if ignored is None and device is not None:
return self.is_handleable(_get_parent(device))
return not ignored | python | def is_handleable(self, device):
# TODO: handle pathes in first argument
"""
Check whether this device should be handled by udiskie.
:param device: device object, block device path or mount path
:returns: handleability
Currently this just means that the device is removable and holds a
filesystem or the device is a LUKS encrypted volume.
"""
ignored = self._ignore_device(device)
# propagate handleability of parent devices:
if ignored is None and device is not None:
return self.is_handleable(_get_parent(device))
return not ignored | [
"def",
"is_handleable",
"(",
"self",
",",
"device",
")",
":",
"# TODO: handle pathes in first argument",
"ignored",
"=",
"self",
".",
"_ignore_device",
"(",
"device",
")",
"# propagate handleability of parent devices:",
"if",
"ignored",
"is",
"None",
"and",
"device",
"is",
"not",
"None",
":",
"return",
"self",
".",
"is_handleable",
"(",
"_get_parent",
"(",
"device",
")",
")",
"return",
"not",
"ignored"
] | Check whether this device should be handled by udiskie.
:param device: device object, block device path or mount path
:returns: handleability
Currently this just means that the device is removable and holds a
filesystem or the device is a LUKS encrypted volume. | [
"Check",
"whether",
"this",
"device",
"should",
"be",
"handled",
"by",
"udiskie",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L631-L646 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.is_addable | def is_addable(self, device, automount=True):
"""Check if device can be added with ``auto_add``."""
if not self.is_automount(device, automount):
return False
if device.is_filesystem:
return not device.is_mounted
if device.is_crypto:
return self._prompt and not device.is_unlocked
if device.is_partition_table:
return any(self.is_addable(dev)
for dev in self.get_all_handleable()
if dev.partition_slave == device)
return False | python | def is_addable(self, device, automount=True):
"""Check if device can be added with ``auto_add``."""
if not self.is_automount(device, automount):
return False
if device.is_filesystem:
return not device.is_mounted
if device.is_crypto:
return self._prompt and not device.is_unlocked
if device.is_partition_table:
return any(self.is_addable(dev)
for dev in self.get_all_handleable()
if dev.partition_slave == device)
return False | [
"def",
"is_addable",
"(",
"self",
",",
"device",
",",
"automount",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"is_automount",
"(",
"device",
",",
"automount",
")",
":",
"return",
"False",
"if",
"device",
".",
"is_filesystem",
":",
"return",
"not",
"device",
".",
"is_mounted",
"if",
"device",
".",
"is_crypto",
":",
"return",
"self",
".",
"_prompt",
"and",
"not",
"device",
".",
"is_unlocked",
"if",
"device",
".",
"is_partition_table",
":",
"return",
"any",
"(",
"self",
".",
"is_addable",
"(",
"dev",
")",
"for",
"dev",
"in",
"self",
".",
"get_all_handleable",
"(",
")",
"if",
"dev",
".",
"partition_slave",
"==",
"device",
")",
"return",
"False"
] | Check if device can be added with ``auto_add``. | [
"Check",
"if",
"device",
"can",
"be",
"added",
"with",
"auto_add",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L656-L668 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.is_removable | def is_removable(self, device):
"""Check if device can be removed with ``auto_remove``."""
if not self.is_handleable(device):
return False
if device.is_filesystem:
return device.is_mounted
if device.is_crypto:
return device.is_unlocked
if device.is_partition_table or device.is_drive:
return any(self.is_removable(dev)
for dev in self.get_all_handleable()
if _is_parent_of(device, dev))
return False | python | def is_removable(self, device):
"""Check if device can be removed with ``auto_remove``."""
if not self.is_handleable(device):
return False
if device.is_filesystem:
return device.is_mounted
if device.is_crypto:
return device.is_unlocked
if device.is_partition_table or device.is_drive:
return any(self.is_removable(dev)
for dev in self.get_all_handleable()
if _is_parent_of(device, dev))
return False | [
"def",
"is_removable",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"False",
"if",
"device",
".",
"is_filesystem",
":",
"return",
"device",
".",
"is_mounted",
"if",
"device",
".",
"is_crypto",
":",
"return",
"device",
".",
"is_unlocked",
"if",
"device",
".",
"is_partition_table",
"or",
"device",
".",
"is_drive",
":",
"return",
"any",
"(",
"self",
".",
"is_removable",
"(",
"dev",
")",
"for",
"dev",
"in",
"self",
".",
"get_all_handleable",
"(",
")",
"if",
"_is_parent_of",
"(",
"device",
",",
"dev",
")",
")",
"return",
"False"
] | Check if device can be removed with ``auto_remove``. | [
"Check",
"if",
"device",
"can",
"be",
"removed",
"with",
"auto_remove",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L670-L682 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.get_all_handleable | def get_all_handleable(self):
"""Get list of all known handleable devices."""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._sort_key)
if not node.ignored and node.device] | python | def get_all_handleable(self):
"""Get list of all known handleable devices."""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._sort_key)
if not node.ignored and node.device] | [
"def",
"get_all_handleable",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"get_device_tree",
"(",
")",
"return",
"[",
"node",
".",
"device",
"for",
"node",
"in",
"sorted",
"(",
"nodes",
".",
"values",
"(",
")",
",",
"key",
"=",
"DevNode",
".",
"_sort_key",
")",
"if",
"not",
"node",
".",
"ignored",
"and",
"node",
".",
"device",
"]"
] | Get list of all known handleable devices. | [
"Get",
"list",
"of",
"all",
"known",
"handleable",
"devices",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L684-L689 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.get_all_handleable_roots | def get_all_handleable_roots(self):
"""
Get list of all handleable devices, return only those that represent
root nodes within the filtered device tree.
"""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._sort_key)
if not node.ignored and node.device
and (node.root == '/' or nodes[node.root].ignored)] | python | def get_all_handleable_roots(self):
"""
Get list of all handleable devices, return only those that represent
root nodes within the filtered device tree.
"""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._sort_key)
if not node.ignored and node.device
and (node.root == '/' or nodes[node.root].ignored)] | [
"def",
"get_all_handleable_roots",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"get_device_tree",
"(",
")",
"return",
"[",
"node",
".",
"device",
"for",
"node",
"in",
"sorted",
"(",
"nodes",
".",
"values",
"(",
")",
",",
"key",
"=",
"DevNode",
".",
"_sort_key",
")",
"if",
"not",
"node",
".",
"ignored",
"and",
"node",
".",
"device",
"and",
"(",
"node",
".",
"root",
"==",
"'/'",
"or",
"nodes",
"[",
"node",
".",
"root",
"]",
".",
"ignored",
")",
"]"
] | Get list of all handleable devices, return only those that represent
root nodes within the filtered device tree. | [
"Get",
"list",
"of",
"all",
"handleable",
"devices",
"return",
"only",
"those",
"that",
"represent",
"root",
"nodes",
"within",
"the",
"filtered",
"device",
"tree",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L691-L700 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.get_all_handleable_leaves | def get_all_handleable_leaves(self):
"""
Get list of all handleable devices, return only those that represent
leaf nodes within the filtered device tree.
"""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._sort_key)
if not node.ignored and node.device
and all(child.ignored for child in node.children)] | python | def get_all_handleable_leaves(self):
"""
Get list of all handleable devices, return only those that represent
leaf nodes within the filtered device tree.
"""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._sort_key)
if not node.ignored and node.device
and all(child.ignored for child in node.children)] | [
"def",
"get_all_handleable_leaves",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"get_device_tree",
"(",
")",
"return",
"[",
"node",
".",
"device",
"for",
"node",
"in",
"sorted",
"(",
"nodes",
".",
"values",
"(",
")",
",",
"key",
"=",
"DevNode",
".",
"_sort_key",
")",
"if",
"not",
"node",
".",
"ignored",
"and",
"node",
".",
"device",
"and",
"all",
"(",
"child",
".",
"ignored",
"for",
"child",
"in",
"node",
".",
"children",
")",
"]"
] | Get list of all handleable devices, return only those that represent
leaf nodes within the filtered device tree. | [
"Get",
"list",
"of",
"all",
"handleable",
"devices",
"return",
"only",
"those",
"that",
"represent",
"leaf",
"nodes",
"within",
"the",
"filtered",
"device",
"tree",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L702-L711 | train |
coldfix/udiskie | udiskie/mount.py | Mounter.get_device_tree | def get_device_tree(self):
"""Get a tree of all devices."""
root = DevNode(None, None, [], None)
device_nodes = {
dev.object_path: DevNode(dev, dev.parent_object_path, [],
self._ignore_device(dev))
for dev in self.udisks
}
for node in device_nodes.values():
device_nodes.get(node.root, root).children.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.children.sort(key=DevNode._sort_key)
# use parent as fallback, update top->down:
def propagate_ignored(node):
for child in node.children:
if child.ignored is None:
child.ignored = node.ignored
propagate_ignored(child)
propagate_ignored(root)
return device_nodes | python | def get_device_tree(self):
"""Get a tree of all devices."""
root = DevNode(None, None, [], None)
device_nodes = {
dev.object_path: DevNode(dev, dev.parent_object_path, [],
self._ignore_device(dev))
for dev in self.udisks
}
for node in device_nodes.values():
device_nodes.get(node.root, root).children.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.children.sort(key=DevNode._sort_key)
# use parent as fallback, update top->down:
def propagate_ignored(node):
for child in node.children:
if child.ignored is None:
child.ignored = node.ignored
propagate_ignored(child)
propagate_ignored(root)
return device_nodes | [
"def",
"get_device_tree",
"(",
"self",
")",
":",
"root",
"=",
"DevNode",
"(",
"None",
",",
"None",
",",
"[",
"]",
",",
"None",
")",
"device_nodes",
"=",
"{",
"dev",
".",
"object_path",
":",
"DevNode",
"(",
"dev",
",",
"dev",
".",
"parent_object_path",
",",
"[",
"]",
",",
"self",
".",
"_ignore_device",
"(",
"dev",
")",
")",
"for",
"dev",
"in",
"self",
".",
"udisks",
"}",
"for",
"node",
"in",
"device_nodes",
".",
"values",
"(",
")",
":",
"device_nodes",
".",
"get",
"(",
"node",
".",
"root",
",",
"root",
")",
".",
"children",
".",
"append",
"(",
"node",
")",
"device_nodes",
"[",
"'/'",
"]",
"=",
"root",
"for",
"node",
"in",
"device_nodes",
".",
"values",
"(",
")",
":",
"node",
".",
"children",
".",
"sort",
"(",
"key",
"=",
"DevNode",
".",
"_sort_key",
")",
"# use parent as fallback, update top->down:",
"def",
"propagate_ignored",
"(",
"node",
")",
":",
"for",
"child",
"in",
"node",
".",
"children",
":",
"if",
"child",
".",
"ignored",
"is",
"None",
":",
"child",
".",
"ignored",
"=",
"node",
".",
"ignored",
"propagate_ignored",
"(",
"child",
")",
"propagate_ignored",
"(",
"root",
")",
"return",
"device_nodes"
] | Get a tree of all devices. | [
"Get",
"a",
"tree",
"of",
"all",
"devices",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L713-L734 | train |
coldfix/udiskie | udiskie/mount.py | DeviceActions.detect | def detect(self, root_device='/'):
"""
Detect all currently known devices.
:param str root_device: object path of root device to return
:returns: root node of device hierarchy
"""
root = Device(None, [], None, "", [])
device_nodes = dict(map(self._device_node,
self._mounter.get_all_handleable()))
# insert child devices as branches into their roots:
for node in device_nodes.values():
device_nodes.get(node.root, root).branches.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.branches.sort(key=lambda node: node.label)
return device_nodes[root_device] | python | def detect(self, root_device='/'):
"""
Detect all currently known devices.
:param str root_device: object path of root device to return
:returns: root node of device hierarchy
"""
root = Device(None, [], None, "", [])
device_nodes = dict(map(self._device_node,
self._mounter.get_all_handleable()))
# insert child devices as branches into their roots:
for node in device_nodes.values():
device_nodes.get(node.root, root).branches.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.branches.sort(key=lambda node: node.label)
return device_nodes[root_device] | [
"def",
"detect",
"(",
"self",
",",
"root_device",
"=",
"'/'",
")",
":",
"root",
"=",
"Device",
"(",
"None",
",",
"[",
"]",
",",
"None",
",",
"\"\"",
",",
"[",
"]",
")",
"device_nodes",
"=",
"dict",
"(",
"map",
"(",
"self",
".",
"_device_node",
",",
"self",
".",
"_mounter",
".",
"get_all_handleable",
"(",
")",
")",
")",
"# insert child devices as branches into their roots:",
"for",
"node",
"in",
"device_nodes",
".",
"values",
"(",
")",
":",
"device_nodes",
".",
"get",
"(",
"node",
".",
"root",
",",
"root",
")",
".",
"branches",
".",
"append",
"(",
"node",
")",
"device_nodes",
"[",
"'/'",
"]",
"=",
"root",
"for",
"node",
"in",
"device_nodes",
".",
"values",
"(",
")",
":",
"node",
".",
"branches",
".",
"sort",
"(",
"key",
"=",
"lambda",
"node",
":",
"node",
".",
"label",
")",
"return",
"device_nodes",
"[",
"root_device",
"]"
] | Detect all currently known devices.
:param str root_device: object path of root device to return
:returns: root node of device hierarchy | [
"Detect",
"all",
"currently",
"known",
"devices",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L785-L801 | train |
coldfix/udiskie | udiskie/mount.py | DeviceActions._get_device_methods | def _get_device_methods(self, device):
"""Return an iterable over all available methods the device has."""
if device.is_filesystem:
if device.is_mounted:
if self._mounter._browser:
yield 'browse'
if self._mounter._terminal:
yield 'terminal'
yield 'unmount'
else:
yield 'mount'
elif device.is_crypto:
if device.is_unlocked:
yield 'lock'
else:
yield 'unlock'
cache = self._mounter._cache
if cache and device in cache:
yield 'forget_password'
if device.is_ejectable and device.has_media:
yield 'eject'
if device.is_detachable:
yield 'detach'
if device.is_loop:
yield 'delete' | python | def _get_device_methods(self, device):
"""Return an iterable over all available methods the device has."""
if device.is_filesystem:
if device.is_mounted:
if self._mounter._browser:
yield 'browse'
if self._mounter._terminal:
yield 'terminal'
yield 'unmount'
else:
yield 'mount'
elif device.is_crypto:
if device.is_unlocked:
yield 'lock'
else:
yield 'unlock'
cache = self._mounter._cache
if cache and device in cache:
yield 'forget_password'
if device.is_ejectable and device.has_media:
yield 'eject'
if device.is_detachable:
yield 'detach'
if device.is_loop:
yield 'delete' | [
"def",
"_get_device_methods",
"(",
"self",
",",
"device",
")",
":",
"if",
"device",
".",
"is_filesystem",
":",
"if",
"device",
".",
"is_mounted",
":",
"if",
"self",
".",
"_mounter",
".",
"_browser",
":",
"yield",
"'browse'",
"if",
"self",
".",
"_mounter",
".",
"_terminal",
":",
"yield",
"'terminal'",
"yield",
"'unmount'",
"else",
":",
"yield",
"'mount'",
"elif",
"device",
".",
"is_crypto",
":",
"if",
"device",
".",
"is_unlocked",
":",
"yield",
"'lock'",
"else",
":",
"yield",
"'unlock'",
"cache",
"=",
"self",
".",
"_mounter",
".",
"_cache",
"if",
"cache",
"and",
"device",
"in",
"cache",
":",
"yield",
"'forget_password'",
"if",
"device",
".",
"is_ejectable",
"and",
"device",
".",
"has_media",
":",
"yield",
"'eject'",
"if",
"device",
".",
"is_detachable",
":",
"yield",
"'detach'",
"if",
"device",
".",
"is_loop",
":",
"yield",
"'delete'"
] | Return an iterable over all available methods the device has. | [
"Return",
"an",
"iterable",
"over",
"all",
"available",
"methods",
"the",
"device",
"has",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L803-L827 | train |
coldfix/udiskie | udiskie/mount.py | DeviceActions._device_node | def _device_node(self, device):
"""Create an empty menu node for the specified device."""
label = device.ui_label
dev_label = device.ui_device_label
# determine available methods
methods = [Action(method, device,
self._labels[method].format(label, dev_label),
partial(self._actions[method], device))
for method in self._get_device_methods(device)]
# find the root device:
root = device.parent_object_path
# in this first step leave branches empty
return device.object_path, Device(root, [], device, dev_label, methods) | python | def _device_node(self, device):
"""Create an empty menu node for the specified device."""
label = device.ui_label
dev_label = device.ui_device_label
# determine available methods
methods = [Action(method, device,
self._labels[method].format(label, dev_label),
partial(self._actions[method], device))
for method in self._get_device_methods(device)]
# find the root device:
root = device.parent_object_path
# in this first step leave branches empty
return device.object_path, Device(root, [], device, dev_label, methods) | [
"def",
"_device_node",
"(",
"self",
",",
"device",
")",
":",
"label",
"=",
"device",
".",
"ui_label",
"dev_label",
"=",
"device",
".",
"ui_device_label",
"# determine available methods",
"methods",
"=",
"[",
"Action",
"(",
"method",
",",
"device",
",",
"self",
".",
"_labels",
"[",
"method",
"]",
".",
"format",
"(",
"label",
",",
"dev_label",
")",
",",
"partial",
"(",
"self",
".",
"_actions",
"[",
"method",
"]",
",",
"device",
")",
")",
"for",
"method",
"in",
"self",
".",
"_get_device_methods",
"(",
"device",
")",
"]",
"# find the root device:",
"root",
"=",
"device",
".",
"parent_object_path",
"# in this first step leave branches empty",
"return",
"device",
".",
"object_path",
",",
"Device",
"(",
"root",
",",
"[",
"]",
",",
"device",
",",
"dev_label",
",",
"methods",
")"
] | Create an empty menu node for the specified device. | [
"Create",
"an",
"empty",
"menu",
"node",
"for",
"the",
"specified",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L829-L841 | train |
coldfix/udiskie | udiskie/common.py | samefile | def samefile(a: str, b: str) -> bool:
"""Check if two pathes represent the same file."""
try:
return os.path.samefile(a, b)
except OSError:
return os.path.normpath(a) == os.path.normpath(b) | python | def samefile(a: str, b: str) -> bool:
"""Check if two pathes represent the same file."""
try:
return os.path.samefile(a, b)
except OSError:
return os.path.normpath(a) == os.path.normpath(b) | [
"def",
"samefile",
"(",
"a",
":",
"str",
",",
"b",
":",
"str",
")",
"->",
"bool",
":",
"try",
":",
"return",
"os",
".",
"path",
".",
"samefile",
"(",
"a",
",",
"b",
")",
"except",
"OSError",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"a",
")",
"==",
"os",
".",
"path",
".",
"normpath",
"(",
"b",
")"
] | Check if two pathes represent the same file. | [
"Check",
"if",
"two",
"pathes",
"represent",
"the",
"same",
"file",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L55-L60 | train |
coldfix/udiskie | udiskie/common.py | sameuuid | def sameuuid(a: str, b: str) -> bool:
"""Compare two UUIDs."""
return a and b and a.lower() == b.lower() | python | def sameuuid(a: str, b: str) -> bool:
"""Compare two UUIDs."""
return a and b and a.lower() == b.lower() | [
"def",
"sameuuid",
"(",
"a",
":",
"str",
",",
"b",
":",
"str",
")",
"->",
"bool",
":",
"return",
"a",
"and",
"b",
"and",
"a",
".",
"lower",
"(",
")",
"==",
"b",
".",
"lower",
"(",
")"
] | Compare two UUIDs. | [
"Compare",
"two",
"UUIDs",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L63-L65 | train |
coldfix/udiskie | udiskie/common.py | extend | def extend(a: dict, b: dict) -> dict:
"""Merge two dicts and return a new dict. Much like subclassing works."""
res = a.copy()
res.update(b)
return res | python | def extend(a: dict, b: dict) -> dict:
"""Merge two dicts and return a new dict. Much like subclassing works."""
res = a.copy()
res.update(b)
return res | [
"def",
"extend",
"(",
"a",
":",
"dict",
",",
"b",
":",
"dict",
")",
"->",
"dict",
":",
"res",
"=",
"a",
".",
"copy",
"(",
")",
"res",
".",
"update",
"(",
"b",
")",
"return",
"res"
] | Merge two dicts and return a new dict. Much like subclassing works. | [
"Merge",
"two",
"dicts",
"and",
"return",
"a",
"new",
"dict",
".",
"Much",
"like",
"subclassing",
"works",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L74-L78 | train |
coldfix/udiskie | udiskie/common.py | decode_ay | def decode_ay(ay):
"""Convert binary blob from DBus queries to strings."""
if ay is None:
return ''
elif isinstance(ay, str):
return ay
elif isinstance(ay, bytes):
return ay.decode('utf-8')
else:
# dbus.Array([dbus.Byte]) or any similar sequence type:
return bytearray(ay).rstrip(bytearray((0,))).decode('utf-8') | python | def decode_ay(ay):
"""Convert binary blob from DBus queries to strings."""
if ay is None:
return ''
elif isinstance(ay, str):
return ay
elif isinstance(ay, bytes):
return ay.decode('utf-8')
else:
# dbus.Array([dbus.Byte]) or any similar sequence type:
return bytearray(ay).rstrip(bytearray((0,))).decode('utf-8') | [
"def",
"decode_ay",
"(",
"ay",
")",
":",
"if",
"ay",
"is",
"None",
":",
"return",
"''",
"elif",
"isinstance",
"(",
"ay",
",",
"str",
")",
":",
"return",
"ay",
"elif",
"isinstance",
"(",
"ay",
",",
"bytes",
")",
":",
"return",
"ay",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"# dbus.Array([dbus.Byte]) or any similar sequence type:",
"return",
"bytearray",
"(",
"ay",
")",
".",
"rstrip",
"(",
"bytearray",
"(",
"(",
"0",
",",
")",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | Convert binary blob from DBus queries to strings. | [
"Convert",
"binary",
"blob",
"from",
"DBus",
"queries",
"to",
"strings",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L151-L161 | train |
coldfix/udiskie | udiskie/common.py | format_exc | def format_exc(*exc_info):
"""Show exception with traceback."""
typ, exc, tb = exc_info or sys.exc_info()
error = traceback.format_exception(typ, exc, tb)
return "".join(error) | python | def format_exc(*exc_info):
"""Show exception with traceback."""
typ, exc, tb = exc_info or sys.exc_info()
error = traceback.format_exception(typ, exc, tb)
return "".join(error) | [
"def",
"format_exc",
"(",
"*",
"exc_info",
")",
":",
"typ",
",",
"exc",
",",
"tb",
"=",
"exc_info",
"or",
"sys",
".",
"exc_info",
"(",
")",
"error",
"=",
"traceback",
".",
"format_exception",
"(",
"typ",
",",
"exc",
",",
"tb",
")",
"return",
"\"\"",
".",
"join",
"(",
"error",
")"
] | Show exception with traceback. | [
"Show",
"exception",
"with",
"traceback",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L170-L174 | train |
coldfix/udiskie | udiskie/common.py | Emitter.trigger | def trigger(self, event, *args):
"""Trigger event by name."""
for handler in self._event_handlers[event]:
handler(*args) | python | def trigger(self, event, *args):
"""Trigger event by name."""
for handler in self._event_handlers[event]:
handler(*args) | [
"def",
"trigger",
"(",
"self",
",",
"event",
",",
"*",
"args",
")",
":",
"for",
"handler",
"in",
"self",
".",
"_event_handlers",
"[",
"event",
"]",
":",
"handler",
"(",
"*",
"args",
")"
] | Trigger event by name. | [
"Trigger",
"event",
"by",
"name",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/common.py#L41-L44 | train |
coldfix/udiskie | udiskie/cli.py | Choice._check | def _check(self, args):
"""Exit in case of multiple exclusive arguments."""
if sum(bool(args[arg]) for arg in self._mapping) > 1:
raise DocoptExit(_('These options are mutually exclusive: {0}',
', '.join(self._mapping))) | python | def _check(self, args):
"""Exit in case of multiple exclusive arguments."""
if sum(bool(args[arg]) for arg in self._mapping) > 1:
raise DocoptExit(_('These options are mutually exclusive: {0}',
', '.join(self._mapping))) | [
"def",
"_check",
"(",
"self",
",",
"args",
")",
":",
"if",
"sum",
"(",
"bool",
"(",
"args",
"[",
"arg",
"]",
")",
"for",
"arg",
"in",
"self",
".",
"_mapping",
")",
">",
"1",
":",
"raise",
"DocoptExit",
"(",
"_",
"(",
"'These options are mutually exclusive: {0}'",
",",
"', '",
".",
"join",
"(",
"self",
".",
"_mapping",
")",
")",
")"
] | Exit in case of multiple exclusive arguments. | [
"Exit",
"in",
"case",
"of",
"multiple",
"exclusive",
"arguments",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L43-L47 | train |
coldfix/udiskie | udiskie/cli.py | _EntryPoint.program_options | def program_options(self, args):
"""Get program options from docopt parsed options."""
options = {}
for name, rule in self.option_rules.items():
val = rule(args)
if val is not None:
options[name] = val
return options | python | def program_options(self, args):
"""Get program options from docopt parsed options."""
options = {}
for name, rule in self.option_rules.items():
val = rule(args)
if val is not None:
options[name] = val
return options | [
"def",
"program_options",
"(",
"self",
",",
"args",
")",
":",
"options",
"=",
"{",
"}",
"for",
"name",
",",
"rule",
"in",
"self",
".",
"option_rules",
".",
"items",
"(",
")",
":",
"val",
"=",
"rule",
"(",
"args",
")",
"if",
"val",
"is",
"not",
"None",
":",
"options",
"[",
"name",
"]",
"=",
"val",
"return",
"options"
] | Get program options from docopt parsed options. | [
"Get",
"program",
"options",
"from",
"docopt",
"parsed",
"options",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L176-L183 | train |
coldfix/udiskie | udiskie/cli.py | _EntryPoint.run | def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self.exit_code
except KeyboardInterrupt:
return 1 | python | def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self.exit_code
except KeyboardInterrupt:
return 1 | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"exit_code",
"=",
"1",
"self",
".",
"mainloop",
"=",
"GLib",
".",
"MainLoop",
"(",
")",
"try",
":",
"future",
"=",
"ensure_future",
"(",
"self",
".",
"_start_async_tasks",
"(",
")",
")",
"future",
".",
"callbacks",
".",
"append",
"(",
"self",
".",
"set_exit_code",
")",
"self",
".",
"mainloop",
".",
"run",
"(",
")",
"return",
"self",
".",
"exit_code",
"except",
"KeyboardInterrupt",
":",
"return",
"1"
] | Run the main loop. Returns exit code. | [
"Run",
"the",
"main",
"loop",
".",
"Returns",
"exit",
"code",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L204-L214 | train |
coldfix/udiskie | udiskie/cli.py | _EntryPoint._start_async_tasks | async def _start_async_tasks(self):
"""Start asynchronous operations."""
try:
self.udisks = await udiskie.udisks2.Daemon.create()
results = await self._init()
return 0 if all(results) else 1
except Exception:
traceback.print_exc()
return 1
finally:
self.mainloop.quit() | python | async def _start_async_tasks(self):
"""Start asynchronous operations."""
try:
self.udisks = await udiskie.udisks2.Daemon.create()
results = await self._init()
return 0 if all(results) else 1
except Exception:
traceback.print_exc()
return 1
finally:
self.mainloop.quit() | [
"async",
"def",
"_start_async_tasks",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"udisks",
"=",
"await",
"udiskie",
".",
"udisks2",
".",
"Daemon",
".",
"create",
"(",
")",
"results",
"=",
"await",
"self",
".",
"_init",
"(",
")",
"return",
"0",
"if",
"all",
"(",
"results",
")",
"else",
"1",
"except",
"Exception",
":",
"traceback",
".",
"print_exc",
"(",
")",
"return",
"1",
"finally",
":",
"self",
".",
"mainloop",
".",
"quit",
"(",
")"
] | Start asynchronous operations. | [
"Start",
"asynchronous",
"operations",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/cli.py#L219-L229 | train |
coldfix/udiskie | udiskie/automount.py | AutoMounter.device_changed | def device_changed(self, old_state, new_state):
"""Mount newly mountable devices."""
# udisks2 sometimes adds empty devices and later updates them - which
# makes is_external become true at a time later than device_added:
if (self._mounter.is_addable(new_state)
and not self._mounter.is_addable(old_state)
and not self._mounter.is_removable(old_state)):
self.auto_add(new_state) | python | def device_changed(self, old_state, new_state):
"""Mount newly mountable devices."""
# udisks2 sometimes adds empty devices and later updates them - which
# makes is_external become true at a time later than device_added:
if (self._mounter.is_addable(new_state)
and not self._mounter.is_addable(old_state)
and not self._mounter.is_removable(old_state)):
self.auto_add(new_state) | [
"def",
"device_changed",
"(",
"self",
",",
"old_state",
",",
"new_state",
")",
":",
"# udisks2 sometimes adds empty devices and later updates them - which",
"# makes is_external become true at a time later than device_added:",
"if",
"(",
"self",
".",
"_mounter",
".",
"is_addable",
"(",
"new_state",
")",
"and",
"not",
"self",
".",
"_mounter",
".",
"is_addable",
"(",
"old_state",
")",
"and",
"not",
"self",
".",
"_mounter",
".",
"is_removable",
"(",
"old_state",
")",
")",
":",
"self",
".",
"auto_add",
"(",
"new_state",
")"
] | Mount newly mountable devices. | [
"Mount",
"newly",
"mountable",
"devices",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/automount.py#L41-L48 | train |
coldfix/udiskie | udiskie/dbus.py | connect_service | async def connect_service(bus_name, object_path, interface):
"""Connect to the service object on DBus, return InterfaceProxy."""
proxy = await proxy_new_for_bus(
Gio.BusType.SYSTEM,
Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES |
Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS,
info=None,
name=bus_name,
object_path=object_path,
interface_name=interface,
)
return InterfaceProxy(proxy) | python | async def connect_service(bus_name, object_path, interface):
"""Connect to the service object on DBus, return InterfaceProxy."""
proxy = await proxy_new_for_bus(
Gio.BusType.SYSTEM,
Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES |
Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS,
info=None,
name=bus_name,
object_path=object_path,
interface_name=interface,
)
return InterfaceProxy(proxy) | [
"async",
"def",
"connect_service",
"(",
"bus_name",
",",
"object_path",
",",
"interface",
")",
":",
"proxy",
"=",
"await",
"proxy_new_for_bus",
"(",
"Gio",
".",
"BusType",
".",
"SYSTEM",
",",
"Gio",
".",
"DBusProxyFlags",
".",
"DO_NOT_LOAD_PROPERTIES",
"|",
"Gio",
".",
"DBusProxyFlags",
".",
"DO_NOT_CONNECT_SIGNALS",
",",
"info",
"=",
"None",
",",
"name",
"=",
"bus_name",
",",
"object_path",
"=",
"object_path",
",",
"interface_name",
"=",
"interface",
",",
")",
"return",
"InterfaceProxy",
"(",
"proxy",
")"
] | Connect to the service object on DBus, return InterfaceProxy. | [
"Connect",
"to",
"the",
"service",
"object",
"on",
"DBus",
"return",
"InterfaceProxy",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/dbus.py#L286-L297 | train |
coldfix/udiskie | udiskie/dbus.py | InterfaceProxy.object | def object(self):
"""Get an ObjectProxy instanec for the underlying object."""
proxy = self._proxy
return ObjectProxy(proxy.get_connection(),
proxy.get_name(),
proxy.get_object_path()) | python | def object(self):
"""Get an ObjectProxy instanec for the underlying object."""
proxy = self._proxy
return ObjectProxy(proxy.get_connection(),
proxy.get_name(),
proxy.get_object_path()) | [
"def",
"object",
"(",
"self",
")",
":",
"proxy",
"=",
"self",
".",
"_proxy",
"return",
"ObjectProxy",
"(",
"proxy",
".",
"get_connection",
"(",
")",
",",
"proxy",
".",
"get_name",
"(",
")",
",",
"proxy",
".",
"get_object_path",
"(",
")",
")"
] | Get an ObjectProxy instanec for the underlying object. | [
"Get",
"an",
"ObjectProxy",
"instanec",
"for",
"the",
"underlying",
"object",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/dbus.py#L103-L108 | train |
coldfix/udiskie | udiskie/dbus.py | BusProxy.connect | def connect(self, interface, event, object_path, handler):
"""
Connect to a DBus signal. If ``object_path`` is None, subscribe for
all objects and invoke the callback with the object_path as its first
argument.
"""
if object_path:
def callback(connection, sender_name, object_path,
interface_name, signal_name, parameters):
return handler(*unpack_variant(parameters))
else:
def callback(connection, sender_name, object_path,
interface_name, signal_name, parameters):
return handler(object_path, *unpack_variant(parameters))
return self.connection.signal_subscribe(
self.bus_name,
interface,
event,
object_path,
None,
Gio.DBusSignalFlags.NONE,
callback,
) | python | def connect(self, interface, event, object_path, handler):
"""
Connect to a DBus signal. If ``object_path`` is None, subscribe for
all objects and invoke the callback with the object_path as its first
argument.
"""
if object_path:
def callback(connection, sender_name, object_path,
interface_name, signal_name, parameters):
return handler(*unpack_variant(parameters))
else:
def callback(connection, sender_name, object_path,
interface_name, signal_name, parameters):
return handler(object_path, *unpack_variant(parameters))
return self.connection.signal_subscribe(
self.bus_name,
interface,
event,
object_path,
None,
Gio.DBusSignalFlags.NONE,
callback,
) | [
"def",
"connect",
"(",
"self",
",",
"interface",
",",
"event",
",",
"object_path",
",",
"handler",
")",
":",
"if",
"object_path",
":",
"def",
"callback",
"(",
"connection",
",",
"sender_name",
",",
"object_path",
",",
"interface_name",
",",
"signal_name",
",",
"parameters",
")",
":",
"return",
"handler",
"(",
"*",
"unpack_variant",
"(",
"parameters",
")",
")",
"else",
":",
"def",
"callback",
"(",
"connection",
",",
"sender_name",
",",
"object_path",
",",
"interface_name",
",",
"signal_name",
",",
"parameters",
")",
":",
"return",
"handler",
"(",
"object_path",
",",
"*",
"unpack_variant",
"(",
"parameters",
")",
")",
"return",
"self",
".",
"connection",
".",
"signal_subscribe",
"(",
"self",
".",
"bus_name",
",",
"interface",
",",
"event",
",",
"object_path",
",",
"None",
",",
"Gio",
".",
"DBusSignalFlags",
".",
"NONE",
",",
"callback",
",",
")"
] | Connect to a DBus signal. If ``object_path`` is None, subscribe for
all objects and invoke the callback with the object_path as its first
argument. | [
"Connect",
"to",
"a",
"DBus",
"signal",
".",
"If",
"object_path",
"is",
"None",
"subscribe",
"for",
"all",
"objects",
"and",
"invoke",
"the",
"callback",
"with",
"the",
"object_path",
"as",
"its",
"first",
"argument",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/dbus.py#L212-L234 | train |
coldfix/udiskie | udiskie/depend.py | require_Gtk | def require_Gtk(min_version=2):
"""
Make sure Gtk is properly initialized.
:raises RuntimeError: if Gtk can not be properly initialized
"""
if not _in_X:
raise RuntimeError('Not in X session.')
if _has_Gtk < min_version:
raise RuntimeError('Module gi.repository.Gtk not available!')
if _has_Gtk == 2:
logging.getLogger(__name__).warn(
_("Missing runtime dependency GTK 3. Falling back to GTK 2 "
"for password prompt"))
from gi.repository import Gtk
# if we attempt to create any GUI elements with no X server running the
# program will just crash, so let's make a way to catch this case:
if not Gtk.init_check(None)[0]:
raise RuntimeError(_("X server not connected!"))
return Gtk | python | def require_Gtk(min_version=2):
"""
Make sure Gtk is properly initialized.
:raises RuntimeError: if Gtk can not be properly initialized
"""
if not _in_X:
raise RuntimeError('Not in X session.')
if _has_Gtk < min_version:
raise RuntimeError('Module gi.repository.Gtk not available!')
if _has_Gtk == 2:
logging.getLogger(__name__).warn(
_("Missing runtime dependency GTK 3. Falling back to GTK 2 "
"for password prompt"))
from gi.repository import Gtk
# if we attempt to create any GUI elements with no X server running the
# program will just crash, so let's make a way to catch this case:
if not Gtk.init_check(None)[0]:
raise RuntimeError(_("X server not connected!"))
return Gtk | [
"def",
"require_Gtk",
"(",
"min_version",
"=",
"2",
")",
":",
"if",
"not",
"_in_X",
":",
"raise",
"RuntimeError",
"(",
"'Not in X session.'",
")",
"if",
"_has_Gtk",
"<",
"min_version",
":",
"raise",
"RuntimeError",
"(",
"'Module gi.repository.Gtk not available!'",
")",
"if",
"_has_Gtk",
"==",
"2",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warn",
"(",
"_",
"(",
"\"Missing runtime dependency GTK 3. Falling back to GTK 2 \"",
"\"for password prompt\"",
")",
")",
"from",
"gi",
".",
"repository",
"import",
"Gtk",
"# if we attempt to create any GUI elements with no X server running the",
"# program will just crash, so let's make a way to catch this case:",
"if",
"not",
"Gtk",
".",
"init_check",
"(",
"None",
")",
"[",
"0",
"]",
":",
"raise",
"RuntimeError",
"(",
"_",
"(",
"\"X server not connected!\"",
")",
")",
"return",
"Gtk"
] | Make sure Gtk is properly initialized.
:raises RuntimeError: if Gtk can not be properly initialized | [
"Make",
"sure",
"Gtk",
"is",
"properly",
"initialized",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/depend.py#L38-L57 | train |
coldfix/udiskie | udiskie/locale.py | _ | def _(text, *args, **kwargs):
"""Translate and then and format the text with ``str.format``."""
msg = _t.gettext(text)
if args or kwargs:
return msg.format(*args, **kwargs)
else:
return msg | python | def _(text, *args, **kwargs):
"""Translate and then and format the text with ``str.format``."""
msg = _t.gettext(text)
if args or kwargs:
return msg.format(*args, **kwargs)
else:
return msg | [
"def",
"_",
"(",
"text",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"_t",
".",
"gettext",
"(",
"text",
")",
"if",
"args",
"or",
"kwargs",
":",
"return",
"msg",
".",
"format",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"msg"
] | Translate and then and format the text with ``str.format``. | [
"Translate",
"and",
"then",
"and",
"format",
"the",
"text",
"with",
"str",
".",
"format",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/locale.py#L11-L17 | train |
coldfix/udiskie | udiskie/udisks2.py | filter_opt | def filter_opt(opt):
"""Remove ``None`` values from a dictionary."""
return {k: GLib.Variant(*v) for k, v in opt.items() if v[1] is not None} | python | def filter_opt(opt):
"""Remove ``None`` values from a dictionary."""
return {k: GLib.Variant(*v) for k, v in opt.items() if v[1] is not None} | [
"def",
"filter_opt",
"(",
"opt",
")",
":",
"return",
"{",
"k",
":",
"GLib",
".",
"Variant",
"(",
"*",
"v",
")",
"for",
"k",
",",
"v",
"in",
"opt",
".",
"items",
"(",
")",
"if",
"v",
"[",
"1",
"]",
"is",
"not",
"None",
"}"
] | Remove ``None`` values from a dictionary. | [
"Remove",
"None",
"values",
"from",
"a",
"dictionary",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L43-L45 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.eject | def eject(self, auth_no_user_interaction=None):
"""Eject media from the device."""
return self._assocdrive._M.Drive.Eject(
'(a{sv})',
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | python | def eject(self, auth_no_user_interaction=None):
"""Eject media from the device."""
return self._assocdrive._M.Drive.Eject(
'(a{sv})',
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | [
"def",
"eject",
"(",
"self",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_assocdrive",
".",
"_M",
".",
"Drive",
".",
"Eject",
"(",
"'(a{sv})'",
",",
"filter_opt",
"(",
"{",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] | Eject media from the device. | [
"Eject",
"media",
"from",
"the",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L232-L239 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.device_id | def device_id(self):
"""
Return a unique and persistent identifier for the device.
This is the basename (last path component) of the symlink in
`/dev/disk/by-id/`.
"""
if self.is_block:
for filename in self._P.Block.Symlinks:
parts = decode_ay(filename).split('/')
if parts[-2] == 'by-id':
return parts[-1]
elif self.is_drive:
return self._assocdrive._P.Drive.Id
return '' | python | def device_id(self):
"""
Return a unique and persistent identifier for the device.
This is the basename (last path component) of the symlink in
`/dev/disk/by-id/`.
"""
if self.is_block:
for filename in self._P.Block.Symlinks:
parts = decode_ay(filename).split('/')
if parts[-2] == 'by-id':
return parts[-1]
elif self.is_drive:
return self._assocdrive._P.Drive.Id
return '' | [
"def",
"device_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_block",
":",
"for",
"filename",
"in",
"self",
".",
"_P",
".",
"Block",
".",
"Symlinks",
":",
"parts",
"=",
"decode_ay",
"(",
"filename",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"parts",
"[",
"-",
"2",
"]",
"==",
"'by-id'",
":",
"return",
"parts",
"[",
"-",
"1",
"]",
"elif",
"self",
".",
"is_drive",
":",
"return",
"self",
".",
"_assocdrive",
".",
"_P",
".",
"Drive",
".",
"Id",
"return",
"''"
] | Return a unique and persistent identifier for the device.
This is the basename (last path component) of the symlink in
`/dev/disk/by-id/`. | [
"Return",
"a",
"unique",
"and",
"persistent",
"identifier",
"for",
"the",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L286-L300 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.is_external | def is_external(self):
"""Check if the device is external."""
# NOTE: Checking for equality HintSystem==False returns False if the
# property is resolved to a None value (interface not available).
if self._P.Block.HintSystem == False: # noqa: E712
return True
# NOTE: udisks2 seems to guess incorrectly in some cases. This
# leads to HintSystem=True for unlocked devices. In order to show
# the device anyway, it needs to be recursively checked if any
# parent device is recognized as external.
if self.is_luks_cleartext and self.luks_cleartext_slave.is_external:
return True
if self.is_partition and self.partition_slave.is_external:
return True
return False | python | def is_external(self):
"""Check if the device is external."""
# NOTE: Checking for equality HintSystem==False returns False if the
# property is resolved to a None value (interface not available).
if self._P.Block.HintSystem == False: # noqa: E712
return True
# NOTE: udisks2 seems to guess incorrectly in some cases. This
# leads to HintSystem=True for unlocked devices. In order to show
# the device anyway, it needs to be recursively checked if any
# parent device is recognized as external.
if self.is_luks_cleartext and self.luks_cleartext_slave.is_external:
return True
if self.is_partition and self.partition_slave.is_external:
return True
return False | [
"def",
"is_external",
"(",
"self",
")",
":",
"# NOTE: Checking for equality HintSystem==False returns False if the",
"# property is resolved to a None value (interface not available).",
"if",
"self",
".",
"_P",
".",
"Block",
".",
"HintSystem",
"==",
"False",
":",
"# noqa: E712",
"return",
"True",
"# NOTE: udisks2 seems to guess incorrectly in some cases. This",
"# leads to HintSystem=True for unlocked devices. In order to show",
"# the device anyway, it needs to be recursively checked if any",
"# parent device is recognized as external.",
"if",
"self",
".",
"is_luks_cleartext",
"and",
"self",
".",
"luks_cleartext_slave",
".",
"is_external",
":",
"return",
"True",
"if",
"self",
".",
"is_partition",
"and",
"self",
".",
"partition_slave",
".",
"is_external",
":",
"return",
"True",
"return",
"False"
] | Check if the device is external. | [
"Check",
"if",
"the",
"device",
"is",
"external",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L335-L349 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.drive | def drive(self):
"""Get wrapper to the drive containing this device."""
if self.is_drive:
return self
cleartext = self.luks_cleartext_slave
if cleartext:
return cleartext.drive
if self.is_block:
return self._daemon[self._P.Block.Drive]
return None | python | def drive(self):
"""Get wrapper to the drive containing this device."""
if self.is_drive:
return self
cleartext = self.luks_cleartext_slave
if cleartext:
return cleartext.drive
if self.is_block:
return self._daemon[self._P.Block.Drive]
return None | [
"def",
"drive",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_drive",
":",
"return",
"self",
"cleartext",
"=",
"self",
".",
"luks_cleartext_slave",
"if",
"cleartext",
":",
"return",
"cleartext",
".",
"drive",
"if",
"self",
".",
"is_block",
":",
"return",
"self",
".",
"_daemon",
"[",
"self",
".",
"_P",
".",
"Block",
".",
"Drive",
"]",
"return",
"None"
] | Get wrapper to the drive containing this device. | [
"Get",
"wrapper",
"to",
"the",
"drive",
"containing",
"this",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L357-L366 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.root | def root(self):
"""Get the top level block device in the ancestry of this device."""
drive = self.drive
for device in self._daemon:
if device.is_drive:
continue
if device.is_toplevel and device.drive == drive:
return device
return None | python | def root(self):
"""Get the top level block device in the ancestry of this device."""
drive = self.drive
for device in self._daemon:
if device.is_drive:
continue
if device.is_toplevel and device.drive == drive:
return device
return None | [
"def",
"root",
"(",
"self",
")",
":",
"drive",
"=",
"self",
".",
"drive",
"for",
"device",
"in",
"self",
".",
"_daemon",
":",
"if",
"device",
".",
"is_drive",
":",
"continue",
"if",
"device",
".",
"is_toplevel",
"and",
"device",
".",
"drive",
"==",
"drive",
":",
"return",
"device",
"return",
"None"
] | Get the top level block device in the ancestry of this device. | [
"Get",
"the",
"top",
"level",
"block",
"device",
"in",
"the",
"ancestry",
"of",
"this",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L369-L377 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.symlinks | def symlinks(self):
"""Known symlinks of the block device."""
if not self._P.Block.Symlinks:
return []
return [decode_ay(path) for path in self._P.Block.Symlinks] | python | def symlinks(self):
"""Known symlinks of the block device."""
if not self._P.Block.Symlinks:
return []
return [decode_ay(path) for path in self._P.Block.Symlinks] | [
"def",
"symlinks",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_P",
".",
"Block",
".",
"Symlinks",
":",
"return",
"[",
"]",
"return",
"[",
"decode_ay",
"(",
"path",
")",
"for",
"path",
"in",
"self",
".",
"_P",
".",
"Block",
".",
"Symlinks",
"]"
] | Known symlinks of the block device. | [
"Known",
"symlinks",
"of",
"the",
"block",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L395-L399 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.mount | def mount(self,
fstype=None,
options=None,
auth_no_user_interaction=None):
"""Mount filesystem."""
return self._M.Filesystem.Mount(
'(a{sv})',
filter_opt({
'fstype': ('s', fstype),
'options': ('s', ','.join(options or [])),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | python | def mount(self,
fstype=None,
options=None,
auth_no_user_interaction=None):
"""Mount filesystem."""
return self._M.Filesystem.Mount(
'(a{sv})',
filter_opt({
'fstype': ('s', fstype),
'options': ('s', ','.join(options or [])),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | [
"def",
"mount",
"(",
"self",
",",
"fstype",
"=",
"None",
",",
"options",
"=",
"None",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_M",
".",
"Filesystem",
".",
"Mount",
"(",
"'(a{sv})'",
",",
"filter_opt",
"(",
"{",
"'fstype'",
":",
"(",
"'s'",
",",
"fstype",
")",
",",
"'options'",
":",
"(",
"'s'",
",",
"','",
".",
"join",
"(",
"options",
"or",
"[",
"]",
")",
")",
",",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] | Mount filesystem. | [
"Mount",
"filesystem",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L432-L444 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.unmount | def unmount(self, force=None, auth_no_user_interaction=None):
"""Unmount filesystem."""
return self._M.Filesystem.Unmount(
'(a{sv})',
filter_opt({
'force': ('b', force),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | python | def unmount(self, force=None, auth_no_user_interaction=None):
"""Unmount filesystem."""
return self._M.Filesystem.Unmount(
'(a{sv})',
filter_opt({
'force': ('b', force),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | [
"def",
"unmount",
"(",
"self",
",",
"force",
"=",
"None",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_M",
".",
"Filesystem",
".",
"Unmount",
"(",
"'(a{sv})'",
",",
"filter_opt",
"(",
"{",
"'force'",
":",
"(",
"'b'",
",",
"force",
")",
",",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] | Unmount filesystem. | [
"Unmount",
"filesystem",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L446-L454 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.luks_cleartext_holder | def luks_cleartext_holder(self):
"""Get wrapper to the unlocked luks cleartext device."""
if not self.is_luks:
return None
for device in self._daemon:
if device.luks_cleartext_slave == self:
return device
return None | python | def luks_cleartext_holder(self):
"""Get wrapper to the unlocked luks cleartext device."""
if not self.is_luks:
return None
for device in self._daemon:
if device.luks_cleartext_slave == self:
return device
return None | [
"def",
"luks_cleartext_holder",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_luks",
":",
"return",
"None",
"for",
"device",
"in",
"self",
".",
"_daemon",
":",
"if",
"device",
".",
"luks_cleartext_slave",
"==",
"self",
":",
"return",
"device",
"return",
"None"
] | Get wrapper to the unlocked luks cleartext device. | [
"Get",
"wrapper",
"to",
"the",
"unlocked",
"luks",
"cleartext",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L462-L469 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.unlock | def unlock(self, password, auth_no_user_interaction=None):
"""Unlock Luks device."""
return self._M.Encrypted.Unlock(
'(sa{sv})',
password,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | python | def unlock(self, password, auth_no_user_interaction=None):
"""Unlock Luks device."""
return self._M.Encrypted.Unlock(
'(sa{sv})',
password,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | [
"def",
"unlock",
"(",
"self",
",",
"password",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_M",
".",
"Encrypted",
".",
"Unlock",
"(",
"'(sa{sv})'",
",",
"password",
",",
"filter_opt",
"(",
"{",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] | Unlock Luks device. | [
"Unlock",
"Luks",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L477-L485 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.set_autoclear | def set_autoclear(self, value, auth_no_user_interaction=None):
"""Set autoclear flag for loop partition."""
return self._M.Loop.SetAutoclear(
'(ba{sv})',
value,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | python | def set_autoclear(self, value, auth_no_user_interaction=None):
"""Set autoclear flag for loop partition."""
return self._M.Loop.SetAutoclear(
'(ba{sv})',
value,
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | [
"def",
"set_autoclear",
"(",
"self",
",",
"value",
",",
"auth_no_user_interaction",
"=",
"None",
")",
":",
"return",
"self",
".",
"_M",
".",
"Loop",
".",
"SetAutoclear",
"(",
"'(ba{sv})'",
",",
"value",
",",
"filter_opt",
"(",
"{",
"'auth.no_user_interaction'",
":",
"(",
"'b'",
",",
"auth_no_user_interaction",
")",
",",
"}",
")",
")"
] | Set autoclear flag for loop partition. | [
"Set",
"autoclear",
"flag",
"for",
"loop",
"partition",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L532-L540 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.is_file | def is_file(self, path):
"""Comparison by mount and device file path."""
return (samefile(path, self.device_file) or
samefile(path, self.loop_file) or
any(samefile(path, mp) for mp in self.mount_paths) or
sameuuid(path, self.id_uuid) or
sameuuid(path, self.partition_uuid)) | python | def is_file(self, path):
"""Comparison by mount and device file path."""
return (samefile(path, self.device_file) or
samefile(path, self.loop_file) or
any(samefile(path, mp) for mp in self.mount_paths) or
sameuuid(path, self.id_uuid) or
sameuuid(path, self.partition_uuid)) | [
"def",
"is_file",
"(",
"self",
",",
"path",
")",
":",
"return",
"(",
"samefile",
"(",
"path",
",",
"self",
".",
"device_file",
")",
"or",
"samefile",
"(",
"path",
",",
"self",
".",
"loop_file",
")",
"or",
"any",
"(",
"samefile",
"(",
"path",
",",
"mp",
")",
"for",
"mp",
"in",
"self",
".",
"mount_paths",
")",
"or",
"sameuuid",
"(",
"path",
",",
"self",
".",
"id_uuid",
")",
"or",
"sameuuid",
"(",
"path",
",",
"self",
".",
"partition_uuid",
")",
")"
] | Comparison by mount and device file path. | [
"Comparison",
"by",
"mount",
"and",
"device",
"file",
"path",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L546-L552 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.in_use | def in_use(self):
"""Check whether this device is in use, i.e. mounted or unlocked."""
if self.is_mounted or self.is_unlocked:
return True
if self.is_partition_table:
for device in self._daemon:
if device.partition_slave == self and device.in_use:
return True
return False | python | def in_use(self):
"""Check whether this device is in use, i.e. mounted or unlocked."""
if self.is_mounted or self.is_unlocked:
return True
if self.is_partition_table:
for device in self._daemon:
if device.partition_slave == self and device.in_use:
return True
return False | [
"def",
"in_use",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_mounted",
"or",
"self",
".",
"is_unlocked",
":",
"return",
"True",
"if",
"self",
".",
"is_partition_table",
":",
"for",
"device",
"in",
"self",
".",
"_daemon",
":",
"if",
"device",
".",
"partition_slave",
"==",
"self",
"and",
"device",
".",
"in_use",
":",
"return",
"True",
"return",
"False"
] | Check whether this device is in use, i.e. mounted or unlocked. | [
"Check",
"whether",
"this",
"device",
"is",
"in",
"use",
"i",
".",
"e",
".",
"mounted",
"or",
"unlocked",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L569-L577 | train |
coldfix/udiskie | udiskie/udisks2.py | Device.ui_label | def ui_label(self):
"""UI string identifying the partition if possible."""
return ': '.join(filter(None, [
self.ui_device_presentation,
self.ui_id_label or self.ui_id_uuid or self.drive_label
])) | python | def ui_label(self):
"""UI string identifying the partition if possible."""
return ': '.join(filter(None, [
self.ui_device_presentation,
self.ui_id_label or self.ui_id_uuid or self.drive_label
])) | [
"def",
"ui_label",
"(",
"self",
")",
":",
"return",
"': '",
".",
"join",
"(",
"filter",
"(",
"None",
",",
"[",
"self",
".",
"ui_device_presentation",
",",
"self",
".",
"ui_id_label",
"or",
"self",
".",
"ui_id_uuid",
"or",
"self",
".",
"drive_label",
"]",
")",
")"
] | UI string identifying the partition if possible. | [
"UI",
"string",
"identifying",
"the",
"partition",
"if",
"possible",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L595-L600 | train |
coldfix/udiskie | udiskie/udisks2.py | Daemon.find | def find(self, path):
"""
Get a device proxy by device name or any mount path of the device.
This searches through all accessible devices and compares device
path as well as mount pathes.
"""
if isinstance(path, Device):
return path
for device in self:
if device.is_file(path):
self._log.debug(_('found device owning "{0}": "{1}"',
path, device))
return device
raise FileNotFoundError(_('no device found owning "{0}"', path)) | python | def find(self, path):
"""
Get a device proxy by device name or any mount path of the device.
This searches through all accessible devices and compares device
path as well as mount pathes.
"""
if isinstance(path, Device):
return path
for device in self:
if device.is_file(path):
self._log.debug(_('found device owning "{0}": "{1}"',
path, device))
return device
raise FileNotFoundError(_('no device found owning "{0}"', path)) | [
"def",
"find",
"(",
"self",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"Device",
")",
":",
"return",
"path",
"for",
"device",
"in",
"self",
":",
"if",
"device",
".",
"is_file",
"(",
"path",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"_",
"(",
"'found device owning \"{0}\": \"{1}\"'",
",",
"path",
",",
"device",
")",
")",
"return",
"device",
"raise",
"FileNotFoundError",
"(",
"_",
"(",
"'no device found owning \"{0}\"'",
",",
"path",
")",
")"
] | Get a device proxy by device name or any mount path of the device.
This searches through all accessible devices and compares device
path as well as mount pathes. | [
"Get",
"a",
"device",
"proxy",
"by",
"device",
"name",
"or",
"any",
"mount",
"path",
"of",
"the",
"device",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L651-L665 | train |
coldfix/udiskie | udiskie/udisks2.py | Daemon.get | def get(self, object_path, interfaces_and_properties=None):
"""Create a Device instance from object path."""
# check this before creating the DBus object for more
# controlled behaviour:
if not interfaces_and_properties:
interfaces_and_properties = self._objects.get(object_path)
if not interfaces_and_properties:
return None
property_hub = PropertyHub(interfaces_and_properties)
method_hub = MethodHub(
self._proxy.object.bus.get_object(object_path))
return Device(self, object_path, property_hub, method_hub) | python | def get(self, object_path, interfaces_and_properties=None):
"""Create a Device instance from object path."""
# check this before creating the DBus object for more
# controlled behaviour:
if not interfaces_and_properties:
interfaces_and_properties = self._objects.get(object_path)
if not interfaces_and_properties:
return None
property_hub = PropertyHub(interfaces_and_properties)
method_hub = MethodHub(
self._proxy.object.bus.get_object(object_path))
return Device(self, object_path, property_hub, method_hub) | [
"def",
"get",
"(",
"self",
",",
"object_path",
",",
"interfaces_and_properties",
"=",
"None",
")",
":",
"# check this before creating the DBus object for more",
"# controlled behaviour:",
"if",
"not",
"interfaces_and_properties",
":",
"interfaces_and_properties",
"=",
"self",
".",
"_objects",
".",
"get",
"(",
"object_path",
")",
"if",
"not",
"interfaces_and_properties",
":",
"return",
"None",
"property_hub",
"=",
"PropertyHub",
"(",
"interfaces_and_properties",
")",
"method_hub",
"=",
"MethodHub",
"(",
"self",
".",
"_proxy",
".",
"object",
".",
"bus",
".",
"get_object",
"(",
"object_path",
")",
")",
"return",
"Device",
"(",
"self",
",",
"object_path",
",",
"property_hub",
",",
"method_hub",
")"
] | Create a Device instance from object path. | [
"Create",
"a",
"Device",
"instance",
"from",
"object",
"path",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/udisks2.py#L754-L765 | train |
coldfix/udiskie | udiskie/notify.py | Notify.device_mounted | def device_mounted(self, device):
"""Show mount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
browse_action = ('browse', _('Browse directory'),
self._mounter.browse, device)
terminal_action = ('terminal', _('Open terminal'),
self._mounter.terminal, device)
self._show_notification(
'device_mounted',
_('Device mounted'),
_('{0.ui_label} mounted on {0.mount_paths[0]}', device),
device.icon_name,
self._mounter._browser and browse_action,
self._mounter._terminal and terminal_action) | python | def device_mounted(self, device):
"""Show mount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
browse_action = ('browse', _('Browse directory'),
self._mounter.browse, device)
terminal_action = ('terminal', _('Open terminal'),
self._mounter.terminal, device)
self._show_notification(
'device_mounted',
_('Device mounted'),
_('{0.ui_label} mounted on {0.mount_paths[0]}', device),
device.icon_name,
self._mounter._browser and browse_action,
self._mounter._terminal and terminal_action) | [
"def",
"device_mounted",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"browse_action",
"=",
"(",
"'browse'",
",",
"_",
"(",
"'Browse directory'",
")",
",",
"self",
".",
"_mounter",
".",
"browse",
",",
"device",
")",
"terminal_action",
"=",
"(",
"'terminal'",
",",
"_",
"(",
"'Open terminal'",
")",
",",
"self",
".",
"_mounter",
".",
"terminal",
",",
"device",
")",
"self",
".",
"_show_notification",
"(",
"'device_mounted'",
",",
"_",
"(",
"'Device mounted'",
")",
",",
"_",
"(",
"'{0.ui_label} mounted on {0.mount_paths[0]}'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
",",
"self",
".",
"_mounter",
".",
"_browser",
"and",
"browse_action",
",",
"self",
".",
"_mounter",
".",
"_terminal",
"and",
"terminal_action",
")"
] | Show mount notification for specified device object. | [
"Show",
"mount",
"notification",
"for",
"specified",
"device",
"object",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L58-L72 | train |
coldfix/udiskie | udiskie/notify.py | Notify.device_unmounted | def device_unmounted(self, device):
"""Show unmount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unmounted',
_('Device unmounted'),
_('{0.ui_label} unmounted', device),
device.icon_name) | python | def device_unmounted(self, device):
"""Show unmount notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unmounted',
_('Device unmounted'),
_('{0.ui_label} unmounted', device),
device.icon_name) | [
"def",
"device_unmounted",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"self",
".",
"_show_notification",
"(",
"'device_unmounted'",
",",
"_",
"(",
"'Device unmounted'",
")",
",",
"_",
"(",
"'{0.ui_label} unmounted'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
")"
] | Show unmount notification for specified device object. | [
"Show",
"unmount",
"notification",
"for",
"specified",
"device",
"object",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L74-L82 | train |
coldfix/udiskie | udiskie/notify.py | Notify.device_locked | def device_locked(self, device):
"""Show lock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_locked',
_('Device locked'),
_('{0.device_presentation} locked', device),
device.icon_name) | python | def device_locked(self, device):
"""Show lock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_locked',
_('Device locked'),
_('{0.device_presentation} locked', device),
device.icon_name) | [
"def",
"device_locked",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"self",
".",
"_show_notification",
"(",
"'device_locked'",
",",
"_",
"(",
"'Device locked'",
")",
",",
"_",
"(",
"'{0.device_presentation} locked'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
")"
] | Show lock notification for specified device object. | [
"Show",
"lock",
"notification",
"for",
"specified",
"device",
"object",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L84-L92 | train |
coldfix/udiskie | udiskie/notify.py | Notify.device_unlocked | def device_unlocked(self, device):
"""Show unlock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unlocked',
_('Device unlocked'),
_('{0.device_presentation} unlocked', device),
device.icon_name) | python | def device_unlocked(self, device):
"""Show unlock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unlocked',
_('Device unlocked'),
_('{0.device_presentation} unlocked', device),
device.icon_name) | [
"def",
"device_unlocked",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"self",
".",
"_show_notification",
"(",
"'device_unlocked'",
",",
"_",
"(",
"'Device unlocked'",
")",
",",
"_",
"(",
"'{0.device_presentation} unlocked'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
")"
] | Show unlock notification for specified device object. | [
"Show",
"unlock",
"notification",
"for",
"specified",
"device",
"object",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L94-L102 | train |
coldfix/udiskie | udiskie/notify.py | Notify.device_added | def device_added(self, device):
"""Show discovery notification for specified device object."""
if not self._mounter.is_handleable(device):
return
if self._has_actions('device_added'):
# wait for partitions etc to be reported to udiskie, otherwise we
# can't discover the actions
GLib.timeout_add(500, self._device_added, device)
else:
self._device_added(device) | python | def device_added(self, device):
"""Show discovery notification for specified device object."""
if not self._mounter.is_handleable(device):
return
if self._has_actions('device_added'):
# wait for partitions etc to be reported to udiskie, otherwise we
# can't discover the actions
GLib.timeout_add(500, self._device_added, device)
else:
self._device_added(device) | [
"def",
"device_added",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"if",
"self",
".",
"_has_actions",
"(",
"'device_added'",
")",
":",
"# wait for partitions etc to be reported to udiskie, otherwise we",
"# can't discover the actions",
"GLib",
".",
"timeout_add",
"(",
"500",
",",
"self",
".",
"_device_added",
",",
"device",
")",
"else",
":",
"self",
".",
"_device_added",
"(",
"device",
")"
] | Show discovery notification for specified device object. | [
"Show",
"discovery",
"notification",
"for",
"specified",
"device",
"object",
"."
] | 804c9d27df6f7361fec3097c432398f2d702f911 | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/notify.py#L104-L113 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.