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 add_watcher(self, fd, callback): """Starts watching a non-blocking fd for data."""
if not isinstance(fd, int): fd = fd.fileno() self.callbacks[fd] = callback self.epoll.register(fd, EPOLLIN)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_watcher(self, fd): """Stops watching a fd."""
if not isinstance(fd, int): fd = fd.fileno() if fd not in self.callbacks: return self.callbacks.pop(fd, None) self.epoll.unregister(fd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fire_event(self, event, *args, **kwargs): """Fires a event."""
self.event_queue.append((event, args)) self.process_events()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_events(self): """Processes any events in the queue."""
for event, args in iter_except(self.event_queue.popleft, IndexError): for callback in self.event_callbacks[event]: callback(*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 run(self): """Starts the loop."""
self.running = True while self.running: for fd, event in self.epoll.poll(self.epoll_timeout): callback = self.callbacks.get(fd) if callback: callback()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stops the loop."""
self.running = False self.callbacks = {} self.epoll = epoll() self.event_queue = deque() self.event_callbacks = defaultdict(set)
<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_future_devices(self, context): """Return a generator yielding new devices."""
monitor = Monitor.from_netlink(context) monitor.filter_by("hidraw") monitor.start() self._scanning_log_message() for device in iter(monitor.poll, None): if device.action == "add": # Sometimes udev rules has not been applied at this point, # causing permission denied error if we are running in user # mode. With this sleep this will hopefully not happen. sleep(1) yield device self._scanning_log_message()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rumble(self, small=0, big=0): """Sets the intensity of the rumble motors. Valid range is 0-255."""
self._control(small_rumble=small, big_rumble=big)
<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_led(self, red=0, green=0, blue=0): """Sets the LED color. Values are RGB between 0-255."""
self._led = (red, green, blue) self._control()
<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_led_flash(self, on, off): """Starts flashing the LED."""
if not self._led_flashing: self._led_flash = (on, off) self._led_flashing = True self._control()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_led_flash(self): """Stops flashing the LED."""
if self._led_flashing: self._led_flash = (0, 0) self._led_flashing = False # Call twice, once to stop flashing... self._control() # ...and once more to make sure the LED is on. self._control()
<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_report(self, buf): """Parse a buffer containing a HID report."""
dpad = buf[5] % 16 return DS4Report( # Left analog stick buf[1], buf[2], # Right analog stick buf[3], buf[4], # L2 and R2 analog buf[8], buf[9], # DPad up, down, left, right (dpad in (0, 1, 7)), (dpad in (3, 4, 5)), (dpad in (5, 6, 7)), (dpad in (1, 2, 3)), # Buttons cross, circle, square, triangle (buf[5] & 32) != 0, (buf[5] & 64) != 0, (buf[5] & 16) != 0, (buf[5] & 128) != 0, # L1, L2 and L3 buttons (buf[6] & 1) != 0, (buf[6] & 4) != 0, (buf[6] & 64) != 0, # R1, R2,and R3 buttons (buf[6] & 2) != 0, (buf[6] & 8) != 0, (buf[6] & 128) != 0, # Share and option buttons (buf[6] & 16) != 0, (buf[6] & 32) != 0, # Trackpad and PS buttons (buf[7] & 2) != 0, (buf[7] & 1) != 0, # Acceleration S16LE.unpack_from(buf, 13)[0], S16LE.unpack_from(buf, 15)[0], S16LE.unpack_from(buf, 17)[0], # Orientation -(S16LE.unpack_from(buf, 19)[0]), S16LE.unpack_from(buf, 21)[0], S16LE.unpack_from(buf, 23)[0], # Trackpad touch 1: id, active, x, y buf[35] & 0x7f, (buf[35] >> 7) == 0, ((buf[37] & 0x0f) << 8) | buf[36], buf[38] << 4 | ((buf[37] & 0xf0) >> 4), # Trackpad touch 2: id, active, x, y buf[39] & 0x7f, (buf[39] >> 7) == 0, ((buf[41] & 0x0f) << 8) | buf[40], buf[42] << 4 | ((buf[41] & 0xf0) >> 4), # Timestamp and battery buf[7] >> 2, buf[30] % 16, # External inputs (usb, audio, mic) (buf[30] & 16) != 0, (buf[30] & 32) != 0, (buf[30] & 64) != 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 exec_(controller, cmd, *args): """Executes a subprocess in the foreground, blocking until returned."""
controller.logger.info("Executing: {0} {1}", cmd, " ".join(args)) try: subprocess.check_call([cmd] + list(args)) except (OSError, subprocess.CalledProcessError) as err: controller.logger.error("Failed to execute process: {0}", err)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exec_background(controller, cmd, *args): """Executes a subprocess in the background."""
controller.logger.info("Executing in the background: {0} {1}", cmd, " ".join(args)) try: subprocess.Popen([cmd] + list(args), stdout=open(os.devnull, "wb"), stderr=open(os.devnull, "wb")) except OSError as err: controller.logger.error("Failed to execute process: {0}", err)
<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_uinput_device(mapping): """Creates a uinput device."""
if mapping not in _mappings: raise DeviceError("Unknown device mapping: {0}".format(mapping)) try: mapping = _mappings[mapping] device = UInputDevice(mapping) except UInputError as err: raise DeviceError(err) return device
<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_uinput_mapping(name, mapping): """Parses a dict of mapping options."""
axes, buttons, mouse, mouse_options = {}, {}, {}, {} description = "ds4drv custom mapping ({0})".format(name) for key, attr in mapping.items(): key = key.upper() if key.startswith("BTN_") or key.startswith("KEY_"): buttons[key] = attr elif key.startswith("ABS_"): axes[key] = attr elif key.startswith("REL_"): mouse[key] = attr elif key.startswith("MOUSE_"): mouse_options[key] = attr create_mapping(name, description, axes=axes, buttons=buttons, mouse=mouse, mouse_options=mouse_options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_joystick_device(): """Finds the next available js device name."""
for i in range(100): dev = "/dev/input/js{0}".format(i) if not os.path.exists(dev): return dev
<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_device(self, layout): """Creates a uinput device using the specified layout."""
events = {ecodes.EV_ABS: [], ecodes.EV_KEY: [], ecodes.EV_REL: []} # Joystick device if layout.axes or layout.buttons or layout.hats: self.joystick_dev = next_joystick_device() for name in layout.axes: params = layout.axes_options.get(name, DEFAULT_AXIS_OPTIONS) if not absInfoUsesValue: params = params[1:] events[ecodes.EV_ABS].append((name, params)) for name in layout.hats: params = (0, -1, 1, 0, 0) if not absInfoUsesValue: params = params[1:] events[ecodes.EV_ABS].append((name, params)) for name in layout.buttons: events[ecodes.EV_KEY].append(name) if layout.mouse: self.mouse_pos = {} self.mouse_rel = {} self.mouse_analog_sensitivity = float( layout.mouse_options.get("MOUSE_SENSITIVITY", DEFAULT_MOUSE_SENSITIVTY) ) self.mouse_analog_deadzone = int( layout.mouse_options.get("MOUSE_DEADZONE", DEFAULT_MOUSE_DEADZONE) ) self.scroll_repeat_delay = float( layout.mouse_options.get("MOUSE_SCROLL_REPEAT_DELAY", DEFAULT_SCROLL_REPEAT_DELAY) ) self.scroll_delay = float( layout.mouse_options.get("MOUSE_SCROLL_DELAY", DEFAULT_SCROLL_DELAY) ) for name in layout.mouse: if name in (ecodes.REL_WHEELUP, ecodes.REL_WHEELDOWN): if ecodes.REL_WHEEL not in events[ecodes.EV_REL]: # This ensures that scroll wheel events can work events[ecodes.EV_REL].append(ecodes.REL_WHEEL) else: events[ecodes.EV_REL].append(name) self.mouse_rel[name] = 0.0 self.device = UInput(name=layout.name, events=events, bustype=layout.bustype, vendor=layout.vendor, product=layout.product, version=layout.version) self.layout = layout
<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_event(self, etype, code, value): """Writes a event to the device, if it has changed."""
last_value = self._write_cache.get(code) if last_value != value: self.device.write(etype, code, value) self._write_cache[code] = 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 emit(self, report): """Writes axes, buttons and hats with values from the report to the device."""
for name, attr in self.layout.axes.items(): value = getattr(report, attr) self.write_event(ecodes.EV_ABS, name, value) for name, attr in self.layout.buttons.items(): attr, modifier = attr if attr in self.ignored_buttons: value = False else: value = getattr(report, attr) if modifier and "analog" in attr: if modifier == "+": value = value > (128 + DEFAULT_A2D_DEADZONE) elif modifier == "-": value = value < (128 - DEFAULT_A2D_DEADZONE) self.write_event(ecodes.EV_KEY, name, value) for name, attr in self.layout.hats.items(): if getattr(report, attr[0]): value = -1 elif getattr(report, attr[1]): value = 1 else: value = 0 self.write_event(ecodes.EV_ABS, name, value) self.device.syn()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emit_reset(self): """Resets the device to a blank state."""
for name in self.layout.axes: params = self.layout.axes_options.get(name, DEFAULT_AXIS_OPTIONS) self.write_event(ecodes.EV_ABS, name, int(sum(params[1:3]) / 2)) for name in self.layout.buttons: self.write_event(ecodes.EV_KEY, name, False) for name in self.layout.hats: self.write_event(ecodes.EV_ABS, name, 0) self.device.syn()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def emit_mouse(self, report): """Calculates relative mouse values from a report and writes them."""
for name, attr in self.layout.mouse.items(): # If the attr is a tuple like (left_analog_y, "-") # then set the attr to just be the first item attr, modifier = attr if attr.startswith("trackpad_touch"): active_attr = attr[:16] + "active" if not getattr(report, active_attr): self.mouse_pos.pop(name, None) continue pos = getattr(report, attr) if name not in self.mouse_pos: self.mouse_pos[name] = pos sensitivity = 0.5 self.mouse_rel[name] += (pos - self.mouse_pos[name]) * sensitivity self.mouse_pos[name] = pos elif "analog" in attr: pos = getattr(report, attr) if (pos > (128 + self.mouse_analog_deadzone) or pos < (128 - self.mouse_analog_deadzone)): accel = (pos - 128) / 10 else: continue # If a minus modifier has been given then minus the acceleration # to invert the direction. if (modifier and modifier == "-"): accel = -accel sensitivity = self.mouse_analog_sensitivity self.mouse_rel[name] += accel * sensitivity # Emulate mouse wheel (needs special handling) if name in (ecodes.REL_WHEELUP, ecodes.REL_WHEELDOWN): ecode = ecodes.REL_WHEEL # The real event we need to emit write = False if getattr(report, attr): self._scroll_details['direction'] = name now = time.time() last_write = self._scroll_details.get('last_write') if not last_write: # No delay for the first button press for fast feedback write = True self._scroll_details['count'] = 0 if name == ecodes.REL_WHEELUP: value = 1 elif name == ecodes.REL_WHEELDOWN: value = -1 if last_write: # Delay at least one cycle before continual scrolling if self._scroll_details['count'] > 1: if now - last_write > self.scroll_delay: write = True elif now - last_write > self.scroll_repeat_delay: write = True if write: self.device.write(ecodes.EV_REL, ecode, value) self._scroll_details['last_write'] = now self._scroll_details['count'] += 1 continue # No need to proceed further else: # Reset so you can quickly tap the button to scroll if self._scroll_details.get('direction') == name: self._scroll_details['last_write'] = 0 self._scroll_details['count'] = 0 rel = int(self.mouse_rel[name]) self.mouse_rel[name] = self.mouse_rel[name] - rel self.device.write(ecodes.EV_REL, name, rel) self.device.syn()
<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 gml comment."""
super(GMLLogger, self).start_output() if self.has_part("intro"): self.write_intro() self.writeln() self.writeln(u"graph [") self.writeln(u" directed 1") 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 GML comment."""
self.writeln(s=u'comment "%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 getaddresses (addr): """Return list of email addresses from given field value."""
parsed = [mail for name, mail in AddressList(addr).addresslist if mail] if parsed: addresses = parsed elif addr: # we could not parse any mail addresses, so try with the raw string addresses = [addr] else: addresses = [] return addresses
<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_addresses (self): """Parse all mail addresses out of the URL target. Also parses optional CGI headers like "?to=foo@example.org". Stores parsed addresses in the self.addresses set. """
# cut off leading mailto: and unquote url = urllib.unquote(self.base_url[7:]) # search for cc, bcc, to and store in headers mode = 0 # 0=default, 1=quote, 2=esc quote = None i = 0 for i, c in enumerate(url): if mode == 0: if c == '?': break elif c in '<"': quote = c mode = 1 elif c == '\\': mode = 2 elif mode==1: if c == '"' and quote == '"': mode = 0 elif c == '>' and quote == '<': mode = 0 elif mode == 2: mode = 0 if i < (len(url) - 1): self.addresses.update(getaddresses(url[:i])) try: headers = urlparse.parse_qs(url[(i+1):], strict_parsing=True) for key, vals in headers.items(): if key.lower() in EMAIL_CGI_ADDRESS: # Only the first header value is added self.addresses.update(getaddresses(urllib.unquote(vals[0]))) if key.lower() == EMAIL_CGI_SUBJECT: self.subject = vals[0] except ValueError as err: self.add_warning(_("Error parsing CGI values: %s") % str(err)) else: self.addresses.update(getaddresses(url)) log.debug(LOG_CHECK, "addresses: %s", self.addresses)
<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_connection (self): """ Verify a list of email addresses. If one address fails, the whole list will fail. For each mail address the MX DNS records are found. If no MX records are found, print a warning and try to look for A DNS records. If no A records are found either print an error. """
for mail in sorted(self.addresses): self.check_smtp_domain(mail) if not self.valid: 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 check_smtp_domain (self, mail): """ Check a single mail address. """
from dns.exception import DNSException log.debug(LOG_CHECK, "checking mail address %r", mail) mail = strformat.ascii_safe(mail) username, domain = mail.rsplit('@', 1) log.debug(LOG_CHECK, "looking up MX mailhost %r", domain) try: answers = resolver.query(domain, 'MX') except DNSException: answers = [] if len(answers) == 0: self.add_warning(_("No MX mail host for %(domain)s found.") % {'domain': domain}, tag=WARN_MAIL_NO_MX_HOST) try: answers = resolver.query(domain, 'A') except DNSException: answers = [] if len(answers) == 0: self.set_result(_("No host for %(domain)s found.") % {'domain': domain}, valid=False, overwrite=True) return # set preference to zero mxdata = [(0, rdata.to_text(omit_final_dot=True)) for rdata in answers] else: from dns.rdtypes.mxbase import MXBase mxdata = [(rdata.preference, rdata.exchange.to_text(omit_final_dot=True)) for rdata in answers if isinstance(rdata, MXBase)] if not mxdata: self.set_result( _("Got invalid DNS answer %(answer)s for %(domain)s.") % {'answer': answers, 'domain': domain}, valid=False, overwrite=True) return # sort according to preference (lower preference means this # host should be preferred) mxdata.sort() # debug output log.debug(LOG_CHECK, "found %d MX mailhosts:", len(answers)) for preference, host in mxdata: log.debug(LOG_CHECK, "MX host %r, preference %d", host, preference) pass self.set_result(_("Valid mail address syntax"))
<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_cache_url(self): """ The cache url is a comma separated list of emails. """
emails = u",".join(sorted(self.addresses)) self.cache_url = u"%s:%s" % (self.scheme, emails)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normpath (path): """Norm given system path with all available norm or expand functions in os.path."""
expanded = os.path.expanduser(os.path.expandvars(path)) return os.path.normcase(os.path.normpath(expanded))
<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_modules_info(): """Return unicode string with detected module info."""
module_infos = [] for (mod, name, version_attr) in Modules: if not fileutil.has_module(mod): continue if hasattr(mod, version_attr): attr = getattr(mod, version_attr) version = attr() if callable(attr) else attr module_infos.append("%s %s" % (name, version)) else: # ignore attribute errors in case library developers # change the version information attribute module_infos.append(name) return u"Modules: %s" % (u", ".join(module_infos))
<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_share_file (filename, devel_dir=None): """Return a filename in the share directory. @param devel_dir: directory to search when developing @ptype devel_dir: string @param filename: filename to search for @ptype filename: string @return: the found filename or None @rtype: string @raises: ValueError if not found """
paths = [get_share_dir()] if devel_dir is not None: # when developing paths.insert(0, devel_dir) for path in paths: fullpath = os.path.join(path, filename) if os.path.isfile(fullpath): return fullpath # not found msg = "%s not found in %s; check your installation" % (filename, paths) raise ValueError(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_system_cert_file(): """Try to find a system-wide SSL certificate file. @return: the filename to the cert file @raises: ValueError when no system cert file could be found """
if os.name == 'posix': filename = "/etc/ssl/certs/ca-certificates.crt" if os.path.isfile(filename): return filename msg = "no system certificate file found" raise ValueError(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_certifi_file(): """Get the SSL certifications installed by the certifi package. @return: the filename to the cert file @rtype: string @raises: ImportError when certifi is not installed or ValueError when the file is not found """
import certifi filename = certifi.where() if os.path.isfile(filename): return filename msg = "%s not found; check your certifi installation" % filename raise ValueError(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 make_userdir(child): """Create a child directory."""
userdir = os.path.dirname(child) if not os.path.isdir(userdir): if os.name == 'nt': # Windows forbids filenames with leading dot unless # a trailing dot is added. userdir += "." os.mkdir(userdir, 0700)
<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_kde_home_dir (): """Return KDE home directory or None if not found."""
if os.environ.get("KDEHOME"): kde_home = os.path.abspath(os.environ["KDEHOME"]) else: home = os.environ.get("HOME") if not home: # $HOME is not set return kde3_home = os.path.join(home, ".kde") kde4_home = os.path.join(home, ".kde4") if fileutil.find_executable("kde4-config"): # kde4 kde3_file = kde_home_to_config(kde3_home) kde4_file = kde_home_to_config(kde4_home) if os.path.exists(kde4_file) and os.path.exists(kde3_file): if fileutil.get_mtime(kde4_file) >= fileutil.get_mtime(kde3_file): kde_home = kde4_home else: kde_home = kde3_home else: kde_home = kde4_home else: # kde3 kde_home = kde3_home return kde_home if os.path.exists(kde_home) else 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 read_kioslaverc (kde_config_dir): """Read kioslaverc into data dictionary."""
data = {} filename = os.path.join(kde_config_dir, "kioslaverc") with open(filename) as fd: # First read all lines into dictionary since they can occur # in any order. for line in fd: line = line.rstrip() if line.startswith('['): in_proxy_settings = line.startswith("[Proxy Settings]") elif in_proxy_settings: if '=' not in line: continue key, value = line.split('=', 1) key = key.strip() value = value.strip() if not key: continue # trim optional localization key = loc_ro.sub("", key).strip() if not key: continue add_kde_setting(key, value, data) resolve_kde_settings(data) 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 add_kde_setting (key, value, data): """Add a KDE proxy setting value to data dictionary."""
if key == "ProxyType": mode = None int_value = int(value) if int_value == 1: mode = "manual" elif int_value == 2: # PAC URL mode = "pac" elif int_value == 3: # WPAD. mode = "wpad" elif int_value == 4: # Indirect manual via environment variables. mode = "indirect" data["mode"] = mode elif key == "Proxy Config Script": data["autoconfig_url"] = value elif key == "httpProxy": add_kde_proxy("http_proxy", value, data) elif key == "httpsProxy": add_kde_proxy("https_proxy", value, data) elif key == "ftpProxy": add_kde_proxy("ftp_proxy", value, data) elif key == "ReversedException": data["reversed_bypass"] = bool(value == "true" or int(value)) elif key == "NoProxyFor": data["ignore_hosts"] = split_hosts(value) elif key == "AuthMode": mode = int(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 resolve_indirect (data, key, splithosts=False): """Replace name of environment variable with its value."""
value = data[key] env_value = os.environ.get(value) if env_value: if splithosts: data[key] = split_hosts(env_value) else: data[key] = env_value else: del data[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 resolve_kde_settings (data): """Write final proxy configuration values in data dictionary."""
if "mode" not in data: return if data["mode"] == "indirect": for key in ("http_proxy", "https_proxy", "ftp_proxy"): if key in data: resolve_indirect(data, key) if "ignore_hosts" in data: resolve_indirect(data, "ignore_hosts", splithosts=True) elif data["mode"] != "manual": # unsupported config for key in ("http_proxy", "https_proxy", "ftp_proxy"): if key in data: del data[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 logger_new (self, loggername, **kwargs): """Instantiate new logger and return it."""
args = self[loggername] args.update(kwargs) return self.loggers[loggername](**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 logger_add (self, loggerclass): """Add a new logger type to the known loggers."""
self.loggers[loggerclass.LoggerName] = loggerclass self[loggerclass.LoggerName] = {}
<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_auth (self, user=None, password=None, pattern=None): """Add given authentication data."""
if not user or not pattern: log.warn(LOG_CHECK, _("missing user or URL pattern in authentication data.")) return entry = dict( user=user, password=password, pattern=re.compile(pattern), ) self["authentication"].append(entry)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sanitize (self): "Make sure the configuration is consistent." if self['logger'] is None: self.sanitize_logger() if self['loginurl']: self.sanitize_loginurl() self.sanitize_proxies() self.sanitize_plugins() self.sanitize_ssl() # set default socket timeout socket.setdefaulttimeout(self['timeout'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanitize_logger (self): """Make logger configuration consistent."""
if not self['output']: log.warn(LOG_CHECK, _("activating text logger output.")) self['output'] = 'text' self['logger'] = self.logger_new(self['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 sanitize_loginurl (self): """Make login configuration consistent."""
url = self["loginurl"] disable = False if not self["loginpasswordfield"]: log.warn(LOG_CHECK, _("no CGI password fieldname given for login URL.")) disable = True if not self["loginuserfield"]: log.warn(LOG_CHECK, _("no CGI user fieldname given for login URL.")) disable = True if self.get_user_password(url) == (None, None): log.warn(LOG_CHECK, _("no user/password authentication data found for login URL.")) disable = True if not url.lower().startswith(("http:", "https:")): log.warn(LOG_CHECK, _("login URL is not a HTTP URL.")) disable = True urlparts = urlparse.urlsplit(url) if not urlparts[0] or not urlparts[1] or not urlparts[2]: log.warn(LOG_CHECK, _("login URL is incomplete.")) disable = True if disable: log.warn(LOG_CHECK, _("disabling login URL %(url)s.") % {"url": url}) self["loginurl"] = 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 sanitize_proxies (self): """Try to read additional proxy settings which urllib does not support."""
if os.name != 'posix': return if "http" not in self["proxy"]: http_proxy = get_gconf_http_proxy() or get_kde_http_proxy() if http_proxy: self["proxy"]["http"] = http_proxy if "ftp" not in self["proxy"]: ftp_proxy = get_gconf_ftp_proxy() or get_kde_ftp_proxy() if ftp_proxy: self["proxy"]["ftp"] = ftp_proxy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sanitize_ssl(self): """Use local installed certificate file if available. Tries to get system, then certifi, then the own installed certificate file."""
if self["sslverify"] is True: try: self["sslverify"] = get_system_cert_file() except ValueError: try: self["sslverify"] = get_certifi_file() except (ValueError, ImportError): try: self["sslverify"] = get_share_file('cacert.pem') except ValueError: pass
<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_command(self): """ Get a line of text that was received from the DE. The class's cmd_ready attribute will be true if lines are available. """
cmd = None count = len(self.command_list) if count > 0: cmd = self.command_list.pop(0) ## If that was the last line, turn off lines_pending if count == 1: self.cmd_ready = False return cmd
<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(self, text): """ Send raw text to the distant end. """
if text: self.send_buffer += text.replace('\n', '\r\n') self.send_pending = True
<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_wrapped(self, text): """ Send text padded and wrapped to the user's screen width. """
lines = word_wrap(text, self.columns) for line in lines: self.send_cc(line + '\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 request_will_echo(self): """ Tell the DE that we would like to echo their text. See RFC 857. """
self._iac_will(ECHO) self._note_reply_pending(ECHO, True) self.telnet_echo = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request_wont_echo(self): """ Tell the DE that we would like to stop echoing their text. See RFC 857. """
self._iac_wont(ECHO) self._note_reply_pending(ECHO, True) self.telnet_echo = 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 socket_send(self): """ Called by TelnetServer when send data is ready. """
if len(self.send_buffer): try: sent = self.sock.send(self.send_buffer) except socket.error, err: print("!! SEND error '%d:%s' from %s" % (err[0], err[1], self.addrport())) self.active = False return self.bytes_sent += sent self.send_buffer = self.send_buffer[sent:] else: self.send_pending = 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 socket_recv(self): """ Called by TelnetServer when recv data is ready. """
try: data = self.sock.recv(2048) except socket.error, ex: print ("?? socket.recv() error '%d:%s' from %s" % (ex[0], ex[1], self.addrport())) raise BogConnectionLost() ## Did they close the connection? size = len(data) if size == 0: raise BogConnectionLost() ## Update some trackers self.last_input_time = time.time() self.bytes_received += size ## Test for telnet commands for byte in data: self._iac_sniffer(byte) ## Look for newline characters to get whole lines from the buffer while True: mark = self.recv_buffer.find('\n') if mark == -1: break cmd = self.recv_buffer[:mark].strip() self.command_list.append(cmd) self.cmd_ready = True self.recv_buffer = self.recv_buffer[mark+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 _recv_byte(self, byte): """ Non-printable filtering currently disabled because it did not play well with extended character sets. """
## Filter out non-printing characters #if (byte >= ' ' and byte <= '~') or byte == '\n': if self.telnet_echo: self._echo_byte(byte) self.recv_buffer += byte
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _echo_byte(self, byte): """ Echo a character back to the client and convert LF into CR\LF. """
if byte == '\n': self.send_buffer += '\r' if self.telnet_echo_password: self.send_buffer += '*' else: self.send_buffer += byte
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _two_byte_cmd(self, cmd): """ Handle incoming Telnet commands that are two bytes long. """
#print "got two byte cmd %d" % ord(cmd) if cmd == SB: ## Begin capturing a sub-negotiation string self.telnet_got_sb = True self.telnet_sb_buffer = '' elif cmd == SE: ## Stop capturing a sub-negotiation string self.telnet_got_sb = False self._sb_decoder() elif cmd == NOP: pass elif cmd == DATMK: pass elif cmd == IP: pass elif cmd == AO: pass elif cmd == AYT: pass elif cmd == EC: pass elif cmd == EL: pass elif cmd == GA: pass else: print "2BC: Should not be here." self.telnet_got_iac = False self.telnet_got_cmd = 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 _sb_decoder(self): """ Figures out what to do with a received sub-negotiation block. """
#print "at decoder" bloc = self.telnet_sb_buffer if len(bloc) > 2: if bloc[0] == TTYPE and bloc[1] == IS: self.terminal_type = bloc[2:] #print "Terminal type = '%s'" % self.terminal_type if bloc[0] == NAWS: if len(bloc) != 5: print "Bad length on NAWS SB:", len(bloc) else: self.columns = (256 * ord(bloc[1])) + ord(bloc[2]) self.rows = (256 * ord(bloc[3])) + ord(bloc[4]) #print "Screen is %d x %d" % (self.columns, self.rows) self.telnet_sb_buffer = ''
<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_local_option(self, option): """Test the status of local negotiated Telnet options."""
if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() return self.telnet_opt_dict[option].local_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 _check_remote_option(self, option): """Test the status of remote negotiated Telnet options."""
if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() return self.telnet_opt_dict[option].remote_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 _check_reply_pending(self, option): """Test the status of requested Telnet options."""
if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() return self.telnet_opt_dict[option].reply_pending
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _note_reply_pending(self, option, state): """Record the status of requested Telnet options."""
if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() self.telnet_opt_dict[option].reply_pending = state
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pipecmd (cmd1, cmd2): """Return output of "cmd1 | cmd2"."""
p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE) p2 = subprocess.Popen(cmd2, stdin=p1.stdout, stdout=subprocess.PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. return p2.communicate()[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 _getaddr (self, ifname, func): """Get interface address."""
try: result = self._ioctl(func, self._getifreq(ifname)) except IOError as msg: log.warn(LOG_CHECK, "error getting addr for interface %r: %s", ifname, msg) return None return socket.inet_ntoa(result[20:24])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getInterfaceList (self, flags=0): """Get all interface names in a list."""
if sys.platform == 'darwin': command = ['ifconfig', '-l'] if flags & self.IFF_UP: command.append('-u') # replace with subprocess.check_output() for Python 2.7 res = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0] return res.split() # initial 8kB buffer to hold interface data bufsize = 8192 # 80kB buffer should be enough for most boxen max_bufsize = bufsize * 10 while True: buf = array.array('c', '\0' * bufsize) ifreq = struct.pack("iP", buf.buffer_info()[1], buf.buffer_info()[0]) try: result = self._ioctl(self.SIOCGIFCONF, ifreq) break except IOError as msg: # in case of EINVAL the buffer size was too small if msg[0] != errno.EINVAL or bufsize == max_bufsize: raise # increase buffer bufsize += 8192 # loop over interface names data = buf.tostring() iflist = [] size, ptr = struct.unpack("iP", result) i = 0 while i < size: ifconf = data[i:i+self.ifr_size] name = struct.unpack("16s%ds" % (self.ifr_size-16), ifconf)[0] name = name.split('\0', 1)[0] if name: if flags and not (self.getFlags(name) & flags): continue iflist.append(name) i += self.ifr_size return iflist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getFlags (self, ifname): """Get the flags for an interface"""
try: result = self._ioctl(self.SIOCGIFFLAGS, self._getifreq(ifname)) except IOError as msg: log.warn(LOG_CHECK, "error getting flags for interface %r: %s", ifname, msg) return 0 # extract the interface's flags from the return value flags, = struct.unpack('H', result[16:18]) # return "UP" bit return flags
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAddr (self, ifname): """Get the inet addr for an interface. @param ifname: interface name @type ifname: string """
if sys.platform == 'darwin': return ifconfig_inet(ifname).get('address') return self._getaddr(ifname, self.SIOCGIFADDR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getMask (self, ifname): """Get the netmask for an interface. @param ifname: interface name @type ifname: string """
if sys.platform == 'darwin': return ifconfig_inet(ifname).get('netmask') return self._getaddr(ifname, self.SIOCGIFNETMASK)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getBroadcast (self, ifname): """Get the broadcast addr for an interface. @param ifname: interface name @type ifname: string """
if sys.platform == 'darwin': return ifconfig_inet(ifname).get('broadcast') return self._getaddr(ifname, self.SIOCGIFBRDADDR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isLoopback (self, ifname): """Check whether interface is a loopback device. @param ifname: interface name @type ifname: string """
# since not all systems have IFF_LOOPBACK as a flag defined, # the ifname is tested first if ifname.startswith('lo'): return True return (self.getFlags(ifname) & self.IFF_LOOPBACK) != 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 check(self, url_data): """Extracts urls from the file."""
content = url_data.get_content() self._check_by_re(url_data, content) self._check_inline_links(url_data, content)
<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_by_re(self, url_data, content): """ Finds urls by re. :param url_data: object for url storing :param content: file content """
for link_re in self._link_res: for u in link_re.finditer(content): self._save_url(url_data, content, u.group(1), u.start(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 _find_balanced(self, text, start, open_c, close_c): """Returns the index where the open_c and close_c characters balance out - the same number of open_c and close_c are encountered - or the end of string if it's reached before the balance point is found. """
i = start l = len(text) count = 1 while count > 0 and i < l: if text[i] == open_c: count += 1 elif text[i] == close_c: count -= 1 i += 1 return i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_url_and_title(self, text, start): """Extracts the url from the tail of a link."""
# text[start] equals the opening parenthesis idx = self._whitespace.match(text, start + 1).end() if idx == len(text): return None, None end_idx = idx has_anglebrackets = text[idx] == "<" if has_anglebrackets: end_idx = self._find_balanced(text, end_idx+1, "<", ">") end_idx = self._find_balanced(text, end_idx, "(", ")") match = self._inline_link_title.search(text, idx, end_idx) if not match: return None, None url = text[idx:match.start()] if has_anglebrackets: url = self._strip_anglebrackets.sub(r'\1', url) return url, end_idx
<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_inline_links(self, url_data, content): """Checks inline links. :param url_data: url_data object :param content: content for processing """
MAX_LINK_TEXT_SENTINEL = 3000 curr_pos = 0 content_length = len(content) while True: # Handle the next link. # The next '[' is the start of: # - an inline anchor: [text](url "title") # - an inline img: ![text](url "title") # - not markup: [...anything else... try: start_idx = content.index('[', curr_pos) except ValueError: break # Find the matching closing ']'. bracket_depth = 0 for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, content_length)): if content[p] == ']': bracket_depth -= 1 if bracket_depth < 0: break elif content[p] == '[': bracket_depth += 1 else: # Closing bracket not found within sentinel length. This isn't markup. curr_pos = start_idx + 1 continue # Now determine what this is by the remainder. p += 1 if p >= content_length: return if content[p] == '(': url, url_end_idx = self._extract_url_and_title(content, p) if url is not None: self._save_url(url_data, content, url, p) start_idx = url_end_idx # Otherwise, it isn't markup. curr_pos = start_idx + 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 is_meta_url (attr, attrs): """Check if the meta attributes contain a URL."""
res = False if attr == "content": equiv = attrs.get_true('http-equiv', u'').lower() scheme = attrs.get_true('scheme', u'').lower() res = equiv in (u'refresh',) or scheme in (u'dcterms.uri',) if attr == "href": rel = attrs.get_true('rel', u'').lower() res = rel in (u'shortcut icon', u'icon') return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_form_get(attr, attrs): """Check if this is a GET form action URL."""
res = False if attr == "action": method = attrs.get_true('method', u'').lower() res = method != 'post' return res
<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_element (self, tag, attrs): """Search for meta robots.txt "nofollow" and "noindex" flags."""
if tag == 'meta' and attrs.get('name') == 'robots': val = attrs.get_true('content', u'').lower().split(u',') self.follow = u'nofollow' not in val self.index = u'noindex' not in val raise StopParse("found <meta name=robots> tag") elif tag == 'body': raise StopParse("found <body> tag")
<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_element (self, tag, attrs): """Search for links and store found URLs in a list."""
log.debug(LOG_CHECK, "LinkFinder tag %s attrs %s", tag, attrs) log.debug(LOG_CHECK, "line %d col %d old line %d old col %d", self.parser.lineno(), self.parser.column(), self.parser.last_lineno(), self.parser.last_column()) if tag == "base" and not self.base_ref: self.base_ref = attrs.get_true("href", u'') tagattrs = self.tags.get(tag, self.universal_attrs) # parse URLs in tag (possibly multiple URLs in CSS styles) for attr in tagattrs.intersection(attrs): if tag == "meta" and not is_meta_url(attr, attrs): continue if tag == "form" and not is_form_get(attr, attrs): continue # name of this link name = self.get_link_name(tag, attrs, attr) # possible codebase base = u'' if tag == 'applet': base = attrs.get_true('codebase', u'') if not base: base = self.base_ref # note: value can be None value = attrs.get(attr) if tag == 'link' and attrs.get('rel') == 'dns-prefetch': if ':' in value: value = value.split(':', 1)[1] value = 'dns:' + value.rstrip('/') # parse tag for URLs self.parse_tag(tag, attr, value, name, base) log.debug(LOG_CHECK, "LinkFinder finished tag %s", tag)
<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_link_name (self, tag, attrs, attr): """Parse attrs for link name. Return name of link."""
if tag == 'a' and attr == 'href': # Look for name only up to MAX_NAMELEN characters data = self.parser.peek(MAX_NAMELEN) data = data.decode(self.parser.encoding, "ignore") name = linkname.href_name(data) if not name: name = attrs.get_true('title', u'') elif tag == 'img': name = attrs.get_true('alt', u'') if not name: name = attrs.get_true('title', u'') else: name = u"" return 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_tag (self, tag, attr, value, name, base): """Add given url data to url list."""
assert isinstance(tag, unicode), repr(tag) assert isinstance(attr, unicode), repr(attr) assert isinstance(name, unicode), repr(name) assert isinstance(base, unicode), repr(base) assert isinstance(value, unicode) or value is None, repr(value) # look for meta refresh if tag == u'meta' and value: mo = refresh_re.match(value) if mo: self.found_url(mo.group("url"), name, base) elif attr != 'content': self.found_url(value, name, base) elif attr == u'style' and value: for mo in css_url_re.finditer(value): url = unquote(mo.group("url"), matching=True) self.found_url(url, name, base) elif attr == u'archive': for url in value.split(u','): self.found_url(url, name, base) elif attr == u'srcset': for img_candidate in value.split(u','): url = img_candidate.split()[0] self.found_url(url, name, base) else: self.found_url(value, name, base)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def found_url(self, url, name, base): """Add newly found URL to queue."""
assert isinstance(url, unicode) or url is None, repr(url) self.callback(url, line=self.parser.last_lineno(), column=self.parser.last_column(), name=name, base=base)
<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_list(name, ttl, rdclass, rdtype, text_rdatas): """Create an RRset with the specified name, TTL, class, and type, and with the specified list of rdatas in text format. @rtype: dns.rrset.RRset object """
if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if isinstance(rdclass, (str, unicode)): rdclass = dns.rdataclass.from_text(rdclass) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) r = RRset(name, rdclass, rdtype) r.update_ttl(ttl) for t in text_rdatas: rd = dns.rdata.from_text(r.rdclass, r.rdtype, t) r.add(rd) 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 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 """
return from_text_list(name, ttl, rdclass, rdtype, text_rdatas)
<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_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 """
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) first_time = False r.add(rd) 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 match(self, name, rdclass, rdtype, covers, deleting=None): """Returns True if this rrset matches the specified class, type, covers, and deletion state."""
if not super(RRset, self).match(rdclass, rdtype, covers): return False if self.name != name or self.deleting != deleting: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 origin: The origin for relative names, or None. @type origin: dns.name.Name object @param relativize: True if names should names be relativized @type relativize: bool"""
return super(RRset, self).to_text(self.name, origin, relativize, self.deleting, **kw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_wire(self, file, compress=None, origin=None, **kw): """Convert the RRset to wire format."""
return super(RRset, self).to_wire(self.name, file, compress, origin, self.deleting, **kw)
<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): """ Put invalid url in blacklist, delete valid url from blacklist. """
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: self.blacklist[key] = 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 read_blacklist (self): """ Read a previously stored blacklist from file fd. """
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, 1) self.blacklist[key] = int(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 write_blacklist (self): """ Write the blacklist. """
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)
<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, 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 or string @param rdclass: The zone's rdata class; the default is class IN. @type rdclass: int @param relativize: should names be relativized? The default is True @type relativize: bool @param zone_factory: The zone factory to use @type zone_factory: function returning a Zone @param filename: The filename to emit when describing where an error occurred; the default is '<string>'. @type filename: string @param allow_include: is $INCLUDE allowed? @type allow_include: bool @param check_origin: should sanity checks of the origin node be done? The default is True. @type check_origin: bool @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 @rtype: dns.zone.Zone object """
# '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, relativize, zone_factory, allow_include=allow_include, check_origin=check_origin) reader.read() return reader.zone
<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_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: dns.name.Name object or string @param rdclass: The zone's rdata class; the default is class IN. @type rdclass: int @param relativize: should names be relativized? The default is True @type relativize: bool @param zone_factory: The zone factory to use @type zone_factory: function returning a Zone @param filename: The filename to emit when describing where an error occurred; the default is '<file>', or the value of I{f} if I{f} is a string. @type filename: string @param allow_include: is $INCLUDE allowed? @type allow_include: bool @param check_origin: should sanity checks of the origin node be done? The default is True. @type check_origin: bool @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 @rtype: dns.zone.Zone object """
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, opts) want_close = True else: if filename is None: filename = '<file>' want_close = False try: z = from_text(f, origin, rdclass, relativize, zone_factory, filename, allow_include, check_origin) finally: if want_close: f.close() return z
<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_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.query.xfr(). @type relativize: bool @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 @rtype: dns.zone.Zone object """
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: znode = z.nodes.get(rrset.name) if not znode: znode = z.node_factory() z.nodes[rrset.name] = znode zrds = znode.find_rdataset(rrset.rdclass, rrset.rdtype, rrset.covers, True) zrds.update_ttl(rrset.ttl) for rd in rrset: rd.choose_relativity(z.origin, relativize) zrds.add(rd) z.check_origin() return z
<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_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 specified. @rtype: dns.node.Node object """
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
<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_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 string @param create: should the node be created if it doesn't exist? @type create: bool @rtype: dns.node.Node object or None """
try: node = self.find_node(name, create) except KeyError: node = None return node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_node(self, name): """Delete the specified node if it exists. It is not an error if the node does not exist. """
name = self._validate_name(name) if name in self.nodes: del self.nodes[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 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. If the I{name} node does not exist, it is created. @param name: the owner name @type name: DNS.name.Name object or string @param replacement: the replacement rdataset @type replacement: dns.rdataset.Rdataset """
if replacement.rdclass != self.rdclass: raise ValueError('replacement.rdclass != zone.rdclass') node = self.find_node(name, True) node.replace_rdataset(replacement)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 order they happen to have in the zone's dictionary. @param relativize: if True, domain names in the output will be relativized to the zone's origin (if possible). @type relativize: bool @param nl: The end of line string. If not specified, the output will use the platform's native end-of-line marker (i.e. LF on POSIX, CRLF on Windows, CR on Macintosh). @type nl: string or None """
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) want_close = True else: want_close = False try: if sorted: names = self.keys() names.sort() else: names = self.iterkeys() for n in names: l = self[n].to_text(n, origin=self.origin, relativize=relativize) if nl is None: print >> f, l else: f.write(l) f.write(nl) finally: if want_close: f.close()