text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self): """Read a wire format DNS message and build a dns.message.Message object."""
l = len(self.wire) if l < 12: raise ShortHeader (self.message.id, self.message.flags, qcount, ancount, aucount, adcount) = struct.unpack('!HHHHHH', self.wire[:12]) self.current = 12 if dns.opcode.is_update(self.message.flags): self.updating = True self._get_question(qcount) if self.question_only: return self._get_section(self.message.answer, ancount) self._get_section(self.message.authority, aucount) self._get_section(self.message.additional, adcount) if self.current != l: raise TrailingJunk if self.message.multi and self.message.tsig_ctx and \ not self.message.had_tsig: self.message.tsig_ctx.update(self.wire)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _header_line(self, section): """Process one line from the text format header section."""
token = self.tok.get() what = token.value if what == 'id': self.message.id = self.tok.get_int() elif what == 'flags': while True: token = self.tok.get() if not token.is_identifier(): self.tok.unget(token) break self.message.flags = self.message.flags | \ dns.flags.from_text(token.value) if dns.opcode.is_update(self.message.flags): self.updating = True elif what == 'edns': self.message.edns = self.tok.get_int() self.message.ednsflags = self.message.ednsflags | \ (self.message.edns << 16) elif what == 'eflags': if self.message.edns < 0: self.message.edns = 0 while True: token = self.tok.get() if not token.is_identifier(): self.tok.unget(token) break self.message.ednsflags = self.message.ednsflags | \ dns.flags.edns_from_text(token.value) elif what == 'payload': self.message.payload = self.tok.get_int() if self.message.edns < 0: self.message.edns = 0 elif what == 'opcode': text = self.tok.get_string() self.message.flags = self.message.flags | \ dns.opcode.to_flags(dns.opcode.from_text(text)) elif what == 'rcode': text = self.tok.get_string() self.message.set_rcode(dns.rcode.from_text(text)) else: raise UnknownHeaderField self.tok.get_eol()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _question_line(self, section): """Process one line from the text format question section."""
token = self.tok.get(want_leading = True) if not token.is_whitespace(): self.last_name = dns.name.from_text(token.value, None) name = self.last_name token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError # Class try: rdclass = dns.rdataclass.from_text(token.value) token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError except dns.exception.SyntaxError: raise dns.exception.SyntaxError except Exception: rdclass = dns.rdataclass.IN # Type rdtype = dns.rdatatype.from_text(token.value) self.message.find_rrset(self.message.question, name, rdclass, rdtype, create=True, force_unique=True) if self.updating: self.zone_rdclass = rdclass self.tok.get_eol()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rr_line(self, section): """Process one line from the text format answer, authority, or additional data sections. """
deleting = None # Name token = self.tok.get(want_leading = True) if not token.is_whitespace(): self.last_name = dns.name.from_text(token.value, None) name = self.last_name token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError # TTL try: ttl = int(token.value, 0) token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError except dns.exception.SyntaxError: raise dns.exception.SyntaxError except Exception: ttl = 0 # Class try: rdclass = dns.rdataclass.from_text(token.value) token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError if rdclass == dns.rdataclass.ANY or rdclass == dns.rdataclass.NONE: deleting = rdclass rdclass = self.zone_rdclass except dns.exception.SyntaxError: raise dns.exception.SyntaxError except Exception: rdclass = dns.rdataclass.IN # Type rdtype = dns.rdatatype.from_text(token.value) token = self.tok.get() if not token.is_eol_or_eof(): self.tok.unget(token) rd = dns.rdata.from_text(rdclass, rdtype, self.tok, None) covers = rd.covers() else: rd = None covers = dns.rdatatype.NONE rrset = self.message.find_rrset(section, name, rdclass, rdtype, covers, deleting, True, self.updating) if not rd is None: rrset.add(rd, ttl)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self): """Read a text format DNS message and build a dns.message.Message object."""
line_method = self._header_line section = None while 1: token = self.tok.get(True, True) if token.is_eol_or_eof(): break if token.is_comment(): u = token.value.upper() if u == 'HEADER': line_method = self._header_line elif u == 'QUESTION' or u == 'ZONE': line_method = self._question_line section = self.message.question elif u == 'ANSWER' or u == 'PREREQ': line_method = self._rr_line section = self.message.answer elif u == 'AUTHORITY' or u == 'UPDATE': line_method = self._rr_line section = self.message.authority elif u == 'ADDITIONAL': line_method = self._rr_line section = self.message.additional self.tok.get_eol() continue self.tok.unget(token) line_method(section)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_text(text): """Convert text into an opcode. @param text: the textual opcode @type text: string @raises UnknownOpcode: the opcode is unknown @rtype: int """
if text.isdigit(): value = int(text) if value >= 0 and value <= 15: return value value = _by_text.get(text.upper()) if value is None: raise UnknownOpcode return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chmod(config): """Set correct file permissions."""
output_dir = config["output_dir"] for dirpath, dirnames, filenames in os.walk(output_dir): for dirname in dirnames: os.chmod(os.path.join(dirpath, dirname), 0755) for filename in filenames: os.chmod(os.path.join(dirpath, filename), 0644)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trace_filter (patterns): """Add given patterns to trace filter set or clear set if patterns is None."""
if patterns is None: _trace_filter.clear() else: _trace_filter.update(re.compile(pat) for pat in patterns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _trace (frame, event, arg): """Trace function calls."""
if event in ('call', 'c_call'): _trace_line(frame, event, arg) elif event in ('return', 'c_return'): _trace_line(frame, event, arg) print(" return:", arg) #elif event in ('exception', 'c_exception'): # _trace_line(frame, event, arg) return _trace
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _trace_full (frame, event, arg): """Trace every executed line."""
if event == "line": _trace_line(frame, event, arg) else: _trace(frame, event, arg) return _trace_full
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _trace_line (frame, event, arg): """Print current executed line."""
name = frame.f_globals["__name__"] if name in _trace_ignore: return _trace_line for pat in _trace_filter: if not pat.match(name): return _trace_line lineno = frame.f_lineno filename = frame.f_globals["__file__"] if filename.endswith((".pyc", ".pyo")): filename = filename[:-1] line = linecache.getline(filename, lineno) currentThread = threading.currentThread() tid = currentThread.ident tname = currentThread.getName() args = (tid, tname, time.time(), line.rstrip(), name, lineno) print("THREAD(%d) %r %.2f %s # %s:%d" % args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_output (self): """Write start of checking info as DOT comment."""
super(DOTLogger, self).start_output() if self.has_part("intro"): self.write_intro() self.writeln() self.writeln(u"digraph G {") self.writeln(u" graph [") self.writeln(u" charset=\"%s\"," % self.get_charset_encoding()) self.writeln(u" ];") self.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comment (self, s, **args): """Write DOT comment."""
self.write(u"// ") self.writeln(s=s, **args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_edge (self, node): """Write edge from parent to node."""
source = dotquote(self.nodes[node["parent_url"]]["label"]) target = dotquote(node["label"]) self.writeln(u' "%s" -> "%s" [' % (source, target)) self.writeln(u' label="%s",' % dotquote(node["edge"])) if self.has_part("result"): self.writeln(u" valid=%d," % node["valid"]) self.writeln(u" ];")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_url (self, url_data): """ Log URL data in custom XML format. """
self.xml_starttag(u'urldata') if self.has_part('url'): self.xml_tag(u"url", unicode(url_data.base_url)) if url_data.name and self.has_part('name'): self.xml_tag(u"name", unicode(url_data.name)) if url_data.parent_url and self.has_part('parenturl'): attrs = { u'line': u"%d" % url_data.line, u'column': u"%d" % url_data.column, } self.xml_tag(u"parent", unicode(url_data.parent_url), attrs=attrs) if url_data.base_ref and self.has_part('base'): self.xml_tag(u"baseref", unicode(url_data.base_ref)) if self.has_part("realurl"): self.xml_tag(u"realurl", unicode(url_data.url)) if self.has_part("extern"): self.xml_tag(u"extern", u"%d" % (1 if url_data.extern else 0)) if url_data.dltime >= 0 and self.has_part("dltime"): self.xml_tag(u"dltime", u"%f" % url_data.dltime) if url_data.size >= 0 and self.has_part("dlsize"): self.xml_tag(u"dlsize", u"%d" % url_data.size) if url_data.checktime and self.has_part("checktime"): self.xml_tag(u"checktime", u"%f" % url_data.checktime) if self.has_part("level"): self.xml_tag(u"level", u"%d" % url_data.level) if url_data.info and self.has_part('info'): self.xml_starttag(u"infos") for info in url_data.info: self.xml_tag(u"info", info) self.xml_endtag(u"infos") if url_data.modified and self.has_part('modified'): self.xml_tag(u"modified", self.format_modified(url_data.modified)) if url_data.warnings and self.has_part('warning'): self.xml_starttag(u"warnings") for tag, data in url_data.warnings: attrs = {} if tag: attrs["tag"] = tag self.xml_tag(u"warning", data, attrs) self.xml_endtag(u"warnings") if self.has_part("result"): attrs = {} if url_data.result: attrs["result"] = url_data.result self.xml_tag(u"valid", u"%d" % (1 if url_data.valid else 0), attrs) self.xml_endtag(u'urldata') self.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_w3_errors (url_data, xml, w3type): """Add warnings for W3C HTML or CSS errors in xml format. w3type is either "W3C HTML" or "W3C CSS"."""
dom = parseString(xml) for error in dom.getElementsByTagName('m:error'): warnmsg = _("%(w3type)s validation error at line %(line)s col %(column)s: %(msg)s") attrs = { "w3type": w3type, "line": getXmlText(error, "m:line"), "column": getXmlText(error, "m:col"), "msg": getXmlText(error, "m:message"), } url_data.add_warning(warnmsg % attrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getXmlText (parent, tag): """Return XML content of given tag in parent element."""
elem = parent.getElementsByTagName(tag)[0] # Yes, the DOM standard is awful. rc = [] for node in elem.childNodes: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_w3_time (self): """Make sure the W3C validators are at most called once a second."""
if time.time() - self.last_w3_call < W3Timer.SleepSeconds: time.sleep(W3Timer.SleepSeconds) self.last_w3_call = time.time()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self, url_data): """Check HTML syntax of given URL."""
self.timer.check_w3_time() session = url_data.session try: body = {'uri': url_data.url, 'output': 'soap12'} response = session.post('http://validator.w3.org/check', data=body) response.raise_for_status() if response.headers.get('x-w3c-validator-status', 'Invalid') == 'Valid': url_data.add_info(u"W3C Validator: %s" % _("valid HTML syntax")) return check_w3_errors(url_data, response.text, "W3C HTML") except requests.exceptions.RequestException: pass # ignore service failures except Exception as msg: log.warn(LOG_PLUGIN, _("HTML syntax check plugin error: %(msg)s ") % {"msg": msg})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_filter_url(self, url_data, do_print): """Update accounting data and determine if URL should be included in the sitemap. """
self.stats.log_url(url_data, do_print) if self.disabled: return # initialize prefix and priority if self.prefix is None: if not url_data.url.startswith(HTTP_SCHEMES): log.warn(LOG_CHECK, "Sitemap URL %r does not start with http: or https:.", url_data.url) self.disabled = True return self.prefix = url_data.url # first URL (ie. the homepage) gets priority 1.0 per default priority = 1.0 elif url_data.url == self.prefix: return else: # all other pages get priority 0.5 per default priority = 0.5 if self.priority is not None: priority = self.priority # ignore the do_print flag and determine ourselves if we filter the url if (url_data.valid and url_data.url.startswith(HTTP_SCHEMES) and url_data.url.startswith(self.prefix) and url_data.content_type in HTML_TYPES): self.log_url(url_data, priority=priority)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_url (self, url_data, priority=None): """Log URL data in sitemap format."""
self.xml_starttag(u'url') self.xml_tag(u'loc', url_data.url) if url_data.modified: self.xml_tag(u'lastmod', self.format_modified(url_data.modified, sep="T")) self.xml_tag(u'changefreq', self.frequency) self.xml_tag(u'priority', "%.2f" % priority) self.xml_endtag(u'url') self.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset (self): """ Initialize HTTP specific variables. """
super(HttpUrl, self).reset() # initialize check data # server headers self.headers = {} self.auth = None self.ssl_cipher = None self.ssl_cert = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content_allows_robots (self): """ Return False if the content of this URL forbids robots to search for recursive links. """
if not self.is_html(): return True # construct parser object handler = linkparse.MetaRobotsFinder() parser = htmlsax.parser(handler) handler.parser = parser if self.charset: parser.encoding = self.charset # parse try: parser.feed(self.get_content()) parser.flush() except linkparse.StopParse as msg: log.debug(LOG_CHECK, "Stopped parsing: %s", msg) pass # break cyclic dependencies handler.parser = None parser.handler = None return handler.follow
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_size_info (self): """Get size of URL content from HTTP header."""
if self.headers and "Content-Length" in self.headers and \ "Transfer-Encoding" not in self.headers: # Note that content-encoding causes size differences since # the content data is always decoded. try: self.size = int(self.getheader("Content-Length")) except (ValueError, OverflowError): pass else: self.size = -1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_request(self): """Build a prepared request object."""
clientheaders = {} if (self.parent_url and self.parent_url.lower().startswith(HTTP_SCHEMAS)): clientheaders["Referer"] = self.parent_url kwargs = dict( method='GET', url=self.url, headers=clientheaders, ) if self.auth: kwargs['auth'] = self.auth log.debug(LOG_CHECK, "Prepare request with %s", kwargs) request = requests.Request(**kwargs) return self.session.prepare_request(request)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_request(self, request): """Send request and store response in self.url_connection."""
# throttle the number of requests to each host self.aggregate.wait_for_host(self.urlparts[1]) kwargs = self.get_request_kwargs() kwargs["allow_redirects"] = False self._send_request(request, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_request(self, request, **kwargs): """Send GET request."""
log.debug(LOG_CHECK, "Send request %s with %s", request, kwargs) log.debug(LOG_CHECK, "Request headers %s", request.headers) self.url_connection = self.session.send(request, **kwargs) self.headers = self.url_connection.headers self._add_ssl_info()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_ssl_sock(self): """Get raw SSL socket."""
assert self.scheme == u"https", self raw_connection = self.url_connection.raw._connection if raw_connection.sock is None: # sometimes the socket is not yet connected # see https://github.com/kennethreitz/requests/issues/1966 raw_connection.connect() return raw_connection.sock
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_ssl_info(self): """Add SSL cipher info."""
if self.scheme == u'https': sock = self._get_ssl_sock() if hasattr(sock, 'cipher'): self.ssl_cert = sock.getpeercert() else: # using pyopenssl cert = sock.connection.get_peer_certificate() self.ssl_cert = httputil.x509_to_dict(cert) log.debug(LOG_CHECK, "Got SSL certificate %s", self.ssl_cert) else: self.ssl_cert = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_redirects(self, request): """Return iterator of redirects for given request."""
kwargs = self.get_request_kwargs() return self.session.resolve_redirects(self.url_connection, request, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def follow_redirections(self, request): """Follow all redirections of http response."""
log.debug(LOG_CHECK, "follow all redirections") if self.is_redirect(): # run connection plugins for old connection self.aggregate.plugin_manager.run_connection_plugins(self) response = None for response in self.get_redirects(request): newurl = response.url log.debug(LOG_CHECK, "Redirected to %r", newurl) self.aliases.append(newurl) # XXX on redirect errors this is not printed self.add_info(_("Redirected to `%(url)s'.") % {'url': newurl}) # Reset extern and recalculate self.extern = None self.set_extern(newurl) self.urlparts = strformat.url_unicode_split(newurl) self.build_url_parts() self.url_connection = response self.headers = response.headers self.url = urlutil.urlunsplit(self.urlparts) self.scheme = self.urlparts[0].lower() self._add_ssl_info() self._add_response_info() if self.is_redirect(): # run connection plugins for old connection self.aggregate.plugin_manager.run_connection_plugins(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getheader (self, name, default=None): """Get decoded header value. @return: decoded header value or default of not found @rtype: unicode or type of default """
value = self.headers.get(name) if value is None: return default return unicode_safe(value, encoding=HEADER_ENCODING)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_response (self): """Check final result and log it."""
if self.url_connection.status_code >= 400: self.set_result(u"%d %s" % (self.url_connection.status_code, self.url_connection.reason), valid=False) else: if self.url_connection.status_code == 204: # no content self.add_warning(self.url_connection.reason, tag=WARN_HTTP_EMPTY_CONTENT) if self.url_connection.status_code >= 200: self.set_result(u"%r %s" % (self.url_connection.status_code, self.url_connection.reason)) else: self.set_result(_("OK"))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_content(self): """Return data and data size for this URL. Can be overridden in subclasses."""
maxbytes = self.aggregate.config["maxfilesizedownload"] buf = StringIO() for data in self.url_connection.iter_content(chunk_size=self.ReadChunkBytes): if buf.tell() + len(data) > maxbytes: raise LinkCheckerError(_("File size too large")) buf.write(data) return buf.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_file(type_str, open_files, basedir): """Get already opened file, or open and initialize a new one."""
if type_str not in open_files: filename = type_str+".html" encoding = 'utf-8' fd = codecs.open(os.path.join(basedir, filename), 'w', encoding) open_files[type_str] = fd write_html_header(fd, type_str, encoding) return open_files[type_str]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_loggers(): """Return list of Logger classes."""
from .. import loader modules = loader.get_package_modules('logger') return list(loader.get_plugins(modules, [_Logger]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset (self): """Reset all log statistics to default values."""
# number of logged URLs self.number = 0 # number of encountered URL errors self.errors = 0 # number of URL errors that were printed self.errors_printed = 0 # number of URL warnings self.warnings = 0 # number of URL warnings that were printed self.warnings_printed = 0 # number of internal errors self.internal_errors = 0 # link types self.link_types = ContentTypes.copy() # URL length statistics self.max_url_length = 0 self.min_url_length = 0 self.avg_url_length = 0.0 self.avg_number = 0 # overall downloaded bytes self.downloaded_bytes = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_url (self, url_data, do_print): """Log URL statistics."""
self.number += 1 if not url_data.valid: self.errors += 1 if do_print: self.errors_printed += 1 num_warnings = len(url_data.warnings) self.warnings += num_warnings if do_print: self.warnings_printed += num_warnings if url_data.content_type: key = url_data.content_type.split('/', 1)[0].lower() if key not in self.link_types: key = "other" elif url_data.url.startswith(u"mailto:"): key = "mail" else: key = "other" self.link_types[key] += 1 if url_data.url: l = len(url_data.url) self.max_url_length = max(l, self.max_url_length) if self.min_url_length == 0: self.min_url_length = l else: self.min_url_length = min(l, self.min_url_length) # track average number separately since empty URLs do not count self.avg_number += 1 # calculate running average self.avg_url_length += (l - self.avg_url_length) / self.avg_number
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_args(self, kwargs): """Construct log configuration from default and user args."""
args = dict(self.LoggerArgs) args.update(kwargs) return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode (self, s): """Encode string with output encoding."""
assert isinstance(s, unicode) return s.encode(self.output_encoding, self.codec_errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_fileoutput (self): """Start output to configured file."""
path = os.path.dirname(self.filename) try: if path and not os.path.isdir(path): os.makedirs(path) self.fd = self.create_fd() self.close_fd = True except IOError: msg = sys.exc_info()[1] log.warn(LOG_CHECK, "Could not open file %r for writing: %s\n" "Disabling log output of %s", self.filename, msg, self) self.fd = dummy.Dummy() self.is_active = False self.filename = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_fd (self): """Create open file descriptor."""
if self.filename is None: return i18n.get_encoded_writer(encoding=self.output_encoding, errors=self.codec_errors) return codecs.open(self.filename, "wb", self.output_encoding, self.codec_errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_fileoutput (self): """ Flush and close the file output denoted by self.fd. """
if self.fd is not None: try: self.flush() except IOError: # ignore flush errors pass if self.close_fd: try: self.fd.close() except IOError: # ignore close errors pass self.fd = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_date (self): """ Check for special dates. """
now = datetime.date.today() if now.day == 7 and now.month == 1: msg = _("Happy birthday for LinkChecker, I'm %d years old today!") self.comment(msg % (now.year - 2000))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap (self, lines, width): """ Return wrapped version of given lines. """
sep = os.linesep+os.linesep text = sep.join(lines) kwargs = dict(subsequent_indent=" "*self.max_indent, initial_indent=" "*self.max_indent, break_long_words=False, break_on_hyphens=False) return strformat.wrap(text, width, **kwargs).lstrip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write (self, s, **args): """Write string to output descriptor. Strips control characters from string before writing. """
if self.filename is not None: self.start_fileoutput() if self.fd is None: # Happens when aborting threads times out log.warn(LOG_CHECK, "writing to unitialized or closed file") else: try: self.fd.write(s, **args) except IOError: msg = sys.exc_info()[1] log.warn(LOG_CHECK, "Could not write to output file: %s\n" "Disabling log output of %s", msg, self) self.close_fileoutput() self.fd = dummy.Dummy() self.is_active = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeln (self, s=u"", **args): """ Write string to output descriptor plus a newline. """
self.write(u"%s%s" % (s, unicode(os.linesep)), **args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_output (self): """ Start log output. """
# map with spaces between part name and value if self.logparts is None: parts = Fields.keys() else: parts = self.logparts values = (self.part(x) for x in parts) # maximum indent for localized log part names self.max_indent = max(len(x) for x in values)+1 for key in parts: numspaces = (self.max_indent - len(self.part(key))) self.logspaces[key] = u" " * numspaces self.stats.reset() self.starttime = time.time()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_filter_url (self, url_data, do_print): """ Log a new url with this logger if do_print is True. Else only update accounting data. """
self.stats.log_url(url_data, do_print) if do_print: self.log_url(url_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_intro (self): """Write intro comments."""
self.comment(_("created by %(app)s at %(time)s") % {"app": configuration.AppName, "time": strformat.strtime(self.starttime)}) self.comment(_("Get the newest version at %(url)s") % {'url': configuration.Url}) self.comment(_("Write comments and bugs to %(url)s") % {'url': configuration.SupportUrl}) self.comment(_("Support this project at %(url)s") % {'url': configuration.DonateUrl}) self.check_date()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_outro (self): """Write outro comments."""
self.stoptime = time.time() duration = self.stoptime - self.starttime self.comment(_("Stopped checking at %(time)s (%(duration)s)") % {"time": strformat.strtime(self.stoptime), "duration": strformat.strduration_long(duration)})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_modified(self, modified, sep=" "): """Format modification date in UTC if it's not None. @param modified: modification date in UTC @ptype modified: datetime or None @return: formatted date or empty string @rtype: unicode """
if modified is not None: return modified.strftime("%Y-%m-%d{0}%H:%M:%S.%fZ".format(sep)) return u""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formvalue (form, key): """Get value with given key from WSGI form."""
field = form.get(key) if isinstance(field, list): field = field[0] return field
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checklink (form=None, env=os.environ): """Validates the CGI form and checks the given links."""
if form is None: form = {} try: checkform(form, env) except LCFormError as errmsg: log(env, errmsg) yield encode(format_error(errmsg)) return out = ThreadsafeIO() config = get_configuration(form, out) url = strformat.stripurl(formvalue(form, "url")) aggregate = director.get_aggregate(config) url_data = checker.get_url_from(url, 0, aggregate, extern=(0, 0)) aggregate.urlqueue.put(url_data) for html_str in start_check(aggregate, out): yield encode(html_str) out.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_check (aggregate, out): """Start checking in background and write encoded output to out."""
# check in background t = threading.Thread(target=director.check_urls, args=(aggregate,)) t.start() # time to wait for new data sleep_seconds = 2 # current running time run_seconds = 0 while not aggregate.is_finished(): yield out.get_data() time.sleep(sleep_seconds) run_seconds += sleep_seconds if run_seconds > MAX_REQUEST_SECONDS: director.abort(aggregate) break yield out.get_data()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_configuration(form, out): """Initialize a CGI configuration."""
config = configuration.Configuration() config["recursionlevel"] = int(formvalue(form, "level")) config["logger"] = config.logger_new('html', fd=out, encoding=HTML_ENCODING) config["threads"] = 2 if "anchors" in form: config["enabledplugins"].append("AnchorCheck") if "errors" not in form: config["verbose"] = True # avoid checking of local files or other nasty stuff pat = "!^%s$" % urlutil.safe_url_pattern config["externlinks"].append(get_link_pat(pat, strict=True)) config.sanitize() return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkform (form, env): """Check form data. throw exception on error Be sure to NOT print out any user-given data as HTML code, so use only plain strings as exception text."""
# check lang support if "language" in form: lang = formvalue(form, 'language') if lang in _supported_langs: localestr = lang_locale[lang] try: # XXX this is not thread-safe, so think of something else locale.setlocale(locale.LC_ALL, localestr) init_i18n() except locale.Error as errmsg: log(env, "could not set locale %r: %s" % (localestr, errmsg)) else: raise LCFormError(_("unsupported language %r") % lang) # check url syntax if "url" in form: url = formvalue(form, "url") if not url or url == "http://": raise LCFormError(_("empty url was given")) if not urlutil.is_safe_url(url): raise LCFormError(_("disallowed url %r was given") % url) else: raise LCFormError(_("no url was given")) # check recursion level if "level" in form: level = formvalue(form, "level") if not _is_level(level): raise LCFormError(_("invalid recursion level %r") % level) # check options for option in ("anchors", "errors", "intern"): if option in form: value = formvalue(form, option) if value != "on": raise LCFormError(_("invalid %s option %r") % (option, value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump (env, form): """Log environment and form."""
for var, value in env.items(): log(env, var+"="+value) for key in form: log(env, str(formvalue(form, key)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write (self, data): """Write given unicode data to buffer."""
assert isinstance(data, unicode) if self.closed: raise IOError("Write on closed I/O object") if data: self.buf.append(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_data (self): """Get bufferd unicode data."""
data = u"".join(self.buf) self.buf = [] return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_opera (url_data): """Parse an opera bookmark file."""
from ..bookmarks.opera import parse_bookmark_data for url, name, lineno in parse_bookmark_data(url_data.get_content()): url_data.add_url(url, line=lineno, name=name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_chromium (url_data): """Parse a Chromium or Google Chrome bookmark file."""
from ..bookmarks.chromium import parse_bookmark_data for url, name in parse_bookmark_data(url_data.get_content()): url_data.add_url(url, name=name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_safari (url_data): """Parse a Safari bookmark file."""
from ..bookmarks.safari import parse_bookmark_data for url, name in parse_bookmark_data(url_data.get_content()): url_data.add_url(url, name=name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_text (url_data): """Parse a text file with one url per line; comment and blank lines are ignored."""
lineno = 0 for line in url_data.get_content().splitlines(): lineno += 1 line = line.strip() if not line or line.startswith('#'): continue url_data.add_url(line, line=lineno)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_swf (url_data): """Parse a SWF file for URLs."""
linkfinder = linkparse.swf_url_re.finditer for mo in linkfinder(url_data.get_content()): url = mo.group() url_data.add_url(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_links (url_data, callback, tags): """Parse into content and search for URLs to check. Found URLs are added to the URL queue. """
# construct parser object handler = linkparse.LinkFinder(callback, tags) parser = htmlsax.parser(handler) if url_data.charset: parser.encoding = url_data.charset handler.parser = parser # parse try: parser.feed(url_data.get_content()) parser.flush() except linkparse.StopParse as msg: log.debug(LOG_CHECK, "Stopped parsing: %s", msg) pass # break cyclic dependencies handler.parser = None parser.handler = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_firefox (url_data): """Parse a Firefox3 bookmark file."""
filename = url_data.get_os_filename() for url, name in firefox.parse_bookmark_file(filename): url_data.add_url(url, name=name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_itms_services(url_data): """Get "url" CGI parameter value as child URL."""
query = url_data.urlparts[3] for k, v, sep in urlutil.parse_qsl(query, keep_blank_values=True): if k == "url": url_data.add_url(v) break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_package_modules(packagename): """Find all valid modules in the given package which must be a folder in the same directory as this loader.py module. A valid module has a .py extension, and is importable. @return: all loaded valid modules @rtype: iterator of module """
if is_frozen(): # find modules in library.zip filename zipname = os.path.dirname(os.path.dirname(__file__)) parentmodule = os.path.basename(os.path.dirname(__file__)) with zipfile.ZipFile(zipname, 'r') as f: prefix = "%s/%s/" % (parentmodule, packagename) modnames = [os.path.splitext(n[len(prefix):])[0] for n in f.namelist() if n.startswith(prefix) and "__init__" not in n] else: dirname = os.path.join(os.path.dirname(__file__), packagename) modnames = [x[:-3] for x in get_importable_files(dirname)] for modname in modnames: try: name ="..%s.%s" % (packagename, modname) yield importlib.import_module(name, __name__) except ImportError as msg: print("WARN: could not load module %s: %s" % (modname, msg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_lock (name, debug=False): """Get a new lock. @param debug: if True, acquire() and release() will have debug messages @ptype debug: boolean, default is False @return: a lock object @rtype: threading.Lock or DebugLock """
lock = threading.Lock() # for thread debugging, use the DebugLock wrapper if debug: lock = DebugLock(lock, name) return lock
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_semaphore(name, value=None, debug=False): """Get a new semaphore. @param value: if not None, a BoundedSemaphore will be used @ptype debug: int or None @param debug: if True, acquire() and release() will have debug messages @ptype debug: boolean, default is False @return: a semaphore object @rtype: threading.Semaphore or threading.BoundedSemaphore or DebugLock """
if value is None: lock = threading.Semaphore() else: lock = threading.BoundedSemaphore(value) if debug: lock = DebugLock(lock, name) return lock
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acquire (self, blocking=1): """Acquire lock."""
threadname = threading.currentThread().getName() log.debug(LOG_THREAD, "Acquire %s for %s", self.name, threadname) self.lock.acquire(blocking) log.debug(LOG_THREAD, "...acquired %s for %s", self.name, threadname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_multiline (value): """Helper function reading multiline values."""
for line in value.splitlines(): line = line.strip() if not line or line.startswith('#'): continue yield line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_string_option (self, section, option, allowempty=False): """Read a string option."""
if self.has_option(section, option): value = self.get(section, option) if not allowempty and not value: raise LinkCheckerError(_("invalid empty value for %s: %s\n") % (option, value)) self.config[option] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_boolean_option(self, section, option): """Read a boolean option."""
if self.has_option(section, option): self.config[option] = self.getboolean(section, option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_int_option (self, section, option, key=None, min=None, max=None): """Read an integer option."""
if self.has_option(section, option): num = self.getint(section, option) if min is not None and num < min: raise LinkCheckerError( _("invalid value for %s: %d must not be less than %d") % (option, num, min)) if max is not None and num < max: raise LinkCheckerError( _("invalid value for %s: %d must not be greater than %d") % (option, num, max)) if key is None: key = option self.config[key] = num
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_output_config (self): """Read configuration options in section "output"."""
section = "output" from ..logger import LoggerClasses for c in LoggerClasses: key = c.LoggerName if self.has_section(key): for opt in self.options(key): self.config[key][opt] = self.get(key, opt) if self.has_option(key, 'parts'): val = self.get(key, 'parts') parts = [f.strip().lower() for f in val.split(',')] self.config[key]['parts'] = parts self.read_boolean_option(section, "warnings") if self.has_option(section, "verbose"): if self.getboolean(section, "verbose"): self.config["verbose"] = True self.config["warnings"] = True if self.has_option(section, "quiet"): if self.getboolean(section, "quiet"): self.config['output'] = 'none' self.config['quiet'] = True if self.has_option(section, "debug"): val = self.get(section, "debug") parts = [f.strip().lower() for f in val.split(',')] logconf.set_debug(parts) self.read_boolean_option(section, "status") if self.has_option(section, "log"): val = self.get(section, "log").strip().lower() self.config['output'] = val if self.has_option(section, "fileoutput"): loggers = self.get(section, "fileoutput").split(",") # strip names from whitespace loggers = (x.strip().lower() for x in loggers) # no file output for the blacklist and none Logger from ..logger import LoggerNames loggers = (x for x in loggers if x in LoggerNames and x not in ("blacklist", "none")) for val in loggers: output = self.config.logger_new(val, fileoutput=1) self.config['fileoutput'].append(output)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_checking_config (self): """Read configuration options in section "checking"."""
section = "checking" self.read_int_option(section, "threads", min=-1) self.config['threads'] = max(0, self.config['threads']) self.read_int_option(section, "timeout", min=1) self.read_int_option(section, "aborttimeout", min=1) self.read_int_option(section, "recursionlevel", min=-1) self.read_string_option(section, "nntpserver") self.read_string_option(section, "useragent") self.read_int_option(section, "maxrequestspersecond", min=1) self.read_int_option(section, "maxnumurls", min=0) self.read_int_option(section, "maxfilesizeparse", min=1) self.read_int_option(section, "maxfilesizedownload", min=1) if self.has_option(section, "allowedschemes"): self.config['allowedschemes'] = [x.strip().lower() for x in \ self.get(section, 'allowedschemes').split(',')] self.read_boolean_option(section, "debugmemory") self.read_string_option(section, "cookiefile") self.read_string_option(section, "localwebroot") try: self.read_boolean_option(section, "sslverify") except ValueError: self.read_string_option(section, "sslverify") self.read_int_option(section, "maxrunseconds", min=0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_authentication_config (self): """Read configuration options in section "authentication"."""
section = "authentication" password_fields = [] if self.has_option(section, "entry"): for val in read_multiline(self.get(section, "entry")): auth = val.split() if len(auth) == 3: self.config.add_auth(pattern=auth[0], user=auth[1], password=auth[2]) password_fields.append("entry/%s/%s" % (auth[0], auth[1])) elif len(auth) == 2: self.config.add_auth(pattern=auth[0], user=auth[1]) else: raise LinkCheckerError( _("missing auth part in entry %(val)r") % {"val": val}) # read login URL and field names if self.has_option(section, "loginurl"): val = self.get(section, "loginurl").strip() if not (val.lower().startswith("http:") or val.lower().startswith("https:")): raise LinkCheckerError(_("invalid login URL `%s'. Only " \ "HTTP and HTTPS URLs are supported.") % val) self.config["loginurl"] = val self.read_string_option(section, "loginuserfield") self.read_string_option(section, "loginpasswordfield") # read login extra fields if self.has_option(section, "loginextrafields"): for val in read_multiline(self.get(section, "loginextrafields")): name, value = val.split(":", 1) self.config["loginextrafields"][name] = value self.check_password_readable(section, password_fields)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_password_readable(self, section, fields): """Check if there is a readable configuration file and print a warning."""
if not fields: return # The information which of the configuration files # included which option is not available. To avoid false positives, # a warning is only printed if exactly one file has been read. if len(self.read_ok) != 1: return fn = self.read_ok[0] if fileutil.is_accessable_by_others(fn): log.warn(LOG_CHECK, "The configuration file %s contains password information (in section [%s] and options %s) and the file is readable by others. Please make the file only readable by you.", fn, section, fields) if os.name == 'posix': log.warn(LOG_CHECK, _("For example execute 'chmod go-rw %s'.") % fn) elif os.name == 'nt': log.warn(LOG_CHECK, _("See http://support.microsoft.com/kb/308419 for more info on setting file permissions."))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_filtering_config (self): """ Read configuration options in section "filtering". """
section = "filtering" if self.has_option(section, "ignorewarnings"): self.config['ignorewarnings'] = [f.strip().lower() for f in \ self.get(section, 'ignorewarnings').split(',')] if self.has_option(section, "ignore"): for line in read_multiline(self.get(section, "ignore")): pat = get_link_pat(line, strict=1) self.config["externlinks"].append(pat) if self.has_option(section, "nofollow"): for line in read_multiline(self.get(section, "nofollow")): pat = get_link_pat(line, strict=0) self.config["externlinks"].append(pat) if self.has_option(section, "internlinks"): pat = get_link_pat(self.get(section, "internlinks")) self.config["internlinks"].append(pat) self.read_boolean_option(section, "checkextern")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_plugin_config(self): """Read plugin-specific configuration values."""
folders = self.config["pluginfolders"] modules = plugins.get_plugin_modules(folders) for pluginclass in plugins.get_plugin_classes(modules): section = pluginclass.__name__ if self.has_section(section): self.config["enabledplugins"].append(section) self.config[section] = pluginclass.read_config(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self, url_data): """Check content."""
log.debug(LOG_PLUGIN, "checking content for warning regex") content = url_data.get_content() # add warnings for found matches, up to the maximum allowed number match = self.warningregex.search(content) if match: # calculate line number for match line = content.count('\n', 0, match.start()) # add a warning message msg = _("Found %(match)r at line %(line)d in link contents.") url_data.add_warning(msg % {"match": match.group(), "line": line})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_section(self, section): """Set the renderer's current section. Sections must be rendered order: QUESTION, ANSWER, AUTHORITY, ADDITIONAL. Sections may be empty. @param section: the section @type section: int @raises dns.exception.FormError: an attempt was made to set a section value less than the current section. """
if self.section != section: if self.section > section: raise dns.exception.FormError self.section = section
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN): """Add a question to the message. @param qname: the question name @type qname: dns.name.Name @param rdtype: the question rdata type @type rdtype: int @param rdclass: the question rdata class @type rdclass: int """
self._set_section(QUESTION) before = self.output.tell() qname.to_wire(self.output, self.compress, self.origin) self.output.write(struct.pack("!HH", rdtype, rdclass)) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.counts[QUESTION] += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_rrset(self, section, rrset, **kw): """Add the rrset to the specified section. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param rrset: the rrset @type rrset: dns.rrset.RRset object """
self._set_section(section) before = self.output.tell() n = rrset.to_wire(self.output, self.compress, self.origin, **kw) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.counts[section] += n
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_rdataset(self, section, name, rdataset, **kw): """Add the rdataset to the specified section, using the specified name as the owner name. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param name: the owner name @type name: dns.name.Name object @param rdataset: the rdataset @type rdataset: dns.rdataset.Rdataset object """
self._set_section(section) before = self.output.tell() n = rdataset.to_wire(name, self.output, self.compress, self.origin, **kw) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.counts[section] += n
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_edns(self, edns, ednsflags, payload, options=None): """Add an EDNS OPT record to the message. @param edns: The EDNS level to use. @type edns: int @param ednsflags: EDNS flag values. @type ednsflags: int @param payload: The EDNS sender's payload field, which is the maximum size of UDP datagram the sender can handle. @type payload: int @param options: The EDNS options list @type options: list of dns.edns.Option instances @see: RFC 2671 """
# make sure the EDNS version in ednsflags agrees with edns ednsflags &= 0xFF00FFFFL ednsflags |= (edns << 16) self._set_section(ADDITIONAL) before = self.output.tell() self.output.write(struct.pack('!BHHIH', 0, dns.rdatatype.OPT, payload, ednsflags, 0)) if not options is None: lstart = self.output.tell() for opt in options: stuff = struct.pack("!HH", opt.otype, 0) self.output.write(stuff) start = self.output.tell() opt.to_wire(self.output) end = self.output.tell() assert end - start < 65536 self.output.seek(start - 2) stuff = struct.pack("!H", end - start) self.output.write(stuff) self.output.seek(0, 2) lend = self.output.tell() assert lend - lstart < 65536 self.output.seek(lstart - 2) stuff = struct.pack("!H", lend - lstart) self.output.write(stuff) self.output.seek(0, 2) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.counts[ADDITIONAL] += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_tsig(self, keyname, secret, fudge, id, tsig_error, other_data, request_mac, algorithm=dns.tsig.default_algorithm): """Add a TSIG signature to the message. @param keyname: the TSIG key name @type keyname: dns.name.Name object @param secret: the secret to use @type secret: string @param fudge: TSIG time fudge @type fudge: int @param id: the message id to encode in the tsig signature @type id: int @param tsig_error: TSIG error code; default is 0. @type tsig_error: int @param other_data: TSIG other data. @type other_data: string @param request_mac: This message is a response to the request which had the specified MAC. @type request_mac: string @param algorithm: the TSIG algorithm to use @type algorithm: dns.name.Name object """
self._set_section(ADDITIONAL) before = self.output.tell() s = self.output.getvalue() (tsig_rdata, self.mac, ctx) = dns.tsig.sign(s, keyname, secret, int(time.time()), fudge, id, tsig_error, other_data, request_mac, algorithm=algorithm) keyname.to_wire(self.output, self.compress, self.origin) self.output.write(struct.pack('!HHIH', dns.rdatatype.TSIG, dns.rdataclass.ANY, 0, 0)) rdata_start = self.output.tell() self.output.write(tsig_rdata) after = self.output.tell() assert after - rdata_start < 65536 if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.output.seek(rdata_start - 2) self.output.write(struct.pack('!H', after - rdata_start)) self.counts[ADDITIONAL] += 1 self.output.seek(10) self.output.write(struct.pack('!H', self.counts[ADDITIONAL])) self.output.seek(0, 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_header(self): """Write the DNS message header. Writing the DNS message header is done asfter all sections have been rendered, but before the optional TSIG signature is added. """
self.output.seek(0) self.output.write(struct.pack('!HHHHHH', self.id, self.flags, self.counts[0], self.counts[1], self.counts[2], self.counts[3])) self.output.seek(0, 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def option_from_wire(otype, wire, current, olen): """Build an EDNS option object from wire format @param otype: The option type @type otype: int @param wire: The wire-format message @type wire: string @param current: The offet in wire of the beginning of the rdata. @type current: int @param olen: The length of the wire-format option data @type olen: int @rtype: dns.ends.Option instance"""
cls = get_option_class(otype) return cls.from_wire(otype, wire, current, olen)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comment (self, s, **args): """Write CSV comment."""
self.writeln(s=u"# %s" % s, **args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_output (self): """Write checking start info as csv comment."""
super(CSVLogger, self).start_output() row = [] if self.has_part("intro"): self.write_intro() self.flush() else: # write empty string to initialize file output self.write(u"") self.queue = StringIO() self.writer = csv.writer(self.queue, dialect=self.dialect, delimiter=self.separator, lineterminator=self.linesep, quotechar=self.quotechar) for s in Columns: if self.has_part(s): row.append(s) if row: self.writerow(row)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_url (self, url_data): """Write csv formatted url check info."""
row = [] if self.has_part("urlname"): row.append(url_data.base_url) if self.has_part("parentname"): row.append(url_data.parent_url) if self.has_part("baseref"): row.append(url_data.base_ref) if self.has_part("result"): row.append(url_data.result) if self.has_part("warningstring"): row.append(self.linesep.join(x[1] for x in url_data.warnings)) if self.has_part("infostring"): row.append(self.linesep.join(url_data.info)) if self.has_part("valid"): row.append(url_data.valid) if self.has_part("url"): row.append(url_data.url) if self.has_part("line"): row.append(url_data.line) if self.has_part("column"): row.append(url_data.column) if self.has_part("name"): row.append(url_data.name) if self.has_part("dltime"): row.append(url_data.dltime) if self.has_part("dlsize"): row.append(url_data.size) if self.has_part("checktime"): row.append(url_data.checktime) if self.has_part("cached"): row.append(0) if self.has_part("level"): row.append(url_data.level) if self.has_part("modified"): row.append(self.format_modified(url_data.modified)) self.writerow(map(strformat.unicode_safe, row)) self.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_urls (urlqueue, logger): """Check URLs without threading."""
while not urlqueue.empty(): url_data = urlqueue.get() try: check_url(url_data, logger) finally: urlqueue.task_done(url_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_url(url_data, logger): """Check a single URL with logging."""
if url_data.has_result: logger.log_url(url_data.to_wire()) else: cache = url_data.aggregate.result_cache key = url_data.cache_url result = cache.get_result(key) if result is None: # check check_start = time.time() try: url_data.check() do_parse = url_data.check_content() url_data.checktime = time.time() - check_start # Add result to cache result = url_data.to_wire() cache.add_result(key, result) for alias in url_data.aliases: # redirect aliases cache.add_result(alias, result) # parse content recursively # XXX this could add new warnings which should be cached. if do_parse: parser.parse_url(url_data) finally: # close/release possible open connection url_data.close_connection() else: # copy data from cache and adjust it result = copy.copy(result) result.parent_url = url_data.parent_url result.base_ref = url_data.base_ref or u"" result.base_url = url_data.base_url or u"" result.line = url_data.line result.column = url_data.column result.level = url_data.recursion_level result.name = url_data.name logger.log_url(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_url (self): """Try to get URL data from queue and check it."""
try: url_data = self.urlqueue.get(timeout=QUEUE_POLL_INTERVALL_SECS) if url_data is not None: try: self.check_url_data(url_data) finally: self.urlqueue.task_done(url_data) self.setName(self.origname) except urlqueue.Empty: pass except Exception: self.internal_error()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_url_data (self, url_data): """Check one URL data instance."""
if url_data.url is None: url = "" else: url = url_data.url.encode("ascii", "replace") self.setName("CheckThread-%s" % url) check_url(url_data, self.logger)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def udp(q, where, timeout=None, port=53, af=None, source=None, source_port=0, ignore_unexpected=False, one_rr_per_rrset=False): """Return the response obtained after sending a query via UDP. @param q: the query @type q: dns.message.Message @param where: where to send the message @type where: string containing an IPv4 or IPv6 address @param timeout: The number of seconds to wait before the query times out. If None, the default, wait forever. @type timeout: float @param port: The port to which to send the message. The default is 53. @type port: int @param af: the address family to use. The default is None, which causes the address family to use to be inferred from the form of of where. If the inference attempt fails, AF_INET is used. @type af: int @rtype: dns.message.Message object @param source: source address. The default is the IPv4 wildcard address. @type source: string @param source_port: The port from which to send the message. The default is 0. @type source_port: int @param ignore_unexpected: If True, ignore responses from unexpected sources. The default is False. @type ignore_unexpected: bool @param one_rr_per_rrset: Put each RR into its own RRset @type one_rr_per_rrset: bool """
wire = q.to_wire() if af is None: try: af = dns.inet.af_for_address(where) except Exception: af = dns.inet.AF_INET if af == dns.inet.AF_INET: destination = (where, port) if source is not None: source = (source, source_port) elif af == dns.inet.AF_INET6: destination = (where, port, 0, 0) if source is not None: source = (source, source_port, 0, 0) s = socket.socket(af, socket.SOCK_DGRAM, 0) try: expiration = _compute_expiration(timeout) s.setblocking(0) if source is not None: s.bind(source) _wait_for_writable(s, expiration) s.sendto(wire, destination) while 1: _wait_for_readable(s, expiration) (wire, from_address) = s.recvfrom(65535) if _addresses_equal(af, from_address, destination) or \ (dns.inet.is_multicast(where) and \ from_address[1:] == destination[1:]): break if not ignore_unexpected: raise UnexpectedSource('got a response from ' '%s instead of %s' % (from_address, destination)) finally: s.close() r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac, one_rr_per_rrset=one_rr_per_rrset) if not q.is_response(r): raise BadResponse return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _net_read(sock, count, expiration): """Read the specified number of bytes from sock. Keep trying until we either get the desired amount, or we hit EOF. A Timeout exception will be raised if the operation is not completed by the expiration time. """
s = '' while count > 0: _wait_for_readable(sock, expiration) n = sock.recv(count) if n == '': raise EOFError count = count - len(n) s = s + n return s