code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return from_text_list(name, ttl, rdclass, rdtype, text_rdatas) | def from_text(name, ttl, rdclass, rdtype, *text_rdatas) | Create an RRset with the specified name, TTL, class, and type and with
the specified rdatas in text format.
@rtype: dns.rrset.RRset object | 3.33735 | 6.157791 | 0.541972 |
if isinstance(name, (str, unicode)):
name = dns.name.from_text(name, None)
if len(rdatas) == 0:
raise ValueError("rdata list must not be empty")
r = None
for rd in rdatas:
if r is None:
r = RRset(name, rd.rdclass, rd.rdtype)
r.update_ttl(ttl)
... | def from_rdata_list(name, ttl, rdatas) | Create an RRset with the specified name and TTL, and with
the specified list of rdata objects.
@rtype: dns.rrset.RRset object | 3.029755 | 2.964385 | 1.022052 |
if not super(RRset, self).match(rdclass, rdtype, covers):
return False
if self.name != name or self.deleting != deleting:
return False
return True | def match(self, name, rdclass, rdtype, covers, deleting=None) | Returns True if this rrset matches the specified class, type,
covers, and deletion state. | 3.627236 | 3.504338 | 1.03507 |
return super(RRset, self).to_text(self.name, origin, relativize,
self.deleting, **kw) | def to_text(self, origin=None, relativize=True, **kw) | Convert the RRset 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 ori... | 8.749801 | 8.917015 | 0.981248 |
return super(RRset, self).to_wire(self.name, file, compress, origin,
self.deleting, **kw) | def to_wire(self, file, compress=None, origin=None, **kw) | Convert the RRset to wire format. | 8.377426 | 5.885028 | 1.423515 |
key = (url_data.parent_url, url_data.cache_url)
key = repr(key)
if key in self.blacklist:
if url_data.valid:
del self.blacklist[key]
else:
self.blacklist[key] += 1
else:
if not url_data.valid:
se... | def log_url (self, url_data) | Put invalid url in blacklist, delete valid url from blacklist. | 3.363045 | 2.700995 | 1.245113 |
with codecs.open(self.filename, 'r', self.output_encoding,
self.codec_errors) as fd:
for line in fd:
line = line.rstrip()
if line.startswith('#') or not line:
continue
value, key = line.split(None, ... | def read_blacklist (self) | Read a previously stored blacklist from file fd. | 3.271196 | 3.029263 | 1.079865 |
oldmask = os.umask(0077)
for key, value in self.blacklist.items():
self.write(u"%d %s%s" % (value, repr(key), os.linesep))
self.close_fileoutput()
# restore umask
os.umask(oldmask) | def write_blacklist (self) | Write the blacklist. | 4.72118 | 4.518983 | 1.044744 |
# 'text' can also be a file, but we don't publish that fact
# since it's an implementation detail. The official file
# interface is from_file().
if filename is None:
filename = '<string>'
tok = dns.tokenizer.Tokenizer(text, filename)
reader = _MasterReader(tok, origin, rdclass, r... | def from_text(text, origin = None, rdclass = dns.rdataclass.IN,
relativize = True, zone_factory=Zone, filename=None,
allow_include=False, check_origin=True) | Build a zone object from a master file format string.
@param text: the master file format input
@type text: string.
@param origin: The origin of the zone; if not specified, the first
$ORIGIN statement in the master file will determine the origin of the
zone.
@type origin: dns.name.Name object o... | 4.572726 | 4.570164 | 1.000561 |
if sys.hexversion >= 0x02030000:
# allow Unicode filenames; turn on universal newline support
str_type = basestring
opts = 'rU'
else:
str_type = str
opts = 'r'
if isinstance(f, str_type):
if filename is None:
filename = f
f = file(f, ... | def from_file(f, origin = None, rdclass = dns.rdataclass.IN,
relativize = True, zone_factory=Zone, filename=None,
allow_include=True, check_origin=True) | Read a master file and build a zone object.
@param f: file or string. If I{f} is a string, it is treated
as the name of a file to open.
@param origin: The origin of the zone; if not specified, the first
$ORIGIN statement in the master file will determine the origin of the
zone.
@type origin: d... | 2.664061 | 2.763466 | 0.964029 |
z = None
for r in xfr:
if z is None:
if relativize:
origin = r.origin
else:
origin = r.answer[0].name
rdclass = r.answer[0].rdclass
z = zone_factory(origin, rdclass, relativize=relativize)
for rrset in r.answer... | def from_xfr(xfr, zone_factory=Zone, relativize=True) | Convert the output of a zone transfer generator into a zone object.
@param xfr: The xfr generator
@type xfr: generator of dns.message.Message objects
@param relativize: should names be relativized? The default is True.
It is essential that the relativize setting matches the one specified
to dns.qu... | 3.081507 | 2.78253 | 1.107448 |
name = self._validate_name(name)
node = self.nodes.get(name)
if node is None:
if not create:
raise KeyError
node = self.node_factory()
self.nodes[name] = node
return node | def find_node(self, name, create=False) | Find a node in the zone, possibly creating it.
@param name: the name of the node to find
@type name: dns.name.Name object or string
@param create: should the node be created if it doesn't exist?
@type create: bool
@raises KeyError: the name is not known and create was not specif... | 2.735708 | 2.954177 | 0.926047 |
try:
node = self.find_node(name, create)
except KeyError:
node = None
return node | def get_node(self, name, create=False) | Get a node in the zone, possibly creating it.
This method is like L{find_node}, except it returns None instead
of raising an exception if the node does not exist and creation
has not been requested.
@param name: the name of the node to find
@type name: dns.name.Name object or s... | 3.901994 | 4.157035 | 0.938648 |
name = self._validate_name(name)
if name in self.nodes:
del self.nodes[name] | def delete_node(self, name) | Delete the specified node if it exists.
It is not an error if the node does not exist. | 4.064126 | 3.929589 | 1.034237 |
name = self._validate_name(name)
if isinstance(rdtype, (str, unicode)):
rdtype = dns.rdatatype.from_text(rdtype)
if isinstance(covers, (str, unicode)):
covers = dns.rdatatype.from_text(covers)
node = self.find_node(name, create)
return node.find_... | def find_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE,
create=False) | Look for rdata with the specified name and type in the zone,
and return an rdataset encapsulating it.
The I{name}, I{rdtype}, and I{covers} parameters may be
strings, in which case they will be converted to their proper
type.
The rdataset returned is not a copy; changes to it w... | 2.337633 | 2.345907 | 0.996473 |
try:
rdataset = self.find_rdataset(name, rdtype, covers, create)
except KeyError:
rdataset = None
return rdataset | def get_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE,
create=False) | Look for rdata with the specified name and type in the zone,
and return an rdataset encapsulating it.
The I{name}, I{rdtype}, and I{covers} parameters may be
strings, in which case they will be converted to their proper
type.
The rdataset returned is not a copy; changes to it w... | 2.5933 | 2.888828 | 0.8977 |
name = self._validate_name(name)
if isinstance(rdtype, (str, unicode)):
rdtype = dns.rdatatype.from_text(rdtype)
if isinstance(covers, (str, unicode)):
covers = dns.rdatatype.from_text(covers)
node = self.get_node(name)
if not node is None:
... | def delete_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE) | Delete the rdataset matching I{rdtype} and I{covers}, if it
exists at the node specified by I{name}.
The I{name}, I{rdtype}, and I{covers} parameters may be
strings, in which case they will be converted to their proper
type.
It is not an error if the node does not exist, or if ... | 2.211442 | 2.189785 | 1.00989 |
if replacement.rdclass != self.rdclass:
raise ValueError('replacement.rdclass != zone.rdclass')
node = self.find_node(name, True)
node.replace_rdataset(replacement) | def replace_rdataset(self, name, replacement) | Replace an rdataset at name.
It is not an error if there is no rdataset matching I{replacement}.
Ownership of the I{replacement} object is transferred to the zone;
in other words, this method does not store a copy of I{replacement}
at the node, it stores I{replacement} itself.
... | 4.468554 | 3.94378 | 1.133064 |
name = self._validate_name(name)
if isinstance(rdtype, (str, unicode)):
rdtype = dns.rdatatype.from_text(rdtype)
if isinstance(covers, (str, unicode)):
covers = dns.rdatatype.from_text(covers)
rdataset = self.nodes[name].find_rdataset(self.rdclass, rdtyp... | def find_rrset(self, name, rdtype, covers=dns.rdatatype.NONE) | Look for rdata with the specified name and type in the zone,
and return an RRset encapsulating it.
The I{name}, I{rdtype}, and I{covers} parameters may be
strings, in which case they will be converted to their proper
type.
This method is less efficient than the similar
... | 2.193653 | 2.258837 | 0.971143 |
try:
rrset = self.find_rrset(name, rdtype, covers)
except KeyError:
rrset = None
return rrset | def get_rrset(self, name, rdtype, covers=dns.rdatatype.NONE) | Look for rdata with the specified name and type in the zone,
and return an RRset encapsulating it.
The I{name}, I{rdtype}, and I{covers} parameters may be
strings, in which case they will be converted to their proper
type.
This method is less efficient than the similar L{get_rd... | 2.646195 | 2.943559 | 0.898978 |
if isinstance(rdtype, (str, unicode)):
rdtype = dns.rdatatype.from_text(rdtype)
if isinstance(covers, (str, unicode)):
covers = dns.rdatatype.from_text(covers)
for (name, node) in self.iteritems():
for rds in node:
if rdtype == dns.rd... | def iterate_rdatasets(self, rdtype=dns.rdatatype.ANY,
covers=dns.rdatatype.NONE) | Return a generator which yields (name, rdataset) tuples for
all rdatasets in the zone which have the specified I{rdtype}
and I{covers}. If I{rdtype} is dns.rdatatype.ANY, the default,
then all rdatasets will be matched.
@param rdtype: int or string
@type rdtype: int or string
... | 2.168963 | 2.059275 | 1.053265 |
if isinstance(rdtype, (str, unicode)):
rdtype = dns.rdatatype.from_text(rdtype)
if isinstance(covers, (str, unicode)):
covers = dns.rdatatype.from_text(covers)
for (name, node) in self.iteritems():
for rds in node:
if rdtype == dns.rd... | def iterate_rdatas(self, rdtype=dns.rdatatype.ANY,
covers=dns.rdatatype.NONE) | Return a generator which yields (name, ttl, rdata) tuples for
all rdatas in the zone which have the specified I{rdtype}
and I{covers}. If I{rdtype} is dns.rdatatype.ANY, the default,
then all rdatas will be matched.
@param rdtype: int or string
@type rdtype: int or string
... | 2.270233 | 2.11217 | 1.074834 |
if sys.hexversion >= 0x02030000:
# allow Unicode filenames
str_type = basestring
else:
str_type = str
if nl is None:
opts = 'w'
else:
opts = 'wb'
if isinstance(f, str_type):
f = file(f, opts)
... | def to_file(self, f, sorted=True, relativize=True, nl=None) | Write a zone to a file.
@param f: file or string. If I{f} is a string, it is treated
as the name of a file to open.
@param sorted: if True, the file will be written with the
names sorted in DNSSEC order from least to greatest. Otherwise
the names will be written in whatever or... | 2.525444 | 2.401241 | 1.051725 |
if self.relativize:
name = dns.name.empty
else:
name = self.origin
if self.get_rdataset(name, dns.rdatatype.SOA) is None:
raise NoSOA
if self.get_rdataset(name, dns.rdatatype.NS) is None:
raise NoNS | def check_origin(self) | Do some simple checking of the zone's origin.
@raises dns.zone.NoSOA: there is no SOA RR
@raises dns.zone.NoNS: there is no NS RRset
@raises KeyError: there is no origin node | 3.855888 | 2.460696 | 1.566991 |
# Name
if self.current_origin is None:
raise UnknownOrigin
token = self.tok.get(want_leading = True)
if not token.is_whitespace():
self.last_name = dns.name.from_text(token.value, self.current_origin)
else:
token = self.tok.get()
... | def _rr_line(self) | Process one line from a DNS master file. | 2.973457 | 2.885833 | 1.030364 |
try:
while 1:
token = self.tok.get(True, True).unescape()
if token.is_eof():
if not self.current_file is None:
self.current_file.close()
if len(self.saved_state) > 0:
(se... | def read(self) | Read a DNS master file and build a zone object.
@raises dns.zone.NoSOA: No SOA RR was found at the zone origin
@raises dns.zone.NoNS: No NS RRset was found at the zone origin | 2.594348 | 2.452933 | 1.057652 |
path = normpath(path)
if os.name == 'nt':
# replace slashes with backslashes
path = path.replace("/", "\\")
if not os.path.isabs(path):
path = normpath(os.path.join(sys.prefix, path))
return path | def cnormpath (path) | Norm a path name to platform specific notation and make it absolute. | 2.518643 | 2.355736 | 1.069153 |
fname = os.path.join("doc", "changelog.txt")
release_date = "unknown"
with open(fname) as fd:
# the release date is on the first line
line = fd.readline()
mo = release_ro.search(line)
if mo:
release_date = mo.groups(1)
return release_date | def get_release_date () | Parse and return relase date as string from doc/changelog.txt. | 4.194088 | 3.490259 | 1.201655 |
prog = b"int main(){}\n"
pipe = subprocess.Popen(args,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
pipe.communicate(input=prog)
if os.WIFEXITED(pipe.returncode):
return os.WEXITSTATUS(pipe.returncode) == 0
return False | def cc_run (args) | Run the C compiler with a simple main program.
@return: successful exit flag
@rtype: bool | 3.482715 | 3.065675 | 1.136035 |
for fname in glob.glob("po/*" + suffix):
# basename (without extension) is a locale name
localename = os.path.splitext(os.path.basename(fname))[0]
domainname = "%s.mo" % package.lower()
yield (fname, os.path.join(
"share", "locale", localename, "LC_MESSAGES", domainn... | def list_message_files (package, suffix=".mo") | Return list of all found message files and their installation paths. | 4.676392 | 4.610662 | 1.014256 |
try:
f = open('MANIFEST')
except Exception:
print('\n*** SOURCE WARNING: The MANIFEST file is missing!')
return
try:
manifest = [l.strip() for l in f.readlines() if not l.startswith('#')]
finally:
f.close()
err = [line for line in manifest if not os.path.... | def check_manifest () | Snatched from roundup.sf.net.
Check that the files listed in the MANIFEST are present when the
source is unpacked. | 3.926234 | 3.58102 | 1.096401 |
outs = super(MyInstallLib, self).install()
infile = self.create_conf_file()
outfile = os.path.join(self.install_dir, os.path.basename(infile))
self.copy_file(infile, outfile)
outs.append(outfile)
return outs | def install (self) | Install the generated config file. | 3.996657 | 3.771758 | 1.059627 |
cmd_obj = self.distribution.get_command_obj("install")
cmd_obj.ensure_finalized()
# we have to write a configuration file because we need the
# <install_data> directory (and other stuff like author, url, ...)
# all paths are made absolute by cnormpath()
data = []... | def create_conf_file (self) | Create configuration file. | 4.021986 | 3.996409 | 1.0064 |
outs = super(MyInstallLib, self).get_outputs()
conf_output = self.get_conf_output()
outs.append(conf_output)
if self.compile:
outs.extend(self._bytecode_filenames([conf_output]))
return outs | def get_outputs (self) | Add the generated config file to the list of outputs. | 6.234542 | 5.605844 | 1.11215 |
if os.name == 'posix' and not self.dry_run:
# Make the data files we just installed world-readable,
# and the directories world-executable as well.
for path in self.get_outputs():
mode = os.stat(path)[stat.ST_MODE]
if stat.S_ISDIR(mode... | def fix_permissions (self) | Set correct read permissions on POSIX systems. Might also
be possible by setting umask? | 5.582386 | 4.972157 | 1.122729 |
cwd = os.getcwd()
data = []
data.append('config_dir = %r' % os.path.join(cwd, "config"))
data.append("install_data = %r" % cwd)
data.append("install_scripts = %r" % cwd)
self.create_conf_file(data)
super(MyDistribution, self).run_commands() | def run_commands (self) | Generate config file and run commands. | 4.19104 | 3.841329 | 1.091039 |
data.insert(0, "# this file is automatically created by setup.py")
data.insert(0, "# -*- coding: iso-8859-1 -*-")
if directory is None:
directory = os.getcwd()
filename = self.get_conf_filename(directory)
# add metadata
metanames = ("name", "version",... | def create_conf_file (self, data, directory=None) | Create local config file from given data (list of lines) in
the directory (or current directory if not given). | 3.11301 | 3.121412 | 0.997308 |
# For gcc >= 3 we can add -std=gnu99 to get rid of warnings.
extra = []
if self.compiler.compiler_type == 'unix':
option = "-std=gnu99"
if cc_supports_option(self.compiler.compiler, option):
extra.append(option)
# First, sanity-check the '... | def build_extensions (self) | Add -std=gnu99 to build options if supported. | 4.119589 | 3.739358 | 1.101684 |
if self.all:
# remove share directory
directory = os.path.join("build", "share")
if os.path.exists(directory):
remove_tree(directory, dry_run=self.dry_run)
else:
log.warn("'%s' does not exist -- can't clean it", directory)
... | def run (self) | Remove share directory on clean. | 4.997673 | 3.799882 | 1.315218 |
try:
parts = list(dns.ipv6.inet_aton(text).encode('hex_codec'))
origin = ipv6_reverse_domain
except Exception:
parts = ['%d' % ord(byte) for byte in dns.ipv4.inet_aton(text)]
origin = ipv4_reverse_domain
parts.reverse()
return dns.name.from_text('.'.join(parts), orig... | def from_address(text) | Convert an IPv4 or IPv6 address in textual form into a Name object whose
value is the reverse-map domain name of the address.
@param text: an IPv4 or IPv6 address in textual form (e.g. '127.0.0.1',
'::1')
@type text: str
@rtype: dns.name.Name object | 4.592043 | 3.798887 | 1.208787 |
if name.is_subdomain(ipv4_reverse_domain):
name = name.relativize(ipv4_reverse_domain)
labels = list(name.labels)
labels.reverse()
text = '.'.join(labels)
# run through inet_aton() to check syntax and make pretty.
return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text... | def to_address(name) | Convert a reverse map domain name into textual address form.
@param name: an IPv4 or IPv6 address in reverse-map form.
@type name: dns.name.Name object
@rtype: str | 2.590736 | 2.242919 | 1.155073 |
if text.isdigit():
v = int(text)
if v >= 0 and v <= 4095:
return v
v = _by_text.get(text.upper())
if v is None:
raise UnknownRcode
return v | def from_text(text) | Convert text into an rcode.
@param text: the texual rcode
@type text: string
@raises UnknownRcode: the rcode is unknown
@rtype: int | 4.681519 | 3.365592 | 1.390994 |
value = (flags & 0x000f) | ((ednsflags >> 20) & 0xff0)
if value < 0 or value > 4095:
raise ValueError('rcode must be >= 0 and <= 4095')
return value | def from_flags(flags, ednsflags) | Return the rcode value encoded by flags and ednsflags.
@param flags: the DNS flags
@type flags: int
@param ednsflags: the EDNS flags
@type ednsflags: int
@raises ValueError: rcode is < 0 or > 4095
@rtype: int | 3.877222 | 2.914377 | 1.330378 |
if value < 0 or value > 4095:
raise ValueError('rcode must be >= 0 and <= 4095')
v = value & 0xf
ev = long(value & 0xff0) << 20
return (v, ev) | def to_flags(value) | Return a (flags, ednsflags) tuple which encodes the rcode.
@param value: the rcode
@type value: int
@raises ValueError: rcode is < 0 or > 4095
@rtype: (int, int) tuple | 6.136691 | 3.705266 | 1.656208 |
text = _by_value.get(value)
if text is None:
text = str(value)
return text | def to_text(value) | Convert rcode into text.
@param value: the rcode
@type value: int
@rtype: string | 5.598246 | 4.629431 | 1.209273 |
ent = mo.group("entity")
s = mo.group()
if s.startswith('&#'):
if s[2] in 'xX':
radix = 16
else:
radix = 10
try:
num = int(ent, radix)
except (ValueError, OverflowError):
return u''
else:
num = name2codepoint.ge... | def _resolve_entity (mo) | Resolve a HTML entity.
@param mo: matched _entity_re object with a "entity" match group
@type mo: MatchObject instance
@return: resolved entity char, or empty string on error
@rtype: unicode string | 3.259886 | 2.876922 | 1.133116 |
charset = attrs.get_true('charset', u'')
if charset:
# <meta charset="utf-8">
# eg. in http://cn.dolphin-browser.com/activity/Dolphinjump
charset = charset.encode('ascii', 'ignore').lower()
elif attrs.get_true('http-equiv', u'').lower() == u"content-type":
# <meta http-e... | def set_encoding (parsobj, attrs) | Set document encoding for the HTML parser according to the <meta>
tag attribute information.
@param attrs: attributes of a <meta> HTML tag
@type attrs: dict
@return: None | 3.977154 | 4.062791 | 0.978922 |
for param in text.lower().split(';'):
param = param.strip()
if param.startswith('charset='):
charset = param[8:].strip()
try:
codecs.lookup(charset)
return charset
except (LookupError, ValueError):
pass
retu... | def get_ctype_charset (text) | Extract charset information from mime content type string, eg.
"text/html; charset=iso8859-1". | 2.750197 | 2.5105 | 1.095478 |
datafiles = ("GeoIPCity.dat", "GeoIP.dat")
if os.name == 'nt':
paths = (sys.exec_prefix, r"c:\geoip")
else:
paths = ("/usr/local/share/GeoIP", "/usr/share/GeoIP")
for path in paths:
for datafile in datafiles:
filename = os.path.join(path, datafile)
if... | def get_geoip_dat () | Find a GeoIP database, preferring city over country lookup. | 2.435975 | 2.336848 | 1.042419 |
if geoip is None:
# no geoip available
return None
try:
record = get_geoip_record(host)
except (geoip_error, socket.error):
log.debug(LOG_PLUGIN, "Geoip error for %r", host, exception=True)
# ignore lookup errors
return None
value = u""
if record ... | def get_location (host) | Get translated country and optional city name.
@return: country with optional city or an boolean False if not found | 4.061423 | 4.217662 | 0.962956 |
location = get_location(url_data.host)
if location:
url_data.add_info(_("URL is located in %(location)s.") %
{"location": _(location)}) | def check(self, url_data) | Try to ask GeoIP database for country info. | 7.231716 | 6.531263 | 1.107246 |
if os.name != 'posix':
# not supported
return 0.0
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except IOError:
# unsupported platform (non-Linux?)
return 0.0
# get ... | def _VmB (VmKey) | Parse /proc/<pid>/status file for given key.
@return: requested number value of status entry
@rtype: float | 4.270975 | 4.109138 | 1.039385 |
parts = strformat.url_unicode_split(url)
scheme = parts[0].lower()
domain = parts[1].lower()
domain, is_idn = urlutil.idna_encode(domain)
# allow redirection www.example.com -> example.com and vice versa
if domain.startswith('www.'):
domain = domain[4:]
if not (domain and scheme... | def get_intern_pattern (url) | Return intern pattern for given URL. Redirections to the same
domain with or without "www." prepended are allowed. | 4.576774 | 4.400901 | 1.039963 |
if url is None:
url = absolute_url(self.base_url, self.base_ref, self.parent_url)
if not url:
return None
return get_intern_pattern(url) | def get_intern_pattern (self, url=None) | Get pattern for intern URL matching.
@return non-empty regex pattern or None
@rtype String or None | 4.9434 | 4.771459 | 1.036035 |
if key not in self:
self._keys.append(key)
return super(ListDict, self).setdefault(key, *args) | def setdefault (self, key, *args) | Remember key order if key not found. | 4.248662 | 3.451923 | 1.23081 |
if key in self._keys:
self._keys.remove(key)
super(ListDict, self).pop(key) | def pop (self, key) | Remove key from dict and return value. | 4.335762 | 4.216372 | 1.028316 |
if self._keys:
k = self._keys[0]
v = self[k]
del self[k]
return (k, v)
raise KeyError("popitem() on empty dictionary") | def popitem (self) | Remove oldest key from dict and return item. | 2.856805 | 2.481206 | 1.151378 |
if key not in self or not self[key]:
return default
return self[key] | def get_true (self, key, default) | Return default element if key is not in the dict, or if self[key]
evaluates to False. Useful for example if value is None, but
default value should be an empty string. | 4.593807 | 3.013612 | 1.524353 |
assert isinstance(key, basestring)
return dict.get(self, key.lower(), def_val) | def get (self, key, def_val=None) | Return lowercase key value. | 5.222814 | 3.556817 | 1.468396 |
assert isinstance(key, basestring)
return dict.setdefault(self, key.lower(), *args) | def setdefault (self, key, *args) | Set lowercase key value and return. | 6.070049 | 3.709475 | 1.636363 |
d = cls()
for k in iterable:
dict.__setitem__(d, k.lower(), value)
return d | def fromkeys (cls, iterable, value=None) | Construct new caseless dict from given data. | 5.292427 | 3.216464 | 1.645418 |
assert isinstance(key, basestring)
return dict.pop(self, key.lower(), *args) | def pop (self, key, *args) | Remove lowercase key from dict and return value. | 6.375705 | 3.30273 | 1.930435 |
trim = int(0.05*len(self))
if trim:
items = super(LFUCache, self).items()
# sorting function for items
keyfunc = lambda x: x[1][0]
values = sorted(items, key=keyfunc)
for item in values[0:trim]:
del self[item[0]] | def shrink (self) | Shrink ca. 5% of entries. | 5.521511 | 4.852697 | 1.137823 |
if key in self:
return self[key]
self[key] = def_val
return def_val | def setdefault (self, key, def_val=None) | Update key usage if found and return value, else set and return
default. | 2.715374 | 2.359173 | 1.150986 |
return [(key, value[1]) for key, value in super(LFUCache, self).items()] | def items (self) | Return list of items, not updating usage count. | 9.72449 | 7.343745 | 1.324187 |
key, value = super(LFUCache, self).popitem()
return (key, value[1]) | def popitem (self) | Remove and return an item. | 6.852237 | 5.769012 | 1.187766 |
assert s is not None, "argument to unicode_safe was None"
if isinstance(s, unicode):
# s is already unicode, nothing to do
return s
return unicode(str(s), encoding, errors) | def unicode_safe (s, encoding=i18n.default_encoding, errors='replace') | Get unicode string without raising encoding errors. Unknown
characters of the given encoding will be ignored.
@param s: the string to be decoded
@type s: any object except None
@return: if s is already unicode, return s unchanged; else return
decoded unicode string of str(s)
@rtype: unicode | 3.894674 | 3.85256 | 1.010931 |
if not s:
return s
if len(s) < 2:
return s
if matching:
if s[0] in ("\"'") and s[0] == s[-1]:
s = s[1:-1]
else:
if s[0] in ("\"'"):
s = s[1:]
if s[-1] in ("\"'"):
s = s[:-1]
return s | def unquote (s, matching=False) | Remove leading and ending single and double quotes.
The quotes need to match if matching is True. Only one quote from each
end will be stripped.
@return: if s evaluates to False, return s as is, else return
string with stripped quotes
@rtype: unquoted string, or s unchanged if it is evaluting t... | 2.207664 | 2.176318 | 1.014403 |
if width <= 0 or not text:
return text
ret = []
for para in get_paragraphs(text):
text = " ".join(para.strip().split())
ret.extend(textwrap.wrap(text, width, **kwargs))
return os.linesep.join(ret) | def wrap (text, width, **kwargs) | Adjust lines of text to be not longer than width. The text will be
returned unmodified if width <= 0.
See textwrap.wrap() for a list of supported kwargs.
Returns text with lines no longer than given width. | 3.244034 | 2.988349 | 1.085561 |
lines = str(text).splitlines()
return os.linesep.join("%s%s" % (indent_string, x) for x in lines) | def indent (text, indent_string=" ") | Indent each line of text with the given indent string. | 3.478703 | 2.976942 | 1.168549 |
r
i = 0
if index < 0:
return 0
line = 1
while i < index:
if s[i] == '\n':
line += 1
i += 1
return line | def get_line_number (s, index) | r"""Return the line number of s[index] or zero on errors.
Lines are assumed to be separated by the ASCII character '\n'. | 3.518335 | 2.989518 | 1.17689 |
mo = _markup_re.search(s)
while mo:
s = s[0:mo.start()] + s[mo.end():]
mo = _markup_re.search(s)
return s | def remove_markup (s) | Remove all <*> html markup tags from s. | 2.26339 | 2.038721 | 1.110201 |
if b < 0:
raise ValueError("Invalid negative byte number")
if b < 1024:
return u"%sB" % locale.format("%d", b, grouping)
if b < 1024 * 10:
return u"%sKB" % locale.format("%d", (b // 1024), grouping)
if b < 1024 * 1024:
return u"%sKB" % locale.format("%.2f", (float(b)... | def strsize (b, grouping=True) | Return human representation of bytes b. A negative number of bytes
raises a value error. | 1.439144 | 1.405622 | 1.023849 |
return time.strftime("%Y-%m-%d %H:%M:%S", func(t)) + strtimezone() | def strtime (t, func=time.localtime) | Return ISO 8601 formatted time. | 4.879045 | 4.364261 | 1.117954 |
if duration < 0:
duration = abs(duration)
prefix = "-"
else:
prefix = ""
duration = math.ceil(duration)
if duration >= SECONDS_PER_HOUR: # 1 hour
# time, in hours:minutes:seconds
return "%s%02d:%02d:%02d" % (prefix, duration // SECONDS_PER_HOUR,
... | def strduration (duration) | Turn a time value in seconds into hh:mm:ss or mm:ss. | 2.003899 | 2.011247 | 0.996346 |
if do_translate:
# use global translator functions
global _, _n
else:
# do not translate
_ = lambda x: x
_n = lambda a, b, n: a if n==1 else b
if duration < 0:
duration = abs(duration)
prefix = "-"
else:
prefix = ""
if duration < 1... | def strduration_long (duration, do_translate=True) | Turn a time value in seconds into x hours, x minutes, etc. | 2.477763 | 2.447239 | 1.012473 |
if time.daylight:
zone = time.altzone
else:
zone = time.timezone
return "%+04d" % (-zone//SECONDS_PER_HOUR) | def strtimezone () | Return timezone info, %z on some platforms, but not supported on all. | 4.16993 | 3.893389 | 1.071028 |
assert length >= 0, "length limit must be a non-negative integer"
if not s or len(s) <= length:
return s
if length == 0:
return ""
return "%s..." % s[:length] | def limit (s, length=72) | If the length of the string exceeds the given limit, it will be cut
off and three dots will be appended.
@param s: the string to limit
@type s: string
@param length: maximum length
@type length: non-negative integer
@return: limited string, at most length+3 characters long | 3.574422 | 3.422718 | 1.044323 |
sock = socket.socket(family, socktype, proto=proto)
sock.settimeout(timeout)
socktypes_inet = [socket.AF_INET]
if has_ipv6:
socktypes_inet.append(socket.AF_INET6)
if family in socktypes_inet and socktype == socket.SOCK_STREAM:
# disable NAGLE algorithm, which means sending pendi... | def create_socket (family, socktype, proto=0, timeout=60) | Create a socket with given family and type. If SSL context
is given an SSL socket is created. | 4.062357 | 4.183149 | 0.971124 |
return url_data.valid and url_data.scheme == 'https' and \
not url_data.extern[0] and url_data.url_connection is not None | def applies_to(self, url_data) | Check validity, scheme, extern and url_connection. | 10.572868 | 4.328312 | 2.442723 |
host = url_data.urlparts[1]
if host in self.checked_hosts:
return
self.checked_hosts.add(host)
cert = url_data.ssl_cert
config = url_data.aggregate.config
if cert and 'notAfter' in cert:
self.check_ssl_valid_date(url_data, cert)
el... | def check(self, url_data) | Run all SSL certificate checks that have not yet been done.
OpenSSL already checked the SSL notBefore and notAfter dates. | 5.036358 | 4.31146 | 1.168133 |
import ssl
try:
notAfter = ssl.cert_time_to_seconds(cert['notAfter'])
except ValueError as msg:
msg = _('Invalid SSL certficate "notAfter" value %r') % cert['notAfter']
url_data.add_warning(msg)
return
curTime = time.time()
... | def check_ssl_valid_date(self, url_data, cert) | Check if the certificate is still valid, or if configured check
if it's at least a number of days valid. | 3.560676 | 3.436098 | 1.036256 |
config = dict()
section = cls.__name__
option = sslcertwarndays
if configparser.has_option(section, option):
num = configparser.getint(section, option)
if num > 0:
config[option] = num
else:
msg = _("invalid val... | def read_config(cls, configparser) | Read configuration file options. | 4.357183 | 4.240793 | 1.027446 |
log.debug(LOG_PLUGIN, "checking content for invalid anchors")
# list of parsed anchors
self.anchors = []
find_links(url_data, self.add_anchor, linkparse.AnchorTags)
self.check_anchor(url_data) | def check(self, url_data) | Check content for invalid anchors. | 12.921151 | 9.443009 | 1.36833 |
self.anchors.append((url, line, column, name, base)) | def add_anchor (self, url, line, column, name, base) | Add anchor URL. | 3.930786 | 2.752969 | 1.427835 |
log.debug(LOG_PLUGIN, "checking anchor %r in %s", url_data.anchor, self.anchors)
enc = lambda anchor: urlutil.url_quote_part(anchor, encoding=url_data.encoding)
if any(x for x in self.anchors if enc(x[0]) == url_data.anchor):
return
if self.anchors:
ancho... | def check_anchor(self, url_data) | If URL is valid, parseable and has an anchor, check it.
A warning is logged and True is returned if the anchor is not found. | 4.360538 | 4.379797 | 0.995603 |
if resolver is None:
resolver = get_default_resolver()
return resolver.query(qname, rdtype, rdclass, tcp, source, raise_on_no_answer) | def query(qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
tcp=False, source=None, raise_on_no_answer=True, resolver=None) | Query nameservers to find the answer to the question.
This is a convenience function that uses the default resolver
object to make the query.
@see: L{dns.resolver.Resolver.query} for more information on the
parameters. | 1.909195 | 2.341327 | 0.815433 |
if isinstance(name, basestring):
name = dns.name.from_text(name, dns.name.root)
if resolver is None:
resolver = get_default_resolver()
if not name.is_absolute():
raise NotAbsolute(name)
while 1:
try:
answer = resolver.query(name, dns.rdatatype.SOA, rdcla... | def zone_for_name(name, rdclass=dns.rdataclass.IN, tcp=False, resolver=None) | Find the name of the zone which contains the specified name.
@param name: the query name
@type name: absolute dns.name.Name object or string
@param rdclass: The query class
@type rdclass: int
@param tcp: use TCP to make the query (default is False).
@type tcp: bool
@param resolver: the reso... | 2.791666 | 2.799999 | 0.997024 |
now = time.time()
if self.next_cleaning <= now:
keys_to_delete = []
for (k, v) in self.data.iteritems():
if v.expiration <= now:
keys_to_delete.append(k)
for k in keys_to_delete:
del self.data[k]
... | def maybe_clean(self) | Clean the cache if it's time to do so. | 2.475331 | 2.199853 | 1.125226 |
self.maybe_clean()
v = self.data.get(key)
if v is None or v.expiration <= time.time():
return None
return v | def get(self, key) | Get the answer associated with I{key}. Returns None if
no answer is cached for the key.
@param key: the key
@type key: (dns.name.Name, int, int) tuple whose values are the
query name, rdtype, and rdclass.
@rtype: dns.resolver.Answer object or None | 6.10811 | 6.518428 | 0.937053 |
self.maybe_clean()
self.data[key] = value | def put(self, key, value) | Associate key and value in the cache.
@param key: the key
@type key: (dns.name.Name, int, int) tuple whose values are the
query name, rdtype, and rdclass.
@param value: The answer being cached
@type value: dns.resolver.Answer object | 12.643548 | 17.00844 | 0.743369 |
if not key is None:
if key in self.data:
del self.data[key]
else:
self.data = {}
self.next_cleaning = time.time() + self.cleaning_interval | def flush(self, key=None) | Flush the cache.
If I{key} is specified, only that item is flushed. Otherwise
the entire cache is flushed.
@param key: the key to flush
@type key: (dns.name.Name, int, int) tuple or None | 3.61012 | 4.139091 | 0.872201 |
self.domain = \
dns.name.Name(dns.name.from_text(socket.gethostname())[1:])
if len(self.domain) == 0:
self.domain = dns.name.root
self.nameservers = []
self.localhosts = set([
'localhost',
'loopback',
'127.0.0.1',
'... | def reset(self) | Reset all resolver configuration to the defaults. | 3.434211 | 3.277151 | 1.047926 |
if isinstance(f, basestring):
try:
f = open(f, 'r')
except IOError:
# /etc/resolv.conf doesn't exist, can't be read, etc.
# We'll just use the default resolver configuration.
self.nameservers = ['127.0.0.1']
... | def read_resolv_conf(self, f) | Process f as a file in the /etc/resolv.conf format. If f is
a string, it is used as the name of the file to open; otherwise it
is treated as the file itself. | 2.002892 | 1.972407 | 1.015456 |
if os.name != 'posix':
# only POSIX is supported right now
return []
try:
from linkcheck.network import IfConfig
except ImportError:
return []
ifaddrs = []
ifc = IfConfig()
for iface in ifc.getInterfaceList(flags=If... | def read_local_ifaddrs (self) | IP addresses for all active interfaces.
@return: list of IP addresses
@rtype: list of strings | 4.03253 | 4.081169 | 0.988082 |
# we call str() on nameservers to convert it from unicode to ascii
nameservers = str(nameservers)
split_char = self._determine_split_char(nameservers)
ns_list = nameservers.split(split_char)
for ns in ns_list:
if not ns in self.nameservers:
se... | def _config_win32_nameservers(self, nameservers) | Configure a NameServer registry entry. | 3.947104 | 3.969707 | 0.994306 |
# we call str() on domain to convert it from unicode to ascii
self.domain = dns.name.from_text(str(domain)) | def _config_win32_domain(self, domain) | Configure a Domain registry entry. | 9.029305 | 8.286053 | 1.089699 |
# we call str() on search to convert it from unicode to ascii
search = str(search)
split_char = self._determine_split_char(search)
search_list = search.split(split_char)
for s in search_list:
if not s in self.search:
self.search.add(dns.name.f... | def _config_win32_search(self, search) | Configure a Search registry entry. | 5.152505 | 5.242108 | 0.982907 |
try:
ip, rtype = _winreg.QueryValueEx(key, name)
if isinstance(ip, basestring) and ip:
ip = str(ip).lower()
self.localhosts.add(ip)
self.interfaces.add(ip)
except WindowsError:
pass | def _config_win32_add_ifaddr (self, key, name) | Add interface ip address to self.localhosts. | 4.827097 | 4.06999 | 1.186022 |
try:
enable_dhcp, rtype = _winreg.QueryValueEx(key, 'EnableDHCP')
except WindowsError:
enable_dhcp = False
if enable_dhcp:
try:
servers, rtype = _winreg.QueryValueEx(key, 'DhcpNameServer')
except WindowsError:
... | def _config_win32_fromkey(self, key) | Extract DNS info from a registry key. | 1.953666 | 1.911193 | 1.022223 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.