code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
token = self.get() if not token.is_eol_or_eof(): raise dns.exception.SyntaxError('expected EOL or EOF, got %d "%s"' % (token.ttype, token.value)) return token.value
def get_eol(self)
Read the next token and raise an exception if it isn't EOL or EOF. @raises dns.exception.SyntaxError: @rtype: string
5.054842
3.275671
1.543147
if len(rdatas) == 0: raise ValueError("rdata list must not be empty") r = None for rd in rdatas: if r is None: r = Rdataset(rd.rdclass, rd.rdtype) r.update_ttl(ttl) first_time = False r.add(rd) return r
def from_rdata_list(ttl, rdatas)
Create an rdataset with the specified TTL, and with the specified list of rdata objects. @rtype: dns.rdataset.Rdataset object
3.220898
3.181993
1.012226
if len(self) == 0: self.ttl = ttl elif ttl < self.ttl: self.ttl = ttl
def update_ttl(self, ttl)
Set the TTL of the rdataset to be the lesser of the set's current TTL or the specified TTL. If the set contains no rdatas, set the TTL to the specified TTL. @param ttl: The TTL @type ttl: int
3.980185
3.406553
1.168391
# # If we're adding a signature, do some special handling to # check that the signature covers the same type as the # other rdatas in this rdataset. If this is the first rdata # in the set, initialize the covers field. # if self.rdclass != rd.rdclass or...
def add(self, rd, ttl=None)
Add the specified rdata to the rdataset. If the optional I{ttl} parameter is supplied, then self.update_ttl(ttl) will be called prior to adding the rdata. @param rd: The rdata @type rd: dns.rdata.Rdata object @param ttl: The TTL @type ttl: int
4.160907
3.717441
1.119293
self.update_ttl(other.ttl) super(Rdataset, self).update(other)
def update(self, other)
Add all rdatas in other to self. @param other: The rdataset from which to update @type other: dns.rdataset.Rdataset object
12.925535
5.410554
2.388948
if not name is None: name = name.choose_relativity(origin, relativize) ntext = str(name) pad = ' ' else: ntext = '' pad = '' s = StringIO.StringIO() if not override_rdclass is None: rdclass = override_rdclas...
def to_text(self, name=None, origin=None, relativize=True, override_rdclass=None, **kw)
Convert the rdataset into DNS master file format. @see: L{dns.name.Name.choose_relativity} for more information on how I{origin} and I{relativize} determine the way names are emitted. Any additional keyword arguments are passed on to the rdata to_text() method. @param ...
3.293427
2.96714
1.109967
if not override_rdclass is None: rdclass = override_rdclass want_shuffle = False else: rdclass = self.rdclass file.seek(0, 2) if len(self) == 0: name.to_wire(file, compress, origin) stuff = struct.pack("!HHIH", self.r...
def to_wire(self, name, file, compress=None, origin=None, override_rdclass=None, want_shuffle=True)
Convert the rdataset to wire format. @param name: The owner name of the RRset that will be emitted @type name: dns.name.Name object @param file: The file to which the wire format data will be appended @type file: file @param compress: The compression table to use; the default is...
2.27795
2.225031
1.023783
if self.rdclass == rdclass and \ self.rdtype == rdtype and \ self.covers == covers: return True return False
def match(self, rdclass, rdtype, covers)
Returns True if this rdataset matches the specified class, type, and covers
2.52579
2.838949
0.889692
for folder in folders: for module in loader.get_folder_modules(folder, parentpackage): yield module for module in loader.get_package_modules(package): yield module
def get_plugin_modules(folders, package='plugins', parentpackage='linkcheck.dummy')
Get plugin modules for given folders.
2.971959
2.80043
1.061251
classes = (_ConnectionPlugin, _ContentPlugin, _ParserPlugin) return loader.get_plugins(modules, classes)
def get_plugin_classes(modules)
Get plugin classes for given modules.
14.783339
13.245253
1.116124
for plugin in plugins: log.debug(LOG_PLUGIN, "Run plugin %s", plugin.__class__.__name__) if plugin.applies_to(url_data, **kwargs): plugin.check(url_data) if stop_after_match: break
def run_plugins(plugins, url_data, stop_after_match=False, **kwargs)
Run the check(url_data) method of given plugins.
3.329864
3.055243
1.089885
for pluginclass in get_plugin_classes(modules): name = pluginclass.__name__ if name in config["enabledplugins"]: if issubclass(pluginclass, _ConnectionPlugin): log.debug(LOG_PLUGIN, "Enable connection plugin %s", name) self...
def load_modules(self, modules, config)
Load plugin modules.
2.298326
2.191531
1.048731
run_plugins(self.parser_plugins, url_data, stop_after_match=True, pagetype=pagetype)
def run_parser_plugins(self, url_data, pagetype)
Run parser plugins for given pagetype.
4.795487
5.083354
0.943371
version, value = get_online_version() if version is None: # value is an error message return False, value if version == CurrentVersion: # user has newest version return True, None if is_newer_version(version): # value is an URL linking to the update package ...
def check_update ()
Return the following values: (False, errmsg) - online version could not be determined (True, None) - user has newest version (True, (version, url string)) - update available (True, (version, None)) - current version is newer than online version
6.417099
4.186603
1.53277
# prevent getting a cached answer headers = {'Pragma': 'no-cache', 'Cache-Control': 'no-cache'} content, info = get_content(UPDATE_URL, addheaders=headers) if content is None: return content, info version, url = None, None for line in content.splitlines(): if line.startswith...
def get_online_version ()
Download update info and parse it.
3.389213
3.308246
1.024474
try: aggregate.visit_loginurl() except Exception as msg: log.warn(LOG_CHECK, _("Error using login URL: %(msg)s.") % \ dict(msg=msg)) raise try: aggregate.logger.start_log_output() except Exception as msg: log.error(LOG_CHECK, _("Error startin...
def check_urls (aggregate)
Main check function; checks all configured URLs until interrupted with Ctrl-C. @return: None
5.986086
5.999158
0.997821
while True: try: aggregate.urlqueue.join(timeout=30) break except urlqueue.Timeout: # Cleanup threads every 30 seconds aggregate.remove_stopped_threads() if not any(aggregate.get_check_threads()): break
def check_url (aggregate)
Helper function waiting for URL queue.
8.988135
7.888905
1.139339
while True: try: log.warn(LOG_CHECK, _("interrupt; waiting for active threads to finish")) log.warn(LOG_CHECK, _("another interrupt will exit immediately")) abort(aggregate) break except KeyboardInterrupt: ...
def interrupt (aggregate)
Interrupt execution and shutdown, ignoring any subsequent interrupts.
11.919366
11.407142
1.044904
while True: try: aggregate.abort() aggregate.finish() aggregate.end_log_output(interrupt=True) break except KeyboardInterrupt: log.warn(LOG_CHECK, _("user abort; force shutdown")) aggregate.end_log_output(interrupt=True) ...
def abort (aggregate)
Helper function to ensure a clean shutdown.
8.317002
7.74651
1.073645
if os.name == 'posix': # Unix systems can use signals import signal os.kill(os.getpid(), signal.SIGTERM) time.sleep(1) os.kill(os.getpid(), signal.SIGKILL) elif os.name == 'nt': # NT has os.abort() os.abort() else: # All other systems have...
def abort_now ()
Force exit of current process without cleanup.
3.700438
3.55079
1.042145
_urlqueue = urlqueue.UrlQueue(max_allowed_urls=config["maxnumurls"]) _robots_txt = robots_txt.RobotsTxt(config["useragent"]) plugin_manager = plugins.PluginManager(config) result_cache = results.ResultCache() return aggregator.Aggregate(config, _urlqueue, _robots_txt, plugin_manager, re...
def get_aggregate (config)
Get an aggregator instance with given configuration.
5.468522
5.164204
1.058928
if len(address) != 16: raise ValueError("IPv6 addresses are 16 bytes long") hex = address.encode('hex_codec') chunks = [] i = 0 l = len(hex) while i < l: chunk = hex[i : i + 4] # strip leading zeros. we do this with an re instead of # with lstrip() because ...
def inet_ntoa(address)
Convert a network format IPv6 address into text. @param address: the binary address @type address: string @rtype: string @raises ValueError: the address isn't 16 bytes long
2.837028
2.827232
1.003465
# # Our aim here is not something fast; we just want something that works. # if text == '::': text = '0::' # # Get rid of the icky dot-quad syntax if we have it. # m = _v4_ending.match(text) if not m is None: text = "%s:%04x:%04x" % (m.group(1), ...
def inet_aton(text)
Convert a text format IPv6 address into network format. @param text: the textual address @type text: string @rtype: string @raises dns.exception.SyntaxError: the text was not properly formatted
3.144838
3.033901
1.036566
if isinstance(text, unicode): return text.encode(i18n.default_encoding, 'ignore') return text
def encode (text)
Encode text with default encoding if its Unicode.
4.855603
3.86461
1.256428
print(os.linesep, file=out) print(_() % configuration.SupportUrl, file=out) if etype is None: etype = sys.exc_info()[0] if evalue is None: evalue = sys.exc_info()[1] if tb is None: tb = sys.exc_info()[2] better_exchook2.better_exchook(etype, evalue, tb, out=out) ...
def internal_error (out=stderr, etype=None, evalue=None, tb=None)
Print internal error message (output defaults to stderr).
4.380185
4.352961
1.006254
for key in ("LANGUAGE", "LC_ALL", "LC_CTYPE", "LANG"): print_env_info(key, out=out) print(_("Default locale:"), i18n.get_locale(), file=out)
def print_locale_info (out=stderr)
Print locale info.
5.117554
4.679649
1.093576
print(_("System info:"), file=out) print(configuration.App, file=out) print(_("Released on:"), configuration.ReleaseDate, file=out) print(_("Python %(version)s on %(platform)s") % {"version": sys.version, "platform": sys.platform}, file=out) for key in PYTHON_ENV_VARS: ...
def print_app_info (out=stderr)
Print system and application info (output defaults to stderr).
4.645929
4.538167
1.023746
print(configuration.App, _("released"), configuration.ReleaseDate, file=out) print(configuration.Copyright, file=out)
def print_version (out=stdout)
Print the program version (output defaults to stdout).
15.695541
13.985509
1.122272
msg = _n("%2d thread active", "%2d threads active", in_progress) % \ in_progress self.write(u"%s, " % msg) msg = _n("%5d link queued", "%5d links queued", queue) % queue self.write(u"%s, " % msg) msg = _n("%4d link", "%4d links", checked) % checked self...
def log_status (self, checked, in_progress, queue, duration, num_urls)
Write status message to file descriptor.
4.080852
3.98975
1.022834
self.fd.write(u"%s%s" % (msg, unicode(os.linesep)))
def writeln (self, msg)
Write status message and line break to file descriptor.
6.313071
4.90379
1.287386
fake_func.__module__ = real_func.__module__ fake_func.__name__ = real_func.__name__ fake_func.__doc__ = real_func.__doc__ fake_func.__dict__.update(real_func.__dict__) return fake_func
def update_func_meta (fake_func, real_func)
Set meta information (eg. __doc__) of fake function to that of the real function. @return fake_func
1.579661
1.746514
0.904465
def newfunc (*args, **kwargs): warnings.warn("Call to deprecated function %s." % func.__name__, category=DeprecationWarning) return func(*args, **kwargs) return update_func_meta(newfunc, func)
def deprecated (func)
A decorator which can be used to mark functions as deprecated. It emits a warning when the function is called.
3.284736
4.130363
0.795266
# create the 'real' decorator which takes only a function as an argument def newfunc (function): # note: actually the kill(2) function uses the signal number of 0 # for a special case, but for signal(2) only positive integers # are allowed is_valid_signal = 0 < sign...
def signal_handler (signal_number)
From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410666 A decorator to set the specified function as handler for a signal. This function is the 'outer' decorator, called with only the (non-function) arguments. If signal_number is not a valid signal (for example signal.SIGN), no handler ...
9.144169
8.600539
1.063209
def newfunc (*args, **kwargs): t = time.time() with lock: duration = time.time() - t if duration > log_duration_secs > 0: print("WARN:", func.__name__, "locking took %0.2f seconds" % duration, file=sys.stderr) return func(*args, **kwa...
def synchronize (lock, func, log_duration_secs=0)
Return synchronized function acquiring the given lock.
4.606582
4.531508
1.016567
def newfunc (*args, **kwargs): co = func.func_code attrs = (co.co_name, co.co_filename, co.co_firstlineno) raise NotImplementedError("function %s at %s:%d is not implemented" % attrs) return update_func_meta(newfunc, func)
def notimplemented (func)
Raises a NotImplementedError if the function is called.
4.512597
4.951344
0.911388
def newfunc (*args, **kwargs): t = time.time() res = func(*args, **kwargs) duration = time.time() - t if duration > limit: print(func.__name__, "took %0.2f seconds" % duration, file=log) print(args, file=log) print(kwargs, file=log) ...
def timeit (func, log, limit)
Print execution time of the function. For quick'n'dirty profiling.
3.748589
3.368374
1.112878
return lambda func: timeit(func, log, limit)
def timed (log=sys.stderr, limit=2.0)
Decorator to run a function with timing info.
8.377245
6.442911
1.300227
if text.isdigit(): total = long(text) else: if not text[0].isdigit(): raise BadTTL total = 0L current = 0L for c in text: if c.isdigit(): current *= 10 current += long(c) else: c = c...
def from_text(text)
Convert the text form of a TTL to an integer. The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported. @param text: the textual TTL @type text: string @raises dns.ttl.BadTTL: the TTL is not well-formed @rtype: int
2.069069
1.930727
1.071652
try: self.run_checked() except KeyboardInterrupt: thread.interrupt_main() except Exception: self.internal_error()
def run (self)
Handle keyboard interrupt and other errors.
7.180964
5.281774
1.359574
self.url_data = url_data self.loc = False self.url = u"" data = url_data.get_content() isfinal = True try: self.parser.Parse(data, isfinal) except ExpatError as expaterr: self.url_data.add_warning(expaterr.message,tag=WARN_XML_PARS...
def parse(self, url_data)
Parse XML URL data.
6.191163
5.84798
1.058684
self.in_tag = (name == self.tag) self.url = u""
def start_element(self, name, attrs)
Set tag status for start element.
9.849885
8.642539
1.139698
self.in_tag = False if name == self.tag: self.add_url()
def end_element(self, name)
If end tag is our tag, call add_url().
6.842764
2.771014
2.469408
if self.url: self.url_data.add_url(self.url, line=self.parser.CurrentLineNumber, column=self.parser.CurrentColumnNumber) self.url = u""
def add_url(self)
Add non-empty URLs to the queue.
5.957481
5.567325
1.07008
try: import _winreg as winreg except ImportError: import winreg lm = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) try: key = winreg.OpenKey(lm, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") try: return winreg.QueryValueEx(...
def get_shell_folder (name)
Get Windows Shell Folder locations from the registry.
1.800867
1.7581
1.024326
response = requests.get(url, stream=True) reader = csv.reader(response.iter_lines()) first_row = True for row in reader: if first_row: # skip first row first_row = False else: scheme, template, description, reference = row res[scheme] ...
def parse_csv_file(url, res)
Parse given URL and write res with {scheme -> description}
3.556813
2.912548
1.221203
print "++ Opened connection to %s" % client.addrport() broadcast('%s joins the conversation.\n' % client.addrport() ) CLIENT_LIST.append(client) client.send("Welcome to the Chat Server, %s.\n" % client.addrport() )
def on_connect(client)
Sample on_connect function. Handles new connections.
7.571213
7.271489
1.041219
print "-- Lost connection to %s" % client.addrport() CLIENT_LIST.remove(client) broadcast('%s leaves the conversation.\n' % client.addrport() )
def on_disconnect(client)
Sample on_disconnect function. Handles lost connections.
8.312819
8.8683
0.937363
## Who hasn't been typing? for client in CLIENT_LIST: if client.idle() > IDLE_TIMEOUT: print('-- Kicking idle lobby client from %s' % client.addrport()) client.active = False
def kick_idle()
Looks for idle clients and disconnects them by setting active to False.
12.047673
9.733263
1.237784
global SERVER_RUN msg = client.get_command() print '%s says, "%s"' % (client.addrport(), msg) for guest in CLIENT_LIST: if guest != client: guest.send('%s says, %s\n' % (client.addrport(), msg)) else: guest.send('You say, %s\n' % msg) cmd = msg.lower() ...
def chat(client)
Echo whatever client types to everyone.
4.755861
4.593775
1.035284
host, port = urllib.splitport(host_port.strip()) if port is not None: if urlutil.is_numeric_port(port): port = int(port) return host, port
def parse_host_port (host_port)
Parse a host:port string into separate components.
3.900249
3.654803
1.067157
self.proxy = proxy self.proxytype = "http" self.proxyauth = None if not self.proxy: return proxyurl = urlparse.urlparse(self.proxy) self.proxytype = proxyurl.scheme if self.proxytype not in ('http', 'https'): # Note that invalid pr...
def set_proxy (self, proxy)
Parse given proxy information and store parsed values. Note that only http:// proxies are supported, both for ftp:// and http:// URLs.
3.402916
3.295464
1.032606
if urllib.proxy_bypass(self.host): return True no_proxy = os.environ.get("no_proxy") if no_proxy: entries = [parse_host_port(x) for x in no_proxy.split(",")] for host, port in entries: if host.lower() == self.host and port == self.port...
def ignore_proxy_host (self)
Check if self.host is in the $no_proxy ignore list.
3.137085
2.574457
1.218542
if self.proxy: scheme = self.proxytype host = self.proxyhost port = self.proxyport else: scheme = self.scheme host = self.host port = self.port return (scheme, host, port)
def get_netloc(self)
Determine scheme, host and port for this connection taking proxy data into account. @return: tuple (scheme, host, port) @rtype: tuple(string, string, int)
2.591358
1.918686
1.35059
(algorithm_name, digestmod) = get_algorithm(algorithm) if first: ctx = hmac.new(secret, digestmod=digestmod) ml = len(request_mac) if ml > 0: ctx.update(struct.pack('!H', ml)) ctx.update(request_mac) id = struct.pack('!H', original_id) ctx.update(id)...
def sign(wire, keyname, secret, time, fudge, original_id, error, other_data, request_mac, ctx=None, multi=False, first=True, algorithm=default_algorithm)
Return a (tsig_rdata, mac, ctx) tuple containing the HMAC TSIG rdata for the input parameters, the HMAC MAC calculated by applying the TSIG signature algorithm, and the TSIG digest context. @rtype: (string, string, hmac.HMAC object) @raises ValueError: I{other_data} is too long @raises NotImplemente...
2.849795
2.762726
1.031516
(adcount,) = struct.unpack("!H", wire[10:12]) if adcount == 0: raise dns.exception.FormError adcount -= 1 new_wire = wire[0:10] + struct.pack("!H", adcount) + wire[12:tsig_start] current = tsig_rdata (aname, used) = dns.name.from_wire(wire, current) current = current + used ...
def validate(wire, keyname, secret, now, request_mac, tsig_start, tsig_rdata, tsig_rdlen, ctx=None, multi=False, first=True)
Validate the specified TSIG rdata against the other input parameters. @raises FormError: The TSIG is badly formed. @raises BadTime: There is too much time skew between the client and the server. @raises BadSignature: The TSIG signature did not validate @rtype: hmac.HMAC object
3.441543
3.507056
0.98132
global _hashes if _hashes is None: _setup_hashes() if isinstance(algorithm, (str, unicode)): algorithm = dns.name.from_text(algorithm) if sys.hexversion < 0x02050200 and \ (algorithm == HMAC_SHA384 or algorithm == HMAC_SHA512): raise NotImplementedError("TSIG algor...
def get_algorithm(algorithm)
Returns the wire format string and the hash module to use for the specified TSIG algorithm @rtype: (string, hash constructor) @raises NotImplementedError: I{algorithm} is not supported
3.76029
3.363294
1.118038
if family == AF_INET: return dns.ipv4.inet_aton(text) elif family == AF_INET6: return dns.ipv6.inet_aton(text) else: raise NotImplementedError
def inet_pton(family, text)
Convert the textual form of a network address into its binary form. @param family: the address family @type family: int @param text: the textual address @type text: string @raises NotImplementedError: the address family specified is not implemented. @rtype: string
2.499455
2.57184
0.971855
if family == AF_INET: return dns.ipv4.inet_ntoa(address) elif family == AF_INET6: return dns.ipv6.inet_ntoa(address) else: raise NotImplementedError
def inet_ntop(family, address)
Convert the binary form of a network address into its textual form. @param family: the address family @type family: int @param address: the binary address @type address: string @raises NotImplementedError: the address family specified is not implemented. @rtype: string
2.163213
2.419316
0.894143
try: junk = dns.ipv4.inet_aton(text) return AF_INET except Exception: try: junk = dns.ipv6.inet_aton(text) return AF_INET6 except Exception: raise ValueError
def af_for_address(text)
Determine the address family of a textual-form network address. @param text: the textual address @type text: string @raises ValueError: the address family cannot be determined from the input. @rtype: int
2.687863
2.727549
0.98545
try: first = ord(dns.ipv4.inet_aton(text)[0]) return (first >= 224 and first <= 239) except Exception: try: first = ord(dns.ipv6.inet_aton(text)[0]) return (first == 255) except Exception: raise ValueError
def is_multicast(text)
Is the textual-form network address a multicast address? @param text: the textual address @raises ValueError: the address family cannot be determined from the input. @rtype: bool
2.833153
2.779728
1.019219
s = StringIO() s.write('Traceback:') s.write(os.linesep) for frame, fname, lineno, method, lines, dummy in reversed(stack): s.write(' File %r, line %d, in %s' % (fname, lineno, method)) s.write(os.linesep) s.write(' %s' % lines[0].lstrip()) if PRINT_LOCALVARS: ...
def _stack_format (stack)
Format a stack trace to a message. @return: formatted stack message @rtype: string
3.456181
3.529543
0.979215
fun(msg, *args) if kwargs.get("traceback"): # note: get rid of last parts of the stack fun(_stack_format(inspect.stack()[2:])) if kwargs.get("exception"): fun(traceback.format_exc())
def _log (fun, msg, args, **kwargs)
Log a message with given function. Optional the following keyword arguments are supported: traceback(bool) - if True print traceback of current function exception(bool) - if True print last exception traceback @return: None
8.383852
8.254402
1.015683
log = logging.getLogger(logname) if log.isEnabledFor(logging.DEBUG): _log(log.debug, msg, args, **kwargs)
def debug (logname, msg, *args, **kwargs)
Log a debug message. return: None
2.719449
3.098167
0.877761
log = logging.getLogger(logname) if log.isEnabledFor(logging.INFO): _log(log.info, msg, args, **kwargs)
def info (logname, msg, *args, **kwargs)
Log an informational message. return: None
2.791719
3.121269
0.894418
log = logging.getLogger(logname) if log.isEnabledFor(logging.WARN): _log(log.warn, msg, args, **kwargs)
def warn (logname, msg, *args, **kwargs)
Log a warning. return: None
2.923503
3.356132
0.871093
log = logging.getLogger(logname) if log.isEnabledFor(logging.ERROR): _log(log.error, msg, args, **kwargs)
def error (logname, msg, *args, **kwargs)
Log an error. return: None
2.953085
3.302398
0.894225
log = logging.getLogger(logname) if log.isEnabledFor(logging.CRITICAL): _log(log.critical, msg, args, **kwargs)
def critical (logname, msg, *args, **kwargs)
Log a critical error. return: None
2.69954
3.066234
0.880409
for entry in os.listdir(dirname): fullentry = os.path.join(dirname, entry) if os.path.islink(fullentry): continue if os.path.isfile(fullentry): yield entry elif os.path.isdir(fullentry): yield entry+"/"
def get_files (dirname)
Get iterator of entries in directory. Only allows regular files and directories, no symlinks.
2.265899
2.122109
1.067758
unc, rest = os.path.splitunc(path) head, tail = os.path.split(rest) if not tail: return path for fname in os.listdir(unc+head): if fname.lower() == tail.lower(): return os.path.join(get_nt_filename(unc+head), fname) log.error(LOG_CHECK, "could not find %r in %r", tai...
def get_nt_filename (path)
Return case sensitive filename for NT path.
3.885265
3.619894
1.073309
if os.name == 'nt': path = prepare_urlpath_for_nt(path) res = urllib.url2pathname(fileutil.pathencode(path)) if os.name == 'nt' and res.endswith(':') and len(res) == 2: # Work around http://bugs.python.org/issue11474 res += os.sep return res
def get_os_filename (path)
Return filesystem path for given URL path.
4.856883
4.227256
1.148944
if os.name == 'nt': if re.search(r"^[a-zA-Z]:", path): return True path = path.replace("\\", "/") return path.startswith("/")
def is_absolute_path (path)
Check if given path is absolute. On Windows absolute paths start with a drive letter. On all other systems absolute paths start with a slash.
3.314813
3.095266
1.07093
super(FileUrl, self).init(base_ref, base_url, parent_url, recursion_level, aggregate, line, column, page, name, url_encoding, extern) self.scheme = u'file'
def init (self, base_ref, base_url, parent_url, recursion_level, aggregate, line, column, page, name, url_encoding, extern)
Initialize the scheme.
3.049978
2.481372
1.22915
if self.base_url is None: return base_url = self.base_url if not (self.parent_url or self.base_ref or base_url.startswith("file:")): base_url = os.path.expanduser(base_url) if not is_absolute_path(base_url): try: ba...
def build_base_url(self)
The URL is normed according to the platform: - the base URL is made an absolute file:// URL - under Windows platform the drive specifier is normed
3.654202
3.476338
1.051164
self.build_base_url() if self.parent_url is not None: # URL joining with the parent URL only works if the query # of the base URL are removed first. # Otherwise the join function thinks the query is part of # the file name. from .urlba...
def build_url (self)
Calls super.build_url() and adds a trailing slash to directories.
5.744908
5.383568
1.067119
if self.is_directory(): # Directory size always differs from the customer index.html # that is generated. So return without calculating any size. return filename = self.get_os_filename() self.size = fileutil.get_size(filename) self.modified = ...
def add_size_info (self)
Get size of file content and modification time from filename path.
9.896777
8.375115
1.181688
if (self.parent_url is not None and not self.parent_url.startswith(u"file:")): msg = _("local files are only checked without parent URL or when the parent URL is also a file") raise LinkCheckerError(msg) if self.is_directory(): self.set_result(_("d...
def check_connection (self)
Try to open the local file. Under NT systems the case sensitivity is checked.
9.222569
7.697336
1.198151
if os.name != 'nt': return path = self.get_os_filename() realpath = get_nt_filename(path) if path != realpath: self.add_warning(_("The URL path %(path)r is not the same as the " "system path %(realpath)r. You should always use ...
def check_case_sensitivity (self)
Check if url and windows path name match cases else there might be problems when copying such files on web servers that are case sensitive.
6.48373
5.56074
1.165983
if self.is_directory(): data = get_index_html(get_files(self.get_os_filename())) if isinstance(data, unicode): data = data.encode("iso8859-1", "ignore") else: data = super(FileUrl, self).read_content() return data
def read_content (self)
Return file content, or in case of directories a dummy HTML file with links to the files.
5.142627
4.3248
1.189102
filename = self.get_os_filename() return os.path.isdir(filename) and not os.path.islink(filename)
def is_directory (self)
Check if file is a directory. @return: True iff file is a directory @rtype: bool
4.399566
4.737599
0.928649
if self.is_directory(): return True if firefox.has_sqlite and firefox.extension.search(self.url): return True if self.content_type in self.ContentMimetypes: return True log.debug(LOG_CHECK, "File with content type %r is not parseable.", self.c...
def is_parseable (self)
Check if content is parseable for recursion. @return: True if content is parseable @rtype: bool
8.592041
8.71998
0.985328
if self.url: self.content_type = mimeutil.guess_mimetype(self.url, read=self.get_content) else: self.content_type = u""
def set_content_type (self)
Return URL content type, or an empty string if content type could not be found.
5.947458
5.35749
1.11012
if url is None: url = self.url if not url: return None if url.startswith('file://'): i = url.rindex('/') if i > 6: # remove last filename to make directory internal url = url[:i+1] return re.escape(u...
def get_intern_pattern (self, url=None)
Get pattern for intern URL matching. @return non-empty regex pattern or None @rtype String or None
5.267901
4.932269
1.068048
webroot = self.aggregate.config["localwebroot"] if webroot and url and url.startswith(u"/"): url = webroot + url[1:] log.debug(LOG_CHECK, "Applied local webroot `%s' to `%s'.", webroot, url) super(FileUrl, self).add_url(url, line=line, column=column, page=page, n...
def add_url (self, url, line=0, column=0, page=0, name=u"", base=None)
If a local webroot directory is configured, replace absolute URLs with it. After that queue the URL data for checking.
4.828828
3.812235
1.266666
session = requests.Session() if cookies: session.cookies = cookies session.max_redirects = config["maxhttpredirects"] session.headers.update({ "User-Agent": config["useragent"], }) if config["cookiefile"]: for cookie in cookies.from_file(config["cookiefile"]): ...
def new_request_session(config, cookies)
Create a new request session.
2.806595
2.797923
1.0031
url = self.config["loginurl"] if not url: return user, password = self.config.get_user_password(url) session = requests.Session() # XXX user-agent header # XXX timeout response = session.get(url) cgiuser = self.config["loginuserfield"]...
def visit_loginurl(self)
Check for a login URL and visit it.
3.503404
3.399097
1.030686
if self.config["status"]: t = status.Status(self, self.config["status_wait_seconds"]) t.start() self.threads.append(t) if self.config["maxrunseconds"]: t = interrupt.Interrupt(self.config["maxrunseconds"]) t.start() self.th...
def start_threads (self)
Spawn threads for URL checking and status printing.
4.35764
3.774652
1.154448
session = new_request_session(self.config, self.cookies) self.request_sessions[thread.get_ident()] = session
def add_request_session(self)
Add a request session for current thread.
5.793702
4.549255
1.27355
t = time.time() if host in self.times: due_time = self.times[host] if due_time > t: wait = due_time - t time.sleep(wait) t = time.time() wait_time = random.uniform(self.wait_time_min, self.wait_time_max) sel...
def wait_for_host(self, host)
Throttle requests to one host.
2.581275
2.415375
1.068685
debug = log.is_debug(LOG_CHECK) if debug: first = True for name in self.get_check_threads(): if first: log.info(LOG_CHECK, _("These URLs are still active:")) first = False log.info(LOG_CHECK, name[12...
def print_active_threads (self)
Log all currently active threads.
7.289453
7.103373
1.026196
for t in self.threads: name = t.getName() if name.startswith("CheckThread-"): yield name
def get_check_threads(self)
Return iterator of checker threads.
5.32188
4.479697
1.188
self.print_active_threads() self.cancel() timeout = self.config["aborttimeout"] try: self.urlqueue.join(timeout=timeout) except urlqueue.Timeout: log.warn(LOG_CHECK, "Abort timed out after %d seconds, stopping application." % timeout) ...
def abort (self)
Print still-active URLs and empty the URL queue.
10.683447
7.81782
1.366551
self.threads = [t for t in self.threads if t.is_alive()]
def remove_stopped_threads (self)
Remove the stopped threads from the internal thread list.
3.688562
2.793106
1.320595
if not self.urlqueue.empty(): # This happens when all checker threads died. self.cancel() for t in self.threads: t.stop()
def finish (self)
Wait for checker threads to finish.
12.403062
8.040154
1.54264
kwargs.update(dict( downloaded_bytes=self.downloaded_bytes, num_urls = len(self.result_cache), )) self.logger.end_log_output(**kwargs)
def end_log_output(self, **kwargs)
Print ending output to log.
5.912713
5.742133
1.029707
super(TelnetUrl, self).build_url() # default port if self.port is None: self.port = 23 # set user/pass self.user, self.password = self.get_user_password()
def build_url (self)
Call super.build_url(), set default telnet port and initialize the login credentials.
4.346942
3.320935
1.308951
if not self.host: self.set_result(_("Host is empty"), valid=False) return super(TelnetUrl, self).local_check()
def local_check (self)
Warn about empty host names. Else call super.local_check().
10.93236
6.876028
1.589924
self.url_connection = telnetlib.Telnet(timeout=self.aggregate.config["timeout"]) if log.is_debug(LOG_CHECK): self.url_connection.set_debuglevel(1) self.url_connection.open(self.host, self.port) if self.user: self.url_connection.read_until("login: ", 10) ...
def check_connection (self)
Open a telnet connection and try to login. Expected login label is "login: ", expected password label is "Password: ".
3.173426
2.962165
1.07132
from requests.packages.urllib3.contrib.pyopenssl import get_subj_alt_name res = { 'subject': ( (('commonName', x509.get_subject().CN),), ), 'subjectAltName': [ ('DNS', value) for value in get_subj_alt_name(x509) ...
def x509_to_dict(x509)
Parse a x509 pyopenssl object to a dictionary with keys subject, subjectAltName and optional notAfter.
3.437961
3.124954
1.100164
res = None timeformat = "%Y%m%d%H%M%S" try: res = datetime.strptime(timestr, timeformat + 'Z') except ValueError: try: res = datetime.strptime(timestr, timeformat + '%z') except ValueError: pass return res
def asn1_generaltime_to_seconds(timestr)
The given string has one of the following formats YYYYMMDDhhmmssZ YYYYMMDDhhmmss+hhmm YYYYMMDDhhmmss-hhmm @return: a datetime object or None on error
2.439739
2.565041
0.95115
name = name.lower() value = value.lower() for hname, hvalue in headers: if hname.lower()==name and hvalue.lower()==value: return True return False
def has_header_value (headers, name, value)
Look in headers for a specific header name and value. Both name and value are case insensitive. @return: True if header name and value are found @rtype: bool
2.461189
2.358453
1.04356