desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Adds `state` (IOLoop.{READ,WRITE} flags) to our event handler. Implementation notes: Reads and writes have a fast path and a slow path. The fast path reads synchronously from socket buffers, while the slow path uses `_add_io_state` to schedule an IOLoop callback. Note that in both cases, the callback is run asynchro...
def _add_io_state(self, state):
if self.closed(): return if (self._state is None): self._state = (ioloop.IOLoop.ERROR | state) with stack_context.NullContext(): self.io_loop.add_handler(self.fileno(), self._handle_events, self._state) elif (not (self._state & state)): self._state = (self._state ...
'Return true if exc is ECONNRESET or equivalent. May be overridden in subclasses.'
def _is_connreset(self, exc):
return (isinstance(exc, (socket.error, IOError)) and (errno_from_exception(exc) in _ERRNO_CONNRESET))
'Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is in the same format as for `socket.connect <socket.socket.connect>` for the type of socket passed to the IOStream constructor, e.g. an ``(ip, port)...
def connect(self, address, callback=None, server_hostname=None):
self._connecting = True if (callback is not None): self._connect_callback = stack_context.wrap(callback) future = None else: future = self._connect_future = TracebackFuture() try: self.socket.connect(address) except socket.error as e: if ((errno_from_exception...
'Convert this `IOStream` to an `SSLIOStream`. This enables protocols that begin in clear-text mode and switch to SSL after some initial negotiation (such as the ``STARTTLS`` extension to SMTP and IMAP). This method cannot be used if there are outstanding reads or writes on the stream, or if there is any data in the IOS...
def start_tls(self, server_side, ssl_options=None, server_hostname=None):
if (self._read_callback or self._read_future or self._write_callback or self._write_futures or self._connect_callback or self._connect_future or self._pending_callbacks or self._closed or self._read_buffer or self._write_buffer): raise ValueError('IOStream is not idle; cannot convert to ...
'The ``ssl_options`` keyword argument may either be an `ssl.SSLContext` object or a dictionary of keywords arguments for `ssl.wrap_socket`'
def __init__(self, *args, **kwargs):
self._ssl_options = kwargs.pop('ssl_options', _client_ssl_defaults) super(SSLIOStream, self).__init__(*args, **kwargs) self._ssl_accepting = True self._handshake_reading = False self._handshake_writing = False self._ssl_connect_callback = None self._server_hostname = None try: se...
'Returns True if peercert is valid according to the configured validation mode and hostname. The ssl handshake already tested the certificate for a valid CA signature; the only thing that remains is to check the hostname.'
def _verify_cert(self, peercert):
if isinstance(self._ssl_options, dict): verify_mode = self._ssl_options.get('cert_reqs', ssl.CERT_NONE) elif isinstance(self._ssl_options, ssl.SSLContext): verify_mode = self._ssl_options.verify_mode assert (verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL)) if ((verif...
'Wait for the initial SSL handshake to complete. If a ``callback`` is given, it will be called with no arguments once the handshake is complete; otherwise this method returns a `.Future` which will resolve to the stream itself after the handshake is complete. Once the handshake is complete, information such as the peer...
def wait_for_handshake(self, callback=None):
if ((self._ssl_connect_callback is not None) or (self._ssl_connect_future is not None)): raise RuntimeError('Already waiting') if (callback is not None): self._ssl_connect_callback = stack_context.wrap(callback) future = None else: future = self._ssl_connect_future = Trace...
'Parse the first line of a GNTP message to get security and other info values @param data: GNTP Message @return: GNTP Message information in a dictionary'
def parse_info(self, data):
match = re.match((('GNTP/(?P<version>\\d+\\.\\d+) (?P<messagetype>REGISTER|NOTIFY|SUBSCRIBE|\\-OK|\\-ERROR)' + ' (?P<encryptionAlgorithmID>[A-Z0-9]+(:(?P<ivValue>[A-F0-9]+))?) ?') + '((?P<keyHashAlgorithmID>[A-Z0-9]+):(?P<keyHash>[A-F0-9]+).(?P<salt>[A-F0-9]+))?\r\n'), data, re.IGNORECASE) if (not matc...
'Set a password for a GNTP Message @param password: Null to clear password @param encryptAlgo: Currently only supports MD5 @todo: Support other hash functions'
def set_password(self, password, encryptAlgo='MD5'):
self.password = password if (not password): self.info['encryptionAlgorithmID'] = None self.info['keyHashAlgorithm'] = None return password = password.encode('utf8') seed = time.ctime() salt = hashlib.md5(seed).hexdigest() saltHash = hashlib.md5(seed).digest() keyBasis...
'Helper function to decode hex string to `proper` hex string @param value: Value to decode @return: Hex string'
def _decode_hex(self, value):
result = '' for i in range(0, len(value), 2): tmp = int(value[i:(i + 2)], 16) result += chr(tmp) return result
'Validate GNTP Message against stored password'
def validate_password(self, password):
self.password = password if (password == None): raise Exception() keyHash = self.info.get('keyHash', None) if ((keyHash is None) and (self.password is None)): return True if (keyHash is None): raise AuthError('Invalid keyHash') if (self.password is None): raise...
'Verify required headers'
def validate(self):
for header in self.requiredHeaders: if (not self.headers.get(header, False)): raise ParseError(('Missing Notification Header: ' + header))
'Generate info line for GNTP Message @return: Info line string'
def format_info(self):
info = (u'GNTP/%s %s' % (self.info.get('version'), self.info.get('messagetype'))) if self.info.get('encryptionAlgorithmID', None): info += (' %s:%s' % (self.info.get('encryptionAlgorithmID'), self.info.get('ivValue'))) else: info += ' NONE' if self.info.get('keyHashAlgorithmID',...
'Helper function to parse blocks of GNTP headers into a dictionary @param data: @return: Dictionary of headers'
def parse_dict(self, data):
dict = {} for line in data.split('\r\n'): match = re.match('([\\w-]+):(.+)', line) if (not match): continue key = match.group(1).strip() val = match.group(2).strip() dict[key] = val return dict
'Decode GNTP Message @param data:'
def decode(self, data, password=None):
self.password = password self.raw = data parts = self.raw.split('\r\n\r\n') self.info = self.parse_info(data) self.headers = self.parse_dict(parts[0])
'Encode a GNTP Message @return: GNTP Message ready to be sent'
def encode(self):
self.validate() SEP = u': ' EOL = u'\r\n' message = (self.format_info() + EOL) for (k, v) in self.headers.iteritems(): message += (((k.encode('utf8') + SEP) + str(v).encode('utf8')) + EOL) message += EOL return message
'@param data: (Optional) See decode() @param password: (Optional) Password to use while encoding/decoding messages'
def __init__(self, data=None, password=None):
_GNTPBase.__init__(self, 'REGISTER') self.notifications = [] self.resources = {} self.requiredHeaders = ['Application-Name', 'Notifications-Count'] self.requiredNotification = ['Notification-Name'] if data: self.decode(data, password) else: self.set_password(password) ...
'Validate required headers and validate notification headers'
def validate(self):
for header in self.requiredHeaders: if (not self.headers.get(header, False)): raise ParseError(('Missing Registration Header: ' + header)) for notice in self.notifications: for header in self.requiredNotification: if (not notice.get(header, False)): ...
'Decode existing GNTP Registration message @param data: Message to decode.'
def decode(self, data, password):
self.raw = data parts = self.raw.split('\r\n\r\n') self.info = self.parse_info(data) self.validate_password(password) self.headers = self.parse_dict(parts[0]) for (i, part) in enumerate(parts): if (i == 0): continue if (part.strip() == ''): continue ...
'Add new Notification to Registration message @param name: Notification Name @param enabled: Default Notification to Enabled'
def add_notification(self, name, enabled=True):
notice = {} notice['Notification-Name'] = name notice['Notification-Enabled'] = str(enabled) self.notifications.append(notice) self.headers['Notifications-Count'] = len(self.notifications)
'Encode a GNTP Registration Message @return: GNTP Registration Message ready to be sent'
def encode(self):
self.validate() SEP = u': ' EOL = u'\r\n' message = (self.format_info() + EOL) for (k, v) in self.headers.iteritems(): message += (((k.encode('utf8') + SEP) + str(v).encode('utf8')) + EOL) if (len(self.notifications) > 0): for notice in self.notifications: message ...
'@param data: (Optional) See decode() @param app: (Optional) Set Application-Name @param name: (Optional) Set Notification-Name @param title: (Optional) Set Notification Title @param password: (Optional) Password to use while encoding/decoding messages'
def __init__(self, data=None, app=None, name=None, title=None, password=None):
_GNTPBase.__init__(self, 'NOTIFY') self.resources = {} self.requiredHeaders = ['Application-Name', 'Notification-Name', 'Notification-Title'] if data: self.decode(data, password) else: self.set_password(password) if app: self.headers['Application-Name'] = app ...
'Decode existing GNTP Notification message @param data: Message to decode.'
def decode(self, data, password):
self.raw = data parts = self.raw.split('\r\n\r\n') self.info = self.parse_info(data) self.validate_password(password) self.headers = self.parse_dict(parts[0]) for (i, part) in enumerate(parts): if (i == 0): continue if (part.strip() == ''): continue ...
'Encode a GNTP Notification Message @return: GNTP Notification Message ready to be sent'
def encode(self):
self.validate() SEP = u': ' EOL = u'\r\n' message = (self.format_info() + EOL) for (k, v) in self.headers.iteritems(): message += (((k + SEP) + unicode(v)) + EOL) message += EOL return message.encode('utf-8')
'@param data: (Optional) See _GNTPResponse.decode() @param action: (Optional) Set type of action the OK Response is for'
def __init__(self, data=None, action=None):
_GNTPBase.__init__(self, '-OK') self.requiredHeaders = ['Response-Action'] if data: self.decode(data) if action: self.headers['Response-Action'] = action self.add_origin_info()
'@param data: (Optional) See _GNTPResponse.decode() @param errorcode: (Optional) Error code @param errordesc: (Optional) Error Description'
def __init__(self, data=None, errorcode=None, errordesc=None):
_GNTPBase.__init__(self, '-ERROR') self.requiredHeaders = ['Error-Code', 'Error-Description'] if data: self.decode(data) if errorcode: self.headers['Error-Code'] = errorcode self.headers['Error-Description'] = errordesc self.add_origin_info()
'Initializes a new ThreadPoolExecutor instance. Args: max_workers: The maximum number of threads that can be used to execute the given calls.'
def __init__(self, max_workers=None):
if (max_workers is None): max_workers = ((cpu_count() or 1) * 5) if (max_workers <= 0): raise ValueError('max_workers must be greater than 0') self._max_workers = max_workers self._work_queue = queue.Queue() self._threads = set() self._shutdown = False self._sh...
'Initializes the future. Should not be called by clients.'
def __init__(self):
self._condition = threading.Condition() self._state = PENDING self._result = None self._exception = None self._traceback = None self._waiters = [] self._done_callbacks = []
'Cancel the future if possible. Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed.'
def cancel(self):
with self._condition: if (self._state in [RUNNING, FINISHED]): return False if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]): return True self._state = CANCELLED self._condition.notify_all() self._invoke_callbacks() return True
'Return True if the future has cancelled.'
def cancelled(self):
with self._condition: return (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED])
'Return True if the future is currently executing.'
def running(self):
with self._condition: return (self._state == RUNNING)
'Return True of the future was cancelled or finished executing.'
def done(self):
with self._condition: return (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED])
'Attaches a callable that will be called when the future finishes. Args: fn: A callable that will be called with this future as its only argument when the future completes or is cancelled. The callable will always be called by a thread in the same process in which it was added. If the future has already completed or be...
def add_done_callback(self, fn):
with self._condition: if (self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]): self._done_callbacks.append(fn) return fn(self)
'Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn\'t done. If None, then there is no limit on the wait time. Returns: The result of the call that the future represents. Raises: CancelledError: If the future was cancelled. TimeoutErro...
def result(self, timeout=None):
with self._condition: if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]): raise CancelledError() elif (self._state == FINISHED): return self.__get_result() self._condition.wait(timeout) if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]): ...
'Return a tuple of (exception, traceback) raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn\'t done. If None, then there is no limit on the wait time. Returns: The exception raised by the call that the future represents or None if the call co...
def exception_info(self, timeout=None):
with self._condition: if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]): raise CancelledError() elif (self._state == FINISHED): return (self._exception, self._traceback) self._condition.wait(timeout) if (self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]...
'Return the exception raised by the call that the future represents. Args: timeout: The number of seconds to wait for the exception if the future isn\'t done. If None, then there is no limit on the wait time. Returns: The exception raised by the call that the future represents or None if the call completed without rais...
def exception(self, timeout=None):
return self.exception_info(timeout)[0]
'Mark the future as running or process any cancel notifications. Should only be used by Executor implementations and unit tests. If the future has been cancelled (cancel() was called and returned True) then any threads waiting on the future completing (though calls to as_completed() or wait()) are notified and False is...
def set_running_or_notify_cancel(self):
with self._condition: if (self._state == CANCELLED): self._state = CANCELLED_AND_NOTIFIED for waiter in self._waiters: waiter.add_cancelled(self) return False elif (self._state == PENDING): self._state = RUNNING return True ...
'Sets the return value of work associated with the future. Should only be used by Executor implementations and unit tests.'
def set_result(self, result):
with self._condition: self._result = result self._state = FINISHED for waiter in self._waiters: waiter.add_result(self) self._condition.notify_all() self._invoke_callbacks()
'Sets the result of the future as being the given exception and traceback. Should only be used by Executor implementations and unit tests.'
def set_exception_info(self, exception, traceback):
with self._condition: self._exception = exception self._traceback = traceback self._state = FINISHED for waiter in self._waiters: waiter.add_exception(self) self._condition.notify_all() self._invoke_callbacks()
'Sets the result of the future as being the given exception. Should only be used by Executor implementations and unit tests.'
def set_exception(self, exception):
self.set_exception_info(exception, None)
'Submits a callable to be executed with the given arguments. Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. Returns: A Future representing the given call.'
def submit(self, fn, *args, **kwargs):
raise NotImplementedError()
'Returns a iterator equivalent to map(fn, iter). Args: fn: A callable that will take as many arguments as there are passed iterables. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. Returns: An iterator equivalent to: map(func, *iterables) but the calls may be evaluated...
def map(self, fn, *iterables, **kwargs):
timeout = kwargs.get('timeout') if (timeout is not None): end_time = (timeout + time.time()) fs = [self.submit(fn, *args) for args in itertools.izip(*iterables)] def result_iterator(): try: for future in fs: if (timeout is None): (yield fut...
'Clean-up the resources associated with the Executor. It is safe to call this method several times. Otherwise, no other methods can be called after this one. Args: wait: If True then shutdown will not return until all running futures have finished executing and the resources used by the executor have been reclaimed.'
def shutdown(self, wait=True):
pass
'Initializes a new ProcessPoolExecutor instance. Args: max_workers: The maximum number of processes that can be used to execute the given calls. If None or not given then as many worker processes will be created as the machine has processors.'
def __init__(self, max_workers=None):
_check_system_limits() if (max_workers is None): self._max_workers = multiprocessing.cpu_count() else: if (max_workers <= 0): raise ValueError('max_workers must be greater than 0') self._max_workers = max_workers self._call_queue = multiprocessing.Queue...
':return: A :class:`FeedParserDict`.'
def __getitem__(self, key):
if (key == u'category'): try: return dict.__getitem__(self, u'tags')[0][u'term'] except IndexError: raise KeyError(u"object doesn't have key 'category'") elif (key == u'enclosures'): norel = (lambda link: FeedParserDict([(name, value) for (name, value)...
':return: A :class:`FeedParserDict`.'
def get(self, key, default=None):
try: return self.__getitem__(key) except KeyError: return default
'Return processed HTML as a single string'
def output(self):
return u''.join(self.pieces)
'Search all episodes in show. Can search all data, or a specific key (for example, episodename) Always returns an array (can be empty). First index contains the first match, and so on. Each array index is an Episode() instance, so doing search_results[0][b\'episodename\'] will retrieve the episode name of the first mat...
def search(self, term=None, key=None):
results = [] for cur_season in self.values(): searchresult = cur_season.search(term=term, key=key) if (len(searchresult) != 0): results.extend(searchresult) return results
'The show attribute points to the parent show'
def __init__(self, show=None):
self.show = show
'Search all episodes in season, returns a list of matching Episode instances. >>> t = Tvdb() >>> t[\'scrubs\'][1].search(\'first day\') [<Episode 01x01 - My First Day>] See Show.search documentation for further information on search'
def search(self, term=None, key=None):
results = [] for ep in self.values(): searchresult = ep.search(term=term, key=key) if (searchresult is not None): results.append(searchresult) return results
'The season attribute points to the parent season'
def __init__(self, season=None):
self.season = season
'Search episode data for term, if it matches, return the Episode (self). The key parameter can be used to limit the search to a specific element, for example, episodename. This primarily for use use by Show.search and Season.search. See Show.search for further information on search Simple example: >>> e = Episode() >>>...
def search(self, term=None, key=None):
if (term == None): raise TypeError('must supply string to search for (contents)') term = unicode(term).lower() for (cur_key, cur_value) in self.items(): (cur_key, cur_value) = (unicode(cur_key).lower(), unicode(cur_value).lower()) if ((key is not None) and (cur_key ...
'interactive (True/False): When True, uses built-in console UI is used to select the correct show. When False, the first search result is used. select_first (True/False): Automatically selects the first series search result (rather than showing the user a list of more than one series). Is overridden by interactive = Fa...
def __init__(self, interactive=False, select_first=False, debug=False, cache=True, banners=False, actors=False, custom_ui=None, language=None, search_all_languages=False, apikey=None, forceConnect=False, useZip=False, dvdorder=False, proxy=None):
self.shows = ShowContainer() self.corrections = {} self.config = {} if (apikey is not None): self.config['apikey'] = apikey else: self.config['apikey'] = '0629B785CE550C8D' self.config['debug_enabled'] = debug self.config['custom_ui'] = custom_ui self.config['interactive'...
'Returns the [system temp dir]/tvdb_api-u501 (or tvdb_api-myuser)'
def _getTempDir(self):
if hasattr(os, 'getuid'): uid = ('u%d' % os.getuid()) else: try: uid = getpass.getuser() except ImportError: return os.path.join(tempfile.gettempdir(), 'tvdb_api') return os.path.join(tempfile.gettempdir(), ('tvdb_api-%s' % uid))
'Loads a URL using caching, returns an ElementTree of the source'
def _getetsrc(self, url, params=None, language=None):
try: return self._loadUrl(url, params=params, language=language).values()[0] except Exception as e: raise tvdb_error(e)
'Creates a new episode, creating Show(), Season() and Episode()s as required. Called by _getShowData to populate show Since the nice-to-use tvdb[1][24][\'name] interface makes it impossible to do tvdb[1][24][\'name] = "name" and still be capable of checking if an episode exists so we can raise tvdb_shownotfound, we hav...
def _setItem(self, sid, seas, ep, attrib, value):
if (sid not in self.shows): self.shows[sid] = Show() if (seas not in self.shows[sid]): self.shows[sid][seas] = Season(show=self.shows[sid]) if (ep not in self.shows[sid][seas]): self.shows[sid][seas][ep] = Episode(season=self.shows[sid][seas]) self.shows[sid][seas][ep][attrib] = ...
'Sets self.shows[sid] to a new Show instance, or sets the data'
def _setShowData(self, sid, key, value):
if (sid not in self.shows): self.shows[sid] = Show() self.shows[sid].data[key] = value
'Cleans up strings returned by TheTVDB.com Issues corrected: - Replaces &amp; with & - Trailing whitespace'
def _cleanData(self, data):
data = unicode(data).replace(u'&amp;', u'&') data = data.strip() return data
'This searches TheTVDB.com for the series name and returns the result list'
def search(self, series):
series = series.encode('utf-8') log().debug(('Searching for show %s' % series)) self.config['params_getSeries']['seriesname'] = series results = self._getetsrc(self.config['url_getSeries'], self.config['params_getSeries']) if (not results): return return results.values()[0]
'This searches TheTVDB.com for the series name, If a custom_ui UI is configured, it uses this to select the correct series. If not, and interactive == True, ConsoleUI is used, if not BaseUI is used to select the first result.'
def _getSeries(self, series):
allSeries = self.search(series) if (not allSeries): log().debug('Series result returned zero') raise tvdb_shownotfound('Show search returned zero results (cannot find show on TVDB)') if (not isinstance(allSeries, list)): allSeries = [allSeries] ...
'Parses banners XML, from http://thetvdb.com/api/[APIKEY]/series/[SERIES ID]/banners.xml Banners are retrieved using t[\'show name][\'_banners\'], for example: >>> t = Tvdb(banners = True) >>> t[\'scrubs\'][\'_banners\'].keys() [\'fanart\', \'poster\', \'series\', \'season\'] >>> t[\'scrubs\'][\'_banners\'][\'poster\']...
def _parseBanners(self, sid):
log().debug(('Getting season banners for %s' % sid)) bannersEt = self._getetsrc((self.config['url_seriesBanner'] % sid)) if (not bannersEt): log().debug('Banners result returned zero') return banners = {} for cur_banner in (bannersEt['banner'] if isinstance(banne...
'Parsers actors XML, from http://thetvdb.com/api/[APIKEY]/series/[SERIES ID]/actors.xml Actors are retrieved using t[\'show name][\'_actors\'], for example: >>> t = Tvdb(actors = True) >>> actors = t[\'scrubs\'][\'_actors\'] >>> type(actors) <class \'tvdb_api.Actors\'> >>> type(actors[0]) <class \'tvdb_api.Actor\'> >>>...
def _parseActors(self, sid):
log().debug(('Getting actors for %s' % sid)) actorsEt = self._getetsrc((self.config['url_actorsInfo'] % sid)) if (not actorsEt): log().debug('Actors result returned zero') return cur_actors = Actors() for cur_actor in (actorsEt['actor'] if isinstance(actorsEt['actor...
'Takes a series ID, gets the epInfo URL and parses the TVDB XML file into the shows dict in layout: shows[series_id][season_number][episode_number]'
def _getShowData(self, sid, language, getEpInfo=False):
if (self.config['language'] is None): log().debug('Config language is none, using show language') if (language is None): raise tvdb_error("config['language'] was None, this should not happen") getShowInLanguage = language else: log(...
'Takes show name, returns the correct series ID (if the show has already been grabbed), or grabs all episodes and returns the correct SID.'
def _nameToSid(self, name):
if (name in self.corrections): log().debug(('Correcting %s to %s' % (name, self.corrections[name]))) return self.corrections[name] else: log().debug(('Getting show %s' % name)) selected_series = self._getSeries(name) if isinstance(selected_series, dict): ...
'Handles tvdb_instance[\'seriesname\'] calls. The dict index should be the show id'
def __getitem__(self, key):
if isinstance(key, (int, long)): if (key not in self.shows): self._getShowData(key, self.config['language'], True) return self.shows[key] key = str(key).lower() self.config['searchterm'] = key selected_series = self._getSeries(key) if isinstance(selected_series, dict): ...
'The location of the cache directory'
@locked_function def __init__(self, cache_location, max_age=21600):
self.max_age = max_age self.cache_location = cache_location if (not os.path.exists(self.cache_location)): try: os.mkdir(self.cache_location) except OSError as e: if ((e.errno == errno.EEXIST) and os.path.isdir(self.cache_location)): pass el...
'Handles GET requests, if the response is cached it returns it'
def default_open(self, request):
if (request.get_method() != 'GET'): return None if exists_in_cache(self.cache_location, request.get_full_url(), self.max_age): return CachedResponse(self.cache_location, request.get_full_url(), set_cache_header=True) else: return None
'Gets a HTTP response, if it was a GET request and the status code starts with 2 (200 OK etc) it caches it and returns a CachedResponse'
def http_response(self, request, response):
if ((request.get_method() == 'GET') and str(response.code).startswith('2')): if ('x-local-cache' not in response.info()): set_cache_header = store_in_cache(self.cache_location, request.get_full_url(), response) else: set_cache_header = True return CachedResponse(self....
'Returns headers'
def info(self):
return self.headers
'Returns original URL'
def geturl(self):
return self.url
'Helper function, lists series with corresponding ID'
def _displaySeries(self, allSeries, limit=6):
if (limit is not None): toshow = allSeries[:limit] else: toshow = allSeries print 'TVDB Search Results:' for (i, cshow) in enumerate(toshow): i_show = (i + 1) log().debug(('Showing allSeries[%s], series %s)' % (i_show, allSeries[i]['seriesname']))) ...
'Creates a profiler for a function. Every profiler has its own log file (the name of which is derived from the function name). FuncProfile registers an atexit handler that prints profiling information to sys.stderr when the program terminates.'
def __init__(self, fn, skip=0, filename=None, immediate=False, dirs=False, sort=None, entries=40):
self.fn = fn self.skip = skip self.filename = filename self.immediate = immediate self.dirs = dirs self.sort = (sort or ('cumulative', 'time', 'calls')) if isinstance(self.sort, str): self.sort = (self.sort,) self.entries = entries self.reset_stats() atexit.register(self....
'Profile a singe call to the function.'
def __call__(self, *args, **kw):
self.ncalls += 1 if (self.skip > 0): self.skip -= 1 self.skipped += 1 return self.fn(*args, **kw) if FuncProfile.in_profiler: return self.fn(*args, **kw) profiler = self.Profile() try: FuncProfile.in_profiler = True return profiler.runcall(self.fn, *ar...
'Print profile information to sys.stdout.'
def print_stats(self):
funcname = self.fn.__name__ filename = self.fn.func_code.co_filename lineno = self.fn.func_code.co_firstlineno print print '*** PROFILER RESULTS ***' print ('%s (%s:%s)' % (funcname, filename, lineno)) print ('function called %d times' % self.ncalls), if self.skipped...
'Reset accumulated profiler statistics.'
def reset_stats(self):
self.stats = pstats.Stats(Profile()) self.ncalls = 0 self.skipped = 0
'Stop profiling and print profile information to sys.stdout. This function is registered as an atexit hook.'
def atexit(self):
if (not self.immediate): self.print_stats()
'Creates a profiler for a function. Every profiler has its own log file (the name of which is derived from the function name). TraceFuncCoverage registers an atexit handler that prints profiling information to sys.stderr when the program terminates. The log file is not removed and remains there to clutter the current w...
def __init__(self, fn):
self.fn = fn self.logfilename = (fn.__name__ + '.cprof') self.ncalls = 0 atexit.register(self.atexit)
'Profile a singe call to the function.'
def __call__(self, *args, **kw):
self.ncalls += 1 if TraceFuncCoverage.tracing: return self.fn(*args, **kw) try: TraceFuncCoverage.tracing = True return self.tracer.runfunc(self.fn, *args, **kw) finally: TraceFuncCoverage.tracing = False
'Stop profiling and print profile information to sys.stderr. This function is registered as an atexit hook.'
def atexit(self):
funcname = self.fn.__name__ filename = self.fn.func_code.co_filename lineno = self.fn.func_code.co_firstlineno print print '*** COVERAGE RESULTS ***' print ('%s (%s:%s)' % (funcname, filename, lineno)) print ('function called %d times' % self.ncalls) print fs = F...
'Mark all executable source lines in fn as executed 0 times.'
def find_source_lines(self):
strs = trace.find_strings(self.filename) lines = trace.find_lines_from_code(self.fn.func_code, strs) self.firstcodelineno = sys.maxint for lineno in lines: self.firstcodelineno = min(self.firstcodelineno, lineno) self.sourcelines.setdefault(lineno, 0) if (self.firstcodelineno == sys....
'Mark a given source line as executed count times. Multiple calls to mark for the same lineno add up.'
def mark(self, lineno, count=1):
self.sourcelines[lineno] = (self.sourcelines.get(lineno, 0) + count)
'Count statements that were never executed.'
def count_never_executed(self):
lineno = self.firstlineno counter = 0 for line in self.source: if (self.sourcelines.get(lineno) == 0): if (not self.blank_rx.match(line)): counter += 1 lineno += 1 return counter
'Return annotated source code for the function.'
def __str__(self):
lines = [] lineno = self.firstlineno for line in self.source: counter = self.sourcelines.get(lineno) if (counter is None): prefix = (' ' * 7) elif (counter == 0): if self.blank_rx.match(line): prefix = (' ' * 7) else: ...
'Profile a singe call to the function.'
def __call__(self, *args, **kw):
fn = self.fn timer = self.timer self.ncalls += 1 try: start = timer() return fn(*args, **kw) finally: duration = (timer() - start) self.totaltime += duration if self.immediate: funcname = fn.__name__ filename = fn.func_code.co_filename ...
'Changes anything not dundered or not a descriptor. If a descriptor is added with the same name as an enum member, the name is removed from _member_names (this may leave a hole in the numerical sequence of values). If an enum member name is used twice, an error is raised; duplicate values are not checked for. Single un...
def __setitem__(self, key, value):
if ((pyver >= 3.0) and (key == '__order__')): return if _is_sunder(key): raise ValueError('_names_ are reserved for future Enum use') elif _is_dunder(key): pass elif (key in self._member_names): raise TypeError(('Attempted to reuse key: %r' %...
'Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum(\'Color\', names=\'red green blue\')). When used for the functional API: `module`, if set, will be...
def __call__(cls, value, names=None, module=None, type=None):
if (names is None): return cls.__new__(cls, value) return cls._create_(value, names, module=module, type=type)
'Returns a mapping of member name->value. This mapping lists all enum members, including aliases. Note that this is a copy of the internal mapping.'
@property def __members__(cls):
return cls._member_map_.copy()
'Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class\' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class\' __dict__) and enum members themselves.'
def __getattr__(cls, name):
if _is_dunder(name): raise AttributeError(name) try: return cls._member_map_[name] except KeyError: raise AttributeError(name)
'Block attempts to reassign Enum members. A simple assignment to the class namespace only changes one of the several possible ways to get an Enum member from the Enum class, resulting in an inconsistent Enumeration.'
def __setattr__(cls, name, value):
member_map = cls.__dict__.get('_member_map_', {}) if (name in member_map): raise AttributeError('Cannot reassign members.') super(EnumMeta, cls).__setattr__(name, value)
'Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are auto-numbered from 1. * An iterable of member names. Values are auto-numbered from 1. * An iterable of (member name, value) pairs. * A mapping of member name -> value....
def _create_(cls, class_name, names=None, module=None, type=None):
if (pyver < 3.0): if isinstance(class_name, unicode): try: class_name = class_name.encode('ascii') except UnicodeEncodeError: raise TypeError(('%r is not representable in ASCII' % class_name)) metacls = cls.__class__ if (type is ...
'Returns the type for creating enum members, and the first inherited enum class. bases: the tuple of bases that was given to __new__'
@staticmethod def _get_mixins_(bases):
if ((not bases) or (Enum is None)): return (object, Enum) member_type = first_enum = None for base in bases: if ((base is not Enum) and issubclass(base, Enum) and base._member_names_): raise TypeError('Cannot extend enumerations') if (not issubclass(base, Enum)): ...
'Changes anything not dundered or not a descriptor. If a descriptor is added with the same name as an enum member, the name is removed from _member_names (this may leave a hole in the numerical sequence of values). If an enum member name is used twice, an error is raised; duplicate values are not checked for. Single un...
def __setitem__(self, key, value):
if ((pyver >= 3.0) and (key == '__order__')): return if _is_sunder(key): raise ValueError('_names_ are reserved for future Enum use') elif _is_dunder(key): pass elif (key in self._member_names): raise TypeError(('Attempted to reuse key: %r' %...
'Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum(\'Color\', names=\'red green blue\')). When used for the functional API: `module`, if set, will be...
def __call__(cls, value, names=None, module=None, type=None):
if (names is None): return cls.__new__(cls, value) return cls._create_(value, names, module=module, type=type)
'Returns a mapping of member name->value. This mapping lists all enum members, including aliases. Note that this is a copy of the internal mapping.'
@property def __members__(cls):
return cls._member_map_.copy()
'Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class\' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class\' __dict__) and enum members themselves.'
def __getattr__(cls, name):
if _is_dunder(name): raise AttributeError(name) try: return cls._member_map_[name] except KeyError: raise AttributeError(name)
'Block attempts to reassign Enum members. A simple assignment to the class namespace only changes one of the several possible ways to get an Enum member from the Enum class, resulting in an inconsistent Enumeration.'
def __setattr__(cls, name, value):
member_map = cls.__dict__.get('_member_map_', {}) if (name in member_map): raise AttributeError('Cannot reassign members.') super(EnumMeta, cls).__setattr__(name, value)
'Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are auto-numbered from 1. * An iterable of member names. Values are auto-numbered from 1. * An iterable of (member name, value) pairs. * A mapping of member name -> value....
def _create_(cls, class_name, names=None, module=None, type=None):
if (pyver < 3.0): if isinstance(class_name, unicode): try: class_name = class_name.encode('ascii') except UnicodeEncodeError: raise TypeError(('%r is not representable in ASCII' % class_name)) metacls = cls.__class__ if (type is ...
'Returns the type for creating enum members, and the first inherited enum class. bases: the tuple of bases that was given to __new__'
@staticmethod def _get_mixins_(bases):
if ((not bases) or (Enum is None)): return (object, Enum) member_type = first_enum = None for base in bases: if ((base is not Enum) and issubclass(base, Enum) and base._member_names_): raise TypeError('Cannot extend enumerations') if (not issubclass(base, Enum)): ...
'Convert the given text.'
def convert(self, text):
self.reset() if (not isinstance(text, unicode)): text = unicode(text, 'utf-8') if self.use_file_vars: emacs_vars = self._get_emacs_vars(text) if ('markdown-extras' in emacs_vars): splitter = re.compile('[ ,]+') for e in splitter.split(emacs_vars['markdown-e...
'A hook for subclasses to do some postprocessing of the html, if desired. This is called before unescaping of special chars and unhashing of raw HTML spans.'
def postprocess(self, text):
return text