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.discard(tag[1:]) elif tag.startswith('+'): tagset.add(tag[1:]) else: tagset.add(tag) # Write back new tagset, if changed tagset.discard('') if tagset != previous: tagset = ' '.join(sorted(tagset)) self._make_it_so("setting tags %r on" % (tagset,), ["custom.set"], "tags", tagset) self._fields["custom_tags"] = tagset
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.discard(tag[1:]) elif tag.startswith('+'): tagset.add(tag[1:]) else: tagset.add(tag) # Write back new tagset, if changed tagset.discard('') if tagset != previous: tagset = ' '.join(sorted(tagset)) self._make_it_so("setting tags %r on" % (tagset,), ["custom.set"], "tags", tagset) self._fields["custom_tags"] = tagset
[ "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", ".", "replace", "(", "','", ",", "' '", ")", ".", "split", "(", ")", ":", "if", "tag", ".", "startswith", "(", "'-'", ")", ":", "tagset", ".", "discard", "(", "tag", "[", "1", ":", "]", ")", "elif", "tag", ".", "startswith", "(", "'+'", ")", ":", "tagset", ".", "add", "(", "tag", "[", "1", ":", "]", ")", "else", ":", "tagset", ".", "add", "(", "tag", ")", "# Write back new tagset, if changed", "tagset", ".", "discard", "(", "''", ")", "if", "tagset", "!=", "previous", ":", "tagset", "=", "' '", ".", "join", "(", "sorted", "(", "tagset", ")", ")", "self", ".", "_make_it_so", "(", "\"setting tags %r on\"", "%", "(", "tagset", ",", ")", ",", "[", "\"custom.set\"", "]", ",", "\"tags\"", ",", "tagset", ")", "self", ".", "_fields", "[", "\"custom_tags\"", "]", "=", "tagset" ]
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, name) == -1: if self._engine._rpc.throttle.down.max(xmlrpc.NOHASH, name) == -1: raise error.UserError("Unknown throttle name '{}'".format(name)) self._engine.known_throttle_names.add(name) if (name or "NONE") == self.throttle: self._engine.LOG.debug("Keeping throttle %r on torrent #%s" % (self.throttle, self._fields["hash"])) return active = self.is_active if active: self._engine.LOG.debug("Torrent #%s stopped for throttling" % (self._fields["hash"],)) self.stop() self._make_it_so("setting throttle %r on" % (name,), ["throttle_name.set"], name) if active: self._engine.LOG.debug("Torrent #%s restarted after throttling" % (self._fields["hash"],)) self.start()
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, name) == -1: if self._engine._rpc.throttle.down.max(xmlrpc.NOHASH, name) == -1: raise error.UserError("Unknown throttle name '{}'".format(name)) self._engine.known_throttle_names.add(name) if (name or "NONE") == self.throttle: self._engine.LOG.debug("Keeping throttle %r on torrent #%s" % (self.throttle, self._fields["hash"])) return active = self.is_active if active: self._engine.LOG.debug("Torrent #%s stopped for throttling" % (self._fields["hash"],)) self.stop() self._make_it_so("setting throttle %r on" % (name,), ["throttle_name.set"], name) if active: self._engine.LOG.debug("Torrent #%s restarted after throttling" % (self._fields["hash"],)) self.start()
[ "def", "set_throttle", "(", "self", ",", "name", ")", ":", "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", ",", "name", ")", "==", "-", "1", ":", "if", "self", ".", "_engine", ".", "_rpc", ".", "throttle", ".", "down", ".", "max", "(", "xmlrpc", ".", "NOHASH", ",", "name", ")", "==", "-", "1", ":", "raise", "error", ".", "UserError", "(", "\"Unknown throttle name '{}'\"", ".", "format", "(", "name", ")", ")", "self", ".", "_engine", ".", "known_throttle_names", ".", "add", "(", "name", ")", "if", "(", "name", "or", "\"NONE\"", ")", "==", "self", ".", "throttle", ":", "self", ".", "_engine", ".", "LOG", ".", "debug", "(", "\"Keeping throttle %r on torrent #%s\"", "%", "(", "self", ".", "throttle", ",", "self", ".", "_fields", "[", "\"hash\"", "]", ")", ")", "return", "active", "=", "self", ".", "is_active", "if", "active", ":", "self", ".", "_engine", ".", "LOG", ".", "debug", "(", "\"Torrent #%s stopped for throttling\"", "%", "(", "self", ".", "_fields", "[", "\"hash\"", "]", ",", ")", ")", "self", ".", "stop", "(", ")", "self", ".", "_make_it_so", "(", "\"setting throttle %r on\"", "%", "(", "name", ",", ")", ",", "[", "\"throttle_name.set\"", "]", ",", "name", ")", "if", "active", ":", "self", ".", "_engine", ".", "LOG", ".", "debug", "(", "\"Torrent #%s restarted after throttling\"", "%", "(", "self", ".", "_fields", "[", "\"hash\"", "]", ",", ")", ")", "self", ".", "start", "(", ")" ]
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=["get_completed_chunks", "get_size_chunks"])
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=["get_completed_chunks", "get_size_chunks"])
[ "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", "=", "partial_file", ",", "attrs", "=", "[", "\"get_completed_chunks\"", ",", "\"get_size_chunks\"", "]", ")" ]
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 rcfile: rcfile = getattr(config, "rtorrent_rc", None) if not rcfile: raise error.UserError("No 'rtorrent_rc' path defined in configuration!") if not os.path.isfile(rcfile): raise error.UserError("Config file %r doesn't exist!" % (rcfile,)) # Parse the file self.LOG.debug("Loading rtorrent config from %r" % (rcfile,)) rc_vals = Bunch(scgi_local='', scgi_port = '') with open(rcfile) as handle: continued = False for line in handle.readlines(): # Skip comments, continuations, and empty lines line = line.strip() continued, was_continued = line.endswith('\\'), continued if not line or was_continued or line.startswith("#"): continue # Be lenient about errors, after all it's not our own config file try: key, val = line.split("=", 1) except ValueError: self.LOG.warning("Ignored invalid line %r in %r!" % (line, rcfile)) continue key, val = key.strip(), val.strip() key = self.RTORRENT_RC_ALIASES.get(key, key).replace('.', '_') # Copy values we're interested in if key in self.RTORRENT_RC_KEYS: self.LOG.debug("rtorrent.rc: %s = %s" % (key, val)) rc_vals[key] = val # Validate fields if rc_vals.scgi_local: rc_vals.scgi_local = os.path.expanduser(rc_vals.scgi_local) if rc_vals.scgi_local.startswith('/'): rc_vals.scgi_local = "scgi://" + rc_vals.scgi_local if rc_vals.scgi_port and not rc_vals.scgi_port.startswith("scgi://"): rc_vals.scgi_port = "scgi://" + rc_vals.scgi_port # Prefer UNIX domain sockets over TCP sockets namespace.scgi_url = rc_vals.scgi_local or rc_vals.scgi_port
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 rcfile: rcfile = getattr(config, "rtorrent_rc", None) if not rcfile: raise error.UserError("No 'rtorrent_rc' path defined in configuration!") if not os.path.isfile(rcfile): raise error.UserError("Config file %r doesn't exist!" % (rcfile,)) # Parse the file self.LOG.debug("Loading rtorrent config from %r" % (rcfile,)) rc_vals = Bunch(scgi_local='', scgi_port = '') with open(rcfile) as handle: continued = False for line in handle.readlines(): # Skip comments, continuations, and empty lines line = line.strip() continued, was_continued = line.endswith('\\'), continued if not line or was_continued or line.startswith("#"): continue # Be lenient about errors, after all it's not our own config file try: key, val = line.split("=", 1) except ValueError: self.LOG.warning("Ignored invalid line %r in %r!" % (line, rcfile)) continue key, val = key.strip(), val.strip() key = self.RTORRENT_RC_ALIASES.get(key, key).replace('.', '_') # Copy values we're interested in if key in self.RTORRENT_RC_KEYS: self.LOG.debug("rtorrent.rc: %s = %s" % (key, val)) rc_vals[key] = val # Validate fields if rc_vals.scgi_local: rc_vals.scgi_local = os.path.expanduser(rc_vals.scgi_local) if rc_vals.scgi_local.startswith('/'): rc_vals.scgi_local = "scgi://" + rc_vals.scgi_local if rc_vals.scgi_port and not rc_vals.scgi_port.startswith("scgi://"): rc_vals.scgi_port = "scgi://" + rc_vals.scgi_port # Prefer UNIX domain sockets over TCP sockets namespace.scgi_url = rc_vals.scgi_local or rc_vals.scgi_port
[ "def", "load_config", "(", "self", ",", "namespace", "=", "None", ",", "rcfile", "=", "None", ")", ":", "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", "rcfile", ":", "rcfile", "=", "getattr", "(", "config", ",", "\"rtorrent_rc\"", ",", "None", ")", "if", "not", "rcfile", ":", "raise", "error", ".", "UserError", "(", "\"No 'rtorrent_rc' path defined in configuration!\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "rcfile", ")", ":", "raise", "error", ".", "UserError", "(", "\"Config file %r doesn't exist!\"", "%", "(", "rcfile", ",", ")", ")", "# Parse the file", "self", ".", "LOG", ".", "debug", "(", "\"Loading rtorrent config from %r\"", "%", "(", "rcfile", ",", ")", ")", "rc_vals", "=", "Bunch", "(", "scgi_local", "=", "''", ",", "scgi_port", "=", "''", ")", "with", "open", "(", "rcfile", ")", "as", "handle", ":", "continued", "=", "False", "for", "line", "in", "handle", ".", "readlines", "(", ")", ":", "# Skip comments, continuations, and empty lines", "line", "=", "line", ".", "strip", "(", ")", "continued", ",", "was_continued", "=", "line", ".", "endswith", "(", "'\\\\'", ")", ",", "continued", "if", "not", "line", "or", "was_continued", "or", "line", ".", "startswith", "(", "\"#\"", ")", ":", "continue", "# Be lenient about errors, after all it's not our own config file", "try", ":", "key", ",", "val", "=", "line", ".", "split", "(", "\"=\"", ",", "1", ")", "except", "ValueError", ":", "self", ".", "LOG", ".", "warning", "(", "\"Ignored invalid line %r in %r!\"", "%", "(", "line", ",", "rcfile", ")", ")", "continue", "key", ",", "val", "=", "key", ".", "strip", "(", ")", ",", "val", ".", "strip", "(", ")", "key", "=", "self", ".", "RTORRENT_RC_ALIASES", ".", "get", "(", "key", ",", "key", ")", ".", "replace", "(", "'.'", ",", "'_'", ")", "# Copy values we're interested in", "if", "key", "in", "self", ".", "RTORRENT_RC_KEYS", ":", "self", ".", "LOG", ".", "debug", "(", "\"rtorrent.rc: %s = %s\"", "%", "(", "key", ",", "val", ")", ")", "rc_vals", "[", "key", "]", "=", "val", "# Validate fields", "if", "rc_vals", ".", "scgi_local", ":", "rc_vals", ".", "scgi_local", "=", "os", ".", "path", ".", "expanduser", "(", "rc_vals", ".", "scgi_local", ")", "if", "rc_vals", ".", "scgi_local", ".", "startswith", "(", "'/'", ")", ":", "rc_vals", ".", "scgi_local", "=", "\"scgi://\"", "+", "rc_vals", ".", "scgi_local", "if", "rc_vals", ".", "scgi_port", "and", "not", "rc_vals", ".", "scgi_port", ".", "startswith", "(", "\"scgi://\"", ")", ":", "rc_vals", ".", "scgi_port", "=", "\"scgi://\"", "+", "rc_vals", ".", "scgi_port", "# Prefer UNIX domain sockets over TCP sockets", "namespace", ".", "scgi_url", "=", "rc_vals", ".", "scgi_local", "or", "rc_vals", ".", "scgi_port" ]
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 as exc: raise error.EngineError("Can't get name of current view: %s" % (exc)) return viewname
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 as exc: raise error.EngineError("Can't get name of current view: %s" % (exc)) return viewname
[ "def", "_resolve_viewname", "(", "self", ",", "viewname", ")", ":", "if", "viewname", "==", "\"-\"", ":", "try", ":", "# Only works with rTorrent-PS at this time!", "viewname", "=", "self", ".", "open", "(", ")", ".", "ui", ".", "current_view", "(", ")", "except", "xmlrpc", ".", "ERRORS", "as", "exc", ":", "raise", "error", ".", "EngineError", "(", "\"Can't get name of current view: %s\"", "%", "(", "exc", ")", ")", "return", "viewname" ]
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: raise error.UserError("You need to configure a XMLRPC connection, read" " https://pyrocore.readthedocs.io/en/latest/setup.html") # Connect and get instance ID (also ensures we're connectable) self._rpc = xmlrpc.RTorrentProxy(config.scgi_url) self.versions, self.version_info = self._rpc._set_mappings() self.engine_id = self._rpc.session.name() time_usec = self._rpc.system.time_usec() # Make sure xmlrpc-c works as expected if time_usec < 2**32: self.LOG.warn("Your xmlrpc-c is broken (64 bit integer support missing," " %r returned instead)" % (type(time_usec),)) # Get other manifest values self.engine_software = "rTorrent %s/%s" % self.versions if "+ssh:" in config.scgi_url: self.startup = int(self._rpc.startup_time() or time.time()) else: self._session_dir = self._rpc.session.path() if not self._session_dir: raise error.UserError("You need a session directory, read" " https://pyrocore.readthedocs.io/en/latest/setup.html") if not os.path.exists(self._session_dir): raise error.UserError("Non-existing session directory %r" % self._session_dir) self._download_dir = os.path.expanduser(self._rpc.directory.default()) if not os.path.exists(self._download_dir): raise error.UserError("Non-existing download directory %r" % self._download_dir) self.startup = os.path.getmtime(os.path.join(self._session_dir, "rtorrent.lock")) # Return connection self.LOG.debug(repr(self)) return self._rpc
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: raise error.UserError("You need to configure a XMLRPC connection, read" " https://pyrocore.readthedocs.io/en/latest/setup.html") # Connect and get instance ID (also ensures we're connectable) self._rpc = xmlrpc.RTorrentProxy(config.scgi_url) self.versions, self.version_info = self._rpc._set_mappings() self.engine_id = self._rpc.session.name() time_usec = self._rpc.system.time_usec() # Make sure xmlrpc-c works as expected if time_usec < 2**32: self.LOG.warn("Your xmlrpc-c is broken (64 bit integer support missing," " %r returned instead)" % (type(time_usec),)) # Get other manifest values self.engine_software = "rTorrent %s/%s" % self.versions if "+ssh:" in config.scgi_url: self.startup = int(self._rpc.startup_time() or time.time()) else: self._session_dir = self._rpc.session.path() if not self._session_dir: raise error.UserError("You need a session directory, read" " https://pyrocore.readthedocs.io/en/latest/setup.html") if not os.path.exists(self._session_dir): raise error.UserError("Non-existing session directory %r" % self._session_dir) self._download_dir = os.path.expanduser(self._rpc.directory.default()) if not os.path.exists(self._download_dir): raise error.UserError("Non-existing download directory %r" % self._download_dir) self.startup = os.path.getmtime(os.path.join(self._session_dir, "rtorrent.lock")) # Return connection self.LOG.debug(repr(self)) return self._rpc
[ "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, so...", "if", "not", "config", ".", "scgi_url", ":", "raise", "error", ".", "UserError", "(", "\"You need to configure a XMLRPC connection, read\"", "\" https://pyrocore.readthedocs.io/en/latest/setup.html\"", ")", "# Connect and get instance ID (also ensures we're connectable)", "self", ".", "_rpc", "=", "xmlrpc", ".", "RTorrentProxy", "(", "config", ".", "scgi_url", ")", "self", ".", "versions", ",", "self", ".", "version_info", "=", "self", ".", "_rpc", ".", "_set_mappings", "(", ")", "self", ".", "engine_id", "=", "self", ".", "_rpc", ".", "session", ".", "name", "(", ")", "time_usec", "=", "self", ".", "_rpc", ".", "system", ".", "time_usec", "(", ")", "# Make sure xmlrpc-c works as expected", "if", "time_usec", "<", "2", "**", "32", ":", "self", ".", "LOG", ".", "warn", "(", "\"Your xmlrpc-c is broken (64 bit integer support missing,\"", "\" %r returned instead)\"", "%", "(", "type", "(", "time_usec", ")", ",", ")", ")", "# Get other manifest values", "self", ".", "engine_software", "=", "\"rTorrent %s/%s\"", "%", "self", ".", "versions", "if", "\"+ssh:\"", "in", "config", ".", "scgi_url", ":", "self", ".", "startup", "=", "int", "(", "self", ".", "_rpc", ".", "startup_time", "(", ")", "or", "time", ".", "time", "(", ")", ")", "else", ":", "self", ".", "_session_dir", "=", "self", ".", "_rpc", ".", "session", ".", "path", "(", ")", "if", "not", "self", ".", "_session_dir", ":", "raise", "error", ".", "UserError", "(", "\"You need a session directory, read\"", "\" https://pyrocore.readthedocs.io/en/latest/setup.html\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_session_dir", ")", ":", "raise", "error", ".", "UserError", "(", "\"Non-existing session directory %r\"", "%", "self", ".", "_session_dir", ")", "self", ".", "_download_dir", "=", "os", ".", "path", ".", "expanduser", "(", "self", ".", "_rpc", ".", "directory", ".", "default", "(", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_download_dir", ")", ":", "raise", "error", ".", "UserError", "(", "\"Non-existing download directory %r\"", "%", "self", ".", "_download_dir", ")", "self", ".", "startup", "=", "os", ".", "path", ".", "getmtime", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_session_dir", ",", "\"rtorrent.lock\"", ")", ")", "# Return connection", "self", ".", "LOG", ".", "debug", "(", "repr", "(", "self", ")", ")", "return", "self", ".", "_rpc" ]
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 = namedtuple('DownloadItem', [x.replace('.', '_') for x in fields]) items = self.open().d.multicall(viewname, *commands) return [result_type(*x) for x in items]
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 = namedtuple('DownloadItem', [x.replace('.', '_') for x in fields]) items = self.open().d.multicall(viewname, *commands) return [result_type(*x) for x in items]
[ "def", "multicall", "(", "self", ",", "viewname", ",", "fields", ")", ":", "commands", "=", "tuple", "(", "'d.{}='", ".", "format", "(", "x", ")", "for", "x", "in", "fields", ")", "result_type", "=", "namedtuple", "(", "'DownloadItem'", ",", "[", "x", ".", "replace", "(", "'.'", ",", "'_'", ")", "for", "x", "in", "fields", "]", ")", "items", "=", "self", ".", "open", "(", ")", ".", "d", ".", "multicall", "(", "viewname", ",", "*", "commands", ")", "return", "[", "result_type", "(", "*", "x", ")", "for", "x", "in", "items", "]" ]
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.UserError("There is no [{}] section in your configuration" .format(section_name.upper())) for ruledef, filtercond in ruledefs.items(): if ruledef.endswith('.filter'): rulename = ruledef.rsplit('.', 1)[0] rule = SweepRule(ruleset, rulename, int(ruledefs.get(rulename + '.prio', '999')), ruledefs.get(rulename + '.order', self.default_order), parse_cond(filtercond)) self.rules.append(rule) self.rules.sort(key=lambda x: (x.prio, x.name)) return self.rules
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.UserError("There is no [{}] section in your configuration" .format(section_name.upper())) for ruledef, filtercond in ruledefs.items(): if ruledef.endswith('.filter'): rulename = ruledef.rsplit('.', 1)[0] rule = SweepRule(ruleset, rulename, int(ruledefs.get(rulename + '.prio', '999')), ruledefs.get(rulename + '.order', self.default_order), parse_cond(filtercond)) self.rules.append(rule) self.rules.sort(key=lambda x: (x.prio, x.name)) return self.rules
[ "def", "_load_rules", "(", "self", ")", ":", "for", "ruleset", "in", "self", ".", "active_rulesets", ":", "section_name", "=", "'sweep_rules_'", "+", "ruleset", ".", "lower", "(", ")", "try", ":", "ruledefs", "=", "getattr", "(", "self", ".", "config", ",", "section_name", ")", "except", "AttributeError", ":", "raise", "error", ".", "UserError", "(", "\"There is no [{}] section in your configuration\"", ".", "format", "(", "section_name", ".", "upper", "(", ")", ")", ")", "for", "ruledef", ",", "filtercond", "in", "ruledefs", ".", "items", "(", ")", ":", "if", "ruledef", ".", "endswith", "(", "'.filter'", ")", ":", "rulename", "=", "ruledef", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "rule", "=", "SweepRule", "(", "ruleset", ",", "rulename", ",", "int", "(", "ruledefs", ".", "get", "(", "rulename", "+", "'.prio'", ",", "'999'", ")", ")", ",", "ruledefs", ".", "get", "(", "rulename", "+", "'.order'", ",", "self", ".", "default_order", ")", ",", "parse_cond", "(", "filtercond", ")", ")", "self", ".", "rules", ".", "append", "(", "rule", ")", "self", ".", "rules", ".", "sort", "(", "key", "=", "lambda", "x", ":", "(", "x", ".", "prio", ",", "x", ".", "name", ")", ")", "return", "self", ".", "rules" ]
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("Bad param '%s' in job schedule '%s'" % (param, schedule)) else: result[key] = val return result
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("Bad param '%s' in job schedule '%s'" % (param, schedule)) else: result[key] = val return result
[ "def", "_parse_schedule", "(", "self", ",", "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", "(", "\"Bad param '%s' in job schedule '%s'\"", "%", "(", "param", ",", "schedule", ")", ")", "else", ":", "result", "[", "key", "]", "=", "val", "return", "result" ]
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(): config.torque[key] = val = int(val) elif val.lower() in (matching.TRUE | matching.FALSE): val = matching.truth(str(val), key) # Assemble grouped parameters stem = key.split('.', 1)[0] if key == "httpd.active": groups[stem]["active"] = val elif stem in groups: try: stem, name, param = key.split('.', 2) except (TypeError, ValueError): self.fatal("Bad %s configuration key %r (expecting %s.NAME.PARAM)" % (stem, key, stem)) else: groups[stem][name][param] = val for key, val in groups.iteritems(): setattr(self, key.replace("job", "jobs"), Bunch(val)) # Validate httpd config if self.httpd.active: if self.httpd.waitress.url_scheme not in ("http", "https"): self.fatal("HTTP URL scheme must be either 'http' or 'https'") if not isinstance(self.httpd.waitress.port, int) or not(1024 <= self.httpd.waitress.port < 65536): self.fatal("HTTP port must be a 16 bit number >= 1024") # Validate jobs for name, params in self.jobs.items(): for key in ("handler", "schedule"): if key not in params: self.fatal("Job '%s' is missing the required 'job.%s.%s' parameter" % (name, name, key)) bool_param = lambda k, default, p=params: matching.truth(p.get(k, default), "job.%s.%s" % (name, k)) params.job_name = name params.dry_run = bool_param("dry_run", False) or self.options.dry_run params.active = bool_param("active", True) params.schedule = self._parse_schedule(params.schedule) if params.active: try: params.handler = pymagic.import_name(params.handler) except ImportError as exc: self.fatal("Bad handler name '%s' for job '%s':\n %s" % (params.handler, name, exc))
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(): config.torque[key] = val = int(val) elif val.lower() in (matching.TRUE | matching.FALSE): val = matching.truth(str(val), key) # Assemble grouped parameters stem = key.split('.', 1)[0] if key == "httpd.active": groups[stem]["active"] = val elif stem in groups: try: stem, name, param = key.split('.', 2) except (TypeError, ValueError): self.fatal("Bad %s configuration key %r (expecting %s.NAME.PARAM)" % (stem, key, stem)) else: groups[stem][name][param] = val for key, val in groups.iteritems(): setattr(self, key.replace("job", "jobs"), Bunch(val)) # Validate httpd config if self.httpd.active: if self.httpd.waitress.url_scheme not in ("http", "https"): self.fatal("HTTP URL scheme must be either 'http' or 'https'") if not isinstance(self.httpd.waitress.port, int) or not(1024 <= self.httpd.waitress.port < 65536): self.fatal("HTTP port must be a 16 bit number >= 1024") # Validate jobs for name, params in self.jobs.items(): for key in ("handler", "schedule"): if key not in params: self.fatal("Job '%s' is missing the required 'job.%s.%s' parameter" % (name, name, key)) bool_param = lambda k, default, p=params: matching.truth(p.get(k, default), "job.%s.%s" % (name, k)) params.job_name = name params.dry_run = bool_param("dry_run", False) or self.options.dry_run params.active = bool_param("active", True) params.schedule = self._parse_schedule(params.schedule) if params.active: try: params.handler = pymagic.import_name(params.handler) except ImportError as exc: self.fatal("Bad handler name '%s' for job '%s':\n %s" % (params.handler, name, exc))
[ "def", "_validate_config", "(", "self", ")", ":", "groups", "=", "dict", "(", "job", "=", "defaultdict", "(", "Bunch", ")", ",", "httpd", "=", "defaultdict", "(", "Bunch", ")", ",", ")", "for", "key", ",", "val", "in", "config", ".", "torque", ".", "items", "(", ")", ":", "# Auto-convert numbers and bools", "if", "val", ".", "isdigit", "(", ")", ":", "config", ".", "torque", "[", "key", "]", "=", "val", "=", "int", "(", "val", ")", "elif", "val", ".", "lower", "(", ")", "in", "(", "matching", ".", "TRUE", "|", "matching", ".", "FALSE", ")", ":", "val", "=", "matching", ".", "truth", "(", "str", "(", "val", ")", ",", "key", ")", "# Assemble grouped parameters", "stem", "=", "key", ".", "split", "(", "'.'", ",", "1", ")", "[", "0", "]", "if", "key", "==", "\"httpd.active\"", ":", "groups", "[", "stem", "]", "[", "\"active\"", "]", "=", "val", "elif", "stem", "in", "groups", ":", "try", ":", "stem", ",", "name", ",", "param", "=", "key", ".", "split", "(", "'.'", ",", "2", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "self", ".", "fatal", "(", "\"Bad %s configuration key %r (expecting %s.NAME.PARAM)\"", "%", "(", "stem", ",", "key", ",", "stem", ")", ")", "else", ":", "groups", "[", "stem", "]", "[", "name", "]", "[", "param", "]", "=", "val", "for", "key", ",", "val", "in", "groups", ".", "iteritems", "(", ")", ":", "setattr", "(", "self", ",", "key", ".", "replace", "(", "\"job\"", ",", "\"jobs\"", ")", ",", "Bunch", "(", "val", ")", ")", "# Validate httpd config", "if", "self", ".", "httpd", ".", "active", ":", "if", "self", ".", "httpd", ".", "waitress", ".", "url_scheme", "not", "in", "(", "\"http\"", ",", "\"https\"", ")", ":", "self", ".", "fatal", "(", "\"HTTP URL scheme must be either 'http' or 'https'\"", ")", "if", "not", "isinstance", "(", "self", ".", "httpd", ".", "waitress", ".", "port", ",", "int", ")", "or", "not", "(", "1024", "<=", "self", ".", "httpd", ".", "waitress", ".", "port", "<", "65536", ")", ":", "self", ".", "fatal", "(", "\"HTTP port must be a 16 bit number >= 1024\"", ")", "# Validate jobs", "for", "name", ",", "params", "in", "self", ".", "jobs", ".", "items", "(", ")", ":", "for", "key", "in", "(", "\"handler\"", ",", "\"schedule\"", ")", ":", "if", "key", "not", "in", "params", ":", "self", ".", "fatal", "(", "\"Job '%s' is missing the required 'job.%s.%s' parameter\"", "%", "(", "name", ",", "name", ",", "key", ")", ")", "bool_param", "=", "lambda", "k", ",", "default", ",", "p", "=", "params", ":", "matching", ".", "truth", "(", "p", ".", "get", "(", "k", ",", "default", ")", ",", "\"job.%s.%s\"", "%", "(", "name", ",", "k", ")", ")", "params", ".", "job_name", "=", "name", "params", ".", "dry_run", "=", "bool_param", "(", "\"dry_run\"", ",", "False", ")", "or", "self", ".", "options", ".", "dry_run", "params", ".", "active", "=", "bool_param", "(", "\"active\"", ",", "True", ")", "params", ".", "schedule", "=", "self", ".", "_parse_schedule", "(", "params", ".", "schedule", ")", "if", "params", ".", "active", ":", "try", ":", "params", ".", "handler", "=", "pymagic", ".", "import_name", "(", "params", ".", "handler", ")", "except", "ImportError", "as", "exc", ":", "self", ".", "fatal", "(", "\"Bad handler name '%s' for job '%s':\\n %s\"", "%", "(", "params", ".", "handler", ",", "name", ",", "exc", ")", ")" ]
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", ".", "sched", ".", "add_cron_job", "(", "params", ".", "handler", ".", "run", ",", "*", "*", "params", ".", "schedule", ")" ]
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 up WSGI stack wsgi_app = webapp.make_app(self.httpd) # try: # import wsgilog # except ImportError: # self.LOG.info("'wsgilog' middleware not installed") # else: # wsgi_app = wsgilog.WsgiLog(wsgi_app, **self.httpd.wsgilog) ##logging.getLogger('waitress').setLevel(logging.DEBUG) self.LOG.debug("Waitress config: %r" % self.httpd.waitress) self.wsgi_server = WSGIServer(wsgi_app, **self.httpd.waitress) self.LOG.info("Started web server at %s://%s:%d/" % ( self.httpd.waitress.url_scheme, self.wsgi_server.get_server_name(self.wsgi_server.effective_host), int(self.wsgi_server.effective_port), ))
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 up WSGI stack wsgi_app = webapp.make_app(self.httpd) # try: # import wsgilog # except ImportError: # self.LOG.info("'wsgilog' middleware not installed") # else: # wsgi_app = wsgilog.WsgiLog(wsgi_app, **self.httpd.wsgilog) ##logging.getLogger('waitress').setLevel(logging.DEBUG) self.LOG.debug("Waitress config: %r" % self.httpd.waitress) self.wsgi_server = WSGIServer(wsgi_app, **self.httpd.waitress) self.LOG.info("Started web server at %s://%s:%d/" % ( self.httpd.waitress.url_scheme, self.wsgi_server.get_server_name(self.wsgi_server.effective_host), int(self.wsgi_server.effective_port), ))
[ "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", "pyrocore", ".", "daemon", "import", "webapp", "# Set up WSGI stack", "wsgi_app", "=", "webapp", ".", "make_app", "(", "self", ".", "httpd", ")", "# try:", "# import wsgilog", "# except ImportError:", "# self.LOG.info(\"'wsgilog' middleware not installed\")", "# else:", "# wsgi_app = wsgilog.WsgiLog(wsgi_app, **self.httpd.wsgilog)", "##logging.getLogger('waitress').setLevel(logging.DEBUG)", "self", ".", "LOG", ".", "debug", "(", "\"Waitress config: %r\"", "%", "self", ".", "httpd", ".", "waitress", ")", "self", ".", "wsgi_server", "=", "WSGIServer", "(", "wsgi_app", ",", "*", "*", "self", ".", "httpd", ".", "waitress", ")", "self", ".", "LOG", ".", "info", "(", "\"Started web server at %s://%s:%d/\"", "%", "(", "self", ".", "httpd", ".", "waitress", ".", "url_scheme", ",", "self", ".", "wsgi_server", ".", "get_server_name", "(", "self", ".", "wsgi_server", ".", "effective_host", ")", ",", "int", "(", "self", ".", "wsgi_server", ".", "effective_port", ")", ",", ")", ")" ]
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 += self.POLL_TIMEOUT - time.time() if tick > 0: # wait POLL_TIMEOUT at most (robust against time shifts) time.sleep(min(tick, self.POLL_TIMEOUT)) except KeyboardInterrupt as exc: self.LOG.info("Termination request received (%s)" % exc) break except SystemExit as exc: self.return_code = exc.code or 0 self.LOG.info("System exit (RC=%r)" % self.return_code) break else: # Idle work #self.LOG.warn("IDLE %s %r" % (self.options.guard_file, os.path.exists(self.options.guard_file))) if self.options.guard_file and not os.path.exists(self.options.guard_file): self.LOG.warn("Guard file '%s' disappeared, exiting!" % self.options.guard_file) break
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 += self.POLL_TIMEOUT - time.time() if tick > 0: # wait POLL_TIMEOUT at most (robust against time shifts) time.sleep(min(tick, self.POLL_TIMEOUT)) except KeyboardInterrupt as exc: self.LOG.info("Termination request received (%s)" % exc) break except SystemExit as exc: self.return_code = exc.code or 0 self.LOG.info("System exit (RC=%r)" % self.return_code) break else: # Idle work #self.LOG.warn("IDLE %s %r" % (self.options.guard_file, os.path.exists(self.options.guard_file))) if self.options.guard_file and not os.path.exists(self.options.guard_file): self.LOG.warn("Guard file '%s' disappeared, exiting!" % self.options.guard_file) break
[ "def", "_run_forever", "(", "self", ")", ":", "while", "True", ":", "try", ":", "tick", "=", "time", ".", "time", "(", ")", "asyncore", ".", "loop", "(", "timeout", "=", "self", ".", "POLL_TIMEOUT", ",", "use_poll", "=", "True", ")", "# Sleep for remaining poll cycle time", "tick", "+=", "self", ".", "POLL_TIMEOUT", "-", "time", ".", "time", "(", ")", "if", "tick", ">", "0", ":", "# wait POLL_TIMEOUT at most (robust against time shifts)", "time", ".", "sleep", "(", "min", "(", "tick", ",", "self", ".", "POLL_TIMEOUT", ")", ")", "except", "KeyboardInterrupt", "as", "exc", ":", "self", ".", "LOG", ".", "info", "(", "\"Termination request received (%s)\"", "%", "exc", ")", "break", "except", "SystemExit", "as", "exc", ":", "self", ".", "return_code", "=", "exc", ".", "code", "or", "0", "self", ".", "LOG", ".", "info", "(", "\"System exit (RC=%r)\"", "%", "self", ".", "return_code", ")", "break", "else", ":", "# Idle work", "#self.LOG.warn(\"IDLE %s %r\" % (self.options.guard_file, os.path.exists(self.options.guard_file)))", "if", "self", ".", "options", ".", "guard_file", "and", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "options", ".", "guard_file", ")", ":", "self", ".", "LOG", ".", "warn", "(", "\"Guard file '%s' disappeared, exiting!\"", "%", "self", ".", "options", ".", "guard_file", ")", "break" ]
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' to support @URL arguments.") try: response = requests.get(arg[1:]) response.raise_for_status() result = response.content except requests.RequestException as exc: raise error.UserError(str(exc)) else: with open(os.path.expanduser(arg[1:]), 'rb') as handle: result = handle.read() return result
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' to support @URL arguments.") try: response = requests.get(arg[1:]) response.raise_for_status() result = response.content except requests.RequestException as exc: raise error.UserError(str(exc)) else: with open(os.path.expanduser(arg[1:]), 'rb') as handle: result = handle.read() return result
[ "def", "read_blob", "(", "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' to support @URL arguments.\"", ")", "try", ":", "response", "=", "requests", ".", "get", "(", "arg", "[", "1", ":", "]", ")", "response", ".", "raise_for_status", "(", ")", "result", "=", "response", ".", "content", "except", "requests", ".", "RequestException", "as", "exc", ":", "raise", "error", ".", "UserError", "(", "str", "(", "exc", ")", ")", "else", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "arg", "[", "1", ":", "]", ")", ",", "'rb'", ")", "as", "handle", ":", "result", "=", "handle", ".", "read", "(", ")", "return", "result" ]
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://pyrocore.readthedocs.io/en/latest/setup.html") self.proxy = xmlrpc.RTorrentProxy(config.scgi_url) self.proxy._set_mappings() return self.proxy
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://pyrocore.readthedocs.io/en/latest/setup.html") self.proxy = xmlrpc.RTorrentProxy(config.scgi_url) self.proxy._set_mappings() return self.proxy
[ "def", "open", "(", "self", ")", ":", "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://pyrocore.readthedocs.io/en/latest/setup.html\"", ")", "self", ".", "proxy", "=", "xmlrpc", ".", "RTorrentProxy", "(", "config", ".", "scgi_url", ")", "self", ".", "proxy", ".", "_set_mappings", "(", ")", "return", "self", ".", "proxy" ]
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)) self.return_code = error.EX_NOINPUT if "not find" in getattr(exc, "faultString", "") else error.EX_DATAERR else: if not self.options.quiet: if self.options.repr: # Pretty-print if requested, or it's a collection and not a scalar result = pformat(result) elif hasattr(result, "__iter__"): result = '\n'.join(i if isinstance(i, basestring) else pformat(i) for i in result) print(fmt.to_console(result))
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)) self.return_code = error.EX_NOINPUT if "not find" in getattr(exc, "faultString", "") else error.EX_DATAERR else: if not self.options.quiet: if self.options.repr: # Pretty-print if requested, or it's a collection and not a scalar result = pformat(result) elif hasattr(result, "__iter__"): result = '\n'.join(i if isinstance(i, basestring) else pformat(i) for i in result) print(fmt.to_console(result))
[ "def", "execute", "(", "self", ",", "proxy", ",", "method", ",", "args", ")", ":", "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", ")", ")", "self", ".", "return_code", "=", "error", ".", "EX_NOINPUT", "if", "\"not find\"", "in", "getattr", "(", "exc", ",", "\"faultString\"", ",", "\"\"", ")", "else", "error", ".", "EX_DATAERR", "else", ":", "if", "not", "self", ".", "options", ".", "quiet", ":", "if", "self", ".", "options", ".", "repr", ":", "# Pretty-print if requested, or it's a collection and not a scalar", "result", "=", "pformat", "(", "result", ")", "elif", "hasattr", "(", "result", ",", "\"__iter__\"", ")", ":", "result", "=", "'\\n'", ".", "join", "(", "i", "if", "isinstance", "(", "i", ",", "basestring", ")", "else", "pformat", "(", "i", ")", "for", "i", "in", "result", ")", "print", "(", "fmt", ".", "to_console", "(", "result", ")", ")" ]
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.options.quiet = False proxy = self.open() ps1 = proxy.session.name() + u'> ' words = ['help', 'stats', 'exit'] words += [x + '=' for x in proxy.system.listMethods()] history_file = os.path.join(config.config_dir, '.rtxmlrpc_history') while True: try: try: cmd = prompt(ps1, completer=WordCompleter(words), auto_suggest=AutoSuggestFromHistory(), history=FileHistory(history_file)) except KeyboardInterrupt: cmd = '' if not cmd: print("Enter '?' or 'help' for usage information, 'Ctrl-D' to exit.") if cmd in {'?', 'help'}: self.repl_usage() continue elif cmd in {'', 'stats'}: print(repr(proxy).split(None, 1)[1]) continue elif cmd in {'exit'}: raise EOFError() try: method, raw_args = cmd.split('=', 1) except ValueError: print("ERROR: '=' not found") continue raw_args = raw_args.split(',') args = self.cooked(raw_args) self.execute(proxy, method, args) except EOFError: print('Bye from {!r}'.format(proxy)) break
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.options.quiet = False proxy = self.open() ps1 = proxy.session.name() + u'> ' words = ['help', 'stats', 'exit'] words += [x + '=' for x in proxy.system.listMethods()] history_file = os.path.join(config.config_dir, '.rtxmlrpc_history') while True: try: try: cmd = prompt(ps1, completer=WordCompleter(words), auto_suggest=AutoSuggestFromHistory(), history=FileHistory(history_file)) except KeyboardInterrupt: cmd = '' if not cmd: print("Enter '?' or 'help' for usage information, 'Ctrl-D' to exit.") if cmd in {'?', 'help'}: self.repl_usage() continue elif cmd in {'', 'stats'}: print(repr(proxy).split(None, 1)[1]) continue elif cmd in {'exit'}: raise EOFError() try: method, raw_args = cmd.split('=', 1) except ValueError: print("ERROR: '=' not found") continue raw_args = raw_args.split(',') args = self.cooked(raw_args) self.execute(proxy, method, args) except EOFError: print('Bye from {!r}'.format(proxy)) break
[ "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", ".", "contrib", ".", "completers", "import", "WordCompleter", "self", ".", "options", ".", "quiet", "=", "False", "proxy", "=", "self", ".", "open", "(", ")", "ps1", "=", "proxy", ".", "session", ".", "name", "(", ")", "+", "u'> '", "words", "=", "[", "'help'", ",", "'stats'", ",", "'exit'", "]", "words", "+=", "[", "x", "+", "'='", "for", "x", "in", "proxy", ".", "system", ".", "listMethods", "(", ")", "]", "history_file", "=", "os", ".", "path", ".", "join", "(", "config", ".", "config_dir", ",", "'.rtxmlrpc_history'", ")", "while", "True", ":", "try", ":", "try", ":", "cmd", "=", "prompt", "(", "ps1", ",", "completer", "=", "WordCompleter", "(", "words", ")", ",", "auto_suggest", "=", "AutoSuggestFromHistory", "(", ")", ",", "history", "=", "FileHistory", "(", "history_file", ")", ")", "except", "KeyboardInterrupt", ":", "cmd", "=", "''", "if", "not", "cmd", ":", "print", "(", "\"Enter '?' or 'help' for usage information, 'Ctrl-D' to exit.\"", ")", "if", "cmd", "in", "{", "'?'", ",", "'help'", "}", ":", "self", ".", "repl_usage", "(", ")", "continue", "elif", "cmd", "in", "{", "''", ",", "'stats'", "}", ":", "print", "(", "repr", "(", "proxy", ")", ".", "split", "(", "None", ",", "1", ")", "[", "1", "]", ")", "continue", "elif", "cmd", "in", "{", "'exit'", "}", ":", "raise", "EOFError", "(", ")", "try", ":", "method", ",", "raw_args", "=", "cmd", ".", "split", "(", "'='", ",", "1", ")", "except", "ValueError", ":", "print", "(", "\"ERROR: '=' not found\"", ")", "continue", "raw_args", "=", "raw_args", ".", "split", "(", "','", ")", "args", "=", "self", ".", "cooked", "(", "raw_args", ")", "self", ".", "execute", "(", "proxy", ",", "method", ",", "args", ")", "except", "EOFError", ":", "print", "(", "'Bye from {!r}'", ".", "format", "(", "proxy", ")", ")", "break" ]
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): self.parser.error("File not found (or not a file): {}".format(import_file)) args = (xmlrpc.NOHASH, os.path.abspath(import_file)) else: script_text = '\n'.join(self.args + ['']) if script_text == '@-\n': script_text = sys.stdin.read() with tempfile.NamedTemporaryFile(suffix='.rc', prefix='rtxmlrpc-', delete=False) as handle: handle.write(script_text) tmp_import = handle.name args = (xmlrpc.NOHASH, tmp_import) self.execute(self.open(), 'import', args) finally: if tmp_import and os.path.exists(tmp_import): os.remove(tmp_import)
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): self.parser.error("File not found (or not a file): {}".format(import_file)) args = (xmlrpc.NOHASH, os.path.abspath(import_file)) else: script_text = '\n'.join(self.args + ['']) if script_text == '@-\n': script_text = sys.stdin.read() with tempfile.NamedTemporaryFile(suffix='.rc', prefix='rtxmlrpc-', delete=False) as handle: handle.write(script_text) tmp_import = handle.name args = (xmlrpc.NOHASH, tmp_import) self.execute(self.open(), 'import', args) finally: if tmp_import and os.path.exists(tmp_import): os.remove(tmp_import)
[ "def", "do_import", "(", "self", ")", ":", "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", ")", ":", "self", ".", "parser", ".", "error", "(", "\"File not found (or not a file): {}\"", ".", "format", "(", "import_file", ")", ")", "args", "=", "(", "xmlrpc", ".", "NOHASH", ",", "os", ".", "path", ".", "abspath", "(", "import_file", ")", ")", "else", ":", "script_text", "=", "'\\n'", ".", "join", "(", "self", ".", "args", "+", "[", "''", "]", ")", "if", "script_text", "==", "'@-\\n'", ":", "script_text", "=", "sys", ".", "stdin", ".", "read", "(", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.rc'", ",", "prefix", "=", "'rtxmlrpc-'", ",", "delete", "=", "False", ")", "as", "handle", ":", "handle", ".", "write", "(", "script_text", ")", "tmp_import", "=", "handle", ".", "name", "args", "=", "(", "xmlrpc", ".", "NOHASH", ",", "tmp_import", ")", "self", ".", "execute", "(", "self", ".", "open", "(", ")", ",", "'import'", ",", "args", ")", "finally", ":", "if", "tmp_import", "and", "os", ".", "path", ".", "exists", "(", "tmp_import", ")", ":", "os", ".", "remove", "(", "tmp_import", ")" ]
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.split('=', 1) raw_args = raw_args.split(',') self.execute(self.open(), method, self.cooked(raw_args))
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.split('=', 1) raw_args = raw_args.split(',') self.execute(self.open(), method, self.cooked(raw_args))
[ "def", "do_command", "(", "self", ")", ":", "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", ".", "split", "(", "'='", ",", "1", ")", "raw_args", "=", "raw_args", ".", "split", "(", "','", ")", "self", ".", "execute", "(", "self", ".", "open", "(", ")", ",", "method", ",", "self", ".", "cooked", "(", "raw_args", ")", ")" ]
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(target, guard)): self.LOG.info("Already have '%s' in '%s'..." % (download_url, target)) return if not os.path.isdir(target): os.makedirs(target) self.LOG.info("Downloading '%s' to '%s'..." % (download_url, target)) with closing(urllib2.urlopen(download_url)) as url_handle: if download_url.endswith(".zip"): with closing(ZipFile(StringIO(url_handle.read()))) as zip_handle: # pylint: disable=no-member zip_handle.extractall(target) # pylint: disable=no-member else: with open(os.path.join(target, guard), "wb") as file_handle: shutil.copyfileobj(url_handle, file_handle)
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(target, guard)): self.LOG.info("Already have '%s' in '%s'..." % (download_url, target)) return if not os.path.isdir(target): os.makedirs(target) self.LOG.info("Downloading '%s' to '%s'..." % (download_url, target)) with closing(urllib2.urlopen(download_url)) as url_handle: if download_url.endswith(".zip"): with closing(ZipFile(StringIO(url_handle.read()))) as zip_handle: # pylint: disable=no-member zip_handle.extractall(target) # pylint: disable=no-member else: with open(os.path.join(target, guard), "wb") as file_handle: shutil.copyfileobj(url_handle, file_handle)
[ "def", "download_resource", "(", "self", ",", "download_url", ",", "target", ",", "guard", ")", ":", "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", "(", "target", ",", "guard", ")", ")", ":", "self", ".", "LOG", ".", "info", "(", "\"Already have '%s' in '%s'...\"", "%", "(", "download_url", ",", "target", ")", ")", "return", "if", "not", "os", ".", "path", ".", "isdir", "(", "target", ")", ":", "os", ".", "makedirs", "(", "target", ")", "self", ".", "LOG", ".", "info", "(", "\"Downloading '%s' to '%s'...\"", "%", "(", "download_url", ",", "target", ")", ")", "with", "closing", "(", "urllib2", ".", "urlopen", "(", "download_url", ")", ")", "as", "url_handle", ":", "if", "download_url", ".", "endswith", "(", "\".zip\"", ")", ":", "with", "closing", "(", "ZipFile", "(", "StringIO", "(", "url_handle", ".", "read", "(", ")", ")", ")", ")", "as", "zip_handle", ":", "# pylint: disable=no-member", "zip_handle", ".", "extractall", "(", "target", ")", "# pylint: disable=no-member", "else", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "target", ",", "guard", ")", ",", "\"wb\"", ")", "as", "file_handle", ":", "shutil", ".", "copyfileobj", "(", "url_handle", ",", "file_handle", ")" ]
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("Bad boolean value %r in %r (expected one of '%s', or '%s')" % ( val, context, "' '".join(TRUE), "' '".join(FALSE) )) else: return bool(val)
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("Bad boolean value %r in %r (expected one of '%s', or '%s')" % ( val, context, "' '".join(TRUE), "' '".join(FALSE) )) else: return bool(val)
[ "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", ":", "return", "False", "else", ":", "raise", "FilterError", "(", "\"Bad boolean value %r in %r (expected one of '%s', or '%s')\"", "%", "(", "val", ",", "context", ",", "\"' '\"", ".", "join", "(", "TRUE", ")", ",", "\"' '\"", ".", "join", "(", "FALSE", ")", ")", ")", "else", ":", "return", "bool", "(", "val", ")" ]
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", ".", "mktime", "(", "timestamp", ")" ]
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], pre_filter) return pre_filter
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], pre_filter) return pre_filter
[ "def", "unquote_pre_filter", "(", "pre_filter", ",", "_regex", "=", "re", ".", "compile", "(", "r'[\\\\]+'", ")", ")", ":", "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", "]", ",", "pre_filter", ")", "return", "pre_filter" ]
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() if values and values[0] in "+-": raise FilterError("Comparison operator cannot be followed by '%s' in '%s'" % (values[0], condition)) values = self.COMPARISON_OPS[comparison] % values else: # Split name from value(s) try: name, values = condition.split('=', 1) except ValueError: if self.default_field: name, values = self.default_field, condition else: raise FilterError("Field name missing in '%s' (expected '=')" % condition) # Try to find field definition field = self.lookup(name) if not field: raise FilterError("Unknown field %r in %r" % (name, condition)) if field.get("matcher") is None: raise FilterError("Field %r cannot be used as a filter" % (name,)) # Make filters from values (split on commas outside of /…/) filters = [] split_values = re.findall(r'(!?/[^/]*/|[^,]+)(?:,|$)', values) if values else [''] if not split_values: raise FilterError("Internal Error: Cannot split %r into match values" % (values,)) for value in split_values: wrapper = None if value.startswith('!'): wrapper = NegateFilter value = value[1:] field_matcher = field["matcher"](name, value) filters.append(wrapper(field_matcher) if wrapper else field_matcher) # Return filters return CompoundFilterAny(filters) if len(filters) > 1 else filters[0]
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() if values and values[0] in "+-": raise FilterError("Comparison operator cannot be followed by '%s' in '%s'" % (values[0], condition)) values = self.COMPARISON_OPS[comparison] % values else: # Split name from value(s) try: name, values = condition.split('=', 1) except ValueError: if self.default_field: name, values = self.default_field, condition else: raise FilterError("Field name missing in '%s' (expected '=')" % condition) # Try to find field definition field = self.lookup(name) if not field: raise FilterError("Unknown field %r in %r" % (name, condition)) if field.get("matcher") is None: raise FilterError("Field %r cannot be used as a filter" % (name,)) # Make filters from values (split on commas outside of /…/) filters = [] split_values = re.findall(r'(!?/[^/]*/|[^,]+)(?:,|$)', values) if values else [''] if not split_values: raise FilterError("Internal Error: Cannot split %r into match values" % (values,)) for value in split_values: wrapper = None if value.startswith('!'): wrapper = NegateFilter value = value[1:] field_matcher = field["matcher"](name, value) filters.append(wrapper(field_matcher) if wrapper else field_matcher) # Return filters return CompoundFilterAny(filters) if len(filters) > 1 else filters[0]
[ "def", "_create_filter", "(", "self", ",", "condition", ")", ":", "# \"Normal\" comparison operators?", "comparison", "=", "re", ".", "match", "(", "r\"^(%s)(<[>=]?|>=?|!=|~)(.*)$\"", "%", "self", ".", "ident_re", ",", "condition", ")", "if", "comparison", ":", "name", ",", "comparison", ",", "values", "=", "comparison", ".", "groups", "(", ")", "if", "values", "and", "values", "[", "0", "]", "in", "\"+-\"", ":", "raise", "FilterError", "(", "\"Comparison operator cannot be followed by '%s' in '%s'\"", "%", "(", "values", "[", "0", "]", ",", "condition", ")", ")", "values", "=", "self", ".", "COMPARISON_OPS", "[", "comparison", "]", "%", "values", "else", ":", "# Split name from value(s)", "try", ":", "name", ",", "values", "=", "condition", ".", "split", "(", "'='", ",", "1", ")", "except", "ValueError", ":", "if", "self", ".", "default_field", ":", "name", ",", "values", "=", "self", ".", "default_field", ",", "condition", "else", ":", "raise", "FilterError", "(", "\"Field name missing in '%s' (expected '=')\"", "%", "condition", ")", "# Try to find field definition", "field", "=", "self", ".", "lookup", "(", "name", ")", "if", "not", "field", ":", "raise", "FilterError", "(", "\"Unknown field %r in %r\"", "%", "(", "name", ",", "condition", ")", ")", "if", "field", ".", "get", "(", "\"matcher\"", ")", "is", "None", ":", "raise", "FilterError", "(", "\"Field %r cannot be used as a filter\"", "%", "(", "name", ",", ")", ")", "# Make filters from values (split on commas outside of /…/)", "filters", "=", "[", "]", "split_values", "=", "re", ".", "findall", "(", "r'(!?/[^/]*/|[^,]+)(?:,|$)'", ",", "values", ")", "if", "values", "else", "[", "''", "]", "if", "not", "split_values", ":", "raise", "FilterError", "(", "\"Internal Error: Cannot split %r into match values\"", "%", "(", "values", ",", ")", ")", "for", "value", "in", "split_values", ":", "wrapper", "=", "None", "if", "value", ".", "startswith", "(", "'!'", ")", ":", "wrapper", "=", "NegateFilter", "value", "=", "value", "[", "1", ":", "]", "field_matcher", "=", "field", "[", "\"matcher\"", "]", "(", "name", ",", "value", ")", "filters", ".", "append", "(", "wrapper", "(", "field_matcher", ")", "if", "wrapper", "else", "field_matcher", ")", "# Return filters", "return", "CompoundFilterAny", "(", "filters", ")", "if", "len", "(", "filters", ")", ">", "1", "else", "filters", "[", "0", "]" ]
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: # Not a string, assume parsed tree conditions_text = self._tree2str(conditions) # Empty list? if not conditions: raise FilterError("No conditions given at all!") # NOT *must* appear at the start of a group negate = conditions[:1] == ["NOT"] if negate: conditions = conditions[1:] if not conditions: raise FilterError("NOT must be followed by some conditions!") # Handle grouping if '[' in conditions: tree = [[]] for term in conditions: if term == '[': tree.append([]) # new grouping elif term == ']': subtree = tree.pop() if not tree: raise FilterError("Unbalanced brackets, too many closing ']' in condition %r" % (conditions_text,)) tree[-1].append(subtree) # append finished group to containing level else: tree[-1].append(term) # append to current level if len(tree) > 1: raise FilterError("Unbalanced brackets, too many open '[' in condition %r" % (conditions_text,)) conditions = tree[0] # Prepare root matcher conditions = list(conditions) matcher = CompoundFilterAll() if "OR" in conditions: root = CompoundFilterAny() root.append(matcher) else: root = matcher # Go through conditions and parse them for condition in conditions: if condition == "OR": # Leading OR, or OR OR in sequence? if not matcher: raise FilterError("Left-hand side of OR missing in %r!" % (conditions_text,)) # Start next run of AND conditions matcher = CompoundFilterAll() root.append(matcher) elif isinstance(condition, list): matcher.append(self.parse(condition)) else: matcher.append(self._create_filter(condition)) # Trailing OR? if not matcher: raise FilterError("Right-hand side of OR missing in %r!" % (conditions_text,)) return NegateFilter(root) if negate else root
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: # Not a string, assume parsed tree conditions_text = self._tree2str(conditions) # Empty list? if not conditions: raise FilterError("No conditions given at all!") # NOT *must* appear at the start of a group negate = conditions[:1] == ["NOT"] if negate: conditions = conditions[1:] if not conditions: raise FilterError("NOT must be followed by some conditions!") # Handle grouping if '[' in conditions: tree = [[]] for term in conditions: if term == '[': tree.append([]) # new grouping elif term == ']': subtree = tree.pop() if not tree: raise FilterError("Unbalanced brackets, too many closing ']' in condition %r" % (conditions_text,)) tree[-1].append(subtree) # append finished group to containing level else: tree[-1].append(term) # append to current level if len(tree) > 1: raise FilterError("Unbalanced brackets, too many open '[' in condition %r" % (conditions_text,)) conditions = tree[0] # Prepare root matcher conditions = list(conditions) matcher = CompoundFilterAll() if "OR" in conditions: root = CompoundFilterAny() root.append(matcher) else: root = matcher # Go through conditions and parse them for condition in conditions: if condition == "OR": # Leading OR, or OR OR in sequence? if not matcher: raise FilterError("Left-hand side of OR missing in %r!" % (conditions_text,)) # Start next run of AND conditions matcher = CompoundFilterAll() root.append(matcher) elif isinstance(condition, list): matcher.append(self.parse(condition)) else: matcher.append(self._create_filter(condition)) # Trailing OR? if not matcher: raise FilterError("Right-hand side of OR missing in %r!" % (conditions_text,)) return NegateFilter(root) if negate else root
[ "def", "parse", "(", "self", ",", "conditions", ")", ":", "conditions_text", "=", "conditions", "try", ":", "conditions", "=", "shlex", ".", "split", "(", "fmt", ".", "to_utf8", "(", "conditions", ")", ")", "except", "AttributeError", ":", "# Not a string, assume parsed tree", "conditions_text", "=", "self", ".", "_tree2str", "(", "conditions", ")", "# Empty list?", "if", "not", "conditions", ":", "raise", "FilterError", "(", "\"No conditions given at all!\"", ")", "# NOT *must* appear at the start of a group", "negate", "=", "conditions", "[", ":", "1", "]", "==", "[", "\"NOT\"", "]", "if", "negate", ":", "conditions", "=", "conditions", "[", "1", ":", "]", "if", "not", "conditions", ":", "raise", "FilterError", "(", "\"NOT must be followed by some conditions!\"", ")", "# Handle grouping", "if", "'['", "in", "conditions", ":", "tree", "=", "[", "[", "]", "]", "for", "term", "in", "conditions", ":", "if", "term", "==", "'['", ":", "tree", ".", "append", "(", "[", "]", ")", "# new grouping", "elif", "term", "==", "']'", ":", "subtree", "=", "tree", ".", "pop", "(", ")", "if", "not", "tree", ":", "raise", "FilterError", "(", "\"Unbalanced brackets, too many closing ']' in condition %r\"", "%", "(", "conditions_text", ",", ")", ")", "tree", "[", "-", "1", "]", ".", "append", "(", "subtree", ")", "# append finished group to containing level", "else", ":", "tree", "[", "-", "1", "]", ".", "append", "(", "term", ")", "# append to current level", "if", "len", "(", "tree", ")", ">", "1", ":", "raise", "FilterError", "(", "\"Unbalanced brackets, too many open '[' in condition %r\"", "%", "(", "conditions_text", ",", ")", ")", "conditions", "=", "tree", "[", "0", "]", "# Prepare root matcher", "conditions", "=", "list", "(", "conditions", ")", "matcher", "=", "CompoundFilterAll", "(", ")", "if", "\"OR\"", "in", "conditions", ":", "root", "=", "CompoundFilterAny", "(", ")", "root", ".", "append", "(", "matcher", ")", "else", ":", "root", "=", "matcher", "# Go through conditions and parse them", "for", "condition", "in", "conditions", ":", "if", "condition", "==", "\"OR\"", ":", "# Leading OR, or OR OR in sequence?", "if", "not", "matcher", ":", "raise", "FilterError", "(", "\"Left-hand side of OR missing in %r!\"", "%", "(", "conditions_text", ",", ")", ")", "# Start next run of AND conditions", "matcher", "=", "CompoundFilterAll", "(", ")", "root", ".", "append", "(", "matcher", ")", "elif", "isinstance", "(", "condition", ",", "list", ")", ":", "matcher", ".", "append", "(", "self", ".", "parse", "(", "condition", ")", ")", "else", ":", "matcher", ".", "append", "(", "self", ".", "_create_filter", "(", "condition", ")", ")", "# Trailing OR?", "if", "not", "matcher", ":", "raise", "FilterError", "(", "\"Right-hand side of OR missing in %r!\"", "%", "(", "conditions_text", ",", ")", ")", "return", "NegateFilter", "(", "root", ")", "if", "negate", "else", "root" ]
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"][1] data["version"] = data["versions"][0] views = data["views"] del data["upload"] del data["download"] del data["versions"] del data["views"] return data, views
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"][1] data["version"] = data["versions"][0] views = data["views"] del data["upload"] del data["download"] del data["versions"] del data["views"] return data, views
[ "def", "_flux_engine_data", "(", "engine", ")", ":", "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\"", "]", "[", "1", "]", "data", "[", "\"version\"", "]", "=", "data", "[", "\"versions\"", "]", "[", "0", "]", "views", "=", "data", "[", "\"views\"", "]", "del", "data", "[", "\"upload\"", "]", "del", "data", "[", "\"download\"", "]", "del", "data", "[", "\"versions\"", "]", "del", "data", "[", "\"views\"", "]", "return", "data", ",", "views" ]
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, True).strip(), proxy )) except (error.LoggableError, xmlrpc.ERRORS), exc: self.LOG.warn(str(exc))
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, True).strip(), proxy )) except (error.LoggableError, xmlrpc.ERRORS), exc: self.LOG.warn(str(exc))
[ "def", "run", "(", "self", ")", ":", "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", ",", "True", ")", ".", "strip", "(", ")", ",", "proxy", ")", ")", "except", "(", "error", ".", "LoggableError", ",", "xmlrpc", ".", "ERRORS", ")", ",", "exc", ":", "self", ".", "LOG", ".", "warn", "(", "str", "(", "exc", ")", ")" ]
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.password) return url
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.password) return url
[ "def", "_influxdb_url", "(", "self", ")", ":", "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", ".", "password", ")", "return", "url" ]
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 self.config.series: try: config_ini.engine.open() data, views = _flux_engine_data(config_ini.engine) fluxdata.append(dict( name=self.config.series, columns=data.keys(), points=[data.values()] )) fluxdata.append(dict( name=self.config.series + '_views', columns=views.keys(), points=[views.values()] )) except (error.LoggableError, xmlrpc.ERRORS), exc: self.LOG.warn("InfluxDB stats: {0}".format(exc)) # if self.config.series_host: # fluxdata.append(dict( # name = self.config.series_host, # columns = .keys(), # points = [.values()] # )) if not fluxdata: self.LOG.debug("InfluxDB stats: no data (previous errors?)") return # Encode into InfluxDB data packet fluxurl = self._influxdb_url() fluxjson = json.dumps(fluxdata) self.LOG.debug("POST to {0} with {1}".format(fluxurl.split('?')[0], fluxjson)) # Push it! try: # TODO: Use a session requests.post(fluxurl, data=fluxjson, timeout=self.influxdb.timeout) except RequestException, exc: self.LOG.info("InfluxDB POST error: {0}".format(exc))
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 self.config.series: try: config_ini.engine.open() data, views = _flux_engine_data(config_ini.engine) fluxdata.append(dict( name=self.config.series, columns=data.keys(), points=[data.values()] )) fluxdata.append(dict( name=self.config.series + '_views', columns=views.keys(), points=[views.values()] )) except (error.LoggableError, xmlrpc.ERRORS), exc: self.LOG.warn("InfluxDB stats: {0}".format(exc)) # if self.config.series_host: # fluxdata.append(dict( # name = self.config.series_host, # columns = .keys(), # points = [.values()] # )) if not fluxdata: self.LOG.debug("InfluxDB stats: no data (previous errors?)") return # Encode into InfluxDB data packet fluxurl = self._influxdb_url() fluxjson = json.dumps(fluxdata) self.LOG.debug("POST to {0} with {1}".format(fluxurl.split('?')[0], fluxjson)) # Push it! try: # TODO: Use a session requests.post(fluxurl, data=fluxjson, timeout=self.influxdb.timeout) except RequestException, exc: self.LOG.info("InfluxDB POST error: {0}".format(exc))
[ "def", "_push_data", "(", "self", ")", ":", "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", "self", ".", "config", ".", "series", ":", "try", ":", "config_ini", ".", "engine", ".", "open", "(", ")", "data", ",", "views", "=", "_flux_engine_data", "(", "config_ini", ".", "engine", ")", "fluxdata", ".", "append", "(", "dict", "(", "name", "=", "self", ".", "config", ".", "series", ",", "columns", "=", "data", ".", "keys", "(", ")", ",", "points", "=", "[", "data", ".", "values", "(", ")", "]", ")", ")", "fluxdata", ".", "append", "(", "dict", "(", "name", "=", "self", ".", "config", ".", "series", "+", "'_views'", ",", "columns", "=", "views", ".", "keys", "(", ")", ",", "points", "=", "[", "views", ".", "values", "(", ")", "]", ")", ")", "except", "(", "error", ".", "LoggableError", ",", "xmlrpc", ".", "ERRORS", ")", ",", "exc", ":", "self", ".", "LOG", ".", "warn", "(", "\"InfluxDB stats: {0}\"", ".", "format", "(", "exc", ")", ")", "# if self.config.series_host:", "# fluxdata.append(dict(", "# name = self.config.series_host,", "# columns = .keys(),", "# points = [.values()]", "# ))", "if", "not", "fluxdata", ":", "self", ".", "LOG", ".", "debug", "(", "\"InfluxDB stats: no data (previous errors?)\"", ")", "return", "# Encode into InfluxDB data packet", "fluxurl", "=", "self", ".", "_influxdb_url", "(", ")", "fluxjson", "=", "json", ".", "dumps", "(", "fluxdata", ")", "self", ".", "LOG", ".", "debug", "(", "\"POST to {0} with {1}\"", ".", "format", "(", "fluxurl", ".", "split", "(", "'?'", ")", "[", "0", "]", ",", "fluxjson", ")", ")", "# Push it!", "try", ":", "# TODO: Use a session", "requests", ".", "post", "(", "fluxurl", ",", "data", "=", "fluxjson", ",", "timeout", "=", "self", ".", "influxdb", ".", "timeout", ")", "except", "RequestException", ",", "exc", ":", "self", ".", "LOG", ".", "info", "(", "\"InfluxDB POST error: {0}\"", ".", "format", "(", "exc", ")", ")" ]
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.LOG.warn(str(exc))
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.LOG.warn(str(exc))
[ "def", "run", "(", "self", ")", ":", "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", ".", "LOG", ".", "warn", "(", "str", "(", "exc", ")", ")" ]
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', '.') for i in field.replace('..', '\0').split('.')] for key in keypath[:-1]: namespace = namespace[key] namespace[keypath[-1]] = re.sub(regex, subst, namespace[keypath[-1]]) except (KeyError, IndexError, TypeError, ValueError) as exc: raise error.UserError("Bad substitution '%s' (%s)!" % (pattern, exc)) return meta
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', '.') for i in field.replace('..', '\0').split('.')] for key in keypath[:-1]: namespace = namespace[key] namespace[keypath[-1]] = re.sub(regex, subst, namespace[keypath[-1]]) except (KeyError, IndexError, TypeError, ValueError) as exc: raise error.UserError("Bad substitution '%s' (%s)!" % (pattern, exc)) return meta
[ "def", "replace_fields", "(", "meta", ",", "patterns", ")", ":", "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'", ",", "'.'", ")", "for", "i", "in", "field", ".", "replace", "(", "'..'", ",", "'\\0'", ")", ".", "split", "(", "'.'", ")", "]", "for", "key", "in", "keypath", "[", ":", "-", "1", "]", ":", "namespace", "=", "namespace", "[", "key", "]", "namespace", "[", "keypath", "[", "-", "1", "]", "]", "=", "re", ".", "sub", "(", "regex", ",", "subst", ",", "namespace", "[", "keypath", "[", "-", "1", "]", "]", ")", "except", "(", "KeyError", ",", "IndexError", ",", "TypeError", ",", "ValueError", ")", "as", "exc", ":", "raise", "error", ".", "UserError", "(", "\"Bad substitution '%s' (%s)!\"", "%", "(", "pattern", ",", "exc", ")", ")", "return", "meta" ]
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) load_config.ConfigLoader(config_dir).load(optional_config_files or []) from pyrocore import config config.engine.open() return config.engine
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) load_config.ConfigLoader(config_dir).load(optional_config_files or []) from pyrocore import config config.engine.open() return config.engine
[ "def", "connect", "(", "config_dir", "=", "None", ",", "optional_config_files", "=", "None", ",", "cron_cfg", "=", "\"cron\"", ")", ":", "from", "pyrocore", ".", "scripts", ".", "base", "import", "ScriptBase", "from", "pyrocore", ".", "util", "import", "load_config", "ScriptBase", ".", "setup", "(", "cron_cfg", "=", "cron_cfg", ")", "load_config", ".", "ConfigLoader", "(", "config_dir", ")", ".", "load", "(", "optional_config_files", "or", "[", "]", ")", "from", "pyrocore", "import", "config", "config", ".", "engine", ".", "open", "(", ")", "return", "config", ".", "engine" ]
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(logging_cfg) if os.path.exists(logging_cfg): logging.HERE = os.path.dirname(logging_cfg) logging.config.fileConfig(logging_cfg) else: logging.basicConfig(level=logging.INFO) logging.getLogger().debug("Logging config read from '%s'" % logging_cfg)
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(logging_cfg) if os.path.exists(logging_cfg): logging.HERE = os.path.dirname(logging_cfg) logging.config.fileConfig(logging_cfg) else: logging.basicConfig(level=logging.INFO) logging.getLogger().debug("Logging config read from '%s'" % logging_cfg)
[ "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", "\"--cron\"", "in", "sys", ".", "argv", "[", "1", ":", "]", "else", "\"scripts\"", ",", ")", "logging_cfg", "=", "os", ".", "path", ".", "expanduser", "(", "logging_cfg", ")", "if", "os", ".", "path", ".", "exists", "(", "logging_cfg", ")", ":", "logging", ".", "HERE", "=", "os", ".", "path", ".", "dirname", "(", "logging_cfg", ")", "logging", ".", "config", ".", "fileConfig", "(", "logging_cfg", ")", "else", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ")", "logging", ".", "getLogger", "(", ")", ".", "debug", "(", "\"Logging config read from '%s'\"", "%", "logging_cfg", ")" ]
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: # Development setup pkg_path = os.path.join( __file__.split(__name__.replace('.', os.sep))[0], # containing path __name__.split(".")[0] # package name ) if os.path.exists(pkg_path + info_ext): pkg_path += info_ext else: globbed_paths = glob.glob(pkg_path + "-*-py%d.%d" % sys.version_info[:2] + info_ext) if len(globbed_paths) == 1: pkg_path = globbed_paths[0] elif globbed_paths: warnings.append("Found {} release-specific candidate versions in *{}" .format(len(globbed_paths), info_ext)) pkg_path = None else: globbed_paths = glob.glob(pkg_path + "-*" + info_ext) if len(globbed_paths) == 1: pkg_path = globbed_paths[0] else: warnings.append("Found {} candidate versions in *{}" .format(len(globbed_paths), info_ext)) pkg_path = None if pkg_path: with open(os.path.join(pkg_path, info_name)) as handle: pkg_info = handle.read() break except IOError: continue if not pkg_info: logger.warn("Software version cannot be determined! ({})".format(', '.join(warnings))) return pkg_info or "Version: 0.0.0\n"
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: # Development setup pkg_path = os.path.join( __file__.split(__name__.replace('.', os.sep))[0], # containing path __name__.split(".")[0] # package name ) if os.path.exists(pkg_path + info_ext): pkg_path += info_ext else: globbed_paths = glob.glob(pkg_path + "-*-py%d.%d" % sys.version_info[:2] + info_ext) if len(globbed_paths) == 1: pkg_path = globbed_paths[0] elif globbed_paths: warnings.append("Found {} release-specific candidate versions in *{}" .format(len(globbed_paths), info_ext)) pkg_path = None else: globbed_paths = glob.glob(pkg_path + "-*" + info_ext) if len(globbed_paths) == 1: pkg_path = globbed_paths[0] else: warnings.append("Found {} candidate versions in *{}" .format(len(globbed_paths), info_ext)) pkg_path = None if pkg_path: with open(os.path.join(pkg_path, info_name)) as handle: pkg_info = handle.read() break except IOError: continue if not pkg_info: logger.warn("Software version cannot be determined! ({})".format(', '.join(warnings))) return pkg_info or "Version: 0.0.0\n"
[ "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'", ",", "'METADATA'", ")", ",", "(", "'.egg-info'", ",", "'PKG-INFO'", ")", ")", ":", "try", ":", "# Development setup", "pkg_path", "=", "os", ".", "path", ".", "join", "(", "__file__", ".", "split", "(", "__name__", ".", "replace", "(", "'.'", ",", "os", ".", "sep", ")", ")", "[", "0", "]", ",", "# containing path", "__name__", ".", "split", "(", "\".\"", ")", "[", "0", "]", "# package name", ")", "if", "os", ".", "path", ".", "exists", "(", "pkg_path", "+", "info_ext", ")", ":", "pkg_path", "+=", "info_ext", "else", ":", "globbed_paths", "=", "glob", ".", "glob", "(", "pkg_path", "+", "\"-*-py%d.%d\"", "%", "sys", ".", "version_info", "[", ":", "2", "]", "+", "info_ext", ")", "if", "len", "(", "globbed_paths", ")", "==", "1", ":", "pkg_path", "=", "globbed_paths", "[", "0", "]", "elif", "globbed_paths", ":", "warnings", ".", "append", "(", "\"Found {} release-specific candidate versions in *{}\"", ".", "format", "(", "len", "(", "globbed_paths", ")", ",", "info_ext", ")", ")", "pkg_path", "=", "None", "else", ":", "globbed_paths", "=", "glob", ".", "glob", "(", "pkg_path", "+", "\"-*\"", "+", "info_ext", ")", "if", "len", "(", "globbed_paths", ")", "==", "1", ":", "pkg_path", "=", "globbed_paths", "[", "0", "]", "else", ":", "warnings", ".", "append", "(", "\"Found {} candidate versions in *{}\"", ".", "format", "(", "len", "(", "globbed_paths", ")", ",", "info_ext", ")", ")", "pkg_path", "=", "None", "if", "pkg_path", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "pkg_path", ",", "info_name", ")", ")", "as", "handle", ":", "pkg_info", "=", "handle", ".", "read", "(", ")", "break", "except", "IOError", ":", "continue", "if", "not", "pkg_info", ":", "logger", ".", "warn", "(", "\"Software version cannot be determined! ({})\"", ".", "format", "(", "', '", ".", "join", "(", "warnings", ")", ")", ")", "return", "pkg_info", "or", "\"Version: 0.0.0\\n\"" ]
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, help=kwargs['help'], *args)
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, help=kwargs['help'], *args)
[ "def", "add_bool_option", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "dest", "=", "[", "o", "for", "o", "in", "args", "if", "o", ".", "startswith", "(", "\"--\"", ")", "]", "[", "0", "]", ".", "replace", "(", "\"--\"", ",", "\"\"", ")", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "self", ".", "parser", ".", "add_option", "(", "dest", "=", "dest", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "kwargs", "[", "'help'", "]", ",", "*", "args", ")" ]
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 this value to the help string. """ kwargs['metavar'] = args[-1] if 'dest' not in kwargs: kwargs['dest'] = [o for o in args if o.startswith("--")][0].replace("--", "").replace("-", "_") if 'default' in kwargs and kwargs['default']: kwargs['help'] += " [%s]" % kwargs['default'] self.parser.add_option(*args[:-1], **kwargs)
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 this value to the help string. """ kwargs['metavar'] = args[-1] if 'dest' not in kwargs: kwargs['dest'] = [o for o in args if o.startswith("--")][0].replace("--", "").replace("-", "_") if 'default' in kwargs and kwargs['default']: kwargs['help'] += " [%s]" % kwargs['default'] self.parser.add_option(*args[:-1], **kwargs)
[ "def", "add_value_option", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'metavar'", "]", "=", "args", "[", "-", "1", "]", "if", "'dest'", "not", "in", "kwargs", ":", "kwargs", "[", "'dest'", "]", "=", "[", "o", "for", "o", "in", "args", "if", "o", ".", "startswith", "(", "\"--\"", ")", "]", "[", "0", "]", ".", "replace", "(", "\"--\"", ",", "\"\"", ")", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "if", "'default'", "in", "kwargs", "and", "kwargs", "[", "'default'", "]", ":", "kwargs", "[", "'help'", "]", "+=", "\" [%s]\"", "%", "kwargs", "[", "'default'", "]", "self", ".", "parser", ".", "add_option", "(", "*", "args", "[", ":", "-", "1", "]", ",", "*", "*", "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 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) if handler: print '\n'.join(sorted(handler())) self.STD_LOG_LEVEL = logging.DEBUG sys.exit(error.EX_OK)
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) if handler: print '\n'.join(sorted(handler())) self.STD_LOG_LEVEL = logging.DEBUG sys.exit(error.EX_OK)
[ "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-\"", ")", ":", "handler", "=", "getattr", "(", "self", ",", "sys", ".", "argv", "[", "1", "]", "[", "2", ":", "]", ".", "replace", "(", "'-'", ",", "'_'", ")", ",", "None", ")", "if", "handler", ":", "print", "'\\n'", ".", "join", "(", "sorted", "(", "handler", "(", ")", ")", ")", "self", ".", "STD_LOG_LEVEL", "=", "logging", ".", "DEBUG", "sys", ".", "exit", "(", "error", ".", "EX_OK", ")" ]
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_SOFTWARE)
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_SOFTWARE)
[ "def", "fatal", "(", "self", ",", "msg", ",", "exc", "=", "None", ")", ":", "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_SOFTWARE", ")" ]
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.LoggableError, exc: if self.options.debug: raise # Log errors caused by invalid user input try: msg = str(exc) except UnicodeError: msg = unicode(exc, "UTF-8") self.LOG.error(msg) sys.exit(error.EX_SOFTWARE) except KeyboardInterrupt, exc: if self.options.debug: raise sys.stderr.write("\n\nAborted by CTRL-C!\n") sys.stderr.flush() sys.exit(error.EX_TEMPFAIL) except IOError, exc: # [Errno 32] Broken pipe? if exc.errno == errno.EPIPE: sys.stderr.write("\n%s, exiting!\n" % exc) sys.stderr.flush() # Monkey patch to prevent an exception during logging shutdown try: handlers = logging._handlerList except AttributeError: pass else: for handler in handlers: try: handler.flush = lambda *_: None except AttributeError: pass # skip special handlers log_total = False sys.exit(error.EX_IOERR) else: raise finally: # Shut down if log_total and self.options: ## No time logging on --version and such running_time = time.time() - self.startup self.LOG.log(self.STD_LOG_LEVEL, "Total time: %.3f seconds." % running_time) logging.shutdown() # Special exit code? if self.return_code: sys.exit(self.return_code)
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.LoggableError, exc: if self.options.debug: raise # Log errors caused by invalid user input try: msg = str(exc) except UnicodeError: msg = unicode(exc, "UTF-8") self.LOG.error(msg) sys.exit(error.EX_SOFTWARE) except KeyboardInterrupt, exc: if self.options.debug: raise sys.stderr.write("\n\nAborted by CTRL-C!\n") sys.stderr.flush() sys.exit(error.EX_TEMPFAIL) except IOError, exc: # [Errno 32] Broken pipe? if exc.errno == errno.EPIPE: sys.stderr.write("\n%s, exiting!\n" % exc) sys.stderr.flush() # Monkey patch to prevent an exception during logging shutdown try: handlers = logging._handlerList except AttributeError: pass else: for handler in handlers: try: handler.flush = lambda *_: None except AttributeError: pass # skip special handlers log_total = False sys.exit(error.EX_IOERR) else: raise finally: # Shut down if log_total and self.options: ## No time logging on --version and such running_time = time.time() - self.startup self.LOG.log(self.STD_LOG_LEVEL, "Total time: %.3f seconds." % running_time) logging.shutdown() # Special exit code? if self.return_code: sys.exit(self.return_code)
[ "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", ".", "LoggableError", ",", "exc", ":", "if", "self", ".", "options", ".", "debug", ":", "raise", "# Log errors caused by invalid user input", "try", ":", "msg", "=", "str", "(", "exc", ")", "except", "UnicodeError", ":", "msg", "=", "unicode", "(", "exc", ",", "\"UTF-8\"", ")", "self", ".", "LOG", ".", "error", "(", "msg", ")", "sys", ".", "exit", "(", "error", ".", "EX_SOFTWARE", ")", "except", "KeyboardInterrupt", ",", "exc", ":", "if", "self", ".", "options", ".", "debug", ":", "raise", "sys", ".", "stderr", ".", "write", "(", "\"\\n\\nAborted by CTRL-C!\\n\"", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "sys", ".", "exit", "(", "error", ".", "EX_TEMPFAIL", ")", "except", "IOError", ",", "exc", ":", "# [Errno 32] Broken pipe?", "if", "exc", ".", "errno", "==", "errno", ".", "EPIPE", ":", "sys", ".", "stderr", ".", "write", "(", "\"\\n%s, exiting!\\n\"", "%", "exc", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "# Monkey patch to prevent an exception during logging shutdown", "try", ":", "handlers", "=", "logging", ".", "_handlerList", "except", "AttributeError", ":", "pass", "else", ":", "for", "handler", "in", "handlers", ":", "try", ":", "handler", ".", "flush", "=", "lambda", "*", "_", ":", "None", "except", "AttributeError", ":", "pass", "# skip special handlers", "log_total", "=", "False", "sys", ".", "exit", "(", "error", ".", "EX_IOERR", ")", "else", ":", "raise", "finally", ":", "# Shut down", "if", "log_total", "and", "self", ".", "options", ":", "## No time logging on --version and such", "running_time", "=", "time", ".", "time", "(", ")", "-", "self", ".", "startup", "self", ".", "LOG", ".", "log", "(", "self", ".", "STD_LOG_LEVEL", ",", "\"Total time: %.3f seconds.\"", "%", "running_time", ")", "logging", ".", "shutdown", "(", ")", "# Special exit code?", "if", "self", ".", "return_code", ":", "sys", ".", "exit", "(", "self", ".", "return_code", ")" ]
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_value_option("--config-file", "PATH", action="append", default=[], help="additional config file(s) to read") self.add_value_option("-D", "--define", "KEY=VAL [-D ...]", default=[], action="append", dest="defines", help="override configuration attributes")
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_value_option("--config-file", "PATH", action="append", default=[], help="additional config file(s) to read") self.add_value_option("-D", "--define", "KEY=VAL [-D ...]", default=[], action="append", dest="defines", help="override configuration attributes")
[ "def", "add_options", "(", "self", ")", ":", "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_value_option", "(", "\"--config-file\"", ",", "\"PATH\"", ",", "action", "=", "\"append\"", ",", "default", "=", "[", "]", ",", "help", "=", "\"additional config file(s) to read\"", ")", "self", ".", "add_value_option", "(", "\"-D\"", ",", "\"--define\"", ",", "\"KEY=VAL [-D ...]\"", ",", "default", "=", "[", "]", ",", "action", "=", "\"append\"", ",", "dest", "=", "\"defines\"", ",", "help", "=", "\"override configuration attributes\"", ")" ]
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:])) config.scgi_url = config.connections[arg[1:]] self.LOG.debug("Switched to connection %s (%s)", arg[1:], config.scgi_url) del self.args[idx] break
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:])) config.scgi_url = config.connections[arg[1:]] self.LOG.debug("Switched to connection %s (%s)", arg[1:], config.scgi_url) del self.args[idx] break
[ "def", "check_for_connection", "(", "self", ")", ":", "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", ":", "]", ")", ")", "config", ".", "scgi_url", "=", "config", ".", "connections", "[", "arg", "[", "1", ":", "]", "]", "self", ".", "LOG", ".", "debug", "(", "\"Switched to connection %s (%s)\"", ",", "arg", "[", "1", ":", "]", ",", "config", ".", "scgi_url", ")", "del", "self", ".", "args", "[", "idx", "]", "break" ]
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=target)
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=target)
[ "def", "redirect", "(", "req", ",", "_log", "=", "pymagic", ".", "get_lazy_logger", "(", "\"redirect\"", ")", ")", ":", "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", "=", "target", ")" ]
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.__file__), "data", "htdocs"), ] return (Router() .add_route("/", controller=redirect, to="/static/index.html") .add_route("/favicon.ico", controller=redirect, to="/static/favicon.ico") .add_route("/static/{filepath:.+}", controller=StaticFolders(htdocs_paths)) .add_route("/json/{action}", controller=JsonController(**httpd_config.json)) )
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.__file__), "data", "htdocs"), ] return (Router() .add_route("/", controller=redirect, to="/static/index.html") .add_route("/favicon.ico", controller=redirect, to="/static/favicon.ico") .add_route("/static/{filepath:.+}", controller=StaticFolders(htdocs_paths)) .add_route("/json/{action}", controller=JsonController(**httpd_config.json)) )
[ "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", ".", "config_dir", ",", "\"htdocs\"", ")", ")", ",", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "config", ".", "__file__", ")", ",", "\"data\"", ",", "\"htdocs\"", ")", ",", "]", "return", "(", "Router", "(", ")", ".", "add_route", "(", "\"/\"", ",", "controller", "=", "redirect", ",", "to", "=", "\"/static/index.html\"", ")", ".", "add_route", "(", "\"/favicon.ico\"", ",", "controller", "=", "redirect", ",", "to", "=", "\"/static/favicon.ico\"", ")", ".", "add_route", "(", "\"/static/{filepath:.+}\"", ",", "controller", "=", "StaticFolders", "(", "htdocs_paths", ")", ")", ".", "add_route", "(", "\"/json/{action}\"", ",", "controller", "=", "JsonController", "(", "*", "*", "httpd_config", ".", "json", ")", ")", ")" ]
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.warn("While calling '%s': %s" % (func.__name__, g_exc)) self.ERRORS_LOGGED.add(func.__name__) return None
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.warn("While calling '%s': %s" % (func.__name__, g_exc)) self.ERRORS_LOGGED.add(func.__name__) return None
[ "def", "guarded", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "(", "EnvironmentError", ",", "error", ".", "LoggableError", ",", "xmlrpc", ".", "ERRORS", ")", "as", "g_exc", ":", "if", "func", ".", "__name__", "not", "in", "self", ".", "ERRORS_LOGGED", ":", "self", ".", "LOG", ".", "warn", "(", "\"While calling '%s': %s\"", "%", "(", "func", ".", "__name__", ",", "g_exc", ")", ")", "self", ".", "ERRORS_LOGGED", ".", "add", "(", "func", ".", "__name__", ")", "return", "None" ]
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", ")", "as", "torrent_exc", ":", "raise", "exc", ".", "HTTPInternalServerError", "(", "str", "(", "torrent_exc", ")", ")" ]
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 disk_usage: disk_used += disk_usage.used disk_total += disk_usage.total disk_detail.append((disk_usage.used, disk_usage.total)) data = dict( engine = self.json_engine(req), uptime = time.time() - psutil.BOOT_TIME, # pylint: disable=no-member fqdn = self.guarded(socket.getfqdn), cpu_usage = self.guarded(psutil.cpu_percent, 0), ram_usage = self.guarded(psutil.virtual_memory), swap_usage = self.guarded(psutil.swap_memory), disk_usage = (disk_used, disk_total, disk_detail) if disk_total else None, disk_io = self.guarded(psutil.disk_io_counters), net_io = self.guarded(psutil.net_io_counters), ) return data
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 disk_usage: disk_used += disk_usage.used disk_total += disk_usage.total disk_detail.append((disk_usage.used, disk_usage.total)) data = dict( engine = self.json_engine(req), uptime = time.time() - psutil.BOOT_TIME, # pylint: disable=no-member fqdn = self.guarded(socket.getfqdn), cpu_usage = self.guarded(psutil.cpu_percent, 0), ram_usage = self.guarded(psutil.virtual_memory), swap_usage = self.guarded(psutil.swap_memory), disk_usage = (disk_used, disk_total, disk_detail) if disk_total else None, disk_io = self.guarded(psutil.disk_io_counters), net_io = self.guarded(psutil.net_io_counters), ) return data
[ "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", ".", "pathsep", ")", ":", "disk_usage", "=", "self", ".", "guarded", "(", "psutil", ".", "disk_usage", ",", "os", ".", "path", ".", "expanduser", "(", "disk_usage_path", ".", "strip", "(", ")", ")", ")", "if", "disk_usage", ":", "disk_used", "+=", "disk_usage", ".", "used", "disk_total", "+=", "disk_usage", ".", "total", "disk_detail", ".", "append", "(", "(", "disk_usage", ".", "used", ",", "disk_usage", ".", "total", ")", ")", "data", "=", "dict", "(", "engine", "=", "self", ".", "json_engine", "(", "req", ")", ",", "uptime", "=", "time", ".", "time", "(", ")", "-", "psutil", ".", "BOOT_TIME", ",", "# pylint: disable=no-member", "fqdn", "=", "self", ".", "guarded", "(", "socket", ".", "getfqdn", ")", ",", "cpu_usage", "=", "self", ".", "guarded", "(", "psutil", ".", "cpu_percent", ",", "0", ")", ",", "ram_usage", "=", "self", ".", "guarded", "(", "psutil", ".", "virtual_memory", ")", ",", "swap_usage", "=", "self", ".", "guarded", "(", "psutil", ".", "swap_memory", ")", ",", "disk_usage", "=", "(", "disk_used", ",", "disk_total", ",", "disk_detail", ")", "if", "disk_total", "else", "None", ",", "disk_io", "=", "self", ".", "guarded", "(", "psutil", ".", "disk_io_counters", ")", ",", "net_io", "=", "self", ".", "guarded", "(", "psutil", ".", "net_io_counters", ")", ",", ")", "return", "data" ]
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.group(1) expr = match.group(2) or '[^/]+' expr = '(?P<%s>%s)' % (var_name, expr) regex += expr last_pos = match.end() regex += re.escape(template[last_pos:]) regex = '^%s$' % regex return re.compile(regex)
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.group(1) expr = match.group(2) or '[^/]+' expr = '(?P<%s>%s)' % (var_name, expr) regex += expr last_pos = match.end() regex += re.escape(template[last_pos:]) regex = '^%s$' % regex return re.compile(regex)
[ "def", "parse_route", "(", "cls", ",", "template", ")", ":", "regex", "=", "''", "last_pos", "=", "0", "for", "match", "in", "cls", ".", "ROUTES_RE", ".", "finditer", "(", "template", ")", ":", "regex", "+=", "re", ".", "escape", "(", "template", "[", "last_pos", ":", "match", ".", "start", "(", ")", "]", ")", "var_name", "=", "match", ".", "group", "(", "1", ")", "expr", "=", "match", ".", "group", "(", "2", ")", "or", "'[^/]+'", "expr", "=", "'(?P<%s>%s)'", "%", "(", "var_name", ",", "expr", ")", "regex", "+=", "expr", "last_pos", "=", "match", ".", "end", "(", ")", "regex", "+=", "re", ".", "escape", "(", "template", "[", "last_pos", ":", "]", ")", "regex", "=", "'^%s$'", "%", "regex", "return", "re", ".", "compile", "(", "regex", ")" ]
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(controller) self.routes.append((self.parse_route(template), controller, kwargs)) return self
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(controller) self.routes.append((self.parse_route(template), controller, kwargs)) return self
[ "def", "add_route", "(", "self", ",", "template", ",", "controller", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "controller", ",", "basestring", ")", ":", "controller", "=", "pymagic", ".", "import_name", "(", "controller", ")", "self", ".", "routes", ".", "append", "(", "(", "self", ".", "parse_route", "(", "template", ")", ",", "controller", ",", "kwargs", ")", ")", "return", "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", "(", ")", "-", "start", "else", ":", "return", "None" ]
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 filelist) for path, name, fileinfo in sorted_files: path = path[:depth] if path != prev_path: common = min([depth] + [idx for idx, (dirname, prev_name) in enumerate(zip(path, prev_path)) if dirname != prev_name ]) #result.append("!!%r %r" % (indent, common)) #result.append("!!%r" % (prev_path,)) #result.append("!!%r" % (path,)) while indent > common: indent -= 1 result.append("%s%s/" % (base_indent, ' ' * indent)) for dirname in path[common:]: if dirname == '\uFFFE': break result.append("%s%s\\ %s" % (base_indent, ' ' * indent, dirname)) indent += 1 ##result.append("!!%r %r" % (path, name)) result.append(" %s %s %s %s| %s" % ( {0: "off ", 1: " ", 2: "high"}.get(fileinfo.prio, "????"), fmt.iso_datetime(fileinfo.mtime), fmt.human_size(fileinfo.size), ' ' * indent, name, )) prev_path = path while indent > 0: indent -= 1 result.append("%s%s/" % (base_indent, ' ' * indent)) result.append("%s= %d file(s)" % (base_indent, len(filelist))) return '\n'.join(result)
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 filelist) for path, name, fileinfo in sorted_files: path = path[:depth] if path != prev_path: common = min([depth] + [idx for idx, (dirname, prev_name) in enumerate(zip(path, prev_path)) if dirname != prev_name ]) #result.append("!!%r %r" % (indent, common)) #result.append("!!%r" % (prev_path,)) #result.append("!!%r" % (path,)) while indent > common: indent -= 1 result.append("%s%s/" % (base_indent, ' ' * indent)) for dirname in path[common:]: if dirname == '\uFFFE': break result.append("%s%s\\ %s" % (base_indent, ' ' * indent, dirname)) indent += 1 ##result.append("!!%r %r" % (path, name)) result.append(" %s %s %s %s| %s" % ( {0: "off ", 1: " ", 2: "high"}.get(fileinfo.prio, "????"), fmt.iso_datetime(fileinfo.mtime), fmt.human_size(fileinfo.size), ' ' * indent, name, )) prev_path = path while indent > 0: indent -= 1 result.append("%s%s/" % (base_indent, ' ' * indent)) result.append("%s= %d file(s)" % (base_indent, len(filelist))) return '\n'.join(result)
[ "def", "_fmt_files", "(", "filelist", ")", ":", "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", "filelist", ")", "for", "path", ",", "name", ",", "fileinfo", "in", "sorted_files", ":", "path", "=", "path", "[", ":", "depth", "]", "if", "path", "!=", "prev_path", ":", "common", "=", "min", "(", "[", "depth", "]", "+", "[", "idx", "for", "idx", ",", "(", "dirname", ",", "prev_name", ")", "in", "enumerate", "(", "zip", "(", "path", ",", "prev_path", ")", ")", "if", "dirname", "!=", "prev_name", "]", ")", "#result.append(\"!!%r %r\" % (indent, common))", "#result.append(\"!!%r\" % (prev_path,))", "#result.append(\"!!%r\" % (path,))", "while", "indent", ">", "common", ":", "indent", "-=", "1", "result", ".", "append", "(", "\"%s%s/\"", "%", "(", "base_indent", ",", "' '", "*", "indent", ")", ")", "for", "dirname", "in", "path", "[", "common", ":", "]", ":", "if", "dirname", "==", "'\\uFFFE'", ":", "break", "result", ".", "append", "(", "\"%s%s\\\\ %s\"", "%", "(", "base_indent", ",", "' '", "*", "indent", ",", "dirname", ")", ")", "indent", "+=", "1", "##result.append(\"!!%r %r\" % (path, name))", "result", ".", "append", "(", "\" %s %s %s %s| %s\"", "%", "(", "{", "0", ":", "\"off \"", ",", "1", ":", "\" \"", ",", "2", ":", "\"high\"", "}", ".", "get", "(", "fileinfo", ".", "prio", ",", "\"????\"", ")", ",", "fmt", ".", "iso_datetime", "(", "fileinfo", ".", "mtime", ")", ",", "fmt", ".", "human_size", "(", "fileinfo", ".", "size", ")", ",", "' '", "*", "indent", ",", "name", ",", ")", ")", "prev_path", "=", "path", "while", "indent", ">", "0", ":", "indent", "-=", "1", "result", ".", "append", "(", "\"%s%s/\"", "%", "(", "base_indent", ",", "' '", "*", "indent", ")", ")", "result", ".", "append", "(", "\"%s= %d file(s)\"", "%", "(", "base_indent", ",", "len", "(", "filelist", ")", ")", ")", "return", "'\\n'", ".", "join", "(", "result", ")" ]
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=(list(item.fetch("kind_51")) or [None]).pop(), )
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=(list(item.fetch("kind_51")) or [None]).pop(), )
[ "def", "detect_traits", "(", "item", ")", ":", "return", "traits", ".", "detect_traits", "(", "name", "=", "item", ".", "name", ",", "alias", "=", "item", ".", "alias", ",", "filetype", "=", "(", "list", "(", "item", ".", "fetch", "(", "\"kind_51\"", ")", ")", "or", "[", "None", "]", ")", ".", "pop", "(", ")", ",", ")" ]
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 KeyError: field = OnDemandField(fmt.to_unicode, name, "custom attribute %r" % name.split('_', 1)[1], matcher=matching.PatternFilter) setattr(cls, name, field) # add field to all proxy objects return field elif name.startswith("kind_") and name[5:].isdigit(): try: return FieldDefinition.FIELDS[name] except KeyError: limit = int(name[5:].lstrip('0') or '0', 10) if limit > 100: raise error.UserError("kind_N: N > 100 in %r" % name) field = OnDemandField(set, name, "kinds of files that make up more than %d%% of this item's size" % limit, matcher=matching.TaggedAsFilter, formatter=_fmt_tags, engine_name="kind_%d" % limit) setattr(cls, name, field) return field
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 KeyError: field = OnDemandField(fmt.to_unicode, name, "custom attribute %r" % name.split('_', 1)[1], matcher=matching.PatternFilter) setattr(cls, name, field) # add field to all proxy objects return field elif name.startswith("kind_") and name[5:].isdigit(): try: return FieldDefinition.FIELDS[name] except KeyError: limit = int(name[5:].lstrip('0') or '0', 10) if limit > 100: raise error.UserError("kind_N: N > 100 in %r" % name) field = OnDemandField(set, name, "kinds of files that make up more than %d%% of this item's size" % limit, matcher=matching.TaggedAsFilter, formatter=_fmt_tags, engine_name="kind_%d" % limit) setattr(cls, name, field) return field
[ "def", "add_manifold_attribute", "(", "cls", ",", "name", ")", ":", "if", "name", ".", "startswith", "(", "\"custom_\"", ")", ":", "try", ":", "return", "FieldDefinition", ".", "FIELDS", "[", "name", "]", "except", "KeyError", ":", "field", "=", "OnDemandField", "(", "fmt", ".", "to_unicode", ",", "name", ",", "\"custom attribute %r\"", "%", "name", ".", "split", "(", "'_'", ",", "1", ")", "[", "1", "]", ",", "matcher", "=", "matching", ".", "PatternFilter", ")", "setattr", "(", "cls", ",", "name", ",", "field", ")", "# add field to all proxy objects", "return", "field", "elif", "name", ".", "startswith", "(", "\"kind_\"", ")", "and", "name", "[", "5", ":", "]", ".", "isdigit", "(", ")", ":", "try", ":", "return", "FieldDefinition", ".", "FIELDS", "[", "name", "]", "except", "KeyError", ":", "limit", "=", "int", "(", "name", "[", "5", ":", "]", ".", "lstrip", "(", "'0'", ")", "or", "'0'", ",", "10", ")", "if", "limit", ">", "100", ":", "raise", "error", ".", "UserError", "(", "\"kind_N: N > 100 in %r\"", "%", "name", ")", "field", "=", "OnDemandField", "(", "set", ",", "name", ",", "\"kinds of files that make up more than %d%% of this item's size\"", "%", "limit", ",", "matcher", "=", "matching", ".", "TaggedAsFilter", ",", "formatter", "=", "_fmt_tags", ",", "engine_name", "=", "\"kind_%d\"", "%", "limit", ")", "setattr", "(", "cls", ",", "name", ",", "field", ")", "return", "field" ]
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", ".", "name", ",", "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) except (TypeError, ValueError): pass else: infohash = self.viewname return infohash
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) except (TypeError, ValueError): pass else: infohash = self.viewname return infohash
[ "def", "_check_hash_view", "(", "self", ")", ":", "infohash", "=", "None", "if", "self", ".", "viewname", ".", "startswith", "(", "'#'", ")", ":", "infohash", "=", "self", ".", "viewname", "[", "1", ":", "]", "elif", "len", "(", "self", ".", "viewname", ")", "==", "40", ":", "try", ":", "int", "(", "self", ".", "viewname", ",", "16", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "else", ":", "infohash", "=", "self", ".", "viewname", "return", "infohash" ]
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", ".", "NOHASH", ",", "self", ".", "viewname", ")" ]
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: key = operator.attrgetter(fields + '') except TypeError: def key(obj, names=tuple(fields)): 'Helper to return group key tuple' return tuple(getattr(obj, x) for x in names) for item in items: result[key(item)].append(item) return result
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: key = operator.attrgetter(fields + '') except TypeError: def key(obj, names=tuple(fields)): 'Helper to return group key tuple' return tuple(getattr(obj, x) for x in names) for item in items: result[key(item)].append(item) return result
[ "def", "group_by", "(", "self", ",", "fields", ",", "items", "=", "None", ")", ":", "result", "=", "defaultdict", "(", "list", ")", "if", "items", "is", "None", ":", "items", "=", "self", ".", "items", "(", ")", "try", ":", "key", "=", "operator", ".", "attrgetter", "(", "fields", "+", "''", ")", "except", "TypeError", ":", "def", "key", "(", "obj", ",", "names", "=", "tuple", "(", "fields", ")", ")", ":", "'Helper to return group key tuple'", "return", "tuple", "(", "getattr", "(", "obj", ",", "x", ")", "for", "x", "in", "names", ")", "for", "item", "in", "items", ":", "result", "[", "key", "(", "item", ")", "]", ".", "append", "(", "item", ")", "return", "result" ]
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_deprecated = self._version_info < (0, 8, 7) # Merge mappings for this version self._mapping = self._mapping.copy() for key, val in sorted(i for i in vars(config).items() if i[0].startswith("xmlrpc_")): map_version = tuple(int(i) for i in key.split('_')[1:]) if map_version <= self._version_info: if config.debug: self.LOG.debug("MAPPING for %r added: %r" % (map_version, val)) self._mapping.update(val) self._fix_mappings() except ERRORS as exc: raise error.LoggableError("Can't connect to %s (%s)" % (self._url, exc)) return self._versions, self._version_info
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_deprecated = self._version_info < (0, 8, 7) # Merge mappings for this version self._mapping = self._mapping.copy() for key, val in sorted(i for i in vars(config).items() if i[0].startswith("xmlrpc_")): map_version = tuple(int(i) for i in key.split('_')[1:]) if map_version <= self._version_info: if config.debug: self.LOG.debug("MAPPING for %r added: %r" % (map_version, val)) self._mapping.update(val) self._fix_mappings() except ERRORS as exc: raise error.LoggableError("Can't connect to %s (%s)" % (self._url, exc)) return self._versions, self._version_info
[ "def", "_set_mappings", "(", "self", ")", ":", "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_deprecated", "=", "self", ".", "_version_info", "<", "(", "0", ",", "8", ",", "7", ")", "# Merge mappings for this version", "self", ".", "_mapping", "=", "self", ".", "_mapping", ".", "copy", "(", ")", "for", "key", ",", "val", "in", "sorted", "(", "i", "for", "i", "in", "vars", "(", "config", ")", ".", "items", "(", ")", "if", "i", "[", "0", "]", ".", "startswith", "(", "\"xmlrpc_\"", ")", ")", ":", "map_version", "=", "tuple", "(", "int", "(", "i", ")", "for", "i", "in", "key", ".", "split", "(", "'_'", ")", "[", "1", ":", "]", ")", "if", "map_version", "<=", "self", ".", "_version_info", ":", "if", "config", ".", "debug", ":", "self", ".", "LOG", ".", "debug", "(", "\"MAPPING for %r added: %r\"", "%", "(", "map_version", ",", "val", ")", ")", "self", ".", "_mapping", ".", "update", "(", "val", ")", "self", ".", "_fix_mappings", "(", ")", "except", "ERRORS", "as", "exc", ":", "raise", "error", ".", "LoggableError", "(", "\"Can't connect to %s (%s)\"", "%", "(", "self", ".", "_url", ",", "exc", ")", ")", "return", "self", ".", "_versions", ",", "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", ".", "endswith", "(", "'='", ")", ")", "if", "config", ".", "debug", ":", "self", ".", "LOG", ".", "debug", "(", "\"CMD MAPPINGS ARE: %r\"", "%", "(", "self", ".", "_mapping", ",", ")", ")" ]
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 config if not self._use_deprecated and any(cmd.startswith(i) for i in ("d.get_", "f.get_", "p.get_", "t.get_")): cmd = cmd[:2] + cmd[6:] return cmd
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 config if not self._use_deprecated and any(cmd.startswith(i) for i in ("d.get_", "f.get_", "p.get_", "t.get_")): cmd = cmd[:2] + cmd[6:] return cmd
[ "def", "_map_call", "(", "self", ",", "cmd", ")", ":", "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 config", "if", "not", "self", ".", "_use_deprecated", "and", "any", "(", "cmd", ".", "startswith", "(", "i", ")", "for", "i", "in", "(", "\"d.get_\"", ",", "\"f.get_\"", ",", "\"p.get_\"", ",", "\"t.get_\"", ")", ")", ":", "cmd", "=", "cmd", "[", ":", "2", "]", "+", "cmd", "[", "6", ":", "]", "return", "cmd" ]
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,)) return self.metadata = metafile.checked_open(self.ns.pathname) except EnvironmentError as exc: self.job.LOG.error("Can't read metafile '%s' (%s)" % ( self.ns.pathname, str(exc).replace(": '%s'" % self.ns.pathname, ""), )) return except ValueError as exc: self.job.LOG.error("Invalid metafile '%s': %s" % (self.ns.pathname, exc)) return self.ns.info_hash = metafile.info_hash(self.metadata) self.ns.info_name = self.metadata["info"]["name"] self.job.LOG.info("Loaded '%s' from metafile '%s'" % (self.ns.info_name, self.ns.pathname)) # Check whether item is already loaded try: name = self.job.proxy.d.name(self.ns.info_hash, fail_silently=True) except xmlrpc.HashNotFound: pass except xmlrpc.ERRORS as exc: if exc.faultString != "Could not find info-hash.": self.job.LOG.error("While checking for #%s: %s" % (self.ns.info_hash, exc)) return else: self.job.LOG.warn("Item #%s '%s' already added to client" % (self.ns.info_hash, name)) return return True
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,)) return self.metadata = metafile.checked_open(self.ns.pathname) except EnvironmentError as exc: self.job.LOG.error("Can't read metafile '%s' (%s)" % ( self.ns.pathname, str(exc).replace(": '%s'" % self.ns.pathname, ""), )) return except ValueError as exc: self.job.LOG.error("Invalid metafile '%s': %s" % (self.ns.pathname, exc)) return self.ns.info_hash = metafile.info_hash(self.metadata) self.ns.info_name = self.metadata["info"]["name"] self.job.LOG.info("Loaded '%s' from metafile '%s'" % (self.ns.info_name, self.ns.pathname)) # Check whether item is already loaded try: name = self.job.proxy.d.name(self.ns.info_hash, fail_silently=True) except xmlrpc.HashNotFound: pass except xmlrpc.ERRORS as exc: if exc.faultString != "Could not find info-hash.": self.job.LOG.error("While checking for #%s: %s" % (self.ns.info_hash, exc)) return else: self.job.LOG.warn("Item #%s '%s' already added to client" % (self.ns.info_hash, name)) return return True
[ "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", ".", "warn", "(", "\"Ignoring 0-byte metafile '%s'\"", "%", "(", "self", ".", "ns", ".", "pathname", ",", ")", ")", "return", "self", ".", "metadata", "=", "metafile", ".", "checked_open", "(", "self", ".", "ns", ".", "pathname", ")", "except", "EnvironmentError", "as", "exc", ":", "self", ".", "job", ".", "LOG", ".", "error", "(", "\"Can't read metafile '%s' (%s)\"", "%", "(", "self", ".", "ns", ".", "pathname", ",", "str", "(", "exc", ")", ".", "replace", "(", "\": '%s'\"", "%", "self", ".", "ns", ".", "pathname", ",", "\"\"", ")", ",", ")", ")", "return", "except", "ValueError", "as", "exc", ":", "self", ".", "job", ".", "LOG", ".", "error", "(", "\"Invalid metafile '%s': %s\"", "%", "(", "self", ".", "ns", ".", "pathname", ",", "exc", ")", ")", "return", "self", ".", "ns", ".", "info_hash", "=", "metafile", ".", "info_hash", "(", "self", ".", "metadata", ")", "self", ".", "ns", ".", "info_name", "=", "self", ".", "metadata", "[", "\"info\"", "]", "[", "\"name\"", "]", "self", ".", "job", ".", "LOG", ".", "info", "(", "\"Loaded '%s' from metafile '%s'\"", "%", "(", "self", ".", "ns", ".", "info_name", ",", "self", ".", "ns", ".", "pathname", ")", ")", "# Check whether item is already loaded", "try", ":", "name", "=", "self", ".", "job", ".", "proxy", ".", "d", ".", "name", "(", "self", ".", "ns", ".", "info_hash", ",", "fail_silently", "=", "True", ")", "except", "xmlrpc", ".", "HashNotFound", ":", "pass", "except", "xmlrpc", ".", "ERRORS", "as", "exc", ":", "if", "exc", ".", "faultString", "!=", "\"Could not find info-hash.\"", ":", "self", ".", "job", ".", "LOG", ".", "error", "(", "\"While checking for #%s: %s\"", "%", "(", "self", ".", "ns", ".", "info_hash", ",", "exc", ")", ")", "return", "else", ":", "self", ".", "job", ".", "LOG", ".", "warn", "(", "\"Item #%s '%s' already added to client\"", "%", "(", "self", ".", "ns", ".", "info_hash", ",", "name", ")", ")", "return", "return", "True" ]
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.ns.relpath = os.path.dirname(self.ns.pathname)[len(watch.rstrip('/'))+1:] break # Build indicator flags for target state from filename flags = self.ns.pathname.split(os.sep) flags.extend(flags[-1].split('.')) self.ns.flags = set(i for i in flags if i) # Metafile stuff announce = self.metadata.get("announce", None) if announce: self.ns.tracker_alias = configuration.map_announce2alias(announce) main_file = self.ns.info_name if "files" in self.metadata["info"]: main_file = list(sorted((i["length"], i["path"][-1]) for i in self.metadata["info"]["files"]))[-1][1] self.ns.filetype = os.path.splitext(main_file)[1] # Add name traits kind, info = traits.name_trait(self.ns.info_name, add_info=True) self.ns.traits = Bunch(info) self.ns.traits.kind = kind self.ns.label = '/'.join(traits.detect_traits( name=self.ns.info_name, alias=self.ns.tracker_alias, filetype=self.ns.filetype)).strip('/') # Finally, expand commands from templates self.ns.commands = [] for key, cmd in sorted(self.job.custom_cmds.items()): try: self.ns.commands.append(formatting.expand_template(cmd, self.ns)) except error.LoggableError as exc: self.job.LOG.error("While expanding '%s' custom command: %s" % (key, exc))
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.ns.relpath = os.path.dirname(self.ns.pathname)[len(watch.rstrip('/'))+1:] break # Build indicator flags for target state from filename flags = self.ns.pathname.split(os.sep) flags.extend(flags[-1].split('.')) self.ns.flags = set(i for i in flags if i) # Metafile stuff announce = self.metadata.get("announce", None) if announce: self.ns.tracker_alias = configuration.map_announce2alias(announce) main_file = self.ns.info_name if "files" in self.metadata["info"]: main_file = list(sorted((i["length"], i["path"][-1]) for i in self.metadata["info"]["files"]))[-1][1] self.ns.filetype = os.path.splitext(main_file)[1] # Add name traits kind, info = traits.name_trait(self.ns.info_name, add_info=True) self.ns.traits = Bunch(info) self.ns.traits.kind = kind self.ns.label = '/'.join(traits.detect_traits( name=self.ns.info_name, alias=self.ns.tracker_alias, filetype=self.ns.filetype)).strip('/') # Finally, expand commands from templates self.ns.commands = [] for key, cmd in sorted(self.job.custom_cmds.items()): try: self.ns.commands.append(formatting.expand_template(cmd, self.ns)) except error.LoggableError as exc: self.job.LOG.error("While expanding '%s' custom command: %s" % (key, exc))
[ "def", "addinfo", "(", "self", ")", ":", "# 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", ".", "ns", ".", "relpath", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "ns", ".", "pathname", ")", "[", "len", "(", "watch", ".", "rstrip", "(", "'/'", ")", ")", "+", "1", ":", "]", "break", "# Build indicator flags for target state from filename", "flags", "=", "self", ".", "ns", ".", "pathname", ".", "split", "(", "os", ".", "sep", ")", "flags", ".", "extend", "(", "flags", "[", "-", "1", "]", ".", "split", "(", "'.'", ")", ")", "self", ".", "ns", ".", "flags", "=", "set", "(", "i", "for", "i", "in", "flags", "if", "i", ")", "# Metafile stuff", "announce", "=", "self", ".", "metadata", ".", "get", "(", "\"announce\"", ",", "None", ")", "if", "announce", ":", "self", ".", "ns", ".", "tracker_alias", "=", "configuration", ".", "map_announce2alias", "(", "announce", ")", "main_file", "=", "self", ".", "ns", ".", "info_name", "if", "\"files\"", "in", "self", ".", "metadata", "[", "\"info\"", "]", ":", "main_file", "=", "list", "(", "sorted", "(", "(", "i", "[", "\"length\"", "]", ",", "i", "[", "\"path\"", "]", "[", "-", "1", "]", ")", "for", "i", "in", "self", ".", "metadata", "[", "\"info\"", "]", "[", "\"files\"", "]", ")", ")", "[", "-", "1", "]", "[", "1", "]", "self", ".", "ns", ".", "filetype", "=", "os", ".", "path", ".", "splitext", "(", "main_file", ")", "[", "1", "]", "# Add name traits", "kind", ",", "info", "=", "traits", ".", "name_trait", "(", "self", ".", "ns", ".", "info_name", ",", "add_info", "=", "True", ")", "self", ".", "ns", ".", "traits", "=", "Bunch", "(", "info", ")", "self", ".", "ns", ".", "traits", ".", "kind", "=", "kind", "self", ".", "ns", ".", "label", "=", "'/'", ".", "join", "(", "traits", ".", "detect_traits", "(", "name", "=", "self", ".", "ns", ".", "info_name", ",", "alias", "=", "self", ".", "ns", ".", "tracker_alias", ",", "filetype", "=", "self", ".", "ns", ".", "filetype", ")", ")", ".", "strip", "(", "'/'", ")", "# Finally, expand commands from templates", "self", ".", "ns", ".", "commands", "=", "[", "]", "for", "key", ",", "cmd", "in", "sorted", "(", "self", ".", "job", ".", "custom_cmds", ".", "items", "(", ")", ")", ":", "try", ":", "self", ".", "ns", ".", "commands", ".", "append", "(", "formatting", ".", "expand_template", "(", "cmd", ",", "self", ".", "ns", ")", ")", "except", "error", ".", "LoggableError", "as", "exc", ":", "self", ".", "job", ".", "LOG", ".", "error", "(", "\"While expanding '%s' custom command: %s\"", "%", "(", "key", ",", "exc", ")", ")" ]
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.config.load_mode.lower() in ("start", "started") queue_it = self.job.config.queued if "start" in self.ns.flags: start_it = True elif "load" in self.ns.flags: start_it = False if "queue" in self.ns.flags: queue_it = True # Load metafile into client load_cmd = self.job.proxy.load.verbose if queue_it: if not start_it: self.ns.commands.append("d.priority.set=0") elif start_it: load_cmd = self.job.proxy.load.start_verbose self.job.LOG.debug("Templating values are:\n %s" % "\n ".join("%s=%s" % (key, repr(val)) for key, val in sorted(self.ns.items()) )) load_cmd(xmlrpc.NOHASH, self.ns.pathname, *tuple(self.ns.commands)) time.sleep(.05) # let things settle # Announce new item if not self.job.config.quiet: msg = "%s: Loaded '%s' from '%s/'%s%s" % ( self.job.__class__.__name__, fmt.to_utf8(self.job.proxy.d.name(self.ns.info_hash, fail_silently=True)), os.path.dirname(self.ns.pathname).rstrip(os.sep), " [queued]" if queue_it else "", (" [startable]" if queue_it else " [started]") if start_it else " [normal]", ) self.job.proxy.log(xmlrpc.NOHASH, msg) # TODO: Evaluate fields and set client values # TODO: Add metadata to tied file if requested # TODO: Execute commands AFTER adding the item, with full templating # Example: Labeling - add items to a persistent view, i.e. "postcmd = view.set_visible={{label}}" # could also be done automatically from the path, see above under "flags" (autolabel = True) # and add traits to the flags, too, in that case except xmlrpc.ERRORS as exc: self.job.LOG.error("While loading #%s: %s" % (self.ns.info_hash, exc))
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.config.load_mode.lower() in ("start", "started") queue_it = self.job.config.queued if "start" in self.ns.flags: start_it = True elif "load" in self.ns.flags: start_it = False if "queue" in self.ns.flags: queue_it = True # Load metafile into client load_cmd = self.job.proxy.load.verbose if queue_it: if not start_it: self.ns.commands.append("d.priority.set=0") elif start_it: load_cmd = self.job.proxy.load.start_verbose self.job.LOG.debug("Templating values are:\n %s" % "\n ".join("%s=%s" % (key, repr(val)) for key, val in sorted(self.ns.items()) )) load_cmd(xmlrpc.NOHASH, self.ns.pathname, *tuple(self.ns.commands)) time.sleep(.05) # let things settle # Announce new item if not self.job.config.quiet: msg = "%s: Loaded '%s' from '%s/'%s%s" % ( self.job.__class__.__name__, fmt.to_utf8(self.job.proxy.d.name(self.ns.info_hash, fail_silently=True)), os.path.dirname(self.ns.pathname).rstrip(os.sep), " [queued]" if queue_it else "", (" [startable]" if queue_it else " [started]") if start_it else " [normal]", ) self.job.proxy.log(xmlrpc.NOHASH, msg) # TODO: Evaluate fields and set client values # TODO: Add metadata to tied file if requested # TODO: Execute commands AFTER adding the item, with full templating # Example: Labeling - add items to a persistent view, i.e. "postcmd = view.set_visible={{label}}" # could also be done automatically from the path, see above under "flags" (autolabel = True) # and add traits to the flags, too, in that case except xmlrpc.ERRORS as exc: self.job.LOG.error("While loading #%s: %s" % (self.ns.info_hash, exc))
[ "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", "# Determine target state", "start_it", "=", "self", ".", "job", ".", "config", ".", "load_mode", ".", "lower", "(", ")", "in", "(", "\"start\"", ",", "\"started\"", ")", "queue_it", "=", "self", ".", "job", ".", "config", ".", "queued", "if", "\"start\"", "in", "self", ".", "ns", ".", "flags", ":", "start_it", "=", "True", "elif", "\"load\"", "in", "self", ".", "ns", ".", "flags", ":", "start_it", "=", "False", "if", "\"queue\"", "in", "self", ".", "ns", ".", "flags", ":", "queue_it", "=", "True", "# Load metafile into client", "load_cmd", "=", "self", ".", "job", ".", "proxy", ".", "load", ".", "verbose", "if", "queue_it", ":", "if", "not", "start_it", ":", "self", ".", "ns", ".", "commands", ".", "append", "(", "\"d.priority.set=0\"", ")", "elif", "start_it", ":", "load_cmd", "=", "self", ".", "job", ".", "proxy", ".", "load", ".", "start_verbose", "self", ".", "job", ".", "LOG", ".", "debug", "(", "\"Templating values are:\\n %s\"", "%", "\"\\n \"", ".", "join", "(", "\"%s=%s\"", "%", "(", "key", ",", "repr", "(", "val", ")", ")", "for", "key", ",", "val", "in", "sorted", "(", "self", ".", "ns", ".", "items", "(", ")", ")", ")", ")", "load_cmd", "(", "xmlrpc", ".", "NOHASH", ",", "self", ".", "ns", ".", "pathname", ",", "*", "tuple", "(", "self", ".", "ns", ".", "commands", ")", ")", "time", ".", "sleep", "(", ".05", ")", "# let things settle", "# Announce new item", "if", "not", "self", ".", "job", ".", "config", ".", "quiet", ":", "msg", "=", "\"%s: Loaded '%s' from '%s/'%s%s\"", "%", "(", "self", ".", "job", ".", "__class__", ".", "__name__", ",", "fmt", ".", "to_utf8", "(", "self", ".", "job", ".", "proxy", ".", "d", ".", "name", "(", "self", ".", "ns", ".", "info_hash", ",", "fail_silently", "=", "True", ")", ")", ",", "os", ".", "path", ".", "dirname", "(", "self", ".", "ns", ".", "pathname", ")", ".", "rstrip", "(", "os", ".", "sep", ")", ",", "\" [queued]\"", "if", "queue_it", "else", "\"\"", ",", "(", "\" [startable]\"", "if", "queue_it", "else", "\" [started]\"", ")", "if", "start_it", "else", "\" [normal]\"", ",", ")", "self", ".", "job", ".", "proxy", ".", "log", "(", "xmlrpc", ".", "NOHASH", ",", "msg", ")", "# TODO: Evaluate fields and set client values", "# TODO: Add metadata to tied file if requested", "# TODO: Execute commands AFTER adding the item, with full templating", "# Example: Labeling - add items to a persistent view, i.e. \"postcmd = view.set_visible={{label}}\"", "# could also be done automatically from the path, see above under \"flags\" (autolabel = True)", "# and add traits to the flags, too, in that case", "except", "xmlrpc", ".", "ERRORS", "as", "exc", ":", "self", ".", "job", ".", "LOG", ".", "error", "(", "\"While loading #%s: %s\"", "%", "(", "self", ".", "ns", ".", "info_hash", ",", "exc", ")", ")" ]
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() elif os.path.basename(event.pathname) == "watch.ini": self.job.LOG.info("NOT YET Reloading watch config for '%s'" % event.path)
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() elif os.path.basename(event.pathname) == "watch.ini": self.job.LOG.info("NOT YET Reloading watch config for '%s'" % event.path)
[ "def", "handle_path", "(", "self", ",", "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", "(", ")", "elif", "os", ".", "path", ".", "basename", "(", "event", ".", "pathname", ")", "==", "\"watch.ini\"", ":", "self", ".", "job", ".", "LOG", ".", "info", "(", "\"NOT YET Reloading watch config for '%s'\"", "%", "event", ".", "path", ")" ]
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)) # pylint: disable=E1101, W0212 self.manager = pyinotify.WatchManager() self.handler = TreeWatchHandler(job=self) self.notifier = pyinotify.AsyncNotifier(self.manager, self.handler) if self.LOG.isEnabledFor(logging.DEBUG): mask = pyinotify.ALL_EVENTS else: mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO # bogus pylint: disable=E1101 # Add all configured base dirs for path in self.config.path: self.manager.add_watch(path.strip(), mask, rec=True, auto_add=True)
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)) # pylint: disable=E1101, W0212 self.manager = pyinotify.WatchManager() self.handler = TreeWatchHandler(job=self) self.notifier = pyinotify.AsyncNotifier(self.manager, self.handler) if self.LOG.isEnabledFor(logging.DEBUG): mask = pyinotify.ALL_EVENTS else: mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO # bogus pylint: disable=E1101 # Add all configured base dirs for path in self.config.path: self.manager.add_watch(path.strip(), mask, rec=True, auto_add=True)
[ "def", "setup", "(", "self", ")", ":", "if", "not", "pyinotify", ".", "WatchManager", ":", "raise", "error", ".", "UserError", "(", "\"You need to install 'pyinotify' to use %s (%s)!\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "pyinotify", ".", "_import_error", ")", ")", "# pylint: disable=E1101, W0212", "self", ".", "manager", "=", "pyinotify", ".", "WatchManager", "(", ")", "self", ".", "handler", "=", "TreeWatchHandler", "(", "job", "=", "self", ")", "self", ".", "notifier", "=", "pyinotify", ".", "AsyncNotifier", "(", "self", ".", "manager", ",", "self", ".", "handler", ")", "if", "self", ".", "LOG", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "mask", "=", "pyinotify", ".", "ALL_EVENTS", "else", ":", "mask", "=", "pyinotify", ".", "IN_CLOSE_WRITE", "|", "pyinotify", ".", "IN_MOVED_TO", "# bogus pylint: disable=E1101", "# Add all configured base dirs", "for", "path", "in", "self", ".", "config", ".", "path", ":", "self", ".", "manager", ".", "add_watch", "(", "path", ".", "strip", "(", ")", ",", "mask", ",", "rec", "=", "True", ",", "auto_add", "=", "True", ")" ]
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 = path or (lambda _: _) # Get total size for each file extension histo = defaultdict(int) for entry in filelist: ext = os.path.splitext(path(entry))[1].lstrip('.').lower() if ext and ext[0] == 'r' and ext[1:].isdigit(): ext = "rar" elif ext == "jpeg": ext = "jpg" elif ext == "mpeg": ext = "mpg" histo[ext] += size(entry) # Normalize values to integer percent total = sum(histo.values()) if total: for ext, val in histo.items(): histo[ext] = int(val * 100.0 / total + .499) return sorted(zip(histo.values(), histo.keys()), reverse=True)
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 = path or (lambda _: _) # Get total size for each file extension histo = defaultdict(int) for entry in filelist: ext = os.path.splitext(path(entry))[1].lstrip('.').lower() if ext and ext[0] == 'r' and ext[1:].isdigit(): ext = "rar" elif ext == "jpeg": ext = "jpg" elif ext == "mpeg": ext = "mpg" histo[ext] += size(entry) # Normalize values to integer percent total = sum(histo.values()) if total: for ext, val in histo.items(): histo[ext] = int(val * 100.0 / total + .499) return sorted(zip(histo.values(), histo.keys()), reverse=True)
[ "def", "get_filetypes", "(", "filelist", ",", "path", "=", "None", ",", "size", "=", "os", ".", "path", ".", "getsize", ")", ":", "path", "=", "path", "or", "(", "lambda", "_", ":", "_", ")", "# Get total size for each file extension", "histo", "=", "defaultdict", "(", "int", ")", "for", "entry", "in", "filelist", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", "(", "entry", ")", ")", "[", "1", "]", ".", "lstrip", "(", "'.'", ")", ".", "lower", "(", ")", "if", "ext", "and", "ext", "[", "0", "]", "==", "'r'", "and", "ext", "[", "1", ":", "]", ".", "isdigit", "(", ")", ":", "ext", "=", "\"rar\"", "elif", "ext", "==", "\"jpeg\"", ":", "ext", "=", "\"jpg\"", "elif", "ext", "==", "\"mpeg\"", ":", "ext", "=", "\"mpg\"", "histo", "[", "ext", "]", "+=", "size", "(", "entry", ")", "# Normalize values to integer percent", "total", "=", "sum", "(", "histo", ".", "values", "(", ")", ")", "if", "total", ":", "for", "ext", ",", "val", "in", "histo", ".", "items", "(", ")", ":", "histo", "[", "ext", "]", "=", "int", "(", "val", "*", "100.0", "/", "total", "+", ".499", ")", "return", "sorted", "(", "zip", "(", "histo", ".", "values", "(", ")", ",", "histo", ".", "keys", "(", ")", ")", ",", "reverse", "=", "True", ")" ]
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")) # TV check if any(i in lower_name for i in _DEFINITELY_TV): kind = "tv" trait_patterns = trait_patterns[:1] # Regex checks re_name = '.'.join([i.lstrip('[(').rstrip(')]') for i in name.split(' .')]) for trait, patterns, title_group in trait_patterns: matched, patname = None, None for patname, pattern in patterns: matched = pattern.match(re_name) ##print matched, patname, re_name; print " ", pattern.pattern if matched and not any(i in matched.groupdict()[title_group].lower() for i in BAD_TITLE_WORDS): kind, info = trait, matched.groupdict() break if matched: info["pattern"] = patname # Fold auxiliary groups into main one for key, val in list(info.items()): if key[-1].isdigit(): del info[key] if val: key = re.sub("[0-9]+$", "", key) info[key] = ("%s %s" % (info.get(key) or "", val)).strip() break # TODO: Split by "dvdrip", year, etc. to get to the title and then # do a imdb / tvdb lookup; cache results, hits for longer, misses # for a day at max. # Return requested result return (kind, info) if add_info else kind
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")) # TV check if any(i in lower_name for i in _DEFINITELY_TV): kind = "tv" trait_patterns = trait_patterns[:1] # Regex checks re_name = '.'.join([i.lstrip('[(').rstrip(')]') for i in name.split(' .')]) for trait, patterns, title_group in trait_patterns: matched, patname = None, None for patname, pattern in patterns: matched = pattern.match(re_name) ##print matched, patname, re_name; print " ", pattern.pattern if matched and not any(i in matched.groupdict()[title_group].lower() for i in BAD_TITLE_WORDS): kind, info = trait, matched.groupdict() break if matched: info["pattern"] = patname # Fold auxiliary groups into main one for key, val in list(info.items()): if key[-1].isdigit(): del info[key] if val: key = re.sub("[0-9]+$", "", key) info[key] = ("%s %s" % (info.get(key) or "", val)).strip() break # TODO: Split by "dvdrip", year, etc. to get to the title and then # do a imdb / tvdb lookup; cache results, hits for longer, misses # for a day at max. # Return requested result return (kind, info) if add_info else kind
[ "def", "name_trait", "(", "name", ",", "add_info", "=", "False", ")", ":", "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\"", ")", ")", "# TV check", "if", "any", "(", "i", "in", "lower_name", "for", "i", "in", "_DEFINITELY_TV", ")", ":", "kind", "=", "\"tv\"", "trait_patterns", "=", "trait_patterns", "[", ":", "1", "]", "# Regex checks", "re_name", "=", "'.'", ".", "join", "(", "[", "i", ".", "lstrip", "(", "'[('", ")", ".", "rstrip", "(", "')]'", ")", "for", "i", "in", "name", ".", "split", "(", "' .'", ")", "]", ")", "for", "trait", ",", "patterns", ",", "title_group", "in", "trait_patterns", ":", "matched", ",", "patname", "=", "None", ",", "None", "for", "patname", ",", "pattern", "in", "patterns", ":", "matched", "=", "pattern", ".", "match", "(", "re_name", ")", "##print matched, patname, re_name; print \" \", pattern.pattern", "if", "matched", "and", "not", "any", "(", "i", "in", "matched", ".", "groupdict", "(", ")", "[", "title_group", "]", ".", "lower", "(", ")", "for", "i", "in", "BAD_TITLE_WORDS", ")", ":", "kind", ",", "info", "=", "trait", ",", "matched", ".", "groupdict", "(", ")", "break", "if", "matched", ":", "info", "[", "\"pattern\"", "]", "=", "patname", "# Fold auxiliary groups into main one", "for", "key", ",", "val", "in", "list", "(", "info", ".", "items", "(", ")", ")", ":", "if", "key", "[", "-", "1", "]", ".", "isdigit", "(", ")", ":", "del", "info", "[", "key", "]", "if", "val", ":", "key", "=", "re", ".", "sub", "(", "\"[0-9]+$\"", ",", "\"\"", ",", "key", ")", "info", "[", "key", "]", "=", "(", "\"%s %s\"", "%", "(", "info", ".", "get", "(", "key", ")", "or", "\"\"", ",", "val", ")", ")", ".", "strip", "(", ")", "break", "# TODO: Split by \"dvdrip\", year, etc. to get to the title and then", "# do a imdb / tvdb lookup; cache results, hits for longer, misses", "# for a day at max.", "# Return requested result", "return", "(", "kind", ",", "info", ")", "if", "add_info", "else", "kind" ]
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 directory structures. """ result = [] if filetype: filetype = filetype.lstrip('.') # Check for "themed" trackers theme = config.traits_by_alias.get(alias) if alias and theme: result = [theme, filetype or "other"] # Guess from file extensionn and name elif filetype in KIND_AUDIO: result = ["audio", filetype] elif filetype in KIND_VIDEO: result = ["video", filetype] contents = name_trait(name) if contents: result = [contents, filetype] elif filetype in KIND_IMAGE: result = ["img", filetype] elif filetype in KIND_DOCS: result = ["docs", filetype] elif filetype in KIND_ARCHIVE: result = ["misc", filetype] contents = name_trait(name) if contents: result = [contents, filetype] return result
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 directory structures. """ result = [] if filetype: filetype = filetype.lstrip('.') # Check for "themed" trackers theme = config.traits_by_alias.get(alias) if alias and theme: result = [theme, filetype or "other"] # Guess from file extensionn and name elif filetype in KIND_AUDIO: result = ["audio", filetype] elif filetype in KIND_VIDEO: result = ["video", filetype] contents = name_trait(name) if contents: result = [contents, filetype] elif filetype in KIND_IMAGE: result = ["img", filetype] elif filetype in KIND_DOCS: result = ["docs", filetype] elif filetype in KIND_ARCHIVE: result = ["misc", filetype] contents = name_trait(name) if contents: result = [contents, filetype] return result
[ "def", "detect_traits", "(", "name", "=", "None", ",", "alias", "=", "None", ",", "filetype", "=", "None", ")", ":", "result", "=", "[", "]", "if", "filetype", ":", "filetype", "=", "filetype", ".", "lstrip", "(", "'.'", ")", "# Check for \"themed\" trackers", "theme", "=", "config", ".", "traits_by_alias", ".", "get", "(", "alias", ")", "if", "alias", "and", "theme", ":", "result", "=", "[", "theme", ",", "filetype", "or", "\"other\"", "]", "# Guess from file extensionn and name", "elif", "filetype", "in", "KIND_AUDIO", ":", "result", "=", "[", "\"audio\"", ",", "filetype", "]", "elif", "filetype", "in", "KIND_VIDEO", ":", "result", "=", "[", "\"video\"", ",", "filetype", "]", "contents", "=", "name_trait", "(", "name", ")", "if", "contents", ":", "result", "=", "[", "contents", ",", "filetype", "]", "elif", "filetype", "in", "KIND_IMAGE", ":", "result", "=", "[", "\"img\"", ",", "filetype", "]", "elif", "filetype", "in", "KIND_DOCS", ":", "result", "=", "[", "\"docs\"", ",", "filetype", "]", "elif", "filetype", "in", "KIND_ARCHIVE", ":", "result", "=", "[", "\"misc\"", ",", "filetype", "]", "contents", "=", "name_trait", "(", "name", ")", "if", "contents", ":", "result", "=", "[", "contents", ",", "filetype", "]", "return", "result" ]
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.write(msg + " \r") sys.stdout.flush() try: return progress if sys.stdout.isatty() else None except AttributeError: return None
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.write(msg + " \r") sys.stdout.flush() try: return progress if sys.stdout.isatty() else None except AttributeError: return None
[ "def", "console_progress", "(", ")", ":", "def", "progress", "(", "totalhashed", ",", "totalsize", ")", ":", "\"Helper\"", "msg", "=", "\" \"", "*", "30", "if", "totalhashed", "<", "totalsize", ":", "msg", "=", "\"%5.1f%% complete\"", "%", "(", "totalhashed", "*", "100.0", "/", "totalsize", ")", "sys", ".", "stdout", ".", "write", "(", "msg", "+", "\" \\r\"", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "try", ":", "return", "progress", "if", "sys", ".", "stdout", ".", "isatty", "(", ")", "else", "None", "except", "AttributeError", ":", "return", "None" ]
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 ValueError("bad metainfo - bad pieces key") piece_size = info.get("piece length") if not isinstance(piece_size, (int, long)) or piece_size <= 0: raise ValueError("bad metainfo - illegal piece length") name = info.get("name") if not isinstance(name, basestring): raise ValueError("bad metainfo - bad name (type is %r)" % type(name).__name__) if not ALLOWED_ROOT_NAME.match(name): raise ValueError("name %s disallowed for security reasons" % name) if ("files" in info) == ("length" in info): raise ValueError("single/multiple file mix") if "length" in info: length = info.get("length") if not isinstance(length, (int, long)) or length < 0: raise ValueError("bad metainfo - bad length") else: files = info.get("files") if not isinstance(files, (list, tuple)): raise ValueError("bad metainfo - bad file list") for item in files: if not isinstance(item, dict): raise ValueError("bad metainfo - bad file value") length = item.get("length") if not isinstance(length, (int, long)) or length < 0: raise ValueError("bad metainfo - bad length") path = item.get("path") if not isinstance(path, (list, tuple)) or not path: raise ValueError("bad metainfo - bad path") for part in path: if not isinstance(part, basestring): raise ValueError("bad metainfo - bad path dir") part = fmt.to_unicode(part) if part == '..': raise ValueError("relative path in %s disallowed for security reasons" % '/'.join(path)) if part and not ALLOWED_PATH_NAME.match(part): raise ValueError("path %s disallowed for security reasons" % part) file_paths = [os.sep.join(item["path"]) for item in files] if len(set(file_paths)) != len(file_paths): raise ValueError("bad metainfo - duplicate path") return info
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 ValueError("bad metainfo - bad pieces key") piece_size = info.get("piece length") if not isinstance(piece_size, (int, long)) or piece_size <= 0: raise ValueError("bad metainfo - illegal piece length") name = info.get("name") if not isinstance(name, basestring): raise ValueError("bad metainfo - bad name (type is %r)" % type(name).__name__) if not ALLOWED_ROOT_NAME.match(name): raise ValueError("name %s disallowed for security reasons" % name) if ("files" in info) == ("length" in info): raise ValueError("single/multiple file mix") if "length" in info: length = info.get("length") if not isinstance(length, (int, long)) or length < 0: raise ValueError("bad metainfo - bad length") else: files = info.get("files") if not isinstance(files, (list, tuple)): raise ValueError("bad metainfo - bad file list") for item in files: if not isinstance(item, dict): raise ValueError("bad metainfo - bad file value") length = item.get("length") if not isinstance(length, (int, long)) or length < 0: raise ValueError("bad metainfo - bad length") path = item.get("path") if not isinstance(path, (list, tuple)) or not path: raise ValueError("bad metainfo - bad path") for part in path: if not isinstance(part, basestring): raise ValueError("bad metainfo - bad path dir") part = fmt.to_unicode(part) if part == '..': raise ValueError("relative path in %s disallowed for security reasons" % '/'.join(path)) if part and not ALLOWED_PATH_NAME.match(part): raise ValueError("path %s disallowed for security reasons" % part) file_paths = [os.sep.join(item["path"]) for item in files] if len(set(file_paths)) != len(file_paths): raise ValueError("bad metainfo - duplicate path") return info
[ "def", "check_info", "(", "info", ")", ":", "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", "ValueError", "(", "\"bad metainfo - bad pieces key\"", ")", "piece_size", "=", "info", ".", "get", "(", "\"piece length\"", ")", "if", "not", "isinstance", "(", "piece_size", ",", "(", "int", ",", "long", ")", ")", "or", "piece_size", "<=", "0", ":", "raise", "ValueError", "(", "\"bad metainfo - illegal piece length\"", ")", "name", "=", "info", ".", "get", "(", "\"name\"", ")", "if", "not", "isinstance", "(", "name", ",", "basestring", ")", ":", "raise", "ValueError", "(", "\"bad metainfo - bad name (type is %r)\"", "%", "type", "(", "name", ")", ".", "__name__", ")", "if", "not", "ALLOWED_ROOT_NAME", ".", "match", "(", "name", ")", ":", "raise", "ValueError", "(", "\"name %s disallowed for security reasons\"", "%", "name", ")", "if", "(", "\"files\"", "in", "info", ")", "==", "(", "\"length\"", "in", "info", ")", ":", "raise", "ValueError", "(", "\"single/multiple file mix\"", ")", "if", "\"length\"", "in", "info", ":", "length", "=", "info", ".", "get", "(", "\"length\"", ")", "if", "not", "isinstance", "(", "length", ",", "(", "int", ",", "long", ")", ")", "or", "length", "<", "0", ":", "raise", "ValueError", "(", "\"bad metainfo - bad length\"", ")", "else", ":", "files", "=", "info", ".", "get", "(", "\"files\"", ")", "if", "not", "isinstance", "(", "files", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"bad metainfo - bad file list\"", ")", "for", "item", "in", "files", ":", "if", "not", "isinstance", "(", "item", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"bad metainfo - bad file value\"", ")", "length", "=", "item", ".", "get", "(", "\"length\"", ")", "if", "not", "isinstance", "(", "length", ",", "(", "int", ",", "long", ")", ")", "or", "length", "<", "0", ":", "raise", "ValueError", "(", "\"bad metainfo - bad length\"", ")", "path", "=", "item", ".", "get", "(", "\"path\"", ")", "if", "not", "isinstance", "(", "path", ",", "(", "list", ",", "tuple", ")", ")", "or", "not", "path", ":", "raise", "ValueError", "(", "\"bad metainfo - bad path\"", ")", "for", "part", "in", "path", ":", "if", "not", "isinstance", "(", "part", ",", "basestring", ")", ":", "raise", "ValueError", "(", "\"bad metainfo - bad path dir\"", ")", "part", "=", "fmt", ".", "to_unicode", "(", "part", ")", "if", "part", "==", "'..'", ":", "raise", "ValueError", "(", "\"relative path in %s disallowed for security reasons\"", "%", "'/'", ".", "join", "(", "path", ")", ")", "if", "part", "and", "not", "ALLOWED_PATH_NAME", ".", "match", "(", "part", ")", ":", "raise", "ValueError", "(", "\"path %s disallowed for security reasons\"", "%", "part", ")", "file_paths", "=", "[", "os", ".", "sep", ".", "join", "(", "item", "[", "\"path\"", "]", ")", "for", "item", "in", "files", "]", "if", "len", "(", "set", "(", "file_paths", ")", ")", "!=", "len", "(", "file_paths", ")", ":", "raise", "ValueError", "(", "\"bad metainfo - duplicate path\"", ")", "return", "info" ]
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") check_info(meta.get("info")) return meta
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") check_info(meta.get("info")) return meta
[ "def", "check_meta", "(", "meta", ")", ":", "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\"", ")", "check_info", "(", "meta", ".", "get", "(", "\"info\"", ")", ")", "return", "meta" ]
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(): if [key] not in METAFILE_STD_KEYS: if logger: logger("Removing key %r..." % (key,)) del meta[key] modified.add(key) if including_info: for key in meta["info"].keys(): if ["info", key] not in METAFILE_STD_KEYS: if logger: logger("Removing key %r..." % ("info." + key,)) del meta["info"][key] modified.add("info." + key) for idx, entry in enumerate(meta["info"].get("files", [])): for key in entry.keys(): if ["info", "files", key] not in METAFILE_STD_KEYS: if logger: logger("Removing key %r from file #%d..." % (key, idx + 1)) del entry[key] modified.add("info.files." + key) # Remove crap that certain PHP software puts in paths entry["path"] = [i for i in entry["path"] if i] return modified
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(): if [key] not in METAFILE_STD_KEYS: if logger: logger("Removing key %r..." % (key,)) del meta[key] modified.add(key) if including_info: for key in meta["info"].keys(): if ["info", key] not in METAFILE_STD_KEYS: if logger: logger("Removing key %r..." % ("info." + key,)) del meta["info"][key] modified.add("info." + key) for idx, entry in enumerate(meta["info"].get("files", [])): for key in entry.keys(): if ["info", "files", key] not in METAFILE_STD_KEYS: if logger: logger("Removing key %r from file #%d..." % (key, idx + 1)) del entry[key] modified.add("info.files." + key) # Remove crap that certain PHP software puts in paths entry["path"] = [i for i in entry["path"] if i] return modified
[ "def", "clean_meta", "(", "meta", ",", "including_info", "=", "False", ",", "logger", "=", "None", ")", ":", "modified", "=", "set", "(", ")", "for", "key", "in", "meta", ".", "keys", "(", ")", ":", "if", "[", "key", "]", "not", "in", "METAFILE_STD_KEYS", ":", "if", "logger", ":", "logger", "(", "\"Removing key %r...\"", "%", "(", "key", ",", ")", ")", "del", "meta", "[", "key", "]", "modified", ".", "add", "(", "key", ")", "if", "including_info", ":", "for", "key", "in", "meta", "[", "\"info\"", "]", ".", "keys", "(", ")", ":", "if", "[", "\"info\"", ",", "key", "]", "not", "in", "METAFILE_STD_KEYS", ":", "if", "logger", ":", "logger", "(", "\"Removing key %r...\"", "%", "(", "\"info.\"", "+", "key", ",", ")", ")", "del", "meta", "[", "\"info\"", "]", "[", "key", "]", "modified", ".", "add", "(", "\"info.\"", "+", "key", ")", "for", "idx", ",", "entry", "in", "enumerate", "(", "meta", "[", "\"info\"", "]", ".", "get", "(", "\"files\"", ",", "[", "]", ")", ")", ":", "for", "key", "in", "entry", ".", "keys", "(", ")", ":", "if", "[", "\"info\"", ",", "\"files\"", ",", "key", "]", "not", "in", "METAFILE_STD_KEYS", ":", "if", "logger", ":", "logger", "(", "\"Removing key %r from file #%d...\"", "%", "(", "key", ",", "idx", "+", "1", ")", ")", "del", "entry", "[", "key", "]", "modified", ".", "add", "(", "\"info.files.\"", "+", "key", ")", "# Remove crap that certain PHP software puts in paths", "entry", "[", "\"path\"", "]", "=", "[", "i", "for", "i", "in", "entry", "[", "\"path\"", "]", "if", "i", "]", "return", "modified" ]
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'): if encoding: try: u8_text = text.decode(encoding).encode("utf-8") if encoding != 'utf-8': bad_encodings.add(encoding) bad_fields.add(field) return u8_text except UnicodeError: continue else: # Broken beyond anything reasonable bad_encodings.add('UNKNOWN/EXOTIC') bad_fields.add(field) return str(text, 'utf-8', 'replace').replace('\ufffd', '_').encode("utf-8") # Go through all string fields and check them for field in ("comment", "created by"): if field in meta: meta[field] = sane_encoding(field, meta[field]) meta["info"]["name"] = sane_encoding('info name', meta["info"]["name"]) for entry in meta["info"].get("files", []): entry["path"] = [sane_encoding('file path', i) for i in entry["path"]] return (meta, bad_encodings, bad_fields) if diagnostics else meta
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'): if encoding: try: u8_text = text.decode(encoding).encode("utf-8") if encoding != 'utf-8': bad_encodings.add(encoding) bad_fields.add(field) return u8_text except UnicodeError: continue else: # Broken beyond anything reasonable bad_encodings.add('UNKNOWN/EXOTIC') bad_fields.add(field) return str(text, 'utf-8', 'replace').replace('\ufffd', '_').encode("utf-8") # Go through all string fields and check them for field in ("comment", "created by"): if field in meta: meta[field] = sane_encoding(field, meta[field]) meta["info"]["name"] = sane_encoding('info name', meta["info"]["name"]) for entry in meta["info"].get("files", []): entry["path"] = [sane_encoding('file path', i) for i in entry["path"]] return (meta, bad_encodings, bad_fields) if diagnostics else meta
[ "def", "sanitize", "(", "meta", ",", "diagnostics", "=", "False", ")", ":", "bad_encodings", ",", "bad_fields", "=", "set", "(", ")", ",", "set", "(", ")", "def", "sane_encoding", "(", "field", ",", "text", ")", ":", "\"Transcoding helper.\"", "for", "encoding", "in", "(", "'utf-8'", ",", "meta", ".", "get", "(", "'encoding'", ",", "None", ")", ",", "'cp1252'", ")", ":", "if", "encoding", ":", "try", ":", "u8_text", "=", "text", ".", "decode", "(", "encoding", ")", ".", "encode", "(", "\"utf-8\"", ")", "if", "encoding", "!=", "'utf-8'", ":", "bad_encodings", ".", "add", "(", "encoding", ")", "bad_fields", ".", "add", "(", "field", ")", "return", "u8_text", "except", "UnicodeError", ":", "continue", "else", ":", "# Broken beyond anything reasonable", "bad_encodings", ".", "add", "(", "'UNKNOWN/EXOTIC'", ")", "bad_fields", ".", "add", "(", "field", ")", "return", "str", "(", "text", ",", "'utf-8'", ",", "'replace'", ")", ".", "replace", "(", "'\\ufffd'", ",", "'_'", ")", ".", "encode", "(", "\"utf-8\"", ")", "# Go through all string fields and check them", "for", "field", "in", "(", "\"comment\"", ",", "\"created by\"", ")", ":", "if", "field", "in", "meta", ":", "meta", "[", "field", "]", "=", "sane_encoding", "(", "field", ",", "meta", "[", "field", "]", ")", "meta", "[", "\"info\"", "]", "[", "\"name\"", "]", "=", "sane_encoding", "(", "'info name'", ",", "meta", "[", "\"info\"", "]", "[", "\"name\"", "]", ")", "for", "entry", "in", "meta", "[", "\"info\"", "]", ".", "get", "(", "\"files\"", ",", "[", "]", ")", ":", "entry", "[", "\"path\"", "]", "=", "[", "sane_encoding", "(", "'file path'", ",", "i", ")", "for", "i", "in", "entry", "[", "\"path\"", "]", "]", "return", "(", "meta", ",", "bad_encodings", ",", "bad_fields", ")", "if", "diagnostics", "else", "meta" ]
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"]) files = [Bunch( path=[os.path.abspath(datapath)], length=meta["info"]["length"], )] # Prepare resume data resume = meta.setdefault("libtorrent_resume", {}) resume["bitfield"] = len(meta["info"]["pieces"]) // 20 resume["files"] = [] piece_length = meta["info"]["piece length"] offset = 0 for fileinfo in files: # Get the path into the filesystem filepath = os.sep.join(fileinfo["path"]) if not single: filepath = os.path.join(datapath, filepath.strip(os.sep)) # Check file size if os.path.getsize(filepath) != fileinfo["length"]: raise OSError(errno.EINVAL, "File size mismatch for %r [is %d, expected %d]" % ( filepath, os.path.getsize(filepath), fileinfo["length"], )) # Add resume data for this file resume["files"].append(dict( priority=1, mtime=int(os.path.getmtime(filepath)), completed=(offset+fileinfo["length"]+piece_length-1) // piece_length - offset // piece_length, )) offset += fileinfo["length"] return meta
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"]) files = [Bunch( path=[os.path.abspath(datapath)], length=meta["info"]["length"], )] # Prepare resume data resume = meta.setdefault("libtorrent_resume", {}) resume["bitfield"] = len(meta["info"]["pieces"]) // 20 resume["files"] = [] piece_length = meta["info"]["piece length"] offset = 0 for fileinfo in files: # Get the path into the filesystem filepath = os.sep.join(fileinfo["path"]) if not single: filepath = os.path.join(datapath, filepath.strip(os.sep)) # Check file size if os.path.getsize(filepath) != fileinfo["length"]: raise OSError(errno.EINVAL, "File size mismatch for %r [is %d, expected %d]" % ( filepath, os.path.getsize(filepath), fileinfo["length"], )) # Add resume data for this file resume["files"].append(dict( priority=1, mtime=int(os.path.getmtime(filepath)), completed=(offset+fileinfo["length"]+piece_length-1) // piece_length - offset // piece_length, )) offset += fileinfo["length"] return meta
[ "def", "add_fast_resume", "(", "meta", ",", "datapath", ")", ":", "# 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\"", "]", ")", "files", "=", "[", "Bunch", "(", "path", "=", "[", "os", ".", "path", ".", "abspath", "(", "datapath", ")", "]", ",", "length", "=", "meta", "[", "\"info\"", "]", "[", "\"length\"", "]", ",", ")", "]", "# Prepare resume data", "resume", "=", "meta", ".", "setdefault", "(", "\"libtorrent_resume\"", ",", "{", "}", ")", "resume", "[", "\"bitfield\"", "]", "=", "len", "(", "meta", "[", "\"info\"", "]", "[", "\"pieces\"", "]", ")", "//", "20", "resume", "[", "\"files\"", "]", "=", "[", "]", "piece_length", "=", "meta", "[", "\"info\"", "]", "[", "\"piece length\"", "]", "offset", "=", "0", "for", "fileinfo", "in", "files", ":", "# Get the path into the filesystem", "filepath", "=", "os", ".", "sep", ".", "join", "(", "fileinfo", "[", "\"path\"", "]", ")", "if", "not", "single", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "datapath", ",", "filepath", ".", "strip", "(", "os", ".", "sep", ")", ")", "# Check file size", "if", "os", ".", "path", ".", "getsize", "(", "filepath", ")", "!=", "fileinfo", "[", "\"length\"", "]", ":", "raise", "OSError", "(", "errno", ".", "EINVAL", ",", "\"File size mismatch for %r [is %d, expected %d]\"", "%", "(", "filepath", ",", "os", ".", "path", ".", "getsize", "(", "filepath", ")", ",", "fileinfo", "[", "\"length\"", "]", ",", ")", ")", "# Add resume data for this file", "resume", "[", "\"files\"", "]", ".", "append", "(", "dict", "(", "priority", "=", "1", ",", "mtime", "=", "int", "(", "os", ".", "path", ".", "getmtime", "(", "filepath", ")", ")", ",", "completed", "=", "(", "offset", "+", "fileinfo", "[", "\"length\"", "]", "+", "piece_length", "-", "1", ")", "//", "piece_length", "-", "offset", "//", "piece_length", ",", ")", ")", "offset", "+=", "fileinfo", "[", "\"length\"", "]", "return", "meta" ]
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']]) return total_size
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']]) return total_size
[ "def", "data_size", "(", "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'", "]", "]", ")", "return", "total_size" ]
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") as handle: raw_data = handle.read() data = bencode.bdecode(raw_data) try: check_meta(data) if raw_data != bencode.bencode(data): raise ValueError("Bad bencoded data - dict keys out of order?") except ValueError as exc: if log: # Warn about it, unless it's a quiet value query if not quiet: log.warn("%s: %s" % (filename, exc)) else: raise return data
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") as handle: raw_data = handle.read() data = bencode.bdecode(raw_data) try: check_meta(data) if raw_data != bencode.bencode(data): raise ValueError("Bad bencoded data - dict keys out of order?") except ValueError as exc: if log: # Warn about it, unless it's a quiet value query if not quiet: log.warn("%s: %s" % (filename, exc)) else: raise return data
[ "def", "checked_open", "(", "filename", ",", "log", "=", "None", ",", "quiet", "=", "False", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "handle", ":", "raw_data", "=", "handle", ".", "read", "(", ")", "data", "=", "bencode", ".", "bdecode", "(", "raw_data", ")", "try", ":", "check_meta", "(", "data", ")", "if", "raw_data", "!=", "bencode", ".", "bencode", "(", "data", ")", ":", "raise", "ValueError", "(", "\"Bad bencoded data - dict keys out of order?\"", ")", "except", "ValueError", "as", "exc", ":", "if", "log", ":", "# Warn about it, unless it's a quiet value query", "if", "not", "quiet", ":", "log", ".", "warn", "(", "\"%s: %s\"", "%", "(", "filename", ",", "exc", ")", ")", "else", ":", "raise", "return", "data" ]
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", "supress", "that", "warning", "." ]
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.format(self, obj, context, maxlevels, level)
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.format(self, obj, context, maxlevels, level)
[ "def", "format", "(", "self", ",", "obj", ",", "context", ",", "maxlevels", ",", "level", ")", ":", "# pylint: disable=arguments-differ", "if", "isinstance", "(", "obj", ",", "basestring", ")", "and", "\"://\"", "in", "fmt", ".", "to_unicode", "(", "obj", ")", ":", "obj", "=", "mask_keys", "(", "obj", ")", "return", "pprint", ".", "PrettyPrinter", ".", "format", "(", "self", ",", "obj", ",", "context", ",", "maxlevels", ",", "level", ")" ]
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", ".", "_datapath" ]
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", ".", "stat", "(", "self", ".", "datapath", ")", ".", "st_mode", ")", ")", "else", ":", "self", ".", "_datapath", "=", "None", "self", ".", "_fifo", "=", "False" ]
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 with open(self.datapath, "r") as fifo: while True: relpath = fifo.readline().rstrip('\n') if not relpath: # EOF? break self.LOG.debug("Read relative path %r from FIFO..." % (relpath,)) yield os.path.join(os.path.dirname(self.datapath), relpath) self.LOG.debug("FIFO %r closed!" % (self.datapath,)) # Directory? elif os.path.isdir(self.datapath): # Walk the directory tree for dirpath, dirnames, filenames in os.walk(self.datapath): #, followlinks=True): # Don't scan blacklisted directories for bad in dirnames[:]: if any(fnmatch.fnmatch(bad, pattern) for pattern in self.ignore): dirnames.remove(bad) # Yield all filenames that aren't blacklisted for filename in filenames: if not any(fnmatch.fnmatch(filename, pattern) for pattern in self.ignore): #yield os.path.join(dirpath[len(self.datapath)+1:], filename) yield os.path.join(dirpath, filename) # Single file else: # Yield the filename yield self.datapath
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 with open(self.datapath, "r") as fifo: while True: relpath = fifo.readline().rstrip('\n') if not relpath: # EOF? break self.LOG.debug("Read relative path %r from FIFO..." % (relpath,)) yield os.path.join(os.path.dirname(self.datapath), relpath) self.LOG.debug("FIFO %r closed!" % (self.datapath,)) # Directory? elif os.path.isdir(self.datapath): # Walk the directory tree for dirpath, dirnames, filenames in os.walk(self.datapath): #, followlinks=True): # Don't scan blacklisted directories for bad in dirnames[:]: if any(fnmatch.fnmatch(bad, pattern) for pattern in self.ignore): dirnames.remove(bad) # Yield all filenames that aren't blacklisted for filename in filenames: if not any(fnmatch.fnmatch(filename, pattern) for pattern in self.ignore): #yield os.path.join(dirpath[len(self.datapath)+1:], filename) yield os.path.join(dirpath, filename) # Single file else: # Yield the filename yield self.datapath
[ "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 directory containing the FIFO", "with", "open", "(", "self", ".", "datapath", ",", "\"r\"", ")", "as", "fifo", ":", "while", "True", ":", "relpath", "=", "fifo", ".", "readline", "(", ")", ".", "rstrip", "(", "'\\n'", ")", "if", "not", "relpath", ":", "# EOF?", "break", "self", ".", "LOG", ".", "debug", "(", "\"Read relative path %r from FIFO...\"", "%", "(", "relpath", ",", ")", ")", "yield", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "datapath", ")", ",", "relpath", ")", "self", ".", "LOG", ".", "debug", "(", "\"FIFO %r closed!\"", "%", "(", "self", ".", "datapath", ",", ")", ")", "# Directory?", "elif", "os", ".", "path", ".", "isdir", "(", "self", ".", "datapath", ")", ":", "# Walk the directory tree", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "self", ".", "datapath", ")", ":", "#, followlinks=True):", "# Don't scan blacklisted directories", "for", "bad", "in", "dirnames", "[", ":", "]", ":", "if", "any", "(", "fnmatch", ".", "fnmatch", "(", "bad", ",", "pattern", ")", "for", "pattern", "in", "self", ".", "ignore", ")", ":", "dirnames", ".", "remove", "(", "bad", ")", "# Yield all filenames that aren't blacklisted", "for", "filename", "in", "filenames", ":", "if", "not", "any", "(", "fnmatch", ".", "fnmatch", "(", "filename", ",", "pattern", ")", "for", "pattern", "in", "self", ".", "ignore", ")", ":", "#yield os.path.join(dirpath[len(self.datapath)+1:], filename)", "yield", "os", ".", "path", ".", "join", "(", "dirpath", ",", "filename", ")", "# Single file", "else", ":", "# Yield the filename", "yield", "self", ".", "datapath" ]
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 self._fifo else self._calc_size() totalhashed = 0 # Start a new piece sha1sum = hashlib.sha1() done = 0 filename = None # Hash all files for filename in walker: # Assemble file info filesize = os.path.getsize(filename) filepath = filename[len(os.path.dirname(self.datapath) if self._fifo else self.datapath):].lstrip(os.sep) file_list.append({ "length": filesize, "path": [fmt.to_utf8(x) for x in fmt.to_unicode(filepath).replace(os.sep, '/').split('/')], }) self.LOG.debug("Hashing %r, size %d..." % (filename, filesize)) # Open file and hash it fileoffset = 0 handle = open(filename, "rb") try: while fileoffset < filesize: # Read rest of piece or file, whatever is smaller chunk = handle.read(min(filesize - fileoffset, piece_size - done)) sha1sum.update(chunk) # bogus pylint: disable=E1101 done += len(chunk) fileoffset += len(chunk) totalhashed += len(chunk) # Piece is done if done == piece_size: pieces.append(sha1sum.digest()) # bogus pylint: disable=E1101 if piece_callback: piece_callback(filename, pieces[-1]) # Start a new piece sha1sum = hashlib.sha1() done = 0 # Report progress if progress: progress(totalhashed, totalsize) finally: handle.close() # Add hash of partial last piece if done > 0: pieces.append(sha1sum.digest()) # bogus pylint: disable=E1103 if piece_callback: piece_callback(filename, pieces[-1]) # Build the meta dict metainfo = { "pieces": b"".join(pieces), "piece length": piece_size, "name": os.path.basename(self.datapath), } # Handle directory/FIFO vs. single file if self._fifo or os.path.isdir(self.datapath): metainfo["files"] = file_list else: metainfo["length"] = totalhashed hashing_secs = time.time() - hashing_secs self.LOG.info("Hashing of %s took %.1f secs (%s/s)" % ( fmt.human_size(totalhashed).strip(), hashing_secs, fmt.human_size(totalhashed / hashing_secs).strip(), )) # Return validated info dict return check_info(metainfo), totalhashed
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 self._fifo else self._calc_size() totalhashed = 0 # Start a new piece sha1sum = hashlib.sha1() done = 0 filename = None # Hash all files for filename in walker: # Assemble file info filesize = os.path.getsize(filename) filepath = filename[len(os.path.dirname(self.datapath) if self._fifo else self.datapath):].lstrip(os.sep) file_list.append({ "length": filesize, "path": [fmt.to_utf8(x) for x in fmt.to_unicode(filepath).replace(os.sep, '/').split('/')], }) self.LOG.debug("Hashing %r, size %d..." % (filename, filesize)) # Open file and hash it fileoffset = 0 handle = open(filename, "rb") try: while fileoffset < filesize: # Read rest of piece or file, whatever is smaller chunk = handle.read(min(filesize - fileoffset, piece_size - done)) sha1sum.update(chunk) # bogus pylint: disable=E1101 done += len(chunk) fileoffset += len(chunk) totalhashed += len(chunk) # Piece is done if done == piece_size: pieces.append(sha1sum.digest()) # bogus pylint: disable=E1101 if piece_callback: piece_callback(filename, pieces[-1]) # Start a new piece sha1sum = hashlib.sha1() done = 0 # Report progress if progress: progress(totalhashed, totalsize) finally: handle.close() # Add hash of partial last piece if done > 0: pieces.append(sha1sum.digest()) # bogus pylint: disable=E1103 if piece_callback: piece_callback(filename, pieces[-1]) # Build the meta dict metainfo = { "pieces": b"".join(pieces), "piece length": piece_size, "name": os.path.basename(self.datapath), } # Handle directory/FIFO vs. single file if self._fifo or os.path.isdir(self.datapath): metainfo["files"] = file_list else: metainfo["length"] = totalhashed hashing_secs = time.time() - hashing_secs self.LOG.info("Hashing of %s took %.1f secs (%s/s)" % ( fmt.human_size(totalhashed).strip(), hashing_secs, fmt.human_size(totalhashed / hashing_secs).strip(), )) # Return validated info dict return check_info(metainfo), totalhashed
[ "def", "_make_info", "(", "self", ",", "piece_size", ",", "progress", ",", "walker", ",", "piece_callback", "=", "None", ")", ":", "# These collect the file descriptions and piece hashes", "file_list", "=", "[", "]", "pieces", "=", "[", "]", "# Initialize progress state", "hashing_secs", "=", "time", ".", "time", "(", ")", "totalsize", "=", "-", "1", "if", "self", ".", "_fifo", "else", "self", ".", "_calc_size", "(", ")", "totalhashed", "=", "0", "# Start a new piece", "sha1sum", "=", "hashlib", ".", "sha1", "(", ")", "done", "=", "0", "filename", "=", "None", "# Hash all files", "for", "filename", "in", "walker", ":", "# Assemble file info", "filesize", "=", "os", ".", "path", ".", "getsize", "(", "filename", ")", "filepath", "=", "filename", "[", "len", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "datapath", ")", "if", "self", ".", "_fifo", "else", "self", ".", "datapath", ")", ":", "]", ".", "lstrip", "(", "os", ".", "sep", ")", "file_list", ".", "append", "(", "{", "\"length\"", ":", "filesize", ",", "\"path\"", ":", "[", "fmt", ".", "to_utf8", "(", "x", ")", "for", "x", "in", "fmt", ".", "to_unicode", "(", "filepath", ")", ".", "replace", "(", "os", ".", "sep", ",", "'/'", ")", ".", "split", "(", "'/'", ")", "]", ",", "}", ")", "self", ".", "LOG", ".", "debug", "(", "\"Hashing %r, size %d...\"", "%", "(", "filename", ",", "filesize", ")", ")", "# Open file and hash it", "fileoffset", "=", "0", "handle", "=", "open", "(", "filename", ",", "\"rb\"", ")", "try", ":", "while", "fileoffset", "<", "filesize", ":", "# Read rest of piece or file, whatever is smaller", "chunk", "=", "handle", ".", "read", "(", "min", "(", "filesize", "-", "fileoffset", ",", "piece_size", "-", "done", ")", ")", "sha1sum", ".", "update", "(", "chunk", ")", "# bogus pylint: disable=E1101", "done", "+=", "len", "(", "chunk", ")", "fileoffset", "+=", "len", "(", "chunk", ")", "totalhashed", "+=", "len", "(", "chunk", ")", "# Piece is done", "if", "done", "==", "piece_size", ":", "pieces", ".", "append", "(", "sha1sum", ".", "digest", "(", ")", ")", "# bogus pylint: disable=E1101", "if", "piece_callback", ":", "piece_callback", "(", "filename", ",", "pieces", "[", "-", "1", "]", ")", "# Start a new piece", "sha1sum", "=", "hashlib", ".", "sha1", "(", ")", "done", "=", "0", "# Report progress", "if", "progress", ":", "progress", "(", "totalhashed", ",", "totalsize", ")", "finally", ":", "handle", ".", "close", "(", ")", "# Add hash of partial last piece", "if", "done", ">", "0", ":", "pieces", ".", "append", "(", "sha1sum", ".", "digest", "(", ")", ")", "# bogus pylint: disable=E1103", "if", "piece_callback", ":", "piece_callback", "(", "filename", ",", "pieces", "[", "-", "1", "]", ")", "# Build the meta dict", "metainfo", "=", "{", "\"pieces\"", ":", "b\"\"", ".", "join", "(", "pieces", ")", ",", "\"piece length\"", ":", "piece_size", ",", "\"name\"", ":", "os", ".", "path", ".", "basename", "(", "self", ".", "datapath", ")", ",", "}", "# Handle directory/FIFO vs. single file", "if", "self", ".", "_fifo", "or", "os", ".", "path", ".", "isdir", "(", "self", ".", "datapath", ")", ":", "metainfo", "[", "\"files\"", "]", "=", "file_list", "else", ":", "metainfo", "[", "\"length\"", "]", "=", "totalhashed", "hashing_secs", "=", "time", ".", "time", "(", ")", "-", "hashing_secs", "self", ".", "LOG", ".", "info", "(", "\"Hashing of %s took %.1f secs (%s/s)\"", "%", "(", "fmt", ".", "human_size", "(", "totalhashed", ")", ".", "strip", "(", ")", ",", "hashing_secs", ",", "fmt", ".", "human_size", "(", "totalhashed", "/", "hashing_secs", ")", ".", "strip", "(", ")", ",", ")", ")", "# Return validated info dict", "return", "check_info", "(", "metainfo", ")", ",", "totalhashed" ]
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 else: total_size = self._calc_size() if total_size: piece_size_exp = int(math.log(total_size) / math.log(2)) - 9 else: piece_size_exp = 0 piece_size_exp = min(max(15, piece_size_exp), 24) piece_size = 2 ** piece_size_exp # Build info hash info, totalhashed = self._make_info(piece_size, progress, self.walk() if self._fifo else sorted(self.walk())) # Enforce unique hash per tracker info["x_cross_seed"] = hashlib.md5(tracker_url).hexdigest() # Set private flag if private: info["private"] = 1 # Freely chosen root name (default is basename of the data path) if root_name: info["name"] = root_name # Torrent metadata meta = { "info": info, "announce": tracker_url.strip(), } #XXX meta["encoding"] = "UTF-8" # Return validated meta dict return check_meta(meta), totalhashed
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 else: total_size = self._calc_size() if total_size: piece_size_exp = int(math.log(total_size) / math.log(2)) - 9 else: piece_size_exp = 0 piece_size_exp = min(max(15, piece_size_exp), 24) piece_size = 2 ** piece_size_exp # Build info hash info, totalhashed = self._make_info(piece_size, progress, self.walk() if self._fifo else sorted(self.walk())) # Enforce unique hash per tracker info["x_cross_seed"] = hashlib.md5(tracker_url).hexdigest() # Set private flag if private: info["private"] = 1 # Freely chosen root name (default is basename of the data path) if root_name: info["name"] = root_name # Torrent metadata meta = { "info": info, "announce": tracker_url.strip(), } #XXX meta["encoding"] = "UTF-8" # Return validated meta dict return check_meta(meta), totalhashed
[ "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", "piece_size_exp", "=", "20", "else", ":", "total_size", "=", "self", ".", "_calc_size", "(", ")", "if", "total_size", ":", "piece_size_exp", "=", "int", "(", "math", ".", "log", "(", "total_size", ")", "/", "math", ".", "log", "(", "2", ")", ")", "-", "9", "else", ":", "piece_size_exp", "=", "0", "piece_size_exp", "=", "min", "(", "max", "(", "15", ",", "piece_size_exp", ")", ",", "24", ")", "piece_size", "=", "2", "**", "piece_size_exp", "# Build info hash", "info", ",", "totalhashed", "=", "self", ".", "_make_info", "(", "piece_size", ",", "progress", ",", "self", ".", "walk", "(", ")", "if", "self", ".", "_fifo", "else", "sorted", "(", "self", ".", "walk", "(", ")", ")", ")", "# Enforce unique hash per tracker", "info", "[", "\"x_cross_seed\"", "]", "=", "hashlib", ".", "md5", "(", "tracker_url", ")", ".", "hexdigest", "(", ")", "# Set private flag", "if", "private", ":", "info", "[", "\"private\"", "]", "=", "1", "# Freely chosen root name (default is basename of the data path)", "if", "root_name", ":", "info", "[", "\"name\"", "]", "=", "root_name", "# Torrent metadata", "meta", "=", "{", "\"info\"", ":", "info", ",", "\"announce\"", ":", "tracker_url", ".", "strip", "(", ")", ",", "}", "#XXX meta[\"encoding\"] = \"UTF-8\"", "# Return validated meta dict", "return", "check_meta", "(", "meta", ")", ",", "totalhashed" ]
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"]["pieces"][check_piece.piece_index:check_piece.piece_index+20]: self.LOG.warn("Piece #%d: Hashes differ in file %r" % (check_piece.piece_index//20, filename)) check_piece.piece_index += 20 check_piece.piece_index = 0 datameta, _ = self._make_info(int(metainfo["info"]["piece length"]), progress, [datapath] if "length" in metainfo["info"] else (os.path.join(*([datapath] + i["path"])) for i in metainfo["info"]["files"]), piece_callback=check_piece ) return datameta["pieces"] == metainfo["info"]["pieces"]
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"]["pieces"][check_piece.piece_index:check_piece.piece_index+20]: self.LOG.warn("Piece #%d: Hashes differ in file %r" % (check_piece.piece_index//20, filename)) check_piece.piece_index += 20 check_piece.piece_index = 0 datameta, _ = self._make_info(int(metainfo["info"]["piece length"]), progress, [datapath] if "length" in metainfo["info"] else (os.path.join(*([datapath] + i["path"])) for i in metainfo["info"]["files"]), piece_callback=check_piece ) return datameta["pieces"] == metainfo["info"]["pieces"]
[ "def", "check", "(", "self", ",", "metainfo", ",", "datapath", ",", "progress", "=", "None", ")", ":", "if", "datapath", ":", "self", ".", "datapath", "=", "datapath", "def", "check_piece", "(", "filename", ",", "piece", ")", ":", "\"Callback for new piece\"", "if", "piece", "!=", "metainfo", "[", "\"info\"", "]", "[", "\"pieces\"", "]", "[", "check_piece", ".", "piece_index", ":", "check_piece", ".", "piece_index", "+", "20", "]", ":", "self", ".", "LOG", ".", "warn", "(", "\"Piece #%d: Hashes differ in file %r\"", "%", "(", "check_piece", ".", "piece_index", "//", "20", ",", "filename", ")", ")", "check_piece", ".", "piece_index", "+=", "20", "check_piece", ".", "piece_index", "=", "0", "datameta", ",", "_", "=", "self", ".", "_make_info", "(", "int", "(", "metainfo", "[", "\"info\"", "]", "[", "\"piece length\"", "]", ")", ",", "progress", ",", "[", "datapath", "]", "if", "\"length\"", "in", "metainfo", "[", "\"info\"", "]", "else", "(", "os", ".", "path", ".", "join", "(", "*", "(", "[", "datapath", "]", "+", "i", "[", "\"path\"", "]", ")", ")", "for", "i", "in", "metainfo", "[", "\"info\"", "]", "[", "\"files\"", "]", ")", ",", "piece_callback", "=", "check_piece", ")", "return", "datameta", "[", "\"pieces\"", "]", "==", "metainfo", "[", "\"info\"", "]", "[", "\"pieces\"", "]" ]
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 if anything more is ready to start downloading startable = [i for i in items if self.config.startable.match(i)] if not startable: self.LOG.debug("Checked %d item(s), none startable according to [ %s ]", len(items), self.config.startable) return # Check intermission delay now = time.time() if now < self.last_start: # compensate for summer time and other oddities self.last_start = now delayed = int(self.last_start + self.config.intermission - now) if delayed > 0: self.LOG.debug("Delaying start of {:d} item(s)," " due to {:d}s intermission with {:d}s left" .format(len(startable), self.config.intermission, delayed)) return # TODO: sort by priority, then loaded time # Stick to "start_at_once" parameter, unless "downloading_min" is violated downloading = [i for i in items if self.config.downloading.match(i)] start_now = max(self.config.start_at_once, self.config.downloading_min - len(downloading)) start_now = min(start_now, len(startable)) #down_traffic = sum(i.down for i in downloading) ##self.LOG.info("%d downloading, down %d" % (len(downloading), down_traffic)) # Start eligible items for idx, item in enumerate(startable): # Check if we reached 'start_now' in this run if idx >= start_now: self.LOG.debug("Only starting %d item(s) in this run, %d more could be downloading" % ( start_now, len(startable)-idx,)) break # TODO: Prevent start of more torrents that can fit on the drive (taking "off" files into account) # (restarts items that were stopped due to the "low_diskspace" schedule, and also avoids triggering it at all) # Only check the other conditions when we have `downloading_min` covered if len(downloading) < self.config.downloading_min: self.LOG.debug("Catching up from %d to a minimum of %d downloading item(s)" % ( len(downloading), self.config.downloading_min)) else: # Limit to the given maximum of downloading items if len(downloading) >= self.config.downloading_max: self.LOG.debug("Already downloading %d item(s) out of %d max, %d more could be downloading" % ( len(downloading), self.config.downloading_max, len(startable)-idx,)) break # If we made it here, start it! self.last_start = now downloading.append(item) self.LOG.info("%s '%s' [%s, #%s]" % ( "WOULD start" if self.config.dry_run else "Starting", fmt.to_utf8(item.name), item.alias, item.hash)) if not self.config.dry_run: item.start() if not self.config.quiet: self.proxy.log(xmlrpc.NOHASH, "%s: Started '%s' {%s}" % ( self.__class__.__name__, fmt.to_utf8(item.name), item.alias, ))
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 if anything more is ready to start downloading startable = [i for i in items if self.config.startable.match(i)] if not startable: self.LOG.debug("Checked %d item(s), none startable according to [ %s ]", len(items), self.config.startable) return # Check intermission delay now = time.time() if now < self.last_start: # compensate for summer time and other oddities self.last_start = now delayed = int(self.last_start + self.config.intermission - now) if delayed > 0: self.LOG.debug("Delaying start of {:d} item(s)," " due to {:d}s intermission with {:d}s left" .format(len(startable), self.config.intermission, delayed)) return # TODO: sort by priority, then loaded time # Stick to "start_at_once" parameter, unless "downloading_min" is violated downloading = [i for i in items if self.config.downloading.match(i)] start_now = max(self.config.start_at_once, self.config.downloading_min - len(downloading)) start_now = min(start_now, len(startable)) #down_traffic = sum(i.down for i in downloading) ##self.LOG.info("%d downloading, down %d" % (len(downloading), down_traffic)) # Start eligible items for idx, item in enumerate(startable): # Check if we reached 'start_now' in this run if idx >= start_now: self.LOG.debug("Only starting %d item(s) in this run, %d more could be downloading" % ( start_now, len(startable)-idx,)) break # TODO: Prevent start of more torrents that can fit on the drive (taking "off" files into account) # (restarts items that were stopped due to the "low_diskspace" schedule, and also avoids triggering it at all) # Only check the other conditions when we have `downloading_min` covered if len(downloading) < self.config.downloading_min: self.LOG.debug("Catching up from %d to a minimum of %d downloading item(s)" % ( len(downloading), self.config.downloading_min)) else: # Limit to the given maximum of downloading items if len(downloading) >= self.config.downloading_max: self.LOG.debug("Already downloading %d item(s) out of %d max, %d more could be downloading" % ( len(downloading), self.config.downloading_max, len(startable)-idx,)) break # If we made it here, start it! self.last_start = now downloading.append(item) self.LOG.info("%s '%s' [%s, #%s]" % ( "WOULD start" if self.config.dry_run else "Starting", fmt.to_utf8(item.name), item.alias, item.hash)) if not self.config.dry_run: item.start() if not self.config.quiet: self.proxy.log(xmlrpc.NOHASH, "%s: Started '%s' {%s}" % ( self.__class__.__name__, fmt.to_utf8(item.name), item.alias, ))
[ "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 start downloading", "startable", "=", "[", "i", "for", "i", "in", "items", "if", "self", ".", "config", ".", "startable", ".", "match", "(", "i", ")", "]", "if", "not", "startable", ":", "self", ".", "LOG", ".", "debug", "(", "\"Checked %d item(s), none startable according to [ %s ]\"", ",", "len", "(", "items", ")", ",", "self", ".", "config", ".", "startable", ")", "return", "# Check intermission delay", "now", "=", "time", ".", "time", "(", ")", "if", "now", "<", "self", ".", "last_start", ":", "# compensate for summer time and other oddities", "self", ".", "last_start", "=", "now", "delayed", "=", "int", "(", "self", ".", "last_start", "+", "self", ".", "config", ".", "intermission", "-", "now", ")", "if", "delayed", ">", "0", ":", "self", ".", "LOG", ".", "debug", "(", "\"Delaying start of {:d} item(s),\"", "\" due to {:d}s intermission with {:d}s left\"", ".", "format", "(", "len", "(", "startable", ")", ",", "self", ".", "config", ".", "intermission", ",", "delayed", ")", ")", "return", "# TODO: sort by priority, then loaded time", "# Stick to \"start_at_once\" parameter, unless \"downloading_min\" is violated", "downloading", "=", "[", "i", "for", "i", "in", "items", "if", "self", ".", "config", ".", "downloading", ".", "match", "(", "i", ")", "]", "start_now", "=", "max", "(", "self", ".", "config", ".", "start_at_once", ",", "self", ".", "config", ".", "downloading_min", "-", "len", "(", "downloading", ")", ")", "start_now", "=", "min", "(", "start_now", ",", "len", "(", "startable", ")", ")", "#down_traffic = sum(i.down for i in downloading)", "##self.LOG.info(\"%d downloading, down %d\" % (len(downloading), down_traffic))", "# Start eligible items", "for", "idx", ",", "item", "in", "enumerate", "(", "startable", ")", ":", "# Check if we reached 'start_now' in this run", "if", "idx", ">=", "start_now", ":", "self", ".", "LOG", ".", "debug", "(", "\"Only starting %d item(s) in this run, %d more could be downloading\"", "%", "(", "start_now", ",", "len", "(", "startable", ")", "-", "idx", ",", ")", ")", "break", "# TODO: Prevent start of more torrents that can fit on the drive (taking \"off\" files into account)", "# (restarts items that were stopped due to the \"low_diskspace\" schedule, and also avoids triggering it at all)", "# Only check the other conditions when we have `downloading_min` covered", "if", "len", "(", "downloading", ")", "<", "self", ".", "config", ".", "downloading_min", ":", "self", ".", "LOG", ".", "debug", "(", "\"Catching up from %d to a minimum of %d downloading item(s)\"", "%", "(", "len", "(", "downloading", ")", ",", "self", ".", "config", ".", "downloading_min", ")", ")", "else", ":", "# Limit to the given maximum of downloading items", "if", "len", "(", "downloading", ")", ">=", "self", ".", "config", ".", "downloading_max", ":", "self", ".", "LOG", ".", "debug", "(", "\"Already downloading %d item(s) out of %d max, %d more could be downloading\"", "%", "(", "len", "(", "downloading", ")", ",", "self", ".", "config", ".", "downloading_max", ",", "len", "(", "startable", ")", "-", "idx", ",", ")", ")", "break", "# If we made it here, start it!", "self", ".", "last_start", "=", "now", "downloading", ".", "append", "(", "item", ")", "self", ".", "LOG", ".", "info", "(", "\"%s '%s' [%s, #%s]\"", "%", "(", "\"WOULD start\"", "if", "self", ".", "config", ".", "dry_run", "else", "\"Starting\"", ",", "fmt", ".", "to_utf8", "(", "item", ".", "name", ")", ",", "item", ".", "alias", ",", "item", ".", "hash", ")", ")", "if", "not", "self", ".", "config", ".", "dry_run", ":", "item", ".", "start", "(", ")", "if", "not", "self", ".", "config", ".", "quiet", ":", "self", ".", "proxy", ".", "log", "(", "xmlrpc", ".", "NOHASH", ",", "\"%s: Started '%s' {%s}\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "fmt", ".", "to_utf8", "(", "item", ".", "name", ")", ",", "item", ".", "alias", ",", ")", ")" ]
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=self.sort_key) #self.LOG.debug("Sorted: %r" % [i.name for i in items]) # Handle found items self._start(items) self.LOG.debug("%s - %s" % (config_ini.engine.engine_id, self.proxy)) except (error.LoggableError, xmlrpc.ERRORS) as exc: # only debug, let the statistics logger do its job self.LOG.debug(str(exc))
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=self.sort_key) #self.LOG.debug("Sorted: %r" % [i.name for i in items]) # Handle found items self._start(items) self.LOG.debug("%s - %s" % (config_ini.engine.engine_id, self.proxy)) except (error.LoggableError, xmlrpc.ERRORS) as exc: # only debug, let the statistics logger do its job self.LOG.debug(str(exc))
[ "def", "run", "(", "self", ")", ":", "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", "=", "self", ".", "sort_key", ")", "#self.LOG.debug(\"Sorted: %r\" % [i.name for i in items])", "# Handle found items", "self", ".", "_start", "(", "items", ")", "self", ".", "LOG", ".", "debug", "(", "\"%s - %s\"", "%", "(", "config_ini", ".", "engine", ".", "engine_id", ",", "self", ".", "proxy", ")", ")", "except", "(", "error", ".", "LoggableError", ",", "xmlrpc", ".", "ERRORS", ")", "as", "exc", ":", "# only debug, let the statistics logger do its job", "self", ".", "LOG", ".", "debug", "(", "str", "(", "exc", ")", ")" ]
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) def kind_manifold(): "file types that contribute at least N% to the item's total size" return ("kind_N", kind_manifold) print('') print("Fields are:") print("\n".join([" %-21s %s" % (name, field.__doc__) for name, field in sorted(engine.FieldDefinition.FIELDS.items() + [ custom_manifold(), kind_manifold(), ]) ])) print('') print("Format specifiers are:") print("\n".join([" %-21s %s" % (name, doc) for name, doc in sorted(formatting.OutputMapping.formatter_help()) ])) print('') print("Append format specifiers using a '.' to field names in '-o' lists,\n" "e.g. 'size.sz' or 'completed.raw.delta'.")
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 kind_manifold(): "file types that contribute at least N% to the item's total size" return ("kind_N", kind_manifold) print('') print("Fields are:") print("\n".join([" %-21s %s" % (name, field.__doc__) for name, field in sorted(engine.FieldDefinition.FIELDS.items() + [ custom_manifold(), kind_manifold(), ]) ])) print('') print("Format specifiers are:") print("\n".join([" %-21s %s" % (name, doc) for name, doc in sorted(formatting.OutputMapping.formatter_help()) ])) print('') print("Append format specifiers using a '.' to field names in '-o' lists,\n" "e.g. 'size.sz' or 'completed.raw.delta'.")
[ "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_manifold", ")", "def", "kind_manifold", "(", ")", ":", "\"file types that contribute at least N% to the item's total size\"", "return", "(", "\"kind_N\"", ",", "kind_manifold", ")", "print", "(", "''", ")", "print", "(", "\"Fields are:\"", ")", "print", "(", "\"\\n\"", ".", "join", "(", "[", "\" %-21s %s\"", "%", "(", "name", ",", "field", ".", "__doc__", ")", "for", "name", ",", "field", "in", "sorted", "(", "engine", ".", "FieldDefinition", ".", "FIELDS", ".", "items", "(", ")", "+", "[", "custom_manifold", "(", ")", ",", "kind_manifold", "(", ")", ",", "]", ")", "]", ")", ")", "print", "(", "''", ")", "print", "(", "\"Format specifiers are:\"", ")", "print", "(", "\"\\n\"", ".", "join", "(", "[", "\" %-21s %s\"", "%", "(", "name", ",", "doc", ")", "for", "name", ",", "doc", "in", "sorted", "(", "formatting", ".", "OutputMapping", ".", "formatter_help", "(", ")", ")", "]", ")", ")", "print", "(", "''", ")", "print", "(", "\"Append format specifiers using a '.' to field names in '-o' lists,\\n\"", "\"e.g. 'size.sz' or 'completed.raw.delta'.\"", ")" ]
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 self.max[field] = max(self.max[field], val) except (ValueError, TypeError): self.errors[field] += 1
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 self.max[field] = max(self.max[field], val) except (ValueError, TypeError): self.errors[field] += 1
[ "def", "add", "(", "self", ",", "field", ",", "val", ")", ":", "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", "self", ".", "max", "[", "field", "]", "=", "max", "(", "self", ".", "max", "[", "field", "]", ",", "val", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "self", ".", "errors", "[", "field", "]", "+=", "1" ]
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,) continue elif issubclass(field._matcher, matching.PatternFilter): yield "%s=" % (name,) yield "%s=/" % (name,) yield "%s=?" % (name,) yield "%s=\"'*'\"" % (name,) continue elif issubclass(field._matcher, matching.NumericFilterBase): for i in range(10): yield "%s=%d" % (name, i) else: yield "%s=" % (name,) yield r"%s=+" % (name,) yield r"%s=-" % (name,) yield "custom_" yield "kind_"
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,) continue elif issubclass(field._matcher, matching.PatternFilter): yield "%s=" % (name,) yield "%s=/" % (name,) yield "%s=?" % (name,) yield "%s=\"'*'\"" % (name,) continue elif issubclass(field._matcher, matching.NumericFilterBase): for i in range(10): yield "%s=%d" % (name, i) else: yield "%s=" % (name,) yield r"%s=+" % (name,) yield r"%s=-" % (name,) yield "custom_" yield "kind_"
[ "def", "help_completion_fields", "(", "self", ")", ":", "for", "name", ",", "field", "in", "sorted", "(", "engine", ".", "FieldDefinition", ".", "FIELDS", ".", "items", "(", ")", ")", ":", "if", "issubclass", "(", "field", ".", "_matcher", ",", "matching", ".", "BoolFilter", ")", ":", "yield", "\"%s=no\"", "%", "(", "name", ",", ")", "yield", "\"%s=yes\"", "%", "(", "name", ",", ")", "continue", "elif", "issubclass", "(", "field", ".", "_matcher", ",", "matching", ".", "PatternFilter", ")", ":", "yield", "\"%s=\"", "%", "(", "name", ",", ")", "yield", "\"%s=/\"", "%", "(", "name", ",", ")", "yield", "\"%s=?\"", "%", "(", "name", ",", ")", "yield", "\"%s=\\\"'*'\\\"\"", "%", "(", "name", ",", ")", "continue", "elif", "issubclass", "(", "field", ".", "_matcher", ",", "matching", ".", "NumericFilterBase", ")", ":", "for", "i", "in", "range", "(", "10", ")", ":", "yield", "\"%s=%d\"", "%", "(", "name", ",", "i", ")", "else", ":", "yield", "\"%s=\"", "%", "(", "name", ",", ")", "yield", "r\"%s=+\"", "%", "(", "name", ",", ")", "yield", "r\"%s=-\"", "%", "(", "name", ",", ")", "yield", "\"custom_\"", "yield", "\"kind_\"" ]
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), exc: self.fatal("Trouble with formatting item %r\n\n FORMAT = %r\n\n REASON =" % (item, self.options.output_format), exc) raise # in --debug mode if self.options.shell: item_text = '\t'.join(shell_escape(i) for i in item_text.split('\t')) # Justify headers according to stencil if stencil: item_text = '\t'.join(i.ljust(len(s)) for i, s in zip(item_text.split('\t'), stencil)) return item_text
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), exc: self.fatal("Trouble with formatting item %r\n\n FORMAT = %r\n\n REASON =" % (item, self.options.output_format), exc) raise # in --debug mode if self.options.shell: item_text = '\t'.join(shell_escape(i) for i in item_text.split('\t')) # Justify headers according to stencil if stencil: item_text = '\t'.join(i.ljust(len(s)) for i, s in zip(item_text.split('\t'), stencil)) return item_text
[ "def", "format_item", "(", "self", ",", "item", ",", "defaults", "=", "None", ",", "stencil", "=", "None", ")", ":", "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", ")", ",", "exc", ":", "self", ".", "fatal", "(", "\"Trouble with formatting item %r\\n\\n FORMAT = %r\\n\\n REASON =\"", "%", "(", "item", ",", "self", ".", "options", ".", "output_format", ")", ",", "exc", ")", "raise", "# in --debug mode", "if", "self", ".", "options", ".", "shell", ":", "item_text", "=", "'\\t'", ".", "join", "(", "shell_escape", "(", "i", ")", "for", "i", "in", "item_text", ".", "split", "(", "'\\t'", ")", ")", "# Justify headers according to stencil", "if", "stencil", ":", "item_text", "=", "'\\t'", ".", "join", "(", "i", ".", "ljust", "(", "len", "(", "s", ")", ")", "for", "i", ",", "s", "in", "zip", "(", "item_text", ".", "split", "(", "'\\t'", ")", ",", "stencil", ")", ")", "return", "item_text" ]
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(item_text) # For a header, use configured escape codes on a terminal if item is None and os.isatty(sys.stdout.fileno()): item_text = ''.join((config.output_header_ecma48, item_text, "\x1B[0m")) # Dump to selected target if to_log: if callable(to_log): to_log(item_text) else: self.LOG.info(item_text) elif self.options.nul: sys.stdout.write(item_text + '\0') sys.stdout.flush() else: print(item_text) return item_text.count('\n') + 1
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(item_text) # For a header, use configured escape codes on a terminal if item is None and os.isatty(sys.stdout.fileno()): item_text = ''.join((config.output_header_ecma48, item_text, "\x1B[0m")) # Dump to selected target if to_log: if callable(to_log): to_log(item_text) else: self.LOG.info(item_text) elif self.options.nul: sys.stdout.write(item_text + '\0') sys.stdout.flush() else: print(item_text) return item_text.count('\n') + 1
[ "def", "emit", "(", "self", ",", "item", ",", "defaults", "=", "None", ",", "stencil", "=", "None", ",", "to_log", "=", "False", ",", "item_formatter", "=", "None", ")", ":", "item_text", "=", "self", ".", "format_item", "(", "item", ",", "defaults", ",", "stencil", ")", "# Post-process line?", "if", "item_formatter", ":", "item_text", "=", "item_formatter", "(", "item_text", ")", "# For a header, use configured escape codes on a terminal", "if", "item", "is", "None", "and", "os", ".", "isatty", "(", "sys", ".", "stdout", ".", "fileno", "(", ")", ")", ":", "item_text", "=", "''", ".", "join", "(", "(", "config", ".", "output_header_ecma48", ",", "item_text", ",", "\"\\x1B[0m\"", ")", ")", "# Dump to selected target", "if", "to_log", ":", "if", "callable", "(", "to_log", ")", ":", "to_log", "(", "item_text", ")", "else", ":", "self", ".", "LOG", ".", "info", "(", "item_text", ")", "elif", "self", ".", "options", ".", "nul", ":", "sys", ".", "stdout", ".", "write", "(", "item_text", "+", "'\\0'", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "else", ":", "print", "(", "item_text", ")", "return", "item_text", ".", "count", "(", "'\\n'", ")", "+", "1" ]
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 output format from configuration # (they take precedence over field names, so name them wisely) output_format = config.formats.get(output_format, output_format) # Expand plain field list to usable form if re.match(r"^[,._0-9a-zA-Z]+$", output_format): self.plain_output_format = True output_format = "%%(%s)s" % ")s\t%(".join(formatting.validate_field_list(output_format, allow_fmt_specs=True)) # Replace some escape sequences output_format = (output_format .replace(r"\\", "\\") .replace(r"\n", "\n") .replace(r"\t", "\t") .replace(r"\$", "\0") # the next 3 allow using $() instead of %() .replace("$(", "%(") .replace("\0", "$") .replace(r"\ ", " ") # to prevent stripping in config file #.replace(r"\", "\") ) self.options.output_format = formatting.preparse(output_format)
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 output format from configuration # (they take precedence over field names, so name them wisely) output_format = config.formats.get(output_format, output_format) # Expand plain field list to usable form if re.match(r"^[,._0-9a-zA-Z]+$", output_format): self.plain_output_format = True output_format = "%%(%s)s" % ")s\t%(".join(formatting.validate_field_list(output_format, allow_fmt_specs=True)) # Replace some escape sequences output_format = (output_format .replace(r"\\", "\\") .replace(r"\n", "\n") .replace(r"\t", "\t") .replace(r"\$", "\0") # the next 3 allow using $() instead of %() .replace("$(", "%(") .replace("\0", "$") .replace(r"\ ", " ") # to prevent stripping in config file #.replace(r"\", "\") ) self.options.output_format = formatting.preparse(output_format)
[ "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", "# Check if it's a custom output format from configuration", "# (they take precedence over field names, so name them wisely)", "output_format", "=", "config", ".", "formats", ".", "get", "(", "output_format", ",", "output_format", ")", "# Expand plain field list to usable form", "if", "re", ".", "match", "(", "r\"^[,._0-9a-zA-Z]+$\"", ",", "output_format", ")", ":", "self", ".", "plain_output_format", "=", "True", "output_format", "=", "\"%%(%s)s\"", "%", "\")s\\t%(\"", ".", "join", "(", "formatting", ".", "validate_field_list", "(", "output_format", ",", "allow_fmt_specs", "=", "True", ")", ")", "# Replace some escape sequences", "output_format", "=", "(", "output_format", ".", "replace", "(", "r\"\\\\\"", ",", "\"\\\\\"", ")", ".", "replace", "(", "r\"\\n\"", ",", "\"\\n\"", ")", ".", "replace", "(", "r\"\\t\"", ",", "\"\\t\"", ")", ".", "replace", "(", "r\"\\$\"", ",", "\"\\0\"", ")", "# the next 3 allow using $() instead of %()", ".", "replace", "(", "\"$(\"", ",", "\"%(\"", ")", ".", "replace", "(", "\"\\0\"", ",", "\"$\"", ")", ".", "replace", "(", "r\"\\ \"", ",", "\" \"", ")", "# to prevent stripping in config file", "#.replace(r\"\\\", \"\\\")", ")", "self", ".", "options", ".", "output_format", "=", "formatting", ".", "preparse", "(", "output_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(None)).split()) # Validate result result = [] for name in emit_fields[:]: if name not in engine.FieldDefinition.FIELDS: self.LOG.warn("Omitted unknown name '%s' from statistics and output format sorting" % name) else: result.append(name) return result
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(None)).split()) # Validate result result = [] for name in emit_fields[:]: if name not in engine.FieldDefinition.FIELDS: self.LOG.warn("Omitted unknown name '%s' from statistics and output format sorting" % name) else: result.append(name) return result
[ "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", ".", "sub", "(", "r\"[^_A-Z]+\"", ",", "' '", ",", "self", ".", "format_item", "(", "None", ")", ")", ".", "split", "(", ")", ")", "# Validate result", "result", "=", "[", "]", "for", "name", "in", "emit_fields", "[", ":", "]", ":", "if", "name", "not", "in", "engine", ".", "FieldDefinition", ".", "FIELDS", ":", "self", ".", "LOG", ".", "warn", "(", "\"Omitted unknown name '%s' from statistics and output format sorting\"", "%", "name", ")", "else", ":", "result", ".", "append", "(", "name", ")", "return", "result" ]
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", "(", ")", "return", "formatting", ".", "validate_sort_fields", "(", "sort_fields", "or", "config", ".", "sort_fields", ")" ]
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 ', removing from' if remove else ' into' targetname = config.engine.show(matches, targetname or self.options.to_view or "rtcontrol", append=append, disjoin=remove) msg = "Filtered %d out of %d torrents using [ %s ]" % ( len(matches), sourceview.size(), sourceview.matcher) self.LOG.info("%s%s rTorrent view %r." % (msg, action_name, targetname)) config.engine.log(msg)
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 ', removing from' if remove else ' into' targetname = config.engine.show(matches, targetname or self.options.to_view or "rtcontrol", append=append, disjoin=remove) msg = "Filtered %d out of %d torrents using [ %s ]" % ( len(matches), sourceview.size(), sourceview.matcher) self.LOG.info("%s%s rTorrent view %r." % (msg, action_name, targetname)) config.engine.log(msg)
[ "def", "show_in_view", "(", "self", ",", "sourceview", ",", "matches", ",", "targetname", "=", "None", ")", ":", "append", "=", "self", ".", "options", ".", "append_view", "or", "self", ".", "options", ".", "alter_view", "==", "'append'", "remove", "=", "self", ".", "options", ".", "alter_view", "==", "'remove'", "action_name", "=", "', appending to'", "if", "append", "else", "', removing from'", "if", "remove", "else", "' into'", "targetname", "=", "config", ".", "engine", ".", "show", "(", "matches", ",", "targetname", "or", "self", ".", "options", ".", "to_view", "or", "\"rtcontrol\"", ",", "append", "=", "append", ",", "disjoin", "=", "remove", ")", "msg", "=", "\"Filtered %d out of %d torrents using [ %s ]\"", "%", "(", "len", "(", "matches", ")", ",", "sourceview", ".", "size", "(", ")", ",", "sourceview", ".", "matcher", ")", "self", ".", "LOG", ".", "info", "(", "\"%s%s rTorrent view %r.\"", "%", "(", "msg", ",", "action_name", ",", "targetname", ")", ")", "config", ".", "engine", ".", "log", "(", "msg", ")" ]
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