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
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
RtorrentItem.tag
def tag(self, tags): """ Add or remove tags. """ # Get tag list and add/remove given tags tags = tags.lower() previous = self.tagged tagset = previous.copy() for tag in tags.replace(',', ' ').split(): if tag.startswith('-'): tagset.disc...
python
def tag(self, tags): """ Add or remove tags. """ # Get tag list and add/remove given tags tags = tags.lower() previous = self.tagged tagset = previous.copy() for tag in tags.replace(',', ' ').split(): if tag.startswith('-'): tagset.disc...
[ "def", "tag", "(", "self", ",", "tags", ")", ":", "# Get tag list and add/remove given tags", "tags", "=", "tags", ".", "lower", "(", ")", "previous", "=", "self", ".", "tagged", "tagset", "=", "previous", ".", "copy", "(", ")", "for", "tag", "in", "tags...
Add or remove tags.
[ "Add", "or", "remove", "tags", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L264-L284
train
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
RtorrentItem.set_throttle
def set_throttle(self, name): """ Assign to throttle group. """ if name.lower() == "null": name = "NULL" if name.lower() == "none": name = '' if name not in self._engine.known_throttle_names: if self._engine._rpc.throttle.up.max(xmlrpc.NOHASH,...
python
def set_throttle(self, name): """ Assign to throttle group. """ if name.lower() == "null": name = "NULL" if name.lower() == "none": name = '' if name not in self._engine.known_throttle_names: if self._engine._rpc.throttle.up.max(xmlrpc.NOHASH,...
[ "def", "set_throttle", "(", "self", ",", "name", ")", ":", "if", "name", ".", "lower", "(", ")", "==", "\"null\"", ":", "name", "=", "\"NULL\"", "if", "name", ".", "lower", "(", ")", "==", "\"none\"", ":", "name", "=", "''", "if", "name", "not", ...
Assign to throttle group.
[ "Assign", "to", "throttle", "group", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L287-L312
train
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
RtorrentItem.purge
def purge(self): """ Delete PARTIAL data files and remove torrent from client. """ def partial_file(item): "Filter out partial files" #print "???", repr(item) return item.completed_chunks < item.size_chunks self.cull(file_filter=partial_file, attrs=["...
python
def purge(self): """ Delete PARTIAL data files and remove torrent from client. """ def partial_file(item): "Filter out partial files" #print "???", repr(item) return item.completed_chunks < item.size_chunks self.cull(file_filter=partial_file, attrs=["...
[ "def", "purge", "(", "self", ")", ":", "def", "partial_file", "(", "item", ")", ":", "\"Filter out partial files\"", "#print \"???\", repr(item)", "return", "item", ".", "completed_chunks", "<", "item", ".", "size_chunks", "self", ".", "cull", "(", "file_filter", ...
Delete PARTIAL data files and remove torrent from client.
[ "Delete", "PARTIAL", "data", "files", "and", "remove", "torrent", "from", "client", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L388-L396
train
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
RtorrentEngine.load_config
def load_config(self, namespace=None, rcfile=None): """ Load file given in "rcfile". """ if namespace is None: namespace = config if namespace.scgi_url: return # already have the connection to rTorrent # Get and check config file name if not rcfi...
python
def load_config(self, namespace=None, rcfile=None): """ Load file given in "rcfile". """ if namespace is None: namespace = config if namespace.scgi_url: return # already have the connection to rTorrent # Get and check config file name if not rcfi...
[ "def", "load_config", "(", "self", ",", "namespace", "=", "None", ",", "rcfile", "=", "None", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "config", "if", "namespace", ".", "scgi_url", ":", "return", "# already have the connection to rTorr...
Load file given in "rcfile".
[ "Load", "file", "given", "in", "rcfile", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L577-L628
train
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
RtorrentEngine._resolve_viewname
def _resolve_viewname(self, viewname): """ Check for special view names and return existing rTorrent one. """ if viewname == "-": try: # Only works with rTorrent-PS at this time! viewname = self.open().ui.current_view() except xmlrpc.ERRORS...
python
def _resolve_viewname(self, viewname): """ Check for special view names and return existing rTorrent one. """ if viewname == "-": try: # Only works with rTorrent-PS at this time! viewname = self.open().ui.current_view() except xmlrpc.ERRORS...
[ "def", "_resolve_viewname", "(", "self", ",", "viewname", ")", ":", "if", "viewname", "==", "\"-\"", ":", "try", ":", "# Only works with rTorrent-PS at this time!", "viewname", "=", "self", ".", "open", "(", ")", ".", "ui", ".", "current_view", "(", ")", "ex...
Check for special view names and return existing rTorrent one.
[ "Check", "for", "special", "view", "names", "and", "return", "existing", "rTorrent", "one", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L655-L665
train
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
RtorrentEngine.open
def open(self): """ Open connection. """ # Only connect once if self._rpc is not None: return self._rpc # Get connection URL from rtorrent.rc self.load_config() # Reading abilities are on the downfall, so... if not config.scgi_url: ...
python
def open(self): """ Open connection. """ # Only connect once if self._rpc is not None: return self._rpc # Get connection URL from rtorrent.rc self.load_config() # Reading abilities are on the downfall, so... if not config.scgi_url: ...
[ "def", "open", "(", "self", ")", ":", "# Only connect once", "if", "self", ".", "_rpc", "is", "not", "None", ":", "return", "self", ".", "_rpc", "# Get connection URL from rtorrent.rc", "self", ".", "load_config", "(", ")", "# Reading abilities are on the downfall, ...
Open connection.
[ "Open", "connection", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L668-L713
train
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
RtorrentEngine.multicall
def multicall(self, viewname, fields): """ Query the given fields of items in the given view. The result list contains named tuples, so you can access the fields directly by their name. """ commands = tuple('d.{}='.format(x) for x in fields) result_type = namedtu...
python
def multicall(self, viewname, fields): """ Query the given fields of items in the given view. The result list contains named tuples, so you can access the fields directly by their name. """ commands = tuple('d.{}='.format(x) for x in fields) result_type = namedtu...
[ "def", "multicall", "(", "self", ",", "viewname", ",", "fields", ")", ":", "commands", "=", "tuple", "(", "'d.{}='", ".", "format", "(", "x", ")", "for", "x", "in", "fields", ")", "result_type", "=", "namedtuple", "(", "'DownloadItem'", ",", "[", "x", ...
Query the given fields of items in the given view. The result list contains named tuples, so you can access the fields directly by their name.
[ "Query", "the", "given", "fields", "of", "items", "in", "the", "given", "view", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L716-L725
train
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
RtorrentEngine.item
def item(self, infohash, prefetch=None, cache=False): """ Fetch a single item by its info hash. """ return next(self.items(infohash, prefetch, cache))
python
def item(self, infohash, prefetch=None, cache=False): """ Fetch a single item by its info hash. """ return next(self.items(infohash, prefetch, cache))
[ "def", "item", "(", "self", ",", "infohash", ",", "prefetch", "=", "None", ",", "cache", "=", "False", ")", ":", "return", "next", "(", "self", ".", "items", "(", "infohash", ",", "prefetch", ",", "cache", ")", ")" ]
Fetch a single item by its info hash.
[ "Fetch", "a", "single", "item", "by", "its", "info", "hash", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L734-L737
train
pyroscope/pyrocore
src/pyrocore/torrent/broom.py
DiskSpaceManager._load_rules
def _load_rules(self): """Load rule definitions from config.""" for ruleset in self.active_rulesets: section_name = 'sweep_rules_' + ruleset.lower() try: ruledefs = getattr(self.config, section_name) except AttributeError: raise error.U...
python
def _load_rules(self): """Load rule definitions from config.""" for ruleset in self.active_rulesets: section_name = 'sweep_rules_' + ruleset.lower() try: ruledefs = getattr(self.config, section_name) except AttributeError: raise error.U...
[ "def", "_load_rules", "(", "self", ")", ":", "for", "ruleset", "in", "self", ".", "active_rulesets", ":", "section_name", "=", "'sweep_rules_'", "+", "ruleset", ".", "lower", "(", ")", "try", ":", "ruledefs", "=", "getattr", "(", "self", ".", "config", "...
Load rule definitions from config.
[ "Load", "rule", "definitions", "from", "config", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/broom.py#L54-L74
train
pyroscope/pyrocore
src/pyrocore/scripts/pyrotorque.py
RtorrentQueueManager._parse_schedule
def _parse_schedule(self, schedule): """ Parse a job schedule. """ result = {} for param in shlex.split(str(schedule)): # do not feed unicode to shlex try: key, val = param.split('=', 1) except (TypeError, ValueError): self.fatal("...
python
def _parse_schedule(self, schedule): """ Parse a job schedule. """ result = {} for param in shlex.split(str(schedule)): # do not feed unicode to shlex try: key, val = param.split('=', 1) except (TypeError, ValueError): self.fatal("...
[ "def", "_parse_schedule", "(", "self", ",", "schedule", ")", ":", "result", "=", "{", "}", "for", "param", "in", "shlex", ".", "split", "(", "str", "(", "schedule", ")", ")", ":", "# do not feed unicode to shlex", "try", ":", "key", ",", "val", "=", "p...
Parse a job schedule.
[ "Parse", "a", "job", "schedule", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/pyrotorque.py#L76-L89
train
pyroscope/pyrocore
src/pyrocore/scripts/pyrotorque.py
RtorrentQueueManager._validate_config
def _validate_config(self): """ Handle and check configuration. """ groups = dict( job=defaultdict(Bunch), httpd=defaultdict(Bunch), ) for key, val in config.torque.items(): # Auto-convert numbers and bools if val.isdigit(): ...
python
def _validate_config(self): """ Handle and check configuration. """ groups = dict( job=defaultdict(Bunch), httpd=defaultdict(Bunch), ) for key, val in config.torque.items(): # Auto-convert numbers and bools if val.isdigit(): ...
[ "def", "_validate_config", "(", "self", ")", ":", "groups", "=", "dict", "(", "job", "=", "defaultdict", "(", "Bunch", ")", ",", "httpd", "=", "defaultdict", "(", "Bunch", ")", ",", ")", "for", "key", ",", "val", "in", "config", ".", "torque", ".", ...
Handle and check configuration.
[ "Handle", "and", "check", "configuration", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/pyrotorque.py#L92-L146
train
pyroscope/pyrocore
src/pyrocore/scripts/pyrotorque.py
RtorrentQueueManager._add_jobs
def _add_jobs(self): """ Add configured jobs. """ for name, params in self.jobs.items(): if params.active: params.handler = params.handler(params) self.sched.add_cron_job(params.handler.run, **params.schedule)
python
def _add_jobs(self): """ Add configured jobs. """ for name, params in self.jobs.items(): if params.active: params.handler = params.handler(params) self.sched.add_cron_job(params.handler.run, **params.schedule)
[ "def", "_add_jobs", "(", "self", ")", ":", "for", "name", ",", "params", "in", "self", ".", "jobs", ".", "items", "(", ")", ":", "if", "params", ".", "active", ":", "params", ".", "handler", "=", "params", ".", "handler", "(", "params", ")", "self"...
Add configured jobs.
[ "Add", "configured", "jobs", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/pyrotorque.py#L149-L155
train
pyroscope/pyrocore
src/pyrocore/scripts/pyrotorque.py
RtorrentQueueManager._init_wsgi_server
def _init_wsgi_server(self): """ Set up WSGI HTTP server. """ self.wsgi_server = None if self.httpd.active: # Only import dependencies when server is active from waitress.server import WSGIServer from pyrocore.daemon import webapp # Set u...
python
def _init_wsgi_server(self): """ Set up WSGI HTTP server. """ self.wsgi_server = None if self.httpd.active: # Only import dependencies when server is active from waitress.server import WSGIServer from pyrocore.daemon import webapp # Set u...
[ "def", "_init_wsgi_server", "(", "self", ")", ":", "self", ".", "wsgi_server", "=", "None", "if", "self", ".", "httpd", ".", "active", ":", "# Only import dependencies when server is active", "from", "waitress", ".", "server", "import", "WSGIServer", "from", "pyro...
Set up WSGI HTTP server.
[ "Set", "up", "WSGI", "HTTP", "server", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/pyrotorque.py#L158-L184
train
pyroscope/pyrocore
src/pyrocore/scripts/pyrotorque.py
RtorrentQueueManager._run_forever
def _run_forever(self): """ Run configured jobs until termination request. """ while True: try: tick = time.time() asyncore.loop(timeout=self.POLL_TIMEOUT, use_poll=True) # Sleep for remaining poll cycle time tick += s...
python
def _run_forever(self): """ Run configured jobs until termination request. """ while True: try: tick = time.time() asyncore.loop(timeout=self.POLL_TIMEOUT, use_poll=True) # Sleep for remaining poll cycle time tick += s...
[ "def", "_run_forever", "(", "self", ")", ":", "while", "True", ":", "try", ":", "tick", "=", "time", ".", "time", "(", ")", "asyncore", ".", "loop", "(", "timeout", "=", "self", ".", "POLL_TIMEOUT", ",", "use_poll", "=", "True", ")", "# Sleep for remai...
Run configured jobs until termination request.
[ "Run", "configured", "jobs", "until", "termination", "request", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/pyrotorque.py#L187-L213
train
pyroscope/pyrocore
src/pyrocore/scripts/rtxmlrpc.py
read_blob
def read_blob(arg): """Read a BLOB from given ``@arg``.""" result = None if arg == '@-': result = sys.stdin.read() elif any(arg.startswith('@{}://'.format(x)) for x in {'http', 'https', 'ftp', 'file'}): if not requests: raise error.UserError("You must 'pip install requests' t...
python
def read_blob(arg): """Read a BLOB from given ``@arg``.""" result = None if arg == '@-': result = sys.stdin.read() elif any(arg.startswith('@{}://'.format(x)) for x in {'http', 'https', 'ftp', 'file'}): if not requests: raise error.UserError("You must 'pip install requests' t...
[ "def", "read_blob", "(", "arg", ")", ":", "result", "=", "None", "if", "arg", "==", "'@-'", ":", "result", "=", "sys", ".", "stdin", ".", "read", "(", ")", "elif", "any", "(", "arg", ".", "startswith", "(", "'@{}://'", ".", "format", "(", "x", ")...
Read a BLOB from given ``@arg``.
[ "Read", "a", "BLOB", "from", "given" ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtxmlrpc.py#L46-L64
train
pyroscope/pyrocore
src/pyrocore/scripts/rtxmlrpc.py
RtorrentXmlRpc.open
def open(self): """Open connection and return proxy.""" if not self.proxy: if not config.scgi_url: config.engine.load_config() if not config.scgi_url: self.LOG.error("You need to configure a XMLRPC connection, read" " https://py...
python
def open(self): """Open connection and return proxy.""" if not self.proxy: if not config.scgi_url: config.engine.load_config() if not config.scgi_url: self.LOG.error("You need to configure a XMLRPC connection, read" " https://py...
[ "def", "open", "(", "self", ")", ":", "if", "not", "self", ".", "proxy", ":", "if", "not", "config", ".", "scgi_url", ":", "config", ".", "engine", ".", "load_config", "(", ")", "if", "not", "config", ".", "scgi_url", ":", "self", ".", "LOG", ".", ...
Open connection and return proxy.
[ "Open", "connection", "and", "return", "proxy", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtxmlrpc.py#L111-L121
train
pyroscope/pyrocore
src/pyrocore/scripts/rtxmlrpc.py
RtorrentXmlRpc.execute
def execute(self, proxy, method, args): """Execute given XMLRPC call.""" try: result = getattr(proxy, method)(raw_xml=self.options.xml, *tuple(args)) except xmlrpc.ERRORS as exc: self.LOG.error("While calling %s(%s): %s" % (method, ", ".join(repr(i) for i in args), exc)) ...
python
def execute(self, proxy, method, args): """Execute given XMLRPC call.""" try: result = getattr(proxy, method)(raw_xml=self.options.xml, *tuple(args)) except xmlrpc.ERRORS as exc: self.LOG.error("While calling %s(%s): %s" % (method, ", ".join(repr(i) for i in args), exc)) ...
[ "def", "execute", "(", "self", ",", "proxy", ",", "method", ",", "args", ")", ":", "try", ":", "result", "=", "getattr", "(", "proxy", ",", "method", ")", "(", "raw_xml", "=", "self", ".", "options", ".", "xml", ",", "*", "tuple", "(", "args", ")...
Execute given XMLRPC call.
[ "Execute", "given", "XMLRPC", "call", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtxmlrpc.py#L149-L163
train
pyroscope/pyrocore
src/pyrocore/scripts/rtxmlrpc.py
RtorrentXmlRpc.do_repl
def do_repl(self): """REPL for rTorrent XMLRPC commands.""" from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.contrib.completers import WordCompleter self.op...
python
def do_repl(self): """REPL for rTorrent XMLRPC commands.""" from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.contrib.completers import WordCompleter self.op...
[ "def", "do_repl", "(", "self", ")", ":", "from", "prompt_toolkit", "import", "prompt", "from", "prompt_toolkit", ".", "history", "import", "FileHistory", "from", "prompt_toolkit", ".", "auto_suggest", "import", "AutoSuggestFromHistory", "from", "prompt_toolkit", ".", ...
REPL for rTorrent XMLRPC commands.
[ "REPL", "for", "rTorrent", "XMLRPC", "commands", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtxmlrpc.py#L179-L224
train
pyroscope/pyrocore
src/pyrocore/scripts/rtxmlrpc.py
RtorrentXmlRpc.do_import
def do_import(self): """Handle import files or streams passed with '-i'.""" tmp_import = None try: if self.args[0].startswith('@') and self.args[0] != '@-': import_file = os.path.expanduser(self.args[0][1:]) if not os.path.isfile(import_file): ...
python
def do_import(self): """Handle import files or streams passed with '-i'.""" tmp_import = None try: if self.args[0].startswith('@') and self.args[0] != '@-': import_file = os.path.expanduser(self.args[0][1:]) if not os.path.isfile(import_file): ...
[ "def", "do_import", "(", "self", ")", ":", "tmp_import", "=", "None", "try", ":", "if", "self", ".", "args", "[", "0", "]", ".", "startswith", "(", "'@'", ")", "and", "self", ".", "args", "[", "0", "]", "!=", "'@-'", ":", "import_file", "=", "os"...
Handle import files or streams passed with '-i'.
[ "Handle", "import", "files", "or", "streams", "passed", "with", "-", "i", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtxmlrpc.py#L227-L249
train
pyroscope/pyrocore
src/pyrocore/scripts/rtxmlrpc.py
RtorrentXmlRpc.do_command
def do_command(self): """Call a single command with arguments.""" method = self.args[0] raw_args = self.args[1:] if '=' in method: if raw_args: self.parser.error("Please don't mix rTorrent and shell argument styles!") method, raw_args = method.spl...
python
def do_command(self): """Call a single command with arguments.""" method = self.args[0] raw_args = self.args[1:] if '=' in method: if raw_args: self.parser.error("Please don't mix rTorrent and shell argument styles!") method, raw_args = method.spl...
[ "def", "do_command", "(", "self", ")", ":", "method", "=", "self", ".", "args", "[", "0", "]", "raw_args", "=", "self", ".", "args", "[", "1", ":", "]", "if", "'='", "in", "method", ":", "if", "raw_args", ":", "self", ".", "parser", ".", "error",...
Call a single command with arguments.
[ "Call", "a", "single", "command", "with", "arguments", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtxmlrpc.py#L252-L263
train
pyroscope/pyrocore
src/pyrocore/scripts/pyroadmin.py
AdminTool.download_resource
def download_resource(self, download_url, target, guard): """ Helper to download and install external resources. """ download_url = download_url.strip() if not os.path.isabs(target): target = os.path.join(config.config_dir, target) if os.path.exists(os.path.join(targ...
python
def download_resource(self, download_url, target, guard): """ Helper to download and install external resources. """ download_url = download_url.strip() if not os.path.isabs(target): target = os.path.join(config.config_dir, target) if os.path.exists(os.path.join(targ...
[ "def", "download_resource", "(", "self", ",", "download_url", ",", "target", ",", "guard", ")", ":", "download_url", "=", "download_url", ".", "strip", "(", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "target", ")", ":", "target", "=", "os"...
Helper to download and install external resources.
[ "Helper", "to", "download", "and", "install", "external", "resources", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/pyroadmin.py#L81-L102
train
pyroscope/pyrocore
docs/examples/rt-down-stats.py
fmt_duration
def fmt_duration(secs): """Format a duration in seconds.""" return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())
python
def fmt_duration(secs): """Format a duration in seconds.""" return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())
[ "def", "fmt_duration", "(", "secs", ")", ":", "return", "' '", ".", "join", "(", "fmt", ".", "human_duration", "(", "secs", ",", "0", ",", "precision", "=", "2", ",", "short", "=", "True", ")", ".", "strip", "(", ")", ".", "split", "(", ")", ")" ...
Format a duration in seconds.
[ "Format", "a", "duration", "in", "seconds", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/docs/examples/rt-down-stats.py#L13-L15
train
pyroscope/pyrocore
docs/examples/rt-down-stats.py
disk_free
def disk_free(path): """Return free bytes on partition holding `path`.""" stats = os.statvfs(path) return stats.f_bavail * stats.f_frsize
python
def disk_free(path): """Return free bytes on partition holding `path`.""" stats = os.statvfs(path) return stats.f_bavail * stats.f_frsize
[ "def", "disk_free", "(", "path", ")", ":", "stats", "=", "os", ".", "statvfs", "(", "path", ")", "return", "stats", ".", "f_bavail", "*", "stats", ".", "f_frsize" ]
Return free bytes on partition holding `path`.
[ "Return", "free", "bytes", "on", "partition", "holding", "path", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/docs/examples/rt-down-stats.py#L18-L21
train
pyroscope/pyrocore
src/pyrocore/util/matching.py
truth
def truth(val, context): """ Convert truth value in "val" to a boolean. """ try: 0 + val except TypeError: lower_val = val.lower() if lower_val in TRUE: return True elif lower_val in FALSE: return False else: raise FilterError(...
python
def truth(val, context): """ Convert truth value in "val" to a boolean. """ try: 0 + val except TypeError: lower_val = val.lower() if lower_val in TRUE: return True elif lower_val in FALSE: return False else: raise FilterError(...
[ "def", "truth", "(", "val", ",", "context", ")", ":", "try", ":", "0", "+", "val", "except", "TypeError", ":", "lower_val", "=", "val", ".", "lower", "(", ")", "if", "lower_val", "in", "TRUE", ":", "return", "True", "elif", "lower_val", "in", "FALSE"...
Convert truth value in "val" to a boolean.
[ "Convert", "truth", "value", "in", "val", "to", "a", "boolean", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/matching.py#L35-L52
train
pyroscope/pyrocore
src/pyrocore/util/matching.py
_time_ym_delta
def _time_ym_delta(timestamp, delta, months): """ Helper to add a year or month delta to a timestamp. """ timestamp = list(time.localtime(timestamp)) timestamp[int(months)] += delta return time.mktime(timestamp)
python
def _time_ym_delta(timestamp, delta, months): """ Helper to add a year or month delta to a timestamp. """ timestamp = list(time.localtime(timestamp)) timestamp[int(months)] += delta return time.mktime(timestamp)
[ "def", "_time_ym_delta", "(", "timestamp", ",", "delta", ",", "months", ")", ":", "timestamp", "=", "list", "(", "time", ".", "localtime", "(", "timestamp", ")", ")", "timestamp", "[", "int", "(", "months", ")", "]", "+=", "delta", "return", "time", "....
Helper to add a year or month delta to a timestamp.
[ "Helper", "to", "add", "a", "year", "or", "month", "delta", "to", "a", "timestamp", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/matching.py#L55-L60
train
pyroscope/pyrocore
src/pyrocore/util/matching.py
unquote_pre_filter
def unquote_pre_filter(pre_filter, _regex=re.compile(r'[\\]+')): """ Unquote a pre-filter condition. """ if pre_filter.startswith('"') and pre_filter.endswith('"'): # Unquote outer level pre_filter = pre_filter[1:-1] pre_filter = _regex.sub(lambda x: x.group(0)[:len(x.group(0)) // 2]...
python
def unquote_pre_filter(pre_filter, _regex=re.compile(r'[\\]+')): """ Unquote a pre-filter condition. """ if pre_filter.startswith('"') and pre_filter.endswith('"'): # Unquote outer level pre_filter = pre_filter[1:-1] pre_filter = _regex.sub(lambda x: x.group(0)[:len(x.group(0)) // 2]...
[ "def", "unquote_pre_filter", "(", "pre_filter", ",", "_regex", "=", "re", ".", "compile", "(", "r'[\\\\]+'", ")", ")", ":", "if", "pre_filter", ".", "startswith", "(", "'\"'", ")", "and", "pre_filter", ".", "endswith", "(", "'\"'", ")", ":", "# Unquote out...
Unquote a pre-filter condition.
[ "Unquote", "a", "pre", "-", "filter", "condition", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/matching.py#L63-L71
train
pyroscope/pyrocore
src/pyrocore/util/matching.py
ConditionParser._create_filter
def _create_filter(self, condition): """ Create a filter object from a textual condition. """ # "Normal" comparison operators? comparison = re.match(r"^(%s)(<[>=]?|>=?|!=|~)(.*)$" % self.ident_re, condition) if comparison: name, comparison, values = comparison.groups(...
python
def _create_filter(self, condition): """ Create a filter object from a textual condition. """ # "Normal" comparison operators? comparison = re.match(r"^(%s)(<[>=]?|>=?|!=|~)(.*)$" % self.ident_re, condition) if comparison: name, comparison, values = comparison.groups(...
[ "def", "_create_filter", "(", "self", ",", "condition", ")", ":", "# \"Normal\" comparison operators?", "comparison", "=", "re", ".", "match", "(", "r\"^(%s)(<[>=]?|>=?|!=|~)(.*)$\"", "%", "self", ".", "ident_re", ",", "condition", ")", "if", "comparison", ":", "n...
Create a filter object from a textual condition.
[ "Create", "a", "filter", "object", "from", "a", "textual", "condition", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/matching.py#L736-L778
train
pyroscope/pyrocore
src/pyrocore/util/matching.py
ConditionParser.parse
def parse(self, conditions): """ Parse filter conditions. @param conditions: multiple conditions. @type conditions: list or str """ conditions_text = conditions try: conditions = shlex.split(fmt.to_utf8(conditions)) except AttributeError: ...
python
def parse(self, conditions): """ Parse filter conditions. @param conditions: multiple conditions. @type conditions: list or str """ conditions_text = conditions try: conditions = shlex.split(fmt.to_utf8(conditions)) except AttributeError: ...
[ "def", "parse", "(", "self", ",", "conditions", ")", ":", "conditions_text", "=", "conditions", "try", ":", "conditions", "=", "shlex", ".", "split", "(", "fmt", ".", "to_utf8", "(", "conditions", ")", ")", "except", "AttributeError", ":", "# Not a string, a...
Parse filter conditions. @param conditions: multiple conditions. @type conditions: list or str
[ "Parse", "filter", "conditions", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/matching.py#L792-L862
train
pyroscope/pyrocore
src/pyrocore/torrent/jobs.py
_flux_engine_data
def _flux_engine_data(engine): """ Return rTorrent data set for pushing to InfluxDB. """ data = stats.engine_data(engine) # Make it flat data["up_rate"] = data["upload"][0] data["up_limit"] = data["upload"][1] data["down_rate"] = data["download"][0] data["down_limit"] = data["download"]...
python
def _flux_engine_data(engine): """ Return rTorrent data set for pushing to InfluxDB. """ data = stats.engine_data(engine) # Make it flat data["up_rate"] = data["upload"][0] data["up_limit"] = data["upload"][1] data["down_rate"] = data["download"][0] data["down_limit"] = data["download"]...
[ "def", "_flux_engine_data", "(", "engine", ")", ":", "data", "=", "stats", ".", "engine_data", "(", "engine", ")", "# Make it flat", "data", "[", "\"up_rate\"", "]", "=", "data", "[", "\"upload\"", "]", "[", "0", "]", "data", "[", "\"up_limit\"", "]", "=...
Return rTorrent data set for pushing to InfluxDB.
[ "Return", "rTorrent", "data", "set", "for", "pushing", "to", "InfluxDB", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/jobs.py#L35-L53
train
pyroscope/pyrocore
src/pyrocore/torrent/jobs.py
EngineStats.run
def run(self): """ Statistics logger job callback. """ try: proxy = config_ini.engine.open() self.LOG.info("Stats for %s - up %s, %s" % ( config_ini.engine.engine_id, fmt.human_duration(proxy.system.time() - config_ini.engine.startup, 0, 2,...
python
def run(self): """ Statistics logger job callback. """ try: proxy = config_ini.engine.open() self.LOG.info("Stats for %s - up %s, %s" % ( config_ini.engine.engine_id, fmt.human_duration(proxy.system.time() - config_ini.engine.startup, 0, 2,...
[ "def", "run", "(", "self", ")", ":", "try", ":", "proxy", "=", "config_ini", ".", "engine", ".", "open", "(", ")", "self", ".", "LOG", ".", "info", "(", "\"Stats for %s - up %s, %s\"", "%", "(", "config_ini", ".", "engine", ".", "engine_id", ",", "fmt"...
Statistics logger job callback.
[ "Statistics", "logger", "job", "callback", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/jobs.py#L68-L79
train
pyroscope/pyrocore
src/pyrocore/torrent/jobs.py
InfluxDBStats._influxdb_url
def _influxdb_url(self): """ Return REST API URL to access time series. """ url = "{0}/db/{1}/series".format(self.influxdb.url.rstrip('/'), self.config.dbname) if self.influxdb.user and self.influxdb.password: url += "?u={0}&p={1}".format(self.influxdb.user, self.influxdb.pa...
python
def _influxdb_url(self): """ Return REST API URL to access time series. """ url = "{0}/db/{1}/series".format(self.influxdb.url.rstrip('/'), self.config.dbname) if self.influxdb.user and self.influxdb.password: url += "?u={0}&p={1}".format(self.influxdb.user, self.influxdb.pa...
[ "def", "_influxdb_url", "(", "self", ")", ":", "url", "=", "\"{0}/db/{1}/series\"", ".", "format", "(", "self", ".", "influxdb", ".", "url", ".", "rstrip", "(", "'/'", ")", ",", "self", ".", "config", ".", "dbname", ")", "if", "self", ".", "influxdb", ...
Return REST API URL to access time series.
[ "Return", "REST", "API", "URL", "to", "access", "time", "series", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/jobs.py#L99-L107
train
pyroscope/pyrocore
src/pyrocore/torrent/jobs.py
InfluxDBStats._push_data
def _push_data(self): """ Push stats data to InfluxDB. """ if not (self.config.series or self.config.series_host): self.LOG.info("Misconfigured InfluxDB job, neither 'series' nor 'series_host' is set!") return # Assemble data fluxdata = [] if sel...
python
def _push_data(self): """ Push stats data to InfluxDB. """ if not (self.config.series or self.config.series_host): self.LOG.info("Misconfigured InfluxDB job, neither 'series' nor 'series_host' is set!") return # Assemble data fluxdata = [] if sel...
[ "def", "_push_data", "(", "self", ")", ":", "if", "not", "(", "self", ".", "config", ".", "series", "or", "self", ".", "config", ".", "series_host", ")", ":", "self", ".", "LOG", ".", "info", "(", "\"Misconfigured InfluxDB job, neither 'series' nor 'series_hos...
Push stats data to InfluxDB.
[ "Push", "stats", "data", "to", "InfluxDB", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/jobs.py#L110-L158
train
pyroscope/pyrocore
src/pyrocore/torrent/filter.py
FilterJobBase.run
def run(self): """ Filter job callback. """ from pyrocore import config try: config.engine.open() # TODO: select view into items items = [] self.run_filter(items) except (error.LoggableError, xmlrpc.ERRORS) as exc: self...
python
def run(self): """ Filter job callback. """ from pyrocore import config try: config.engine.open() # TODO: select view into items items = [] self.run_filter(items) except (error.LoggableError, xmlrpc.ERRORS) as exc: self...
[ "def", "run", "(", "self", ")", ":", "from", "pyrocore", "import", "config", "try", ":", "config", ".", "engine", ".", "open", "(", ")", "# TODO: select view into items", "items", "=", "[", "]", "self", ".", "run_filter", "(", "items", ")", "except", "("...
Filter job callback.
[ "Filter", "job", "callback", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/filter.py#L38-L49
train
pyroscope/pyrocore
src/pyrocore/scripts/chtor.py
replace_fields
def replace_fields(meta, patterns): """ Replace patterns in fields. """ for pattern in patterns: try: field, regex, subst, _ = pattern.split(pattern[-1]) # TODO: Allow numerical indices, and "+" for append namespace = meta keypath = [i.replace('\0', '...
python
def replace_fields(meta, patterns): """ Replace patterns in fields. """ for pattern in patterns: try: field, regex, subst, _ = pattern.split(pattern[-1]) # TODO: Allow numerical indices, and "+" for append namespace = meta keypath = [i.replace('\0', '...
[ "def", "replace_fields", "(", "meta", ",", "patterns", ")", ":", "for", "pattern", "in", "patterns", ":", "try", ":", "field", ",", "regex", ",", "subst", ",", "_", "=", "pattern", ".", "split", "(", "pattern", "[", "-", "1", "]", ")", "# TODO: Allow...
Replace patterns in fields.
[ "Replace", "patterns", "in", "fields", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/chtor.py#L34-L51
train
pyroscope/pyrocore
src/pyrocore/__init__.py
connect
def connect(config_dir=None, optional_config_files=None, cron_cfg="cron"): """ Initialize everything for interactive use. Returns a ready-to-use RtorrentEngine object. """ from pyrocore.scripts.base import ScriptBase from pyrocore.util import load_config ScriptBase.setup(cron_cfg=cron_cfg)...
python
def connect(config_dir=None, optional_config_files=None, cron_cfg="cron"): """ Initialize everything for interactive use. Returns a ready-to-use RtorrentEngine object. """ from pyrocore.scripts.base import ScriptBase from pyrocore.util import load_config ScriptBase.setup(cron_cfg=cron_cfg)...
[ "def", "connect", "(", "config_dir", "=", "None", ",", "optional_config_files", "=", "None", ",", "cron_cfg", "=", "\"cron\"", ")", ":", "from", "pyrocore", ".", "scripts", ".", "base", "import", "ScriptBase", "from", "pyrocore", ".", "util", "import", "load...
Initialize everything for interactive use. Returns a ready-to-use RtorrentEngine object.
[ "Initialize", "everything", "for", "interactive", "use", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/__init__.py#L23-L36
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBase.setup
def setup(cls, cron_cfg="cron"): """ Set up the runtime environment. """ random.seed() logging_cfg = cls.LOGGING_CFG if "%s" in logging_cfg: logging_cfg = logging_cfg % (cron_cfg if "--cron" in sys.argv[1:] else "scripts",) logging_cfg = os.path.expanduser(log...
python
def setup(cls, cron_cfg="cron"): """ Set up the runtime environment. """ random.seed() logging_cfg = cls.LOGGING_CFG if "%s" in logging_cfg: logging_cfg = logging_cfg % (cron_cfg if "--cron" in sys.argv[1:] else "scripts",) logging_cfg = os.path.expanduser(log...
[ "def", "setup", "(", "cls", ",", "cron_cfg", "=", "\"cron\"", ")", ":", "random", ".", "seed", "(", ")", "logging_cfg", "=", "cls", ".", "LOGGING_CFG", "if", "\"%s\"", "in", "logging_cfg", ":", "logging_cfg", "=", "logging_cfg", "%", "(", "cron_cfg", "if...
Set up the runtime environment.
[ "Set", "up", "the", "runtime", "environment", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L61-L76
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBase._get_pkg_meta
def _get_pkg_meta(self): """ Try to find package metadata. """ logger = logging.getLogger('pyrocore.scripts.base.version_info') pkg_info = None warnings = [] for info_ext, info_name in (('.dist-info', 'METADATA'), ('.egg-info', 'PKG-INFO')): try: ...
python
def _get_pkg_meta(self): """ Try to find package metadata. """ logger = logging.getLogger('pyrocore.scripts.base.version_info') pkg_info = None warnings = [] for info_ext, info_name in (('.dist-info', 'METADATA'), ('.egg-info', 'PKG-INFO')): try: ...
[ "def", "_get_pkg_meta", "(", "self", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'pyrocore.scripts.base.version_info'", ")", "pkg_info", "=", "None", "warnings", "=", "[", "]", "for", "info_ext", ",", "info_name", "in", "(", "(", "'.dist-info'"...
Try to find package metadata.
[ "Try", "to", "find", "package", "metadata", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L79-L121
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBase.add_bool_option
def add_bool_option(self, *args, **kwargs): """ Add a boolean option. @keyword help: Option description. """ dest = [o for o in args if o.startswith("--")][0].replace("--", "").replace("-", "_") self.parser.add_option(dest=dest, action="store_true", default=False, ...
python
def add_bool_option(self, *args, **kwargs): """ Add a boolean option. @keyword help: Option description. """ dest = [o for o in args if o.startswith("--")][0].replace("--", "").replace("-", "_") self.parser.add_option(dest=dest, action="store_true", default=False, ...
[ "def", "add_bool_option", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "dest", "=", "[", "o", "for", "o", "in", "args", "if", "o", ".", "startswith", "(", "\"--\"", ")", "]", "[", "0", "]", ".", "replace", "(", "\"--\"", ",...
Add a boolean option. @keyword help: Option description.
[ "Add", "a", "boolean", "option", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L162-L169
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBase.add_value_option
def add_value_option(self, *args, **kwargs): """ Add a value option. @keyword dest: Destination attribute, derived from long option name if not given. @keyword action: How to handle the option. @keyword help: Option description. @keyword default: If given, add th...
python
def add_value_option(self, *args, **kwargs): """ Add a value option. @keyword dest: Destination attribute, derived from long option name if not given. @keyword action: How to handle the option. @keyword help: Option description. @keyword default: If given, add th...
[ "def", "add_value_option", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'metavar'", "]", "=", "args", "[", "-", "1", "]", "if", "'dest'", "not", "in", "kwargs", ":", "kwargs", "[", "'dest'", "]", "=", "[", "o"...
Add a value option. @keyword dest: Destination attribute, derived from long option name if not given. @keyword action: How to handle the option. @keyword help: Option description. @keyword default: If given, add this value to the help string.
[ "Add", "a", "value", "option", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L172-L185
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBase.handle_completion
def handle_completion(self): """ Handle shell completion stuff. """ # We don't want these in the help, so handle them explicitely if len(sys.argv) > 1 and sys.argv[1].startswith("--help-completion-"): handler = getattr(self, sys.argv[1][2:].replace('-', '_'), None) ...
python
def handle_completion(self): """ Handle shell completion stuff. """ # We don't want these in the help, so handle them explicitely if len(sys.argv) > 1 and sys.argv[1].startswith("--help-completion-"): handler = getattr(self, sys.argv[1][2:].replace('-', '_'), None) ...
[ "def", "handle_completion", "(", "self", ")", ":", "# We don't want these in the help, so handle them explicitely", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", "and", "sys", ".", "argv", "[", "1", "]", ".", "startswith", "(", "\"--help-completion-\"", "...
Handle shell completion stuff.
[ "Handle", "shell", "completion", "stuff", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L224-L233
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBase.help_completion_options
def help_completion_options(self): """ Return options of this command. """ for opt in self.parser.option_list: for lopt in opt._long_opts: yield lopt
python
def help_completion_options(self): """ Return options of this command. """ for opt in self.parser.option_list: for lopt in opt._long_opts: yield lopt
[ "def", "help_completion_options", "(", "self", ")", ":", "for", "opt", "in", "self", ".", "parser", ".", "option_list", ":", "for", "lopt", "in", "opt", ".", "_long_opts", ":", "yield", "lopt" ]
Return options of this command.
[ "Return", "options", "of", "this", "command", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L236-L241
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBase.fatal
def fatal(self, msg, exc=None): """ Exit on a fatal error. """ if exc is not None: self.LOG.fatal("%s (%s)" % (msg, exc)) if self.options.debug: return # let the caller re-raise it else: self.LOG.fatal(msg) sys.exit(error.EX_SOF...
python
def fatal(self, msg, exc=None): """ Exit on a fatal error. """ if exc is not None: self.LOG.fatal("%s (%s)" % (msg, exc)) if self.options.debug: return # let the caller re-raise it else: self.LOG.fatal(msg) sys.exit(error.EX_SOF...
[ "def", "fatal", "(", "self", ",", "msg", ",", "exc", "=", "None", ")", ":", "if", "exc", "is", "not", "None", ":", "self", ".", "LOG", ".", "fatal", "(", "\"%s (%s)\"", "%", "(", "msg", ",", "exc", ")", ")", "if", "self", ".", "options", ".", ...
Exit on a fatal error.
[ "Exit", "on", "a", "fatal", "error", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L244-L253
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBase.run
def run(self): """ The main program skeleton. """ log_total = True try: try: # Preparation steps self.get_options() # Template method with the tool's main loop self.mainloop() except error.LoggableE...
python
def run(self): """ The main program skeleton. """ log_total = True try: try: # Preparation steps self.get_options() # Template method with the tool's main loop self.mainloop() except error.LoggableE...
[ "def", "run", "(", "self", ")", ":", "log_total", "=", "True", "try", ":", "try", ":", "# Preparation steps", "self", ".", "get_options", "(", ")", "# Template method with the tool's main loop", "self", ".", "mainloop", "(", ")", "except", "error", ".", "Logga...
The main program skeleton.
[ "The", "main", "program", "skeleton", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L256-L317
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBaseWithConfig.add_options
def add_options(self): """ Add configuration options. """ super(ScriptBaseWithConfig, self).add_options() self.add_value_option("--config-dir", "DIR", help="configuration directory [{}]".format(os.environ.get('PYRO_CONFIG_DIR', self.CONFIG_DIR_DEFAULT))) self.add_val...
python
def add_options(self): """ Add configuration options. """ super(ScriptBaseWithConfig, self).add_options() self.add_value_option("--config-dir", "DIR", help="configuration directory [{}]".format(os.environ.get('PYRO_CONFIG_DIR', self.CONFIG_DIR_DEFAULT))) self.add_val...
[ "def", "add_options", "(", "self", ")", ":", "super", "(", "ScriptBaseWithConfig", ",", "self", ")", ".", "add_options", "(", ")", "self", ".", "add_value_option", "(", "\"--config-dir\"", ",", "\"DIR\"", ",", "help", "=", "\"configuration directory [{}]\"", "."...
Add configuration options.
[ "Add", "configuration", "options", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L338-L350
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
ScriptBaseWithConfig.check_for_connection
def check_for_connection(self): """ Scan arguments for a `@name` one. """ for idx, arg in enumerate(self.args): if arg.startswith('@'): if arg[1:] not in config.connections: self.parser.error("Undefined connection '{}'!".format(arg[1:])) ...
python
def check_for_connection(self): """ Scan arguments for a `@name` one. """ for idx, arg in enumerate(self.args): if arg.startswith('@'): if arg[1:] not in config.connections: self.parser.error("Undefined connection '{}'!".format(arg[1:])) ...
[ "def", "check_for_connection", "(", "self", ")", ":", "for", "idx", ",", "arg", "in", "enumerate", "(", "self", ".", "args", ")", ":", "if", "arg", ".", "startswith", "(", "'@'", ")", ":", "if", "arg", "[", "1", ":", "]", "not", "in", "config", "...
Scan arguments for a `@name` one.
[ "Scan", "arguments", "for", "a" ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L374-L384
train
pyroscope/pyrocore
src/pyrocore/scripts/base.py
PromptDecorator.quit
def quit(self): """ Exit the program due to user's choices. """ self.script.LOG.warn("Abort due to user choice!") sys.exit(self.QUIT_RC)
python
def quit(self): """ Exit the program due to user's choices. """ self.script.LOG.warn("Abort due to user choice!") sys.exit(self.QUIT_RC)
[ "def", "quit", "(", "self", ")", ":", "self", ".", "script", ".", "LOG", ".", "warn", "(", "\"Abort due to user choice!\"", ")", "sys", ".", "exit", "(", "self", ".", "QUIT_RC", ")" ]
Exit the program due to user's choices.
[ "Exit", "the", "program", "due", "to", "user", "s", "choices", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L443-L447
train
pyroscope/pyrocore
src/pyrocore/daemon/webapp.py
redirect
def redirect(req, _log=pymagic.get_lazy_logger("redirect")): """ Redirect controller to emit a HTTP 301. """ log = req.environ.get("wsgilog.logger", _log) target = req.relative_url(req.urlvars.to) log.info("Redirecting '%s' to '%s'" % (req.url, target)) return exc.HTTPMovedPermanently(location=t...
python
def redirect(req, _log=pymagic.get_lazy_logger("redirect")): """ Redirect controller to emit a HTTP 301. """ log = req.environ.get("wsgilog.logger", _log) target = req.relative_url(req.urlvars.to) log.info("Redirecting '%s' to '%s'" % (req.url, target)) return exc.HTTPMovedPermanently(location=t...
[ "def", "redirect", "(", "req", ",", "_log", "=", "pymagic", ".", "get_lazy_logger", "(", "\"redirect\"", ")", ")", ":", "log", "=", "req", ".", "environ", ".", "get", "(", "\"wsgilog.logger\"", ",", "_log", ")", "target", "=", "req", ".", "relative_url",...
Redirect controller to emit a HTTP 301.
[ "Redirect", "controller", "to", "emit", "a", "HTTP", "301", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/daemon/webapp.py#L228-L234
train
pyroscope/pyrocore
src/pyrocore/daemon/webapp.py
make_app
def make_app(httpd_config): """ Factory for the monitoring webapp. """ #mimetypes.add_type('image/vnd.microsoft.icon', '.ico') # Default paths to serve static file from htdocs_paths = [ os.path.realpath(os.path.join(config.config_dir, "htdocs")), os.path.join(os.path.dirname(config....
python
def make_app(httpd_config): """ Factory for the monitoring webapp. """ #mimetypes.add_type('image/vnd.microsoft.icon', '.ico') # Default paths to serve static file from htdocs_paths = [ os.path.realpath(os.path.join(config.config_dir, "htdocs")), os.path.join(os.path.dirname(config....
[ "def", "make_app", "(", "httpd_config", ")", ":", "#mimetypes.add_type('image/vnd.microsoft.icon', '.ico')", "# Default paths to serve static file from", "htdocs_paths", "=", "[", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "config", ...
Factory for the monitoring webapp.
[ "Factory", "for", "the", "monitoring", "webapp", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/daemon/webapp.py#L237-L253
train
pyroscope/pyrocore
src/pyrocore/daemon/webapp.py
JsonController.guarded
def guarded(self, func, *args, **kwargs): """ Call a function, return None on errors. """ try: return func(*args, **kwargs) except (EnvironmentError, error.LoggableError, xmlrpc.ERRORS) as g_exc: if func.__name__ not in self.ERRORS_LOGGED: self.LOG...
python
def guarded(self, func, *args, **kwargs): """ Call a function, return None on errors. """ try: return func(*args, **kwargs) except (EnvironmentError, error.LoggableError, xmlrpc.ERRORS) as g_exc: if func.__name__ not in self.ERRORS_LOGGED: self.LOG...
[ "def", "guarded", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "(", "EnvironmentError", ",", "error", ".", "LoggableError", ",...
Call a function, return None on errors.
[ "Call", "a", "function", "return", "None", "on", "errors", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/daemon/webapp.py#L112-L121
train
pyroscope/pyrocore
src/pyrocore/daemon/webapp.py
JsonController.json_engine
def json_engine(self, req): # pylint: disable=R0201,W0613 """ Return torrent engine data. """ try: return stats.engine_data(config.engine) except (error.LoggableError, xmlrpc.ERRORS) as torrent_exc: raise exc.HTTPInternalServerError(str(torrent_exc))
python
def json_engine(self, req): # pylint: disable=R0201,W0613 """ Return torrent engine data. """ try: return stats.engine_data(config.engine) except (error.LoggableError, xmlrpc.ERRORS) as torrent_exc: raise exc.HTTPInternalServerError(str(torrent_exc))
[ "def", "json_engine", "(", "self", ",", "req", ")", ":", "# pylint: disable=R0201,W0613", "try", ":", "return", "stats", ".", "engine_data", "(", "config", ".", "engine", ")", "except", "(", "error", ".", "LoggableError", ",", "xmlrpc", ".", "ERRORS", ")", ...
Return torrent engine data.
[ "Return", "torrent", "engine", "data", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/daemon/webapp.py#L124-L130
train
pyroscope/pyrocore
src/pyrocore/daemon/webapp.py
JsonController.json_charts
def json_charts(self, req): """ Return charting data. """ disk_used, disk_total, disk_detail = 0, 0, [] for disk_usage_path in self.cfg.disk_usage_path.split(os.pathsep): disk_usage = self.guarded(psutil.disk_usage, os.path.expanduser(disk_usage_path.strip())) if ...
python
def json_charts(self, req): """ Return charting data. """ disk_used, disk_total, disk_detail = 0, 0, [] for disk_usage_path in self.cfg.disk_usage_path.split(os.pathsep): disk_usage = self.guarded(psutil.disk_usage, os.path.expanduser(disk_usage_path.strip())) if ...
[ "def", "json_charts", "(", "self", ",", "req", ")", ":", "disk_used", ",", "disk_total", ",", "disk_detail", "=", "0", ",", "0", ",", "[", "]", "for", "disk_usage_path", "in", "self", ".", "cfg", ".", "disk_usage_path", ".", "split", "(", "os", ".", ...
Return charting data.
[ "Return", "charting", "data", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/daemon/webapp.py#L133-L155
train
pyroscope/pyrocore
src/pyrocore/daemon/webapp.py
Router.parse_route
def parse_route(cls, template): """ Parse a route definition, and return the compiled regex that matches it. """ regex = '' last_pos = 0 for match in cls.ROUTES_RE.finditer(template): regex += re.escape(template[last_pos:match.start()]) var_name = match.g...
python
def parse_route(cls, template): """ Parse a route definition, and return the compiled regex that matches it. """ regex = '' last_pos = 0 for match in cls.ROUTES_RE.finditer(template): regex += re.escape(template[last_pos:match.start()]) var_name = match.g...
[ "def", "parse_route", "(", "cls", ",", "template", ")", ":", "regex", "=", "''", "last_pos", "=", "0", "for", "match", "in", "cls", ".", "ROUTES_RE", ".", "finditer", "(", "template", ")", ":", "regex", "+=", "re", ".", "escape", "(", "template", "["...
Parse a route definition, and return the compiled regex that matches it.
[ "Parse", "a", "route", "definition", "and", "return", "the", "compiled", "regex", "that", "matches", "it", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/daemon/webapp.py#L173-L190
train
pyroscope/pyrocore
src/pyrocore/daemon/webapp.py
Router.add_route
def add_route(self, template, controller, **kwargs): """ Add a route definition `controller` can be either a controller instance, or the name of a callable that will be imported. """ if isinstance(controller, basestring): controller = pymagic.import_name(cont...
python
def add_route(self, template, controller, **kwargs): """ Add a route definition `controller` can be either a controller instance, or the name of a callable that will be imported. """ if isinstance(controller, basestring): controller = pymagic.import_name(cont...
[ "def", "add_route", "(", "self", ",", "template", ",", "controller", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "controller", ",", "basestring", ")", ":", "controller", "=", "pymagic", ".", "import_name", "(", "controller", ")", "self", ...
Add a route definition `controller` can be either a controller instance, or the name of a callable that will be imported.
[ "Add", "a", "route", "definition" ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/daemon/webapp.py#L198-L209
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
_duration
def _duration(start, end): """ Return time delta. """ if start and end: if start > end: return None else: return end - start elif start: return time.time() - start else: return None
python
def _duration(start, end): """ Return time delta. """ if start and end: if start > end: return None else: return end - start elif start: return time.time() - start else: return None
[ "def", "_duration", "(", "start", ",", "end", ")", ":", "if", "start", "and", "end", ":", "if", "start", ">", "end", ":", "return", "None", "else", ":", "return", "end", "-", "start", "elif", "start", ":", "return", "time", ".", "time", "(", ")", ...
Return time delta.
[ "Return", "time", "delta", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L53-L64
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
_fmt_files
def _fmt_files(filelist): """ Produce a file listing. """ depth = max(i.path.count('/') for i in filelist) pad = ['\uFFFE'] * depth base_indent = ' ' * 38 indent = 0 result = [] prev_path = pad sorted_files = sorted((i.path.split('/')[:-1]+pad, i.path.rsplit('/', 1)[-1], i) for i in...
python
def _fmt_files(filelist): """ Produce a file listing. """ depth = max(i.path.count('/') for i in filelist) pad = ['\uFFFE'] * depth base_indent = ' ' * 38 indent = 0 result = [] prev_path = pad sorted_files = sorted((i.path.split('/')[:-1]+pad, i.path.rsplit('/', 1)[-1], i) for i in...
[ "def", "_fmt_files", "(", "filelist", ")", ":", "depth", "=", "max", "(", "i", ".", "path", ".", "count", "(", "'/'", ")", "for", "i", "in", "filelist", ")", "pad", "=", "[", "'\\uFFFE'", "]", "*", "depth", "base_indent", "=", "' '", "*", "38", "...
Produce a file listing.
[ "Produce", "a", "file", "listing", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L142-L190
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
detect_traits
def detect_traits(item): """ Build traits list from attributes of the passed item. Currently, "kind_51", "name" and "alias" are considered. See pyrocore.util.traits:dectect_traits for more details. """ return traits.detect_traits( name=item.name, alias=item.alias, filetype=(...
python
def detect_traits(item): """ Build traits list from attributes of the passed item. Currently, "kind_51", "name" and "alias" are considered. See pyrocore.util.traits:dectect_traits for more details. """ return traits.detect_traits( name=item.name, alias=item.alias, filetype=(...
[ "def", "detect_traits", "(", "item", ")", ":", "return", "traits", ".", "detect_traits", "(", "name", "=", "item", ".", "name", ",", "alias", "=", "item", ".", "alias", ",", "filetype", "=", "(", "list", "(", "item", ".", "fetch", "(", "\"kind_51\"", ...
Build traits list from attributes of the passed item. Currently, "kind_51", "name" and "alias" are considered. See pyrocore.util.traits:dectect_traits for more details.
[ "Build", "traits", "list", "from", "attributes", "of", "the", "passed", "item", ".", "Currently", "kind_51", "name", "and", "alias", "are", "considered", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L193-L202
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
TorrentProxy.add_manifold_attribute
def add_manifold_attribute(cls, name): """ Register a manifold engine attribute. @return: field definition object, or None if "name" isn't a manifold attribute. """ if name.startswith("custom_"): try: return FieldDefinition.FIELDS[name] except...
python
def add_manifold_attribute(cls, name): """ Register a manifold engine attribute. @return: field definition object, or None if "name" isn't a manifold attribute. """ if name.startswith("custom_"): try: return FieldDefinition.FIELDS[name] except...
[ "def", "add_manifold_attribute", "(", "cls", ",", "name", ")", ":", "if", "name", ".", "startswith", "(", "\"custom_\"", ")", ":", "try", ":", "return", "FieldDefinition", ".", "FIELDS", "[", "name", "]", "except", "KeyError", ":", "field", "=", "OnDemandF...
Register a manifold engine attribute. @return: field definition object, or None if "name" isn't a manifold attribute.
[ "Register", "a", "manifold", "engine", "attribute", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L304-L331
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
TorrentProxy.add_custom_fields
def add_custom_fields(cls, *args, **kw): """ Add any custom fields defined in the configuration. """ for factory in config.custom_field_factories: for field in factory(): setattr(cls, field.name, field)
python
def add_custom_fields(cls, *args, **kw): """ Add any custom fields defined in the configuration. """ for factory in config.custom_field_factories: for field in factory(): setattr(cls, field.name, field)
[ "def", "add_custom_fields", "(", "cls", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "for", "factory", "in", "config", ".", "custom_field_factories", ":", "for", "field", "in", "factory", "(", ")", ":", "setattr", "(", "cls", ",", "field", ".", "...
Add any custom fields defined in the configuration.
[ "Add", "any", "custom", "fields", "defined", "in", "the", "configuration", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L335-L340
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
TorrentView._fetch_items
def _fetch_items(self): """ Fetch to attribute. """ if self._items is None: self._items = list(self.engine.items(self)) return self._items
python
def _fetch_items(self): """ Fetch to attribute. """ if self._items is None: self._items = list(self.engine.items(self)) return self._items
[ "def", "_fetch_items", "(", "self", ")", ":", "if", "self", ".", "_items", "is", "None", ":", "self", ".", "_items", "=", "list", "(", "self", ".", "engine", ".", "items", "(", "self", ")", ")", "return", "self", ".", "_items" ]
Fetch to attribute.
[ "Fetch", "to", "attribute", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L605-L611
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
TorrentView._check_hash_view
def _check_hash_view(self): """ Return infohash if view name refers to a single item, else None. """ infohash = None if self.viewname.startswith('#'): infohash = self.viewname[1:] elif len(self.viewname) == 40: try: int(self.viewname, 16) ...
python
def _check_hash_view(self): """ Return infohash if view name refers to a single item, else None. """ infohash = None if self.viewname.startswith('#'): infohash = self.viewname[1:] elif len(self.viewname) == 40: try: int(self.viewname, 16) ...
[ "def", "_check_hash_view", "(", "self", ")", ":", "infohash", "=", "None", "if", "self", ".", "viewname", ".", "startswith", "(", "'#'", ")", ":", "infohash", "=", "self", ".", "viewname", "[", "1", ":", "]", "elif", "len", "(", "self", ".", "viewnam...
Return infohash if view name refers to a single item, else None.
[ "Return", "infohash", "if", "view", "name", "refers", "to", "a", "single", "item", "else", "None", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L614-L627
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
TorrentView.size
def size(self): """ Total unfiltered size of view. """ #return len(self._fetch_items()) if self._check_hash_view(): return 1 else: return self.engine.open().view.size(xmlrpc.NOHASH, self.viewname)
python
def size(self): """ Total unfiltered size of view. """ #return len(self._fetch_items()) if self._check_hash_view(): return 1 else: return self.engine.open().view.size(xmlrpc.NOHASH, self.viewname)
[ "def", "size", "(", "self", ")", ":", "#return len(self._fetch_items())", "if", "self", ".", "_check_hash_view", "(", ")", ":", "return", "1", "else", ":", "return", "self", ".", "engine", ".", "open", "(", ")", ".", "view", ".", "size", "(", "xmlrpc", ...
Total unfiltered size of view.
[ "Total", "unfiltered", "size", "of", "view", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L630-L637
train
pyroscope/pyrocore
src/pyrocore/torrent/engine.py
TorrentEngine.group_by
def group_by(self, fields, items=None): """ Returns a dict of lists of items, grouped by the given fields. ``fields`` can be a string (one field) or an iterable of field names. """ result = defaultdict(list) if items is None: items = self.items() try: ...
python
def group_by(self, fields, items=None): """ Returns a dict of lists of items, grouped by the given fields. ``fields`` can be a string (one field) or an iterable of field names. """ result = defaultdict(list) if items is None: items = self.items() try: ...
[ "def", "group_by", "(", "self", ",", "fields", ",", "items", "=", "None", ")", ":", "result", "=", "defaultdict", "(", "list", ")", "if", "items", "is", "None", ":", "items", "=", "self", ".", "items", "(", ")", "try", ":", "key", "=", "operator", ...
Returns a dict of lists of items, grouped by the given fields. ``fields`` can be a string (one field) or an iterable of field names.
[ "Returns", "a", "dict", "of", "lists", "of", "items", "grouped", "by", "the", "given", "fields", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/engine.py#L700-L719
train
pyroscope/pyrocore
src/pyrocore/util/xmlrpc.py
RTorrentProxy._set_mappings
def _set_mappings(self): """ Set command mappings according to rTorrent version. """ try: self._versions = (self.system.client_version(), self.system.library_version(),) self._version_info = tuple(int(i) for i in self._versions[0].split('.')) self._use_depreca...
python
def _set_mappings(self): """ Set command mappings according to rTorrent version. """ try: self._versions = (self.system.client_version(), self.system.library_version(),) self._version_info = tuple(int(i) for i in self._versions[0].split('.')) self._use_depreca...
[ "def", "_set_mappings", "(", "self", ")", ":", "try", ":", "self", ".", "_versions", "=", "(", "self", ".", "system", ".", "client_version", "(", ")", ",", "self", ".", "system", ".", "library_version", "(", ")", ",", ")", "self", ".", "_version_info",...
Set command mappings according to rTorrent version.
[ "Set", "command", "mappings", "according", "to", "rTorrent", "version", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/xmlrpc.py#L241-L261
train
pyroscope/pyrocore
src/pyrocore/util/xmlrpc.py
RTorrentProxy._fix_mappings
def _fix_mappings(self): """ Add computed stuff to mappings. """ self._mapping.update((key+'=', val+'=') for key, val in self._mapping.items() if not key.endswith('=')) if config.debug: self.LOG.debug("CMD MAPPINGS ARE: %r" % (self._mapping,))
python
def _fix_mappings(self): """ Add computed stuff to mappings. """ self._mapping.update((key+'=', val+'=') for key, val in self._mapping.items() if not key.endswith('=')) if config.debug: self.LOG.debug("CMD MAPPINGS ARE: %r" % (self._mapping,))
[ "def", "_fix_mappings", "(", "self", ")", ":", "self", ".", "_mapping", ".", "update", "(", "(", "key", "+", "'='", ",", "val", "+", "'='", ")", "for", "key", ",", "val", "in", "self", ".", "_mapping", ".", "items", "(", ")", "if", "not", "key", ...
Add computed stuff to mappings.
[ "Add", "computed", "stuff", "to", "mappings", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/xmlrpc.py#L264-L270
train
pyroscope/pyrocore
src/pyrocore/util/xmlrpc.py
RTorrentProxy._map_call
def _map_call(self, cmd): """ Map old to new command names. """ if config.debug and cmd != self._mapping.get(cmd, cmd): self.LOG.debug("MAP %s ==> %s" % (cmd, self._mapping[cmd])) cmd = self._mapping.get(cmd, cmd) # These we do by code, to avoid lengthy lists in the ...
python
def _map_call(self, cmd): """ Map old to new command names. """ if config.debug and cmd != self._mapping.get(cmd, cmd): self.LOG.debug("MAP %s ==> %s" % (cmd, self._mapping[cmd])) cmd = self._mapping.get(cmd, cmd) # These we do by code, to avoid lengthy lists in the ...
[ "def", "_map_call", "(", "self", ",", "cmd", ")", ":", "if", "config", ".", "debug", "and", "cmd", "!=", "self", ".", "_mapping", ".", "get", "(", "cmd", ",", "cmd", ")", ":", "self", ".", "LOG", ".", "debug", "(", "\"MAP %s ==> %s\"", "%", "(", ...
Map old to new command names.
[ "Map", "old", "to", "new", "command", "names", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/xmlrpc.py#L273-L284
train
pyroscope/pyrocore
src/pyrocore/torrent/watch.py
MetafileHandler.parse
def parse(self): """ Parse metafile and check pre-conditions. """ try: if not os.path.getsize(self.ns.pathname): # Ignore 0-byte dummy files (Firefox creates these while downloading) self.job.LOG.warn("Ignoring 0-byte metafile '%s'" % (self.ns.pathname...
python
def parse(self): """ Parse metafile and check pre-conditions. """ try: if not os.path.getsize(self.ns.pathname): # Ignore 0-byte dummy files (Firefox creates these while downloading) self.job.LOG.warn("Ignoring 0-byte metafile '%s'" % (self.ns.pathname...
[ "def", "parse", "(", "self", ")", ":", "try", ":", "if", "not", "os", ".", "path", ".", "getsize", "(", "self", ".", "ns", ".", "pathname", ")", ":", "# Ignore 0-byte dummy files (Firefox creates these while downloading)", "self", ".", "job", ".", "LOG", "."...
Parse metafile and check pre-conditions.
[ "Parse", "metafile", "and", "check", "pre", "-", "conditions", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/watch.py#L59-L94
train
pyroscope/pyrocore
src/pyrocore/torrent/watch.py
MetafileHandler.addinfo
def addinfo(self): """ Add known facts to templating namespace. """ # Basic values self.ns.watch_path = self.job.config.path self.ns.relpath = None for watch in self.job.config.path: if self.ns.pathname.startswith(watch.rstrip('/') + '/'): self...
python
def addinfo(self): """ Add known facts to templating namespace. """ # Basic values self.ns.watch_path = self.job.config.path self.ns.relpath = None for watch in self.job.config.path: if self.ns.pathname.startswith(watch.rstrip('/') + '/'): self...
[ "def", "addinfo", "(", "self", ")", ":", "# Basic values", "self", ".", "ns", ".", "watch_path", "=", "self", ".", "job", ".", "config", ".", "path", "self", ".", "ns", ".", "relpath", "=", "None", "for", "watch", "in", "self", ".", "job", ".", "co...
Add known facts to templating namespace.
[ "Add", "known", "facts", "to", "templating", "namespace", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/watch.py#L97-L137
train
pyroscope/pyrocore
src/pyrocore/torrent/watch.py
MetafileHandler.load
def load(self): """ Load metafile into client. """ if not self.ns.info_hash and not self.parse(): return self.addinfo() # TODO: dry_run try: # TODO: Scrub metafile if requested # Determine target state start_it = self.job...
python
def load(self): """ Load metafile into client. """ if not self.ns.info_hash and not self.parse(): return self.addinfo() # TODO: dry_run try: # TODO: Scrub metafile if requested # Determine target state start_it = self.job...
[ "def", "load", "(", "self", ")", ":", "if", "not", "self", ".", "ns", ".", "info_hash", "and", "not", "self", ".", "parse", "(", ")", ":", "return", "self", ".", "addinfo", "(", ")", "# TODO: dry_run", "try", ":", "# TODO: Scrub metafile if requested", "...
Load metafile into client.
[ "Load", "metafile", "into", "client", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/watch.py#L140-L199
train
pyroscope/pyrocore
src/pyrocore/torrent/watch.py
TreeWatchHandler.handle_path
def handle_path(self, event): """ Handle a path-related event. """ self.job.LOG.debug("Notification %r" % event) if event.dir: return if any(event.pathname.endswith(i) for i in self.METAFILE_EXT): MetafileHandler(self.job, event.pathname).handle() ...
python
def handle_path(self, event): """ Handle a path-related event. """ self.job.LOG.debug("Notification %r" % event) if event.dir: return if any(event.pathname.endswith(i) for i in self.METAFILE_EXT): MetafileHandler(self.job, event.pathname).handle() ...
[ "def", "handle_path", "(", "self", ",", "event", ")", ":", "self", ".", "job", ".", "LOG", ".", "debug", "(", "\"Notification %r\"", "%", "event", ")", "if", "event", ".", "dir", ":", "return", "if", "any", "(", "event", ".", "pathname", ".", "endswi...
Handle a path-related event.
[ "Handle", "a", "path", "-", "related", "event", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/watch.py#L243-L253
train
pyroscope/pyrocore
src/pyrocore/torrent/watch.py
TreeWatch.setup
def setup(self): """ Set up inotify manager. See https://github.com/seb-m/pyinotify/. """ if not pyinotify.WatchManager: raise error.UserError("You need to install 'pyinotify' to use %s (%s)!" % ( self.__class__.__name__, pyinotify._import_error)) # pylin...
python
def setup(self): """ Set up inotify manager. See https://github.com/seb-m/pyinotify/. """ if not pyinotify.WatchManager: raise error.UserError("You need to install 'pyinotify' to use %s (%s)!" % ( self.__class__.__name__, pyinotify._import_error)) # pylin...
[ "def", "setup", "(", "self", ")", ":", "if", "not", "pyinotify", ".", "WatchManager", ":", "raise", "error", ".", "UserError", "(", "\"You need to install 'pyinotify' to use %s (%s)!\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "pyinotify", ".",...
Set up inotify manager. See https://github.com/seb-m/pyinotify/.
[ "Set", "up", "inotify", "manager", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/watch.py#L332-L352
train
pyroscope/pyrocore
src/pyrocore/util/traits.py
get_filetypes
def get_filetypes(filelist, path=None, size=os.path.getsize): """ Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype) """ path = ...
python
def get_filetypes(filelist, path=None, size=os.path.getsize): """ Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype) """ path = ...
[ "def", "get_filetypes", "(", "filelist", ",", "path", "=", "None", ",", "size", "=", "os", ".", "path", ".", "getsize", ")", ":", "path", "=", "path", "or", "(", "lambda", "_", ":", "_", ")", "# Get total size for each file extension", "histo", "=", "def...
Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype)
[ "Get", "a", "sorted", "list", "of", "file", "types", "and", "their", "weight", "in", "percent", "from", "an", "iterable", "of", "file", "names", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/traits.py#L127-L154
train
pyroscope/pyrocore
src/pyrocore/util/traits.py
name_trait
def name_trait(name, add_info=False): """ Determine content type from name. """ kind, info = None, {} # Anything to check against? if name and not name.startswith("VTS_"): lower_name = name.lower() trait_patterns = (("tv", TV_PATTERNS, "show"), ("movie", MOVIE_PATTERNS, "title")) ...
python
def name_trait(name, add_info=False): """ Determine content type from name. """ kind, info = None, {} # Anything to check against? if name and not name.startswith("VTS_"): lower_name = name.lower() trait_patterns = (("tv", TV_PATTERNS, "show"), ("movie", MOVIE_PATTERNS, "title")) ...
[ "def", "name_trait", "(", "name", ",", "add_info", "=", "False", ")", ":", "kind", ",", "info", "=", "None", ",", "{", "}", "# Anything to check against?", "if", "name", "and", "not", "name", ".", "startswith", "(", "\"VTS_\"", ")", ":", "lower_name", "=...
Determine content type from name.
[ "Determine", "content", "type", "from", "name", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/traits.py#L157-L201
train
pyroscope/pyrocore
src/pyrocore/util/traits.py
detect_traits
def detect_traits(name=None, alias=None, filetype=None): """ Build traits list from passed attributes. The result is a list of hierarchical classifiers, the top-level consisting of "audio", "movie", "tv", "video", "document", etc. It can be used as a part of completion paths to build direct...
python
def detect_traits(name=None, alias=None, filetype=None): """ Build traits list from passed attributes. The result is a list of hierarchical classifiers, the top-level consisting of "audio", "movie", "tv", "video", "document", etc. It can be used as a part of completion paths to build direct...
[ "def", "detect_traits", "(", "name", "=", "None", ",", "alias", "=", "None", ",", "filetype", "=", "None", ")", ":", "result", "=", "[", "]", "if", "filetype", ":", "filetype", "=", "filetype", ".", "lstrip", "(", "'.'", ")", "# Check for \"themed\" trac...
Build traits list from passed attributes. The result is a list of hierarchical classifiers, the top-level consisting of "audio", "movie", "tv", "video", "document", etc. It can be used as a part of completion paths to build directory structures.
[ "Build", "traits", "list", "from", "passed", "attributes", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/traits.py#L204-L241
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
console_progress
def console_progress(): """ Return a progress indicator for consoles if stdout is a tty. """ def progress(totalhashed, totalsize): "Helper" msg = " " * 30 if totalhashed < totalsize: msg = "%5.1f%% complete" % (totalhashed * 100.0 / totalsize) sys.stdout.w...
python
def console_progress(): """ Return a progress indicator for consoles if stdout is a tty. """ def progress(totalhashed, totalsize): "Helper" msg = " " * 30 if totalhashed < totalsize: msg = "%5.1f%% complete" % (totalhashed * 100.0 / totalsize) sys.stdout.w...
[ "def", "console_progress", "(", ")", ":", "def", "progress", "(", "totalhashed", ",", "totalsize", ")", ":", "\"Helper\"", "msg", "=", "\" \"", "*", "30", "if", "totalhashed", "<", "totalsize", ":", "msg", "=", "\"%5.1f%% complete\"", "%", "(", "totalhashed"...
Return a progress indicator for consoles if stdout is a tty.
[ "Return", "a", "progress", "indicator", "for", "consoles", "if", "stdout", "is", "a", "tty", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L74-L89
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
check_info
def check_info(info): """ Validate info dict. Raise ValueError if validation fails. """ if not isinstance(info, dict): raise ValueError("bad metainfo - not a dictionary") pieces = info.get("pieces") if not isinstance(pieces, basestring) or len(pieces) % 20 != 0: raise Value...
python
def check_info(info): """ Validate info dict. Raise ValueError if validation fails. """ if not isinstance(info, dict): raise ValueError("bad metainfo - not a dictionary") pieces = info.get("pieces") if not isinstance(pieces, basestring) or len(pieces) % 20 != 0: raise Value...
[ "def", "check_info", "(", "info", ")", ":", "if", "not", "isinstance", "(", "info", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"bad metainfo - not a dictionary\"", ")", "pieces", "=", "info", ".", "get", "(", "\"pieces\"", ")", "if", "not", "isin...
Validate info dict. Raise ValueError if validation fails.
[ "Validate", "info", "dict", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L112-L171
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
check_meta
def check_meta(meta): """ Validate meta dict. Raise ValueError if validation fails. """ if not isinstance(meta, dict): raise ValueError("bad metadata - not a dictionary") if not isinstance(meta.get("announce"), basestring): raise ValueError("bad announce URL - not a string") ...
python
def check_meta(meta): """ Validate meta dict. Raise ValueError if validation fails. """ if not isinstance(meta, dict): raise ValueError("bad metadata - not a dictionary") if not isinstance(meta.get("announce"), basestring): raise ValueError("bad announce URL - not a string") ...
[ "def", "check_meta", "(", "meta", ")", ":", "if", "not", "isinstance", "(", "meta", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"bad metadata - not a dictionary\"", ")", "if", "not", "isinstance", "(", "meta", ".", "get", "(", "\"announce\"", ")", ...
Validate meta dict. Raise ValueError if validation fails.
[ "Validate", "meta", "dict", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L174-L185
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
clean_meta
def clean_meta(meta, including_info=False, logger=None): """ Clean meta dict. Optionally log changes using the given logger. @param logger: If given, a callable accepting a string message. @return: Set of keys removed from C{meta}. """ modified = set() for key in meta.keys(): i...
python
def clean_meta(meta, including_info=False, logger=None): """ Clean meta dict. Optionally log changes using the given logger. @param logger: If given, a callable accepting a string message. @return: Set of keys removed from C{meta}. """ modified = set() for key in meta.keys(): i...
[ "def", "clean_meta", "(", "meta", ",", "including_info", "=", "False", ",", "logger", "=", "None", ")", ":", "modified", "=", "set", "(", ")", "for", "key", "in", "meta", ".", "keys", "(", ")", ":", "if", "[", "key", "]", "not", "in", "METAFILE_STD...
Clean meta dict. Optionally log changes using the given logger. @param logger: If given, a callable accepting a string message. @return: Set of keys removed from C{meta}.
[ "Clean", "meta", "dict", ".", "Optionally", "log", "changes", "using", "the", "given", "logger", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L188-L222
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
sanitize
def sanitize(meta, diagnostics=False): """ Try to fix common problems, especially transcode non-standard string encodings. """ bad_encodings, bad_fields = set(), set() def sane_encoding(field, text): "Transcoding helper." for encoding in ('utf-8', meta.get('encoding', None), 'cp1252'): ...
python
def sanitize(meta, diagnostics=False): """ Try to fix common problems, especially transcode non-standard string encodings. """ bad_encodings, bad_fields = set(), set() def sane_encoding(field, text): "Transcoding helper." for encoding in ('utf-8', meta.get('encoding', None), 'cp1252'): ...
[ "def", "sanitize", "(", "meta", ",", "diagnostics", "=", "False", ")", ":", "bad_encodings", ",", "bad_fields", "=", "set", "(", ")", ",", "set", "(", ")", "def", "sane_encoding", "(", "field", ",", "text", ")", ":", "\"Transcoding helper.\"", "for", "en...
Try to fix common problems, especially transcode non-standard string encodings.
[ "Try", "to", "fix", "common", "problems", "especially", "transcode", "non", "-", "standard", "string", "encodings", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L225-L258
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
add_fast_resume
def add_fast_resume(meta, datapath): """ Add fast resume data to a metafile dict. """ # Get list of files files = meta["info"].get("files", None) single = files is None if single: if os.path.isdir(datapath): datapath = os.path.join(datapath, meta["info"]["name"]) file...
python
def add_fast_resume(meta, datapath): """ Add fast resume data to a metafile dict. """ # Get list of files files = meta["info"].get("files", None) single = files is None if single: if os.path.isdir(datapath): datapath = os.path.join(datapath, meta["info"]["name"]) file...
[ "def", "add_fast_resume", "(", "meta", ",", "datapath", ")", ":", "# Get list of files", "files", "=", "meta", "[", "\"info\"", "]", ".", "get", "(", "\"files\"", ",", "None", ")", "single", "=", "files", "is", "None", "if", "single", ":", "if", "os", ...
Add fast resume data to a metafile dict.
[ "Add", "fast", "resume", "data", "to", "a", "metafile", "dict", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L301-L343
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
data_size
def data_size(metadata): """ Calculate the size of a torrent based on parsed metadata. """ info = metadata['info'] if 'length' in info: # Single file total_size = info['length'] else: # Directory structure total_size = sum([f['length'] for f in info['files']]) r...
python
def data_size(metadata): """ Calculate the size of a torrent based on parsed metadata. """ info = metadata['info'] if 'length' in info: # Single file total_size = info['length'] else: # Directory structure total_size = sum([f['length'] for f in info['files']]) r...
[ "def", "data_size", "(", "metadata", ")", ":", "info", "=", "metadata", "[", "'info'", "]", "if", "'length'", "in", "info", ":", "# Single file", "total_size", "=", "info", "[", "'length'", "]", "else", ":", "# Directory structure", "total_size", "=", "sum",...
Calculate the size of a torrent based on parsed metadata.
[ "Calculate", "the", "size", "of", "a", "torrent", "based", "on", "parsed", "metadata", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L352-L364
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
checked_open
def checked_open(filename, log=None, quiet=False): """ Open and validate the given metafile. Optionally provide diagnostics on the passed logger, for invalid metafiles, which then just cause a warning but no exception. "quiet" can supress that warning. """ with open(filename, "rb") a...
python
def checked_open(filename, log=None, quiet=False): """ Open and validate the given metafile. Optionally provide diagnostics on the passed logger, for invalid metafiles, which then just cause a warning but no exception. "quiet" can supress that warning. """ with open(filename, "rb") a...
[ "def", "checked_open", "(", "filename", ",", "log", "=", "None", ",", "quiet", "=", "False", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "handle", ":", "raw_data", "=", "handle", ".", "read", "(", ")", "data", "=", "bencode",...
Open and validate the given metafile. Optionally provide diagnostics on the passed logger, for invalid metafiles, which then just cause a warning but no exception. "quiet" can supress that warning.
[ "Open", "and", "validate", "the", "given", "metafile", ".", "Optionally", "provide", "diagnostics", "on", "the", "passed", "logger", "for", "invalid", "metafiles", "which", "then", "just", "cause", "a", "warning", "but", "no", "exception", ".", "quiet", "can",...
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L367-L389
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
MaskingPrettyPrinter.format
def format(self, obj, context, maxlevels, level): # pylint: disable=arguments-differ """ Mask obj if it looks like an URL, then pass it to the super class. """ if isinstance(obj, basestring) and "://" in fmt.to_unicode(obj): obj = mask_keys(obj) return pprint.PrettyPrinter.f...
python
def format(self, obj, context, maxlevels, level): # pylint: disable=arguments-differ """ Mask obj if it looks like an URL, then pass it to the super class. """ if isinstance(obj, basestring) and "://" in fmt.to_unicode(obj): obj = mask_keys(obj) return pprint.PrettyPrinter.f...
[ "def", "format", "(", "self", ",", "obj", ",", "context", ",", "maxlevels", ",", "level", ")", ":", "# pylint: disable=arguments-differ", "if", "isinstance", "(", "obj", ",", "basestring", ")", "and", "\"://\"", "in", "fmt", ".", "to_unicode", "(", "obj", ...
Mask obj if it looks like an URL, then pass it to the super class.
[ "Mask", "obj", "if", "it", "looks", "like", "an", "URL", "then", "pass", "it", "to", "the", "super", "class", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L104-L109
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
Metafile._get_datapath
def _get_datapath(self): """ Get a valid datapath, else raise an exception. """ if self._datapath is None: raise OSError(errno.ENOENT, "You didn't provide any datapath for %r" % self.filename) return self._datapath
python
def _get_datapath(self): """ Get a valid datapath, else raise an exception. """ if self._datapath is None: raise OSError(errno.ENOENT, "You didn't provide any datapath for %r" % self.filename) return self._datapath
[ "def", "_get_datapath", "(", "self", ")", ":", "if", "self", ".", "_datapath", "is", "None", ":", "raise", "OSError", "(", "errno", ".", "ENOENT", ",", "\"You didn't provide any datapath for %r\"", "%", "self", ".", "filename", ")", "return", "self", ".", "_...
Get a valid datapath, else raise an exception.
[ "Get", "a", "valid", "datapath", "else", "raise", "an", "exception", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L413-L419
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
Metafile._set_datapath
def _set_datapath(self, datapath): """ Set a datapath. """ if datapath: self._datapath = datapath.rstrip(os.sep) self._fifo = int(stat.S_ISFIFO(os.stat(self.datapath).st_mode)) else: self._datapath = None self._fifo = False
python
def _set_datapath(self, datapath): """ Set a datapath. """ if datapath: self._datapath = datapath.rstrip(os.sep) self._fifo = int(stat.S_ISFIFO(os.stat(self.datapath).st_mode)) else: self._datapath = None self._fifo = False
[ "def", "_set_datapath", "(", "self", ",", "datapath", ")", ":", "if", "datapath", ":", "self", ".", "_datapath", "=", "datapath", ".", "rstrip", "(", "os", ".", "sep", ")", "self", ".", "_fifo", "=", "int", "(", "stat", ".", "S_ISFIFO", "(", "os", ...
Set a datapath.
[ "Set", "a", "datapath", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L421-L429
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
Metafile.walk
def walk(self): """ Generate paths in "self.datapath". """ # FIFO? if self._fifo: if self._fifo > 1: raise RuntimeError("INTERNAL ERROR: FIFO read twice!") self._fifo += 1 # Read paths relative to directory containing the FIFO ...
python
def walk(self): """ Generate paths in "self.datapath". """ # FIFO? if self._fifo: if self._fifo > 1: raise RuntimeError("INTERNAL ERROR: FIFO read twice!") self._fifo += 1 # Read paths relative to directory containing the FIFO ...
[ "def", "walk", "(", "self", ")", ":", "# FIFO?", "if", "self", ".", "_fifo", ":", "if", "self", ".", "_fifo", ">", "1", ":", "raise", "RuntimeError", "(", "\"INTERNAL ERROR: FIFO read twice!\"", ")", "self", ".", "_fifo", "+=", "1", "# Read paths relative to...
Generate paths in "self.datapath".
[ "Generate", "paths", "in", "self", ".", "datapath", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L434-L472
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
Metafile._calc_size
def _calc_size(self): """ Get total size of "self.datapath". """ return sum(os.path.getsize(filename) for filename in self.walk() )
python
def _calc_size(self): """ Get total size of "self.datapath". """ return sum(os.path.getsize(filename) for filename in self.walk() )
[ "def", "_calc_size", "(", "self", ")", ":", "return", "sum", "(", "os", ".", "path", ".", "getsize", "(", "filename", ")", "for", "filename", "in", "self", ".", "walk", "(", ")", ")" ]
Get total size of "self.datapath".
[ "Get", "total", "size", "of", "self", ".", "datapath", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L475-L480
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
Metafile._make_info
def _make_info(self, piece_size, progress, walker, piece_callback=None): """ Create info dict. """ # These collect the file descriptions and piece hashes file_list = [] pieces = [] # Initialize progress state hashing_secs = time.time() totalsize = -1 if s...
python
def _make_info(self, piece_size, progress, walker, piece_callback=None): """ Create info dict. """ # These collect the file descriptions and piece hashes file_list = [] pieces = [] # Initialize progress state hashing_secs = time.time() totalsize = -1 if s...
[ "def", "_make_info", "(", "self", ",", "piece_size", ",", "progress", ",", "walker", ",", "piece_callback", "=", "None", ")", ":", "# These collect the file descriptions and piece hashes", "file_list", "=", "[", "]", "pieces", "=", "[", "]", "# Initialize progress s...
Create info dict.
[ "Create", "info", "dict", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L483-L564
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
Metafile._make_meta
def _make_meta(self, tracker_url, root_name, private, progress): """ Create torrent dict. """ # Calculate piece size if self._fifo: # TODO we need to add a (command line) param, probably for total data size # for now, always 1MB piece_size_exp = 20 ...
python
def _make_meta(self, tracker_url, root_name, private, progress): """ Create torrent dict. """ # Calculate piece size if self._fifo: # TODO we need to add a (command line) param, probably for total data size # for now, always 1MB piece_size_exp = 20 ...
[ "def", "_make_meta", "(", "self", ",", "tracker_url", ",", "root_name", ",", "private", ",", "progress", ")", ":", "# Calculate piece size", "if", "self", ".", "_fifo", ":", "# TODO we need to add a (command line) param, probably for total data size", "# for now, always 1MB...
Create torrent dict.
[ "Create", "torrent", "dict", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L567-L608
train
pyroscope/pyrocore
src/pyrocore/util/metafile.py
Metafile.check
def check(self, metainfo, datapath, progress=None): """ Check piece hashes of a metafile against the given datapath. """ if datapath: self.datapath = datapath def check_piece(filename, piece): "Callback for new piece" if piece != metainfo["info"]["pie...
python
def check(self, metainfo, datapath, progress=None): """ Check piece hashes of a metafile against the given datapath. """ if datapath: self.datapath = datapath def check_piece(filename, piece): "Callback for new piece" if piece != metainfo["info"]["pie...
[ "def", "check", "(", "self", ",", "metainfo", ",", "datapath", ",", "progress", "=", "None", ")", ":", "if", "datapath", ":", "self", ".", "datapath", "=", "datapath", "def", "check_piece", "(", "filename", ",", "piece", ")", ":", "\"Callback for new piece...
Check piece hashes of a metafile against the given datapath.
[ "Check", "piece", "hashes", "of", "a", "metafile", "against", "the", "given", "datapath", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/metafile.py#L674-L692
train
pyroscope/pyrocore
src/pyrocore/torrent/queue.py
QueueManager._start
def _start(self, items): """ Start some items if conditions are met. """ # TODO: Filter by a custom date field, for scheduled downloads starting at a certain time, or after a given delay # TODO: Don't start anything more if download BW is used >= config threshold in % # Check i...
python
def _start(self, items): """ Start some items if conditions are met. """ # TODO: Filter by a custom date field, for scheduled downloads starting at a certain time, or after a given delay # TODO: Don't start anything more if download BW is used >= config threshold in % # Check i...
[ "def", "_start", "(", "self", ",", "items", ")", ":", "# TODO: Filter by a custom date field, for scheduled downloads starting at a certain time, or after a given delay", "# TODO: Don't start anything more if download BW is used >= config threshold in %", "# Check if anything more is ready to st...
Start some items if conditions are met.
[ "Start", "some", "items", "if", "conditions", "are", "met", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/queue.py#L63-L132
train
pyroscope/pyrocore
src/pyrocore/torrent/queue.py
QueueManager.run
def run(self): """ Queue manager job callback. """ try: self.proxy = config_ini.engine.open() # Get items from 'pyrotorque' view items = list(config_ini.engine.items(self.VIEWNAME, cache=False)) if self.sort_key: items.sort(key=se...
python
def run(self): """ Queue manager job callback. """ try: self.proxy = config_ini.engine.open() # Get items from 'pyrotorque' view items = list(config_ini.engine.items(self.VIEWNAME, cache=False)) if self.sort_key: items.sort(key=se...
[ "def", "run", "(", "self", ")", ":", "try", ":", "self", ".", "proxy", "=", "config_ini", ".", "engine", ".", "open", "(", ")", "# Get items from 'pyrotorque' view", "items", "=", "list", "(", "config_ini", ".", "engine", ".", "items", "(", "self", ".", ...
Queue manager job callback.
[ "Queue", "manager", "job", "callback", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/queue.py#L135-L153
train
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
print_help_fields
def print_help_fields(): """ Print help about fields and field formatters. """ # Mock entries, so they fulfill the expectations towards a field definition def custom_manifold(): "named rTorrent custom attribute, e.g. 'custom_completion_target'" return ("custom_KEY", custom_manifold) ...
python
def print_help_fields(): """ Print help about fields and field formatters. """ # Mock entries, so they fulfill the expectations towards a field definition def custom_manifold(): "named rTorrent custom attribute, e.g. 'custom_completion_target'" return ("custom_KEY", custom_manifold) ...
[ "def", "print_help_fields", "(", ")", ":", "# Mock entries, so they fulfill the expectations towards a field definition", "def", "custom_manifold", "(", ")", ":", "\"named rTorrent custom attribute, e.g. 'custom_completion_target'\"", "return", "(", "\"custom_KEY\"", ",", "custom_man...
Print help about fields and field formatters.
[ "Print", "help", "about", "fields", "and", "field", "formatters", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L35-L61
train
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
FieldStatistics.add
def add(self, field, val): "Add a sample" if engine.FieldDefinition.FIELDS[field]._matcher is matching.TimeFilter: val = self._basetime - val try: self.total[field] += val self.min[field] = min(self.min[field], val) if field in self.min else val s...
python
def add(self, field, val): "Add a sample" if engine.FieldDefinition.FIELDS[field]._matcher is matching.TimeFilter: val = self._basetime - val try: self.total[field] += val self.min[field] = min(self.min[field], val) if field in self.min else val s...
[ "def", "add", "(", "self", ",", "field", ",", "val", ")", ":", "if", "engine", ".", "FieldDefinition", ".", "FIELDS", "[", "field", "]", ".", "_matcher", "is", "matching", ".", "TimeFilter", ":", "val", "=", "self", ".", "_basetime", "-", "val", "try...
Add a sample
[ "Add", "a", "sample" ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L83-L93
train
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
RtorrentControl.help_completion_fields
def help_completion_fields(self): """ Return valid field names. """ for name, field in sorted(engine.FieldDefinition.FIELDS.items()): if issubclass(field._matcher, matching.BoolFilter): yield "%s=no" % (name,) yield "%s=yes" % (name,) c...
python
def help_completion_fields(self): """ Return valid field names. """ for name, field in sorted(engine.FieldDefinition.FIELDS.items()): if issubclass(field._matcher, matching.BoolFilter): yield "%s=no" % (name,) yield "%s=yes" % (name,) c...
[ "def", "help_completion_fields", "(", "self", ")", ":", "for", "name", ",", "field", "in", "sorted", "(", "engine", ".", "FieldDefinition", ".", "FIELDS", ".", "items", "(", ")", ")", ":", "if", "issubclass", "(", "field", ".", "_matcher", ",", "matching...
Return valid field names.
[ "Return", "valid", "field", "names", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L309-L333
train
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
RtorrentControl.format_item
def format_item(self, item, defaults=None, stencil=None): """ Format an item. """ from pyrobase.osutil import shell_escape try: item_text = fmt.to_console(formatting.format_item(self.options.output_format, item, defaults)) except (NameError, ValueError, TypeError), e...
python
def format_item(self, item, defaults=None, stencil=None): """ Format an item. """ from pyrobase.osutil import shell_escape try: item_text = fmt.to_console(formatting.format_item(self.options.output_format, item, defaults)) except (NameError, ValueError, TypeError), e...
[ "def", "format_item", "(", "self", ",", "item", ",", "defaults", "=", "None", ",", "stencil", "=", "None", ")", ":", "from", "pyrobase", ".", "osutil", "import", "shell_escape", "try", ":", "item_text", "=", "fmt", ".", "to_console", "(", "formatting", "...
Format an item.
[ "Format", "an", "item", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L337-L355
train
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
RtorrentControl.emit
def emit(self, item, defaults=None, stencil=None, to_log=False, item_formatter=None): """ Print an item to stdout, or the log on INFO level. """ item_text = self.format_item(item, defaults, stencil) # Post-process line? if item_formatter: item_text = item_formatter(i...
python
def emit(self, item, defaults=None, stencil=None, to_log=False, item_formatter=None): """ Print an item to stdout, or the log on INFO level. """ item_text = self.format_item(item, defaults, stencil) # Post-process line? if item_formatter: item_text = item_formatter(i...
[ "def", "emit", "(", "self", ",", "item", ",", "defaults", "=", "None", ",", "stencil", "=", "None", ",", "to_log", "=", "False", ",", "item_formatter", "=", "None", ")", ":", "item_text", "=", "self", ".", "format_item", "(", "item", ",", "defaults", ...
Print an item to stdout, or the log on INFO level.
[ "Print", "an", "item", "to", "stdout", "or", "the", "log", "on", "INFO", "level", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L358-L383
train
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
RtorrentControl.validate_output_format
def validate_output_format(self, default_format): """ Prepare output format for later use. """ output_format = self.options.output_format # Use default format if none is given if output_format is None: output_format = default_format # Check if it's a custom ...
python
def validate_output_format(self, default_format): """ Prepare output format for later use. """ output_format = self.options.output_format # Use default format if none is given if output_format is None: output_format = default_format # Check if it's a custom ...
[ "def", "validate_output_format", "(", "self", ",", "default_format", ")", ":", "output_format", "=", "self", ".", "options", ".", "output_format", "# Use default format if none is given", "if", "output_format", "is", "None", ":", "output_format", "=", "default_format", ...
Prepare output format for later use.
[ "Prepare", "output", "format", "for", "later", "use", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L387-L417
train
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
RtorrentControl.get_output_fields
def get_output_fields(self): """ Get field names from output template. """ # Re-engineer list from output format # XXX TODO: Would be better to use a FieldRecorder class to catch the full field names emit_fields = list(i.lower() for i in re.sub(r"[^_A-Z]+", ' ', self.format_item(...
python
def get_output_fields(self): """ Get field names from output template. """ # Re-engineer list from output format # XXX TODO: Would be better to use a FieldRecorder class to catch the full field names emit_fields = list(i.lower() for i in re.sub(r"[^_A-Z]+", ' ', self.format_item(...
[ "def", "get_output_fields", "(", "self", ")", ":", "# Re-engineer list from output format", "# XXX TODO: Would be better to use a FieldRecorder class to catch the full field names", "emit_fields", "=", "list", "(", "i", ".", "lower", "(", ")", "for", "i", "in", "re", ".", ...
Get field names from output template.
[ "Get", "field", "names", "from", "output", "template", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L421-L436
train
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
RtorrentControl.validate_sort_fields
def validate_sort_fields(self): """ Take care of sorting. """ sort_fields = ','.join(self.options.sort_fields) if sort_fields == '*': sort_fields = self.get_output_fields() return formatting.validate_sort_fields(sort_fields or config.sort_fields)
python
def validate_sort_fields(self): """ Take care of sorting. """ sort_fields = ','.join(self.options.sort_fields) if sort_fields == '*': sort_fields = self.get_output_fields() return formatting.validate_sort_fields(sort_fields or config.sort_fields)
[ "def", "validate_sort_fields", "(", "self", ")", ":", "sort_fields", "=", "','", ".", "join", "(", "self", ".", "options", ".", "sort_fields", ")", "if", "sort_fields", "==", "'*'", ":", "sort_fields", "=", "self", ".", "get_output_fields", "(", ")", "retu...
Take care of sorting.
[ "Take", "care", "of", "sorting", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L439-L446
train
pyroscope/pyrocore
src/pyrocore/scripts/rtcontrol.py
RtorrentControl.show_in_view
def show_in_view(self, sourceview, matches, targetname=None): """ Show search result in ncurses view. """ append = self.options.append_view or self.options.alter_view == 'append' remove = self.options.alter_view == 'remove' action_name = ', appending to' if append else ', removin...
python
def show_in_view(self, sourceview, matches, targetname=None): """ Show search result in ncurses view. """ append = self.options.append_view or self.options.alter_view == 'append' remove = self.options.alter_view == 'remove' action_name = ', appending to' if append else ', removin...
[ "def", "show_in_view", "(", "self", ",", "sourceview", ",", "matches", ",", "targetname", "=", "None", ")", ":", "append", "=", "self", ".", "options", ".", "append_view", "or", "self", ".", "options", ".", "alter_view", "==", "'append'", "remove", "=", ...
Show search result in ncurses view.
[ "Show", "search", "result", "in", "ncurses", "view", "." ]
89ad01346a570943d20311a0b488440975876612
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L449-L461
train