Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|>#///////////////// Use this pattern to write to_string() or drawData() to display each member of the model for a struct. classesToProcess=[] classesEncoded={} class structProcessor: def addGlobalCode(self, classes): pass def resetVars(self, modelRef): pass def processField(self, fieldName, field, fldCat): pass def addOrAmendClasses(self, classes, className, modelRef): pass def processStruct(self, classes, className): global classesEncoded classesEncoded[className]=1 self.currentClassName = className modelRef = progSpec.findSpecOf(classes[0], className, 'model') self.resetVars(modelRef) self.currentModelSpec = modelRef if modelRef==None: <|code_end|> using the current file's imports: import progSpec import codeDogParser import pattern_GenSymbols from progSpec import cdlog, cdErr and any relevant context from other files: # Path: progSpec.py # def cdlog(lvl, mesg): # global MaxLogLevelToShow # global lastLogMesgs # global highestLvl # highestLvl=lvl # resizeLogArray(lvl) # lastLogMesgs[lvl]=mesg # for i in range(highestLvl+1, len(lastLogMesgs)): # lastLogMesgs[i]='' # if(lvl<=MaxLogLevelToShow): # if(lvl==0): print('') # printAtLvl(lvl, mesg, '| ') # # def cdErr(mesg): # global lastLogMesgs # global highestLvl # highestLvl+=1 # lastLogMesgs[highestLvl]="\n\nError: "+mesg # exit(1) . Output only the next line.
cdErr('To write a processing function for class "'+className+'" a model is needed but is not found.')
Given the code snippet: <|code_start|> def checkToolLinux(toolName): if subprocess.call(["which", toolName], stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0: return True else: return None def checkToolWindows(toolName): if subprocess.call(["Where", toolName], stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0: return True else: return None def findPackageManager(): installedPackageManagerList = [] packageManagers = ["dpkg", "brew", "yum", "apt-get", "pacman", "emerge", "zypper", "dnf"] for pmgr in packageManagers: if checkToolLinux(pmgr): installedPackageManagerList.append(pmgr) return installedPackageManagerList def packageInstalled(packageManagar, packageName): <|code_end|> , generate the next line using the imports in this file: import os import subprocess import checkSys import urllib3 from progSpec import cdlog, cdErr from sys import platform and context (functions, classes, or occasionally code) from other files: # Path: progSpec.py # def cdlog(lvl, mesg): # global MaxLogLevelToShow # global lastLogMesgs # global highestLvl # highestLvl=lvl # resizeLogArray(lvl) # lastLogMesgs[lvl]=mesg # for i in range(highestLvl+1, len(lastLogMesgs)): # lastLogMesgs[i]='' # if(lvl<=MaxLogLevelToShow): # if(lvl==0): print('') # printAtLvl(lvl, mesg, '| ') # # def cdErr(mesg): # global lastLogMesgs # global highestLvl # highestLvl+=1 # lastLogMesgs[highestLvl]="\n\nError: "+mesg # exit(1) . Output only the next line.
cdlog(1, "Package Installing: "+packageName)
Next line prediction: <|code_start|> def checkToolLinux(toolName): if subprocess.call(["which", toolName], stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0: return True else: return None def checkToolWindows(toolName): if subprocess.call(["Where", toolName], stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0: return True else: return None def findPackageManager(): installedPackageManagerList = [] packageManagers = ["dpkg", "brew", "yum", "apt-get", "pacman", "emerge", "zypper", "dnf"] for pmgr in packageManagers: if checkToolLinux(pmgr): installedPackageManagerList.append(pmgr) return installedPackageManagerList def packageInstalled(packageManagar, packageName): cdlog(1, "Package Installing: "+packageName) if subprocess.call(f'{packageManagar} {packageName}'+" -y > /dev/null 2>&1", shell=True) == 0: cdlog(1, "Package installed Successfully") return True else: <|code_end|> . Use current file imports: (import os import subprocess import checkSys import urllib3 from progSpec import cdlog, cdErr from sys import platform) and context including class names, function names, or small code snippets from other files: # Path: progSpec.py # def cdlog(lvl, mesg): # global MaxLogLevelToShow # global lastLogMesgs # global highestLvl # highestLvl=lvl # resizeLogArray(lvl) # lastLogMesgs[lvl]=mesg # for i in range(highestLvl+1, len(lastLogMesgs)): # lastLogMesgs[i]='' # if(lvl<=MaxLogLevelToShow): # if(lvl==0): print('') # printAtLvl(lvl, mesg, '| ') # # def cdErr(mesg): # global lastLogMesgs # global highestLvl # highestLvl+=1 # lastLogMesgs[highestLvl]="\n\nError: "+mesg # exit(1) . Output only the next line.
cdErr("Unable to install package. \nPlease install manually : " + packageName)
Based on the snippet: <|code_start|># buildiOS.py def writeFile(path, fileName, fileSpecs, fileExtension): #print path makeDir(path) fileName += fileExtension pathName = path + os.sep + fileName <|code_end|> , predict the immediate next line with the help of imports: import os import subprocess import errno import shutil from progSpec import cdlog, cdErr and context (classes, functions, sometimes code) from other files: # Path: progSpec.py # def cdlog(lvl, mesg): # global MaxLogLevelToShow # global lastLogMesgs # global highestLvl # highestLvl=lvl # resizeLogArray(lvl) # lastLogMesgs[lvl]=mesg # for i in range(highestLvl+1, len(lastLogMesgs)): # lastLogMesgs[i]='' # if(lvl<=MaxLogLevelToShow): # if(lvl==0): print('') # printAtLvl(lvl, mesg, '| ') # # def cdErr(mesg): # global lastLogMesgs # global highestLvl # highestLvl+=1 # lastLogMesgs[highestLvl]="\n\nError: "+mesg # exit(1) . Output only the next line.
cdlog(1, "WRITING FILE: "+pathName)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """Tests for plugin manager.""" try: except ImportError: class Dummy(object): """Empty Dummy class used to test plugin system.""" pass class TestPluginProxy(unittest.TestCase): """Test cases for the PluginProxy.""" def test_proxy_constructor(self): """Test the plugin proxy constructor.""" <|code_end|> , predict the immediate next line with the help of imports: import unittest import mock from unittest import mock from dyndnsc.plugins import manager and context (classes, functions, sometimes code) from other files: # Path: dyndnsc/plugins/manager.py # ENV_PREFIX = "DYNDNSC_WITH_" # LOG = logging.getLogger(__name__) # class PluginProxy(object): # class NullPluginManager(object): # class PluginManager(object): # class EntryPointPluginManager(PluginManager): # class BuiltinPluginManager(PluginManager): # class DefaultPluginManager(EntryPointPluginManager, BuiltinPluginManager): # class DefaultPluginManager(BuiltinPluginManager): # def __init__(self, call, plugins): # def __call__(self, *arg, **kw): # def add_plugin(self, plugin, call): # def listcall(self, *arg, **kw): # def __iter__(self): # def __getattr__(self, call): # def _nop(self, *args, **kwds): # def add_plugin(self, plug): # def add_plugins(self, plugins): # def configure(self, options): # def load_plugins(self): # def __init__(self, plugins=(), proxyClass=None): # def __getattr__(self, call): # def __iter__(self): # def add_plugin(self, plugin): # def plugin_name(plugin): # def add_plugins(self, plugins=()): # def configure(self, args): # def options(self, parser, env): # def get_help(plug): # def load_plugins(self): # def _get_plugins(self): # def _set_plugins(self, plugins): # def load_plugins(self): # def load_plugins(self): . Output only the next line.
self.assertRaises(TypeError, manager.PluginProxy)
Using the snippet: <|code_start|> def give_me_an_interface_ipv6(): """Return a local ipv6 interface or None.""" for interface in netifaces.interfaces(): if netifaces.AF_INET6 in netifaces.ifaddresses(interface): return interface return None def give_me_an_interface_ipv4(): """Return a local ipv4 interface or None.""" for interface in netifaces.interfaces(): if netifaces.AF_INET in netifaces.ifaddresses(interface): return interface return None class IfaceDetectorTest(unittest.TestCase): """Test cases for iface detector.""" def test_iface_detector(self): """Run iface tests.""" self.assertEqual("iface", iface.IPDetector_Iface.configuration_key) # auto-detect an interface: interface = give_me_an_interface_ipv4() self.assertNotEqual(None, interface) detector = iface.IPDetector_Iface(iface=interface) self.assertTrue(detector.can_detect_offline()) self.assertEqual(None, detector.get_current_value()) <|code_end|> , determine the next line of code. You have imports: import unittest import netifaces import netifaces from dyndnsc.detector.base import AF_INET6 from dyndnsc.common.six import string_types from dyndnsc.detector import iface from dyndnsc.detector import teredo and context (class names, function names, or code) available: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # def ipnetwork(addr): . Output only the next line.
self.assertTrue(isinstance(detector.detect(), string_types + (type(None),)))
Predict the next line for this snippet: <|code_start|>def resolve(hostname, family=AF_UNSPEC): """ Resolve hostname to one or more IP addresses through the operating system. Resolution is carried out for the given address family. If no address family is specified, only IPv4 and IPv6 addresses are returned. If multiple IP addresses are found, all are returned. :param family: AF_INET or AF_INET6 or AF_UNSPEC (default) :return: tuple of unique IP addresses """ af_ok = (AF_INET, AF_INET6) if family != AF_UNSPEC and family not in af_ok: raise ValueError("Invalid family '%s'" % family) ips = () try: addrinfo = socket.getaddrinfo(hostname, None, family) except socket.gaierror as exc: # EAI_NODATA and EAI_NONAME are expected if this name is not (yet) # present in DNS if exc.errno not in (socket.EAI_NODATA, socket.EAI_NONAME): LOG.debug("socket.getaddrinfo() raised an exception", exc_info=exc) else: if family == AF_UNSPEC: ips = tuple({item[4][0] for item in addrinfo if item[0] in af_ok}) else: ips = tuple({item[4][0] for item in addrinfo}) return ips <|code_end|> with the help of current file imports: import socket import logging from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC and context from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): , which may contain function names, class names, or code. Output only the next line.
class IPDetector_DNS(IPDetector):
Given snippet: <|code_start|># -*- coding: utf-8 -*- """Module containing logic for dns based detectors.""" LOG = logging.getLogger(__name__) def resolve(hostname, family=AF_UNSPEC): """ Resolve hostname to one or more IP addresses through the operating system. Resolution is carried out for the given address family. If no address family is specified, only IPv4 and IPv6 addresses are returned. If multiple IP addresses are found, all are returned. :param family: AF_INET or AF_INET6 or AF_UNSPEC (default) :return: tuple of unique IP addresses """ <|code_end|> , continue by predicting the next line. Consider current file imports: import socket import logging from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC and context: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): which might include code, classes, or functions. Output only the next line.
af_ok = (AF_INET, AF_INET6)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- """Module containing logic for dns based detectors.""" LOG = logging.getLogger(__name__) def resolve(hostname, family=AF_UNSPEC): """ Resolve hostname to one or more IP addresses through the operating system. Resolution is carried out for the given address family. If no address family is specified, only IPv4 and IPv6 addresses are returned. If multiple IP addresses are found, all are returned. :param family: AF_INET or AF_INET6 or AF_UNSPEC (default) :return: tuple of unique IP addresses """ <|code_end|> . Write the next line using the current file imports: import socket import logging from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC and context from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): , which may include functions, classes, or code. Output only the next line.
af_ok = (AF_INET, AF_INET6)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """Module providing IP detection functionality based on netifaces.""" LOG = logging.getLogger(__name__) def _default_interface(): """Return the default interface name for common operating systems.""" system = platform.system() if system == "Linux": return "eth0" elif system == "Darwin": return "en0" return None <|code_end|> , determine the next line of code. You have imports: import logging import netifaces import platform from .base import IPDetector, AF_INET6 from ..common.six import ipaddress, ipnetwork and context (class names, function names, or code) available: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # def ipnetwork(addr): # """Return an ipaddress.ip_network object from the given string IP.""" # return _ipaddress.ip_network(addr) . Output only the next line.
class IPDetector_Iface(IPDetector):
Based on the snippet: <|code_start|> :param family: IP address family (default: INET, possible: INET6) :param netmask: netmask to be matched if multiple IPs on interface (default: none (match all)", example for teredo: "2001:0000::/32") """ super(IPDetector_Iface, self).__init__(*args, family=family, **kwargs) self.opts_iface = iface if iface else _default_interface() self.opts_netmask = netmask # ensure an interface name was specified: if self.opts_iface is None: raise ValueError("No network interface specified!") # parse/validate given netmask: if self.opts_netmask is not None: # if a netmask was given # This might fail here, but that's OK since we must avoid sending # an IP to the outside world that should be hidden (because in a # "private" netmask) self.netmask = ipnetwork(self.opts_netmask) else: self.netmask = None def can_detect_offline(self): """Return true, as this detector only queries local data.""" return True def _detect(self): """Use the netifaces module to detect ifconfig information.""" theip = None try: <|code_end|> , predict the immediate next line with the help of imports: import logging import netifaces import platform from .base import IPDetector, AF_INET6 from ..common.six import ipaddress, ipnetwork and context (classes, functions, sometimes code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # def ipnetwork(addr): # """Return an ipaddress.ip_network object from the given string IP.""" # return _ipaddress.ip_network(addr) . Output only the next line.
if self.opts_family == AF_INET6:
Given snippet: <|code_start|> if self.opts_iface is None: raise ValueError("No network interface specified!") # parse/validate given netmask: if self.opts_netmask is not None: # if a netmask was given # This might fail here, but that's OK since we must avoid sending # an IP to the outside world that should be hidden (because in a # "private" netmask) self.netmask = ipnetwork(self.opts_netmask) else: self.netmask = None def can_detect_offline(self): """Return true, as this detector only queries local data.""" return True def _detect(self): """Use the netifaces module to detect ifconfig information.""" theip = None try: if self.opts_family == AF_INET6: addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET6] else: addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET] except ValueError as exc: LOG.error("netifaces choked while trying to get network interface" " information for interface '%s'", self.opts_iface, exc_info=exc) else: # now we have a list of addresses as returned by netifaces for pair in addrlist: try: <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import netifaces import platform from .base import IPDetector, AF_INET6 from ..common.six import ipaddress, ipnetwork and context: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # def ipnetwork(addr): # """Return an ipaddress.ip_network object from the given string IP.""" # return _ipaddress.ip_network(addr) which might include code, classes, or functions. Output only the next line.
detip = ipaddress(pair["addr"])
Continue the code snippet: <|code_start|> IPDetector to detect an IP address assigned to a local interface. This is roughly equivalent to using `ifconfig` or `ipconfig`. """ configuration_key = "iface" def __init__(self, iface=None, netmask=None, family=None, *args, **kwargs): """ Initialize. :param iface: name of interface :param family: IP address family (default: INET, possible: INET6) :param netmask: netmask to be matched if multiple IPs on interface (default: none (match all)", example for teredo: "2001:0000::/32") """ super(IPDetector_Iface, self).__init__(*args, family=family, **kwargs) self.opts_iface = iface if iface else _default_interface() self.opts_netmask = netmask # ensure an interface name was specified: if self.opts_iface is None: raise ValueError("No network interface specified!") # parse/validate given netmask: if self.opts_netmask is not None: # if a netmask was given # This might fail here, but that's OK since we must avoid sending # an IP to the outside world that should be hidden (because in a # "private" netmask) <|code_end|> . Use current file imports: import logging import netifaces import platform from .base import IPDetector, AF_INET6 from ..common.six import ipaddress, ipnetwork and context (classes, functions, or code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # def ipnetwork(addr): # """Return an ipaddress.ip_network object from the given string IP.""" # return _ipaddress.ip_network(addr) . Output only the next line.
self.netmask = ipnetwork(self.opts_netmask)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """Module containing logic for socket based detectors.""" LOG = logging.getLogger(__name__) class IPDetector_Socket(IPDetector): """Detect IPs used by the system to communicate with outside world.""" configuration_key = "socket" def __init__(self, family=None, *args, **kwargs): """ Initialize. :param family: IP address family (default: INET, possible: INET6) """ super(IPDetector_Socket, self).__init__(*args, family=family, **kwargs) def can_detect_offline(self): """Return False, this detector works offline.""" # unsure about this. detector does not really transmit data to outside, # but unsure if it gives the wanted IPs if system is offline return False def detect(self): """Detect the IP address.""" <|code_end|> using the current file's imports: import logging from .base import IPDetector, AF_INET6 from ..common.detect_ip import detect_ip, IPV4, IPV6_PUBLIC, GetIpException and any relevant context from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/detect_ip.py # def detect_ip(kind): # """ # Detect IP address. # # kind can be: # IPV4 - returns IPv4 address # IPV6_ANY - returns any IPv6 address (no preference) # IPV6_PUBLIC - returns public IPv6 address # IPV6_TMP - returns temporary IPV6 address (privacy extensions) # # This function either returns an IP address (str) or # raises a GetIpException. # """ # if kind not in (IPV4, IPV6_PUBLIC, IPV6_TMP, IPV6_ANY): # raise ValueError("invalid kind specified") # # # We create an UDP socket and connect it to a public host. # # We query the OS to know what our address is. # # No packet will really be sent since we are using UDP. # af = socket.AF_INET if kind == IPV4 else socket.AF_INET6 # s = socket.socket(af, socket.SOCK_DGRAM) # try: # if kind in [IPV6_PUBLIC, IPV6_TMP, ]: # # caller wants some specific kind of IPv6 address (not IPV6_ANY) # try: # if kind == IPV6_PUBLIC: # preference = socket.IPV6_PREFER_SRC_PUBLIC # elif kind == IPV6_TMP: # preference = socket.IPV6_PREFER_SRC_TMP # s.setsockopt(socket.IPPROTO_IPV6, # socket.IPV6_ADDR_PREFERENCES, preference) # except socket.error as e: # if e.errno == errno.ENOPROTOOPT: # raise GetIpException("Kernel doesn't support IPv6 address preference") # else: # raise GetIpException("Unable to set IPv6 address preference: %s" % e) # # try: # outside_ip = OUTSIDE_IPV4 if kind == IPV4 else OUTSIDE_IPV6 # s.connect((outside_ip, 9)) # except (socket.error, socket.gaierror) as e: # raise GetIpException(str(e)) # # ip = s.getsockname()[0] # finally: # s.close() # return ip # # IPV4 = "ipv4" # # IPV6_PUBLIC = "ipv6_public" # # class GetIpException(Exception): # """Generic base class for all exceptions raised here.""" . Output only the next line.
if self.opts_family == AF_INET6:
Given the code snippet: <|code_start|>LOG = logging.getLogger(__name__) class IPDetector_Socket(IPDetector): """Detect IPs used by the system to communicate with outside world.""" configuration_key = "socket" def __init__(self, family=None, *args, **kwargs): """ Initialize. :param family: IP address family (default: INET, possible: INET6) """ super(IPDetector_Socket, self).__init__(*args, family=family, **kwargs) def can_detect_offline(self): """Return False, this detector works offline.""" # unsure about this. detector does not really transmit data to outside, # but unsure if it gives the wanted IPs if system is offline return False def detect(self): """Detect the IP address.""" if self.opts_family == AF_INET6: kind = IPV6_PUBLIC else: # 'INET': kind = IPV4 theip = None try: <|code_end|> , generate the next line using the imports in this file: import logging from .base import IPDetector, AF_INET6 from ..common.detect_ip import detect_ip, IPV4, IPV6_PUBLIC, GetIpException and context (functions, classes, or occasionally code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/detect_ip.py # def detect_ip(kind): # """ # Detect IP address. # # kind can be: # IPV4 - returns IPv4 address # IPV6_ANY - returns any IPv6 address (no preference) # IPV6_PUBLIC - returns public IPv6 address # IPV6_TMP - returns temporary IPV6 address (privacy extensions) # # This function either returns an IP address (str) or # raises a GetIpException. # """ # if kind not in (IPV4, IPV6_PUBLIC, IPV6_TMP, IPV6_ANY): # raise ValueError("invalid kind specified") # # # We create an UDP socket and connect it to a public host. # # We query the OS to know what our address is. # # No packet will really be sent since we are using UDP. # af = socket.AF_INET if kind == IPV4 else socket.AF_INET6 # s = socket.socket(af, socket.SOCK_DGRAM) # try: # if kind in [IPV6_PUBLIC, IPV6_TMP, ]: # # caller wants some specific kind of IPv6 address (not IPV6_ANY) # try: # if kind == IPV6_PUBLIC: # preference = socket.IPV6_PREFER_SRC_PUBLIC # elif kind == IPV6_TMP: # preference = socket.IPV6_PREFER_SRC_TMP # s.setsockopt(socket.IPPROTO_IPV6, # socket.IPV6_ADDR_PREFERENCES, preference) # except socket.error as e: # if e.errno == errno.ENOPROTOOPT: # raise GetIpException("Kernel doesn't support IPv6 address preference") # else: # raise GetIpException("Unable to set IPv6 address preference: %s" % e) # # try: # outside_ip = OUTSIDE_IPV4 if kind == IPV4 else OUTSIDE_IPV6 # s.connect((outside_ip, 9)) # except (socket.error, socket.gaierror) as e: # raise GetIpException(str(e)) # # ip = s.getsockname()[0] # finally: # s.close() # return ip # # IPV4 = "ipv4" # # IPV6_PUBLIC = "ipv6_public" # # class GetIpException(Exception): # """Generic base class for all exceptions raised here.""" . Output only the next line.
theip = detect_ip(kind)
Given the code snippet: <|code_start|> LOG = logging.getLogger(__name__) class IPDetector_Socket(IPDetector): """Detect IPs used by the system to communicate with outside world.""" configuration_key = "socket" def __init__(self, family=None, *args, **kwargs): """ Initialize. :param family: IP address family (default: INET, possible: INET6) """ super(IPDetector_Socket, self).__init__(*args, family=family, **kwargs) def can_detect_offline(self): """Return False, this detector works offline.""" # unsure about this. detector does not really transmit data to outside, # but unsure if it gives the wanted IPs if system is offline return False def detect(self): """Detect the IP address.""" if self.opts_family == AF_INET6: kind = IPV6_PUBLIC else: # 'INET': <|code_end|> , generate the next line using the imports in this file: import logging from .base import IPDetector, AF_INET6 from ..common.detect_ip import detect_ip, IPV4, IPV6_PUBLIC, GetIpException and context (functions, classes, or occasionally code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/detect_ip.py # def detect_ip(kind): # """ # Detect IP address. # # kind can be: # IPV4 - returns IPv4 address # IPV6_ANY - returns any IPv6 address (no preference) # IPV6_PUBLIC - returns public IPv6 address # IPV6_TMP - returns temporary IPV6 address (privacy extensions) # # This function either returns an IP address (str) or # raises a GetIpException. # """ # if kind not in (IPV4, IPV6_PUBLIC, IPV6_TMP, IPV6_ANY): # raise ValueError("invalid kind specified") # # # We create an UDP socket and connect it to a public host. # # We query the OS to know what our address is. # # No packet will really be sent since we are using UDP. # af = socket.AF_INET if kind == IPV4 else socket.AF_INET6 # s = socket.socket(af, socket.SOCK_DGRAM) # try: # if kind in [IPV6_PUBLIC, IPV6_TMP, ]: # # caller wants some specific kind of IPv6 address (not IPV6_ANY) # try: # if kind == IPV6_PUBLIC: # preference = socket.IPV6_PREFER_SRC_PUBLIC # elif kind == IPV6_TMP: # preference = socket.IPV6_PREFER_SRC_TMP # s.setsockopt(socket.IPPROTO_IPV6, # socket.IPV6_ADDR_PREFERENCES, preference) # except socket.error as e: # if e.errno == errno.ENOPROTOOPT: # raise GetIpException("Kernel doesn't support IPv6 address preference") # else: # raise GetIpException("Unable to set IPv6 address preference: %s" % e) # # try: # outside_ip = OUTSIDE_IPV4 if kind == IPV4 else OUTSIDE_IPV6 # s.connect((outside_ip, 9)) # except (socket.error, socket.gaierror) as e: # raise GetIpException(str(e)) # # ip = s.getsockname()[0] # finally: # s.close() # return ip # # IPV4 = "ipv4" # # IPV6_PUBLIC = "ipv6_public" # # class GetIpException(Exception): # """Generic base class for all exceptions raised here.""" . Output only the next line.
kind = IPV4
Predict the next line after this snippet: <|code_start|> """Module containing logic for socket based detectors.""" LOG = logging.getLogger(__name__) class IPDetector_Socket(IPDetector): """Detect IPs used by the system to communicate with outside world.""" configuration_key = "socket" def __init__(self, family=None, *args, **kwargs): """ Initialize. :param family: IP address family (default: INET, possible: INET6) """ super(IPDetector_Socket, self).__init__(*args, family=family, **kwargs) def can_detect_offline(self): """Return False, this detector works offline.""" # unsure about this. detector does not really transmit data to outside, # but unsure if it gives the wanted IPs if system is offline return False def detect(self): """Detect the IP address.""" if self.opts_family == AF_INET6: <|code_end|> using the current file's imports: import logging from .base import IPDetector, AF_INET6 from ..common.detect_ip import detect_ip, IPV4, IPV6_PUBLIC, GetIpException and any relevant context from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/detect_ip.py # def detect_ip(kind): # """ # Detect IP address. # # kind can be: # IPV4 - returns IPv4 address # IPV6_ANY - returns any IPv6 address (no preference) # IPV6_PUBLIC - returns public IPv6 address # IPV6_TMP - returns temporary IPV6 address (privacy extensions) # # This function either returns an IP address (str) or # raises a GetIpException. # """ # if kind not in (IPV4, IPV6_PUBLIC, IPV6_TMP, IPV6_ANY): # raise ValueError("invalid kind specified") # # # We create an UDP socket and connect it to a public host. # # We query the OS to know what our address is. # # No packet will really be sent since we are using UDP. # af = socket.AF_INET if kind == IPV4 else socket.AF_INET6 # s = socket.socket(af, socket.SOCK_DGRAM) # try: # if kind in [IPV6_PUBLIC, IPV6_TMP, ]: # # caller wants some specific kind of IPv6 address (not IPV6_ANY) # try: # if kind == IPV6_PUBLIC: # preference = socket.IPV6_PREFER_SRC_PUBLIC # elif kind == IPV6_TMP: # preference = socket.IPV6_PREFER_SRC_TMP # s.setsockopt(socket.IPPROTO_IPV6, # socket.IPV6_ADDR_PREFERENCES, preference) # except socket.error as e: # if e.errno == errno.ENOPROTOOPT: # raise GetIpException("Kernel doesn't support IPv6 address preference") # else: # raise GetIpException("Unable to set IPv6 address preference: %s" % e) # # try: # outside_ip = OUTSIDE_IPV4 if kind == IPV4 else OUTSIDE_IPV6 # s.connect((outside_ip, 9)) # except (socket.error, socket.gaierror) as e: # raise GetIpException(str(e)) # # ip = s.getsockname()[0] # finally: # s.close() # return ip # # IPV4 = "ipv4" # # IPV6_PUBLIC = "ipv6_public" # # class GetIpException(Exception): # """Generic base class for all exceptions raised here.""" . Output only the next line.
kind = IPV6_PUBLIC
Given the code snippet: <|code_start|> class IPDetector_Socket(IPDetector): """Detect IPs used by the system to communicate with outside world.""" configuration_key = "socket" def __init__(self, family=None, *args, **kwargs): """ Initialize. :param family: IP address family (default: INET, possible: INET6) """ super(IPDetector_Socket, self).__init__(*args, family=family, **kwargs) def can_detect_offline(self): """Return False, this detector works offline.""" # unsure about this. detector does not really transmit data to outside, # but unsure if it gives the wanted IPs if system is offline return False def detect(self): """Detect the IP address.""" if self.opts_family == AF_INET6: kind = IPV6_PUBLIC else: # 'INET': kind = IPV4 theip = None try: theip = detect_ip(kind) <|code_end|> , generate the next line using the imports in this file: import logging from .base import IPDetector, AF_INET6 from ..common.detect_ip import detect_ip, IPV4, IPV6_PUBLIC, GetIpException and context (functions, classes, or occasionally code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/detect_ip.py # def detect_ip(kind): # """ # Detect IP address. # # kind can be: # IPV4 - returns IPv4 address # IPV6_ANY - returns any IPv6 address (no preference) # IPV6_PUBLIC - returns public IPv6 address # IPV6_TMP - returns temporary IPV6 address (privacy extensions) # # This function either returns an IP address (str) or # raises a GetIpException. # """ # if kind not in (IPV4, IPV6_PUBLIC, IPV6_TMP, IPV6_ANY): # raise ValueError("invalid kind specified") # # # We create an UDP socket and connect it to a public host. # # We query the OS to know what our address is. # # No packet will really be sent since we are using UDP. # af = socket.AF_INET if kind == IPV4 else socket.AF_INET6 # s = socket.socket(af, socket.SOCK_DGRAM) # try: # if kind in [IPV6_PUBLIC, IPV6_TMP, ]: # # caller wants some specific kind of IPv6 address (not IPV6_ANY) # try: # if kind == IPV6_PUBLIC: # preference = socket.IPV6_PREFER_SRC_PUBLIC # elif kind == IPV6_TMP: # preference = socket.IPV6_PREFER_SRC_TMP # s.setsockopt(socket.IPPROTO_IPV6, # socket.IPV6_ADDR_PREFERENCES, preference) # except socket.error as e: # if e.errno == errno.ENOPROTOOPT: # raise GetIpException("Kernel doesn't support IPv6 address preference") # else: # raise GetIpException("Unable to set IPv6 address preference: %s" % e) # # try: # outside_ip = OUTSIDE_IPV4 if kind == IPV4 else OUTSIDE_IPV6 # s.connect((outside_ip, 9)) # except (socket.error, socket.gaierror) as e: # raise GetIpException(str(e)) # # ip = s.getsockname()[0] # finally: # s.close() # return ip # # IPV4 = "ipv4" # # IPV6_PUBLIC = "ipv6_public" # # class GetIpException(Exception): # """Generic base class for all exceptions raised here.""" . Output only the next line.
except GetIpException:
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """Management of updaters.""" def updater_classes(): """Return all built-in updater classes.""" return PLUGINS def get_updater_class(name="noip"): """Return updater class identified by configuration key ``name``.""" <|code_end|> , predict the next line using imports from the current file: from ..common.load import find_class from .builtin import PLUGINS and context including class names, function names, and sometimes code from other files: # Path: dyndnsc/common/load.py # def find_class(name, classes): # """Return class in ``classes`` identified by configuration key ``name``.""" # name = name.lower() # cls = next((c for c in classes if c.configuration_key == name), None) # if cls is None: # raise ValueError("No class named '%s' could be found" % name) # return cls . Output only the next line.
return find_class(name, updater_classes())
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """Management of detectors.""" def detector_classes(): """Return all built-in detector classes.""" return PLUGINS def get_detector_class(name="webcheck4"): """Return detector class identified by configuration key ``name``.""" <|code_end|> , predict the next line using imports from the current file: from ..common.load import find_class from .builtin import PLUGINS and context including class names, function names, and sometimes code from other files: # Path: dyndnsc/common/load.py # def find_class(name, classes): # """Return class in ``classes`` identified by configuration key ``name``.""" # name = name.lower() # cls = next((c for c in classes if c.configuration_key == name), None) # if cls is None: # raise ValueError("No class named '%s' could be found" % name) # return cls . Output only the next line.
return find_class(name, detector_classes())
Continue the code snippet: <|code_start|> regex = re.compile(pattern) for line in text.splitlines(): match_obj = regex.search(line) if match_obj is not None: return str(ipaddress(match_obj.group(1))) LOG.debug("Output '%s' could not be parsed", text) return None def _parser_checkip_dns_he_net(text): return _parser_line_regex(text, pattern="Your IP address is : (.*?)(<.*){0,1}$") def _parser_checkip(text): return _parser_line_regex(text, pattern="Current IP Address: (.*?)(<.*){0,1}$") def _parser_freedns_afraid(text): return _parser_line_regex(text, pattern="Detected IP : (.*?)(<.*){0,1}$") def _parser_jsonip(text): """Parse response text like the one returned by http://jsonip.com/.""" try: return str(json.loads(text).get("ip")) except ValueError as exc: LOG.debug("Text '%s' could not be parsed", exc_info=exc) return None <|code_end|> . Use current file imports: import logging import re import requests import json from random import choice from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC from ..common.six import ipaddress from ..common import constants and context (classes, functions, or code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
class IPDetectorWebCheckBase(IPDetector):
Predict the next line for this snippet: <|code_start|> Return parsable output containing the IP address. .. note:: This detection mechanism requires ipv4 connectivity, otherwise it will simply not detect the IP address. """ configuration_key = "webcheck4" # TODO: consider throwing out all URLs with no TLS support urls = ( ("http://checkip.eurodyndns.org/", "checkip"), ("http://ip.dnsexit.com/", "plain"), ("http://checkip.dns.he.net/", "checkip_dns_he_net"), ("http://ip1.dynupdate.no-ip.com/", "plain"), ("http://ip2.dynupdate.no-ip.com/", "plain"), ("https://api.ipify.org/", "plain"), ("https://dynamic.zoneedit.com/checkip.html", "plain"), ("https://freedns.afraid.org/dynamic/check.php", "freedns_afraid"), ("https://ifconfig.co/ip", "plain"), ("https://ipinfo.io/ip", "plain"), ("https://ipv4.icanhazip.com/", "plain"), ("https://ipv4.nsupdate.info/myip", "plain"), ("https://jsonip.com/", "jsonip"), ) def __init__(self, *args, **kwargs): """Initialize.""" super(IPDetectorWebCheck, self).__init__(*args, **kwargs) <|code_end|> with the help of current file imports: import logging import re import requests import json from random import choice from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC from ..common.six import ipaddress from ..common import constants and context from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } , which may contain function names, class names, or code. Output only the next line.
self.opts_family = AF_INET
Predict the next line after this snippet: <|code_start|> def __init__(self, *args, **kwargs): """Initialize.""" super(IPDetectorWebCheck, self).__init__(*args, **kwargs) self.opts_family = AF_INET class IPDetectorWebCheck6(IPDetectorWebCheckBase): """ Class to detect an IPv6 address as seen by an online web site. Return parsable output containing the IP address. Note: this detection mechanism requires ipv6 connectivity, otherwise it will simply not detect the IP address. """ configuration_key = "webcheck6" urls = ( ("https://ipv6.icanhazip.com/", "plain"), ("https://ipv6.nsupdate.info/myip", "plain"), ("https://v6.ident.me", "plain"), ) def __init__(self, *args, **kwargs): """Initialize.""" super(IPDetectorWebCheck6, self).__init__(*args, **kwargs) <|code_end|> using the current file's imports: import logging import re import requests import json from random import choice from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC from ..common.six import ipaddress from ..common import constants and any relevant context from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
self.opts_family = AF_INET6
Based on the snippet: <|code_start|> Returns parsable output containing the IP address. Note: this detection mechanism works with both ipv4 as well as ipv6 connectivity, however it should be noted that most dns resolvers implement negative caching: Alternating a DNS hostname between A and AAAA records is less efficient than staying within the same RR-Type. This is due to the fact that most libc-implementations do both lookups when getaddrinf() is called and therefore negative caching occurs (e.g. caching that a record does not exist). This also means that alternating only works well if the zone's SOA record has a minimum TTL close to the record TTL, which in turn means that using alternation should only be done in a dedicated (sub)domain with its own SOA record and a low TTL. """ configuration_key = "webcheck46" urls = ( ("https://icanhazip.com/", "plain"), ("https://www.nsupdate.info/myip", "plain"), ("https://ident.me", "plain"), ) def __init__(self, *args, **kwargs): """Initialize.""" super(IPDetectorWebCheck46, self).__init__(*args, **kwargs) <|code_end|> , predict the immediate next line with the help of imports: import logging import re import requests import json from random import choice from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC from ..common.six import ipaddress from ..common import constants and context (classes, functions, sometimes code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
self.opts_family = AF_UNSPEC
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- """Module containing logic for webcheck based detectors.""" LOG = logging.getLogger(__name__) def _get_ip_from_url(url, parser, timeout=10): LOG.debug("Querying IP address from '%s'", url) try: req = requests.get(url, headers=constants.REQUEST_HEADERS_DEFAULT, timeout=timeout) except requests.exceptions.RequestException as exc: LOG.debug("webcheck failed for url '%s'", url, exc_info=exc) return None else: if req.status_code == 200: return parser(req.text) else: LOG.debug("Wrong http status code for '%s': %i", url, req.status_code) return None def _parser_plain(text): try: <|code_end|> . Use current file imports: import logging import re import requests import json from random import choice from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC from ..common.six import ipaddress from ..common import constants and context (classes, functions, or code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
return str(ipaddress(text.strip()))
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """Module containing logic for webcheck based detectors.""" LOG = logging.getLogger(__name__) def _get_ip_from_url(url, parser, timeout=10): LOG.debug("Querying IP address from '%s'", url) try: <|code_end|> , determine the next line of code. You have imports: import logging import re import requests import json from random import choice from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC from ..common.six import ipaddress from ..common import constants and context (class names, function names, or code) available: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
req = requests.get(url, headers=constants.REQUEST_HEADERS_DEFAULT, timeout=timeout)
Next line prediction: <|code_start|> HAVE_IPV6 = True try: socket.socket(socket.AF_INET6, socket.SOCK_DGRAM).connect(("ipv6.google.com", 0)) except (OSError, socket.gaierror): HAVE_IPV6 = False class TestIndividualDetectors(unittest.TestCase): """Test cases for detectors.""" def test_dnswanip_detector_class(self): """Run basic tests for IPDetector_DnsWanIp.""" self.assertEqual("dnswanip", IPDetector_DnsWanIp.configuration_key) detector = IPDetector_DnsWanIp() self.assertFalse(detector.can_detect_offline()) self.assertEqual(None, detector.get_current_value()) # default family should be ipv4: detector = IPDetector_DnsWanIp(family=None) self.assertEqual(AF_INET, detector.af()) detector = IPDetector_DnsWanIp(family=AF_INET) self.assertEqual(AF_INET, detector.af()) detector = IPDetector_DnsWanIp(family=AF_INET6) self.assertEqual(AF_INET6, detector.af()) def test_dnswanip_detector_ipv4(self): """Run ipv4 tests for IPDetector_DnsWanIp.""" detector = IPDetector_DnsWanIp(family=AF_INET) result = detector.detect() <|code_end|> . Use current file imports: (import unittest import pytest import socket from dyndnsc.common.six import string_types from dyndnsc.common.six import ipaddress from dyndnsc.detector.base import AF_INET, AF_INET6 from dyndnsc.detector.dnswanip import IPDetector_DnsWanIp) and context including class names, function names, or small code snippets from other files: # Path: dyndnsc/common/six.py # def ipaddress(addr): # def ipnetwork(addr): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/detector/dnswanip.py # class IPDetector_DnsWanIp(IPDetector): # """Detect the internet visible IP address using publicly available DNS infrastructure.""" # # configuration_key = "dnswanip" # # def __init__(self, family=None, *args, **kwargs): # """ # Initialize. # # :param family: IP address family (default: '' (ANY), also possible: 'INET', 'INET6') # """ # if family is None: # family = AF_INET # super(IPDetector_DnsWanIp, self).__init__(*args, family=family, **kwargs) # # def can_detect_offline(self): # """Return false, as this detector generates dns traffic. # # :return: False # """ # return False # # def detect(self): # """ # Detect the WAN IP of the current process through DNS. # # Depending on the 'family' option, either ipv4 or ipv6 resolution is # carried out. # # :return: ip address # """ # theip = find_ip(family=self.opts_family) # self.set_current_value(theip) # return theip . Output only the next line.
self.assertTrue(isinstance(result, (type(None),) + string_types), type(result))
Predict the next line after this snippet: <|code_start|>HAVE_IPV6 = True try: socket.socket(socket.AF_INET6, socket.SOCK_DGRAM).connect(("ipv6.google.com", 0)) except (OSError, socket.gaierror): HAVE_IPV6 = False class TestIndividualDetectors(unittest.TestCase): """Test cases for detectors.""" def test_dnswanip_detector_class(self): """Run basic tests for IPDetector_DnsWanIp.""" self.assertEqual("dnswanip", IPDetector_DnsWanIp.configuration_key) detector = IPDetector_DnsWanIp() self.assertFalse(detector.can_detect_offline()) self.assertEqual(None, detector.get_current_value()) # default family should be ipv4: detector = IPDetector_DnsWanIp(family=None) self.assertEqual(AF_INET, detector.af()) detector = IPDetector_DnsWanIp(family=AF_INET) self.assertEqual(AF_INET, detector.af()) detector = IPDetector_DnsWanIp(family=AF_INET6) self.assertEqual(AF_INET6, detector.af()) def test_dnswanip_detector_ipv4(self): """Run ipv4 tests for IPDetector_DnsWanIp.""" detector = IPDetector_DnsWanIp(family=AF_INET) result = detector.detect() self.assertTrue(isinstance(result, (type(None),) + string_types), type(result)) # ensure the result is in fact an IP address: <|code_end|> using the current file's imports: import unittest import pytest import socket from dyndnsc.common.six import string_types from dyndnsc.common.six import ipaddress from dyndnsc.detector.base import AF_INET, AF_INET6 from dyndnsc.detector.dnswanip import IPDetector_DnsWanIp and any relevant context from other files: # Path: dyndnsc/common/six.py # def ipaddress(addr): # def ipnetwork(addr): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/detector/dnswanip.py # class IPDetector_DnsWanIp(IPDetector): # """Detect the internet visible IP address using publicly available DNS infrastructure.""" # # configuration_key = "dnswanip" # # def __init__(self, family=None, *args, **kwargs): # """ # Initialize. # # :param family: IP address family (default: '' (ANY), also possible: 'INET', 'INET6') # """ # if family is None: # family = AF_INET # super(IPDetector_DnsWanIp, self).__init__(*args, family=family, **kwargs) # # def can_detect_offline(self): # """Return false, as this detector generates dns traffic. # # :return: False # """ # return False # # def detect(self): # """ # Detect the WAN IP of the current process through DNS. # # Depending on the 'family' option, either ipv4 or ipv6 resolution is # carried out. # # :return: ip address # """ # theip = find_ip(family=self.opts_family) # self.set_current_value(theip) # return theip . Output only the next line.
self.assertNotEqual(ipaddress(result), None)
Given snippet: <|code_start|># -*- coding: utf-8 -*- """Tests for detectors.""" HAVE_IPV6 = True try: socket.socket(socket.AF_INET6, socket.SOCK_DGRAM).connect(("ipv6.google.com", 0)) except (OSError, socket.gaierror): HAVE_IPV6 = False class TestIndividualDetectors(unittest.TestCase): """Test cases for detectors.""" def test_dnswanip_detector_class(self): """Run basic tests for IPDetector_DnsWanIp.""" self.assertEqual("dnswanip", IPDetector_DnsWanIp.configuration_key) detector = IPDetector_DnsWanIp() self.assertFalse(detector.can_detect_offline()) self.assertEqual(None, detector.get_current_value()) # default family should be ipv4: detector = IPDetector_DnsWanIp(family=None) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import pytest import socket from dyndnsc.common.six import string_types from dyndnsc.common.six import ipaddress from dyndnsc.detector.base import AF_INET, AF_INET6 from dyndnsc.detector.dnswanip import IPDetector_DnsWanIp and context: # Path: dyndnsc/common/six.py # def ipaddress(addr): # def ipnetwork(addr): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/detector/dnswanip.py # class IPDetector_DnsWanIp(IPDetector): # """Detect the internet visible IP address using publicly available DNS infrastructure.""" # # configuration_key = "dnswanip" # # def __init__(self, family=None, *args, **kwargs): # """ # Initialize. # # :param family: IP address family (default: '' (ANY), also possible: 'INET', 'INET6') # """ # if family is None: # family = AF_INET # super(IPDetector_DnsWanIp, self).__init__(*args, family=family, **kwargs) # # def can_detect_offline(self): # """Return false, as this detector generates dns traffic. # # :return: False # """ # return False # # def detect(self): # """ # Detect the WAN IP of the current process through DNS. # # Depending on the 'family' option, either ipv4 or ipv6 resolution is # carried out. # # :return: ip address # """ # theip = find_ip(family=self.opts_family) # self.set_current_value(theip) # return theip which might include code, classes, or functions. Output only the next line.
self.assertEqual(AF_INET, detector.af())
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """Tests for detectors.""" HAVE_IPV6 = True try: socket.socket(socket.AF_INET6, socket.SOCK_DGRAM).connect(("ipv6.google.com", 0)) except (OSError, socket.gaierror): HAVE_IPV6 = False class TestIndividualDetectors(unittest.TestCase): """Test cases for detectors.""" def test_dnswanip_detector_class(self): """Run basic tests for IPDetector_DnsWanIp.""" <|code_end|> , predict the immediate next line with the help of imports: import unittest import pytest import socket from dyndnsc.common.six import string_types from dyndnsc.common.six import ipaddress from dyndnsc.detector.base import AF_INET, AF_INET6 from dyndnsc.detector.dnswanip import IPDetector_DnsWanIp and context (classes, functions, sometimes code) from other files: # Path: dyndnsc/common/six.py # def ipaddress(addr): # def ipnetwork(addr): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/detector/dnswanip.py # class IPDetector_DnsWanIp(IPDetector): # """Detect the internet visible IP address using publicly available DNS infrastructure.""" # # configuration_key = "dnswanip" # # def __init__(self, family=None, *args, **kwargs): # """ # Initialize. # # :param family: IP address family (default: '' (ANY), also possible: 'INET', 'INET6') # """ # if family is None: # family = AF_INET # super(IPDetector_DnsWanIp, self).__init__(*args, family=family, **kwargs) # # def can_detect_offline(self): # """Return false, as this detector generates dns traffic. # # :return: False # """ # return False # # def detect(self): # """ # Detect the WAN IP of the current process through DNS. # # Depending on the 'family' option, either ipv4 or ipv6 resolution is # carried out. # # :return: ip address # """ # theip = find_ip(family=self.opts_family) # self.set_current_value(theip) # return theip . Output only the next line.
self.assertEqual("dnswanip", IPDetector_DnsWanIp.configuration_key)
Given snippet: <|code_start|># -*- coding: utf-8 -*- """Tests for the cli.""" class TestCli(unittest.TestCase): """Test cases for Cli.""" def test_create_argparser(self): """Run tests for create_argparser().""" parser, arg_defaults = cli.create_argparser() self.assertTrue(isinstance(parser, argparse.ArgumentParser)) self.assertTrue(isinstance(arg_defaults, dict)) def test_list_presets(self): """Run tests for list_presets().""" sample_config = """[preset:testpreset] updater = fubarUpdater updater-url = https://update.example.com/nic/update updater-moreparam = some_stuff detector = webcheck4 detector-family = INET detector-url = http://ip.example.com/ detector-parser = plain""" parser = configparser.ConfigParser() <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import argparse import os import configparser from dyndnsc.common.six import StringIO from dyndnsc import cli and context: # Path: dyndnsc/common/six.py # def ipaddress(addr): # def ipnetwork(addr): # # Path: dyndnsc/cli.py # def list_presets(cfg, out): # def create_argparser(): # def run_forever(dyndnsclients): # def init_logging(log_level, log_json=False): # def main(): # LOG = logging.getLogger() which might include code, classes, or functions. Output only the next line.
parser.read_file(StringIO(sample_config))
Predict the next line after this snippet: <|code_start|>class SampleListener(object): """An example listener that records all notifications.""" def __init__(self): """Initialize with an empty list of messages.""" self.messages = [] def notify(self, sender, event, msg): """Do nothing but remember the notification.""" self.messages.append((sender, event, msg)) class InvalidListener(object): """An invalid listener.""" def notify(self, dummy): """Do nothing.""" pass class TestSubjectObserver(unittest.TestCase): """Test cases for Subject.""" def setUp(self): """Disable logging to not confuse the person watching the unit test output.""" logging.disable(logging.CRITICAL) unittest.TestCase.setUp(self) def test_observer(self): """Run observer tests.""" <|code_end|> using the current file's imports: import unittest import logging from dyndnsc.common.subject import Subject and any relevant context from other files: # Path: dyndnsc/common/subject.py # class Subject(object): # """Dispatches messages to registered callables.""" # # def __init__(self): # """Initialize.""" # self._observers = {} # # def register_observer(self, observer, events=None): # """Register a listener function. # # :param observer: external listener function # :param events: tuple or list of relevant events (default=None) # """ # if events is not None and not isinstance(events, (tuple, list)): # events = (events,) # # if observer in self._observers: # LOG.warning("Observer '%r' already registered, overwriting for events" # " %r", observer, events) # self._observers[observer] = events # # def notify_observers(self, event=None, msg=None): # """Notify observers.""" # for observer, events in list(self._observers.items()): # # LOG.debug("trying to notify the observer") # if events is None or event is None or event in events: # try: # observer(self, event, msg) # except Exception as ex: # pylint: disable=broad-except # self.unregister_observer(observer) # errmsg = "Exception in message dispatch: Handler '{0}' unregistered for event '{1}' ".format( # observer.__class__.__name__, event) # LOG.error(errmsg, exc_info=ex) # # def unregister_observer(self, observer): # """Unregister observer callable.""" # del self._observers[observer] . Output only the next line.
subject = Subject()
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """Module containing logic for teredo based detectors.""" LOG = logging.getLogger(__name__) class IPDetector_Teredo(IPDetector_Iface): """IPDetector to detect a Teredo ipv6 address of a local interface. Bits 0 to 31 of the ipv6 address are set to the Teredo prefix (normally 2001:0000::/32). This detector only checks the first 16 bits! See http://en.wikipedia.org/wiki/Teredo_tunneling for more information on Teredo. Inherits IPDetector_Iface and sets default options only. """ configuration_key = "teredo" def __init__(self, iface="tun0", netmask="2001:0000::/32", *args, **kwargs): """Initialize.""" super(IPDetector_Teredo, self).__init__(*args, **kwargs) self.opts_iface = iface self.opts_netmask = netmask <|code_end|> . Use current file imports: (import logging from .iface import IPDetector_Iface, AF_INET6) and context including class names, function names, or small code snippets from other files: # Path: dyndnsc/detector/iface.py # LOG = logging.getLogger(__name__) # def _default_interface(): # def __init__(self, iface=None, netmask=None, family=None, *args, **kwargs): # def can_detect_offline(self): # def _detect(self): # def detect(self): # class IPDetector_Iface(IPDetector): . Output only the next line.
self.opts_family = AF_INET6
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Updater for https://dnsimple.com/ compatible dyndns services. This module depends on the python package dnsimple-dyndns from https://pypi.python.org/pypi/dnsimple-dyndns If installed, dyndnsc will be able to utilize it. Since dnsimple.com is a paid service, I have not had a chance to test this yet. """ LOG = logging.getLogger(__name__) <|code_end|> . Use current file imports: import logging from dnsimple_dyndns import DNSimple # @UnresolvedImport pylint: disable=import-error from .base import UpdateProtocol and context (classes, functions, or code) from other files: # Path: dyndnsc/updater/base.py # class UpdateProtocol(Subject, DynamicCliMixin): # """Base class for all update protocols that use a simple http GET protocol.""" # # theip = None # __hostname = None # private place to store the property 'hostname' # configuration_key = None # # @property # def hostname(self): # """ # Return the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # return self.__hostname # # @hostname.setter # def hostname(self, value): # """ # Set the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # self.__hostname = value # # @staticmethod # def configuration_key_prefix(): # """ # Return a human readable string classifying this class as an updater. # # Should not be be implemented or overwritten in updater subclasses. # """ # return "updater" # # def update(self, ip): # """ # Update the hostname on the remote service. # # Abstract method, must be implemented in subclass. # """ # raise NotImplementedError("Please implement in subclass") . Output only the next line.
class UpdateProtocolDnsimple(UpdateProtocol):
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Dynamic loading of built-in plugins. All built-in plugins are listed here and will be dynamically imported on importing this module. If importing a plugin fails, it will be ignored. """ _BUILTINS = () <|code_end|> . Use current file imports: from ..common.load import load_class as _load_plugin and context (classes, functions, or code) from other files: # Path: dyndnsc/common/load.py # def load_class(module_name, class_name): # """Return class object specified by module name and class name. # # Return None if module failed to be imported. # # :param module_name: string module name # :param class_name: string class name # """ # try: # plugmod = import_module(module_name) # except Exception as exc: # warn("Importing built-in plugin %s.%s raised an exception: %r" % # (module_name, class_name, repr(exc)), ImportWarning) # return None # else: # return getattr(plugmod, class_name) . Output only the next line.
PLUGINS = {plug for plug in (_load_plugin(m, c) for m, c in _BUILTINS) if plug is not None}
Given the code snippet: <|code_start|> LOG = getLogger(__name__) class UpdateProtocolDyndns2(UpdateProtocol): """Updater for services compatible with the dyndns2 protocol.""" configuration_key = "dyndns2" def __init__(self, hostname, userid, password, url, *args, **kwargs): """ Initialize. :param hostname: the fully qualified hostname to be managed :param userid: the userid for identification :param password: the password for authentication :param url: the API URL for updating the DNS entry """ self.hostname = hostname self.__userid = userid self.__password = password self._updateurl = url super(UpdateProtocolDyndns2, self).__init__() def update(self, ip): """Update the IP on the remote service.""" timeout = 60 LOG.debug("Updating '%s' to '%s' at service '%s'", self.hostname, ip, self._updateurl) params = {"myip": ip, "hostname": self.hostname} <|code_end|> , generate the next line using the imports in this file: from logging import getLogger from .base import UpdateProtocol from ..common import constants import requests and context (functions, classes, or occasionally code) from other files: # Path: dyndnsc/updater/base.py # class UpdateProtocol(Subject, DynamicCliMixin): # """Base class for all update protocols that use a simple http GET protocol.""" # # theip = None # __hostname = None # private place to store the property 'hostname' # configuration_key = None # # @property # def hostname(self): # """ # Return the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # return self.__hostname # # @hostname.setter # def hostname(self, value): # """ # Set the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # self.__hostname = value # # @staticmethod # def configuration_key_prefix(): # """ # Return a human readable string classifying this class as an updater. # # Should not be be implemented or overwritten in updater subclasses. # """ # return "updater" # # def update(self, ip): # """ # Update the hostname on the remote service. # # Abstract method, must be implemented in subclass. # """ # raise NotImplementedError("Please implement in subclass") # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
req = requests.get(self._updateurl, params=params, headers=constants.REQUEST_HEADERS_DEFAULT,
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """ All built-in updater plugins are listed here and will be dynamically imported. If importing a plugin fails, it will be silently ignored. """ _BUILTINS = ( ("dyndnsc.updater.afraid", "UpdateProtocolAfraid"), ("dyndnsc.updater.dummy", "UpdateProtocolDummy"), ("dyndnsc.updater.duckdns", "UpdateProtocolDuckdns"), ("dyndnsc.updater.dyndns2", "UpdateProtocolDyndns2"), ("dyndnsc.updater.dnsimple", "UpdateProtocolDnsimple"), ) <|code_end|> . Use current file imports: (from ..common.load import load_class as _load_plugin) and context including class names, function names, or small code snippets from other files: # Path: dyndnsc/common/load.py # def load_class(module_name, class_name): # """Return class object specified by module name and class name. # # Return None if module failed to be imported. # # :param module_name: string module name # :param class_name: string class name # """ # try: # plugmod = import_module(module_name) # except Exception as exc: # warn("Importing built-in plugin %s.%s raised an exception: %r" % # (module_name, class_name, repr(exc)), ImportWarning) # return None # else: # return getattr(plugmod, class_name) . Output only the next line.
PLUGINS = {plug for plug in (_load_plugin(m, c) for m, c in _BUILTINS) if plug is not None}
Given the following code snippet before the placeholder: <|code_start|> raise ValueError("args must not be None") parsed_args = {} for kls in classes: prefix = kls.configuration_key_prefix() name = kls.configuration_key if getattr(args, "%s_%s" % (prefix, name), False): logging.debug( "Gathering initargs for '%s.%s'", prefix, name) initargs = {} for arg_name in kls.init_argnames(): val = getattr(args, "%s_%s_%s" % (prefix, name, arg_name)) if val is not None: initargs[arg_name] = val if prefix not in parsed_args: parsed_args[prefix] = [] parsed_args[prefix].append((name, initargs)) return parsed_args class DynamicCliMixin(object): """Base class providing functionality to register and handle CLI args.""" @classmethod def init_argnames(cls): """ Inspect the __init__ arguments of the given cls. :param cls: a class with an __init__ method """ <|code_end|> , predict the next line using imports from the current file: import logging import textwrap from .six import getargspec and context including class names, function names, and sometimes code from other files: # Path: dyndnsc/common/six.py # def ipaddress(addr): # def ipnetwork(addr): . Output only the next line.
return getargspec(cls.__init__).args[1:]
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """Tests for the dynamiccli module.""" class Dummy(DynamicCliMixin): """A dummy class used to verify parse_cmdline_args() behaviour.""" configuration_key = "dummy" def __init__(self, userid, password): """Initialize. Do nothing.""" @staticmethod def configuration_key_prefix(): """Return 'foo', identifying the protocol prefix.""" return "foo" class TestDynamicCli(unittest.TestCase): """Test cases for dynamiccli.""" def test_parse_cmdline_updater_args(self): """Run tests for parse_cmdline_args().""" <|code_end|> , generate the next line using the imports in this file: import unittest from dyndnsc.common.dynamiccli import parse_cmdline_args, DynamicCliMixin from argparse import Namespace and context (functions, classes, or occasionally code) from other files: # Path: dyndnsc/common/dynamiccli.py # def parse_cmdline_args(args, classes): # """ # Parse all updater and detector related arguments from args. # # Returns a list of ("name", { "k": "v"}) # # :param args: argparse arguments # """ # if args is None: # raise ValueError("args must not be None") # parsed_args = {} # for kls in classes: # prefix = kls.configuration_key_prefix() # name = kls.configuration_key # if getattr(args, "%s_%s" % (prefix, name), False): # logging.debug( # "Gathering initargs for '%s.%s'", prefix, name) # initargs = {} # for arg_name in kls.init_argnames(): # val = getattr(args, "%s_%s_%s" % # (prefix, name, arg_name)) # if val is not None: # initargs[arg_name] = val # if prefix not in parsed_args: # parsed_args[prefix] = [] # parsed_args[prefix].append((name, initargs)) # return parsed_args # # class DynamicCliMixin(object): # """Base class providing functionality to register and handle CLI args.""" # # @classmethod # def init_argnames(cls): # """ # Inspect the __init__ arguments of the given cls. # # :param cls: a class with an __init__ method # """ # return getargspec(cls.__init__).args[1:] # # @classmethod # def _init_argdefaults(cls): # defaults = getargspec(cls.__init__).defaults # if defaults is None: # defaults = () # return defaults # # @classmethod # def register_arguments(cls, parser): # """Register command line options. # # Implement this method for normal options behavior with protection from # OptionConflictErrors. If you override this method and want the default # --$name option(s) to be registered, be sure to call super(). # """ # if hasattr(cls, "_dont_register_arguments"): # return # prefix = cls.configuration_key_prefix() # cfgkey = cls.configuration_key # parser.add_argument("--%s-%s" % (prefix, cfgkey), # action="store_true", # dest="%s_%s" % (prefix, cfgkey), # default=False, # help="%s: %s" % # (cls.__name__, cls.help())) # args = cls.init_argnames() # defaults = cls._init_argdefaults() # for arg in args[0:len(args) - len(defaults)]: # parser.add_argument("--%s-%s-%s" % (prefix, cfgkey, arg), # dest="%s_%s_%s" % (prefix, cfgkey, arg), # help="") # for i, arg in enumerate(args[len(args) - len(defaults):]): # parser.add_argument("--%s-%s-%s" % (prefix, cfgkey, arg), # dest="%s_%s_%s" % (prefix, cfgkey, arg), # default=defaults[i], # help="default: %(default)s") # # @classmethod # def help(cls): # """ # Return help for this. # # This will be output as the help section of the --$name option that # enables this plugin. # """ # if cls.__doc__: # # remove doc section indentation # return textwrap.dedent(cls.__doc__) # return "(no help available)" # # @staticmethod # def configuration_key_prefix(): # """ # Return string prefix for configuration key. # # Abstract method, must be implemented in subclass. # """ # raise NotImplementedError("Please implement in subclass") . Output only the next line.
self.assertRaises(TypeError, parse_cmdline_args, None)
Given snippet: <|code_start|># -*- coding: utf-8 -*- """Module for plugin manager.""" ENV_PREFIX = "DYNDNSC_WITH_" LOG = logging.getLogger(__name__) class PluginProxy(object): """Proxy for plugin calls. To verify presence of methods, this proxy is bound to an interface class providing no implementation. """ <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import textwrap import pkg_resources # noqa: @UnusedImport pylint: disable=unused-import from warnings import warn from .base import IPluginInterface from pkg_resources import iter_entry_points from dyndnsc.plugins.builtin import PLUGINS and context: # Path: dyndnsc/plugins/base.py # class IPluginInterface(object): # """IPluginInterface describes the plugin API. # # Do not subclass or use this class directly. # """ # # def __new__(cls, *arg, **kw): # """Private constructor.""" # raise TypeError("IPluginInterface class cannot be instantiated, it " # "is for documentation and API verification only") # # def options(self, parser, env): # """Register command line options with the argparse parser. # # DO NOT return a value from this method unless you want to stop # all other plugins from setting their options. # # :param parser: options parser instance # :type parser: `argparse.ArgumentParser` # :param env: environment, default is os.environ # """ # pass # # def configure(self, options): # """Call after any user input has been parsed, with the options. # # DO NOT return a value from this method unless you want to # stop all other plugins from being configured. # """ # pass # # def initialize(self): # """Call before any core activities are run. # # Use this to perform any plugin specific setup. # """ # pass # # def after_remote_ip_update(self, ip, status): # """Call after a remote IP update was performed.""" which might include code, classes, or functions. Output only the next line.
interface = IPluginInterface
Predict the next line for this snippet: <|code_start|> req = requests.get( url, params=params, headers=constants.REQUEST_HEADERS_DEFAULT, timeout=60) for record_line in (line.strip() for line in req.text.splitlines() if len(line.strip()) > 0): yield AfraidDynDNSRecord(*record_line.split("|")) def update(url): """ Update remote DNS record by requesting its special endpoint URL. This automatically picks the IP address using the HTTP connection: it is not possible to specify the IP address explicitly. :param url: URL to retrieve for triggering the update :return: IP address """ req = requests.get( url, headers=constants.REQUEST_HEADERS_DEFAULT, timeout=60) req.close() # Response must contain an IP address, or else we can't parse it. # Also, the IP address in the response is the newly assigned IP address. ipregex = re.compile(r"\b(?P<ip>(?:[0-9]{1,3}\.){3}[0-9]{1,3})\b") ipmatch = ipregex.search(req.text) if ipmatch: return str(ipaddress(ipmatch.group("ip"))) LOG.error("couldn't parse the server's response '%s'", req.text) return None <|code_end|> with the help of current file imports: import logging import hashlib import re import requests import sys from collections import namedtuple from .base import UpdateProtocol from ..common.six import ipaddress from ..common import constants and context from other files: # Path: dyndnsc/updater/base.py # class UpdateProtocol(Subject, DynamicCliMixin): # """Base class for all update protocols that use a simple http GET protocol.""" # # theip = None # __hostname = None # private place to store the property 'hostname' # configuration_key = None # # @property # def hostname(self): # """ # Return the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # return self.__hostname # # @hostname.setter # def hostname(self, value): # """ # Set the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # self.__hostname = value # # @staticmethod # def configuration_key_prefix(): # """ # Return a human readable string classifying this class as an updater. # # Should not be be implemented or overwritten in updater subclasses. # """ # return "updater" # # def update(self, ip): # """ # Update the hostname on the remote service. # # Abstract method, must be implemented in subclass. # """ # raise NotImplementedError("Please implement in subclass") # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } , which may contain function names, class names, or code. Output only the next line.
class UpdateProtocolAfraid(UpdateProtocol):
Using the snippet: <|code_start|> :param credentials: an AfraidCredentials instance :param url: the service URL """ params = {"action": "getdyndns", "sha": credentials.sha} req = requests.get( url, params=params, headers=constants.REQUEST_HEADERS_DEFAULT, timeout=60) for record_line in (line.strip() for line in req.text.splitlines() if len(line.strip()) > 0): yield AfraidDynDNSRecord(*record_line.split("|")) def update(url): """ Update remote DNS record by requesting its special endpoint URL. This automatically picks the IP address using the HTTP connection: it is not possible to specify the IP address explicitly. :param url: URL to retrieve for triggering the update :return: IP address """ req = requests.get( url, headers=constants.REQUEST_HEADERS_DEFAULT, timeout=60) req.close() # Response must contain an IP address, or else we can't parse it. # Also, the IP address in the response is the newly assigned IP address. ipregex = re.compile(r"\b(?P<ip>(?:[0-9]{1,3}\.){3}[0-9]{1,3})\b") ipmatch = ipregex.search(req.text) if ipmatch: <|code_end|> , determine the next line of code. You have imports: import logging import hashlib import re import requests import sys from collections import namedtuple from .base import UpdateProtocol from ..common.six import ipaddress from ..common import constants and context (class names, function names, or code) available: # Path: dyndnsc/updater/base.py # class UpdateProtocol(Subject, DynamicCliMixin): # """Base class for all update protocols that use a simple http GET protocol.""" # # theip = None # __hostname = None # private place to store the property 'hostname' # configuration_key = None # # @property # def hostname(self): # """ # Return the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # return self.__hostname # # @hostname.setter # def hostname(self, value): # """ # Set the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # self.__hostname = value # # @staticmethod # def configuration_key_prefix(): # """ # Return a human readable string classifying this class as an updater. # # Should not be be implemented or overwritten in updater subclasses. # """ # return "updater" # # def update(self, ip): # """ # Update the hostname on the remote service. # # Abstract method, must be implemented in subclass. # """ # raise NotImplementedError("Please implement in subclass") # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
return str(ipaddress(ipmatch.group("ip")))
Predict the next line after this snippet: <|code_start|> if self._sha is None: self._sha = compute_auth_key(self.userid, self.password) return self._sha def compute_auth_key(userid, password): """ Compute the authentication key for freedns.afraid.org. This is the SHA1 hash of the string b'userid|password'. :param userid: ascii username :param password: ascii password :return: ascii authentication key (SHA1 at this point) """ if sys.version_info >= (3, 0): return hashlib.sha1(b"|".join((userid.encode("ascii"), # noqa: S303 password.encode("ascii")))).hexdigest() return hashlib.sha1("|".join((userid, password))).hexdigest() # noqa: S303 def records(credentials, url="https://freedns.afraid.org/api/"): """ Yield the dynamic DNS records associated with this account. :param credentials: an AfraidCredentials instance :param url: the service URL """ params = {"action": "getdyndns", "sha": credentials.sha} req = requests.get( <|code_end|> using the current file's imports: import logging import hashlib import re import requests import sys from collections import namedtuple from .base import UpdateProtocol from ..common.six import ipaddress from ..common import constants and any relevant context from other files: # Path: dyndnsc/updater/base.py # class UpdateProtocol(Subject, DynamicCliMixin): # """Base class for all update protocols that use a simple http GET protocol.""" # # theip = None # __hostname = None # private place to store the property 'hostname' # configuration_key = None # # @property # def hostname(self): # """ # Return the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # return self.__hostname # # @hostname.setter # def hostname(self, value): # """ # Set the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # self.__hostname = value # # @staticmethod # def configuration_key_prefix(): # """ # Return a human readable string classifying this class as an updater. # # Should not be be implemented or overwritten in updater subclasses. # """ # return "updater" # # def update(self, ip): # """ # Update the hostname on the remote service. # # Abstract method, must be implemented in subclass. # """ # raise NotImplementedError("Please implement in subclass") # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
url, params=params, headers=constants.REQUEST_HEADERS_DEFAULT, timeout=60)
Using the snippet: <|code_start|> HAVE_IPV6 = True try: socket.socket(socket.AF_INET6, socket.SOCK_DGRAM).connect(("ipv6.google.com", 0)) except (OSError, socket.gaierror): HAVE_IPV6 = False class TestPluginDetectors(unittest.TestCase): """Test cases for detector discovery and management.""" def test_detector_builtin(self): """Test that we have at least one builtin detector class.""" self.assertTrue(len(dyndnsc.detector.builtin.PLUGINS) > 0) def test_detector_interfaces(self): """Test that each builtin detector class has certain apis.""" self.assertTrue(len(dyndnsc.detector.manager.detector_classes()) > 0) for cls in dyndnsc.detector.manager.detector_classes(): self.assertTrue(hasattr(cls, "configuration_key")) self.assertTrue(hasattr(cls, "af")) self.assertRaises(ValueError, dyndnsc.detector.manager.get_detector_class, "nonexistent") class TestIndividualDetectors(unittest.TestCase): """Test cases for detectors.""" def test_dns_resolve(self): """Run tests for DNS resolution.""" self.assertTrue(len(ns.resolve("localhost")) > 0) <|code_end|> , determine the next line of code. You have imports: import unittest import socket import dyndnsc.detector.builtin import dyndnsc.detector.manager import dyndnsc.detector.dns as ns import dyndnsc.detector.base import dyndnsc.detector.dns as ns import dyndnsc.detector.command import dyndnsc.detector.rand import dyndnsc.detector.rand from dyndnsc.detector.base import AF_INET, AF_INET6, AF_UNSPEC from dyndnsc.detector import socket_ip from dyndnsc.detector import webcheck from dyndnsc.detector import webcheck from dyndnsc.detector import webcheck from dyndnsc.detector import webcheck from dyndnsc.detector import null and context (class names, function names, or code) available: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): . Output only the next line.
self.assertTrue(len(ns.resolve("localhost", family=ns.AF_INET)) > 0)
Here is a snippet: <|code_start|> ip2 = "127.0.0.2" detector = dyndnsc.detector.base.IPDetector() self.assertEqual(None, detector.get_current_value()) self.assertEqual(None, detector.get_old_value()) self.assertFalse(detector.has_changed()) # set to ip1 self.assertEqual(ip1, detector.set_current_value(ip1)) self.assertTrue(detector.has_changed()) self.assertEqual(ip1, detector.get_current_value()) self.assertEqual(None, detector.get_old_value()) # set to ip2 self.assertEqual(ip2, detector.set_current_value(ip2)) self.assertEqual(ip2, detector.get_current_value()) self.assertEqual(ip1, detector.get_old_value()) self.assertTrue(detector.has_changed()) # set again to ip2 self.assertEqual(ip2, detector.set_current_value(ip2)) self.assertFalse(detector.has_changed()) self.assertEqual(ip2, detector.get_current_value()) self.assertEqual(ip2, detector.get_old_value()) def test_dns_detector(self): """Run tests for IPDetector_DNS.""" self.assertEqual("dns", ns.IPDetector_DNS.configuration_key) detector = ns.IPDetector_DNS(hostname="localhost") self.assertFalse(detector.can_detect_offline()) <|code_end|> . Write the next line using the current file imports: import unittest import socket import dyndnsc.detector.builtin import dyndnsc.detector.manager import dyndnsc.detector.dns as ns import dyndnsc.detector.base import dyndnsc.detector.dns as ns import dyndnsc.detector.command import dyndnsc.detector.rand import dyndnsc.detector.rand from dyndnsc.detector.base import AF_INET, AF_INET6, AF_UNSPEC from dyndnsc.detector import socket_ip from dyndnsc.detector import webcheck from dyndnsc.detector import webcheck from dyndnsc.detector import webcheck from dyndnsc.detector import webcheck from dyndnsc.detector import null and context from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): , which may include functions, classes, or code. Output only the next line.
self.assertEqual(AF_UNSPEC, detector.af())
Predict the next line after this snippet: <|code_start|> def is_reserved_ip(self, ip): """Check if the given ip address is in a reserved ipv4 address space. :param ip: ip address :return: boolean """ theip = ipaddress(ip) for res in self._reserved_netmasks: if theip in ipnetwork(res): return True return False def random_public_ip(self): """Return a randomly generated, public IPv4 address. :return: ip address """ randomip = random_ip() while self.is_reserved_ip(randomip): randomip = random_ip() return randomip def __iter__(self): """Iterate over this instance..""" count = 0 while self._max is None or count < self._max: yield self.random_public_ip() count += 1 <|code_end|> using the current file's imports: import logging from random import randint from .base import IPDetector, AF_INET from ..common.six import ipaddress, ipnetwork and any relevant context from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # def ipnetwork(addr): # """Return an ipaddress.ip_network object from the given string IP.""" # return _ipaddress.ip_network(addr) . Output only the next line.
class IPDetector_Random(IPDetector):
Given the code snippet: <|code_start|> return True return False def random_public_ip(self): """Return a randomly generated, public IPv4 address. :return: ip address """ randomip = random_ip() while self.is_reserved_ip(randomip): randomip = random_ip() return randomip def __iter__(self): """Iterate over this instance..""" count = 0 while self._max is None or count < self._max: yield self.random_public_ip() count += 1 class IPDetector_Random(IPDetector): """Detect randomly generated IP addresses.""" configuration_key = "random" def __init__(self, *args, **kwargs): """Initialize.""" super(IPDetector_Random, self).__init__(*args, **kwargs) <|code_end|> , generate the next line using the imports in this file: import logging from random import randint from .base import IPDetector, AF_INET from ..common.six import ipaddress, ipnetwork and context (functions, classes, or occasionally code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # def ipnetwork(addr): # """Return an ipaddress.ip_network object from the given string IP.""" # return _ipaddress.ip_network(addr) . Output only the next line.
self.opts_family = AF_INET
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """Module containing logic for random IP based detectors.""" LOG = logging.getLogger(__name__) def random_ip(): """Return a randomly generated IPv4 address. :return: ip address """ <|code_end|> , generate the next line using the imports in this file: import logging from random import randint from .base import IPDetector, AF_INET from ..common.six import ipaddress, ipnetwork and context (functions, classes, or occasionally code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # def ipnetwork(addr): # """Return an ipaddress.ip_network object from the given string IP.""" # return _ipaddress.ip_network(addr) . Output only the next line.
return ipaddress(
Given snippet: <|code_start|> """Initialize.""" self._max = num # Reserved list from http://www.iana.org/assignments/ipv4-address-space # (dated 2010-02-22) self._reserved_netmasks = frozenset([ "0.0.0.0/8", "5.0.0.0/8", "10.0.0.0/8", "23.0.0.0/8", "31.0.0.0/8", "36.0.0.0/8", "39.0.0.0/8", "42.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "224.0.0.0/3", "240.0.0.0/8" ]) def is_reserved_ip(self, ip): """Check if the given ip address is in a reserved ipv4 address space. :param ip: ip address :return: boolean """ theip = ipaddress(ip) for res in self._reserved_netmasks: <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from random import randint from .base import IPDetector, AF_INET from ..common.six import ipaddress, ipnetwork and context: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): # # Path: dyndnsc/common/six.py # def ipaddress(addr): # """Return an ipaddress.ip_address object from the given string IP.""" # return _ipaddress.ip_address(addr) # # def ipnetwork(addr): # """Return an ipaddress.ip_network object from the given string IP.""" # return _ipaddress.ip_network(addr) which might include code, classes, or functions. Output only the next line.
if theip in ipnetwork(res):
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """Module containing the logic for updating DNS records using the duckdns protocol. From the duckdns.org website: https://{DOMAIN}/update?domains={DOMAINLIST}&token={TOKEN}&ip={IP} where: DOMAIN the service domain DOMAINLIST is either a single domain or a comma separated list of domains TOKEN is the API token for authentication/authorization IP is either the IP or blank for auto-detection """ LOG = getLogger(__name__) <|code_end|> , predict the immediate next line with the help of imports: from logging import getLogger from .base import UpdateProtocol from ..common import constants import requests and context (classes, functions, sometimes code) from other files: # Path: dyndnsc/updater/base.py # class UpdateProtocol(Subject, DynamicCliMixin): # """Base class for all update protocols that use a simple http GET protocol.""" # # theip = None # __hostname = None # private place to store the property 'hostname' # configuration_key = None # # @property # def hostname(self): # """ # Return the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # return self.__hostname # # @hostname.setter # def hostname(self, value): # """ # Set the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # self.__hostname = value # # @staticmethod # def configuration_key_prefix(): # """ # Return a human readable string classifying this class as an updater. # # Should not be be implemented or overwritten in updater subclasses. # """ # return "updater" # # def update(self, ip): # """ # Update the hostname on the remote service. # # Abstract method, must be implemented in subclass. # """ # raise NotImplementedError("Please implement in subclass") # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
class UpdateProtocolDuckdns(UpdateProtocol):
Given the following code snippet before the placeholder: <|code_start|> class UpdateProtocolDuckdns(UpdateProtocol): """Updater for services compatible with the duckdns protocol.""" configuration_key = "duckdns" def __init__(self, hostname, token, url, *args, **kwargs): """ Initialize. :param hostname: the fully qualified hostname to be managed :param token: the token for authentication :param url: the API URL for updating the DNS entry """ self.hostname = hostname self.__token = token self._updateurl = url super(UpdateProtocolDuckdns, self).__init__() def update(self, ip): """Update the IP on the remote service.""" timeout = 60 LOG.debug("Updating '%s' to '%s' at service '%s'", self.hostname, ip, self._updateurl) params = {"domains": self.hostname.partition(".")[0], "token": self.__token} if ip is None: params["ip"] = "" else: params["ip"] = ip # LOG.debug("Update params: %r", params) <|code_end|> , predict the next line using imports from the current file: from logging import getLogger from .base import UpdateProtocol from ..common import constants import requests and context including class names, function names, and sometimes code from other files: # Path: dyndnsc/updater/base.py # class UpdateProtocol(Subject, DynamicCliMixin): # """Base class for all update protocols that use a simple http GET protocol.""" # # theip = None # __hostname = None # private place to store the property 'hostname' # configuration_key = None # # @property # def hostname(self): # """ # Return the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # return self.__hostname # # @hostname.setter # def hostname(self, value): # """ # Set the hostname managed by this updater. # # May be implemented or overwritten in updater subclasses. # """ # self.__hostname = value # # @staticmethod # def configuration_key_prefix(): # """ # Return a human readable string classifying this class as an updater. # # Should not be be implemented or overwritten in updater subclasses. # """ # return "updater" # # def update(self, ip): # """ # Update the hostname on the remote service. # # Abstract method, must be implemented in subclass. # """ # raise NotImplementedError("Please implement in subclass") # # Path: dyndnsc/common/constants.py # REQUEST_HEADERS_DEFAULT = { # # dyndns2 standard requires that we set our own user agent: # "User-Agent": "python-dyndnsc/%s" % __version__, # } . Output only the next line.
req = requests.get(self._updateurl, params=params, headers=constants.REQUEST_HEADERS_DEFAULT,
Predict the next line after this snippet: <|code_start|> AF_INET: { "@": ("resolver1.opendns.com", "resolver2.opendns.com"), "qname": "myip.opendns.com", "rdtype": "A", }, AF_INET6: { "@": ("resolver1.ipv6-sandbox.opendns.com", "resolver2.ipv6-sandbox.opendns.com"), "qname": "myip.opendns.com", "rdtype": "AAAA", }, }, } dnswanipprovider = dnswanipproviders[provider] # only option as of now resolver = dns.resolver.Resolver() # first, get the IPs of the DNS servers: nameservers = [] for dnsservername in dnswanipprovider[family]["@"]: _answers = resolver.query(qname=dnsservername, rdtype=dnswanipprovider[family]["rdtype"]) nameservers.extend([rdata.address for rdata in _answers]) # specify the nameservers to be used: resolver.nameservers = nameservers # finally, attempt to discover our WAN IP by querying the DNS: answers = resolver.query(qname=dnswanipprovider[family]["qname"], rdtype=dnswanipprovider[family]["rdtype"]) for rdata in answers: return rdata.address return None <|code_end|> using the current file's imports: import logging import dns.resolver from .base import IPDetector, AF_INET, AF_INET6 and any relevant context from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): . Output only the next line.
class IPDetector_DnsWanIp(IPDetector):
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """Module containing logic for DNS WAN IP detection. See also https://www.cyberciti.biz/faq/how-to-find-my-public-ip-address-from-command-line-on-a-linux/ """ from __future__ import absolute_import LOG = logging.getLogger(__name__) <|code_end|> , generate the next line using the imports in this file: import logging import dns.resolver from .base import IPDetector, AF_INET, AF_INET6 and context (functions, classes, or occasionally code) from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): . Output only the next line.
def find_ip(family=AF_INET, provider="opendns"):
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """Module containing logic for DNS WAN IP detection. See also https://www.cyberciti.biz/faq/how-to-find-my-public-ip-address-from-command-line-on-a-linux/ """ from __future__ import absolute_import LOG = logging.getLogger(__name__) def find_ip(family=AF_INET, provider="opendns"): """Find the publicly visible IP address of the current system. This uses public DNS infrastructure that implement a special DNS "hack" to return the IP address of the requester rather than some other address. :param family: address family, optional, default AF_INET (ipv4) :param flavour: selector for public infrastructure provider, optional """ dnswanipproviders = { "opendns": { AF_INET: { "@": ("resolver1.opendns.com", "resolver2.opendns.com"), "qname": "myip.opendns.com", "rdtype": "A", }, <|code_end|> . Use current file imports: (import logging import dns.resolver from .base import IPDetector, AF_INET, AF_INET6) and context including class names, function names, or small code snippets from other files: # Path: dyndnsc/detector/base.py # LOG = logging.getLogger(__name__) # class IPDetector(Subject, DynamicCliMixin): # def __init__(self, *args, **kwargs): # def can_detect_offline(self): # def af(self): # def get_old_value(self): # def set_old_value(self, value): # def get_current_value(self, default=None): # def set_current_value(self, value): # def has_changed(self): # def configuration_key_prefix(): . Output only the next line.
AF_INET6: {
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ All built-in detector plugins are listed here and will be dynamically imported. If importing a plugin fails, it will be ignored. """ _BUILTINS = ( ("dyndnsc.detector.command", "IPDetector_Command"), ("dyndnsc.detector.dns", "IPDetector_DNS"), ("dyndnsc.detector.dnswanip", "IPDetector_DnsWanIp"), ("dyndnsc.detector.iface", "IPDetector_Iface"), ("dyndnsc.detector.socket_ip", "IPDetector_Socket"), ("dyndnsc.detector.rand", "IPDetector_Random"), ("dyndnsc.detector.teredo", "IPDetector_Teredo"), ("dyndnsc.detector.webcheck", "IPDetectorWebCheck"), ("dyndnsc.detector.webcheck", "IPDetectorWebCheck6"), ("dyndnsc.detector.webcheck", "IPDetectorWebCheck46"), ("dyndnsc.detector.null", "IPDetector_Null") ) <|code_end|> , determine the next line of code. You have imports: from ..common.load import load_class as _load_plugin and context (class names, function names, or code) available: # Path: dyndnsc/common/load.py # def load_class(module_name, class_name): # """Return class object specified by module name and class name. # # Return None if module failed to be imported. # # :param module_name: string module name # :param class_name: string class name # """ # try: # plugmod = import_module(module_name) # except Exception as exc: # warn("Importing built-in plugin %s.%s raised an exception: %r" % # (module_name, class_name, repr(exc)), ImportWarning) # return None # else: # return getattr(plugmod, class_name) . Output only the next line.
PLUGINS = {plug for plug in (_load_plugin(m, c) for m, c in _BUILTINS) if plug is not None}
Predict the next line after this snippet: <|code_start|> def test_unconfigured_request(): try: http.request(requests.get, 'test') <|code_end|> using the current file's imports: import requests import helpers from kloudless import http, exceptions and any relevant context from other files: # Path: kloudless/http.py # class BaseAuth: # class APIKeyAuth(BaseAuth): # class DevKeyAuth(BaseAuth): # class BearerTokenAuth(BaseAuth): # def __init__(self, key): # def auth_header(self): # def __call__(self, request): # def request(method, path, configuration=None, **kwargs): # def _request(requestor, configuration): # # Path: kloudless/exceptions.py # class KloudlessException(Exception): # class APIException(KloudlessException): # class AuthenticationException(KloudlessException): # class AuthorizationException(KloudlessException): # class RateLimitException(KloudlessException): # class ServerException(KloudlessException): # class ConfigurationException(Exception): # def __init__(self, message=None, response=None): # def __init__(self, *args, **kwargs): . Output only the next line.
except exceptions.ConfigurationException:
Given the code snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Register your models here. admin.site.register(NamespaceIcon) admin.site.register(PackageComment) admin.site.register(CampaignComment) <|code_end|> , generate the next line using the imports in this file: from django.contrib import admin from kraut_intel.models import NamespaceIcon, PackageComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment and context (functions, classes, or occasionally code) from other files: # Path: kraut_intel/models.py # class NamespaceIcon(models.Model): # namespace = models.CharField(max_length=255, unique=True) # icon = models.CharField(max_length=255) # # def __unicode__(self): # return u"%s (%s)" % (self.namespace, self.icon) # # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) . Output only the next line.
admin.site.register(TTPComment)
Using the snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Register your models here. admin.site.register(NamespaceIcon) admin.site.register(PackageComment) admin.site.register(CampaignComment) admin.site.register(TTPComment) <|code_end|> , determine the next line of code. You have imports: from django.contrib import admin from kraut_intel.models import NamespaceIcon, PackageComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment and context (class names, function names, or code) available: # Path: kraut_intel/models.py # class NamespaceIcon(models.Model): # namespace = models.CharField(max_length=255, unique=True) # icon = models.CharField(max_length=255) # # def __unicode__(self): # return u"%s (%s)" % (self.namespace, self.icon) # # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) . Output only the next line.
admin.site.register(IndicatorComment)
Using the snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Register your models here. admin.site.register(NamespaceIcon) admin.site.register(PackageComment) admin.site.register(CampaignComment) admin.site.register(TTPComment) admin.site.register(IndicatorComment) <|code_end|> , determine the next line of code. You have imports: from django.contrib import admin from kraut_intel.models import NamespaceIcon, PackageComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment and context (class names, function names, or code) available: # Path: kraut_intel/models.py # class NamespaceIcon(models.Model): # namespace = models.CharField(max_length=255, unique=True) # icon = models.CharField(max_length=255) # # def __unicode__(self): # return u"%s (%s)" % (self.namespace, self.icon) # # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) . Output only the next line.
admin.site.register(ObservableComment)
Given the code snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 class HandlerForm(ModelForm): class Meta: model = Handler fields = ["firstname", "lastname", "phone", "email", "description"] widgets = { 'firstname': widgets.TextInput(attrs={'id': 'post_handler_firstname', 'class': 'form-control', 'placeholder': ''}), 'lastname': widgets.TextInput(attrs={'id': 'post_handler_lastname', 'class': 'form-control', 'placeholder': ''}), 'phone': widgets.TextInput(attrs={'id': 'post_handler_phone', 'class': 'form-control', 'placeholder': ''}), 'email': widgets.EmailInput(attrs={'id': 'post_handler_email', 'class': 'form-control', 'placeholder': ''}), 'description': widgets.Textarea(attrs={'id': 'post_handler_description', 'class': 'form-control', 'placeholder': 'What is this handler responsible for ...'}), } class ContactForm(ModelForm): class Meta: model = Contact fields = ["firstname", "lastname", "phone", "email", "description"] widgets = { 'firstname': widgets.TextInput(attrs={'id': 'post_contact_firstname', 'class': 'form-control', 'placeholder': ''}), 'lastname': widgets.TextInput(attrs={'id': 'post_contact_lastname', 'class': 'form-control', 'placeholder': ''}), 'phone': widgets.TextInput(attrs={'id': 'post_contact_phone', 'class': 'form-control', 'placeholder': ''}), 'email': widgets.EmailInput(attrs={'id': 'post_contact_email', 'class': 'form-control', 'placeholder': ''}), 'description': widgets.Textarea(attrs={'id': 'post_contact_description', 'class': 'form-control', 'placeholder': 'What is this contact responsible for ...'}), } class IncidentForm(ModelForm): class Meta: <|code_end|> , generate the next line using the imports in this file: from django.forms import ModelForm, widgets from kraut_incident.models import Incident, Contact, Handler, IncidentComment and context (functions, classes, or occasionally code) from other files: # Path: kraut_incident/models.py # class Incident(models.Model): # """Describe a security incident # """ # incident_number = models.IntegerField(unique=True, default=random_incident_number) # title = models.CharField(max_length=255, default="Unnamed Incident") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # status = models.ForeignKey(Incident_Status, on_delete=models.CASCADE) # category = models.ForeignKey(Incident_Category, on_delete=models.CASCADE) # affected_assets = models.ManyToManyField(Asset, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # incident_handler = models.ManyToManyField(Handler, blank=True, related_name="incident_handler") # contacts = models.ManyToManyField(Contact, blank=True, related_name="contacts") # severity_choices = ( # ('h', 'High'), # ('m', 'Medium'), # ('l', 'Low'), # ) # severity = models.CharField(max_length=2, choices=severity_choices, default='m') # # def __unicode__(self): # return u"%s" % (self.title) # # class Contact(models.Model): # """Describe a contact person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class Handler(models.Model): # """Describe an incident handler person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class IncidentComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # incident_reference = models.ForeignKey(Incident, on_delete=models.CASCADE) . Output only the next line.
model = Incident
Given the following code snippet before the placeholder: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 class HandlerForm(ModelForm): class Meta: model = Handler fields = ["firstname", "lastname", "phone", "email", "description"] widgets = { 'firstname': widgets.TextInput(attrs={'id': 'post_handler_firstname', 'class': 'form-control', 'placeholder': ''}), 'lastname': widgets.TextInput(attrs={'id': 'post_handler_lastname', 'class': 'form-control', 'placeholder': ''}), 'phone': widgets.TextInput(attrs={'id': 'post_handler_phone', 'class': 'form-control', 'placeholder': ''}), 'email': widgets.EmailInput(attrs={'id': 'post_handler_email', 'class': 'form-control', 'placeholder': ''}), 'description': widgets.Textarea(attrs={'id': 'post_handler_description', 'class': 'form-control', 'placeholder': 'What is this handler responsible for ...'}), } class ContactForm(ModelForm): class Meta: <|code_end|> , predict the next line using imports from the current file: from django.forms import ModelForm, widgets from kraut_incident.models import Incident, Contact, Handler, IncidentComment and context including class names, function names, and sometimes code from other files: # Path: kraut_incident/models.py # class Incident(models.Model): # """Describe a security incident # """ # incident_number = models.IntegerField(unique=True, default=random_incident_number) # title = models.CharField(max_length=255, default="Unnamed Incident") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # status = models.ForeignKey(Incident_Status, on_delete=models.CASCADE) # category = models.ForeignKey(Incident_Category, on_delete=models.CASCADE) # affected_assets = models.ManyToManyField(Asset, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # incident_handler = models.ManyToManyField(Handler, blank=True, related_name="incident_handler") # contacts = models.ManyToManyField(Contact, blank=True, related_name="contacts") # severity_choices = ( # ('h', 'High'), # ('m', 'Medium'), # ('l', 'Low'), # ) # severity = models.CharField(max_length=2, choices=severity_choices, default='m') # # def __unicode__(self): # return u"%s" % (self.title) # # class Contact(models.Model): # """Describe a contact person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class Handler(models.Model): # """Describe an incident handler person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class IncidentComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # incident_reference = models.ForeignKey(Incident, on_delete=models.CASCADE) . Output only the next line.
model = Contact
Predict the next line after this snippet: <|code_start|> } class ContactForm(ModelForm): class Meta: model = Contact fields = ["firstname", "lastname", "phone", "email", "description"] widgets = { 'firstname': widgets.TextInput(attrs={'id': 'post_contact_firstname', 'class': 'form-control', 'placeholder': ''}), 'lastname': widgets.TextInput(attrs={'id': 'post_contact_lastname', 'class': 'form-control', 'placeholder': ''}), 'phone': widgets.TextInput(attrs={'id': 'post_contact_phone', 'class': 'form-control', 'placeholder': ''}), 'email': widgets.EmailInput(attrs={'id': 'post_contact_email', 'class': 'form-control', 'placeholder': ''}), 'description': widgets.Textarea(attrs={'id': 'post_contact_description', 'class': 'form-control', 'placeholder': 'What is this contact responsible for ...'}), } class IncidentForm(ModelForm): class Meta: model = Incident fields = ['incident_number', 'title', 'description', 'status', 'category', 'severity'] widgets = { 'incident_number': widgets.NumberInput(attrs={'class': 'form-control', 'readonly': True, 'required': True}), 'title': widgets.TextInput(attrs={'class': 'form-control', 'placeholder': 'Provide a name for the incident or investigation', 'required': True}), 'description': widgets.Textarea(attrs={'class': 'form-control', 'placeholder': 'What and when did it happened ...'}), 'status': widgets.Select(attrs={'class': 'form-control'}), 'category': widgets.Select(attrs={'class': 'form-control'}), 'severity': widgets.Select(attrs={'class': 'form-control'}), } class IncidentCommentForm(ModelForm): class Meta: <|code_end|> using the current file's imports: from django.forms import ModelForm, widgets from kraut_incident.models import Incident, Contact, Handler, IncidentComment and any relevant context from other files: # Path: kraut_incident/models.py # class Incident(models.Model): # """Describe a security incident # """ # incident_number = models.IntegerField(unique=True, default=random_incident_number) # title = models.CharField(max_length=255, default="Unnamed Incident") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # status = models.ForeignKey(Incident_Status, on_delete=models.CASCADE) # category = models.ForeignKey(Incident_Category, on_delete=models.CASCADE) # affected_assets = models.ManyToManyField(Asset, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # incident_handler = models.ManyToManyField(Handler, blank=True, related_name="incident_handler") # contacts = models.ManyToManyField(Contact, blank=True, related_name="contacts") # severity_choices = ( # ('h', 'High'), # ('m', 'Medium'), # ('l', 'Low'), # ) # severity = models.CharField(max_length=2, choices=severity_choices, default='m') # # def __unicode__(self): # return u"%s" % (self.title) # # class Contact(models.Model): # """Describe a contact person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class Handler(models.Model): # """Describe an incident handler person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class IncidentComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # incident_reference = models.ForeignKey(Incident, on_delete=models.CASCADE) . Output only the next line.
model = IncidentComment
Predict the next line after this snippet: <|code_start|> ################### PACKAGE ##################### class PackageCommentForm(ModelForm): class Meta: model = PackageComment fields = ['ctext'] def __init__(self, *args, **kwargs): super(PackageCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) class PackageForm(ModelForm): class Meta: <|code_end|> using the current file's imports: from django.forms import ModelForm from kraut_parser.models import Package, ThreatActor from kraut_intel.models import PackageComment, ThreatActorComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment and any relevant context from other files: # Path: kraut_parser/models.py # class Package(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # version = models.CharField(max_length=255) # package_id = models.CharField(max_length=255) # source = models.CharField(max_length=255) # produced_time = models.DateTimeField(null=True, blank=True) # threat_actors = models.ManyToManyField('ThreatActor', blank=True) # campaigns = models.ManyToManyField('Campaign', blank=True) # indicators = models.ManyToManyField('Indicator', blank=True) # observables = models.ManyToManyField('Observable', blank=True) # ttps = models.ManyToManyField('TTP', blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class ThreatActor(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # campaigns = models.ManyToManyField(Campaign, blank=True) # associated_threat_actors = models.ManyToManyField('self', blank=True) # threat_actor_id = models.CharField(max_length=255) # observed_ttps = models.ManyToManyField(TTP, through='ObservedTTP', symmetrical=False, related_name='ttp_observed_at_ta', blank=True) # # def add_observed_ttp(self, ttp, relationship): # obs_ttp, obs_ttp_created = ObservedTTP.objects.get_or_create( # ta=self, # ttp=ttp, # relationship=relationship # ) # return obs_ttp # # def __unicode__(self): # return u"%s" % (self.name) # # Path: kraut_intel/models.py # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class ThreatActorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # actor_reference = models.ForeignKey(ThreatActor, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) . Output only the next line.
model = Package
Predict the next line for this snippet: <|code_start|>class PackageForm(ModelForm): class Meta: model = Package fields = ['name', 'description', 'short_description', 'namespace', 'version', 'package_id', 'source', 'produced_time'] def __init__(self, *args, **kwargs): super(PackageForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class' : 'form-control', 'id': 'packageName'}) self.fields['namespace'].widget.attrs.update({'class' : 'form-control', 'id': 'nameSpace'}) self.fields['produced_time'].widget.attrs.update({'class' : 'form-control', 'id': 'producedTime'}) self.fields['version'].widget.attrs.update({'class' : 'form-control', 'id': 'version'}) self.fields['source'].widget.attrs.update({'class' : 'form-control', 'id': 'source'}) self.fields['description'].widget.attrs.update({'class' : 'form-control', 'id': 'description'}) self.fields['short_description'].widget.attrs.update({'class' : 'form-control', 'id': 'shortDescription'}) self.fields['package_id'].widget.attrs.update({'class' : 'form-control', 'id': 'packageID'}) self.fields['namespace'].required = True ################### THREAT ACTOR ##################### class ActorCommentForm(ModelForm): class Meta: model = ThreatActorComment fields = ['ctext'] def __init__(self, *args, **kwargs): super(ActorCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) class ActorForm(ModelForm): class Meta: <|code_end|> with the help of current file imports: from django.forms import ModelForm from kraut_parser.models import Package, ThreatActor from kraut_intel.models import PackageComment, ThreatActorComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment and context from other files: # Path: kraut_parser/models.py # class Package(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # version = models.CharField(max_length=255) # package_id = models.CharField(max_length=255) # source = models.CharField(max_length=255) # produced_time = models.DateTimeField(null=True, blank=True) # threat_actors = models.ManyToManyField('ThreatActor', blank=True) # campaigns = models.ManyToManyField('Campaign', blank=True) # indicators = models.ManyToManyField('Indicator', blank=True) # observables = models.ManyToManyField('Observable', blank=True) # ttps = models.ManyToManyField('TTP', blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class ThreatActor(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # campaigns = models.ManyToManyField(Campaign, blank=True) # associated_threat_actors = models.ManyToManyField('self', blank=True) # threat_actor_id = models.CharField(max_length=255) # observed_ttps = models.ManyToManyField(TTP, through='ObservedTTP', symmetrical=False, related_name='ttp_observed_at_ta', blank=True) # # def add_observed_ttp(self, ttp, relationship): # obs_ttp, obs_ttp_created = ObservedTTP.objects.get_or_create( # ta=self, # ttp=ttp, # relationship=relationship # ) # return obs_ttp # # def __unicode__(self): # return u"%s" % (self.name) # # Path: kraut_intel/models.py # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class ThreatActorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # actor_reference = models.ForeignKey(ThreatActor, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) , which may contain function names, class names, or code. Output only the next line.
model = ThreatActor
Using the snippet: <|code_start|> class Meta: model = PackageComment fields = ['ctext'] def __init__(self, *args, **kwargs): super(PackageCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) class PackageForm(ModelForm): class Meta: model = Package fields = ['name', 'description', 'short_description', 'namespace', 'version', 'package_id', 'source', 'produced_time'] def __init__(self, *args, **kwargs): super(PackageForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class' : 'form-control', 'id': 'packageName'}) self.fields['namespace'].widget.attrs.update({'class' : 'form-control', 'id': 'nameSpace'}) self.fields['produced_time'].widget.attrs.update({'class' : 'form-control', 'id': 'producedTime'}) self.fields['version'].widget.attrs.update({'class' : 'form-control', 'id': 'version'}) self.fields['source'].widget.attrs.update({'class' : 'form-control', 'id': 'source'}) self.fields['description'].widget.attrs.update({'class' : 'form-control', 'id': 'description'}) self.fields['short_description'].widget.attrs.update({'class' : 'form-control', 'id': 'shortDescription'}) self.fields['package_id'].widget.attrs.update({'class' : 'form-control', 'id': 'packageID'}) self.fields['namespace'].required = True ################### THREAT ACTOR ##################### class ActorCommentForm(ModelForm): class Meta: <|code_end|> , determine the next line of code. You have imports: from django.forms import ModelForm from kraut_parser.models import Package, ThreatActor from kraut_intel.models import PackageComment, ThreatActorComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment and context (class names, function names, or code) available: # Path: kraut_parser/models.py # class Package(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # version = models.CharField(max_length=255) # package_id = models.CharField(max_length=255) # source = models.CharField(max_length=255) # produced_time = models.DateTimeField(null=True, blank=True) # threat_actors = models.ManyToManyField('ThreatActor', blank=True) # campaigns = models.ManyToManyField('Campaign', blank=True) # indicators = models.ManyToManyField('Indicator', blank=True) # observables = models.ManyToManyField('Observable', blank=True) # ttps = models.ManyToManyField('TTP', blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class ThreatActor(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # campaigns = models.ManyToManyField(Campaign, blank=True) # associated_threat_actors = models.ManyToManyField('self', blank=True) # threat_actor_id = models.CharField(max_length=255) # observed_ttps = models.ManyToManyField(TTP, through='ObservedTTP', symmetrical=False, related_name='ttp_observed_at_ta', blank=True) # # def add_observed_ttp(self, ttp, relationship): # obs_ttp, obs_ttp_created = ObservedTTP.objects.get_or_create( # ta=self, # ttp=ttp, # relationship=relationship # ) # return obs_ttp # # def __unicode__(self): # return u"%s" % (self.name) # # Path: kraut_intel/models.py # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class ThreatActorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # actor_reference = models.ForeignKey(ThreatActor, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) . Output only the next line.
model = ThreatActorComment
Using the snippet: <|code_start|>################### THREAT ACTOR ##################### class ActorCommentForm(ModelForm): class Meta: model = ThreatActorComment fields = ['ctext'] def __init__(self, *args, **kwargs): super(ActorCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) class ActorForm(ModelForm): class Meta: model = ThreatActor fields = ['name', 'description', 'short_description', 'namespace', 'threat_actor_id', 'associated_threat_actors'] def __init__(self, *args, **kwargs): super(ActorForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class' : 'form-control', 'id': 'packageName'}) self.fields['namespace'].widget.attrs.update({'class' : 'form-control', 'id': 'nameSpace'}) self.fields['description'].widget.attrs.update({'class' : 'form-control', 'id': 'description'}) self.fields['short_description'].widget.attrs.update({'class' : 'form-control', 'id': 'shortDescription'}) self.fields['threat_actor_id'].widget.attrs.update({'class' : 'form-control', 'id': 'packageID'}) self.fields['associated_threat_actors'].widget.attrs.update({'class' : 'form-control', 'id': 'nameSpace'}) self.fields['namespace'].required = True ################### CAMPAIGN ##################### class CampaignCommentForm(ModelForm): class Meta: <|code_end|> , determine the next line of code. You have imports: from django.forms import ModelForm from kraut_parser.models import Package, ThreatActor from kraut_intel.models import PackageComment, ThreatActorComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment and context (class names, function names, or code) available: # Path: kraut_parser/models.py # class Package(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # version = models.CharField(max_length=255) # package_id = models.CharField(max_length=255) # source = models.CharField(max_length=255) # produced_time = models.DateTimeField(null=True, blank=True) # threat_actors = models.ManyToManyField('ThreatActor', blank=True) # campaigns = models.ManyToManyField('Campaign', blank=True) # indicators = models.ManyToManyField('Indicator', blank=True) # observables = models.ManyToManyField('Observable', blank=True) # ttps = models.ManyToManyField('TTP', blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class ThreatActor(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # campaigns = models.ManyToManyField(Campaign, blank=True) # associated_threat_actors = models.ManyToManyField('self', blank=True) # threat_actor_id = models.CharField(max_length=255) # observed_ttps = models.ManyToManyField(TTP, through='ObservedTTP', symmetrical=False, related_name='ttp_observed_at_ta', blank=True) # # def add_observed_ttp(self, ttp, relationship): # obs_ttp, obs_ttp_created = ObservedTTP.objects.get_or_create( # ta=self, # ttp=ttp, # relationship=relationship # ) # return obs_ttp # # def __unicode__(self): # return u"%s" % (self.name) # # Path: kraut_intel/models.py # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class ThreatActorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # actor_reference = models.ForeignKey(ThreatActor, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) . Output only the next line.
model = CampaignComment
Next line prediction: <|code_start|>class ActorForm(ModelForm): class Meta: model = ThreatActor fields = ['name', 'description', 'short_description', 'namespace', 'threat_actor_id', 'associated_threat_actors'] def __init__(self, *args, **kwargs): super(ActorForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class' : 'form-control', 'id': 'packageName'}) self.fields['namespace'].widget.attrs.update({'class' : 'form-control', 'id': 'nameSpace'}) self.fields['description'].widget.attrs.update({'class' : 'form-control', 'id': 'description'}) self.fields['short_description'].widget.attrs.update({'class' : 'form-control', 'id': 'shortDescription'}) self.fields['threat_actor_id'].widget.attrs.update({'class' : 'form-control', 'id': 'packageID'}) self.fields['associated_threat_actors'].widget.attrs.update({'class' : 'form-control', 'id': 'nameSpace'}) self.fields['namespace'].required = True ################### CAMPAIGN ##################### class CampaignCommentForm(ModelForm): class Meta: model = CampaignComment fields = ['ctext'] def __init__(self, *args, **kwargs): super(CampaignCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) ################### TTP ##################### class TTPCommentForm(ModelForm): class Meta: <|code_end|> . Use current file imports: (from django.forms import ModelForm from kraut_parser.models import Package, ThreatActor from kraut_intel.models import PackageComment, ThreatActorComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment) and context including class names, function names, or small code snippets from other files: # Path: kraut_parser/models.py # class Package(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # version = models.CharField(max_length=255) # package_id = models.CharField(max_length=255) # source = models.CharField(max_length=255) # produced_time = models.DateTimeField(null=True, blank=True) # threat_actors = models.ManyToManyField('ThreatActor', blank=True) # campaigns = models.ManyToManyField('Campaign', blank=True) # indicators = models.ManyToManyField('Indicator', blank=True) # observables = models.ManyToManyField('Observable', blank=True) # ttps = models.ManyToManyField('TTP', blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class ThreatActor(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # campaigns = models.ManyToManyField(Campaign, blank=True) # associated_threat_actors = models.ManyToManyField('self', blank=True) # threat_actor_id = models.CharField(max_length=255) # observed_ttps = models.ManyToManyField(TTP, through='ObservedTTP', symmetrical=False, related_name='ttp_observed_at_ta', blank=True) # # def add_observed_ttp(self, ttp, relationship): # obs_ttp, obs_ttp_created = ObservedTTP.objects.get_or_create( # ta=self, # ttp=ttp, # relationship=relationship # ) # return obs_ttp # # def __unicode__(self): # return u"%s" % (self.name) # # Path: kraut_intel/models.py # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class ThreatActorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # actor_reference = models.ForeignKey(ThreatActor, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) . Output only the next line.
model = TTPComment
Based on the snippet: <|code_start|> self.fields['threat_actor_id'].widget.attrs.update({'class' : 'form-control', 'id': 'packageID'}) self.fields['associated_threat_actors'].widget.attrs.update({'class' : 'form-control', 'id': 'nameSpace'}) self.fields['namespace'].required = True ################### CAMPAIGN ##################### class CampaignCommentForm(ModelForm): class Meta: model = CampaignComment fields = ['ctext'] def __init__(self, *args, **kwargs): super(CampaignCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) ################### TTP ##################### class TTPCommentForm(ModelForm): class Meta: model = TTPComment fields = ['ctext'] def __init__(self, *args, **kwargs): super(TTPCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) ################### INDICATOR ##################### class IndicatorCommentForm(ModelForm): class Meta: <|code_end|> , predict the immediate next line with the help of imports: from django.forms import ModelForm from kraut_parser.models import Package, ThreatActor from kraut_intel.models import PackageComment, ThreatActorComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment and context (classes, functions, sometimes code) from other files: # Path: kraut_parser/models.py # class Package(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # version = models.CharField(max_length=255) # package_id = models.CharField(max_length=255) # source = models.CharField(max_length=255) # produced_time = models.DateTimeField(null=True, blank=True) # threat_actors = models.ManyToManyField('ThreatActor', blank=True) # campaigns = models.ManyToManyField('Campaign', blank=True) # indicators = models.ManyToManyField('Indicator', blank=True) # observables = models.ManyToManyField('Observable', blank=True) # ttps = models.ManyToManyField('TTP', blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class ThreatActor(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # campaigns = models.ManyToManyField(Campaign, blank=True) # associated_threat_actors = models.ManyToManyField('self', blank=True) # threat_actor_id = models.CharField(max_length=255) # observed_ttps = models.ManyToManyField(TTP, through='ObservedTTP', symmetrical=False, related_name='ttp_observed_at_ta', blank=True) # # def add_observed_ttp(self, ttp, relationship): # obs_ttp, obs_ttp_created = ObservedTTP.objects.get_or_create( # ta=self, # ttp=ttp, # relationship=relationship # ) # return obs_ttp # # def __unicode__(self): # return u"%s" % (self.name) # # Path: kraut_intel/models.py # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class ThreatActorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # actor_reference = models.ForeignKey(ThreatActor, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) . Output only the next line.
model = IndicatorComment
Next line prediction: <|code_start|> def __init__(self, *args, **kwargs): super(CampaignCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) ################### TTP ##################### class TTPCommentForm(ModelForm): class Meta: model = TTPComment fields = ['ctext'] def __init__(self, *args, **kwargs): super(TTPCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) ################### INDICATOR ##################### class IndicatorCommentForm(ModelForm): class Meta: model = IndicatorComment fields = ['ctext'] def __init__(self, *args, **kwargs): super(IndicatorCommentForm, self).__init__(*args, **kwargs) self.fields['ctext'].widget.attrs.update({'class' : 'form-control', 'id': 'packageComment'}) ################### OBSERVABLE ##################### class ObservableCommentForm(ModelForm): class Meta: <|code_end|> . Use current file imports: (from django.forms import ModelForm from kraut_parser.models import Package, ThreatActor from kraut_intel.models import PackageComment, ThreatActorComment, CampaignComment, TTPComment, IndicatorComment, ObservableComment) and context including class names, function names, or small code snippets from other files: # Path: kraut_parser/models.py # class Package(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # version = models.CharField(max_length=255) # package_id = models.CharField(max_length=255) # source = models.CharField(max_length=255) # produced_time = models.DateTimeField(null=True, blank=True) # threat_actors = models.ManyToManyField('ThreatActor', blank=True) # campaigns = models.ManyToManyField('Campaign', blank=True) # indicators = models.ManyToManyField('Indicator', blank=True) # observables = models.ManyToManyField('Observable', blank=True) # ttps = models.ManyToManyField('TTP', blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class ThreatActor(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # campaigns = models.ManyToManyField(Campaign, blank=True) # associated_threat_actors = models.ManyToManyField('self', blank=True) # threat_actor_id = models.CharField(max_length=255) # observed_ttps = models.ManyToManyField(TTP, through='ObservedTTP', symmetrical=False, related_name='ttp_observed_at_ta', blank=True) # # def add_observed_ttp(self, ttp, relationship): # obs_ttp, obs_ttp_created = ObservedTTP.objects.get_or_create( # ta=self, # ttp=ttp, # relationship=relationship # ) # return obs_ttp # # def __unicode__(self): # return u"%s" % (self.name) # # Path: kraut_intel/models.py # class PackageComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # package_reference = models.ForeignKey(Package, on_delete=models.CASCADE) # # class ThreatActorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # actor_reference = models.ForeignKey(ThreatActor, on_delete=models.CASCADE) # # class CampaignComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # campaign_reference = models.ForeignKey(Campaign, on_delete=models.CASCADE) # # class TTPComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # ttp_reference = models.ForeignKey(TTP, on_delete=models.CASCADE) # # class IndicatorComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # indicator_reference = models.ForeignKey(Indicator, on_delete=models.CASCADE) # # class ObservableComment(models.Model): # ctext = models.TextField() # author = models.ForeignKey(User, on_delete=models.CASCADE) # creation_time = models.DateTimeField(auto_now_add=True) # observable_reference = models.ForeignKey(Observable, on_delete=models.CASCADE) . Output only the next line.
model = ObservableComment
Here is a snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Create your views here. @login_required def base_search(request): context = {'sterm': None, 'result': []} if not request.method == 'POST': return HttpResponse(status=status.HTTP_400_BAD_REQUEST) sterm = request.POST.get('searchbar', None) context['sterm'] = sterm ### search observable objects <|code_end|> . Write the next line using the current file imports: from django.http import HttpResponse from rest_framework import status from django.db.models import Prefetch, Q from django.shortcuts import render from django.contrib.auth.decorators import login_required from kraut_parser.models import Observable, File_Object and context from other files: # Path: kraut_parser/models.py # class Observable(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # indicators = models.ManyToManyField(Indicator, blank=True) # compositions = models.ManyToManyField(ObservableComposition, blank=True) # observable_type = models.CharField(max_length=255, null=True, blank=True) # observable_id = models.CharField(max_length=255, unique=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class File_Object(models.Model): # file_meta = models.ManyToManyField(File_Meta_Object, blank=True) # file_custom = models.ManyToManyField(File_Custom_Properties, blank=True) # md5_hash = models.CharField(max_length=32, null=True, blank=True) # sha256_hash = models.CharField(max_length=64, null=True, blank=True) # observables = models.ManyToManyField(Observable) # # def __unicode__(self): # if self.md5_hash: # return u"%s" % (self.md5_hash) # elif self.sha256_hash: # return u"%s" % (self.sha256_hash) # else: # return u"File Object" # # class Meta: # index_together = (("md5_hash", "sha256_hash"),) , which may include functions, classes, or code. Output only the next line.
queryset = Observable.objects.filter(
Given the following code snippet before the placeholder: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 forms.DateInput.input_type="datetime" class DiscoveryForm(forms.Form): url = forms.URLField(label='Discovery URL', max_length='255', widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'discoveryURL', 'name': 'discoveryURL'})) class PollForm(forms.Form): url = forms.URLField(label='URL', max_length='255', widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'URL'})) service = forms.CharField(label='Feed Name', max_length='255', widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'feed'})) begin_time = forms.DateTimeField(label='Begin timestamp', widget=forms.DateTimeInput(attrs={'class':'form-control', 'id': 'begin'}), required=False) end_time = forms.DateTimeField(label='End timestamp', widget=forms.DateTimeInput(attrs={'class':'form-control', 'id': 'end', 'placeholder': 'None'}), required=False) poll_choices = ( ('0', 'only once'), ('1', 'every hour'), ('8', 'every 8 hours'), ('24', 'every 24 hours'), ) poll = forms.ChoiceField(label='Poll periodically', widget=forms.Select(attrs={'class': 'form-control', 'id': 'polling'}), choices=poll_choices) class AddServerForm(ModelForm): class Meta: <|code_end|> , predict the next line using imports from the current file: from django import forms from django.forms import ModelForm, widgets from kraut_sharing.models import TAXII_Remote_Server, TAXII_Remote_Collection and context including class names, function names, and sometimes code from other files: # Path: kraut_sharing/models.py # class TAXII_Remote_Server(models.Model): # creation_time = models.DateTimeField(auto_now_add=True) # name = models.CharField(max_length=255, help_text="""Name/Identifier""") # host = models.CharField(max_length=255, help_text="""Hostname or IP address""") # port = models.IntegerField(help_text="""Remote port""", default=80) # protocol = models.CharField(max_length=5, help_text="""Protocol to use""", default="http") # path = models.CharField(max_length=255, help_text="""Path to service""") # version = models.CharField(max_length=5, help_text="""TAXII version to use""", default="1.1") # auth_type = models.IntegerField(default=0, help_text="""Authentication to use""") # last_discovery = models.DateTimeField(blank=True, null=True) # # TODO: fields for authentication (foreign key) # # TODO: proxy configuration # # def get_url(self): # return "%s://%s:%i%s" % (self.protocol, self.host, self.port, self.path) # # def __unicode__(self): # return u"%s (%s://%s:%i%s)" % (self.name, self.protocol, self.host, self.port, self.path) # # class Meta: # unique_together = (("name", "host", "port", "protocol", "path"),) # # class TAXII_Remote_Collection(models.Model): # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # name = models.CharField(max_length=255, help_text="""name of the collection""", unique=True) # begin_timestamp = models.DateTimeField(blank=True, null=True) # end_timestamp = models.DateTimeField(blank=True, null=True) # server = models.ForeignKey("TAXII_Remote_Server", on_delete=models.CASCADE) # subscribed = models.BooleanField(default=False) # collection_type = models.CharField(max_length=255, default="DATA-FEED") # poll_period = models.IntegerField(default=24, help_text="""poll period in hours (e.g. 24 = every 24 hours)""") # # def __unicode__(self): # return u"%s" % (self.name) . Output only the next line.
model = TAXII_Remote_Server
Given snippet: <|code_start|> class PollForm(forms.Form): url = forms.URLField(label='URL', max_length='255', widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'URL'})) service = forms.CharField(label='Feed Name', max_length='255', widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'feed'})) begin_time = forms.DateTimeField(label='Begin timestamp', widget=forms.DateTimeInput(attrs={'class':'form-control', 'id': 'begin'}), required=False) end_time = forms.DateTimeField(label='End timestamp', widget=forms.DateTimeInput(attrs={'class':'form-control', 'id': 'end', 'placeholder': 'None'}), required=False) poll_choices = ( ('0', 'only once'), ('1', 'every hour'), ('8', 'every 8 hours'), ('24', 'every 24 hours'), ) poll = forms.ChoiceField(label='Poll periodically', widget=forms.Select(attrs={'class': 'form-control', 'id': 'polling'}), choices=poll_choices) class AddServerForm(ModelForm): class Meta: model = TAXII_Remote_Server fields = ['name', 'host', 'path', 'port', 'protocol', 'version'] widgets = { 'name': widgets.TextInput(attrs={'id': 'post_server_name', 'class': 'form-control', 'placeholder': ''}), 'host': widgets.TextInput(attrs={'id': 'post_server_host', 'class': 'form-control', 'placeholder': ''}), 'port': widgets.NumberInput(attrs={'id': 'post_server_port', 'class': 'form-control', 'placeholder': '', 'readonly': True, 'required': True}), 'path': widgets.TextInput(attrs={'id': 'post_server_path', 'class': 'form-control', 'placeholder': ''}), 'version': widgets.TextInput(attrs={'id': 'post_server_version', 'class': 'form-control', 'placeholder': '', 'readonly': True, 'required': True}), 'protocol': widgets.TextInput(attrs={'id': 'post_server_protocol', 'class': 'form-control', 'placeholder': '', 'readonly': True, 'required': True}), } class AddCollectionForm(ModelForm): class Meta: <|code_end|> , continue by predicting the next line. Consider current file imports: from django import forms from django.forms import ModelForm, widgets from kraut_sharing.models import TAXII_Remote_Server, TAXII_Remote_Collection and context: # Path: kraut_sharing/models.py # class TAXII_Remote_Server(models.Model): # creation_time = models.DateTimeField(auto_now_add=True) # name = models.CharField(max_length=255, help_text="""Name/Identifier""") # host = models.CharField(max_length=255, help_text="""Hostname or IP address""") # port = models.IntegerField(help_text="""Remote port""", default=80) # protocol = models.CharField(max_length=5, help_text="""Protocol to use""", default="http") # path = models.CharField(max_length=255, help_text="""Path to service""") # version = models.CharField(max_length=5, help_text="""TAXII version to use""", default="1.1") # auth_type = models.IntegerField(default=0, help_text="""Authentication to use""") # last_discovery = models.DateTimeField(blank=True, null=True) # # TODO: fields for authentication (foreign key) # # TODO: proxy configuration # # def get_url(self): # return "%s://%s:%i%s" % (self.protocol, self.host, self.port, self.path) # # def __unicode__(self): # return u"%s (%s://%s:%i%s)" % (self.name, self.protocol, self.host, self.port, self.path) # # class Meta: # unique_together = (("name", "host", "port", "protocol", "path"),) # # class TAXII_Remote_Collection(models.Model): # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # name = models.CharField(max_length=255, help_text="""name of the collection""", unique=True) # begin_timestamp = models.DateTimeField(blank=True, null=True) # end_timestamp = models.DateTimeField(blank=True, null=True) # server = models.ForeignKey("TAXII_Remote_Server", on_delete=models.CASCADE) # subscribed = models.BooleanField(default=False) # collection_type = models.CharField(max_length=255, default="DATA-FEED") # poll_period = models.IntegerField(default=24, help_text="""poll period in hours (e.g. 24 = every 24 hours)""") # # def __unicode__(self): # return u"%s" % (self.name) which might include code, classes, or functions. Output only the next line.
model = TAXII_Remote_Collection
Here is a snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Create your models here. class UserExtension(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) icon = models.CharField(max_length=100, default="ns_icon/octalpus.png") <|code_end|> . Write the next line using the current file imports: from django.db import models from django.contrib.auth.models import User from kraut_parser.models import Namespace and context from other files: # Path: kraut_parser/models.py # class Namespace(models.Model): # namespace = models.CharField(max_length=255, default='nospace', unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.namespace) # # class Meta: # ordering = ['namespace'] , which may include functions, classes, or code. Output only the next line.
namespaces = models.ManyToManyField(Namespace, blank=True)
Given snippet: <|code_start|> current_user.set_password(n1_pass) update_session_auth_hash(request, request.user) current_user.save() messages.info(request, 'Password successfully changed!') else: messages.error(request, 'Failure updating password!') return HttpResponseRedirect(reverse("accounts:changepw")) context = {'form': PasswordChangeCustomForm()} if hasattr(request.user.userextension, 'namespaces'): context['usernamespace'] = request.user.userextension.namespaces.last().namespace.split(':')[0] context['namespaceicon'] = get_icon_for_namespace(request.user.userextension.namespaces.last().namespace) else: context['usernamespace'] = 'nospace' context['namespaceicon'] = static('ns_icon/octalpus.png') return render(request, 'kraut_accounts/changepw.html', context) def accounts_login(request): """log a user in """ context = {} if request.user.is_authenticated(): return HttpResponseRedirect(reverse("home")) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: if not hasattr(user, 'userextension'): <|code_end|> , continue by predicting the next line. Consider current file imports: from django.shortcuts import render from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.contrib.auth.hashers import check_password from django.http import HttpResponseRedirect from django.urls import reverse from django.template import RequestContext from django.contrib import messages from kraut_accounts.models import UserExtension from kraut_accounts.forms import PasswordChangeCustomForm from kraut_parser.models import Namespace from kraut_intel.utils import get_icon_for_namespace and context: # Path: kraut_accounts/models.py # class UserExtension(models.Model): # user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) # icon = models.CharField(max_length=100, default="ns_icon/octalpus.png") # namespaces = models.ManyToManyField(Namespace, blank=True) # # Path: kraut_accounts/forms.py # class PasswordChangeCustomForm(Form): # old_password = CharField(required=True, label="Old Password", widget=PasswordInput(attrs={'class': 'form-control'})) # new_password1 = CharField(required=True, label="New Password", widget=PasswordInput(attrs={'class': 'form-control'})) # new_password2 = CharField(required=True, label="Repeat New Password", widget=PasswordInput(attrs={'class': 'form-control'})) # # Path: kraut_parser/models.py # class Namespace(models.Model): # namespace = models.CharField(max_length=255, default='nospace', unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.namespace) # # class Meta: # ordering = ['namespace'] # # Path: kraut_intel/utils.py # def get_icon_for_namespace(namespace): # """ Return the static path to the icon associated with given namespace # """ # try: # if namespace.count(':')>0: # namespace = namespace.split(':')[0] # icon = NamespaceIcon.objects.get(namespace=namespace) # except Exception as e: # return static('ns_icon/octalpus.png') # return static('ns_icon/%s' % (icon.icon)) which might include code, classes, or functions. Output only the next line.
user_extension = UserExtension.objects.create(user=user)
Here is a snippet: <|code_start|> current_user.save() messages.info(request, 'Password successfully changed!') else: messages.error(request, 'Failure updating password!') return HttpResponseRedirect(reverse("accounts:changepw")) context = {'form': PasswordChangeCustomForm()} if hasattr(request.user.userextension, 'namespaces'): context['usernamespace'] = request.user.userextension.namespaces.last().namespace.split(':')[0] context['namespaceicon'] = get_icon_for_namespace(request.user.userextension.namespaces.last().namespace) else: context['usernamespace'] = 'nospace' context['namespaceicon'] = static('ns_icon/octalpus.png') return render(request, 'kraut_accounts/changepw.html', context) def accounts_login(request): """log a user in """ context = {} if request.user.is_authenticated(): return HttpResponseRedirect(reverse("home")) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: if not hasattr(user, 'userextension'): user_extension = UserExtension.objects.create(user=user) user_extension.save() <|code_end|> . Write the next line using the current file imports: from django.shortcuts import render from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.contrib.auth.hashers import check_password from django.http import HttpResponseRedirect from django.urls import reverse from django.template import RequestContext from django.contrib import messages from kraut_accounts.models import UserExtension from kraut_accounts.forms import PasswordChangeCustomForm from kraut_parser.models import Namespace from kraut_intel.utils import get_icon_for_namespace and context from other files: # Path: kraut_accounts/models.py # class UserExtension(models.Model): # user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) # icon = models.CharField(max_length=100, default="ns_icon/octalpus.png") # namespaces = models.ManyToManyField(Namespace, blank=True) # # Path: kraut_accounts/forms.py # class PasswordChangeCustomForm(Form): # old_password = CharField(required=True, label="Old Password", widget=PasswordInput(attrs={'class': 'form-control'})) # new_password1 = CharField(required=True, label="New Password", widget=PasswordInput(attrs={'class': 'form-control'})) # new_password2 = CharField(required=True, label="Repeat New Password", widget=PasswordInput(attrs={'class': 'form-control'})) # # Path: kraut_parser/models.py # class Namespace(models.Model): # namespace = models.CharField(max_length=255, default='nospace', unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.namespace) # # class Meta: # ordering = ['namespace'] # # Path: kraut_intel/utils.py # def get_icon_for_namespace(namespace): # """ Return the static path to the icon associated with given namespace # """ # try: # if namespace.count(':')>0: # namespace = namespace.split(':')[0] # icon = NamespaceIcon.objects.get(namespace=namespace) # except Exception as e: # return static('ns_icon/octalpus.png') # return static('ns_icon/%s' % (icon.icon)) , which may include functions, classes, or code. Output only the next line.
new_namespace = Namespace(namespace='nospace:http://nospace.com', description='no particular namespace')
Using the snippet: <|code_start|># Create your views here. def accounts_change_password(request): """change password """ if request.method == 'POST': form = PasswordChangeCustomForm(request.POST) if form.is_valid(): current_user = request.user # check if old password equals current password old_pass = form.cleaned_data['old_password'] n1_pass = form.cleaned_data['new_password1'] n2_pass = form.cleaned_data['new_password2'] if not current_user.check_password(old_pass): messages.error(request, 'Old password wrong!') return HttpResponseRedirect(reverse("accounts:changepw")) if n1_pass != n2_pass: messages.error(request, 'New password does not match!') return HttpResponseRedirect(reverse("accounts:changepw")) # change password current_user.set_password(n1_pass) update_session_auth_hash(request, request.user) current_user.save() messages.info(request, 'Password successfully changed!') else: messages.error(request, 'Failure updating password!') return HttpResponseRedirect(reverse("accounts:changepw")) context = {'form': PasswordChangeCustomForm()} if hasattr(request.user.userextension, 'namespaces'): context['usernamespace'] = request.user.userextension.namespaces.last().namespace.split(':')[0] <|code_end|> , determine the next line of code. You have imports: from django.shortcuts import render from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.contrib.auth.hashers import check_password from django.http import HttpResponseRedirect from django.urls import reverse from django.template import RequestContext from django.contrib import messages from kraut_accounts.models import UserExtension from kraut_accounts.forms import PasswordChangeCustomForm from kraut_parser.models import Namespace from kraut_intel.utils import get_icon_for_namespace and context (class names, function names, or code) available: # Path: kraut_accounts/models.py # class UserExtension(models.Model): # user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) # icon = models.CharField(max_length=100, default="ns_icon/octalpus.png") # namespaces = models.ManyToManyField(Namespace, blank=True) # # Path: kraut_accounts/forms.py # class PasswordChangeCustomForm(Form): # old_password = CharField(required=True, label="Old Password", widget=PasswordInput(attrs={'class': 'form-control'})) # new_password1 = CharField(required=True, label="New Password", widget=PasswordInput(attrs={'class': 'form-control'})) # new_password2 = CharField(required=True, label="Repeat New Password", widget=PasswordInput(attrs={'class': 'form-control'})) # # Path: kraut_parser/models.py # class Namespace(models.Model): # namespace = models.CharField(max_length=255, default='nospace', unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.namespace) # # class Meta: # ordering = ['namespace'] # # Path: kraut_intel/utils.py # def get_icon_for_namespace(namespace): # """ Return the static path to the icon associated with given namespace # """ # try: # if namespace.count(':')>0: # namespace = namespace.split(':')[0] # icon = NamespaceIcon.objects.get(namespace=namespace) # except Exception as e: # return static('ns_icon/octalpus.png') # return static('ns_icon/%s' % (icon.icon)) . Output only the next line.
context['namespaceicon'] = get_icon_for_namespace(request.user.userextension.namespaces.last().namespace)
Predict the next line for this snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Register your models here. admin.site.register(Asset) admin.site.register(Incident) admin.site.register(Incident_Category) <|code_end|> with the help of current file imports: from django.contrib import admin from kraut_incident.models import Asset, Incident, Incident_Category, Incident_Status, Contact, Task, TemplateTask and context from other files: # Path: kraut_incident/models.py # class Asset(models.Model): # """Describe an asset and its role in an incident # """ # asset_type = models.CharField(max_length=255, default="Unknown Type") # description = models.TextField(null=True, blank=True) # status = models.ForeignKey(Asset_Status, on_delete=models.CASCADE) # hostname = models.CharField(max_length=255, null=True, blank=True) # domain = models.CharField(max_length=255, null=True, blank=True) # ip_addresses = models.ManyToManyField(Asset_IP, blank=True) # contacts = models.ManyToManyField(Contact, blank=True) # activities = models.ManyToManyField(Asset_Attacker_Activity, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # accounts = models.ManyToManyField(Account, blank=True) # # class Incident(models.Model): # """Describe a security incident # """ # incident_number = models.IntegerField(unique=True, default=random_incident_number) # title = models.CharField(max_length=255, default="Unnamed Incident") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # status = models.ForeignKey(Incident_Status, on_delete=models.CASCADE) # category = models.ForeignKey(Incident_Category, on_delete=models.CASCADE) # affected_assets = models.ManyToManyField(Asset, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # incident_handler = models.ManyToManyField(Handler, blank=True, related_name="incident_handler") # contacts = models.ManyToManyField(Contact, blank=True, related_name="contacts") # severity_choices = ( # ('h', 'High'), # ('m', 'Medium'), # ('l', 'Low'), # ) # severity = models.CharField(max_length=2, choices=severity_choices, default='m') # # def __unicode__(self): # return u"%s" % (self.title) # # class Incident_Category(models.Model): # """Describe the category of an incident # Prefilled with data # """ # name = models.CharField(max_length=255, unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class Incident_Status(models.Model): # """Describe the status of an incident # Prefilled with data # """ # name = models.CharField(max_length=255, unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class Contact(models.Model): # """Describe a contact person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class Task(models.Model): # """Describe a task to be performed # """ # name = models.CharField(max_length=255, default="Yet another task") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # finish_time = models.DateTimeField(null=True, blank=True) # status_choices = ( # ('op', 'Open'), # ('do', 'Done'), # ('ab', 'Aborted'), # ) # status = models.CharField(max_length=2, choices=status_choices, default='op') # responsible = models.ManyToManyField(Contact, blank=True) # # class Meta: # ordering = ['-status'] # # class TemplateTask(models.Model): # """Describe a template for a task to attach to an incident # """ # name = models.CharField(max_length=255, default="Template Task") # description = models.TextField(null=True, blank=True, default="Task Description") , which may contain function names, class names, or code. Output only the next line.
admin.site.register(Incident_Status)
Given the following code snippet before the placeholder: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Register your models here. admin.site.register(Asset) admin.site.register(Incident) admin.site.register(Incident_Category) admin.site.register(Incident_Status) <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from kraut_incident.models import Asset, Incident, Incident_Category, Incident_Status, Contact, Task, TemplateTask and context including class names, function names, and sometimes code from other files: # Path: kraut_incident/models.py # class Asset(models.Model): # """Describe an asset and its role in an incident # """ # asset_type = models.CharField(max_length=255, default="Unknown Type") # description = models.TextField(null=True, blank=True) # status = models.ForeignKey(Asset_Status, on_delete=models.CASCADE) # hostname = models.CharField(max_length=255, null=True, blank=True) # domain = models.CharField(max_length=255, null=True, blank=True) # ip_addresses = models.ManyToManyField(Asset_IP, blank=True) # contacts = models.ManyToManyField(Contact, blank=True) # activities = models.ManyToManyField(Asset_Attacker_Activity, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # accounts = models.ManyToManyField(Account, blank=True) # # class Incident(models.Model): # """Describe a security incident # """ # incident_number = models.IntegerField(unique=True, default=random_incident_number) # title = models.CharField(max_length=255, default="Unnamed Incident") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # status = models.ForeignKey(Incident_Status, on_delete=models.CASCADE) # category = models.ForeignKey(Incident_Category, on_delete=models.CASCADE) # affected_assets = models.ManyToManyField(Asset, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # incident_handler = models.ManyToManyField(Handler, blank=True, related_name="incident_handler") # contacts = models.ManyToManyField(Contact, blank=True, related_name="contacts") # severity_choices = ( # ('h', 'High'), # ('m', 'Medium'), # ('l', 'Low'), # ) # severity = models.CharField(max_length=2, choices=severity_choices, default='m') # # def __unicode__(self): # return u"%s" % (self.title) # # class Incident_Category(models.Model): # """Describe the category of an incident # Prefilled with data # """ # name = models.CharField(max_length=255, unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class Incident_Status(models.Model): # """Describe the status of an incident # Prefilled with data # """ # name = models.CharField(max_length=255, unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class Contact(models.Model): # """Describe a contact person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class Task(models.Model): # """Describe a task to be performed # """ # name = models.CharField(max_length=255, default="Yet another task") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # finish_time = models.DateTimeField(null=True, blank=True) # status_choices = ( # ('op', 'Open'), # ('do', 'Done'), # ('ab', 'Aborted'), # ) # status = models.CharField(max_length=2, choices=status_choices, default='op') # responsible = models.ManyToManyField(Contact, blank=True) # # class Meta: # ordering = ['-status'] # # class TemplateTask(models.Model): # """Describe a template for a task to attach to an incident # """ # name = models.CharField(max_length=255, default="Template Task") # description = models.TextField(null=True, blank=True, default="Task Description") . Output only the next line.
admin.site.register(Contact)
Next line prediction: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Register your models here. admin.site.register(Asset) admin.site.register(Incident) admin.site.register(Incident_Category) admin.site.register(Incident_Status) admin.site.register(Contact) <|code_end|> . Use current file imports: (from django.contrib import admin from kraut_incident.models import Asset, Incident, Incident_Category, Incident_Status, Contact, Task, TemplateTask) and context including class names, function names, or small code snippets from other files: # Path: kraut_incident/models.py # class Asset(models.Model): # """Describe an asset and its role in an incident # """ # asset_type = models.CharField(max_length=255, default="Unknown Type") # description = models.TextField(null=True, blank=True) # status = models.ForeignKey(Asset_Status, on_delete=models.CASCADE) # hostname = models.CharField(max_length=255, null=True, blank=True) # domain = models.CharField(max_length=255, null=True, blank=True) # ip_addresses = models.ManyToManyField(Asset_IP, blank=True) # contacts = models.ManyToManyField(Contact, blank=True) # activities = models.ManyToManyField(Asset_Attacker_Activity, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # accounts = models.ManyToManyField(Account, blank=True) # # class Incident(models.Model): # """Describe a security incident # """ # incident_number = models.IntegerField(unique=True, default=random_incident_number) # title = models.CharField(max_length=255, default="Unnamed Incident") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # status = models.ForeignKey(Incident_Status, on_delete=models.CASCADE) # category = models.ForeignKey(Incident_Category, on_delete=models.CASCADE) # affected_assets = models.ManyToManyField(Asset, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # incident_handler = models.ManyToManyField(Handler, blank=True, related_name="incident_handler") # contacts = models.ManyToManyField(Contact, blank=True, related_name="contacts") # severity_choices = ( # ('h', 'High'), # ('m', 'Medium'), # ('l', 'Low'), # ) # severity = models.CharField(max_length=2, choices=severity_choices, default='m') # # def __unicode__(self): # return u"%s" % (self.title) # # class Incident_Category(models.Model): # """Describe the category of an incident # Prefilled with data # """ # name = models.CharField(max_length=255, unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class Incident_Status(models.Model): # """Describe the status of an incident # Prefilled with data # """ # name = models.CharField(max_length=255, unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class Contact(models.Model): # """Describe a contact person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class Task(models.Model): # """Describe a task to be performed # """ # name = models.CharField(max_length=255, default="Yet another task") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # finish_time = models.DateTimeField(null=True, blank=True) # status_choices = ( # ('op', 'Open'), # ('do', 'Done'), # ('ab', 'Aborted'), # ) # status = models.CharField(max_length=2, choices=status_choices, default='op') # responsible = models.ManyToManyField(Contact, blank=True) # # class Meta: # ordering = ['-status'] # # class TemplateTask(models.Model): # """Describe a template for a task to attach to an incident # """ # name = models.CharField(max_length=255, default="Template Task") # description = models.TextField(null=True, blank=True, default="Task Description") . Output only the next line.
admin.site.register(Task)
Predict the next line after this snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # Register your models here. admin.site.register(Asset) admin.site.register(Incident) admin.site.register(Incident_Category) admin.site.register(Incident_Status) admin.site.register(Contact) admin.site.register(Task) <|code_end|> using the current file's imports: from django.contrib import admin from kraut_incident.models import Asset, Incident, Incident_Category, Incident_Status, Contact, Task, TemplateTask and any relevant context from other files: # Path: kraut_incident/models.py # class Asset(models.Model): # """Describe an asset and its role in an incident # """ # asset_type = models.CharField(max_length=255, default="Unknown Type") # description = models.TextField(null=True, blank=True) # status = models.ForeignKey(Asset_Status, on_delete=models.CASCADE) # hostname = models.CharField(max_length=255, null=True, blank=True) # domain = models.CharField(max_length=255, null=True, blank=True) # ip_addresses = models.ManyToManyField(Asset_IP, blank=True) # contacts = models.ManyToManyField(Contact, blank=True) # activities = models.ManyToManyField(Asset_Attacker_Activity, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # accounts = models.ManyToManyField(Account, blank=True) # # class Incident(models.Model): # """Describe a security incident # """ # incident_number = models.IntegerField(unique=True, default=random_incident_number) # title = models.CharField(max_length=255, default="Unnamed Incident") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # status = models.ForeignKey(Incident_Status, on_delete=models.CASCADE) # category = models.ForeignKey(Incident_Category, on_delete=models.CASCADE) # affected_assets = models.ManyToManyField(Asset, blank=True) # tasks = models.ManyToManyField(Task, blank=True) # incident_handler = models.ManyToManyField(Handler, blank=True, related_name="incident_handler") # contacts = models.ManyToManyField(Contact, blank=True, related_name="contacts") # severity_choices = ( # ('h', 'High'), # ('m', 'Medium'), # ('l', 'Low'), # ) # severity = models.CharField(max_length=2, choices=severity_choices, default='m') # # def __unicode__(self): # return u"%s" % (self.title) # # class Incident_Category(models.Model): # """Describe the category of an incident # Prefilled with data # """ # name = models.CharField(max_length=255, unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class Incident_Status(models.Model): # """Describe the status of an incident # Prefilled with data # """ # name = models.CharField(max_length=255, unique=True) # description = models.TextField(null=True, blank=True) # # def __unicode__(self): # return u"%s" % (self.name) # # class Contact(models.Model): # """Describe a contact person # """ # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # phone = models.CharField(max_length=255, blank=True) # email = models.EmailField(max_length=255) # description = models.TextField(null=True, blank=True) # # class Meta: # unique_together = (("firstname", "lastname", "email"),) # # class Task(models.Model): # """Describe a task to be performed # """ # name = models.CharField(max_length=255, default="Yet another task") # description = models.TextField(null=True, blank=True) # creation_time = models.DateTimeField(auto_now_add=True) # finish_time = models.DateTimeField(null=True, blank=True) # status_choices = ( # ('op', 'Open'), # ('do', 'Done'), # ('ab', 'Aborted'), # ) # status = models.CharField(max_length=2, choices=status_choices, default='op') # responsible = models.ManyToManyField(Contact, blank=True) # # class Meta: # ordering = ['-status'] # # class TemplateTask(models.Model): # """Describe a template for a task to attach to an incident # """ # name = models.CharField(max_length=255, default="Template Task") # description = models.TextField(null=True, blank=True, default="Task Description") . Output only the next line.
admin.site.register(TemplateTask)
Using the snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # import database models class Command(BaseCommand): def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) def handle(self, *args, **options): <|code_end|> , determine the next line of code. You have imports: from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.db.models import Count from kraut_parser.models import Package and context (class names, function names, or code) available: # Path: kraut_parser/models.py # class Package(models.Model): # name = models.CharField(max_length=255) # creation_time = models.DateTimeField(auto_now_add=True) # last_modified = models.DateTimeField(auto_now=True) # description = models.TextField(null=True, blank=True) # short_description = models.CharField(max_length=255, null=True, blank=True) # namespace = models.ManyToManyField('Namespace', blank=True) # version = models.CharField(max_length=255) # package_id = models.CharField(max_length=255) # source = models.CharField(max_length=255) # produced_time = models.DateTimeField(null=True, blank=True) # threat_actors = models.ManyToManyField('ThreatActor', blank=True) # campaigns = models.ManyToManyField('Campaign', blank=True) # indicators = models.ManyToManyField('Indicator', blank=True) # observables = models.ManyToManyField('Observable', blank=True) # ttps = models.ManyToManyField('TTP', blank=True) # # def __unicode__(self): # return u"%s" % (self.name) . Output only the next line.
p = Package.objects.filter(package_id='edge:Package-a7b3f172-5204-473f-b77d-bce34d071611')
Predict the next line after this snippet: <|code_start|># vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 def get_icon_for_namespace(namespace): """ Return the static path to the icon associated with given namespace """ try: if namespace.count(':')>0: namespace = namespace.split(':')[0] <|code_end|> using the current file's imports: from django.templatetags.static import static from kraut_intel.models import NamespaceIcon and any relevant context from other files: # Path: kraut_intel/models.py # class NamespaceIcon(models.Model): # namespace = models.CharField(max_length=255, unique=True) # icon = models.CharField(max_length=255) # # def __unicode__(self): # return u"%s (%s)" % (self.namespace, self.icon) . Output only the next line.
icon = NamespaceIcon.objects.get(namespace=namespace)
Given snippet: <|code_start|> link_dict['condition'] = li_obj['value'].get('condition', 'equals').lower() if 'url_label' in li_obj: if isinstance(li_obj['url_label'], dict): link_dict['url_label'] = li_obj['url_label'].get('value', 'No Label') if 'type' in li_obj: link_dict['link_type'] = li_obj.get('type', 'No Type') return link_dict def handle_dns_query_object(dns_obj): query_dict = { 'qname': None, 'qtype': None, 'qclass': None, } if 'question' in dns_obj: query_dict['qclass'] = dns_obj['question'].get('qclass', None) query_dict['qtype'] = dns_obj['question'].get('qtype', None) qname = dns_obj['question'].get('qname', None) if isinstance(qname, dict): uri_dict = { 'uri_value': qname.get('value', 'No Value'), 'uri_type': 'Domain Name', 'condition': 'equals' } else: uri_dict = { 'uri_value': qname, 'uri_type': 'Domain Name', 'condition': 'equals' } <|code_end|> , continue by predicting the next line. Consider current file imports: import dateutil, pytz, json from kraut_parser.models import URI_Object, Port_Object and context: # Path: kraut_parser/models.py # class URI_Object(models.Model): # uri_value = models.CharField(max_length=255) # uri_type = models.CharField(max_length=255) # condition = models.CharField(max_length=255, default="equals") # observables = models.ManyToManyField(Observable) # # def __unicode__(self): # if self.uri_value: # return u"%s" % (self.uri_value) # else: # return u"URI Object" # # class Meta: # unique_together = (("uri_value", "uri_type", "condition"),) # # class Port_Object(models.Model): # port = models.IntegerField(unique=True) # # def __unicode__(self): # return u"%s" % (self.port) which might include code, classes, or functions. Output only the next line.
uri_object, uri_object_created = URI_Object.objects.get_or_create(**uri_dict)
Based on the snippet: <|code_start|> 'message_body': None, 'request_method': 'GET', 'request_uri': '/', 'request_version': '1.1', 'user_agent': None, 'domain_name': None, 'port': None, } # get message body if 'http_client_request' in request and 'http_message_body' in request['http_client_request']: client_dict['message_body'] = request['http_client_request']['http_message_body'].get('message_body', None) # get raw header if 'http_client_request' in request and 'http_request_header' in request['http_client_request']: client_dict['raw_header'] = request['http_client_request']['http_request_header'].get('raw_header', None) # get host information if 'parsed_header' in request['http_client_request']['http_request_header']: host = request['http_client_request']['http_request_header']['parsed_header'].get('host', None) if host: if 'domain_name' in host: uri_dict = { 'uri_value': host['domain_name'].get('value', 'No Value'), 'uri_type': 'Domain Name', 'condition': 'equals' } uri_object, uri_object_created = URI_Object.objects.get_or_create(**uri_dict) client_dict['domain_name'] = uri_object if 'port' in host: port_dict = { 'port': host['port'].get('port_value', 'No Value') } <|code_end|> , predict the immediate next line with the help of imports: import dateutil, pytz, json from kraut_parser.models import URI_Object, Port_Object and context (classes, functions, sometimes code) from other files: # Path: kraut_parser/models.py # class URI_Object(models.Model): # uri_value = models.CharField(max_length=255) # uri_type = models.CharField(max_length=255) # condition = models.CharField(max_length=255, default="equals") # observables = models.ManyToManyField(Observable) # # def __unicode__(self): # if self.uri_value: # return u"%s" % (self.uri_value) # else: # return u"URI Object" # # class Meta: # unique_together = (("uri_value", "uri_type", "condition"),) # # class Port_Object(models.Model): # port = models.IntegerField(unique=True) # # def __unicode__(self): # return u"%s" % (self.port) . Output only the next line.
port_object, port_object_created = Port_Object.objects.get_or_create(**port_dict)
Next line prediction: <|code_start|>Cookie handling classese """ try: except ImportError: class RequestCookieHandler(object): """ Class for handling all things regarding to cookies in pyroutes request objects. """ def __init__(self, environ=None): if environ and 'HTTP_COOKIE' in environ: self._raw_cookies = dict( [part.strip() for part in c.split('=', 1)] for c in environ['HTTP_COOKIE'].split(';')) else: self._raw_cookies = {} def __repr__(self): return u'%s' % self._raw_cookies def get_cookie(self, key): """ Return a signed cookie value if it exists. """ if key in self._raw_cookies: if '%s_hash' % key in self._raw_cookies: <|code_end|> . Use current file imports: (import hmac import sha as sha1 from hashlib import sha1 from pyroutes import settings) and context including class names, function names, or small code snippets from other files: # Path: pyroutes/settings.py # BUILTIN_TEMPLATES_DIR = os.path.join( # os.path.dirname(__file__), # 'default_templates' # ) # BUILTIN_BASE_TEMPLATE = 'base.xml' # DEBUG = False # DEFAULT_CONTENT_TYPE = 'text/html; charset=utf-8' # SECRET_KEY = None # TEMPLATE_DIR = None # /foo/bar/templates/ # MIDDLEWARE = ( # 'pyroutes.middleware.errors.NotFoundMiddleware', # #'pyroutes.middleware.appendslash.AppendSlashes', # 'pyroutes.middleware.responsify.Responsify', # 'pyroutes.middleware.errors.ErrorHandlerMiddleware', # ) . Output only the next line.
if settings.SECRET_KEY is None:
Given snippet: <|code_start|>#encoding: utf-8 try: except ImportError: class TestRequestCookieHandler(unittest.TestCase): def setUp(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import hmac import sha as sha1 import datetime import datetime from hashlib import sha1 from pyroutes.http.cookies import * from pyroutes import settings and context: # Path: pyroutes/settings.py # BUILTIN_TEMPLATES_DIR = os.path.join( # os.path.dirname(__file__), # 'default_templates' # ) # BUILTIN_BASE_TEMPLATE = 'base.xml' # DEBUG = False # DEFAULT_CONTENT_TYPE = 'text/html; charset=utf-8' # SECRET_KEY = None # TEMPLATE_DIR = None # /foo/bar/templates/ # MIDDLEWARE = ( # 'pyroutes.middleware.errors.NotFoundMiddleware', # #'pyroutes.middleware.appendslash.AppendSlashes', # 'pyroutes.middleware.responsify.Responsify', # 'pyroutes.middleware.errors.ErrorHandlerMiddleware', # ) which might include code, classes, or functions. Output only the next line.
settings.SECRET_KEY = 'asdfnaj2308sydfahli37flas36al9gaiufw'
Predict the next line after this snippet: <|code_start|># encoding: utf-8 """ This module contains only the Request class, a key class in pyroutes. Request objects hold all meta about incoming requests. """ try: except ImportError: class Request(object): """ The pyroutes Request object. Contains all information about a request, like GET/POST and environment data. """ def __init__(self, environment): self.GET = {} self.POST = {} self.PUT = {} self.FILES = {} self.ENV = environment self.extract_get_data() self.extract_post_data() self.extract_put_data() <|code_end|> using the current file's imports: from cgi import parse_qsl, FieldStorage from pyroutes.http.cookies import RequestCookieHandler from cStringIO import StringIO from StringIO import StringIO and any relevant context from other files: # Path: pyroutes/http/cookies.py # class RequestCookieHandler(object): # """ # Class for handling all things regarding to cookies in pyroutes request # objects. # """ # # def __init__(self, environ=None): # if environ and 'HTTP_COOKIE' in environ: # self._raw_cookies = dict( # [part.strip() for part in c.split('=', 1)] # for c in environ['HTTP_COOKIE'].split(';')) # else: # self._raw_cookies = {} # # def __repr__(self): # return u'%s' % self._raw_cookies # # def get_cookie(self, key): # """ # Return a signed cookie value if it exists. # """ # if key in self._raw_cookies: # if '%s_hash' % key in self._raw_cookies: # if settings.SECRET_KEY is None: # raise CookieKeyMissing( # 'Set SECRET_KEY in settings to use cookies') # cookie_hash = self._raw_cookies['%s_hash' % key] # value_hash = hmac.HMAC(settings.SECRET_KEY, key + # self._raw_cookies[key], sha1).hexdigest() # if cookie_hash == value_hash: # return self._raw_cookies[key] # else: # raise CookieHashInvalid(key, 'Cookie modified') # else: # raise CookieHashMissing(key, 'Cookie hash missing') # else: # return None # # def get_unsigned_cookie(self, key): # """ # Return an unsigned cookie value. (Plain old-fashion cookie reading) # """ # if key in self._raw_cookies: # return self._raw_cookies[key] # else: # return None . Output only the next line.
self.COOKIES = RequestCookieHandler(environment)
Using the snippet: <|code_start|> class TestDevServer(unittest.TestCase): def test_presence(self): utils.devserver class TestFileServer(unittest.TestCase): def setUp(self): self.request_env = {} wsgiref.util.setup_testing_defaults(self.request_env) <|code_end|> , determine the next line of code. You have imports: from datetime import datetime, timedelta from pyroutes.http.response import * from pyroutes.http.request import Request import os import unittest import wsgiref.util import pyroutes.settings as settings import pyroutes.utils as utils and context (class names, function names, or code) available: # Path: pyroutes/http/request.py # class Request(object): # """ # The pyroutes Request object. # Contains all information about a request, # like GET/POST and environment data. # """ # # def __init__(self, environment): # self.GET = {} # self.POST = {} # self.PUT = {} # self.FILES = {} # self.ENV = environment # # self.extract_get_data() # self.extract_post_data() # self.extract_put_data() # # self.COOKIES = RequestCookieHandler(environment) # self.params = {} # # self.matched_path = None # # def __repr__(self): # values = (self.GET, self.POST, self.PUT, self.COOKIES, # self.FILES.keys()) # return "GET: %s\nPOST: %s\nPUT: %s\nCOOKIES: %s\nFILES: %s" % values # # def extract_put_data(self): # """Extracts the file pointer from a PUT request. # # The PUT method allows you to write the contents of the file to the # socket connection that is established with the server directly. # # According to the [HTTP/1.1 specification (RFC2616)][0], the server # must return a status code of 201 (Created) if the file in question # is newly created, and 200 (OK) or 204 (No Content) if the request # results in a successful update. # # When using the POST method, all the fields and files are combined # into a single multipart/form-data type object, and this has to be # decoded by the server side handler. # # [0]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html # # """ # if self.ENV.get('REQUEST_METHOD', 'GET') == 'PUT': # if hasattr(self.ENV['wsgi.input'], 'read'): # self.PUT = self.ENV['wsgi.input'] # # def extract_post_data(self): # "Populates the POST variable" # data = {} # # # Copy enviroment so we dont get GET-variables in the result. # env = self.ENV.copy() # env['QUERY_STRING'] = '' # # if env.get('REQUEST_METHOD', 'GET') == 'POST': # _data = FieldStorage( # fp=self.ENV['wsgi.input'], # environ=env, # keep_blank_values=False # ) # for key in _data.keys(): # value = self._parse_field(_data[key], key, _data) # if value is not None: # self._assign_field_to_section(key, value, data) # # self.POST = data # # def extract_get_data(self): # "Populates the GET variable from environment" # ret_dict = {} # for (key, value) in parse_qsl(self.ENV.get('QUERY_STRING', '')): # if key in ret_dict: # if not isinstance(ret_dict[key], list): # ret_dict[key] = [ret_dict[key]] # ret_dict[key].append(value) # else: # ret_dict[key] = value # self.GET = ret_dict # # def _assign_field_to_section(self, key, value, storage): # if isinstance(value, list): # for val in value: # self._assign_field_to_section(key, val, storage) # else: # if (isinstance(value, tuple) and value[1] and # (isinstance(value[1], file) or hasattr(value[1], 'read'))): # # # If an existing value exists for this key, convert to # # list-result # if key in self.FILES and \ # not isinstance(self.FILES[key], list): # self.FILES[key] = [self.FILES[key]] # # if key in self.FILES and isinstance(self.FILES[key], list): # self.FILES[key].append(value) # else: # self.FILES[key] = value # elif isinstance(value, basestring): # # If an existing value exists for this key, # # convert to list-result # if key in storage and not isinstance(storage[key], list): # storage[key] = [storage[key]] # # if key in storage and isinstance(storage[key], list): # storage[key].append(value) # else: # storage[key] = value # # def _parse_field(self, field, key, data): # value = data.getvalue(key) # # if isinstance(field, list): # value = [self._parse_field(f, key, data) for f in field] # # elif hasattr(field, 'filename') and field.filename: # if field.file: # value = (field.filename, field.file) # else: # value = (field.filename, StringIO(data.getvalue(key))) # # elif isinstance(value, basestring): # try: # value = unicode(value, 'utf-8') # except UnicodeDecodeError: # # If we can't understand the data as utf, try latin1 # value = unicode(value, 'iso-8859-1') # # return value . Output only the next line.
self.request = Request(self.request_env)
Predict the next line for this snippet: <|code_start|>""" A module containing a primitive timing middleware. """ class TimingMiddleware(object): """ This middleware add a timing number at the bottom of the page if settings.DEBUG is True if the response content type is text/html or application/xhtml+xml Primitive profiling, but quite useful. """ def __init__(self, passthrough, route): self.passthrough = passthrough def __call__(self, request): <|code_end|> with the help of current file imports: import time from pyroutes import settings and context from other files: # Path: pyroutes/settings.py # BUILTIN_TEMPLATES_DIR = os.path.join( # os.path.dirname(__file__), # 'default_templates' # ) # BUILTIN_BASE_TEMPLATE = 'base.xml' # DEBUG = False # DEFAULT_CONTENT_TYPE = 'text/html; charset=utf-8' # SECRET_KEY = None # TEMPLATE_DIR = None # /foo/bar/templates/ # MIDDLEWARE = ( # 'pyroutes.middleware.errors.NotFoundMiddleware', # #'pyroutes.middleware.appendslash.AppendSlashes', # 'pyroutes.middleware.responsify.Responsify', # 'pyroutes.middleware.errors.ErrorHandlerMiddleware', # ) , which may contain function names, class names, or code. Output only the next line.
if not settings.DEBUG:
Given the following code snippet before the placeholder: <|code_start|>""" The pyroutes Dispatcher class and supporting methods. Core handling code that is run for all incoming requests. """ class Dispatcher(object): """ The pyroutes Dispatcher object. An instance of this object is kept directly on the pyroutes module for all dispatching purposes. """ def dispatch(self, environ, start_response): """ Dispathes a request. The call signature is that of a standard WSGI application. """ # Update site root value so pyroutes can make root-relative path # redirects if not hasattr(settings, 'SITE_ROOT'): settings.SITE_ROOT = environ.get('SCRIPT_NAME', '').rstrip('/') <|code_end|> , predict the next line using imports from the current file: import pyroutes import pyroutes.settings as settings from pyroutes.http.request import Request and context including class names, function names, and sometimes code from other files: # Path: pyroutes/http/request.py # class Request(object): # """ # The pyroutes Request object. # Contains all information about a request, # like GET/POST and environment data. # """ # # def __init__(self, environment): # self.GET = {} # self.POST = {} # self.PUT = {} # self.FILES = {} # self.ENV = environment # # self.extract_get_data() # self.extract_post_data() # self.extract_put_data() # # self.COOKIES = RequestCookieHandler(environment) # self.params = {} # # self.matched_path = None # # def __repr__(self): # values = (self.GET, self.POST, self.PUT, self.COOKIES, # self.FILES.keys()) # return "GET: %s\nPOST: %s\nPUT: %s\nCOOKIES: %s\nFILES: %s" % values # # def extract_put_data(self): # """Extracts the file pointer from a PUT request. # # The PUT method allows you to write the contents of the file to the # socket connection that is established with the server directly. # # According to the [HTTP/1.1 specification (RFC2616)][0], the server # must return a status code of 201 (Created) if the file in question # is newly created, and 200 (OK) or 204 (No Content) if the request # results in a successful update. # # When using the POST method, all the fields and files are combined # into a single multipart/form-data type object, and this has to be # decoded by the server side handler. # # [0]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html # # """ # if self.ENV.get('REQUEST_METHOD', 'GET') == 'PUT': # if hasattr(self.ENV['wsgi.input'], 'read'): # self.PUT = self.ENV['wsgi.input'] # # def extract_post_data(self): # "Populates the POST variable" # data = {} # # # Copy enviroment so we dont get GET-variables in the result. # env = self.ENV.copy() # env['QUERY_STRING'] = '' # # if env.get('REQUEST_METHOD', 'GET') == 'POST': # _data = FieldStorage( # fp=self.ENV['wsgi.input'], # environ=env, # keep_blank_values=False # ) # for key in _data.keys(): # value = self._parse_field(_data[key], key, _data) # if value is not None: # self._assign_field_to_section(key, value, data) # # self.POST = data # # def extract_get_data(self): # "Populates the GET variable from environment" # ret_dict = {} # for (key, value) in parse_qsl(self.ENV.get('QUERY_STRING', '')): # if key in ret_dict: # if not isinstance(ret_dict[key], list): # ret_dict[key] = [ret_dict[key]] # ret_dict[key].append(value) # else: # ret_dict[key] = value # self.GET = ret_dict # # def _assign_field_to_section(self, key, value, storage): # if isinstance(value, list): # for val in value: # self._assign_field_to_section(key, val, storage) # else: # if (isinstance(value, tuple) and value[1] and # (isinstance(value[1], file) or hasattr(value[1], 'read'))): # # # If an existing value exists for this key, convert to # # list-result # if key in self.FILES and \ # not isinstance(self.FILES[key], list): # self.FILES[key] = [self.FILES[key]] # # if key in self.FILES and isinstance(self.FILES[key], list): # self.FILES[key].append(value) # else: # self.FILES[key] = value # elif isinstance(value, basestring): # # If an existing value exists for this key, # # convert to list-result # if key in storage and not isinstance(storage[key], list): # storage[key] = [storage[key]] # # if key in storage and isinstance(storage[key], list): # storage[key].append(value) # else: # storage[key] = value # # def _parse_field(self, field, key, data): # value = data.getvalue(key) # # if isinstance(field, list): # value = [self._parse_field(f, key, data) for f in field] # # elif hasattr(field, 'filename') and field.filename: # if field.file: # value = (field.filename, field.file) # else: # value = (field.filename, StringIO(data.getvalue(key))) # # elif isinstance(value, basestring): # try: # value = unicode(value, 'utf-8') # except UnicodeDecodeError: # # If we can't understand the data as utf, try latin1 # value = unicode(value, 'iso-8859-1') # # return value . Output only the next line.
request = Request(environ)
Predict the next line after this snippet: <|code_start|>""" Middleware for making non-response objects into Responses """ class Responsify(object): """ If a non-response object s (e.g a string) is passed, returns Response(s) This allows e.g >>> @route('/') >>> def foo(request): >>> return 'Hello, world!' or >>> bar = lambda x: 'Hello, lambda world!' >>> route('/')(bar) """ def __init__(self, passthrough, route): self.passthrough = passthrough def __call__(self, request): response = self.passthrough(request) <|code_end|> using the current file's imports: from pyroutes.http.response import Response and any relevant context from other files: # Path: pyroutes/http/response.py # class Response(object): # """ # A wrapper class for a response to a route. Takes # a content, headers and status_code parameter. # headers should be passed in as a list of tuples. # status_code can be a string including status name, or an integer. # If default_content_header is set and no Content-Type header is set, # settings.DEFAULT_CONTENT_TYPE is added as Content-Type. # """ # def __init__(self, content=None, headers=None, status_code='200 OK', # default_content_header=True): # if content is None: # self.content = [] # else: # self.content = content # # header_names = [] # if headers: # header_names = [header[0] for header in headers] # # self.headers = [] # if default_content_header and 'Content-Type' not in header_names: # self.headers.append(('Content-Type', settings.DEFAULT_CONTENT_TYPE)) # if not headers is None: # self.headers += headers # # if status_code in _RESPONSES: # self.status_code = "%s %s" % (status_code, _RESPONSES[status_code]) # else: # self.status_code = status_code # # self.cookies = ResponseCookieHandler() . Output only the next line.
if not isinstance(response, Response):
Using the snippet: <|code_start|> parser = argparse.ArgumentParser(prog='nimoy', description='Run a suite of Nimoy specs.') parser.add_argument('--power-assertions', metavar='P', type=bool, nargs=1, default=False, help="Should Nimoy evaluate comparison expressions using power assertions (beta)") parser.add_argument('specs', metavar='S', type=str, nargs='*', help="""A path to a spec file to execute or a directory to scan for spec files. When naming a file it is possible to select which spec or feature to run. some_spec.py[::SpecName[::feature_name]] """) args = parser.parse_args() spec_locations = SpecRunner._find_specs(args) spec_locations_and_contents = SpecRunner._read_specs(spec_locations) return SpecRunner._run_on_contents(RunnerContext(use_power_assertions=args.power_assertions), execution_framework, spec_locations_and_contents) @staticmethod def _run_on_contents(runner_context: RunnerContext, execution_framework, spec_locations_and_contents): specs = SpecRunner._load_specs(runner_context, spec_locations_and_contents) return SpecRunner._execute_specs(execution_framework, specs) @staticmethod def _find_specs(args): return SpecFinder(os.getcwd()).find(args.specs) @staticmethod def _read_specs(spec_locations): return SpecReader(fs_resource_reader).read(spec_locations) @staticmethod def _load_specs(runner_context: RunnerContext, spec_locations_and_contents): <|code_end|> , determine the next line of code. You have imports: import argparse import os from nimoy.ast_tools import ast_chain from nimoy.runner import fs_resource_reader from nimoy.runner.metadata import RunnerContext from nimoy.runner.spec_executor import SpecExecutor from nimoy.runner.spec_finder import SpecFinder from nimoy.runner.spec_loader import SpecLoader from nimoy.runner.spec_reader import SpecReader and context (class names, function names, or code) available: # Path: nimoy/ast_tools/ast_chain.py # def apply(runner_context: RunnerContext, spec_location, node): # # Path: nimoy/runner/metadata.py # class RunnerContext: # # def __init__(self, use_power_assertions: bool = False): # self.use_power_assertions = use_power_assertions # # Path: nimoy/runner/spec_executor.py # class SpecExecutor: # def __init__(self, execution_framework) -> None: # super().__init__() # self.execution_framework = execution_framework # # def execute(self, specs): # for spec_metadata in specs: # spec_class_module = spec_metadata.owning_module # # for spec_feature in spec_metadata.features: # self.execution_framework.append_test(spec_class_module(spec_feature)) # # return self.execution_framework.run() # # Path: nimoy/runner/spec_finder.py # class SpecFinder: # def __init__(self, working_directory) -> None: # super().__init__() # self.working_directory = working_directory # self.spec_locations = [] # # def find(self, suggested_locations): # if not suggested_locations: # suggested_locations.append(self.working_directory) # self._find_specs_in_suggested_locations(suggested_locations) # # return self.spec_locations # # def _find_specs_in_suggested_locations(self, suggested_locations): # # for suggested_location in suggested_locations: # normalized_suggested_location = self._normalize_suggested_location(suggested_location) # # if 'spec.py' in normalized_suggested_location: # self.spec_locations.append(Location(normalized_suggested_location)) # else: # self._find_specs_in_directory(normalized_suggested_location) # # def _normalize_suggested_location(self, suggested_location): # # if os.path.isabs(suggested_location): # return suggested_location # return os.path.join(self.working_directory, suggested_location) # # def _find_specs_in_directory(self, directory): # for root, _, file_names in os.walk(directory): # for filename in fnmatch.filter(file_names, '*spec.py'): # self.spec_locations.append(Location(os.path.join(root, filename))) # # Path: nimoy/runner/spec_loader.py # class SpecLoader: # def __init__(self, runner_context: RunnerContext, ast_chain) -> None: # super().__init__() # self.runner_context = runner_context # self.ast_chain = ast_chain # # def load(self, spec_locations_and_contents): # def specs(): # for spec_location, text in spec_locations_and_contents: # node = ast.parse(text, mode='exec') # # metadata_of_specs_from_node = self.ast_chain.apply(self.runner_context, spec_location, node) # ast.fix_missing_locations(node) # compiled = compile(node, spec_location.spec_path, 'exec') # # spec_namespace = {} # exec(compiled, spec_namespace) # # for spec_metadata in metadata_of_specs_from_node: # spec_metadata.set_owning_module(spec_namespace[spec_metadata.name]) # yield spec_metadata # # return specs() # # Path: nimoy/runner/spec_reader.py # class SpecReader: # def __init__(self, resource_reader) -> None: # super().__init__() # self.resource_reader = resource_reader # # def read(self, spec_locations): # def spec_contents(): # for spec_file_location in spec_locations: # text = self.resource_reader.read(spec_file_location.spec_path) # yield (spec_file_location, text) # # return spec_contents() . Output only the next line.
return SpecLoader(runner_context, ast_chain).load(spec_locations_and_contents)
Given snippet: <|code_start|> class SpecRunner: def run(self, execution_framework): parser = argparse.ArgumentParser(prog='nimoy', description='Run a suite of Nimoy specs.') parser.add_argument('--power-assertions', metavar='P', type=bool, nargs=1, default=False, help="Should Nimoy evaluate comparison expressions using power assertions (beta)") parser.add_argument('specs', metavar='S', type=str, nargs='*', help="""A path to a spec file to execute or a directory to scan for spec files. When naming a file it is possible to select which spec or feature to run. some_spec.py[::SpecName[::feature_name]] """) args = parser.parse_args() spec_locations = SpecRunner._find_specs(args) spec_locations_and_contents = SpecRunner._read_specs(spec_locations) <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse import os from nimoy.ast_tools import ast_chain from nimoy.runner import fs_resource_reader from nimoy.runner.metadata import RunnerContext from nimoy.runner.spec_executor import SpecExecutor from nimoy.runner.spec_finder import SpecFinder from nimoy.runner.spec_loader import SpecLoader from nimoy.runner.spec_reader import SpecReader and context: # Path: nimoy/ast_tools/ast_chain.py # def apply(runner_context: RunnerContext, spec_location, node): # # Path: nimoy/runner/metadata.py # class RunnerContext: # # def __init__(self, use_power_assertions: bool = False): # self.use_power_assertions = use_power_assertions # # Path: nimoy/runner/spec_executor.py # class SpecExecutor: # def __init__(self, execution_framework) -> None: # super().__init__() # self.execution_framework = execution_framework # # def execute(self, specs): # for spec_metadata in specs: # spec_class_module = spec_metadata.owning_module # # for spec_feature in spec_metadata.features: # self.execution_framework.append_test(spec_class_module(spec_feature)) # # return self.execution_framework.run() # # Path: nimoy/runner/spec_finder.py # class SpecFinder: # def __init__(self, working_directory) -> None: # super().__init__() # self.working_directory = working_directory # self.spec_locations = [] # # def find(self, suggested_locations): # if not suggested_locations: # suggested_locations.append(self.working_directory) # self._find_specs_in_suggested_locations(suggested_locations) # # return self.spec_locations # # def _find_specs_in_suggested_locations(self, suggested_locations): # # for suggested_location in suggested_locations: # normalized_suggested_location = self._normalize_suggested_location(suggested_location) # # if 'spec.py' in normalized_suggested_location: # self.spec_locations.append(Location(normalized_suggested_location)) # else: # self._find_specs_in_directory(normalized_suggested_location) # # def _normalize_suggested_location(self, suggested_location): # # if os.path.isabs(suggested_location): # return suggested_location # return os.path.join(self.working_directory, suggested_location) # # def _find_specs_in_directory(self, directory): # for root, _, file_names in os.walk(directory): # for filename in fnmatch.filter(file_names, '*spec.py'): # self.spec_locations.append(Location(os.path.join(root, filename))) # # Path: nimoy/runner/spec_loader.py # class SpecLoader: # def __init__(self, runner_context: RunnerContext, ast_chain) -> None: # super().__init__() # self.runner_context = runner_context # self.ast_chain = ast_chain # # def load(self, spec_locations_and_contents): # def specs(): # for spec_location, text in spec_locations_and_contents: # node = ast.parse(text, mode='exec') # # metadata_of_specs_from_node = self.ast_chain.apply(self.runner_context, spec_location, node) # ast.fix_missing_locations(node) # compiled = compile(node, spec_location.spec_path, 'exec') # # spec_namespace = {} # exec(compiled, spec_namespace) # # for spec_metadata in metadata_of_specs_from_node: # spec_metadata.set_owning_module(spec_namespace[spec_metadata.name]) # yield spec_metadata # # return specs() # # Path: nimoy/runner/spec_reader.py # class SpecReader: # def __init__(self, resource_reader) -> None: # super().__init__() # self.resource_reader = resource_reader # # def read(self, spec_locations): # def spec_contents(): # for spec_file_location in spec_locations: # text = self.resource_reader.read(spec_file_location.spec_path) # yield (spec_file_location, text) # # return spec_contents() which might include code, classes, or functions. Output only the next line.
return SpecRunner._run_on_contents(RunnerContext(use_power_assertions=args.power_assertions),
Based on the snippet: <|code_start|> help="""A path to a spec file to execute or a directory to scan for spec files. When naming a file it is possible to select which spec or feature to run. some_spec.py[::SpecName[::feature_name]] """) args = parser.parse_args() spec_locations = SpecRunner._find_specs(args) spec_locations_and_contents = SpecRunner._read_specs(spec_locations) return SpecRunner._run_on_contents(RunnerContext(use_power_assertions=args.power_assertions), execution_framework, spec_locations_and_contents) @staticmethod def _run_on_contents(runner_context: RunnerContext, execution_framework, spec_locations_and_contents): specs = SpecRunner._load_specs(runner_context, spec_locations_and_contents) return SpecRunner._execute_specs(execution_framework, specs) @staticmethod def _find_specs(args): return SpecFinder(os.getcwd()).find(args.specs) @staticmethod def _read_specs(spec_locations): return SpecReader(fs_resource_reader).read(spec_locations) @staticmethod def _load_specs(runner_context: RunnerContext, spec_locations_and_contents): return SpecLoader(runner_context, ast_chain).load(spec_locations_and_contents) @staticmethod def _execute_specs(execution_framework, specs): <|code_end|> , predict the immediate next line with the help of imports: import argparse import os from nimoy.ast_tools import ast_chain from nimoy.runner import fs_resource_reader from nimoy.runner.metadata import RunnerContext from nimoy.runner.spec_executor import SpecExecutor from nimoy.runner.spec_finder import SpecFinder from nimoy.runner.spec_loader import SpecLoader from nimoy.runner.spec_reader import SpecReader and context (classes, functions, sometimes code) from other files: # Path: nimoy/ast_tools/ast_chain.py # def apply(runner_context: RunnerContext, spec_location, node): # # Path: nimoy/runner/metadata.py # class RunnerContext: # # def __init__(self, use_power_assertions: bool = False): # self.use_power_assertions = use_power_assertions # # Path: nimoy/runner/spec_executor.py # class SpecExecutor: # def __init__(self, execution_framework) -> None: # super().__init__() # self.execution_framework = execution_framework # # def execute(self, specs): # for spec_metadata in specs: # spec_class_module = spec_metadata.owning_module # # for spec_feature in spec_metadata.features: # self.execution_framework.append_test(spec_class_module(spec_feature)) # # return self.execution_framework.run() # # Path: nimoy/runner/spec_finder.py # class SpecFinder: # def __init__(self, working_directory) -> None: # super().__init__() # self.working_directory = working_directory # self.spec_locations = [] # # def find(self, suggested_locations): # if not suggested_locations: # suggested_locations.append(self.working_directory) # self._find_specs_in_suggested_locations(suggested_locations) # # return self.spec_locations # # def _find_specs_in_suggested_locations(self, suggested_locations): # # for suggested_location in suggested_locations: # normalized_suggested_location = self._normalize_suggested_location(suggested_location) # # if 'spec.py' in normalized_suggested_location: # self.spec_locations.append(Location(normalized_suggested_location)) # else: # self._find_specs_in_directory(normalized_suggested_location) # # def _normalize_suggested_location(self, suggested_location): # # if os.path.isabs(suggested_location): # return suggested_location # return os.path.join(self.working_directory, suggested_location) # # def _find_specs_in_directory(self, directory): # for root, _, file_names in os.walk(directory): # for filename in fnmatch.filter(file_names, '*spec.py'): # self.spec_locations.append(Location(os.path.join(root, filename))) # # Path: nimoy/runner/spec_loader.py # class SpecLoader: # def __init__(self, runner_context: RunnerContext, ast_chain) -> None: # super().__init__() # self.runner_context = runner_context # self.ast_chain = ast_chain # # def load(self, spec_locations_and_contents): # def specs(): # for spec_location, text in spec_locations_and_contents: # node = ast.parse(text, mode='exec') # # metadata_of_specs_from_node = self.ast_chain.apply(self.runner_context, spec_location, node) # ast.fix_missing_locations(node) # compiled = compile(node, spec_location.spec_path, 'exec') # # spec_namespace = {} # exec(compiled, spec_namespace) # # for spec_metadata in metadata_of_specs_from_node: # spec_metadata.set_owning_module(spec_namespace[spec_metadata.name]) # yield spec_metadata # # return specs() # # Path: nimoy/runner/spec_reader.py # class SpecReader: # def __init__(self, resource_reader) -> None: # super().__init__() # self.resource_reader = resource_reader # # def read(self, spec_locations): # def spec_contents(): # for spec_file_location in spec_locations: # text = self.resource_reader.read(spec_file_location.spec_path) # yield (spec_file_location, text) # # return spec_contents() . Output only the next line.
return SpecExecutor(execution_framework).execute(specs)
Predict the next line after this snippet: <|code_start|> class SpecRunner: def run(self, execution_framework): parser = argparse.ArgumentParser(prog='nimoy', description='Run a suite of Nimoy specs.') parser.add_argument('--power-assertions', metavar='P', type=bool, nargs=1, default=False, help="Should Nimoy evaluate comparison expressions using power assertions (beta)") parser.add_argument('specs', metavar='S', type=str, nargs='*', help="""A path to a spec file to execute or a directory to scan for spec files. When naming a file it is possible to select which spec or feature to run. some_spec.py[::SpecName[::feature_name]] """) args = parser.parse_args() spec_locations = SpecRunner._find_specs(args) spec_locations_and_contents = SpecRunner._read_specs(spec_locations) return SpecRunner._run_on_contents(RunnerContext(use_power_assertions=args.power_assertions), execution_framework, spec_locations_and_contents) @staticmethod def _run_on_contents(runner_context: RunnerContext, execution_framework, spec_locations_and_contents): specs = SpecRunner._load_specs(runner_context, spec_locations_and_contents) return SpecRunner._execute_specs(execution_framework, specs) @staticmethod def _find_specs(args): <|code_end|> using the current file's imports: import argparse import os from nimoy.ast_tools import ast_chain from nimoy.runner import fs_resource_reader from nimoy.runner.metadata import RunnerContext from nimoy.runner.spec_executor import SpecExecutor from nimoy.runner.spec_finder import SpecFinder from nimoy.runner.spec_loader import SpecLoader from nimoy.runner.spec_reader import SpecReader and any relevant context from other files: # Path: nimoy/ast_tools/ast_chain.py # def apply(runner_context: RunnerContext, spec_location, node): # # Path: nimoy/runner/metadata.py # class RunnerContext: # # def __init__(self, use_power_assertions: bool = False): # self.use_power_assertions = use_power_assertions # # Path: nimoy/runner/spec_executor.py # class SpecExecutor: # def __init__(self, execution_framework) -> None: # super().__init__() # self.execution_framework = execution_framework # # def execute(self, specs): # for spec_metadata in specs: # spec_class_module = spec_metadata.owning_module # # for spec_feature in spec_metadata.features: # self.execution_framework.append_test(spec_class_module(spec_feature)) # # return self.execution_framework.run() # # Path: nimoy/runner/spec_finder.py # class SpecFinder: # def __init__(self, working_directory) -> None: # super().__init__() # self.working_directory = working_directory # self.spec_locations = [] # # def find(self, suggested_locations): # if not suggested_locations: # suggested_locations.append(self.working_directory) # self._find_specs_in_suggested_locations(suggested_locations) # # return self.spec_locations # # def _find_specs_in_suggested_locations(self, suggested_locations): # # for suggested_location in suggested_locations: # normalized_suggested_location = self._normalize_suggested_location(suggested_location) # # if 'spec.py' in normalized_suggested_location: # self.spec_locations.append(Location(normalized_suggested_location)) # else: # self._find_specs_in_directory(normalized_suggested_location) # # def _normalize_suggested_location(self, suggested_location): # # if os.path.isabs(suggested_location): # return suggested_location # return os.path.join(self.working_directory, suggested_location) # # def _find_specs_in_directory(self, directory): # for root, _, file_names in os.walk(directory): # for filename in fnmatch.filter(file_names, '*spec.py'): # self.spec_locations.append(Location(os.path.join(root, filename))) # # Path: nimoy/runner/spec_loader.py # class SpecLoader: # def __init__(self, runner_context: RunnerContext, ast_chain) -> None: # super().__init__() # self.runner_context = runner_context # self.ast_chain = ast_chain # # def load(self, spec_locations_and_contents): # def specs(): # for spec_location, text in spec_locations_and_contents: # node = ast.parse(text, mode='exec') # # metadata_of_specs_from_node = self.ast_chain.apply(self.runner_context, spec_location, node) # ast.fix_missing_locations(node) # compiled = compile(node, spec_location.spec_path, 'exec') # # spec_namespace = {} # exec(compiled, spec_namespace) # # for spec_metadata in metadata_of_specs_from_node: # spec_metadata.set_owning_module(spec_namespace[spec_metadata.name]) # yield spec_metadata # # return specs() # # Path: nimoy/runner/spec_reader.py # class SpecReader: # def __init__(self, resource_reader) -> None: # super().__init__() # self.resource_reader = resource_reader # # def read(self, spec_locations): # def spec_contents(): # for spec_file_location in spec_locations: # text = self.resource_reader.read(spec_file_location.spec_path) # yield (spec_file_location, text) # # return spec_contents() . Output only the next line.
return SpecFinder(os.getcwd()).find(args.specs)
Next line prediction: <|code_start|> parser = argparse.ArgumentParser(prog='nimoy', description='Run a suite of Nimoy specs.') parser.add_argument('--power-assertions', metavar='P', type=bool, nargs=1, default=False, help="Should Nimoy evaluate comparison expressions using power assertions (beta)") parser.add_argument('specs', metavar='S', type=str, nargs='*', help="""A path to a spec file to execute or a directory to scan for spec files. When naming a file it is possible to select which spec or feature to run. some_spec.py[::SpecName[::feature_name]] """) args = parser.parse_args() spec_locations = SpecRunner._find_specs(args) spec_locations_and_contents = SpecRunner._read_specs(spec_locations) return SpecRunner._run_on_contents(RunnerContext(use_power_assertions=args.power_assertions), execution_framework, spec_locations_and_contents) @staticmethod def _run_on_contents(runner_context: RunnerContext, execution_framework, spec_locations_and_contents): specs = SpecRunner._load_specs(runner_context, spec_locations_and_contents) return SpecRunner._execute_specs(execution_framework, specs) @staticmethod def _find_specs(args): return SpecFinder(os.getcwd()).find(args.specs) @staticmethod def _read_specs(spec_locations): return SpecReader(fs_resource_reader).read(spec_locations) @staticmethod def _load_specs(runner_context: RunnerContext, spec_locations_and_contents): <|code_end|> . Use current file imports: (import argparse import os from nimoy.ast_tools import ast_chain from nimoy.runner import fs_resource_reader from nimoy.runner.metadata import RunnerContext from nimoy.runner.spec_executor import SpecExecutor from nimoy.runner.spec_finder import SpecFinder from nimoy.runner.spec_loader import SpecLoader from nimoy.runner.spec_reader import SpecReader) and context including class names, function names, or small code snippets from other files: # Path: nimoy/ast_tools/ast_chain.py # def apply(runner_context: RunnerContext, spec_location, node): # # Path: nimoy/runner/metadata.py # class RunnerContext: # # def __init__(self, use_power_assertions: bool = False): # self.use_power_assertions = use_power_assertions # # Path: nimoy/runner/spec_executor.py # class SpecExecutor: # def __init__(self, execution_framework) -> None: # super().__init__() # self.execution_framework = execution_framework # # def execute(self, specs): # for spec_metadata in specs: # spec_class_module = spec_metadata.owning_module # # for spec_feature in spec_metadata.features: # self.execution_framework.append_test(spec_class_module(spec_feature)) # # return self.execution_framework.run() # # Path: nimoy/runner/spec_finder.py # class SpecFinder: # def __init__(self, working_directory) -> None: # super().__init__() # self.working_directory = working_directory # self.spec_locations = [] # # def find(self, suggested_locations): # if not suggested_locations: # suggested_locations.append(self.working_directory) # self._find_specs_in_suggested_locations(suggested_locations) # # return self.spec_locations # # def _find_specs_in_suggested_locations(self, suggested_locations): # # for suggested_location in suggested_locations: # normalized_suggested_location = self._normalize_suggested_location(suggested_location) # # if 'spec.py' in normalized_suggested_location: # self.spec_locations.append(Location(normalized_suggested_location)) # else: # self._find_specs_in_directory(normalized_suggested_location) # # def _normalize_suggested_location(self, suggested_location): # # if os.path.isabs(suggested_location): # return suggested_location # return os.path.join(self.working_directory, suggested_location) # # def _find_specs_in_directory(self, directory): # for root, _, file_names in os.walk(directory): # for filename in fnmatch.filter(file_names, '*spec.py'): # self.spec_locations.append(Location(os.path.join(root, filename))) # # Path: nimoy/runner/spec_loader.py # class SpecLoader: # def __init__(self, runner_context: RunnerContext, ast_chain) -> None: # super().__init__() # self.runner_context = runner_context # self.ast_chain = ast_chain # # def load(self, spec_locations_and_contents): # def specs(): # for spec_location, text in spec_locations_and_contents: # node = ast.parse(text, mode='exec') # # metadata_of_specs_from_node = self.ast_chain.apply(self.runner_context, spec_location, node) # ast.fix_missing_locations(node) # compiled = compile(node, spec_location.spec_path, 'exec') # # spec_namespace = {} # exec(compiled, spec_namespace) # # for spec_metadata in metadata_of_specs_from_node: # spec_metadata.set_owning_module(spec_namespace[spec_metadata.name]) # yield spec_metadata # # return specs() # # Path: nimoy/runner/spec_reader.py # class SpecReader: # def __init__(self, resource_reader) -> None: # super().__init__() # self.resource_reader = resource_reader # # def read(self, spec_locations): # def spec_contents(): # for spec_file_location in spec_locations: # text = self.resource_reader.read(spec_file_location.spec_path) # yield (spec_file_location, text) # # return spec_contents() . Output only the next line.
return SpecLoader(runner_context, ast_chain).load(spec_locations_and_contents)
Using the snippet: <|code_start|> class SpecRunner: def run(self, execution_framework): parser = argparse.ArgumentParser(prog='nimoy', description='Run a suite of Nimoy specs.') parser.add_argument('--power-assertions', metavar='P', type=bool, nargs=1, default=False, help="Should Nimoy evaluate comparison expressions using power assertions (beta)") parser.add_argument('specs', metavar='S', type=str, nargs='*', help="""A path to a spec file to execute or a directory to scan for spec files. When naming a file it is possible to select which spec or feature to run. some_spec.py[::SpecName[::feature_name]] """) args = parser.parse_args() spec_locations = SpecRunner._find_specs(args) spec_locations_and_contents = SpecRunner._read_specs(spec_locations) return SpecRunner._run_on_contents(RunnerContext(use_power_assertions=args.power_assertions), execution_framework, spec_locations_and_contents) @staticmethod def _run_on_contents(runner_context: RunnerContext, execution_framework, spec_locations_and_contents): specs = SpecRunner._load_specs(runner_context, spec_locations_and_contents) return SpecRunner._execute_specs(execution_framework, specs) @staticmethod def _find_specs(args): return SpecFinder(os.getcwd()).find(args.specs) @staticmethod def _read_specs(spec_locations): <|code_end|> , determine the next line of code. You have imports: import argparse import os from nimoy.ast_tools import ast_chain from nimoy.runner import fs_resource_reader from nimoy.runner.metadata import RunnerContext from nimoy.runner.spec_executor import SpecExecutor from nimoy.runner.spec_finder import SpecFinder from nimoy.runner.spec_loader import SpecLoader from nimoy.runner.spec_reader import SpecReader and context (class names, function names, or code) available: # Path: nimoy/ast_tools/ast_chain.py # def apply(runner_context: RunnerContext, spec_location, node): # # Path: nimoy/runner/metadata.py # class RunnerContext: # # def __init__(self, use_power_assertions: bool = False): # self.use_power_assertions = use_power_assertions # # Path: nimoy/runner/spec_executor.py # class SpecExecutor: # def __init__(self, execution_framework) -> None: # super().__init__() # self.execution_framework = execution_framework # # def execute(self, specs): # for spec_metadata in specs: # spec_class_module = spec_metadata.owning_module # # for spec_feature in spec_metadata.features: # self.execution_framework.append_test(spec_class_module(spec_feature)) # # return self.execution_framework.run() # # Path: nimoy/runner/spec_finder.py # class SpecFinder: # def __init__(self, working_directory) -> None: # super().__init__() # self.working_directory = working_directory # self.spec_locations = [] # # def find(self, suggested_locations): # if not suggested_locations: # suggested_locations.append(self.working_directory) # self._find_specs_in_suggested_locations(suggested_locations) # # return self.spec_locations # # def _find_specs_in_suggested_locations(self, suggested_locations): # # for suggested_location in suggested_locations: # normalized_suggested_location = self._normalize_suggested_location(suggested_location) # # if 'spec.py' in normalized_suggested_location: # self.spec_locations.append(Location(normalized_suggested_location)) # else: # self._find_specs_in_directory(normalized_suggested_location) # # def _normalize_suggested_location(self, suggested_location): # # if os.path.isabs(suggested_location): # return suggested_location # return os.path.join(self.working_directory, suggested_location) # # def _find_specs_in_directory(self, directory): # for root, _, file_names in os.walk(directory): # for filename in fnmatch.filter(file_names, '*spec.py'): # self.spec_locations.append(Location(os.path.join(root, filename))) # # Path: nimoy/runner/spec_loader.py # class SpecLoader: # def __init__(self, runner_context: RunnerContext, ast_chain) -> None: # super().__init__() # self.runner_context = runner_context # self.ast_chain = ast_chain # # def load(self, spec_locations_and_contents): # def specs(): # for spec_location, text in spec_locations_and_contents: # node = ast.parse(text, mode='exec') # # metadata_of_specs_from_node = self.ast_chain.apply(self.runner_context, spec_location, node) # ast.fix_missing_locations(node) # compiled = compile(node, spec_location.spec_path, 'exec') # # spec_namespace = {} # exec(compiled, spec_namespace) # # for spec_metadata in metadata_of_specs_from_node: # spec_metadata.set_owning_module(spec_namespace[spec_metadata.name]) # yield spec_metadata # # return specs() # # Path: nimoy/runner/spec_reader.py # class SpecReader: # def __init__(self, resource_reader) -> None: # super().__init__() # self.resource_reader = resource_reader # # def read(self, spec_locations): # def spec_contents(): # for spec_file_location in spec_locations: # text = self.resource_reader.read(spec_file_location.spec_path) # yield (spec_file_location, text) # # return spec_contents() . Output only the next line.
return SpecReader(fs_resource_reader).read(spec_locations)
Given the following code snippet before the placeholder: <|code_start|> class SpecificationExecutorSpec(Specification): def execution(self): with given: execution_framework_mock = Mock() spec_mock = Mock() spec_feature_stub = {} module_mock = Mock(return_value=spec_feature_stub) spec_mock.owning_module = module_mock spec_mock.features = ['spec_feature'] with when: <|code_end|> , predict the next line using imports from the current file: from unittest.mock import Mock from nimoy.runner.spec_executor import SpecExecutor from nimoy.specification import Specification and context including class names, function names, and sometimes code from other files: # Path: nimoy/runner/spec_executor.py # class SpecExecutor: # def __init__(self, execution_framework) -> None: # super().__init__() # self.execution_framework = execution_framework # # def execute(self, specs): # for spec_metadata in specs: # spec_class_module = spec_metadata.owning_module # # for spec_feature in spec_metadata.features: # self.execution_framework.append_test(spec_class_module(spec_feature)) # # return self.execution_framework.run() # # Path: nimoy/specification.py # class Specification(TestCase, metaclass=DataDrivenSpecification): # # def __init__(self, methodName='runTest'): # super().__init__(methodName) # self.thrown_exceptions = [] # # def _feature_block_context(self, block_name): # return FeatureBlock(block_name, self.thrown_exceptions) # # def _compare(self, left, right, comparison_type_name): # Compare().compare(left, right, comparison_type_name) # # def _power_assert(self, expression: Dict): # PowerAssertions().assert_and_raise(expression) # # def _assert_mock(self, number_of_invocations, mock, method, *args): # MockAssertions().assert_mock(number_of_invocations, mock, method, *args) # # def _exception_thrown(self, expected_exception_type): # return ExceptionAssertions().assert_exception(self.thrown_exceptions, expected_exception_type) . Output only the next line.
SpecExecutor(execution_framework_mock).execute([spec_mock])
Given the following code snippet before the placeholder: <|code_start|> class ComparisonExpressionTransformer(ast.NodeTransformer): def __init__(self) -> None: super().__init__() self.comparator_methods = { <|code_end|> , predict the next line using imports from the current file: import ast import _ast import astor from _ast import Dict, Constant from nimoy.compare.types import Types and context including class names, function names, and sometimes code from other files: # Path: nimoy/compare/types.py # class Types(Enum): # EQUAL = 1 # NOT_EQUAL = 2 # LESS_THAN = 3 # LESS_THAN_EQUAL = 4 # GREATER_THAN = 5 # GREATER_THAN_EQUAL = 6 # IS = 7 # IS_NOT = 8 # IN = 9 # NOT_IN = 10 # MATCHES_REGEXP = 11 . Output only the next line.
_ast.Eq: Types.EQUAL,
Continue the code snippet: <|code_start|> class FeatureRegistrationTransformerSpec(Specification): @mock.patch('nimoy.ast_tools.features.FeatureBlockRuleEnforcer') @mock.patch('nimoy.ast_tools.features.FeatureBlockTransformer') def a_feature_was_added(self, feature_block_transformer, feature_block_rule_enforcer): with setup: runner_context = RunnerContext() module_definition = """ class JSpec: def test_jim(self): pass def _jim(self): pass """ node = ast.parse(module_definition, mode='exec') metadata = SpecMetadata('jim') with when: <|code_end|> . Use current file imports: import ast from unittest import mock from nimoy.ast_tools.ast_metadata import SpecMetadata from nimoy.ast_tools.features import FeatureRegistrationTransformer from nimoy.runner.metadata import RunnerContext from nimoy.runner.spec_finder import Location from nimoy.specification import Specification and context (classes, functions, or code) from other files: # Path: nimoy/ast_tools/features.py # class FeatureRegistrationTransformer(ast.NodeTransformer): # def __init__(self, runner_context: RunnerContext, spec_location, spec_metadata: SpecMetadata) -> None: # super().__init__() # self.runner_context = runner_context # self.spec_location = spec_location # self.spec_metadata = spec_metadata # # def visit_FunctionDef(self, feature_node): # if FeatureRegistrationTransformer._skip_feature(feature_node): # return feature_node # # feature_name = feature_node.name # if not feature_name.startswith('_'): # # feature_name_specified = hasattr(self.spec_location, 'feature_name') # # if not feature_name_specified or ( # feature_name_specified and self.spec_location.feature_name == feature_name): # self.spec_metadata.add_feature(feature_name) # FeatureBlockTransformer(self.runner_context, self.spec_metadata, feature_name).visit(feature_node) # FeatureBlockRuleEnforcer(self.spec_metadata, feature_name, feature_node).enforce_tail_end_rules() # # feature_variables = self.spec_metadata.feature_variables.get(feature_name) # if feature_variables: # existing_arg_names = [existing_arg.arg for existing_arg in feature_node.args.args] # # for feature_variable in feature_variables: # if feature_variable in existing_arg_names: # continue # feature_node.args.args.append(_ast.arg(arg=feature_variable)) # feature_node.args.defaults.append(ast.NameConstant(value=None)) # # if self._feature_has_a_where_function(feature_name): # self._remove_where_function_from_node(feature_name, feature_node) # return feature_node # # @staticmethod # def _remove_where_function_from_node(feature_name, feature_node): # where_function = FeatureRegistrationTransformer._locate_where_function_within_feature(feature_name, # feature_node) # feature_node.body.remove(where_function) # # def _feature_has_a_where_function(self, feature_name): # return self.spec_metadata.where_functions.get(feature_name) # # @staticmethod # def _locate_where_function_within_feature(feature_name, feature_node): # def _is_a_where_function(body_element): # return hasattr(body_element, 'name') and body_element.name == feature_name + '_where' # # return next(body_element for body_element in feature_node.body if _is_a_where_function(body_element)) # # @staticmethod # def _skip_feature(feature_node): # decorators = feature_node.decorator_list # return any((hasattr(decorator, 'attr') and decorator.attr == 'skip') for decorator in decorators) # # Path: nimoy/runner/metadata.py # class RunnerContext: # # def __init__(self, use_power_assertions: bool = False): # self.use_power_assertions = use_power_assertions # # Path: nimoy/runner/spec_finder.py # class Location: # def __init__(self, suggested_location): # # # Format may be: # # - some_spec.py # # - some_spec.py::SpecName # # - some_spec.py::feature_name # # - some_spec.py::SpecName::feature_name # split_suggested_location = suggested_location.split("::") # # # some_spec.py # if len(split_suggested_location) == 1: # self.spec_path = split_suggested_location[0] # # # some_spec.py::SpecName or some_spec.py::feature_name # if len(split_suggested_location) == 2: # self.spec_path = split_suggested_location[0] # # # some_spec.py::SpecName # if split_suggested_location[1][0].isupper(): # self.spec_name = split_suggested_location[1] # # # some_spec.py::feature_name # else: # self.feature_name = split_suggested_location[1] # # # some_spec.py::SpecName::feature_name # if len(split_suggested_location) == 3: # self.spec_path = split_suggested_location[0] # self.spec_name = split_suggested_location[1] # self.feature_name = split_suggested_location[2] # # Path: nimoy/specification.py # class Specification(TestCase, metaclass=DataDrivenSpecification): # # def __init__(self, methodName='runTest'): # super().__init__(methodName) # self.thrown_exceptions = [] # # def _feature_block_context(self, block_name): # return FeatureBlock(block_name, self.thrown_exceptions) # # def _compare(self, left, right, comparison_type_name): # Compare().compare(left, right, comparison_type_name) # # def _power_assert(self, expression: Dict): # PowerAssertions().assert_and_raise(expression) # # def _assert_mock(self, number_of_invocations, mock, method, *args): # MockAssertions().assert_mock(number_of_invocations, mock, method, *args) # # def _exception_thrown(self, expected_exception_type): # return ExceptionAssertions().assert_exception(self.thrown_exceptions, expected_exception_type) . Output only the next line.
FeatureRegistrationTransformer(runner_context, Location('some_spec.py'), metadata).visit(node)