code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.write(self.part("realurl") + self.spaces("realurl")) self.writeln(unicode(url_data.url), color=self.colorreal)
def write_real (self, url_data)
Write url_data.url.
20.365496
16.075354
1.266877
self.write(self.part("dltime") + self.spaces("dltime")) self.writeln(_("%.3f seconds") % url_data.dltime, color=self.colordltime)
def write_dltime (self, url_data)
Write url_data.dltime.
11.964545
9.148705
1.307786
self.write(self.part("dlsize") + self.spaces("dlsize")) self.writeln(strformat.strsize(url_data.size), color=self.colordlsize)
def write_size (self, url_data)
Write url_data.size.
17.832726
14.46639
1.2327
self.write(self.part("checktime") + self.spaces("checktime")) self.writeln(_("%.3f seconds") % url_data.checktime, color=self.colordltime)
def write_checktime (self, url_data)
Write url_data.checktime.
16.171776
12.547981
1.288795
self.write(self.part("info") + self.spaces("info")) self.writeln(self.wrap(url_data.info, 65), color=self.colorinfo)
def write_info (self, url_data)
Write url_data.info.
13.603207
10.506577
1.294732
self.write(self.part("modified") + self.spaces("modified")) self.writeln(self.format_modified(url_data.modified))
def write_modified(self, url_data)
Write url_data.modified.
12.538436
9.480558
1.322542
self.write(self.part("warning") + self.spaces("warning")) warning_msgs = [u"[%s] %s" % x for x in url_data.warnings] self.writeln(self.wrap(warning_msgs, 65), color=self.colorwarning)
def write_warning (self, url_data)
Write url_data.warning.
9.006728
7.883947
1.142414
self.write(self.part("result") + self.spaces("result")) if url_data.valid: color = self.colorvalid self.write(_("Valid"), color=color) else: color = self.colorinvalid self.write(_("Error"), color=color) if url_data.result: ...
def write_result (self, url_data)
Write url_data.result.
5.227224
4.606539
1.13474
self.writeln() if interrupt: self.writeln(_("The check has been interrupted; results are not complete.")) self.write(_("That's it.") + " ") self.write(_n("%d link", "%d links", self.stats.number) % self.stats.number) self.write(u" ") ...
def write_outro (self, interrupt=False)
Write end of checking message.
2.75924
2.688678
1.026244
self.writeln() self.writeln(_("Statistics:")) if self.stats.downloaded_bytes is not None: self.writeln(_("Downloaded: %s.") % strformat.strsize(self.stats.downloaded_bytes)) if self.stats.number > 0: self.writeln(_( "Content types: %(image)d...
def write_stats (self)
Write check statistic info.
3.612663
3.455403
1.045512
self.stats.downloaded_bytes = kwargs.get("downloaded_bytes") self.stats.num_urls = kwargs.get("num_urls") if self.has_part('stats'): self.write_stats() if self.has_part('outro'): self.write_outro(interrupt=kwargs.get("interrupt")) self.close_fileo...
def end_output (self, **kwargs)
Write end of output info, and flush all output buffers.
5.886021
5.634709
1.044601
if '/' in path: i = path.find(';', path.rfind('/')) else: i = path.find(';') if i < 0: return path, '' return path[:i], path[i+1:]
def splitparams (path)
Split off parameter part from path. Returns tuple (path-without-param, param)
2.72509
2.5301
1.077068
if portstr.isdigit(): port = int(portstr) # 65536 == 2**16 if 0 < port < 65536: return port return False
def is_numeric_port (portstr)
return: integer port (== True) iff portstr is a valid port number, False otherwise
3.396256
3.181003
1.067668
pairs = [] name_value_amp = qs.split('&') for name_value in name_value_amp: if ';' in name_value: pairs.extend([x, ';'] for x in name_value.split(';')) pairs[-1][1] = '&' else: pairs.append([name_value, '&']) pairs[-1][1] = '' r = [] for n...
def parse_qsl (qs, keep_blank_values=0, strict_parsing=0)
Parse a query given as a string argument. @param qs: URL-encoded query string to be parsed @type qs: string @param keep_blank_values: flag indicating whether blank values in URL encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as bla...
2.672346
2.628568
1.016655
if host and isinstance(host, unicode): try: host.encode('ascii') return host, False except UnicodeError: uhost = host.encode('idna').decode('ascii') return uhost, uhost != host return host, False
def idna_encode (host)
Encode hostname as internationalized domain name (IDN) according to RFC 3490. @raise: UnicodeError if hostname is not properly IDN encoded.
3.157545
3.65145
0.864737
if not urlparts[1]: urlparts[2] = urllib.unquote(urlparts[2]) return False userpass, netloc = urllib.splituser(urlparts[1]) if userpass: userpass = urllib.unquote(userpass) netloc, is_idn = idna_encode(urllib.unquote(netloc).lower()) # a leading backslash in path causes ...
def url_fix_host (urlparts)
Unquote and fix hostname. Returns is_idn.
3.503645
3.358792
1.043127
if url.startswith("http//"): url = "http://" + url[6:] elif url.startswith("https//"): url = "https://" + url[7:] return url
def url_fix_common_typos (url)
Fix common typos in given URL like forgotten colon.
2.588276
2.575223
1.005069
if isinstance(query, unicode): if encoding is None: encoding = url_encoding query = query.encode(encoding, 'ignore') # if ? is in the query, split it off, seen at msdn.microsoft.com append = "" while '?' in query: query, rest = query.rsplit('?', 1) append...
def url_parse_query (query, encoding=None)
Parse and re-join the given CGI query.
3.676439
3.606396
1.019422
res = urlparse.urlunsplit(urlparts) if os.name == 'nt' and urlparts[0] == 'file' and '|' not in urlparts[2]: # UNC paths must have 4 slashes: 'file:////server/path' # Depending on the path in urlparts[2], urlparse.urlunsplit() # left only two or three slashes. This is fixed below ...
def urlunsplit (urlparts)
Same as urlparse.urlunsplit but with extra UNC path handling for Windows OS.
5.004828
4.72082
1.060161
if isinstance(url, unicode): # try to decode the URL to ascii since urllib.unquote() # handles non-unicode strings differently try: url = url.encode('ascii') except UnicodeEncodeError: pass encode_unicode = True else: encode_unicode = ...
def url_norm (url, encoding=None)
Normalize the given URL which must be quoted. Supports unicode hostnames (IDNA encoding) according to RFC 3490. @return: (normed url, idna flag) @rtype: tuple of length two
3.779712
3.751407
1.007545
# replace backslashes # note: this is _against_ the specification (which would require # backslashes to be left alone, and finally quoted with '%5C') # But replacing has several positive effects: # - Prevents path attacks on Windows systems (using \.. parent refs) # - Fixes bad URLs where u...
def collapse_segments (path)
Remove all redundant segments from the given URL path. Precondition: path is an unquoted url path
6.863678
6.649206
1.032255
if not url_is_absolute(url): return document_quote(url) urlparts = list(urlparse.urlsplit(url)) urlparts[0] = url_quote_part(urlparts[0]) # scheme urlparts[1] = url_quote_part(urlparts[1], ':') # host urlparts[2] = url_quote_part(urlparts[2], '/=,') # path urlparts[3] = url_quote_pa...
def url_quote (url)
Quote given URL.
2.368835
2.357929
1.004625
if isinstance(s, unicode): if encoding is None: encoding = url_encoding s = s.encode(encoding, 'ignore') return urllib.quote(s, safechars)
def url_quote_part (s, safechars='/', encoding=None)
Wrap urllib.quote() to support unicode strings. A unicode string is first converted to UTF-8. After that urllib.quote() is called.
2.730296
2.517175
1.084667
doc, query = urllib.splitquery(document) doc = url_quote_part(doc, '/=,') if query: return "%s?%s" % (doc, query) return doc
def document_quote (document)
Quote given document.
7.603586
7.515693
1.011695
if not host: return False for domain in domainlist: if domain.startswith('.'): if host.endswith(domain): return True elif host == domain: return True return False
def match_host (host, domainlist)
Return True if host matches an entry in given domain list.
2.347471
2.122308
1.106093
scheme, netloc = urllib.splittype(url) host, document = urllib.splithost(netloc) port = default_ports.get(scheme, 0) if host: host = host.lower() host, port = splitport(host, port=port) return scheme, host, port, document
def url_split (url)
Split url in a tuple (scheme, hostname, port, document) where hostname is always lowercased. Precondition: url is syntactically correct URI (eg has no whitespace)
3.509712
3.561696
0.985405
if parts[2] == default_ports.get(parts[0]): return "%s://%s%s" % (parts[0], parts[1], parts[3]) return "%s://%s:%d%s" % parts
def url_unsplit (parts)
Rejoin URL parts to a string.
3.0877
2.952366
1.045839
if ":" in host: shost, sport = host.split(":", 1) iport = is_numeric_port(sport) if iport: host, port = shost, iport elif not sport: # empty port, ie. the host was "hostname:" host = shost else: # For an invalid non-empty p...
def splitport (host, port=0)
Split optional port number from host. If host has no port number, the given default port is returned. @param host: host name @ptype host: string @param port: the port number (default 0) @ptype port: int @return: tuple of (host, port) @rtype: tuple of (string, int)
5.773263
6.402025
0.901787
from . import configuration headers = { 'User-Agent': configuration.UserAgent, } if addheaders: headers.update(addheaders) method = 'GET' kwargs = dict(headers=headers) if user and password: kwargs['auth'] = (user, password) if data: kwargs['data'] = ...
def get_content(url, user=None, password=None, proxy=None, data=None, addheaders=None)
Get URL content and info. @return: (decoded text content of URL, headers) or (None, errmsg) on error. @rtype: tuple (String, dict) or (None, String)
3.371653
3.20623
1.051594
if '#' in url: url = url.split('#', 1)[0] if url.endswith('index.html'): return url[:-10] if url.endswith('index.htm'): return url[:-9] return url
def shorten_duplicate_content_url(url)
Remove anchor part and trailing index.html from URL.
2.654148
2.200791
1.205998
if url1 == url2: return True if url2 in url1: url1 = shorten_duplicate_content_url(url1) if not url2.endswith('/') and url1.endswith('/'): url2 += '/' return url1 == url2 if url1 in url2: url2 = shorten_duplicate_content_url(url2) if not url1....
def is_duplicate_content_url(url1, url2)
Check if both URLs are allowed to point to the same content.
1.999177
1.951592
1.024383
# first write in a temp file f = file(filename+".tmp", 'wb') if callback is None: f.write(content) else: callback(f, content) f.close() # move orig file to backup if os.path.exists(filename): os.rename(filename, filename+".bak") # move temp file to orig o...
def write_file (filename, content, backup=False, callback=None)
Overwrite a possibly existing file with new content. Do this in a manner that does not leave truncated or broken files behind. @param filename: name of file to write @type filename: string @param content: file content to write @type content: string @param backup: if backup file should be left ...
2.625665
2.577002
1.018884
try: importlib.import_module(name) return True except ImportError: return False except Exception: # some modules raise errors when intitializing return not without_error
def has_module (name, without_error=True)
Test if given module can be imported. @param without_error: True if module must not throw any errors when importing @return: flag if import is successful @rtype: bool
5.370977
4.762117
1.127855
if isinstance(path, unicode) and not os.path.supports_unicode_filenames: path = path.encode(FSCODING, "replace") return path
def pathencode (path)
Encode a path string with the platform file system encoding.
5.09691
4.669692
1.091488
key = os.path.abspath(filename) mtime = get_mtime(key) if key not in _mtime_cache: _mtime_cache[key] = mtime return True return mtime > _mtime_cache[key]
def has_changed (filename)
Check if filename has changed since the last check. If this is the first check, assume the file is changed.
3.092526
2.87944
1.074003
fd, filename = tempfile.mkstemp(**kwargs) return os.fdopen(fd, mode), filename
def get_temp_file (mode='r', **kwargs)
Return tuple (open file object, filename) pointing to a temporary file.
3.514571
3.264021
1.076761
return os.path.isfile(filename) and os.access(filename, os.R_OK)
def is_readable(filename)
Check if file is a regular file and is readable.
2.254774
1.971162
1.143881
mode = os.stat(filename)[stat.ST_MODE] return mode & (stat.S_IRWXG | stat.S_IRWXO)
def is_accessable_by_others(filename)
Check if file is group or world accessable.
2.59964
2.438538
1.066065
mode = os.stat(filename)[stat.ST_MODE] return mode & stat.S_IWOTH
def is_writable_by_others(filename)
Check if file or directory is world writable.
3.274315
2.9205
1.121149
if not os.path.exists(filename): parentdir = os.path.dirname(filename) return os.path.isdir(parentdir) and os.access(parentdir, os.W_OK) return os.path.isfile(filename) and os.access(filename, os.W_OK)
def is_writable(filename)
Check if - the file is a regular file and is writable, or - the file does not exist and its parent directory exists and is writable
1.926975
1.912362
1.007641
self.tmpbuf.append(data) self.pos += len(data)
def write (self, data)
Write data to buffer.
9.231512
6.602054
1.398279
self.buf += self.empty.join(self.tmpbuf) self.tmpbuf = [] if overlap and overlap < self.pos: data = self.buf[:-overlap] self.buf = self.buf[-overlap:] else: data = self.buf self.buf = self.empty return data
def flush (self, overlap=0)
Flush buffered data and return it.
3.582627
3.195851
1.121025
if url.lower().startswith("www."): # syntactic sugar return "http://%s" % url elif url.lower().startswith("ftp."): # syntactic sugar return "ftp://%s" % url return url
def guess_url(url)
Guess if URL is a http or ftp URL. @param url: the URL to check @ptype url: unicode @return: url with http:// or ftp:// prepended if it's detected as a http respective ftp URL. @rtype: unicode
2.807948
2.863386
0.980639
if base_url and urlutil.url_is_absolute(base_url): return base_url elif base_ref and urlutil.url_is_absolute(base_ref): return base_ref elif parent_url and urlutil.url_is_absolute(parent_url): return parent_url return u""
def absolute_url (base_url, base_ref, parent_url)
Search for the absolute url to detect the link type. This does not join any url fragments together! @param base_url: base url from a link tag @type base_url: string or None @param base_ref: base url from <base> tag @type base_ref: string or None @param parent_url: url of parent document @ty...
2.111719
2.179934
0.968708
if base_url is not None: base_url = strformat.unicode_safe(base_url) # left strip for detection of URL scheme base_url_stripped = base_url.lstrip() else: base_url_stripped = base_url if parent_url is not None: parent_url = strformat.unicode_safe(parent_url) i...
def get_url_from (base_url, recursion_level, aggregate, parent_url=None, base_ref=None, line=0, column=0, page=0, name=u"", parent_content_type=None, extern=None)
Get url data from given base data. @param base_url: base url from a link tag @type base_url: string or None @param recursion_level: current recursion level @type recursion_level: number @param aggregate: aggregate object @type aggregate: aggregate.Consumer @param parent_url: parent url ...
3.621381
3.598075
1.006477
if scheme in ("http", "https"): klass = httpurl.HttpUrl elif scheme == "ftp": klass = ftpurl.FtpUrl elif scheme == "file": klass = fileurl.FileUrl elif scheme == "telnet": klass = telneturl.TelnetUrl elif scheme == "mailto": klass = mailtourl.MailtoUrl ...
def get_urlclass_from (scheme, assume_local_file=False)
Return checker class for given URL scheme. If the scheme cannot be matched and assume_local_file is True, assume a local file.
2.087989
2.093838
0.997206
lines = ["<html>", "<body>"] for entry in urls: name = cgi.escape(entry) try: url = cgi.escape(urllib.quote(entry)) except KeyError: # Some unicode entries raise KeyError. url = name lines.append('<a href="%s">%s</a>' % (url, name)) li...
def get_index_html (urls)
Construct artificial index.html from given URLs. @param urls: URL strings @type urls: iterator of string
3.434681
3.491345
0.98377
self.start_time = time.time() self.setName("Interrupt") while not self.stopped(self.WaitSeconds): duration = time.time() - self.start_time if duration > self.duration: log.warn(LOG_CHECK, "Interrupt after %s" % strformat.strduration_long(duration)...
def run_checked (self)
Wait and raise KeyboardInterrupt after.
10.277282
8.364888
1.228622
super(ItmsServicesUrl, self).check_syntax() if u"url=" not in self.urlparts[3]: self.set_result(_("Missing required url parameter"), valid=False)
def check_syntax(self)
Only logs that this URL is unknown.
19.239405
14.954782
1.286505
if os.name == 'nt': basedir = unicode(os.environ["APPDATA"], nt_filename_encoding) dirpath = os.path.join(basedir, u"Mozilla", u"Firefox", u"Profiles") elif os.name == 'posix': basedir = unicode(os.environ["HOME"]) dirpath = os.path.join(basedir, u".mozilla", u"firefox") ...
def get_profile_dir ()
Return path where all profiles of current user are stored.
2.862724
2.797462
1.023329
if not has_sqlite: return conn = sqlite3.connect(filename, timeout=0.5) try: c = conn.cursor() try: sql = c.execute(sql) for url, name in c: if not name: name = url yield (url, name) ...
def parse_bookmark_file (filename)
Return iterator for bookmarks of the form (url, name). Bookmarks are not sorted. Returns None if sqlite3 module is not installed.
3.17485
2.562188
1.239117
control = '' if ";" in color: control, color = color.split(";", 1) control = AnsiControl.get(control, '')+";" cnum = AnsiColor.get(color, '0') return AnsiEsc % (control+cnum)
def esc_ansicolor (color)
convert a named color definition to an escaped ANSI color
6.457251
5.62116
1.14874
foreground = background = style = None control = '' if ";" in color: control, color = color.split(";", 1) if control == bold: style = colorama.BRIGHT if color in InverseColors: background = WinColor[color] else: foreground = WinColor.get(color) re...
def get_win_color(color)
Convert a named color definition to Windows console color foreground, background and style numbers.
7.328091
6.434762
1.138829
# The is_tty() function ensures that we do not colorize # redirected streams, as this is almost never what we want if not is_tty(fp): return False if os.name == 'nt': return True elif has_curses: import curses try: curses.setupterm(os.environ.get("TER...
def has_colors (fp)
Test if given file is an ANSI color enabled tty.
4.982141
4.788775
1.040379
if not is_tty(fp): return 80 if os.name == 'nt': return colorama.get_console_size().X if has_curses: import curses try: curses.setupterm(os.environ.get("TERM"), fp.fileno()) return curses.tigetnum("cols") except curses.error: pa...
def get_columns (fp)
Return number of columns for given file.
4.778643
4.212762
1.134325
foreground, background, style = get_win_color(color) colorama.set_console(foreground=foreground, background=background, style=style) fp.write(text) colorama.reset_console()
def _write_color_colorama (fp, text, color)
Colorize text with given color.
5.016685
4.767546
1.052257
fp.write(esc_ansicolor(color)) fp.write(text) fp.write(AnsiReset)
def _write_color_ansi (fp, text, color)
Colorize text with given color.
6.962409
6.182431
1.12616
if color is None: self.fp.write(text) else: write_color(self.fp, text, color)
def _write_color (self, text, color=None)
Print text with given color. If color is None, print text as-is.
3.852694
3.170307
1.215243
color = self.get_color(record) msg = self.format(record) if not hasattr(types, "UnicodeType"): # no unicode support self.stream.write("%s" % msg, color=color) else: try: self.stream.write("%s" % msg, color=color) ex...
def emit (self, record)
Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline [N.B. this may be removed depending on feedback].
2.557296
2.559144
0.999278
super(UnknownUrl, self).build_url() if self.is_ignored(): self.add_info(_("%(scheme)s URL ignored.") % {"scheme": self.scheme.capitalize()}) self.set_result(_("ignored")) else: self.set_result(_("URL is unrecognized or has in...
def build_url (self)
Only logs that this URL is unknown.
8.411578
7.345378
1.145153
if isinstance(obj, PDFObjRef): if obj.objid in seen_objs: # prevent recursive loops return seen_objs.add(obj.objid) obj = obj.resolve() if isinstance(obj, dict): for key, value in obj.items(): if key == 'URI' and isinstance(value, basestri...
def search_url(obj, url_data, pageno, seen_objs)
Recurse through a PDF object, searching for URLs.
3.438201
3.232909
1.063501
# XXX user authentication from url_data password = '' data = url_data.get_content() # PDFParser needs a seekable file object fp = StringIO(data) try: parser = PDFParser(fp) doc = PDFDocument(parser, password=password) for (page...
def check(self, url_data)
Parse PDF data.
4.961434
4.711025
1.053154
depth = len(name) if depth > self.max_depth: depth = self.max_depth for i in xrange(-depth, 0): n = dns.name.Name(name[i:]) if n in self: return (n, self[n]) v = self[dns.name.empty] return (dns.name.empty, v)
def get_deepest_match(self, name)
Find the deepest match to I{name} in the dictionary. The deepest match is the longest name in the dictionary which is a superdomain of I{name}. @param name: the name @type name: dns.name.Name object @rtype: (key, value) tuple
3.588543
3.116491
1.151469
text = '' for c in label: if c in _escaped: text += '\\' + c elif ord(c) > 0x20 and ord(c) < 0x7F: text += c else: text += '\\%03d' % ord(c) return text
def _escapify(label)
Escape the characters in label which need it. @returns: the escaped string @rtype: string
2.307868
2.388673
0.966172
l = len(labels) total = 0 i = -1 j = 0 for label in labels: ll = len(label) total += ll + 1 if ll > 63: raise LabelTooLong if i < 0 and label == '': i = j j += 1 if total > 255: raise NameTooLong if i >= 0 and i !=...
def _validate_labels(labels)
Check for empty labels in the middle of a label sequence, labels that are too long, and for too many labels. @raises NameTooLong: the name as a whole is too long @raises LabelTooLong: an individual label is too long @raises EmptyLabel: a label is empty (i.e. the root label) and appears in a position...
4.140827
2.969902
1.394264
if not isinstance(text, unicode): raise ValueError("input to from_unicode() must be a unicode string") if not (origin is None or isinstance(origin, Name)): raise ValueError("origin must be a Name or None") labels = [] label = u'' escaping = False edigits = 0 total = 0 ...
def from_unicode(text, origin = root)
Convert unicode text into a Name object. Lables are encoded in IDN ACE form. @rtype: dns.name.Name object
2.870371
2.74264
1.046572
if not isinstance(text, str): if isinstance(text, unicode) and sys.hexversion >= 0x02030000: return from_unicode(text, origin) else: raise ValueError("input to from_text() must be a string") if not (origin is None or isinstance(origin, Name)): raise ValueErr...
def from_text(text, origin = root)
Convert text into a Name object. @rtype: dns.name.Name object
2.570952
2.401754
1.070448
if not isinstance(message, str): raise ValueError("input to from_wire() must be a byte string") message = dns.wiredata.maybe_wrap(message) labels = [] biggest_pointer = current hops = 0 count = ord(message[current]) current += 1 cused = 1 while count != 0: if co...
def from_wire(message, current)
Convert possibly compressed wire format into a Name. @param message: the entire DNS message @type message: string @param current: the offset of the beginning of the name from the start of the message @type current: int @raises dns.name.BadPointer: a compression pointer did not point backwards ...
4.159095
3.401514
1.222719
sabs = self.is_absolute() oabs = other.is_absolute() if sabs != oabs: if sabs: return (NAMERELN_NONE, 1, 0) else: return (NAMERELN_NONE, -1, 0) l1 = len(self.labels) l2 = len(other.labels) ldiff = l1 - l2 ...
def fullcompare(self, other)
Compare two names, returning a 3-tuple (relation, order, nlabels). I{relation} describes the relation ship beween the names, and is one of: dns.name.NAMERELN_NONE, dns.name.NAMERELN_SUPERDOMAIN, dns.name.NAMERELN_SUBDOMAIN, dns.name.NAMERELN_EQUAL, or dns.name.NAMERELN_COMMONANCESTOR ...
2.269871
1.740142
1.304417
(nr, o, nl) = self.fullcompare(other) if nr == NAMERELN_SUBDOMAIN or nr == NAMERELN_EQUAL: return True return False
def is_subdomain(self, other)
Is self a subdomain of other? The notion of subdomain includes equality. @rtype: bool
12.30807
12.322871
0.998799
(nr, o, nl) = self.fullcompare(other) if nr == NAMERELN_SUPERDOMAIN or nr == NAMERELN_EQUAL: return True return False
def is_superdomain(self, other)
Is self a superdomain of other? The notion of subdomain includes equality. @rtype: bool
11.839067
12.348603
0.958737
if len(self.labels) == 0: return '@' if len(self.labels) == 1 and self.labels[0] == '': return '.' if omit_final_dot and self.is_absolute(): l = self.labels[:-1] else: l = self.labels s = '.'.join(map(_escapify, l)) ...
def to_text(self, omit_final_dot = False)
Convert name to text format. @param omit_final_dot: If True, don't emit the final dot (denoting the root label) for absolute names. The default is False. @rtype: string
3.138041
2.800708
1.120446
if len(self.labels) == 0: return u'@' if len(self.labels) == 1 and self.labels[0] == '': return u'.' if omit_final_dot and self.is_absolute(): l = self.labels[:-1] else: l = self.labels s = u'.'.join([encodings.idna.ToUnic...
def to_unicode(self, omit_final_dot = False)
Convert name to Unicode text format. IDN ACE lables are converted to Unicode. @param omit_final_dot: If True, don't emit the final dot (denoting the root label) for absolute names. The default is False. @rtype: string
3.462683
3.108605
1.113902
if not self.is_absolute(): if origin is None or not origin.is_absolute(): raise NeedAbsoluteNameOrOrigin labels = list(self.labels) labels.extend(list(origin.labels)) else: labels = self.labels dlabels = ["%s%s" % (chr(len...
def to_digestable(self, origin=None)
Convert name to a format suitable for digesting in hashes. The name is canonicalized and converted to uncompressed wire format. @param origin: If the name is relative and origin is not None, then origin will be appended to it. @type origin: dns.name.Name object @raises NeedAbso...
4.970231
2.983528
1.66589
if file is None: file = cStringIO.StringIO() want_return = True else: want_return = False if not self.is_absolute(): if origin is None or not origin.is_absolute(): raise NeedAbsoluteNameOrOrigin labels = list(...
def to_wire(self, file = None, compress = None, origin = None)
Convert name to wire format, possibly compressing it. @param file: the file where the name is emitted (typically a cStringIO file). If None, a string containing the wire name will be returned. @type file: file or None @param compress: The compression table. If None (the defaul...
3.30209
2.746941
1.202097
l = len(self.labels) if depth == 0: return (self, dns.name.empty) elif depth == l: return (dns.name.empty, self) elif depth < 0 or depth > l: raise ValueError('depth must be >= 0 and <= the length of the name') return (Name(self[: -de...
def split(self, depth)
Split a name into a prefix and suffix at depth. @param depth: the number of labels in the suffix @type depth: int @raises ValueError: the depth was not >= 0 and <= the length of the name. @returns: the tuple (prefix, suffix) @rtype: tuple
4.131374
3.350215
1.233167
if self.is_absolute() and len(other) > 0: raise AbsoluteConcatenation labels = list(self.labels) labels.extend(list(other.labels)) return Name(labels)
def concatenate(self, other)
Return a new name which is the concatenation of self and other. @rtype: dns.name.Name object @raises AbsoluteConcatenation: self is absolute and other is not the empty name
6.895456
3.138116
2.197324
if not origin is None and self.is_subdomain(origin): return Name(self[: -len(origin)]) else: return self
def relativize(self, origin)
If self is a subdomain of origin, return a new name which is self relative to origin. Otherwise return self. @rtype: dns.name.Name object
9.427818
5.146279
1.831968
if origin: if relativize: return self.relativize(origin) else: return self.derelativize(origin) else: return self
def choose_relativity(self, origin=None, relativize=True)
Return a name with the relativity desired by the caller. If origin is None, then self is returned. Otherwise, if relativize is true the name is relativized, and if relativize is false the name is derelativized. @rtype: dns.name.Name object
2.807446
2.474168
1.134703
if self == root or self == empty: raise NoParent return Name(self.labels[1:])
def parent(self)
Return the parent of the name. @rtype: dns.name.Name object @raises NoParent: the name is either the root name or the empty name, and thus has no parent.
25.202816
6.523777
3.863224
global _initialized if _initialized: return import win32com.client if win32com.client.gencache.is_readonly: #allow gencache to create the cached wrapper objects win32com.client.gencache.is_readonly = False # under py2exe the call in gencache to __init__() does not ha...
def init_win32com ()
Initialize the win32com.client cache.
7.183397
6.916863
1.038534
if not has_win32com: return False try: import _winreg as winreg except ImportError: import winreg try: key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "Word.Application") winreg.CloseKey(key) return True except (EnvironmentError, ImportError): ...
def has_word ()
Determine if Word is available on the current system.
2.870711
2.519276
1.139498
if not has_word(): return None # Since this function is called from different threads, initialize # the COM layer. pythoncom.CoInitialize() import win32com.client app = win32com.client.gencache.EnsureDispatch("Word.Application") app.Visible = False return app
def get_word_app ()
Return open Word.Application handle, or None if Word is not available on this system.
4.678044
3.921776
1.192838
return app.Documents.Open(filename, ReadOnly=True, AddToRecentFiles=False, Visible=False, NoEncodingDialog=True)
def open_wordfile (app, filename)
Open given Word file with application object.
11.915777
9.569344
1.245203
lineno = 1 wrange.Select() wdFirstCharacterLineNumber = constants("wdFirstCharacterLineNumber") wdGoToLine = constants("wdGoToLine") wdGoToPrevious = constants("wdGoToPrevious") while True: curline = doc.Selection.Information(wdFirstCharacterLineNumber) doc.Selection.GoTo(wd...
def get_line_number(doc, wrange)
Get line number for given range object.
5.698986
5.454368
1.044848
# store content in temporary file fd, filename = fileutil.get_temp_file(mode='wb', suffix='.doc', prefix='lc_') try: fd.write(content) finally: fd.close() return filename
def get_temp_filename (content)
Get temporary filename for content to parse.
5.764947
6.170301
0.934306
content = url_data.get_content() filename = get_temp_filename(content) # open word file and parse hyperlinks try: app = get_word_app() try: doc = open_wordfile(app, filename) if doc is None: raise Error(...
def check(self, url_data)
Parse Word data.
4.525278
4.371549
1.035166
## temporarily escape out ^^ text = text.replace('^^', '\x00') for token, foo in _ANSI_CODES: text = text.replace(token, '') return text.replace('\x00', '^')
def strip_caret_codes(text)
Strip out any caret codes from a string.
8.916121
9.11538
0.97814
if ansi: text = text.replace('^^', '\x00') for token, code in _ANSI_CODES: text = text.replace(token, code) text = text.replace('\x00', '^') else: text = strip_caret_codes(text) return text
def colorize(text, ansi=True)
If the client wants ansi, replace the tokens with ansi sequences -- otherwise, simply strip them out.
4.053055
3.69942
1.095592
paragraphs = _PARA_BREAK.split(text) lines = [] columns -= padding for para in paragraphs: if para.isspace(): continue line = ' ' * indent for word in para.split(): if (len(line) + 1 + len(word)) > columns: lines.append(line) ...
def word_wrap(text, columns=80, indent=4, padding=2)
Given a block of text, breaks into a list of lines wrapped to length.
2.73779
2.827003
0.968443
if self.ungotten_char is None: if self.eof: c = '' else: c = self.file.read(1) if c == '': self.eof = True elif c == '\n': self.line_number += 1 else: c =...
def _get_char(self)
Read a character from input. @rtype: string
3.021866
2.595581
1.164235
skipped = 0 while True: c = self._get_char() if c != ' ' and c != '\t': if (c != '\n') or not self.multiline: self._unget_char(c) return skipped skipped += 1
def skip_whitespace(self)
Consume input until a non-whitespace character is encountered. The non-whitespace character is then ungotten, and the number of whitespace characters consumed is returned. If the tokenizer is in multiline mode, then newlines are whitespace. @rtype: int
4.141663
3.574951
1.158523
if not self.ungotten_token is None: token = self.ungotten_token self.ungotten_token = None if token.is_whitespace(): if want_leading: return token elif token.is_comment(): if want_comment: ...
def get(self, want_leading = False, want_comment = False)
Get the next token. @param want_leading: If True, return a WHITESPACE token if the first character read is whitespace. The default is False. @type want_leading: bool @param want_comment: If True, return a COMMENT token if the first token read is a comment. The default is False...
2.519742
2.420041
1.041198
token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') if not token.value.isdigit(): raise dns.exception.SyntaxError('expecting an integer') return int(token.value)
def get_int(self)
Read the next token and interpret it as an integer. @raises dns.exception.SyntaxError: @rtype: int
4.720992
3.363189
1.403725
value = self.get_int() if value < 0 or value > 255: raise dns.exception.SyntaxError('%d is not an unsigned 8-bit integer' % value) return value
def get_uint8(self)
Read the next token and interpret it as an 8-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int
4.278158
2.803465
1.526025
value = self.get_int() if value < 0 or value > 65535: raise dns.exception.SyntaxError('%d is not an unsigned 16-bit integer' % value) return value
def get_uint16(self)
Read the next token and interpret it as a 16-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int
4.098364
2.76338
1.483098
token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') if not token.value.isdigit(): raise dns.exception.SyntaxError('expecting an integer') value = long(token.value) if value < 0 or...
def get_uint32(self)
Read the next token and interpret it as a 32-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int
3.246086
2.676941
1.21261
token = self.get().unescape() if not (token.is_identifier() or token.is_quoted_string()): raise dns.exception.SyntaxError('expecting a string') return token.value
def get_string(self, origin=None)
Read the next token and interpret it as a string. @raises dns.exception.SyntaxError: @rtype: string
7.888384
4.248857
1.85659
token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') return token.value
def get_identifier(self, origin=None)
Read the next token and raise an exception if it is not an identifier. @raises dns.exception.SyntaxError: @rtype: string
9.11259
4.744107
1.920823
token = self.get() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') return dns.name.from_text(token.value, origin)
def get_name(self, origin=None)
Read the next token and interpret it as a DNS name. @raises dns.exception.SyntaxError: @rtype: dns.name.Name object
5.4775
3.055132
1.792885