Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|># ~ Tune In # # Tuned to: # # https://cymon.io # # # # API Documentation: # # http://docs.cymon.io/ # # # # Author: 10TOHH # # # # Tunes: # # domain_to_ipv4 - Resolves IP to <Domain> # # ipv4_to_domain - Resolves Domain to <IP> # # ipv4_to_hash - Return Hash associated with <IP> # # ipv4_to_url - Return URL to report for given <IP> # # hash_to_url - Return URL to report for given <Hash> # ################################################################# class Cymon(object): def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] # get helping functions <|code_end|> with the help of current file imports: from lib import config, helpers and context from other files: # Path: lib/config.py # # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' , which may contain function names, class names, or code. Output only the next line.
self.api = helpers.Common()
Using the snippet: <|code_start|># # # hash_to_score - Return Score to given <Hash> # # hash_to_url - Return URL to report for given <Hash> # ################################################################# class Virustotal(object): def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] # get helping functions self.api = helpers.Common() # static station settings self.station_name = 'Virustotal' self.endpoint = 'https://www.virustotal.com/vtapi/v2' self.path = '' self.parameters = {} self.headers = {} self.user_agent = {} self.response_format = 'json' <|code_end|> , determine the next line of code. You have imports: from lib import config, helpers and context (class names, function names, or code) available: # Path: lib/config.py # # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' . Output only the next line.
if config.virustotal_api_key:
Based on the snippet: <|code_start|># API Documentation: # # https://www.virustotal.com/en/documentation/public-api/ # # # # Author: 10TOHH # # # # # # Tunes: # # domain_to_ipv4 - Resolves IP to <Domain> # # # # ipv4_to_domain - Resolves Domain to <IP> # # ipv4_to_hash - Return Hash associated with <IP> # # # # hash_to_score - Return Score to given <Hash> # # hash_to_url - Return URL to report for given <Hash> # ################################################################# class Virustotal(object): def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] # get helping functions <|code_end|> , predict the immediate next line with the help of imports: from lib import config, helpers and context (classes, functions, sometimes code) from other files: # Path: lib/config.py # # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' . Output only the next line.
self.api = helpers.Common()
Next line prediction: <|code_start|># hash_to_score - Return Score to given <Hash> # ################################################################# class Metascan(object): def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] # get helping functions self.api = helpers.Common() # static station settings self.station_name = 'Metascan' self.endpoint = 'https://metascan-online.com' # different subdomains for search # hashlookup and ipscan self.url_path = '' self.parameters = {} self.headers = {'content-type': 'application/json', 'accept': 'application/json', 'file_metadata': 1} self.user_agent = {} self.response_format = 'json' <|code_end|> . Use current file imports: (from lib import config, helpers) and context including class names, function names, or small code snippets from other files: # Path: lib/config.py # # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' . Output only the next line.
if config.metascan_api_key:
Predict the next line for this snippet: <|code_start|># Metascan station for QRadio # # ~ Tune In # # Tuned to: # # https://www.metascan-online.com # # # # API Documentation: # # https://www.metascan-online.com/public-api#!/ # # # # Author: 10TOHH # # # # Tunes: # # ipv4_to_score - Return Score to <IP> # # # # hash_to_imphash - Return Imphash associated with <Hash> # # hash_to_score - Return Score to given <Hash> # ################################################################# class Metascan(object): def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] # get helping functions <|code_end|> with the help of current file imports: from lib import config, helpers and context from other files: # Path: lib/config.py # # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' , which may contain function names, class names, or code. Output only the next line.
self.api = helpers.Common()
Given the code snippet: <|code_start|>################################################################# # Hostsfile station for QRadio # # ~ Tune In # # Tuned to: # # http://hosts-file.net/default.asp # # # # Author: 10TOHH # # # # Tunes: # # domain_to_ipv4 - Resolves IP to <Domain> # # ipv4_to_domain - Resolves Domain to <IP> # ################################################################# class Hostsfile(object): def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] # get helping functions <|code_end|> , generate the next line using the imports in this file: from lib import helpers and context (functions, classes, or occasionally code) from other files: # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' . Output only the next line.
self.api = helpers.Common()
Predict the next line for this snippet: <|code_start|># http://www.threatcrowd.org/ API v2 # # # # API Documentation: # # https://github.com/threatcrowd/ApiV2 # # # # Author: 10TOHH # # # # Tunes: # # domain_to_ipv4 - Resolves IP to <Domain> # # domain_to_hash - Return Hash to <Domain> # # ipv4_to_domain - Resolves Domain to <IP> # # ipv4_to_hash - Return Hash associated with <IP> # # hash_to_ipv4 - Return IPv4 associated with <Hash> # # hash_to_domain - Return Domain associated with <Hash> # # hash_to_url - Return URL to report for given <Hash> # ################################################################# class Threatcrowd(object): def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] # get helping functions <|code_end|> with the help of current file imports: from lib import helpers and context from other files: # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' , which may contain function names, class names, or code. Output only the next line.
self.api = helpers.Common()
Based on the snippet: <|code_start|>################################################################# class Malwr(object): logged = False url = "https://malwr.com" headers = { 'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) " + "Gecko/20100101 Firefox/41.0" } def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] self.drop_hash = [] self.error_log = helpers.IO() self.station_name = 'Malwr' self.session = requests.session() # Authenticate and store the session <|code_end|> , predict the immediate next line with the help of imports: from lib import config, helpers from bs4 import BeautifulSoup import requests and context (classes, functions, sometimes code) from other files: # Path: lib/config.py # # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' . Output only the next line.
if config.malwr_login and config.malwr_passwd:
Here is a snippet: <|code_start|># ipv4_to_url - Return URL to report for given <IP> # # # # hash_to_ipv4 - Return IP associated with <Hash> # # hash_to_imphash - Return Imphash associated with <Hash> # # hash_to_url - Return URL to report for given <Hash> # # hash_to_score - Return Score to given <Hash> # ################################################################# class Malwr(object): logged = False url = "https://malwr.com" headers = { 'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) " + "Gecko/20100101 Firefox/41.0" } def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] self.drop_hash = [] <|code_end|> . Write the next line using the current file imports: from lib import config, helpers from bs4 import BeautifulSoup import requests and context from other files: # Path: lib/config.py # # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' , which may include functions, classes, or code. Output only the next line.
self.error_log = helpers.IO()
Here is a snippet: <|code_start|> class Station_name(object): def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] # get helping functions <|code_end|> . Write the next line using the current file imports: from lib import config, helpers import re and context from other files: # Path: lib/config.py # # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' , which may include functions, classes, or code. Output only the next line.
self.api = helpers.Common()
Here is a snippet: <|code_start|>################################################################# # Fortiguard station for QRadio # # ~ Tune In # # Tuned to: # # http://www.fortiguard.com/iprep/index.php # # # # Author: 10TOHH # # # # Tunes: # # domain_to_ipv4 - Resolves IP to <Domain> # ################################################################# class Fortiguard(object): def __init__(self): # lists of values that can be returned self.ip_list = [] self.domain_list = [] self.hash_list = [] self.url_list = [] self.score_list = [] self.imphash_list = [] # get helping functions <|code_end|> . Write the next line using the current file imports: from lib import helpers and context from other files: # Path: lib/helpers.py # class Common(object): # class IO(object): # class MaltegoEntity(object): # class MaltegoTransform(object): # def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name' # endpoint=None, # 'https://station.com/api/search/index.php' # method_type=None, # GET/POST # data_to_send=None, # Data to sent in POST # url_path=None, # '/api/search/google.com' # parameters=None, # {'limit': '1000'} # headers=None, # {'api_key': 'api_key_value'} # user_agent=None, # {'User-agent': 'VxStream Sandbox'} # response_format=None, # json or bs(BeautifulSoup) # go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something # def verbose_output(self, search_value, search_from, search_to, dictionary): # def nonverbose_output(self, search_value, search_from, search_to, dictionary): # def error_log(self, error, station_name=None): # def process_file(self, file_path): # def input_validator(self,input_value): # def __init__(self,eT=None,v=None): # def setType(self,eT=None): # def setValue(self,eV=None): # def setWeight(self,w=None): # def setDisplayInformation(self,di=None): # def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None): # def setIconURL(self,iU=None): # def setLinkColor(self,color): # def setLinkStyle(self,style): # def setLinkThickness(self,thick): # def setLinkLabel(self,label): # def setBookmark(self,bookmark): # def setNote(self,note): # def returnEntity(self): # def __init__(self): # def parseArguments(self,argv): # def getValue(self): # def getVar(self,varName): # def addEntity(self,enType,enValue): # def addEntityToMessage(self,maltegoEntity): # def addUIMessage(self,message,messageType="Inform"): # def addException(self,exceptionString): # def throwExceptions(self): # def returnOutput(self): # def writeSTDERR(self,msg): # def heartbeat(self): # def progress(self,percent): # def debug(self,msg): # def sanitise(self, value): # BOOKMARK_COLOR_NONE="-1" # BOOKMARK_COLOR_BLUE="0" # BOOKMARK_COLOR_GREEN="1" # BOOKMARK_COLOR_YELLOW="2" # BOOKMARK_COLOR_ORANGE="3" # BOOKMARK_COLOR_RED="4" # LINK_STYLE_NORMAL="0" # LINK_STYLE_DASHED="1" # LINK_STYLE_DOTTED="2" # LINK_STYLE_DASHDOT="3" # UIM_FATAL='FatalError' # UIM_PARTIAL='PartialError' # UIM_INFORM='Inform' # UIM_DEBUG='Debug' , which may include functions, classes, or code. Output only the next line.
self.api = helpers.Common()
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This module manages the version info. ''' # Imports ##################################################################### # Metadata #################################################################### __author__ = 'Timothy McFadden' __creationDate__ = '13-APR-2017' # Globals ##################################################################### RE_VERSION = re.compile( '^__version__\s*=\s*[\'"](?P<version>.*?)[\'"]\s*?^', re.MULTILINE) def get_version(): '''Gets the current version''' <|code_end|> . Use current file imports: (import re from fabric.api import task from .constants import VER_FILE, DOCS_CONF_FILE from .helpers import true) and context including class names, function names, or small code snippets from other files: # Path: fabfile/constants.py # VER_FILE = os.path.join(LIB_DIR, 'climenu.py') # # DOCS_CONF_FILE = os.path.join(LIB_DIR, 'docs', 'conf.py') # # Path: fabfile/helpers.py # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) . Output only the next line.
text = open(VER_FILE).read()
Given the code snippet: <|code_start|> if not match: raise Exception("Could not get version") return match.group('version') @task def rev(): """Increases the 'minor' version number by 1""" text = open(VER_FILE).read() whole, ver = re.search("^(__version__\s+=\s+['\"](.*?)['\"]\s*)$", text, re.MULTILINE).groups() major, minor, patch = ver.split('.', 2) new_minor = str(int(minor) + 1) # NOTE: When reving minor, it's customary to set patch to "0" new_ver = ".".join([major, new_minor, "0"]) print("Old version number is [%s]" % ver) print("New version number is [%s]" % new_ver) val = raw_input("OK [Yn]? ") while not true(val): new_ver = raw_input("Enter new version: ") print("Using new version [%s]" % new_ver) val = raw_input("OK [Yn]? ") text = text.replace(ver, new_ver) with open(VER_FILE, "wb") as fh: fh.write(text) <|code_end|> , generate the next line using the imports in this file: import re from fabric.api import task from .constants import VER_FILE, DOCS_CONF_FILE from .helpers import true and context (functions, classes, or occasionally code) from other files: # Path: fabfile/constants.py # VER_FILE = os.path.join(LIB_DIR, 'climenu.py') # # DOCS_CONF_FILE = os.path.join(LIB_DIR, 'docs', 'conf.py') # # Path: fabfile/helpers.py # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) . Output only the next line.
text = open(DOCS_CONF_FILE).read()
Based on the snippet: <|code_start|># Globals ##################################################################### RE_VERSION = re.compile( '^__version__\s*=\s*[\'"](?P<version>.*?)[\'"]\s*?^', re.MULTILINE) def get_version(): '''Gets the current version''' text = open(VER_FILE).read() match = RE_VERSION.search(text) if not match: raise Exception("Could not get version") return match.group('version') @task def rev(): """Increases the 'minor' version number by 1""" text = open(VER_FILE).read() whole, ver = re.search("^(__version__\s+=\s+['\"](.*?)['\"]\s*)$", text, re.MULTILINE).groups() major, minor, patch = ver.split('.', 2) new_minor = str(int(minor) + 1) # NOTE: When reving minor, it's customary to set patch to "0" new_ver = ".".join([major, new_minor, "0"]) print("Old version number is [%s]" % ver) print("New version number is [%s]" % new_ver) val = raw_input("OK [Yn]? ") <|code_end|> , predict the immediate next line with the help of imports: import re from fabric.api import task from .constants import VER_FILE, DOCS_CONF_FILE from .helpers import true and context (classes, functions, sometimes code) from other files: # Path: fabfile/constants.py # VER_FILE = os.path.join(LIB_DIR, 'climenu.py') # # DOCS_CONF_FILE = os.path.join(LIB_DIR, 'docs', 'conf.py') # # Path: fabfile/helpers.py # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) . Output only the next line.
while not true(val):
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This module hold fabric management functions dealing with Git ''' # Imports ##################################################################### # Metadata #################################################################### __author__ = 'Timothy McFadden' __creationDate__ = '14-APR-2017' # Globals ##################################################################### VERSIONED_TAG = namedtuple('VersionedTag', 'string version') def on_master(): '''Returns True if we're currently on the master branch''' <|code_end|> , predict the immediate next line with the help of imports: from collections import namedtuple from pkg_resources import parse_version from fabric.api import task from fabric.utils import abort from .helpers import ex, user_input, true from .ver import get_version and context (classes, functions, sometimes code) from other files: # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def user_input(prompt, default=None): # '''Gets input from the user''' # if sys.version_info[0] == 2: # answer = raw_input(prompt) # else: # answer = input(prompt) # # return answer or default # # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) # # Path: fabfile/ver.py # def get_version(): # '''Gets the current version''' # text = open(VER_FILE).read() # match = RE_VERSION.search(text) # # if not match: # raise Exception("Could not get version") # # return match.group('version') . Output only the next line.
(text, _) = ex(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
Using the snippet: <|code_start|> '''Returns True if nothing is staged or untracked''' (text, _) = ex(['git', 'status', '--porcelain']) return (not bool(text), text) @task def get_tags(): '''Returns a list of tags''' result = [] (text, _) = ex('git tag -l --sort=version:refname "*"') for line in text.splitlines(): result.append(VERSIONED_TAG(line, parse_version(line))) return sorted(result, cmp=lambda x, y: cmp(x.version, y.version)) @task def tag(): '''Create a tag''' current_version = get_version() tags = get_tags() latest_tag = tags[-1] if tags else '' print("...current version is: v%s" % current_version) if latest_tag: print("...latest tag is: %s" % latest_tag.string) default_version = 'v%s' % current_version <|code_end|> , determine the next line of code. You have imports: from collections import namedtuple from pkg_resources import parse_version from fabric.api import task from fabric.utils import abort from .helpers import ex, user_input, true from .ver import get_version and context (class names, function names, or code) available: # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def user_input(prompt, default=None): # '''Gets input from the user''' # if sys.version_info[0] == 2: # answer = raw_input(prompt) # else: # answer = input(prompt) # # return answer or default # # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) # # Path: fabfile/ver.py # def get_version(): # '''Gets the current version''' # text = open(VER_FILE).read() # match = RE_VERSION.search(text) # # if not match: # raise Exception("Could not get version") # # return match.group('version') . Output only the next line.
name = user_input("Enter tag to create [default to: %s]: " % default_version)
Continue the code snippet: <|code_start|> '''Returns a list of tags''' result = [] (text, _) = ex('git tag -l --sort=version:refname "*"') for line in text.splitlines(): result.append(VERSIONED_TAG(line, parse_version(line))) return sorted(result, cmp=lambda x, y: cmp(x.version, y.version)) @task def tag(): '''Create a tag''' current_version = get_version() tags = get_tags() latest_tag = tags[-1] if tags else '' print("...current version is: v%s" % current_version) if latest_tag: print("...latest tag is: %s" % latest_tag.string) default_version = 'v%s' % current_version name = user_input("Enter tag to create [default to: %s]: " % default_version) name = name or default_version name = "v" + name if not name.startswith('v') else name message = "creating tag %s" % name answer = user_input("creating tag [%s]. OK? " % name) <|code_end|> . Use current file imports: from collections import namedtuple from pkg_resources import parse_version from fabric.api import task from fabric.utils import abort from .helpers import ex, user_input, true from .ver import get_version and context (classes, functions, or code) from other files: # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def user_input(prompt, default=None): # '''Gets input from the user''' # if sys.version_info[0] == 2: # answer = raw_input(prompt) # else: # answer = input(prompt) # # return answer or default # # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) # # Path: fabfile/ver.py # def get_version(): # '''Gets the current version''' # text = open(VER_FILE).read() # match = RE_VERSION.search(text) # # if not match: # raise Exception("Could not get version") # # return match.group('version') . Output only the next line.
if not true(answer):
Continue the code snippet: <|code_start|>VERSIONED_TAG = namedtuple('VersionedTag', 'string version') def on_master(): '''Returns True if we're currently on the master branch''' (text, _) = ex(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) return "master" in text.lower() def is_clean(): '''Returns True if nothing is staged or untracked''' (text, _) = ex(['git', 'status', '--porcelain']) return (not bool(text), text) @task def get_tags(): '''Returns a list of tags''' result = [] (text, _) = ex('git tag -l --sort=version:refname "*"') for line in text.splitlines(): result.append(VERSIONED_TAG(line, parse_version(line))) return sorted(result, cmp=lambda x, y: cmp(x.version, y.version)) @task def tag(): '''Create a tag''' <|code_end|> . Use current file imports: from collections import namedtuple from pkg_resources import parse_version from fabric.api import task from fabric.utils import abort from .helpers import ex, user_input, true from .ver import get_version and context (classes, functions, or code) from other files: # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def user_input(prompt, default=None): # '''Gets input from the user''' # if sys.version_info[0] == 2: # answer = raw_input(prompt) # else: # answer = input(prompt) # # return answer or default # # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) # # Path: fabfile/ver.py # def get_version(): # '''Gets the current version''' # text = open(VER_FILE).read() # match = RE_VERSION.search(text) # # if not match: # raise Exception("Could not get version") # # return match.group('version') . Output only the next line.
current_version = get_version()
Given the following code snippet before the placeholder: <|code_start|> if not message: message = get_release_notes(tag) r = repo() r.create_git_release(tag, tag, message) def _upload(): tag = get_tags()[-1] # Make sure the release exists r = repo() github_release = next(( x for x in r.get_releases() if x.tag_name == tag.string), None) if not github_release: create_release(tag.string) # Find the tarball path = None for fname in os.listdir(DIST_DIR): if (str(tag.version) in fname) and fname.endswith('.tar.gz'): path = abspath(DIST_DIR, fname) break if not path: abort("Could not find tarball matching %s" % str(tag.version)) # Make life easier and call ``github-release.exe`` <|code_end|> , predict the next line using imports from the current file: import os import github from fabric.api import task from fabric.utils import abort from .constants import LIB_DIR, DIST_DIR from .helpers import ex, abspath from .git import get_tags from .relnote import get as get_release_notes and context including class names, function names, and sometimes code from other files: # Path: fabfile/constants.py # LIB_DIR = os.path.join(THIS_DIR, '..') # # DIST_DIR = os.path.join(LIB_DIR, 'dist') # # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def abspath(*args): # '''Returns the absolute path of join(*args).''' # return os.path.abspath(os.path.join(*args)) # # Path: fabfile/git.py # @task # def get_tags(): # '''Returns a list of tags''' # result = [] # (text, _) = ex('git tag -l --sort=version:refname "*"') # # for line in text.splitlines(): # result.append(VERSIONED_TAG(line, parse_version(line))) # # return sorted(result, cmp=lambda x, y: cmp(x.version, y.version)) # # Path: fabfile/relnote.py # @task # def get(version=None, path=RELEASE_NOTES_FILE, html='n', display='y'): # '''Return only the release notes for the specified version''' # return _get(version, path, html, display) . Output only the next line.
upload_bin = os.path.join(LIB_DIR, 'bin', 'github-release.exe')
Given the following code snippet before the placeholder: <|code_start|> print([x.name for x in u.get_repos()]) @task def create_release(tag=None, message=None): '''Create a GitHub release''' if not tag: tag = get_tags()[-1].string if not message: message = get_release_notes(tag) r = repo() r.create_git_release(tag, tag, message) def _upload(): tag = get_tags()[-1] # Make sure the release exists r = repo() github_release = next(( x for x in r.get_releases() if x.tag_name == tag.string), None) if not github_release: create_release(tag.string) # Find the tarball path = None <|code_end|> , predict the next line using imports from the current file: import os import github from fabric.api import task from fabric.utils import abort from .constants import LIB_DIR, DIST_DIR from .helpers import ex, abspath from .git import get_tags from .relnote import get as get_release_notes and context including class names, function names, and sometimes code from other files: # Path: fabfile/constants.py # LIB_DIR = os.path.join(THIS_DIR, '..') # # DIST_DIR = os.path.join(LIB_DIR, 'dist') # # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def abspath(*args): # '''Returns the absolute path of join(*args).''' # return os.path.abspath(os.path.join(*args)) # # Path: fabfile/git.py # @task # def get_tags(): # '''Returns a list of tags''' # result = [] # (text, _) = ex('git tag -l --sort=version:refname "*"') # # for line in text.splitlines(): # result.append(VERSIONED_TAG(line, parse_version(line))) # # return sorted(result, cmp=lambda x, y: cmp(x.version, y.version)) # # Path: fabfile/relnote.py # @task # def get(version=None, path=RELEASE_NOTES_FILE, html='n', display='y'): # '''Return only the release notes for the specified version''' # return _get(version, path, html, display) . Output only the next line.
for fname in os.listdir(DIST_DIR):
Given snippet: <|code_start|> # Make sure the release exists r = repo() github_release = next(( x for x in r.get_releases() if x.tag_name == tag.string), None) if not github_release: create_release(tag.string) # Find the tarball path = None for fname in os.listdir(DIST_DIR): if (str(tag.version) in fname) and fname.endswith('.tar.gz'): path = abspath(DIST_DIR, fname) break if not path: abort("Could not find tarball matching %s" % str(tag.version)) # Make life easier and call ``github-release.exe`` upload_bin = os.path.join(LIB_DIR, 'bin', 'github-release.exe') if not os.path.exists(upload_bin): raise Exception("github-release.exe not found") cmd = [ upload_bin, 'upload', '-s', GITHUB_TOKEN, '-u', 'mtik00', '-r', REPO_NAME, '-t', tag.string, '-n', os.path.basename(path), '-f', path ] <|code_end|> , continue by predicting the next line. Consider current file imports: import os import github from fabric.api import task from fabric.utils import abort from .constants import LIB_DIR, DIST_DIR from .helpers import ex, abspath from .git import get_tags from .relnote import get as get_release_notes and context: # Path: fabfile/constants.py # LIB_DIR = os.path.join(THIS_DIR, '..') # # DIST_DIR = os.path.join(LIB_DIR, 'dist') # # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def abspath(*args): # '''Returns the absolute path of join(*args).''' # return os.path.abspath(os.path.join(*args)) # # Path: fabfile/git.py # @task # def get_tags(): # '''Returns a list of tags''' # result = [] # (text, _) = ex('git tag -l --sort=version:refname "*"') # # for line in text.splitlines(): # result.append(VERSIONED_TAG(line, parse_version(line))) # # return sorted(result, cmp=lambda x, y: cmp(x.version, y.version)) # # Path: fabfile/relnote.py # @task # def get(version=None, path=RELEASE_NOTES_FILE, html='n', display='y'): # '''Return only the release notes for the specified version''' # return _get(version, path, html, display) which might include code, classes, or functions. Output only the next line.
ex(cmd)
Using the snippet: <|code_start|> @task def create_release(tag=None, message=None): '''Create a GitHub release''' if not tag: tag = get_tags()[-1].string if not message: message = get_release_notes(tag) r = repo() r.create_git_release(tag, tag, message) def _upload(): tag = get_tags()[-1] # Make sure the release exists r = repo() github_release = next(( x for x in r.get_releases() if x.tag_name == tag.string), None) if not github_release: create_release(tag.string) # Find the tarball path = None for fname in os.listdir(DIST_DIR): if (str(tag.version) in fname) and fname.endswith('.tar.gz'): <|code_end|> , determine the next line of code. You have imports: import os import github from fabric.api import task from fabric.utils import abort from .constants import LIB_DIR, DIST_DIR from .helpers import ex, abspath from .git import get_tags from .relnote import get as get_release_notes and context (class names, function names, or code) available: # Path: fabfile/constants.py # LIB_DIR = os.path.join(THIS_DIR, '..') # # DIST_DIR = os.path.join(LIB_DIR, 'dist') # # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def abspath(*args): # '''Returns the absolute path of join(*args).''' # return os.path.abspath(os.path.join(*args)) # # Path: fabfile/git.py # @task # def get_tags(): # '''Returns a list of tags''' # result = [] # (text, _) = ex('git tag -l --sort=version:refname "*"') # # for line in text.splitlines(): # result.append(VERSIONED_TAG(line, parse_version(line))) # # return sorted(result, cmp=lambda x, y: cmp(x.version, y.version)) # # Path: fabfile/relnote.py # @task # def get(version=None, path=RELEASE_NOTES_FILE, html='n', display='y'): # '''Return only the release notes for the specified version''' # return _get(version, path, html, display) . Output only the next line.
path = abspath(DIST_DIR, fname)
Predict the next line after this snippet: <|code_start|># Metadata #################################################################### __author__ = 'Timothy McFadden' __creationDate__ = '14-APR-2017' # Globals ##################################################################### GITHUB_USER = os.environ['GH_USERNAME'] GITHUB_TOKEN = os.environ['GH_TOKEN'] REPO_NAME = 'pyclimenu' def repo(): '''Retrieve the GitHub repo''' g = github.Github(GITHUB_USER, GITHUB_TOKEN) u = g.get_user() r = u.get_repo(REPO_NAME) return r def repo_list(): '''Retrieves a list of repos''' g = github.Github(GITHUB_USER, GITHUB_TOKEN) u = g.get_user() print([x.name for x in u.get_repos()]) @task def create_release(tag=None, message=None): '''Create a GitHub release''' if not tag: <|code_end|> using the current file's imports: import os import github from fabric.api import task from fabric.utils import abort from .constants import LIB_DIR, DIST_DIR from .helpers import ex, abspath from .git import get_tags from .relnote import get as get_release_notes and any relevant context from other files: # Path: fabfile/constants.py # LIB_DIR = os.path.join(THIS_DIR, '..') # # DIST_DIR = os.path.join(LIB_DIR, 'dist') # # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def abspath(*args): # '''Returns the absolute path of join(*args).''' # return os.path.abspath(os.path.join(*args)) # # Path: fabfile/git.py # @task # def get_tags(): # '''Returns a list of tags''' # result = [] # (text, _) = ex('git tag -l --sort=version:refname "*"') # # for line in text.splitlines(): # result.append(VERSIONED_TAG(line, parse_version(line))) # # return sorted(result, cmp=lambda x, y: cmp(x.version, y.version)) # # Path: fabfile/relnote.py # @task # def get(version=None, path=RELEASE_NOTES_FILE, html='n', display='y'): # '''Return only the release notes for the specified version''' # return _get(version, path, html, display) . Output only the next line.
tag = get_tags()[-1].string
Continue the code snippet: <|code_start|> # Globals ##################################################################### GITHUB_USER = os.environ['GH_USERNAME'] GITHUB_TOKEN = os.environ['GH_TOKEN'] REPO_NAME = 'pyclimenu' def repo(): '''Retrieve the GitHub repo''' g = github.Github(GITHUB_USER, GITHUB_TOKEN) u = g.get_user() r = u.get_repo(REPO_NAME) return r def repo_list(): '''Retrieves a list of repos''' g = github.Github(GITHUB_USER, GITHUB_TOKEN) u = g.get_user() print([x.name for x in u.get_repos()]) @task def create_release(tag=None, message=None): '''Create a GitHub release''' if not tag: tag = get_tags()[-1].string if not message: <|code_end|> . Use current file imports: import os import github from fabric.api import task from fabric.utils import abort from .constants import LIB_DIR, DIST_DIR from .helpers import ex, abspath from .git import get_tags from .relnote import get as get_release_notes and context (classes, functions, or code) from other files: # Path: fabfile/constants.py # LIB_DIR = os.path.join(THIS_DIR, '..') # # DIST_DIR = os.path.join(LIB_DIR, 'dist') # # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def abspath(*args): # '''Returns the absolute path of join(*args).''' # return os.path.abspath(os.path.join(*args)) # # Path: fabfile/git.py # @task # def get_tags(): # '''Returns a list of tags''' # result = [] # (text, _) = ex('git tag -l --sort=version:refname "*"') # # for line in text.splitlines(): # result.append(VERSIONED_TAG(line, parse_version(line))) # # return sorted(result, cmp=lambda x, y: cmp(x.version, y.version)) # # Path: fabfile/relnote.py # @task # def get(version=None, path=RELEASE_NOTES_FILE, html='n', display='y'): # '''Return only the release notes for the specified version''' # return _get(version, path, html, display) . Output only the next line.
message = get_release_notes(tag)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This module holds the management functions for interacting wity Pypi ''' # Imports ##################################################################### # Metadata #################################################################### __author__ = 'Timothy McFadden' __creationDate__ = '14-APR-2017' # Globals ##################################################################### @task def upload(): '''Upload the release files to Pypi''' command = ['twine', 'upload', 'dist/*'] <|code_end|> with the help of current file imports: from .helpers import ex from fabric.api import task and context from other files: # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) , which may contain function names, class names, or code. Output only the next line.
ex(command)
Using the snippet: <|code_start|># coding: utf-8 """ This script is used for project management. See Fabric documentation for more info: http://docs.fabfile.org/en/1.10/index.html """ # Imports ##################################################################### from __future__ import print_function # Internal # Metadata #################################################################### __author__ = "Timothy McFadden" __creationDate__ = "07-JUL-2017" # Fabric environment setup #################################################### env.colorize_errors = True ############################################################################### def _get(version=None, path=RELEASE_NOTES_FILE, html='n', display='n'): '''Return only the release notes for the specified version''' version = version or get_version() text = open(path).read() match = re.search('^(?P<notes># v?{0}.*?)^\*+$\n^$'.format(version), text, re.MULTILINE | re.DOTALL) if match: notes = match.group('notes').strip() <|code_end|> , determine the next line of code. You have imports: import os import re from markdown import markdown from fabric.api import env, task from fabric.colors import red from .helpers import true, ex from .constants import RELEASE_NOTES_FILE from .ver import get_version and context (class names, function names, or code) available: # Path: fabfile/helpers.py # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) # # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # Path: fabfile/constants.py # RELEASE_NOTES_FILE = os.path.join(LIB_DIR, 'release-notes.md') # # Path: fabfile/ver.py # def get_version(): # '''Gets the current version''' # text = open(VER_FILE).read() # match = RE_VERSION.search(text) # # if not match: # raise Exception("Could not get version") # # return match.group('version') . Output only the next line.
if true(html):
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python2.7 # coding: utf-8 """ This script is used for project management. See Fabric documentation for more info: http://docs.fabfile.org/en/1.10/index.html """ # Imports ##################################################################### from __future__ import print_function # Internal # Metadata #################################################################### __author__ = "Timothy McFadden" __creationDate__ = "07-JUL-2017" # Fabric environment setup #################################################### env.colorize_errors = True ############################################################################### <|code_end|> , predict the next line using imports from the current file: import os import re from markdown import markdown from fabric.api import env, task from fabric.colors import red from .helpers import true, ex from .constants import RELEASE_NOTES_FILE from .ver import get_version and context including class names, function names, and sometimes code from other files: # Path: fabfile/helpers.py # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) # # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # Path: fabfile/constants.py # RELEASE_NOTES_FILE = os.path.join(LIB_DIR, 'release-notes.md') # # Path: fabfile/ver.py # def get_version(): # '''Gets the current version''' # text = open(VER_FILE).read() # match = RE_VERSION.search(text) # # if not match: # raise Exception("Could not get version") # # return match.group('version') . Output only the next line.
def _get(version=None, path=RELEASE_NOTES_FILE, html='n', display='n'):
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python2.7 # coding: utf-8 """ This script is used for project management. See Fabric documentation for more info: http://docs.fabfile.org/en/1.10/index.html """ # Imports ##################################################################### from __future__ import print_function # Internal # Metadata #################################################################### __author__ = "Timothy McFadden" __creationDate__ = "07-JUL-2017" # Fabric environment setup #################################################### env.colorize_errors = True ############################################################################### def _get(version=None, path=RELEASE_NOTES_FILE, html='n', display='n'): '''Return only the release notes for the specified version''' <|code_end|> using the current file's imports: import os import re from markdown import markdown from fabric.api import env, task from fabric.colors import red from .helpers import true, ex from .constants import RELEASE_NOTES_FILE from .ver import get_version and any relevant context from other files: # Path: fabfile/helpers.py # def true(value): # '''Since fabric task inputs are always text, we need a way to convert it # to a boolean. # ''' # if isinstance(value, bool): # return value # elif isinstance(value, basestring): # return value.lower()[0] in ['y', 't', '1'] # # # Use the default representation # return bool(value) # # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # Path: fabfile/constants.py # RELEASE_NOTES_FILE = os.path.join(LIB_DIR, 'release-notes.md') # # Path: fabfile/ver.py # def get_version(): # '''Gets the current version''' # text = open(VER_FILE).read() # match = RE_VERSION.search(text) # # if not match: # raise Exception("Could not get version") # # return match.group('version') . Output only the next line.
version = version or get_version()
Next line prediction: <|code_start|> # Metadata #################################################################### __author__ = 'Timothy McFadden' __creationDate__ = '14-APR-2017' # Globals ##################################################################### def _build(): pass @task def build(): '''Build the release''' dist_dir = os.path.join(LIB_DIR, 'dist') setup_path = os.path.join(LIB_DIR, 'setup.py') command = [ sys.executable, setup_path, 'build', 'sdist', '--formats', 'gztar', 'bdist_wheel' ] # Delete older releases remove_directory(dist_dir, remove_top=False) <|code_end|> . Use current file imports: (import os import sys from fabric.api import task from fabric.colors import green from .helpers import ex, remove_directory from .constants import LIB_DIR) and context including class names, function names, or small code snippets from other files: # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def remove_directory(top, remove_top=True, filter=None): # ''' # Removes all files and directories, bottom-up. # # :param str top: The top-level directory to clean out # :param bool remove_top: Whether or not to delete the top # directory when cleared. # :param code filter: A function that returns True or False # based on the name of the file or folder. Returning # True means "delete it", False means "keep it". # ''' # if not os.path.isdir(top): # return # # if filter is None: # filter = lambda x: True # # for root, dirs, files in os.walk(top, topdown=False): # for name in [x for x in files if filter(x)]: # os.remove(os.path.join(root, name)) # # for name in [x for x in dirs if filter(x)]: # os.rmdir(os.path.join(root, name)) # # if remove_top: # try: # os.rmdir(top) # except OSError as e: # print("error removing top:", e.message, file=sys.stderr) # # Path: fabfile/constants.py # LIB_DIR = os.path.join(THIS_DIR, '..') . Output only the next line.
ex(command)
Based on the snippet: <|code_start|># Imports ##################################################################### # Metadata #################################################################### __author__ = 'Timothy McFadden' __creationDate__ = '14-APR-2017' # Globals ##################################################################### def _build(): pass @task def build(): '''Build the release''' dist_dir = os.path.join(LIB_DIR, 'dist') setup_path = os.path.join(LIB_DIR, 'setup.py') command = [ sys.executable, setup_path, 'build', 'sdist', '--formats', 'gztar', 'bdist_wheel' ] # Delete older releases <|code_end|> , predict the immediate next line with the help of imports: import os import sys from fabric.api import task from fabric.colors import green from .helpers import ex, remove_directory from .constants import LIB_DIR and context (classes, functions, sometimes code) from other files: # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def remove_directory(top, remove_top=True, filter=None): # ''' # Removes all files and directories, bottom-up. # # :param str top: The top-level directory to clean out # :param bool remove_top: Whether or not to delete the top # directory when cleared. # :param code filter: A function that returns True or False # based on the name of the file or folder. Returning # True means "delete it", False means "keep it". # ''' # if not os.path.isdir(top): # return # # if filter is None: # filter = lambda x: True # # for root, dirs, files in os.walk(top, topdown=False): # for name in [x for x in files if filter(x)]: # os.remove(os.path.join(root, name)) # # for name in [x for x in dirs if filter(x)]: # os.rmdir(os.path.join(root, name)) # # if remove_top: # try: # os.rmdir(top) # except OSError as e: # print("error removing top:", e.message, file=sys.stderr) # # Path: fabfile/constants.py # LIB_DIR = os.path.join(THIS_DIR, '..') . Output only the next line.
remove_directory(dist_dir, remove_top=False)
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This module holds the function for building the python installers. ''' # Imports ##################################################################### # Metadata #################################################################### __author__ = 'Timothy McFadden' __creationDate__ = '14-APR-2017' # Globals ##################################################################### def _build(): pass @task def build(): '''Build the release''' <|code_end|> . Use current file imports: import os import sys from fabric.api import task from fabric.colors import green from .helpers import ex, remove_directory from .constants import LIB_DIR and context (classes, functions, or code) from other files: # Path: fabfile/helpers.py # def ex(command, cwd=None, shell=None, raise_on_nonzero=True): # """Execute a command and return the output. This will raise an Exception if # the return code is non-zero. # # :param str/list command: Either a string or a list of arguments. # :param bool shell: If None, "shell" will be determined by the type of # `command` (str -> shell=True; list -> shell=False) # :param bool raise_on_nonzero: Raise an exception if the return code of the # process is not zero. # :returns: tuple(text, returncode) # """ # shell = shell if (shell is not None) else (type(command) is not list) # # p = subprocess.Popen( # command, shell=shell, cwd=cwd, stderr=subprocess.STDOUT, # stdout=subprocess.PIPE) # # output, _ = p.communicate() # # if p.returncode and raise_on_nonzero: # raise Exception("command failed: %s" % output) # # return (output, p.returncode) # # def remove_directory(top, remove_top=True, filter=None): # ''' # Removes all files and directories, bottom-up. # # :param str top: The top-level directory to clean out # :param bool remove_top: Whether or not to delete the top # directory when cleared. # :param code filter: A function that returns True or False # based on the name of the file or folder. Returning # True means "delete it", False means "keep it". # ''' # if not os.path.isdir(top): # return # # if filter is None: # filter = lambda x: True # # for root, dirs, files in os.walk(top, topdown=False): # for name in [x for x in files if filter(x)]: # os.remove(os.path.join(root, name)) # # for name in [x for x in dirs if filter(x)]: # os.rmdir(os.path.join(root, name)) # # if remove_top: # try: # os.rmdir(top) # except OSError as e: # print("error removing top:", e.message, file=sys.stderr) # # Path: fabfile/constants.py # LIB_DIR = os.path.join(THIS_DIR, '..') . Output only the next line.
dist_dir = os.path.join(LIB_DIR, 'dist')
Based on the snippet: <|code_start|> class SubscriptionContext: next_proc_id = 1 def __init__(self, address, objectID, confirmed=None, lifetime=None, callback=None): self.address = address self.subscriberProcessIdentifier = SubscriptionContext.next_proc_id SubscriptionContext.next_proc_id += 1 self.monitoredObjectIdentifier = objectID self.issueConfirmedNotifications = confirmed self.lifetime = lifetime self.callback = callback def cov_notification(self, apdu): # make a rash assumption that the property value is going to be # a single application encoded tag source = apdu.pduSource object_changed = apdu.monitoredObjectIdentifier elements = { "source": source, "object_changed": object_changed, "properties": {}, } for element in apdu.listOfValues: prop_id = element.propertyIdentifier datatype = get_datatype(object_changed[0], prop_id) value = element.value if not datatype: <|code_end|> , predict the immediate next line with the help of imports: from bacpypes.apdu import SubscribeCOVRequest, SimpleAckPDU, RejectPDU, AbortPDU from bacpypes.iocb import IOCB from bacpypes.core import deferred from bacpypes.pdu import Address from bacpypes.object import get_object_class, get_datatype from bacpypes.constructeddata import Array from bacpypes.primitivedata import Tag, ObjectIdentifier, Unsigned from BAC0.core.io.Read import cast_datatype_from_tag and context (classes, functions, sometimes code) from other files: # Path: BAC0/core/io/Read.py # def cast_datatype_from_tag(propertyValue, obj_id, prop_id): # try: # tag_list = propertyValue.tagList.tagList # if tag_list[0].tagClass == 0: # tag = tag_list[0].tagNumber # # datatype = Tag._app_tag_class[tag] # else: # from bacpypes.constructeddata import ArrayOf # # subtype_tag = propertyValue.tagList.tagList[0].tagList[0].tagNumber # datatype = ArrayOf(Tag._app_tag_class[subtype_tag]) # value = {"{}_{}".format(obj_id, prop_id): propertyValue.cast_out(datatype)} # except: # value = {"{}_{}".format(obj_id, prop_id): propertyValue} # return value . Output only the next line.
value = cast_datatype_from_tag(
Using the snippet: <|code_start|> def create_BI(oid=1, pv=0, name="BI", activeText="On", inactiveText="Off"): deprecate_msg() return BinaryInputObject( objectIdentifier=("binaryInput", oid), objectName=name, presentValue=pv, activeText=activeText, inactiveText=inactiveText, statusFlags=StatusFlags(), ) def create_AO(oid=1, pv=0, name="AO", units=None, pv_writable=False): aoo = AnalogOutputObject( objectIdentifier=("analogOutput", oid), objectName=name, presentValue=pv, units=units, priorityArray=PriorityArray(), statusFlags=StatusFlags(), ) aoo = _make_mutable(aoo, mutable=pv_writable) deprecate_msg() return aoo def create_BO( oid=1, pv=0, name="BO", activeText="On", inactiveText="Off", pv_writable=False ): <|code_end|> , determine the next line of code. You have imports: from bacpypes.object import ( MultiStateValueObject, AnalogValueObject, BinaryValueObject, AnalogInputObject, BinaryInputObject, AnalogOutputObject, BinaryOutputObject, CharacterStringValueObject, DateTimeValueObject, Property, register_object_type, ) from bacpypes.local.object import ( AnalogOutputCmdObject, AnalogValueCmdObject, BinaryOutputCmdObject, BinaryValueCmdObject, ) from bacpypes.primitivedata import CharacterString, Date, Time, Real, Boolean from bacpypes.constructeddata import ArrayOf from bacpypes.basetypes import EngineeringUnits, DateTime, PriorityArray, StatusFlags from .mixins.CommandableMixin import LocalBinaryOutputObjectCmd and context (class names, function names, or code) available: # Path: BAC0/core/devices/mixins/CommandableMixin.py # class LocalBinaryOutputObjectCmd(CurrentPropertyListMixIn, BinaryOutputObjectCmd): # pass . Output only the next line.
boo = LocalBinaryOutputObjectCmd(
Given the following code snippet before the placeholder: <|code_start|> """ This sample creates an Excel file containing one sheet per controller found on the network Each sheet contyains all the points known by BAC0. Some proprietary point could not display here. """ EXCEL_FILE_NAME = "all_controllers_and_points.xlsx" def create_data(discovered_devices, network): devices = {} dataframes = {} for each in discovered_devices: name, vendor, address, device_id = each # try excep eventually as we may have some issues with werid devices if "TEC3000" in name: <|code_end|> , predict the next line using imports from the current file: import BAC0 import time import pandas as pd from BAC0.core.proprietary_objects.jci import tec_short_point_list and context including class names, function names, and sometimes code from other files: # Path: BAC0/core/proprietary_objects/jci.py # def tec_short_point_list(unit_type="2-pipe"): # """ # unit_type can be : # - 4-pipe # - 2-pipe # - VAV # """ # _lst = [ # ("binaryInput", 30827), # ("binaryInput", 30828), # ("binaryOutput", 86908), # ("binaryOutput", 86909), # ("binaryOutput", 86910), # ("binaryOutput", 86911), # ("binaryOutput", 86912), # ("binaryOutput", 87101), # ("binaryOutput", 87102), # ("multiStateValue", 29501), # ("multiStateValue", 29500), # ("multiStateValue", 29509), # ("multiStateValue", 29517), # ("multiStateValue", 29518), # ("multiStateValue", 29519), # ("multiStateValue", 29520), # ("multiStateValue", 29524), # ("multiStateValue", 29525), # ("multiStateValue", 29527), # ("multiStateValue", 29712), # ("multiStateValue", 29700), # ("multiStateValue", 29709), # ("multiStateValue", 29708), # ("analogValue", 29505), # ("analogValue", 29502), # ("analogValue", 29503), # ("analogValue", 29504), # ("analogValue", 29506), # ("analogValue", 29507), # ("analogValue", 29508), # ("analogValue", 29515), # ("analogValue", 29522), # ("analogValue", 29529), # ("analogValue", 29530), # ("analogValue", 29532), # ("analogValue", 29701), # ("analogValue", 29703), # ("analogValue", 29705), # ("analogValue", 29706), # ("analogValue", 29707), # ("analogValue", 29714), # ("analogValue", 29717), # ("analogValue", 29725), # ("analogValue", 29726), # ("analogValue", 29727), # ("analogOutput", 86905), # ("multiStateValue", 6), # ("trendLog", 101010), # ] # if unit_type == "4-pipe": # _lst.append(("analogOutput", 86914)) # _lst.append(("analogOutput", 86915)) # # return _lst . Output only the next line.
custom_obj_list = tec_short_point_list()
Predict the next line for this snippet: <|code_start|> def points_from_sql(self, db_name): """ Retrieve point list from SQL database """ points = self._read_from_sql("SELECT * FROM history;", db_name) return list(points.columns.values)[1:] def his_from_sql(self, db_name, point): """ Retrive point histories from SQL database """ his = self._read_from_sql('select * from "{}"'.format("history", db_name)) his.index = his["index"].apply(Timestamp) return his.set_index("index")[point] def value_from_sql(self, db_name, point): """ Take last known value as the value """ return self.his_from_sql(db_name, point).last_valid_index() def read_point_prop(self, device_name, point): """ Points properties retrieved from pickle """ with open("{}.bin".format(device_name), "rb") as file: try: _point = pickle.load(file)["points"][point] except KeyError: <|code_end|> with the help of current file imports: import pickle import os.path import sqlite3 import contextlib import pandas as pd from pandas.io import sql from pandas.core.base import DataError from pandas import Timestamp from pandas.lib import Timestamp from ..core.io.IOExceptions import RemovedPointException, NoResponseFromController and context from other files: # Path: BAC0/core/io/IOExceptions.py # class RemovedPointException(Exception): # """ # When defining a device from DB it may not be identical to the # actual device. # """ # # pass # # class NoResponseFromController(Exception): # """ # This exception is used when trying to read or write and there is not answer. # """ # # pass , which may contain function names, class names, or code. Output only the next line.
raise RemovedPointException(
Given the following code snippet before the placeholder: <|code_start|> ) else: return df def save(self, filename=None, resampling=None): """ Save the point histories to sqlite3 database. Save the device object properties to a pickle file so the device can be reloaded. Resampling : valid Pandas resampling frequency. If 0 or False, dataframe will not be resampled on save. """ if not _PANDAS: self._log.error("Pandas is required to save to SQLite.") return if filename: if ".db" in filename: filename = filename.split(".")[0] self.properties.db_name = filename else: self.properties.db_name = "Device_{}".format(self.properties.device_id) if resampling is None: resampling = self.properties.save_resampling # Does file exist? If so, append data def _df_to_backup(): try: return self.backup_histories_df(resampling=resampling) <|code_end|> , predict the next line using imports from the current file: import pickle import os.path import sqlite3 import contextlib import pandas as pd from pandas.io import sql from pandas.core.base import DataError from pandas import Timestamp from pandas.lib import Timestamp from ..core.io.IOExceptions import RemovedPointException, NoResponseFromController and context including class names, function names, and sometimes code from other files: # Path: BAC0/core/io/IOExceptions.py # class RemovedPointException(Exception): # """ # When defining a device from DB it may not be identical to the # actual device. # """ # # pass # # class NoResponseFromController(Exception): # """ # This exception is used when trying to read or write and there is not answer. # """ # # pass . Output only the next line.
except (DataError, NoResponseFromController):
Given the following code snippet before the placeholder: <|code_start|> self.ip = ip self.notifications_log = [] self.notifications_list = "" self.config_flask_app() self.exitFlag = False @property def network(self): return self._network_ref() def run(self): self.process() def process(self): while not self.exitFlag: self.task() def startServer(self): self.flask_app.run(port=self.port, host="0.0.0.0") self.flask_app.logger.removeHandler(default_handler) def config_flask_app(self): @self.flask_app.route("/trends", methods=["GET"]) def bkapp_trends_page(): if self.network.registered_devices: script = server_document("http://{}:5006/trends".format(self.ip)) else: script = "<div>No devices registered yet...</div>" return render_template( "trends.html", <|code_end|> , predict the next line using imports from the current file: from threading import Thread from flask import Flask, render_template, jsonify, request from flask_bootstrap import Bootstrap from bokeh.embed import server_document from .templates import create_sidebar, create_card, update_notifications from flask.logging import default_handler import weakref import logging import json and context including class names, function names, and sometimes code from other files: # Path: BAC0/web/templates.py # def create_sidebar(dash_class="", devices_class="", trends_class=""): # sb = """ # <div class="wrapper"> # <div class="sidebar" data-background-color="white" data-active-color="danger"> # <!-- # Tip 1: you can change the color of the sidebar's background using: data-background-color="white | black" # Tip 2: you can change the color of the active button using the data-active-color="primary | info | success | warning | danger" # --> # <div class="sidebar-wrapper"> # <div class="logo"> # <a href="https://github.com/ChristianTremblay/BAC0" class="simple-text">BAC0</a> # </div> # <ul class="nav"> # <li {}><a href="/"> # <i class="ti-panel"></i> # <p>Dashboard</p> # </a> # </li> # <li {}><a href="/trends"> # <i class="ti-panel"></i> # <p>Trend</p> # </a> # </li> # <li {}><a href="/dash_devices"> # <i class="ti-view-list-alt"></i> # <p>Devices</p> # </a> # </li> # </ul> # </div> # </div> # """.format( # dash_class, trends_class, devices_class # ) # return sb # # def create_card( # icon="ti-server", # title="title", # data="None", # id_data="generic_data", # foot_icon="ti-reload", # foot_data="None", # id_foot_data="generic_foot_data", # ): # card = """ # <div class="col-lg-3 col-sm-6"> # <div class="card"> # <div class="content"> # <div class="row"> # <div class="col-xs-5"> # <div class="icon-big icon-success text-center"> # <i class="{}"></i> # </div> # </div> # <div class="col-xs-7"> # <div class="numbers"> # <p>{}</p> # <div id="{}">{}</div> # </div> # </div> # </div> # <div class="footer"> # <hr /> # <div class="stats"> # <i class="{}"></i> <div id="{}">{}</div> # </div> # </div> # </div> # </div> # </div> # """.format( # icon, title, id_data, data, foot_icon, id_foot_data, foot_data # ) # return card # # def update_notifications(log, new_msg): # notif_log = log # max_notifications = 5 # if new_msg: # notif_log.insert(0, new_msg) # if len(notif_log) > max_notifications: # notif_log.pop() # # notif_list = '<ul class="dropdown-menu">' # for notif in notif_log: # notif_list += '<li><a href="#">' + notif + "</a></li>" # if len(notif_log) == 0: # notif_list += '<li><a href="#">Nothing yet</a></li>' # notif_list += "</ul>" # return notif_list . Output only the next line.
sidebar=create_sidebar(trends_class='class="active"'),
Given the code snippet: <|code_start|> self.flask_app.run(port=self.port, host="0.0.0.0") self.flask_app.logger.removeHandler(default_handler) def config_flask_app(self): @self.flask_app.route("/trends", methods=["GET"]) def bkapp_trends_page(): if self.network.registered_devices: script = server_document("http://{}:5006/trends".format(self.ip)) else: script = "<div>No devices registered yet...</div>" return render_template( "trends.html", sidebar=create_sidebar(trends_class='class="active"'), bokeh_script=script, template="Flask", ) # @self.flask_app.route('/devices', methods=['GET']) # def bkapp_devices_page(): # script = server_document('http://localhost:5006/devices') # return render_template("embed.html", script=script, template="Flask") @self.flask_app.route("/notes", methods=["GET"]) def bkapp_notes_page(): script = server_document("http://{}:5006/notes".format(self.ip)) return render_template("embed.html", script=script, template="Flask") @self.flask_app.route("/", methods=["GET"]) def home_page(): # Stat number of devices <|code_end|> , generate the next line using the imports in this file: from threading import Thread from flask import Flask, render_template, jsonify, request from flask_bootstrap import Bootstrap from bokeh.embed import server_document from .templates import create_sidebar, create_card, update_notifications from flask.logging import default_handler import weakref import logging import json and context (functions, classes, or occasionally code) from other files: # Path: BAC0/web/templates.py # def create_sidebar(dash_class="", devices_class="", trends_class=""): # sb = """ # <div class="wrapper"> # <div class="sidebar" data-background-color="white" data-active-color="danger"> # <!-- # Tip 1: you can change the color of the sidebar's background using: data-background-color="white | black" # Tip 2: you can change the color of the active button using the data-active-color="primary | info | success | warning | danger" # --> # <div class="sidebar-wrapper"> # <div class="logo"> # <a href="https://github.com/ChristianTremblay/BAC0" class="simple-text">BAC0</a> # </div> # <ul class="nav"> # <li {}><a href="/"> # <i class="ti-panel"></i> # <p>Dashboard</p> # </a> # </li> # <li {}><a href="/trends"> # <i class="ti-panel"></i> # <p>Trend</p> # </a> # </li> # <li {}><a href="/dash_devices"> # <i class="ti-view-list-alt"></i> # <p>Devices</p> # </a> # </li> # </ul> # </div> # </div> # """.format( # dash_class, trends_class, devices_class # ) # return sb # # def create_card( # icon="ti-server", # title="title", # data="None", # id_data="generic_data", # foot_icon="ti-reload", # foot_data="None", # id_foot_data="generic_foot_data", # ): # card = """ # <div class="col-lg-3 col-sm-6"> # <div class="card"> # <div class="content"> # <div class="row"> # <div class="col-xs-5"> # <div class="icon-big icon-success text-center"> # <i class="{}"></i> # </div> # </div> # <div class="col-xs-7"> # <div class="numbers"> # <p>{}</p> # <div id="{}">{}</div> # </div> # </div> # </div> # <div class="footer"> # <hr /> # <div class="stats"> # <i class="{}"></i> <div id="{}">{}</div> # </div> # </div> # </div> # </div> # </div> # """.format( # icon, title, id_data, data, foot_icon, id_foot_data, foot_data # ) # return card # # def update_notifications(log, new_msg): # notif_log = log # max_notifications = 5 # if new_msg: # notif_log.insert(0, new_msg) # if len(notif_log) > max_notifications: # notif_log.pop() # # notif_list = '<ul class="dropdown-menu">' # for notif in notif_log: # notif_list += '<li><a href="#">' + notif + "</a></li>" # if len(notif_log) == 0: # notif_list += '<li><a href="#">Nothing yet</a></li>' # notif_list += "</ul>" # return notif_list . Output only the next line.
cnod = create_card(
Given the following code snippet before the placeholder: <|code_start|> icon="ti-server", title="Number of devices", data=self.network.number_of_devices, id_data="devices", foot_icon="ti-reload", foot_data="Refresh to update", ) cnot = create_card( icon="ti-bar-chart", title="Number of trends", data=self.network.number_of_registered_trends, id_data="trends", foot_icon="ti-timer", foot_data="Add trends !", ) cnmn = create_card( icon="ti-plug", title="{} MSTP Networks".format( len(self.network.network_stats["mstp_networks"]) ), data="# {}".format(self.network.network_stats["print_mstpnetworks"]), id_data="mstpnetworks", foot_icon="ti-timer", foot_data="Last update : {}".format( self.network.network_stats["timestamp"] ), id_foot_data="lastwhoisupdate", ) <|code_end|> , predict the next line using imports from the current file: from threading import Thread from flask import Flask, render_template, jsonify, request from flask_bootstrap import Bootstrap from bokeh.embed import server_document from .templates import create_sidebar, create_card, update_notifications from flask.logging import default_handler import weakref import logging import json and context including class names, function names, and sometimes code from other files: # Path: BAC0/web/templates.py # def create_sidebar(dash_class="", devices_class="", trends_class=""): # sb = """ # <div class="wrapper"> # <div class="sidebar" data-background-color="white" data-active-color="danger"> # <!-- # Tip 1: you can change the color of the sidebar's background using: data-background-color="white | black" # Tip 2: you can change the color of the active button using the data-active-color="primary | info | success | warning | danger" # --> # <div class="sidebar-wrapper"> # <div class="logo"> # <a href="https://github.com/ChristianTremblay/BAC0" class="simple-text">BAC0</a> # </div> # <ul class="nav"> # <li {}><a href="/"> # <i class="ti-panel"></i> # <p>Dashboard</p> # </a> # </li> # <li {}><a href="/trends"> # <i class="ti-panel"></i> # <p>Trend</p> # </a> # </li> # <li {}><a href="/dash_devices"> # <i class="ti-view-list-alt"></i> # <p>Devices</p> # </a> # </li> # </ul> # </div> # </div> # """.format( # dash_class, trends_class, devices_class # ) # return sb # # def create_card( # icon="ti-server", # title="title", # data="None", # id_data="generic_data", # foot_icon="ti-reload", # foot_data="None", # id_foot_data="generic_foot_data", # ): # card = """ # <div class="col-lg-3 col-sm-6"> # <div class="card"> # <div class="content"> # <div class="row"> # <div class="col-xs-5"> # <div class="icon-big icon-success text-center"> # <i class="{}"></i> # </div> # </div> # <div class="col-xs-7"> # <div class="numbers"> # <p>{}</p> # <div id="{}">{}</div> # </div> # </div> # </div> # <div class="footer"> # <hr /> # <div class="stats"> # <i class="{}"></i> <div id="{}">{}</div> # </div> # </div> # </div> # </div> # </div> # """.format( # icon, title, id_data, data, foot_icon, id_foot_data, foot_data # ) # return card # # def update_notifications(log, new_msg): # notif_log = log # max_notifications = 5 # if new_msg: # notif_log.insert(0, new_msg) # if len(notif_log) > max_notifications: # notif_log.pop() # # notif_list = '<ul class="dropdown-menu">' # for notif in notif_log: # notif_list += '<li><a href="#">' + notif + "</a></li>" # if len(notif_log) == 0: # notif_list += '<li><a href="#">Nothing yet</a></li>' # notif_list += "</ul>" # return notif_list . Output only the next line.
notif = update_notifications(self.notifications_log, None)
Given the code snippet: <|code_start|> request = WritePropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id ) request.pduDestination = Address(addr) _value = Any() _value.cast_in(CharacterString(value)) request.propertyValue = _value return request def write_text_value(self, request, timeout=10): try: iocb = IOCB(request) iocb.set_timeout(timeout) # pass to the BACnet stack deferred(self.this_application.request_io, iocb) iocb.wait() # Wait for BACnet response if iocb.ioResponse: # successful response apdu = iocb.ioResponse if not isinstance(apdu, SimpleAckPDU): # expect an ACK self._log.error("Not an ack, see debug for more infos.") return if iocb.ioError: # unsuccessful: error/reject/abort apdu = iocb.ioError reason = find_reason(apdu) <|code_end|> , generate the next line using the imports in this file: from bacpypes.iocb import IOCB from bacpypes.core import deferred from bacpypes.apdu import WritePropertyRequest, SimpleAckPDU from bacpypes.primitivedata import CharacterString from bacpypes.constructeddata import Any from bacpypes.pdu import Address from BAC0.core.io.IOExceptions import NoResponseFromController, WritePropertyException from BAC0.core.io.Read import find_reason and context (functions, classes, or occasionally code) from other files: # Path: BAC0/core/io/IOExceptions.py # class NoResponseFromController(Exception): # """ # This exception is used when trying to read or write and there is not answer. # """ # # pass # # class WritePropertyException(Exception): # """ # This exception is used when trying to write a property. # """ # # pass # # Path: BAC0/core/io/Read.py # def find_reason(apdu): # try: # if apdu == TimeoutError: # return "Timeout" # elif apdu.pduType == RejectPDU.pduType: # reasons = RejectReason.enumerations # elif apdu.pduType == AbortPDU.pduType: # reasons = AbortReason.enumerations # else: # if apdu.errorCode and apdu.errorClass: # return "{}".format(apdu.errorCode) # else: # raise ValueError("Cannot find reason...") # code = apdu.apduAbortRejectReason # try: # return [k for k, v in reasons.items() if v == code][0] # except IndexError: # return code # except KeyError as err: # return "KeyError: {} has no key {0!r}".format(type(apdu), err.args[0]) . Output only the next line.
raise NoResponseFromController("APDU Abort Reason : {}".format(reason))
Continue the code snippet: <|code_start|> ) request.pduDestination = Address(addr) _value = Any() _value.cast_in(CharacterString(value)) request.propertyValue = _value return request def write_text_value(self, request, timeout=10): try: iocb = IOCB(request) iocb.set_timeout(timeout) # pass to the BACnet stack deferred(self.this_application.request_io, iocb) iocb.wait() # Wait for BACnet response if iocb.ioResponse: # successful response apdu = iocb.ioResponse if not isinstance(apdu, SimpleAckPDU): # expect an ACK self._log.error("Not an ack, see debug for more infos.") return if iocb.ioError: # unsuccessful: error/reject/abort apdu = iocb.ioError reason = find_reason(apdu) raise NoResponseFromController("APDU Abort Reason : {}".format(reason)) <|code_end|> . Use current file imports: from bacpypes.iocb import IOCB from bacpypes.core import deferred from bacpypes.apdu import WritePropertyRequest, SimpleAckPDU from bacpypes.primitivedata import CharacterString from bacpypes.constructeddata import Any from bacpypes.pdu import Address from BAC0.core.io.IOExceptions import NoResponseFromController, WritePropertyException from BAC0.core.io.Read import find_reason and context (classes, functions, or code) from other files: # Path: BAC0/core/io/IOExceptions.py # class NoResponseFromController(Exception): # """ # This exception is used when trying to read or write and there is not answer. # """ # # pass # # class WritePropertyException(Exception): # """ # This exception is used when trying to write a property. # """ # # pass # # Path: BAC0/core/io/Read.py # def find_reason(apdu): # try: # if apdu == TimeoutError: # return "Timeout" # elif apdu.pduType == RejectPDU.pduType: # reasons = RejectReason.enumerations # elif apdu.pduType == AbortPDU.pduType: # reasons = AbortReason.enumerations # else: # if apdu.errorCode and apdu.errorClass: # return "{}".format(apdu.errorCode) # else: # raise ValueError("Cannot find reason...") # code = apdu.apduAbortRejectReason # try: # return [k for k, v in reasons.items() if v == code][0] # except IndexError: # return code # except KeyError as err: # return "KeyError: {} has no key {0!r}".format(type(apdu), err.args[0]) . Output only the next line.
except WritePropertyException as error:
Predict the next line after this snippet: <|code_start|> ): request = WritePropertyRequest( objectIdentifier=(obj_type, obj_inst), propertyIdentifier=prop_id ) request.pduDestination = Address(addr) _value = Any() _value.cast_in(CharacterString(value)) request.propertyValue = _value return request def write_text_value(self, request, timeout=10): try: iocb = IOCB(request) iocb.set_timeout(timeout) # pass to the BACnet stack deferred(self.this_application.request_io, iocb) iocb.wait() # Wait for BACnet response if iocb.ioResponse: # successful response apdu = iocb.ioResponse if not isinstance(apdu, SimpleAckPDU): # expect an ACK self._log.error("Not an ack, see debug for more infos.") return if iocb.ioError: # unsuccessful: error/reject/abort apdu = iocb.ioError <|code_end|> using the current file's imports: from bacpypes.iocb import IOCB from bacpypes.core import deferred from bacpypes.apdu import WritePropertyRequest, SimpleAckPDU from bacpypes.primitivedata import CharacterString from bacpypes.constructeddata import Any from bacpypes.pdu import Address from BAC0.core.io.IOExceptions import NoResponseFromController, WritePropertyException from BAC0.core.io.Read import find_reason and any relevant context from other files: # Path: BAC0/core/io/IOExceptions.py # class NoResponseFromController(Exception): # """ # This exception is used when trying to read or write and there is not answer. # """ # # pass # # class WritePropertyException(Exception): # """ # This exception is used when trying to write a property. # """ # # pass # # Path: BAC0/core/io/Read.py # def find_reason(apdu): # try: # if apdu == TimeoutError: # return "Timeout" # elif apdu.pduType == RejectPDU.pduType: # reasons = RejectReason.enumerations # elif apdu.pduType == AbortPDU.pduType: # reasons = AbortReason.enumerations # else: # if apdu.errorCode and apdu.errorClass: # return "{}".format(apdu.errorCode) # else: # raise ValueError("Cannot find reason...") # code = apdu.apduAbortRejectReason # try: # return [k for k, v in reasons.items() if v == code][0] # except IndexError: # return code # except KeyError as err: # return "KeyError: {} has no key {0!r}".format(type(apdu), err.args[0]) . Output only the next line.
reason = find_reason(apdu)
Using the snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2015 by Christian Tremblay, P.Eng <christian.tremblay@servisys.com> # # Licensed under LGPLv3, see file LICENSE in this source tree. """ Utility function to retrieve a functionnal IP and a correct broadcast IP address. Goal : not use 255.255.255.255 as a broadcast IP address as it is not accepted by every devices (>3.8.38.1 bacnet.jar of Tridium Jace for example) """ <|code_end|> , determine the next line of code. You have imports: from bacpypes.pdu import Address from ..io.IOExceptions import NetworkInterfaceException from ...core.utils.notes import note_and_log import socket import subprocess import ipaddress import sys import re import netifaces and context (class names, function names, or code) available: # Path: BAC0/core/io/IOExceptions.py # class NetworkInterfaceException(Exception): # """ # This exception covers different network related exc eption (like finding IP # or subnet mask...) # """ # # pass # # Path: BAC0/core/utils/notes.py # def note_and_log(cls): # """ # This will be used as a decorator on class to activate # logging and store messages in the variable cls._notes # This will allow quick access to events in the web app. # A note can be added to cls._notes without logging if passing # the argument log=false to function note() # Something can be logged without addind a note using function log() # """ # if hasattr(cls, "DEBUG_LEVEL"): # if cls.DEBUG_LEVEL == "debug": # file_level = logging.DEBUG # console_level = logging.DEBUG # elif cls.DEBUG_LEVEL == "info": # file_level = logging.INFO # console_level = logging.INFO # else: # file_level = logging.WARNING # console_level = logging.INFO # # Notes object # cls._notes = namedtuple("_notes", ["timestamp", "notes"]) # cls._notes.timestamp = [] # cls._notes.notes = [] # # # Defining log object # cls.logname = "{} | {}".format(cls.__module__, cls.__name__) # cls._log = logging.getLogger("BAC0_Root.{}.{}".format(cls.__module__, cls.__name__)) # # # Set level to debug so filter is done by handler # cls._log.setLevel(logging.DEBUG) # # # Console Handler # ch = logging.StreamHandler(sys.stderr) # ch.set_name("stderr") # ch.setLevel(logging.CRITICAL) # # ch2 = logging.StreamHandler(sys.stdout) # ch2.set_name("stdout") # ch2.setLevel(console_level) # # formatter = logging.Formatter("{asctime} - {levelname:<8}| {message}", style="{") # # # File Handler # _PERMISSION_TO_WRITE = True # logUserPath = expanduser("~") # logSaveFilePath = join(logUserPath, ".BAC0") # # logFile = join(logSaveFilePath, "BAC0.log") # try: # if not os.path.exists(logSaveFilePath): # os.makedirs(logSaveFilePath) # fh = FileHandler(logFile) # fh.set_name("file_handler") # fh.setLevel(file_level) # fh.setFormatter(formatter) # # except OSError: # _PERMISSION_TO_WRITE = False # # ch.setFormatter(formatter) # ch2.setFormatter(formatter) # # Add handlers the first time only... # if not len(cls._log.handlers): # if _PERMISSION_TO_WRITE: # cls._log.addHandler(fh) # cls._log.addHandler(ch) # cls._log.addHandler(ch2) # # LogList.LOGGERS.append(cls._log) # # def log_title(self, title, args=None, width=35): # cls._log.debug("") # cls._log.debug("#" * width) # cls._log.debug("# {}".format(title)) # cls._log.debug("#" * width) # if args: # cls._log.debug("{!r}".format(args)) # cls._log.debug("#" * 35) # # def log_subtitle(self, subtitle, args=None, width=35): # cls._log.debug("") # cls._log.debug("=" * width) # cls._log.debug("{}".format(subtitle)) # cls._log.debug("=" * width) # if args: # cls._log.debug("{!r}".format(args)) # cls._log.debug("=" * width) # # def log(self, note, *, level=logging.DEBUG): # """ # Add a log entry...no note # """ # if not note: # raise ValueError("Provide something to log") # note = "{} | {}".format(cls.logname, note) # cls._log.log(level, note) # # def note(self, note, *, level=logging.INFO, log=True): # """ # Add note to the object. By default, the note will also # be logged # :param note: (str) The note itself # :param level: (logging.level) # :param log: (boolean) Enable or disable logging of note # """ # if not note: # raise ValueError("Provide something to log") # note = "{} | {}".format(cls.logname, note) # cls._notes.timestamp.append(datetime.now().astimezone()) # cls._notes.notes.append(note) # if log: # cls.log(level, note) # # @property # def notes(self): # """ # Retrieve notes list as a Pandas Series # """ # if not _PANDAS: # return dict(zip(self._notes.timestamp, self._notes.notes)) # return pd.Series(self._notes.notes, index=self._notes.timestamp) # # def clear_notes(self): # """ # Clear notes object # """ # cls._notes.timestamp = [] # cls._notes.notes = [] # # # Add the functions to the decorated class # cls.clear_notes = clear_notes # cls.note = note # cls.notes = notes # cls.log = log # cls.log_title = log_title # cls.log_subtitle = log_subtitle # return cls . Output only the next line.
@note_and_log
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding utf-8 -*- """ Test Bacnet communication with another device """ VENDOR_ID = 842 @pytest.fixture(scope="session") def host_ip(): <|code_end|> using the current file's imports: from BAC0.core.functions.GetIPAddr import HostIP import BAC0 import pytest and any relevant context from other files: # Path: BAC0/core/functions/GetIPAddr.py # class HostIP: # """ # Special class to identify host IP informations # """ # # def __init__(self, port=47808): # ip = self._findIPAddr() # mask = self._findSubnetMask(ip) # self._port = port # self.interface = ipaddress.IPv4Interface("{}/{}".format(ip, mask)) # # @property # def ip_address_subnet(self): # """ # IP Address/subnet # """ # return "{}/{}".format( # self.interface.ip.compressed, self.interface.exploded.split("/")[-1] # ) # # @property # def ip_address(self): # """ # IP Address/subnet # """ # return "{}".format(self.interface.ip.compressed) # # @property # def address(self): # """ # IP Address using bacpypes Address format # """ # port = "" # if self._port: # port = ":{}".format(self._port) # return Address( # "{}/{}{}".format( # self.interface.ip.compressed, # self.interface.exploded.split("/")[-1], # port, # ) # ) # # @property # def mask(self): # """ # Subnet mask # """ # return self.interface.exploded.split("/")[-1] # # @property # def port(self): # """ # IP Port used # """ # return self._port # # def _findIPAddr(self): # """ # Retrieve the IP address connected to internet... used as # a default IP address when defining Script # # :returns: IP Adress as String # """ # s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # try: # s.connect(("google.com", 0)) # addr = s.getsockname()[0] # s.close() # except socket.error: # raise NetworkInterfaceException( # "Impossible to retrieve IP, please provide one manually" # ) # return addr # # def _findSubnetMask(self, ip): # """ # Retrieve the broadcast IP address connected to internet... used as # a default IP address when defining Script # # :param ip: (str) optionnal IP address. If not provided, default to getIPAddr() # # :returns: broadcast IP Adress as String # """ # try: # import netifaces # # interfaces = netifaces.interfaces() # for nic in interfaces: # addresses = netifaces.ifaddresses(nic) # try: # for address in addresses[netifaces.AF_INET]: # if address["addr"] == ip: # return address["netmask"] # except KeyError: # pass # # return "255.255.255.255" # except ImportError: # self._log.warning( # "Netifaces not installed on your system. BAC0 can't detect the subnet.\nPlease provide subnet for now, we'll consider 255.255.255.0 (/24).\nYou can install netifaces using 'pip install netifaces'." # ) # return "255.255.255.0" . Output only the next line.
hip = HostIP()
Given snippet: <|code_start|>#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # BAC0 documentation build configuration file, created by # sphinx-quickstart on Sat Sep 5 21:28:35 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # Magic: allowing sphinx to find the 'current source' vs the installed BAC0 library. PACKAGE_PARENT = "../.." SCRIPT_DIR = os.path.dirname( os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))) ) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) print(sys.path) <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import os import shlex from BAC0 import infos as infos and context: # Path: BAC0/infos.py which might include code, classes, or functions. Output only the next line.
from BAC0 import infos as infos
Given snippet: <|code_start|> """ if not self._started: raise ApplicationNotStarted("BACnet stack not running - use startApp()") # with self.this_application._lock: if use lock...won't be able to call read... args = args.split() addr, obj_type, obj_inst, prop_id, value = args[:5] if self.read("{} {} {} outOfService".format(addr, obj_type, obj_inst)): self.write( "{} {} {} {} {}".format(addr, obj_type, obj_inst, prop_id, value) ) else: try: self.write( "{} {} {} outOfService True".format(addr, obj_type, obj_inst) ) except NoResponseFromController as e: self._log.warning( "Failed to write to OutOfService property ({})".format(e) ) try: if self.read("{} {} {} outOfService".format(addr, obj_type, obj_inst)): self.write( "{} {} {} {} {}".format( addr, obj_type, obj_inst, prop_id, value ) ) else: <|code_end|> , continue by predicting the next line. Consider current file imports: from .IOExceptions import ( OutOfServiceNotSet, OutOfServiceSet, NoResponseFromController, ApplicationNotStarted, ) and context: # Path: BAC0/core/io/IOExceptions.py # class OutOfServiceNotSet(Exception): # """ # This exception is used when trying to simulate a point and the out of service property is false. # """ # # pass # # class OutOfServiceSet(Exception): # """ # This exception is used when trying to set the out of service property to # false to release the simulation...and it doesn't work. # """ # # pass # # class NoResponseFromController(Exception): # """ # This exception is used when trying to read or write and there is not answer. # """ # # pass # # class ApplicationNotStarted(Exception): # """ # Application not started, no communication available. # """ # # pass which might include code, classes, or functions. Output only the next line.
raise OutOfServiceNotSet()
Given the following code snippet before the placeholder: <|code_start|> raise ApplicationNotStarted("BACnet stack not running - use startApp()") # with self.this_application._lock: if use lock...won't be able to call read... args = args.split() addr, obj_type, obj_inst = args[:3] try: self.write("{} {} {} outOfService True".format(addr, obj_type, obj_inst)) except NoResponseFromController as e: self._log.warning("Failed to write to OutOfService property ({})".format(e)) def release(self, args): """ Set the Out_Of_Service property to False - to release the I/O point back to the controller's control. :param args: String with <addr> <type> <inst> """ if not self._started: raise ApplicationNotStarted("BACnet stack not running - use startApp()") args = args.split() addr, obj_type, obj_inst = args[:3] try: self.write("{} {} {} outOfService False".format(addr, obj_type, obj_inst)) except NoResponseFromController as e: self._log.warning("Failed to write to OutOfService property ({})".format(e)) try: if self.read("{} {} {} outOfService".format(addr, obj_type, obj_inst)): <|code_end|> , predict the next line using imports from the current file: from .IOExceptions import ( OutOfServiceNotSet, OutOfServiceSet, NoResponseFromController, ApplicationNotStarted, ) and context including class names, function names, and sometimes code from other files: # Path: BAC0/core/io/IOExceptions.py # class OutOfServiceNotSet(Exception): # """ # This exception is used when trying to simulate a point and the out of service property is false. # """ # # pass # # class OutOfServiceSet(Exception): # """ # This exception is used when trying to set the out of service property to # false to release the simulation...and it doesn't work. # """ # # pass # # class NoResponseFromController(Exception): # """ # This exception is used when trying to read or write and there is not answer. # """ # # pass # # class ApplicationNotStarted(Exception): # """ # Application not started, no communication available. # """ # # pass . Output only the next line.
raise OutOfServiceSet()
Predict the next line after this snippet: <|code_start|> class Simulation: """ Global informations regarding simulation """ def sim(self, args): """ Simulate I/O points by setting the Out_Of_Service property, then doing a WriteProperty to the point's Present_Value. :param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ] """ if not self._started: raise ApplicationNotStarted("BACnet stack not running - use startApp()") # with self.this_application._lock: if use lock...won't be able to call read... args = args.split() addr, obj_type, obj_inst, prop_id, value = args[:5] if self.read("{} {} {} outOfService".format(addr, obj_type, obj_inst)): self.write( "{} {} {} {} {}".format(addr, obj_type, obj_inst, prop_id, value) ) else: try: self.write( "{} {} {} outOfService True".format(addr, obj_type, obj_inst) ) <|code_end|> using the current file's imports: from .IOExceptions import ( OutOfServiceNotSet, OutOfServiceSet, NoResponseFromController, ApplicationNotStarted, ) and any relevant context from other files: # Path: BAC0/core/io/IOExceptions.py # class OutOfServiceNotSet(Exception): # """ # This exception is used when trying to simulate a point and the out of service property is false. # """ # # pass # # class OutOfServiceSet(Exception): # """ # This exception is used when trying to set the out of service property to # false to release the simulation...and it doesn't work. # """ # # pass # # class NoResponseFromController(Exception): # """ # This exception is used when trying to read or write and there is not answer. # """ # # pass # # class ApplicationNotStarted(Exception): # """ # Application not started, no communication available. # """ # # pass . Output only the next line.
except NoResponseFromController as e:
Next line prediction: <|code_start|># # Copyright (C) 2015 by Christian Tremblay, P.Eng <christian.tremblay@servisys.com> # Licensed under LGPLv3, see file LICENSE in this source tree. # """ Simulate.py - simulate the value of controller I/O values """ # --- standard Python modules --- # --- 3rd party modules --- # --- this application's modules --- # ------------------------------------------------------------------------------ class Simulation: """ Global informations regarding simulation """ def sim(self, args): """ Simulate I/O points by setting the Out_Of_Service property, then doing a WriteProperty to the point's Present_Value. :param args: String with <addr> <type> <inst> <prop> <value> [ <indx> ] [ <priority> ] """ if not self._started: <|code_end|> . Use current file imports: (from .IOExceptions import ( OutOfServiceNotSet, OutOfServiceSet, NoResponseFromController, ApplicationNotStarted, ) ) and context including class names, function names, or small code snippets from other files: # Path: BAC0/core/io/IOExceptions.py # class OutOfServiceNotSet(Exception): # """ # This exception is used when trying to simulate a point and the out of service property is false. # """ # # pass # # class OutOfServiceSet(Exception): # """ # This exception is used when trying to set the out of service property to # false to release the simulation...and it doesn't work. # """ # # pass # # class NoResponseFromController(Exception): # """ # This exception is used when trying to read or write and there is not answer. # """ # # pass # # class ApplicationNotStarted(Exception): # """ # Application not started, no communication available. # """ # # pass . Output only the next line.
raise ApplicationNotStarted("BACnet stack not running - use startApp()")
Given the code snippet: <|code_start|>""" Setup.py """ requirements = ["bacpypes", "colorama"] setup( name="BAC0", <|code_end|> , generate the next line using the imports in this file: from setuptools import setup from BAC0 import infos and context (functions, classes, or occasionally code) from other files: # Path: BAC0/infos.py . Output only the next line.
version=infos.__version__,
Next line prediction: <|code_start|> ## A list of time-stamped edges of this temporal network self.tedges = [] ## A list of nodes of this temporal network self.nodes = [] ## A dictionary storing all time-stamped links, indexed by time-stamps self.time = _co.defaultdict( lambda: list() ) ## A dictionary storing all time-stamped links, indexed by time and target node self.targets = _co.defaultdict( lambda: dict() ) ## A dictionary storing all time-stamped links, indexed by time and source node self.sources = _co.defaultdict( lambda: dict() ) ## A dictionary storing time stamps at which links (v,*;t) originate from node v self.activities = _co.defaultdict( lambda: list() ) ## A dictionary storing sets of time stamps at which links (v,*;t) originate from node v ## Note that the insertion into a set is much faster than repeatedly checking whether ## an element already exists in a list! self.activities_sets = _co.defaultdict( lambda: set() ) ## An ordered list of time-stamps self.ordered_times = [] nodes_seen = _co.defaultdict( lambda:False ) if tedges is not None: <|code_end|> . Use current file imports: (import numpy as _np import sys as _sys import collections as _co import bisect as _bs import datetime as _dt import time as _t import pathpy.Paths import os as _os from pathpy.Log import Log from pathpy.Log import Severity) and context including class names, function names, or small code snippets from other files: # Path: pathpy/Log.py # class Log: # """ A simple logging class, that allows to select what messages should # be recorded in the output, and where these message should be directed. # """ # # ## the output stream to which log entries will be written # output_stream = sys.stdout # # ## The minimum severity level of messages to be logged # min_severity = Severity.INFO # # # @staticmethod # def setMinSeverity(severity): # """ Sets the minimum sveerity level a message # needs to have in order to be recorded in the output stream. # By default, any message which has a severity of at least # Severity.INFO will be written to the output stream. All messages # with lower priority will be surpressed. # """ # Log.min_severity = severity # # # @staticmethod # def setOutputStream(stream): # """ Sets the output stream to which all messages will be # written. By default, this is sys.stdout, but it can be # changed in order to redirect the log to a logfile. # """ # output_stream = stream # # # @staticmethod # def add(msg, severity=Severity.INFO): # """ Adds a message with the given severity to the log. This message will be written # to the log output stream, which by default is sys.stdout. A newline character # will be added to the message by default. # """ # if severity >= Log.min_severity: # ts = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) # Log.output_stream.write(ts + ' [' + str(severity) + ']\t' + msg + '\n') # Log.output_stream.flush() # # Path: pathpy/Log.py # class Severity(enum.IntEnum): # """ An enumeration that can be used to indicate # the severity of log messages, and which can be # used tpo filter messages based on severities. # """ # # ## Error messages # ERROR = 4 # # ## Warning messages # WARNING = 3 # # ## Informational messages (default minimum level) # INFO = 2 # # ## Messages regarding timing and performance # TIMING = 1 # # ## Debug messages (really verbose) # DEBUG = 0 . Output only the next line.
Log.add('Building index data structures ...')
Predict the next line after this snippet: <|code_start|> @param maxlines: limit reading of file to certain number of lines, default sys.maxsize """ assert (filename != ''), 'Empty filename given' # Read header with open(filename, 'r') as f: tedges = [] header = f.readline() header = header.split(sep) # If header columns are included, arbitrary column orders are supported time_ix = -1 source_ix = -1 mid_ix = -1 weight_ix = -1 target_ix = -1 for i in range(len(header)): header[i] = header[i].strip() if header[i] == 'node1' or header[i] == 'source': source_ix = i elif header[i] == 'node2' or header[i] == 'target': target_ix = i elif header[i] == 'time' or header[i] == 'timestamp': time_ix = i assert (source_ix >= 0 and target_ix >= 0), "Detected invalid header columns: %s" % header if time_ix<0: <|code_end|> using the current file's imports: import numpy as _np import sys as _sys import collections as _co import bisect as _bs import datetime as _dt import time as _t import pathpy.Paths import os as _os from pathpy.Log import Log from pathpy.Log import Severity and any relevant context from other files: # Path: pathpy/Log.py # class Log: # """ A simple logging class, that allows to select what messages should # be recorded in the output, and where these message should be directed. # """ # # ## the output stream to which log entries will be written # output_stream = sys.stdout # # ## The minimum severity level of messages to be logged # min_severity = Severity.INFO # # # @staticmethod # def setMinSeverity(severity): # """ Sets the minimum sveerity level a message # needs to have in order to be recorded in the output stream. # By default, any message which has a severity of at least # Severity.INFO will be written to the output stream. All messages # with lower priority will be surpressed. # """ # Log.min_severity = severity # # # @staticmethod # def setOutputStream(stream): # """ Sets the output stream to which all messages will be # written. By default, this is sys.stdout, but it can be # changed in order to redirect the log to a logfile. # """ # output_stream = stream # # # @staticmethod # def add(msg, severity=Severity.INFO): # """ Adds a message with the given severity to the log. This message will be written # to the log output stream, which by default is sys.stdout. A newline character # will be added to the message by default. # """ # if severity >= Log.min_severity: # ts = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) # Log.output_stream.write(ts + ' [' + str(severity) + ']\t' + msg + '\n') # Log.output_stream.flush() # # Path: pathpy/Log.py # class Severity(enum.IntEnum): # """ An enumeration that can be used to indicate # the severity of log messages, and which can be # used tpo filter messages based on severities. # """ # # ## Error messages # ERROR = 4 # # ## Warning messages # WARNING = 3 # # ## Informational messages (default minimum level) # INFO = 2 # # ## Messages regarding timing and performance # TIMING = 1 # # ## Debug messages (really verbose) # DEBUG = 0 . Output only the next line.
Log.add('No time stamps found in data, assuming consecutive links', Severity.WARNING)
Given the following code snippet before the placeholder: <|code_start|> def getDoF(self, assumption="paths"): """ Calculates the degrees of freedom (i.e. number of parameters) of this k-order model. Depending on the modeling assumptions, this either corresponds to the number of paths of length k in the first-order network or to the number of all possible k-grams. The degrees of freedom of a model can be used to assess the model complexity when calculating, e.g., the Bayesian Information Criterion (BIC). @param assumption: if set to 'paths', for the degree of freedon calculation in the BIC, only paths in the first-order network topology will be considered. This is needed whenever we are interested in a modeling of paths in a given network topology. If set to 'ngrams' all possible n-grams will be considered, independent of whether they are valid paths in the first-order network or not. The 'ngrams' and the 'paths' assumption coincide if the first-order network is fully connected. """ assert assumption == 'paths' or assumption == 'ngrams', 'Error: Invalid assumption' if assumption == 'paths': return self.dof_paths else: return self.dof_ngrams def getDistanceMatrix(self): """ Calculates shortest path distances between all pairs of higher-order nodes using the Floyd-Warshall algorithm. """ <|code_end|> , predict the next line using imports from the current file: import collections as _co import bisect as _bs import itertools as _iter import numpy as _np import scipy.sparse as _sparse import scipy.sparse.linalg as _sla import scipy.linalg as _la import scipy as _sp from pathpy.Log import Log from pathpy.Log import Severity and context including class names, function names, and sometimes code from other files: # Path: pathpy/Log.py # class Log: # """ A simple logging class, that allows to select what messages should # be recorded in the output, and where these message should be directed. # """ # # ## the output stream to which log entries will be written # output_stream = sys.stdout # # ## The minimum severity level of messages to be logged # min_severity = Severity.INFO # # # @staticmethod # def setMinSeverity(severity): # """ Sets the minimum sveerity level a message # needs to have in order to be recorded in the output stream. # By default, any message which has a severity of at least # Severity.INFO will be written to the output stream. All messages # with lower priority will be surpressed. # """ # Log.min_severity = severity # # # @staticmethod # def setOutputStream(stream): # """ Sets the output stream to which all messages will be # written. By default, this is sys.stdout, but it can be # changed in order to redirect the log to a logfile. # """ # output_stream = stream # # # @staticmethod # def add(msg, severity=Severity.INFO): # """ Adds a message with the given severity to the log. This message will be written # to the log output stream, which by default is sys.stdout. A newline character # will be added to the message by default. # """ # if severity >= Log.min_severity: # ts = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) # Log.output_stream.write(ts + ' [' + str(severity) + ']\t' + msg + '\n') # Log.output_stream.flush() # # Path: pathpy/Log.py # class Severity(enum.IntEnum): # """ An enumeration that can be used to indicate # the severity of log messages, and which can be # used tpo filter messages based on severities. # """ # # ## Error messages # ERROR = 4 # # ## Warning messages # WARNING = 3 # # ## Informational messages (default minimum level) # INFO = 2 # # ## Messages regarding timing and performance # TIMING = 1 # # ## Debug messages (really verbose) # DEBUG = 0 . Output only the next line.
Log.add('Calculating distance matrix in higher-order network (k = ' + str(self.order) + ') ...', Severity.INFO)
Here is a snippet: <|code_start|> def getDoF(self, assumption="paths"): """ Calculates the degrees of freedom (i.e. number of parameters) of this k-order model. Depending on the modeling assumptions, this either corresponds to the number of paths of length k in the first-order network or to the number of all possible k-grams. The degrees of freedom of a model can be used to assess the model complexity when calculating, e.g., the Bayesian Information Criterion (BIC). @param assumption: if set to 'paths', for the degree of freedon calculation in the BIC, only paths in the first-order network topology will be considered. This is needed whenever we are interested in a modeling of paths in a given network topology. If set to 'ngrams' all possible n-grams will be considered, independent of whether they are valid paths in the first-order network or not. The 'ngrams' and the 'paths' assumption coincide if the first-order network is fully connected. """ assert assumption == 'paths' or assumption == 'ngrams', 'Error: Invalid assumption' if assumption == 'paths': return self.dof_paths else: return self.dof_ngrams def getDistanceMatrix(self): """ Calculates shortest path distances between all pairs of higher-order nodes using the Floyd-Warshall algorithm. """ <|code_end|> . Write the next line using the current file imports: import collections as _co import bisect as _bs import itertools as _iter import numpy as _np import scipy.sparse as _sparse import scipy.sparse.linalg as _sla import scipy.linalg as _la import scipy as _sp from pathpy.Log import Log from pathpy.Log import Severity and context from other files: # Path: pathpy/Log.py # class Log: # """ A simple logging class, that allows to select what messages should # be recorded in the output, and where these message should be directed. # """ # # ## the output stream to which log entries will be written # output_stream = sys.stdout # # ## The minimum severity level of messages to be logged # min_severity = Severity.INFO # # # @staticmethod # def setMinSeverity(severity): # """ Sets the minimum sveerity level a message # needs to have in order to be recorded in the output stream. # By default, any message which has a severity of at least # Severity.INFO will be written to the output stream. All messages # with lower priority will be surpressed. # """ # Log.min_severity = severity # # # @staticmethod # def setOutputStream(stream): # """ Sets the output stream to which all messages will be # written. By default, this is sys.stdout, but it can be # changed in order to redirect the log to a logfile. # """ # output_stream = stream # # # @staticmethod # def add(msg, severity=Severity.INFO): # """ Adds a message with the given severity to the log. This message will be written # to the log output stream, which by default is sys.stdout. A newline character # will be added to the message by default. # """ # if severity >= Log.min_severity: # ts = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) # Log.output_stream.write(ts + ' [' + str(severity) + ']\t' + msg + '\n') # Log.output_stream.flush() # # Path: pathpy/Log.py # class Severity(enum.IntEnum): # """ An enumeration that can be used to indicate # the severity of log messages, and which can be # used tpo filter messages based on severities. # """ # # ## Error messages # ERROR = 4 # # ## Warning messages # WARNING = 3 # # ## Informational messages (default minimum level) # INFO = 2 # # ## Messages regarding timing and performance # TIMING = 1 # # ## Debug messages (really verbose) # DEBUG = 0 , which may include functions, classes, or code. Output only the next line.
Log.add('Calculating distance matrix in higher-order network (k = ' + str(self.order) + ') ...', Severity.INFO)
Given the code snippet: <|code_start|> def __init__(self, sequence): """ Generates a Markov model for a sequence, given as a single list of strings """ ## The sequence to be modeled self.sequence = sequence ## The transition probabilities of higher-order Markov chains self.P = {} ## the set of states of higher-order Markov chains self.states = {} self.states[1] = set(sequence) def fitMarkovModel(self, k=1): """ Generates a k-th order Markov model for the underlying sequence """ # TODO: Add support for k=0 assert len(self.sequence)>0, "Error: Empty sequence" # MLE fit of transition probabilities self.P[k] = _co.defaultdict( lambda: _co.defaultdict( lambda: 0.0 ) ) <|code_end|> , generate the next line using the imports in this file: import numpy as _np import collections as _co import bisect as _bs import itertools as _iter import scipy.sparse as _sparse import scipy.misc as _misc import scipy.sparse.linalg as _sla import scipy.linalg as _la from scipy.stats import chi2 from pathpy.Log import Log from pathpy.Log import Severity and context (functions, classes, or occasionally code) from other files: # Path: pathpy/Log.py # class Log: # """ A simple logging class, that allows to select what messages should # be recorded in the output, and where these message should be directed. # """ # # ## the output stream to which log entries will be written # output_stream = sys.stdout # # ## The minimum severity level of messages to be logged # min_severity = Severity.INFO # # # @staticmethod # def setMinSeverity(severity): # """ Sets the minimum sveerity level a message # needs to have in order to be recorded in the output stream. # By default, any message which has a severity of at least # Severity.INFO will be written to the output stream. All messages # with lower priority will be surpressed. # """ # Log.min_severity = severity # # # @staticmethod # def setOutputStream(stream): # """ Sets the output stream to which all messages will be # written. By default, this is sys.stdout, but it can be # changed in order to redirect the log to a logfile. # """ # output_stream = stream # # # @staticmethod # def add(msg, severity=Severity.INFO): # """ Adds a message with the given severity to the log. This message will be written # to the log output stream, which by default is sys.stdout. A newline character # will be added to the message by default. # """ # if severity >= Log.min_severity: # ts = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) # Log.output_stream.write(ts + ' [' + str(severity) + ']\t' + msg + '\n') # Log.output_stream.flush() # # Path: pathpy/Log.py # class Severity(enum.IntEnum): # """ An enumeration that can be used to indicate # the severity of log messages, and which can be # used tpo filter messages based on severities. # """ # # ## Error messages # ERROR = 4 # # ## Warning messages # WARNING = 3 # # ## Informational messages (default minimum level) # INFO = 2 # # ## Messages regarding timing and performance # TIMING = 1 # # ## Debug messages (really verbose) # DEBUG = 0 . Output only the next line.
Log.add('Fitting Markov model with order k = ' + str(k))
Given snippet: <|code_start|> client = paho_mqtt.Client() client.username_pw_set(token, token) client.on_connect = on_mqtt_connect client.on_disconnect = on_mqtt_disconnect client.on_message = on_mqtt_message client.on_subscribe = on_mqtt_subscribe client.connect(host, int(port), 60) client.loop_start() return client def _attach_device(self, device): if self.mqtt: logger.debug('Client %s attaching device %s' % (self, device.id)) for action in ['feed', 'command']: logger.debug('Subscribing to %s\'s %ss' % (device.id, action)) self.mqtt.subscribe('device/%s/asset/+/%s' % (device.id, action)) self._devices[device.id] = device def get_assets(self, device_id): """Retrieves assets for the device identified by device_id. :param str device_id: AllThingsTalk Device Identifier :return: Asset list returned by AllThingsTalk API. :rtype: list of Asset """ r = requests.get('%s/device/%s/assets' % (self.http, device_id), headers=self._get_headers()) if r.status_code == 403: raise AccessForbiddenException('Could not use token "%s" to access device "%s" on "%s".' % (self.token, device_id, self.http)) <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import pkg_resources import paho.mqtt.client as paho_mqtt import requests from .assets import Asset from .asset_state import AssetState from .exceptions import AssetStateRetrievalException, AccessForbiddenException and context: # Path: allthingstalk/assets.py # class Asset: # # SENSOR = 'sensor' # ACTUATOR = 'actuator' # CONFIG = 'config' # VIRTUAL = 'virtual' # # _PROFILE_CLASS = None # # def __init__(self, *, kind='sensor', name=None, title=None, # description='', handler=None, profile=None, **kwargs): # """References the asset identified by name. The asset is created on the platform # if it doesn't already exist. If the asset is initialized from a device class, # it's default name is set to the member name referencing it. # # :param str kind: Asset kind: sensor, actuator, virtual or config # :param str name: Asset's name. If the asset is initialized from a device class, the name defaults to the name of the member referencing the asset, e.g. for ``my_asset = IntegerAsset()``, the integer asset's name will be set to ``'my_asset'`` # :param str title: Asset's title. By default it gets set to capitalized name. # :param str description: Asset's description # :param Profile profile: Asset's profile. For default profiles, it's recommend to use Asset variants with preset profile, like IntegerAsset or StringAsset. # """ # # self.id = None # self.thing_id = None # self.kind = kind if kind else 'sensor' # self.name = name # self._internal_id = name # self.title = title or name # self.description = description # self.handler = handler # if self.__class__._PROFILE_CLASS: # self.profile = self.__class__._PROFILE_CLASS(**kwargs) # elif profile is not None: # self.profile = profile # else: # raise exceptions.InvalidAssetProfileException() # if 'type' in self.profile: # self.type = self.profile['type'] # # @staticmethod # def from_dict(d): # asset = Asset( # kind=d['is'], # name=d['name'], # title=d['title'], # description=d['description'], # profile=d['profile']) # asset.id = d['id'] # asset.thing_id = d['deviceId'] # return asset # # Path: allthingstalk/asset_state.py # class AssetState: # """AssetState is used instead of primitive state values (like ``2``, ``"a"`` # or ``True``) when publishing data with a custom timestamp, i.e. not the # current timestamp at the time of publishing.""" # # def __init__(self, value, at=None): # """Initializes the asset state. # # :param value: Any JSON-serializable value applicable to the given :class:`~allthingstalk.Asset`. # :param datetime.datetime at: Optional timestamp # """ # # self.value = value # if at is None: # self.at = datetime.datetime.utcnow() # elif isinstance(at, str): # self.at = parse_date(at) # elif isinstance(at, datetime.datetime): # self.at = at # else: # raise ValueError('Invalid timestamp in at: %s' % at) # # if self.at.tzinfo is None: # self.at = self.at.replace(tzinfo=dateutil.tz.tzutc()) # # def __repr__(self): # return 'AssetState(value=%s, at=%s)' % (self.value, self.at) # # def __str__(self): # return str(self.value) # # Path: allthingstalk/exceptions.py # class AssetStateRetrievalException(Exception): # """Asset state could not be retrieved.""" # pass # # class AccessForbiddenException(Exception): # """Access Forbidden.""" # pass which might include code, classes, or functions. Output only the next line.
return [Asset.from_dict(asset_dict) for asset_dict in r.json()]
Given the following code snippet before the placeholder: <|code_start|> :rtype: Asset """ attalk_asset = { 'Name': asset.name, 'Title': asset.title, 'Description': asset.description, 'Is': asset.kind, 'Profile': asset.profile } asset_dict = requests.post('%s/device/%s/assets' % (self.http, device_id), headers=self._get_headers(), json=attalk_asset).json() return Asset.from_dict(asset_dict) def get_asset_state(self, device_id, asset_name): """Low-level device asset state retrieval. Most of the time, you should be using device asset getters. :param str device_id: AllThingsTalk Device Identifier :param str asset_name: Asset name :return: The Asset state :rtype: AssetState """ r = requests.get('%s/device/%s/asset/%s/state' % (self.http, device_id, asset_name), headers=self._get_headers()) if r.status_code != 200: raise AssetStateRetrievalException() response_json = r.json() <|code_end|> , predict the next line using imports from the current file: import logging import pkg_resources import paho.mqtt.client as paho_mqtt import requests from .assets import Asset from .asset_state import AssetState from .exceptions import AssetStateRetrievalException, AccessForbiddenException and context including class names, function names, and sometimes code from other files: # Path: allthingstalk/assets.py # class Asset: # # SENSOR = 'sensor' # ACTUATOR = 'actuator' # CONFIG = 'config' # VIRTUAL = 'virtual' # # _PROFILE_CLASS = None # # def __init__(self, *, kind='sensor', name=None, title=None, # description='', handler=None, profile=None, **kwargs): # """References the asset identified by name. The asset is created on the platform # if it doesn't already exist. If the asset is initialized from a device class, # it's default name is set to the member name referencing it. # # :param str kind: Asset kind: sensor, actuator, virtual or config # :param str name: Asset's name. If the asset is initialized from a device class, the name defaults to the name of the member referencing the asset, e.g. for ``my_asset = IntegerAsset()``, the integer asset's name will be set to ``'my_asset'`` # :param str title: Asset's title. By default it gets set to capitalized name. # :param str description: Asset's description # :param Profile profile: Asset's profile. For default profiles, it's recommend to use Asset variants with preset profile, like IntegerAsset or StringAsset. # """ # # self.id = None # self.thing_id = None # self.kind = kind if kind else 'sensor' # self.name = name # self._internal_id = name # self.title = title or name # self.description = description # self.handler = handler # if self.__class__._PROFILE_CLASS: # self.profile = self.__class__._PROFILE_CLASS(**kwargs) # elif profile is not None: # self.profile = profile # else: # raise exceptions.InvalidAssetProfileException() # if 'type' in self.profile: # self.type = self.profile['type'] # # @staticmethod # def from_dict(d): # asset = Asset( # kind=d['is'], # name=d['name'], # title=d['title'], # description=d['description'], # profile=d['profile']) # asset.id = d['id'] # asset.thing_id = d['deviceId'] # return asset # # Path: allthingstalk/asset_state.py # class AssetState: # """AssetState is used instead of primitive state values (like ``2``, ``"a"`` # or ``True``) when publishing data with a custom timestamp, i.e. not the # current timestamp at the time of publishing.""" # # def __init__(self, value, at=None): # """Initializes the asset state. # # :param value: Any JSON-serializable value applicable to the given :class:`~allthingstalk.Asset`. # :param datetime.datetime at: Optional timestamp # """ # # self.value = value # if at is None: # self.at = datetime.datetime.utcnow() # elif isinstance(at, str): # self.at = parse_date(at) # elif isinstance(at, datetime.datetime): # self.at = at # else: # raise ValueError('Invalid timestamp in at: %s' % at) # # if self.at.tzinfo is None: # self.at = self.at.replace(tzinfo=dateutil.tz.tzutc()) # # def __repr__(self): # return 'AssetState(value=%s, at=%s)' % (self.value, self.at) # # def __str__(self): # return str(self.value) # # Path: allthingstalk/exceptions.py # class AssetStateRetrievalException(Exception): # """Asset state could not be retrieved.""" # pass # # class AccessForbiddenException(Exception): # """Access Forbidden.""" # pass . Output only the next line.
return AssetState(
Predict the next line for this snippet: <|code_start|> :param Asset asset: The asset :return: The asset :rtype: Asset """ attalk_asset = { 'Name': asset.name, 'Title': asset.title, 'Description': asset.description, 'Is': asset.kind, 'Profile': asset.profile } asset_dict = requests.post('%s/device/%s/assets' % (self.http, device_id), headers=self._get_headers(), json=attalk_asset).json() return Asset.from_dict(asset_dict) def get_asset_state(self, device_id, asset_name): """Low-level device asset state retrieval. Most of the time, you should be using device asset getters. :param str device_id: AllThingsTalk Device Identifier :param str asset_name: Asset name :return: The Asset state :rtype: AssetState """ r = requests.get('%s/device/%s/asset/%s/state' % (self.http, device_id, asset_name), headers=self._get_headers()) if r.status_code != 200: <|code_end|> with the help of current file imports: import logging import pkg_resources import paho.mqtt.client as paho_mqtt import requests from .assets import Asset from .asset_state import AssetState from .exceptions import AssetStateRetrievalException, AccessForbiddenException and context from other files: # Path: allthingstalk/assets.py # class Asset: # # SENSOR = 'sensor' # ACTUATOR = 'actuator' # CONFIG = 'config' # VIRTUAL = 'virtual' # # _PROFILE_CLASS = None # # def __init__(self, *, kind='sensor', name=None, title=None, # description='', handler=None, profile=None, **kwargs): # """References the asset identified by name. The asset is created on the platform # if it doesn't already exist. If the asset is initialized from a device class, # it's default name is set to the member name referencing it. # # :param str kind: Asset kind: sensor, actuator, virtual or config # :param str name: Asset's name. If the asset is initialized from a device class, the name defaults to the name of the member referencing the asset, e.g. for ``my_asset = IntegerAsset()``, the integer asset's name will be set to ``'my_asset'`` # :param str title: Asset's title. By default it gets set to capitalized name. # :param str description: Asset's description # :param Profile profile: Asset's profile. For default profiles, it's recommend to use Asset variants with preset profile, like IntegerAsset or StringAsset. # """ # # self.id = None # self.thing_id = None # self.kind = kind if kind else 'sensor' # self.name = name # self._internal_id = name # self.title = title or name # self.description = description # self.handler = handler # if self.__class__._PROFILE_CLASS: # self.profile = self.__class__._PROFILE_CLASS(**kwargs) # elif profile is not None: # self.profile = profile # else: # raise exceptions.InvalidAssetProfileException() # if 'type' in self.profile: # self.type = self.profile['type'] # # @staticmethod # def from_dict(d): # asset = Asset( # kind=d['is'], # name=d['name'], # title=d['title'], # description=d['description'], # profile=d['profile']) # asset.id = d['id'] # asset.thing_id = d['deviceId'] # return asset # # Path: allthingstalk/asset_state.py # class AssetState: # """AssetState is used instead of primitive state values (like ``2``, ``"a"`` # or ``True``) when publishing data with a custom timestamp, i.e. not the # current timestamp at the time of publishing.""" # # def __init__(self, value, at=None): # """Initializes the asset state. # # :param value: Any JSON-serializable value applicable to the given :class:`~allthingstalk.Asset`. # :param datetime.datetime at: Optional timestamp # """ # # self.value = value # if at is None: # self.at = datetime.datetime.utcnow() # elif isinstance(at, str): # self.at = parse_date(at) # elif isinstance(at, datetime.datetime): # self.at = at # else: # raise ValueError('Invalid timestamp in at: %s' % at) # # if self.at.tzinfo is None: # self.at = self.at.replace(tzinfo=dateutil.tz.tzutc()) # # def __repr__(self): # return 'AssetState(value=%s, at=%s)' % (self.value, self.at) # # def __str__(self): # return str(self.value) # # Path: allthingstalk/exceptions.py # class AssetStateRetrievalException(Exception): # """Asset state could not be retrieved.""" # pass # # class AccessForbiddenException(Exception): # """Access Forbidden.""" # pass , which may contain function names, class names, or code. Output only the next line.
raise AssetStateRetrievalException()
Given the following code snippet before the placeholder: <|code_start|> self._devices[device_id]._on_message(stream, asset_name, message.payload) client = paho_mqtt.Client() client.username_pw_set(token, token) client.on_connect = on_mqtt_connect client.on_disconnect = on_mqtt_disconnect client.on_message = on_mqtt_message client.on_subscribe = on_mqtt_subscribe client.connect(host, int(port), 60) client.loop_start() return client def _attach_device(self, device): if self.mqtt: logger.debug('Client %s attaching device %s' % (self, device.id)) for action in ['feed', 'command']: logger.debug('Subscribing to %s\'s %ss' % (device.id, action)) self.mqtt.subscribe('device/%s/asset/+/%s' % (device.id, action)) self._devices[device.id] = device def get_assets(self, device_id): """Retrieves assets for the device identified by device_id. :param str device_id: AllThingsTalk Device Identifier :return: Asset list returned by AllThingsTalk API. :rtype: list of Asset """ r = requests.get('%s/device/%s/assets' % (self.http, device_id), headers=self._get_headers()) if r.status_code == 403: <|code_end|> , predict the next line using imports from the current file: import logging import pkg_resources import paho.mqtt.client as paho_mqtt import requests from .assets import Asset from .asset_state import AssetState from .exceptions import AssetStateRetrievalException, AccessForbiddenException and context including class names, function names, and sometimes code from other files: # Path: allthingstalk/assets.py # class Asset: # # SENSOR = 'sensor' # ACTUATOR = 'actuator' # CONFIG = 'config' # VIRTUAL = 'virtual' # # _PROFILE_CLASS = None # # def __init__(self, *, kind='sensor', name=None, title=None, # description='', handler=None, profile=None, **kwargs): # """References the asset identified by name. The asset is created on the platform # if it doesn't already exist. If the asset is initialized from a device class, # it's default name is set to the member name referencing it. # # :param str kind: Asset kind: sensor, actuator, virtual or config # :param str name: Asset's name. If the asset is initialized from a device class, the name defaults to the name of the member referencing the asset, e.g. for ``my_asset = IntegerAsset()``, the integer asset's name will be set to ``'my_asset'`` # :param str title: Asset's title. By default it gets set to capitalized name. # :param str description: Asset's description # :param Profile profile: Asset's profile. For default profiles, it's recommend to use Asset variants with preset profile, like IntegerAsset or StringAsset. # """ # # self.id = None # self.thing_id = None # self.kind = kind if kind else 'sensor' # self.name = name # self._internal_id = name # self.title = title or name # self.description = description # self.handler = handler # if self.__class__._PROFILE_CLASS: # self.profile = self.__class__._PROFILE_CLASS(**kwargs) # elif profile is not None: # self.profile = profile # else: # raise exceptions.InvalidAssetProfileException() # if 'type' in self.profile: # self.type = self.profile['type'] # # @staticmethod # def from_dict(d): # asset = Asset( # kind=d['is'], # name=d['name'], # title=d['title'], # description=d['description'], # profile=d['profile']) # asset.id = d['id'] # asset.thing_id = d['deviceId'] # return asset # # Path: allthingstalk/asset_state.py # class AssetState: # """AssetState is used instead of primitive state values (like ``2``, ``"a"`` # or ``True``) when publishing data with a custom timestamp, i.e. not the # current timestamp at the time of publishing.""" # # def __init__(self, value, at=None): # """Initializes the asset state. # # :param value: Any JSON-serializable value applicable to the given :class:`~allthingstalk.Asset`. # :param datetime.datetime at: Optional timestamp # """ # # self.value = value # if at is None: # self.at = datetime.datetime.utcnow() # elif isinstance(at, str): # self.at = parse_date(at) # elif isinstance(at, datetime.datetime): # self.at = at # else: # raise ValueError('Invalid timestamp in at: %s' % at) # # if self.at.tzinfo is None: # self.at = self.at.replace(tzinfo=dateutil.tz.tzutc()) # # def __repr__(self): # return 'AssetState(value=%s, at=%s)' % (self.value, self.at) # # def __str__(self): # return str(self.value) # # Path: allthingstalk/exceptions.py # class AssetStateRetrievalException(Exception): # """Asset state could not be retrieved.""" # pass # # class AccessForbiddenException(Exception): # """Access Forbidden.""" # pass . Output only the next line.
raise AccessForbiddenException('Could not use token "%s" to access device "%s" on "%s".'
Using the snippet: <|code_start|> proc.connect(self.on_done, event="done") self.add(proc) self.on_change(proc) return proc def on_change(self, proc): pass def on_done(self, proc): self.remove(proc) def remove(self, proc): to_be_removed = [] for pref in self.procs: if pref() == proc or pref() is None: to_be_removed.append(pref) for pref in to_be_removed: self.procs.remove(pref) class FCVisibleProcessContainer(QtCore.QObject, FCProcessContainer): something_changed = QtCore.pyqtSignal() def __init__(self, view): <|code_end|> , determine the next line of code. You have imports: from FlatCAMGUI import FlatCAMActivityView from PyQt4 import QtCore import weakref and context (class names, function names, or code) available: # Path: FlatCAMGUI.py # class FlatCAMActivityView(QtGui.QWidget): # # def __init__(self, parent=None): # super(FlatCAMActivityView, self).__init__(parent=parent) # # self.setMinimumWidth(200) # # self.icon = QtGui.QLabel(self) # self.icon.setGeometry(0, 0, 12, 12) # self.movie = QtGui.QMovie("share/active.gif") # self.icon.setMovie(self.movie) # #self.movie.start() # # layout = QtGui.QHBoxLayout() # layout.setContentsMargins(5, 0, 5, 0) # layout.setAlignment(QtCore.Qt.AlignLeft) # self.setLayout(layout) # # layout.addWidget(self.icon) # self.text = QtGui.QLabel(self) # self.text.setText("Idle.") # # layout.addWidget(self.text) # # def set_idle(self): # self.movie.stop() # self.text.setText("Idle.") # # def set_busy(self, msg): # self.movie.start() # self.text.setText(msg) . Output only the next line.
assert isinstance(view, FlatCAMActivityView), \
Continue the code snippet: <|code_start|> #from mpl_toolkits.axes_grid.anchored_artists import AnchoredDrawingArea class BufferSelectionTool(FlatCAMTool): """ Simple input for buffer distance. """ toolName = "Buffer Selection" def __init__(self, app, fcdraw): FlatCAMTool.__init__(self, app) self.fcdraw = fcdraw ## Title title_label = QtGui.QLabel("<font size=4><b>%s</b></font>" % self.toolName) self.layout.addWidget(title_label) ## Form Layout form_layout = QtGui.QFormLayout() self.layout.addLayout(form_layout) ## Buffer distance <|code_end|> . Use current file imports: from PyQt4 import QtGui, QtCore, Qt from camlib import * from FlatCAMTool import FlatCAMTool from ObjectUI import LengthEntry from shapely.geometry import Polygon, LineString, Point, LinearRing from shapely.geometry import MultiPoint, MultiPolygon from shapely.geometry import box as shply_box from shapely.ops import cascaded_union, unary_union from shapely.wkt import loads as sloads from shapely.wkt import dumps as sdumps from shapely.geometry.base import BaseGeometry from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, sign, dot from numpy.linalg import solve from rtree import index as rtindex from vispy.scene.visuals import Markers import FlatCAMApp import shapely.affinity as affinity and context (classes, functions, or code) from other files: # Path: FlatCAMTool.py # class FlatCAMTool(QtGui.QWidget): # # toolName = "FlatCAM Generic Tool" # # def __init__(self, app, parent=None): # """ # # :param app: The application this tool will run in. # :type app: App # :param parent: Qt Parent # :return: FlatCAMTool # """ # QtGui.QWidget.__init__(self, parent) # # # self.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum) # # self.layout = QtGui.QVBoxLayout() # self.setLayout(self.layout) # # self.app = app # # self.menuAction = None # # def install(self): # self.menuAction = self.app.ui.menutool.addAction(self.toolName) # self.menuAction.triggered.connect(self.run) # # def run(self): # # Remove anything else in the GUI # self.app.ui.tool_scroll_area.takeWidget() # # # Put ourself in the GUI # self.app.ui.tool_scroll_area.setWidget(self) # # # Switch notebook to tool page # self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab) # # self.show() # # Path: ObjectUI.py # class ObjectUI(QtGui.QWidget): # class CNCObjectUI(ObjectUI): # class GeometryObjectUI(ObjectUI): # class ExcellonObjectUI(ObjectUI): # class GerberObjectUI(ObjectUI): # def __init__(self, icon_file='share/flatcam_icon32.png', title='FlatCAM Object', parent=None): # def __init__(self, parent=None): # def __init__(self, parent=None): # def __init__(self, parent=None): # def __init__(self, parent=None): . Output only the next line.
self.buffer_distance_entry = LengthEntry()
Based on the snippet: <|code_start|> class WorkerStack(QtCore.QObject): worker_task = QtCore.pyqtSignal(dict) # 'worker_name', 'func', 'params' thread_exception = QtCore.pyqtSignal(object) def __init__(self): super(WorkerStack, self).__init__() self.workers = [] self.threads = [] self.load = {} # {'worker_name': tasks_count} # Create workers crew for i in range(0, 2): <|code_end|> , predict the immediate next line with the help of imports: from PyQt4 import QtCore from FlatCAMWorker import Worker import multiprocessing and context (classes, functions, sometimes code) from other files: # Path: FlatCAMWorker.py # class Worker(QtCore.QObject): # """ # Implements a queue of tasks to be carried out in order # in a single independent thread. # """ # # # avoid multiple tests for debug availability # pydevd_failed = False # task_completed = QtCore.pyqtSignal(str) # # def __init__(self, app, name=None): # super(Worker, self).__init__() # self.app = app # self.name = name # # def allow_debug(self): # """ # allow debuging/breakpoints in this threads # should work from PyCharm and PyDev # :return: # """ # # if not self.pydevd_failed: # try: # import pydevd # pydevd.settrace(suspend=False, trace_only_current_thread=True) # except ImportError: # self.pydevd_failed=True # # def run(self): # # # self.app.log.debug("Worker Started!") # # self.allow_debug() # # # Tasks are queued in the event listener. # self.app.worker_task.connect(self.do_worker_task) # # def do_worker_task(self, task): # # # self.app.log.debug("Running task: %s" % str(task)) # # self.allow_debug() # # if ('worker_name' in task and task['worker_name'] == self.name) or \ # ('worker_name' not in task and self.name is None): # # try: # task['fcn'](*task['params']) # except Exception as e: # self.app.thread_exception.emit(e) # raise e # finally: # self.task_completed.emit(self.name) # # # self.app.log.debug("Task ignored.") . Output only the next line.
worker = Worker(self, 'Slogger-' + str(i))
Given snippet: <|code_start|> Input shape data :param triangulation: str Triangulation engine """ mesh_vertices = [] # Vertices for mesh mesh_tris = [] # Faces for mesh mesh_colors = [] # Face colors line_pts = [] # Vertices for line line_colors = [] # Line color geo, color, face_color, tolerance = data['geometry'], data['color'], data['face_color'], data['tolerance'] if geo is not None and not geo.is_empty: simple = geo.simplify(tolerance) if tolerance else geo # Simplified shape pts = [] # Shape line points tri_pts = [] # Mesh vertices tri_tris = [] # Mesh faces if type(geo) == LineString: # Prepare lines pts = _linestring_to_segments(list(simple.coords)) elif type(geo) == LinearRing: # Prepare lines pts = _linearring_to_segments(list(simple.coords)) elif type(geo) == Polygon: # Prepare polygon faces if face_color is not None: if triangulation == 'glu': <|code_end|> , continue by predicting the next line. Consider current file imports: from vispy.visuals import CompoundVisual, LineVisual, MeshVisual, TextVisual, MarkersVisual from vispy.scene.visuals import VisualNode, generate_docstring, visuals from vispy.gloo import set_state from vispy.color import Color from shapely.geometry import Polygon, LineString, LinearRing from VisPyTesselators import GLUTess import threading import numpy as np and context: # Path: VisPyTesselators.py # class GLUTess: # def __init__(self): # """ # OpenGL GLU triangulation class # """ # self.tris = [] # self.pts = [] # self.vertex_index = 0 # # def _on_begin_primitive(self, type): # pass # # def _on_new_vertex(self, vertex): # self.tris.append(vertex) # # # Force GLU to return separate triangles (GLU_TRIANGLES) # def _on_edge_flag(self, flag): # pass # # def _on_combine(self, coords, data, weight): # return (coords[0], coords[1], coords[2]) # # def _on_error(self, errno): # print "GLUTess error:", errno # # def _on_end_primitive(self): # pass # # def triangulate(self, polygon): # """ # Triangulates polygon # :param polygon: shapely.geometry.polygon # Polygon to tessellate # :return: list, list # Array of triangle vertex indices [t0i0, t0i1, t0i2, t1i0, t1i1, ... ] # Array of polygon points [(x0, y0), (x1, y1), ... ] # """ # # Create tessellation object # tess = GLU.gluNewTess() # # # Setup callbacks # GLU.gluTessCallback(tess, GLU.GLU_TESS_BEGIN, self._on_begin_primitive) # GLU.gluTessCallback(tess, GLU.GLU_TESS_VERTEX, self._on_new_vertex) # GLU.gluTessCallback(tess, GLU.GLU_TESS_EDGE_FLAG, self._on_edge_flag) # GLU.gluTessCallback(tess, GLU.GLU_TESS_COMBINE, self._on_combine) # GLU.gluTessCallback(tess, GLU.GLU_TESS_ERROR, self._on_error) # GLU.gluTessCallback(tess, GLU.GLU_TESS_END, self._on_end_primitive) # # # Reset data # del self.tris[:] # del self.pts[:] # self.vertex_index = 0 # # # Define polygon # GLU.gluTessBeginPolygon(tess, None) # # def define_contour(contour): # vertices = list(contour.coords) # Get vertices coordinates # if vertices[0] == vertices[-1]: # Open ring # vertices = vertices[:-1] # # self.pts += vertices # # GLU.gluTessBeginContour(tess) # Start contour # # # Set vertices # for vertex in vertices: # point = (vertex[0], vertex[1], 0) # GLU.gluTessVertex(tess, point, self.vertex_index) # self.vertex_index += 1 # # GLU.gluTessEndContour(tess) # End contour # # # Polygon exterior # define_contour(polygon.exterior) # # # Interiors # for interior in polygon.interiors: # define_contour(interior) # # # Start tessellation # GLU.gluTessEndPolygon(tess) # # # Free resources # GLU.gluDeleteTess(tess) # # return self.tris, self.pts which might include code, classes, or functions. Output only the next line.
gt = GLUTess()
Given the following code snippet before the placeholder: <|code_start|>############################################################ log = logging.getLogger('base') class PlotCanvas(QtCore.QObject): """ Class handling the plotting area in the application. """ def __init__(self, container, app): """ The constructor configures the Matplotlib figure that will contain all plots, creates the base axes and connects events to the plotting area. :param container: The parent container in which to draw plots. :rtype: PlotCanvas """ super(PlotCanvas, self).__init__() self.app = app # Parent container self.container = container # Attach to parent <|code_end|> , predict the next line using imports from the current file: from PyQt4 import QtCore from VisPyCanvas import VisPyCanvas from VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor from vispy.scene.visuals import InfiniteLine from vispy.geometry import Rect import logging import numpy as np and context including class names, function names, and sometimes code from other files: # Path: VisPyCanvas.py # class VisPyCanvas(scene.SceneCanvas): # # def __init__(self, config=None): # # scene.SceneCanvas.__init__(self, keys=None, config=config) # self.unfreeze() # # back_color = str(QPalette().color(QPalette.Window).name()) # # self.central_widget.bgcolor = back_color # self.central_widget.border_color = back_color # # grid = self.central_widget.add_grid(margin=10) # grid.spacing = 0 # # top_padding = grid.add_widget(row=0, col=0, col_span=2) # top_padding.height_max = 24 # # yaxis = scene.AxisWidget(orientation='left', axis_color='black', text_color='black', font_size=12) # yaxis.width_max = 60 # grid.add_widget(yaxis, row=1, col=0) # # xaxis = scene.AxisWidget(orientation='bottom', axis_color='black', text_color='black', font_size=12) # xaxis.height_max = 40 # grid.add_widget(xaxis, row=2, col=1) # # right_padding = grid.add_widget(row=0, col=2, row_span=2) # right_padding.width_max = 24 # # view = grid.add_view(row=1, col=1, border_color='black', bgcolor='white') # view.camera = Camera(aspect=1) # # # Following function was removed from 'prepare_draw()' of 'Grid' class by patch, # # it is necessary to call manually # grid._update_child_widget_dim() # # grid1 = scene.GridLines(parent=view.scene, color='gray') # grid1.set_gl_state(depth_test=False) # # xaxis.link_view(view) # yaxis.link_view(view) # # self.grid = grid1 # self.view = view # self.freeze() # # self.measure_fps() # # def translate_coords(self, pos): # tr = self.grid.get_transform('canvas', 'visual') # return tr.map(pos) # # Path: VisPyVisuals.py # def _update_shape_buffers(data, triangulation='glu'): # def _linearring_to_segments(arr): # def _linestring_to_segments(arr): # def __init__(self, collection): # def add(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, line_width=1, triangulation='gpc', layers=3, pool=None, **kwargs): # def add(self, shape=None, color=None, face_color=None, visible=True, update=False, layer=1, tolerance=0.01): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self, indexes=None): # def lock_updates(self): # def unlock_updates(self): # def __init__(self, collection): # def set(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, **kwargs): # def add(self, text, pos, visible=True, update=True): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self): # def create_fast_node(subclass): # def __init__(self, *args, **kwargs): # def get_enabled(self): # def set_enabled(self, enabled): # class ShapeGroup(object): # class ShapeCollectionVisual(CompoundVisual): # class TextGroup(object): # class TextCollectionVisual(TextVisual): . Output only the next line.
self.vispy_canvas = VisPyCanvas()
Next line prediction: <|code_start|> # self.shape_collections = [] self.shape_collection = self.new_shape_collection() self.app.pool_recreated.connect(self.on_pool_recreated) self.text_collection = self.new_text_collection() # TODO: Should be setting to show/hide CNC job annotations (global or per object) self.text_collection.enabled = False def vis_connect(self, event_name, callback): return getattr(self.vispy_canvas.events, event_name).connect(callback) def vis_disconnect(self, event_name, callback): getattr(self.vispy_canvas.events, event_name).disconnect(callback) def zoom(self, factor, center=None): """ Zooms the plot by factor around a given center point. Takes care of re-drawing. :param factor: Number by which to scale the plot. :type factor: float :param center: Coordinates [x, y] of the point around which to scale the plot. :type center: list :return: None """ self.vispy_canvas.view.camera.zoom(factor, center) def new_shape_group(self): <|code_end|> . Use current file imports: (from PyQt4 import QtCore from VisPyCanvas import VisPyCanvas from VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor from vispy.scene.visuals import InfiniteLine from vispy.geometry import Rect import logging import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: VisPyCanvas.py # class VisPyCanvas(scene.SceneCanvas): # # def __init__(self, config=None): # # scene.SceneCanvas.__init__(self, keys=None, config=config) # self.unfreeze() # # back_color = str(QPalette().color(QPalette.Window).name()) # # self.central_widget.bgcolor = back_color # self.central_widget.border_color = back_color # # grid = self.central_widget.add_grid(margin=10) # grid.spacing = 0 # # top_padding = grid.add_widget(row=0, col=0, col_span=2) # top_padding.height_max = 24 # # yaxis = scene.AxisWidget(orientation='left', axis_color='black', text_color='black', font_size=12) # yaxis.width_max = 60 # grid.add_widget(yaxis, row=1, col=0) # # xaxis = scene.AxisWidget(orientation='bottom', axis_color='black', text_color='black', font_size=12) # xaxis.height_max = 40 # grid.add_widget(xaxis, row=2, col=1) # # right_padding = grid.add_widget(row=0, col=2, row_span=2) # right_padding.width_max = 24 # # view = grid.add_view(row=1, col=1, border_color='black', bgcolor='white') # view.camera = Camera(aspect=1) # # # Following function was removed from 'prepare_draw()' of 'Grid' class by patch, # # it is necessary to call manually # grid._update_child_widget_dim() # # grid1 = scene.GridLines(parent=view.scene, color='gray') # grid1.set_gl_state(depth_test=False) # # xaxis.link_view(view) # yaxis.link_view(view) # # self.grid = grid1 # self.view = view # self.freeze() # # self.measure_fps() # # def translate_coords(self, pos): # tr = self.grid.get_transform('canvas', 'visual') # return tr.map(pos) # # Path: VisPyVisuals.py # def _update_shape_buffers(data, triangulation='glu'): # def _linearring_to_segments(arr): # def _linestring_to_segments(arr): # def __init__(self, collection): # def add(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, line_width=1, triangulation='gpc', layers=3, pool=None, **kwargs): # def add(self, shape=None, color=None, face_color=None, visible=True, update=False, layer=1, tolerance=0.01): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self, indexes=None): # def lock_updates(self): # def unlock_updates(self): # def __init__(self, collection): # def set(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, **kwargs): # def add(self, text, pos, visible=True, update=True): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self): # def create_fast_node(subclass): # def __init__(self, *args, **kwargs): # def get_enabled(self): # def set_enabled(self, enabled): # class ShapeGroup(object): # class ShapeCollectionVisual(CompoundVisual): # class TextGroup(object): # class TextCollectionVisual(TextVisual): . Output only the next line.
return ShapeGroup(self.shape_collection)
Given snippet: <|code_start|> # TODO: Should be setting to show/hide CNC job annotations (global or per object) self.text_collection.enabled = False def vis_connect(self, event_name, callback): return getattr(self.vispy_canvas.events, event_name).connect(callback) def vis_disconnect(self, event_name, callback): getattr(self.vispy_canvas.events, event_name).disconnect(callback) def zoom(self, factor, center=None): """ Zooms the plot by factor around a given center point. Takes care of re-drawing. :param factor: Number by which to scale the plot. :type factor: float :param center: Coordinates [x, y] of the point around which to scale the plot. :type center: list :return: None """ self.vispy_canvas.view.camera.zoom(factor, center) def new_shape_group(self): return ShapeGroup(self.shape_collection) def new_shape_collection(self, **kwargs): # sc = ShapeCollection(parent=self.vispy_canvas.view.scene, pool=self.app.pool, **kwargs) # self.shape_collections.append(sc) # return sc <|code_end|> , continue by predicting the next line. Consider current file imports: from PyQt4 import QtCore from VisPyCanvas import VisPyCanvas from VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor from vispy.scene.visuals import InfiniteLine from vispy.geometry import Rect import logging import numpy as np and context: # Path: VisPyCanvas.py # class VisPyCanvas(scene.SceneCanvas): # # def __init__(self, config=None): # # scene.SceneCanvas.__init__(self, keys=None, config=config) # self.unfreeze() # # back_color = str(QPalette().color(QPalette.Window).name()) # # self.central_widget.bgcolor = back_color # self.central_widget.border_color = back_color # # grid = self.central_widget.add_grid(margin=10) # grid.spacing = 0 # # top_padding = grid.add_widget(row=0, col=0, col_span=2) # top_padding.height_max = 24 # # yaxis = scene.AxisWidget(orientation='left', axis_color='black', text_color='black', font_size=12) # yaxis.width_max = 60 # grid.add_widget(yaxis, row=1, col=0) # # xaxis = scene.AxisWidget(orientation='bottom', axis_color='black', text_color='black', font_size=12) # xaxis.height_max = 40 # grid.add_widget(xaxis, row=2, col=1) # # right_padding = grid.add_widget(row=0, col=2, row_span=2) # right_padding.width_max = 24 # # view = grid.add_view(row=1, col=1, border_color='black', bgcolor='white') # view.camera = Camera(aspect=1) # # # Following function was removed from 'prepare_draw()' of 'Grid' class by patch, # # it is necessary to call manually # grid._update_child_widget_dim() # # grid1 = scene.GridLines(parent=view.scene, color='gray') # grid1.set_gl_state(depth_test=False) # # xaxis.link_view(view) # yaxis.link_view(view) # # self.grid = grid1 # self.view = view # self.freeze() # # self.measure_fps() # # def translate_coords(self, pos): # tr = self.grid.get_transform('canvas', 'visual') # return tr.map(pos) # # Path: VisPyVisuals.py # def _update_shape_buffers(data, triangulation='glu'): # def _linearring_to_segments(arr): # def _linestring_to_segments(arr): # def __init__(self, collection): # def add(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, line_width=1, triangulation='gpc', layers=3, pool=None, **kwargs): # def add(self, shape=None, color=None, face_color=None, visible=True, update=False, layer=1, tolerance=0.01): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self, indexes=None): # def lock_updates(self): # def unlock_updates(self): # def __init__(self, collection): # def set(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, **kwargs): # def add(self, text, pos, visible=True, update=True): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self): # def create_fast_node(subclass): # def __init__(self, *args, **kwargs): # def get_enabled(self): # def set_enabled(self, enabled): # class ShapeGroup(object): # class ShapeCollectionVisual(CompoundVisual): # class TextGroup(object): # class TextCollectionVisual(TextVisual): which might include code, classes, or functions. Output only the next line.
return ShapeCollection(parent=self.vispy_canvas.view.scene, pool=self.app.pool, **kwargs)
Here is a snippet: <|code_start|> """ Zooms the plot by factor around a given center point. Takes care of re-drawing. :param factor: Number by which to scale the plot. :type factor: float :param center: Coordinates [x, y] of the point around which to scale the plot. :type center: list :return: None """ self.vispy_canvas.view.camera.zoom(factor, center) def new_shape_group(self): return ShapeGroup(self.shape_collection) def new_shape_collection(self, **kwargs): # sc = ShapeCollection(parent=self.vispy_canvas.view.scene, pool=self.app.pool, **kwargs) # self.shape_collections.append(sc) # return sc return ShapeCollection(parent=self.vispy_canvas.view.scene, pool=self.app.pool, **kwargs) def new_cursor(self): c = Cursor(pos=np.empty((0, 2)), parent=self.vispy_canvas.view.scene) c.antialias = 0 return c def new_text_group(self): return TextGroup(self.text_collection) def new_text_collection(self, **kwargs): <|code_end|> . Write the next line using the current file imports: from PyQt4 import QtCore from VisPyCanvas import VisPyCanvas from VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor from vispy.scene.visuals import InfiniteLine from vispy.geometry import Rect import logging import numpy as np and context from other files: # Path: VisPyCanvas.py # class VisPyCanvas(scene.SceneCanvas): # # def __init__(self, config=None): # # scene.SceneCanvas.__init__(self, keys=None, config=config) # self.unfreeze() # # back_color = str(QPalette().color(QPalette.Window).name()) # # self.central_widget.bgcolor = back_color # self.central_widget.border_color = back_color # # grid = self.central_widget.add_grid(margin=10) # grid.spacing = 0 # # top_padding = grid.add_widget(row=0, col=0, col_span=2) # top_padding.height_max = 24 # # yaxis = scene.AxisWidget(orientation='left', axis_color='black', text_color='black', font_size=12) # yaxis.width_max = 60 # grid.add_widget(yaxis, row=1, col=0) # # xaxis = scene.AxisWidget(orientation='bottom', axis_color='black', text_color='black', font_size=12) # xaxis.height_max = 40 # grid.add_widget(xaxis, row=2, col=1) # # right_padding = grid.add_widget(row=0, col=2, row_span=2) # right_padding.width_max = 24 # # view = grid.add_view(row=1, col=1, border_color='black', bgcolor='white') # view.camera = Camera(aspect=1) # # # Following function was removed from 'prepare_draw()' of 'Grid' class by patch, # # it is necessary to call manually # grid._update_child_widget_dim() # # grid1 = scene.GridLines(parent=view.scene, color='gray') # grid1.set_gl_state(depth_test=False) # # xaxis.link_view(view) # yaxis.link_view(view) # # self.grid = grid1 # self.view = view # self.freeze() # # self.measure_fps() # # def translate_coords(self, pos): # tr = self.grid.get_transform('canvas', 'visual') # return tr.map(pos) # # Path: VisPyVisuals.py # def _update_shape_buffers(data, triangulation='glu'): # def _linearring_to_segments(arr): # def _linestring_to_segments(arr): # def __init__(self, collection): # def add(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, line_width=1, triangulation='gpc', layers=3, pool=None, **kwargs): # def add(self, shape=None, color=None, face_color=None, visible=True, update=False, layer=1, tolerance=0.01): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self, indexes=None): # def lock_updates(self): # def unlock_updates(self): # def __init__(self, collection): # def set(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, **kwargs): # def add(self, text, pos, visible=True, update=True): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self): # def create_fast_node(subclass): # def __init__(self, *args, **kwargs): # def get_enabled(self): # def set_enabled(self, enabled): # class ShapeGroup(object): # class ShapeCollectionVisual(CompoundVisual): # class TextGroup(object): # class TextCollectionVisual(TextVisual): , which may include functions, classes, or code. Output only the next line.
return TextCollection(parent=self.vispy_canvas.view.scene, **kwargs)
Next line prediction: <|code_start|> getattr(self.vispy_canvas.events, event_name).disconnect(callback) def zoom(self, factor, center=None): """ Zooms the plot by factor around a given center point. Takes care of re-drawing. :param factor: Number by which to scale the plot. :type factor: float :param center: Coordinates [x, y] of the point around which to scale the plot. :type center: list :return: None """ self.vispy_canvas.view.camera.zoom(factor, center) def new_shape_group(self): return ShapeGroup(self.shape_collection) def new_shape_collection(self, **kwargs): # sc = ShapeCollection(parent=self.vispy_canvas.view.scene, pool=self.app.pool, **kwargs) # self.shape_collections.append(sc) # return sc return ShapeCollection(parent=self.vispy_canvas.view.scene, pool=self.app.pool, **kwargs) def new_cursor(self): c = Cursor(pos=np.empty((0, 2)), parent=self.vispy_canvas.view.scene) c.antialias = 0 return c def new_text_group(self): <|code_end|> . Use current file imports: (from PyQt4 import QtCore from VisPyCanvas import VisPyCanvas from VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor from vispy.scene.visuals import InfiniteLine from vispy.geometry import Rect import logging import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: VisPyCanvas.py # class VisPyCanvas(scene.SceneCanvas): # # def __init__(self, config=None): # # scene.SceneCanvas.__init__(self, keys=None, config=config) # self.unfreeze() # # back_color = str(QPalette().color(QPalette.Window).name()) # # self.central_widget.bgcolor = back_color # self.central_widget.border_color = back_color # # grid = self.central_widget.add_grid(margin=10) # grid.spacing = 0 # # top_padding = grid.add_widget(row=0, col=0, col_span=2) # top_padding.height_max = 24 # # yaxis = scene.AxisWidget(orientation='left', axis_color='black', text_color='black', font_size=12) # yaxis.width_max = 60 # grid.add_widget(yaxis, row=1, col=0) # # xaxis = scene.AxisWidget(orientation='bottom', axis_color='black', text_color='black', font_size=12) # xaxis.height_max = 40 # grid.add_widget(xaxis, row=2, col=1) # # right_padding = grid.add_widget(row=0, col=2, row_span=2) # right_padding.width_max = 24 # # view = grid.add_view(row=1, col=1, border_color='black', bgcolor='white') # view.camera = Camera(aspect=1) # # # Following function was removed from 'prepare_draw()' of 'Grid' class by patch, # # it is necessary to call manually # grid._update_child_widget_dim() # # grid1 = scene.GridLines(parent=view.scene, color='gray') # grid1.set_gl_state(depth_test=False) # # xaxis.link_view(view) # yaxis.link_view(view) # # self.grid = grid1 # self.view = view # self.freeze() # # self.measure_fps() # # def translate_coords(self, pos): # tr = self.grid.get_transform('canvas', 'visual') # return tr.map(pos) # # Path: VisPyVisuals.py # def _update_shape_buffers(data, triangulation='glu'): # def _linearring_to_segments(arr): # def _linestring_to_segments(arr): # def __init__(self, collection): # def add(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, line_width=1, triangulation='gpc', layers=3, pool=None, **kwargs): # def add(self, shape=None, color=None, face_color=None, visible=True, update=False, layer=1, tolerance=0.01): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self, indexes=None): # def lock_updates(self): # def unlock_updates(self): # def __init__(self, collection): # def set(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, **kwargs): # def add(self, text, pos, visible=True, update=True): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self): # def create_fast_node(subclass): # def __init__(self, *args, **kwargs): # def get_enabled(self): # def set_enabled(self, enabled): # class ShapeGroup(object): # class ShapeCollectionVisual(CompoundVisual): # class TextGroup(object): # class TextCollectionVisual(TextVisual): . Output only the next line.
return TextGroup(self.text_collection)
Continue the code snippet: <|code_start|> def vis_connect(self, event_name, callback): return getattr(self.vispy_canvas.events, event_name).connect(callback) def vis_disconnect(self, event_name, callback): getattr(self.vispy_canvas.events, event_name).disconnect(callback) def zoom(self, factor, center=None): """ Zooms the plot by factor around a given center point. Takes care of re-drawing. :param factor: Number by which to scale the plot. :type factor: float :param center: Coordinates [x, y] of the point around which to scale the plot. :type center: list :return: None """ self.vispy_canvas.view.camera.zoom(factor, center) def new_shape_group(self): return ShapeGroup(self.shape_collection) def new_shape_collection(self, **kwargs): # sc = ShapeCollection(parent=self.vispy_canvas.view.scene, pool=self.app.pool, **kwargs) # self.shape_collections.append(sc) # return sc return ShapeCollection(parent=self.vispy_canvas.view.scene, pool=self.app.pool, **kwargs) def new_cursor(self): <|code_end|> . Use current file imports: from PyQt4 import QtCore from VisPyCanvas import VisPyCanvas from VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor from vispy.scene.visuals import InfiniteLine from vispy.geometry import Rect import logging import numpy as np and context (classes, functions, or code) from other files: # Path: VisPyCanvas.py # class VisPyCanvas(scene.SceneCanvas): # # def __init__(self, config=None): # # scene.SceneCanvas.__init__(self, keys=None, config=config) # self.unfreeze() # # back_color = str(QPalette().color(QPalette.Window).name()) # # self.central_widget.bgcolor = back_color # self.central_widget.border_color = back_color # # grid = self.central_widget.add_grid(margin=10) # grid.spacing = 0 # # top_padding = grid.add_widget(row=0, col=0, col_span=2) # top_padding.height_max = 24 # # yaxis = scene.AxisWidget(orientation='left', axis_color='black', text_color='black', font_size=12) # yaxis.width_max = 60 # grid.add_widget(yaxis, row=1, col=0) # # xaxis = scene.AxisWidget(orientation='bottom', axis_color='black', text_color='black', font_size=12) # xaxis.height_max = 40 # grid.add_widget(xaxis, row=2, col=1) # # right_padding = grid.add_widget(row=0, col=2, row_span=2) # right_padding.width_max = 24 # # view = grid.add_view(row=1, col=1, border_color='black', bgcolor='white') # view.camera = Camera(aspect=1) # # # Following function was removed from 'prepare_draw()' of 'Grid' class by patch, # # it is necessary to call manually # grid._update_child_widget_dim() # # grid1 = scene.GridLines(parent=view.scene, color='gray') # grid1.set_gl_state(depth_test=False) # # xaxis.link_view(view) # yaxis.link_view(view) # # self.grid = grid1 # self.view = view # self.freeze() # # self.measure_fps() # # def translate_coords(self, pos): # tr = self.grid.get_transform('canvas', 'visual') # return tr.map(pos) # # Path: VisPyVisuals.py # def _update_shape_buffers(data, triangulation='glu'): # def _linearring_to_segments(arr): # def _linestring_to_segments(arr): # def __init__(self, collection): # def add(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, line_width=1, triangulation='gpc', layers=3, pool=None, **kwargs): # def add(self, shape=None, color=None, face_color=None, visible=True, update=False, layer=1, tolerance=0.01): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self, indexes=None): # def lock_updates(self): # def unlock_updates(self): # def __init__(self, collection): # def set(self, **kwargs): # def clear(self, update=False): # def redraw(self): # def visible(self): # def visible(self, value): # def __init__(self, **kwargs): # def add(self, text, pos, visible=True, update=True): # def remove(self, key, update=False): # def clear(self, update=False): # def __update(self): # def redraw(self): # def create_fast_node(subclass): # def __init__(self, *args, **kwargs): # def get_enabled(self): # def set_enabled(self, enabled): # class ShapeGroup(object): # class ShapeCollectionVisual(CompoundVisual): # class TextGroup(object): # class TextCollectionVisual(TextVisual): . Output only the next line.
c = Cursor(pos=np.empty((0, 2)), parent=self.vispy_canvas.view.scene)
Next line prediction: <|code_start|>## py-arduino is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License version 2 for more details. ## ## You should have received a copy of the GNU General Public License ## along with py-arduino; see the file LICENSE.txt. ##-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- banner = """ ---------------------------------------------------------------------- py-arduino ---------------------------------------------------------------------- Launching IPython shell... Enter 'quit()' to exit. Available variables: - arduino: the PyArduino instance. Example: >>> arduino.ping() 'PING_OK' """ <|code_end|> . Use current file imports: (from IPython.frontend.terminal.embed import InteractiveShellEmbed from IPython.core.prompts import PromptManager from py_arduino_web.pyroproxy.utils import BasePyroMain) and context including class names, function names, or small code snippets from other files: # Path: py_arduino_web/pyroproxy/utils.py # class BasePyroMain(object): # """ # Base class to create scrpits from `pyroproxy.cli.*` # """ # # logger = logging.getLogger('BasePyroMain') # # def __init__(self): # self.parser = optparse.OptionParser() # self.add_options() # # def add_options(self): # self.parser.add_option("--debug", # action="store_true", dest="debug", default=False, # help="Configure logging to show debug messages.") # self.parser.add_option("--info", # action="store_true", dest="info", default=False, # help="Configure logging to show info messages.") # self.parser.add_option("--dont-check-pyro-server", # action="store_true", dest="dont_check_pyro_server", default=False, # help="Don't check if PyRO server is reachable (by default, " # "a check is done and we exit if the server isn't reachable.)") # self.parser.add_option("--wait-until-connected", # action="store_true", dest="wait_until_pyro_server_is_up", default=False, # help="Wait until the PyRO server is up") # # def run(self, options, args, arduino): # """ # To be overriden in subclass. # Do not call this method directly! You must call `start()`. # """ # raise(NotImplementedError()) # # def start(self): # (options, args) = self.parser.parse_args() # # # setup logging # if options.debug: # logging.basicConfig(level=logging.DEBUG) # elif options.info: # logging.basicConfig(level=logging.INFO) # else: # logging.basicConfig(level=logging.ERROR) # # if not options.dont_check_pyro_server: # if not server_is_up(): # print "ERROR: PyRO server isn't reachable" # sys.exit(1) # # if options.wait_until_pyro_server_is_up: # wait_for_server() # # arduino = get_arduino_pyro() # try: # return self.run(options, args, arduino) # except KeyboardInterrupt: # print "" # return None # except Exception: # raise . Output only the next line.
class Main(BasePyroMain):
Predict the next line after this snippet: <|code_start|> def save(self, *args, **kwargs): if self.pin_id is not None and len(self.pin_id.strip()) == 0: self.pin_id = None super(Pin, self).save(*args, **kwargs) # Call the "real" save() method. def __unicode__(self): if self.digital: ret = u"Digital pin #{0}".format(self.pin) else: ret = u"Analog pin #{0}".format(self.pin) if self.label: ret = u"{0} ('{1}')".format(ret, self.label) return ret class Meta: unique_together = (('pin', 'digital',),) class DjStorage(BaseStorage): def __init__(self): # Force access to the database, to raise exception if no DB exists Pin.objects.count() def get_pin(self, pin, is_digital): try: return Pin.objects.get(pin=pin, digital=is_digital) except Pin.DoesNotExist: return Pin.objects.create(pin=pin, digital=is_digital, <|code_end|> using the current file's imports: import logging from django.db import models from py_arduino_web.storage import Storage, default_label, BaseStorage and any relevant context from other files: # Path: py_arduino_web/storage.py # class Storage(BaseStorage): # # def get_pin(self, pin, is_digital): # """ # Returns a Pin instance. # """ # return Pin(pin, is_digital,) # # def get_pin_by_id(self, pin_id): # """ # Returns the Pin instance identified by 'pin_id', # or None if no Pin exists with that identifier. # """ # return None # # def default_label(pin, is_digital): # """Returns a default label for a pin""" # if is_digital: # return 'Digital pin #{0}'.format(pin) # else: # return 'Analog pin #{0}'.format(pin) # # class BaseStorage(): # # def enhanceArduinoTypeStruct(self, arduino_type_struct): # """ # Returns an enhanced copy of `arduino_type_struct` with data from storage. # # The `arduino_type_struct` must be previously # enhanced by `PyArduino.enhanceArduinoTypeStruct()`. # # To each item of `digital_pins_struct`, adds: # + pk (int) # + label (str) # + pin_id (str) # + enabled_in_web (bool) # To each item of `analog_pins_struct`, adds: # + pk (int) # + label (str) # + pin_id (str) # + enabled_in_web (bool) # """ # # arduino_type_struct['digital_pins_items'] # # arduino_type_struct['analog_pins_items'] # assert 'digital_pins_items' in arduino_type_struct # assert 'analog_pins_items' in arduino_type_struct # assert 'digital_pins_struct' in arduino_type_struct # assert 'analog_pins_struct' in arduino_type_struct # # # create 'structs' for each digital pin # for dp, dp_struct in zip( # arduino_type_struct['digital_pins_items'], # arduino_type_struct['digital_pins_struct']): # # # Assert we are 'synchronized' # assert dp == dp_struct['pin'] # # d_pin_obj = self.get_pin(dp, True) # dp_struct.update({ # 'pk': d_pin_obj.pk, # #'pin': dp, # #'digital': True, # #'pwm': (dp in arduino_type_struct['pwm_pin_list']), # 'label': d_pin_obj.label, # 'pin_id': d_pin_obj.pin_id, # 'enabled_in_web': d_pin_obj.enabled_in_web, # #'status.mode': d_pin_status.mode, # #'status.read_value': d_pin_status.read_value, # #'status.written_value': d_pin_status.written_value, # }) # # del dp # to avoid bugs (happened!) # del dp_struct # to avoid bugs (happened!) # del d_pin_obj # to avoid bugs (happened!) # # # create 'structs' for each analog pin # for ap, ap_struct in zip( # arduino_type_struct['analog_pins_items'], # arduino_type_struct['analog_pins_struct']): # # # Assert we are 'synchronized' # assert ap == ap_struct['pin'] # # a_pin_obj = self.get_pin(ap, False) # ap_struct.update({ # 'pk': a_pin_obj.pk, # #'pin': ap, # #'digital': True, # #'pwm': False, # 'label': a_pin_obj.label, # 'pin_id': a_pin_obj.pin_id, # 'enabled_in_web': a_pin_obj.enabled_in_web, # #'status.mode': a_pin_status.mode, # #'status.read_value': a_pin_status.read_value, # #'status.written_value': a_pin_status.written_value, # }) # # return arduino_type_struct . Output only the next line.
label=default_label(pin, is_digital), enabled_in_web=True)
Here is a snippet: <|code_start|>logger = logging.getLogger(__name__) class Pin(models.Model): pin = models.PositiveIntegerField() digital = models.BooleanField() label = models.CharField(max_length=64, help_text="Descriptive text for a pin. Ej: 'Status Led'") pin_id = models.CharField(max_length=64, unique=True, null=True, blank=True, help_text="Unique identifier for internal use of a pin. Ej: 'status-led'") enabled_in_web = models.BooleanField(default=True) def save(self, *args, **kwargs): if self.pin_id is not None and len(self.pin_id.strip()) == 0: self.pin_id = None super(Pin, self).save(*args, **kwargs) # Call the "real" save() method. def __unicode__(self): if self.digital: ret = u"Digital pin #{0}".format(self.pin) else: ret = u"Analog pin #{0}".format(self.pin) if self.label: ret = u"{0} ('{1}')".format(ret, self.label) return ret class Meta: unique_together = (('pin', 'digital',),) <|code_end|> . Write the next line using the current file imports: import logging from django.db import models from py_arduino_web.storage import Storage, default_label, BaseStorage and context from other files: # Path: py_arduino_web/storage.py # class Storage(BaseStorage): # # def get_pin(self, pin, is_digital): # """ # Returns a Pin instance. # """ # return Pin(pin, is_digital,) # # def get_pin_by_id(self, pin_id): # """ # Returns the Pin instance identified by 'pin_id', # or None if no Pin exists with that identifier. # """ # return None # # def default_label(pin, is_digital): # """Returns a default label for a pin""" # if is_digital: # return 'Digital pin #{0}'.format(pin) # else: # return 'Analog pin #{0}'.format(pin) # # class BaseStorage(): # # def enhanceArduinoTypeStruct(self, arduino_type_struct): # """ # Returns an enhanced copy of `arduino_type_struct` with data from storage. # # The `arduino_type_struct` must be previously # enhanced by `PyArduino.enhanceArduinoTypeStruct()`. # # To each item of `digital_pins_struct`, adds: # + pk (int) # + label (str) # + pin_id (str) # + enabled_in_web (bool) # To each item of `analog_pins_struct`, adds: # + pk (int) # + label (str) # + pin_id (str) # + enabled_in_web (bool) # """ # # arduino_type_struct['digital_pins_items'] # # arduino_type_struct['analog_pins_items'] # assert 'digital_pins_items' in arduino_type_struct # assert 'analog_pins_items' in arduino_type_struct # assert 'digital_pins_struct' in arduino_type_struct # assert 'analog_pins_struct' in arduino_type_struct # # # create 'structs' for each digital pin # for dp, dp_struct in zip( # arduino_type_struct['digital_pins_items'], # arduino_type_struct['digital_pins_struct']): # # # Assert we are 'synchronized' # assert dp == dp_struct['pin'] # # d_pin_obj = self.get_pin(dp, True) # dp_struct.update({ # 'pk': d_pin_obj.pk, # #'pin': dp, # #'digital': True, # #'pwm': (dp in arduino_type_struct['pwm_pin_list']), # 'label': d_pin_obj.label, # 'pin_id': d_pin_obj.pin_id, # 'enabled_in_web': d_pin_obj.enabled_in_web, # #'status.mode': d_pin_status.mode, # #'status.read_value': d_pin_status.read_value, # #'status.written_value': d_pin_status.written_value, # }) # # del dp # to avoid bugs (happened!) # del dp_struct # to avoid bugs (happened!) # del d_pin_obj # to avoid bugs (happened!) # # # create 'structs' for each analog pin # for ap, ap_struct in zip( # arduino_type_struct['analog_pins_items'], # arduino_type_struct['analog_pins_struct']): # # # Assert we are 'synchronized' # assert ap == ap_struct['pin'] # # a_pin_obj = self.get_pin(ap, False) # ap_struct.update({ # 'pk': a_pin_obj.pk, # #'pin': ap, # #'digital': True, # #'pwm': False, # 'label': a_pin_obj.label, # 'pin_id': a_pin_obj.pin_id, # 'enabled_in_web': a_pin_obj.enabled_in_web, # #'status.mode': a_pin_status.mode, # #'status.read_value': a_pin_status.read_value, # #'status.written_value': a_pin_status.written_value, # }) # # return arduino_type_struct , which may include functions, classes, or code. Output only the next line.
class DjStorage(BaseStorage):
Given snippet: <|code_start|>## py-arduino is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License version 2 for more details. ## ## You should have received a copy of the GNU General Public License ## along with py-arduino; see the file LICENSE.txt. ##-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # Setup PYTHONPATH SRC_DIR = os.path.split(os.path.realpath(__file__))[0] # SRC_DIR=EXAMPLE_DIR SRC_DIR = os.path.split(SRC_DIR)[0] # SRC_DIR=SRC_DIR/../ SRC_DIR = os.path.join(SRC_DIR, 'src') # SRC_DIR sys.path.append(os.path.abspath(SRC_DIR)) def args_validator(parser, options, args): # pylint: disable=W0613 if len(args) != 2: parser.error("must specified two argument: serial device and digital port") def add_options_callback(parser): parser.add_option("--loop", action="store_true", dest="loop", default=False, help="Keep reading and printing the values.") def main(): <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys from py_arduino.main_utils import default_main and context: # Path: py_arduino/main_utils.py # class BaseMain(object): # def __init__(self): # def add_options(self): # def run(self, options, args, arduino): # def get_device(self, options, args): # def validate(self, options, args): # def start(self): which might include code, classes, or functions. Output only the next line.
options, args, arduino = default_main(
Given snippet: <|code_start|> def validate(self): self.runner.stage() self.__execute(self.validate_sql) self.__promote() self.runner.rollback() def __execute(self, sql): self.table.stage_update() self.sql.execute(( sql, self.schema.update_table, self.source_url, self.aws_access_key_id, self.aws_secret_access_key, self.schema_url, self.max_error_count)) def __promote(self): if self.table.exists(): self.table.drop() self.table.promote_update() class ManifestCopyFromS3JsonStep(PipelineStep): def __init__(self, metadata, source, schema, aws_access_key_id, aws_secret_access_key, bucket, table): self.metadata = metadata self.source = source self.schema = schema self.aws_access_key_id = aws_access_key_id self.aws_secret_access_key = aws_secret_access_key self.bucket = bucket self.table = table self.runner = S3JsonStepRunner(metadata, schema, bucket, table) <|code_end|> , continue by predicting the next line. Consider current file imports: from psycopg2.extensions import AsIs from arbalest.core import PipelineStep from arbalest.redshift.manifest import Manifest from arbalest.redshift.runner import S3JsonStepRunner from arbalest.s3 import normalize_path and context: # Path: arbalest/core.py # class PipelineStep(object): # def run(self): # pass # # def validate(self): # pass # # Path: arbalest/redshift/manifest.py # class Manifest(object): # def __init__(self, metadata, source, schema, bucket): # self.metadata = metadata # self.source = source # self.schema = schema # self.bucket = bucket # self.file_name = '{0}_manifest.json'.format(schema.table) # self.journal_file_name = '{0}_journal.json'.format(schema.table) # # @property # def all_keys(self): # return [k.name for k in self.bucket.list(self.source) if # not k.name.endswith('/')] # # @property # def manifest_key(self): # return normalize_path('{0}/{1}'.format(self.metadata, self.file_name)) # # @property # def journal_key(self): # return normalize_path( # '{0}/{1}'.format(self.metadata, self.journal_file_name)) # # @property # def manifest_url(self): # return 's3://{0}{1}'.format(self.bucket.name, self.manifest_key) # # def journal(self): # journal = self.bucket.get(self.journal_key) # if journal.exists(): # return json.loads(journal.get_contents_as_string()) # else: # return [] # # def get(self): # updated_journal = self.all_keys # journal = self.journal() # keys = list(set(updated_journal) - set(journal)) # # return { # 'manifest': { # 'entries': [ # {'url': 's3://{0}/{1}'.format(self.bucket.name, key), # 'mandatory': True} for key in keys # ] # }, # 'updated_journal': updated_journal # } # # def save(self): # manifest = self.get() # self.bucket.save(self.manifest_key, json.dumps(manifest['manifest'])) # return manifest['updated_journal'] # # def commit(self, saved_keys): # self.bucket.save(self.journal_key, json.dumps(saved_keys)) # # def exists(self): # return self.bucket.get(self.manifest_key).exists() # # def journal_exists(self): # return self.bucket.get(self.journal_key).exists() # # Path: arbalest/redshift/runner.py # class S3JsonStepRunner(object): # def __init__(self, metadata, schema, bucket, table): # self.metadata = metadata # self.bucket = bucket # self.table = table # self.schema = schema # # @property # def schema_key(self): # return normalize_path( # '{0}/{1}'.format(self.metadata, self.schema.file_name)) # # @property # def schema_url(self): # return 's3://{0}{1}'.format(self.bucket.name, self.schema_key) # # def stage(self): # self.bucket.save(self.schema_key, json.dumps(self.schema.paths())) # self.table.database.open() # # def commit(self): # self.table.database.commit() # self.bucket.delete(self.schema_key) # # def rollback(self): # self.table.database.rollback() # self.bucket.delete(self.schema_key) # # Path: arbalest/s3.py # def normalize_path(path): # return posixpath.normpath(path) which might include code, classes, or functions. Output only the next line.
self.manifest = Manifest(metadata, source, schema, bucket)
Here is a snippet: <|code_start|> class BulkCopyFromS3JsonStep(PipelineStep): def __init__(self, metadata, source, schema, aws_access_key_id, aws_secret_access_key, bucket, table): self.metadata = metadata self.source = source self.schema = schema self.aws_access_key_id = aws_access_key_id self.aws_secret_access_key = aws_secret_access_key self.bucket = bucket self.table = table <|code_end|> . Write the next line using the current file imports: from psycopg2.extensions import AsIs from arbalest.core import PipelineStep from arbalest.redshift.manifest import Manifest from arbalest.redshift.runner import S3JsonStepRunner from arbalest.s3 import normalize_path and context from other files: # Path: arbalest/core.py # class PipelineStep(object): # def run(self): # pass # # def validate(self): # pass # # Path: arbalest/redshift/manifest.py # class Manifest(object): # def __init__(self, metadata, source, schema, bucket): # self.metadata = metadata # self.source = source # self.schema = schema # self.bucket = bucket # self.file_name = '{0}_manifest.json'.format(schema.table) # self.journal_file_name = '{0}_journal.json'.format(schema.table) # # @property # def all_keys(self): # return [k.name for k in self.bucket.list(self.source) if # not k.name.endswith('/')] # # @property # def manifest_key(self): # return normalize_path('{0}/{1}'.format(self.metadata, self.file_name)) # # @property # def journal_key(self): # return normalize_path( # '{0}/{1}'.format(self.metadata, self.journal_file_name)) # # @property # def manifest_url(self): # return 's3://{0}{1}'.format(self.bucket.name, self.manifest_key) # # def journal(self): # journal = self.bucket.get(self.journal_key) # if journal.exists(): # return json.loads(journal.get_contents_as_string()) # else: # return [] # # def get(self): # updated_journal = self.all_keys # journal = self.journal() # keys = list(set(updated_journal) - set(journal)) # # return { # 'manifest': { # 'entries': [ # {'url': 's3://{0}/{1}'.format(self.bucket.name, key), # 'mandatory': True} for key in keys # ] # }, # 'updated_journal': updated_journal # } # # def save(self): # manifest = self.get() # self.bucket.save(self.manifest_key, json.dumps(manifest['manifest'])) # return manifest['updated_journal'] # # def commit(self, saved_keys): # self.bucket.save(self.journal_key, json.dumps(saved_keys)) # # def exists(self): # return self.bucket.get(self.manifest_key).exists() # # def journal_exists(self): # return self.bucket.get(self.journal_key).exists() # # Path: arbalest/redshift/runner.py # class S3JsonStepRunner(object): # def __init__(self, metadata, schema, bucket, table): # self.metadata = metadata # self.bucket = bucket # self.table = table # self.schema = schema # # @property # def schema_key(self): # return normalize_path( # '{0}/{1}'.format(self.metadata, self.schema.file_name)) # # @property # def schema_url(self): # return 's3://{0}{1}'.format(self.bucket.name, self.schema_key) # # def stage(self): # self.bucket.save(self.schema_key, json.dumps(self.schema.paths())) # self.table.database.open() # # def commit(self): # self.table.database.commit() # self.bucket.delete(self.schema_key) # # def rollback(self): # self.table.database.rollback() # self.bucket.delete(self.schema_key) # # Path: arbalest/s3.py # def normalize_path(path): # return posixpath.normpath(path) , which may include functions, classes, or code. Output only the next line.
self.runner = S3JsonStepRunner(metadata, schema, bucket, table)
Given the following code snippet before the placeholder: <|code_start|> class BulkCopyFromS3JsonStep(PipelineStep): def __init__(self, metadata, source, schema, aws_access_key_id, aws_secret_access_key, bucket, table): self.metadata = metadata self.source = source self.schema = schema self.aws_access_key_id = aws_access_key_id self.aws_secret_access_key = aws_secret_access_key self.bucket = bucket self.table = table self.runner = S3JsonStepRunner(metadata, schema, bucket, table) self.sql = SqlStep(table.database) self.max_error_count = 1 @property def source_key(self): <|code_end|> , predict the next line using imports from the current file: from psycopg2.extensions import AsIs from arbalest.core import PipelineStep from arbalest.redshift.manifest import Manifest from arbalest.redshift.runner import S3JsonStepRunner from arbalest.s3 import normalize_path and context including class names, function names, and sometimes code from other files: # Path: arbalest/core.py # class PipelineStep(object): # def run(self): # pass # # def validate(self): # pass # # Path: arbalest/redshift/manifest.py # class Manifest(object): # def __init__(self, metadata, source, schema, bucket): # self.metadata = metadata # self.source = source # self.schema = schema # self.bucket = bucket # self.file_name = '{0}_manifest.json'.format(schema.table) # self.journal_file_name = '{0}_journal.json'.format(schema.table) # # @property # def all_keys(self): # return [k.name for k in self.bucket.list(self.source) if # not k.name.endswith('/')] # # @property # def manifest_key(self): # return normalize_path('{0}/{1}'.format(self.metadata, self.file_name)) # # @property # def journal_key(self): # return normalize_path( # '{0}/{1}'.format(self.metadata, self.journal_file_name)) # # @property # def manifest_url(self): # return 's3://{0}{1}'.format(self.bucket.name, self.manifest_key) # # def journal(self): # journal = self.bucket.get(self.journal_key) # if journal.exists(): # return json.loads(journal.get_contents_as_string()) # else: # return [] # # def get(self): # updated_journal = self.all_keys # journal = self.journal() # keys = list(set(updated_journal) - set(journal)) # # return { # 'manifest': { # 'entries': [ # {'url': 's3://{0}/{1}'.format(self.bucket.name, key), # 'mandatory': True} for key in keys # ] # }, # 'updated_journal': updated_journal # } # # def save(self): # manifest = self.get() # self.bucket.save(self.manifest_key, json.dumps(manifest['manifest'])) # return manifest['updated_journal'] # # def commit(self, saved_keys): # self.bucket.save(self.journal_key, json.dumps(saved_keys)) # # def exists(self): # return self.bucket.get(self.manifest_key).exists() # # def journal_exists(self): # return self.bucket.get(self.journal_key).exists() # # Path: arbalest/redshift/runner.py # class S3JsonStepRunner(object): # def __init__(self, metadata, schema, bucket, table): # self.metadata = metadata # self.bucket = bucket # self.table = table # self.schema = schema # # @property # def schema_key(self): # return normalize_path( # '{0}/{1}'.format(self.metadata, self.schema.file_name)) # # @property # def schema_url(self): # return 's3://{0}{1}'.format(self.bucket.name, self.schema_key) # # def stage(self): # self.bucket.save(self.schema_key, json.dumps(self.schema.paths())) # self.table.database.open() # # def commit(self): # self.table.database.commit() # self.bucket.delete(self.schema_key) # # def rollback(self): # self.table.database.rollback() # self.bucket.delete(self.schema_key) # # Path: arbalest/s3.py # def normalize_path(path): # return posixpath.normpath(path) . Output only the next line.
return normalize_path(self.source)
Continue the code snippet: <|code_start|> class Manifest(object): def __init__(self, metadata, source, schema, bucket): self.metadata = metadata self.source = source self.schema = schema self.bucket = bucket self.file_name = '{0}_manifest.json'.format(schema.table) self.journal_file_name = '{0}_journal.json'.format(schema.table) @property def all_keys(self): return [k.name for k in self.bucket.list(self.source) if not k.name.endswith('/')] @property def manifest_key(self): <|code_end|> . Use current file imports: import json from arbalest.s3 import normalize_path from arbalest.sql import Database and context (classes, functions, or code) from other files: # Path: arbalest/s3.py # def normalize_path(path): # return posixpath.normpath(path) # # Path: arbalest/sql.py # class Database(object): # cursor = None # # def __init__(self, connection): # self.connection = connection # # def open(self): # if self.cursor is None: # self.cursor = self.connection.cursor() # # def execute(self, sql, params=None): # try: # return self.cursor.execute(sql, params) # except ValueError, e: # if params is None: # return self.cursor.execute(sql, '') # else: # raise ValueError(e) # # def fetchall(self): # for row in self.cursor: # yield row # # def commit(self): # return self.connection.commit() # # def rollback(self): # return self.connection.rollback() # # def close(self): # return self.connection.close() . Output only the next line.
return normalize_path('{0}/{1}'.format(self.metadata, self.file_name))
Next line prediction: <|code_start|> 'entries': [ {'url': 's3://{0}/{1}'.format(self.bucket.name, key), 'mandatory': True} for key in keys ] }, 'updated_journal': updated_journal } def save(self): manifest = self.get() self.bucket.save(self.manifest_key, json.dumps(manifest['manifest'])) return manifest['updated_journal'] def commit(self, saved_keys): self.bucket.save(self.journal_key, json.dumps(saved_keys)) def exists(self): return self.bucket.get(self.manifest_key).exists() def journal_exists(self): return self.bucket.get(self.journal_key).exists() class SqlManifest(object): def __init__(self, metadata, source, schema, bucket, db_connection): self.metadata = metadata self.source = source self.schema = schema self.bucket = bucket <|code_end|> . Use current file imports: (import json from arbalest.s3 import normalize_path from arbalest.sql import Database) and context including class names, function names, or small code snippets from other files: # Path: arbalest/s3.py # def normalize_path(path): # return posixpath.normpath(path) # # Path: arbalest/sql.py # class Database(object): # cursor = None # # def __init__(self, connection): # self.connection = connection # # def open(self): # if self.cursor is None: # self.cursor = self.connection.cursor() # # def execute(self, sql, params=None): # try: # return self.cursor.execute(sql, params) # except ValueError, e: # if params is None: # return self.cursor.execute(sql, '') # else: # raise ValueError(e) # # def fetchall(self): # for row in self.cursor: # yield row # # def commit(self): # return self.connection.commit() # # def rollback(self): # return self.connection.rollback() # # def close(self): # return self.connection.close() . Output only the next line.
if isinstance(db_connection, Database):
Continue the code snippet: <|code_start|> class SqlStepShould(unittest.TestCase): def assert_sql(self, database, select, select_with_where): actual_select_with_where = database.execute.call_args_list[0][0] actual_select = database.execute.call_args_list[1][0] self.assertEqual(2, len(actual_select_with_where)) self.assertEqual(1, len(actual_select)) self.assertEqual(select_with_where[0], actual_select_with_where[0]) self.assertEqual(select, actual_select[0]) def test_execute_statements_and_commit_on_run(self): database = Mock() select_with_where = ( 'SELECT * FROM some_table WHERE some_column1 = %s', "some_value") select = ('SELECT * FROM some_table') <|code_end|> . Use current file imports: import unittest from mock import Mock from arbalest.redshift.step import SqlStep and context (classes, functions, or code) from other files: # Path: arbalest/redshift/step.py # class SqlStep(PipelineStep): # def __init__(self, database, *args): # self.database = database # self.statements = list(args) # # def run(self): # self.database.open() # self.execute(self.statements) # self.database.commit() # # def validate(self): # self.database.open() # self.execute(self.statements) # self.database.rollback() # # def execute(self, statements): # if not isinstance(statements, list): # self.__execute(statements) # else: # for statement in statements: # self.__execute(statement) # # def __execute(self, statement): # if isinstance(statement, basestring): # self.database.execute(statement) # else: # query = statement[0] # params = statement[1:] # self.database.execute(query, tuple([AsIs(x) for x in params])) . Output only the next line.
step = SqlStep(database, select_with_where, select)
Continue the code snippet: <|code_start|> class S3JsonStepRunner(object): def __init__(self, metadata, schema, bucket, table): self.metadata = metadata self.bucket = bucket self.table = table self.schema = schema @property def schema_key(self): <|code_end|> . Use current file imports: import json from arbalest.s3 import normalize_path and context (classes, functions, or code) from other files: # Path: arbalest/s3.py # def normalize_path(path): # return posixpath.normpath(path) . Output only the next line.
return normalize_path(
Given the following code snippet before the placeholder: <|code_start|> @staticmethod def __validate_supported_type(column_type): types = ['SMALLINT', 'INT2', 'INTEGER', 'INT', 'INT4', 'BIGINT', 'INT8', 'DECIMAL', 'NUMERIC', 'REAL', 'FLOAT4', 'DOUBLE PRECISION', 'FLOAT8', 'FLOAT', 'BOOLEAN', 'BOOL', 'CHAR', 'CHARACTER', 'NCHAR', 'BPCHAR', 'VARCHAR', 'CHARACTER VARYING', 'NVARCHAR', 'TEXT', 'DATE', 'TIMESTAMP'] if True not in [type_name in str(column_type).upper() for type_name in types]: <|code_end|> , predict the next line using imports from the current file: from arbalest.core import SchemaException and context including class names, function names, and sometimes code from other files: # Path: arbalest/core.py # class SchemaException(Exception): # pass . Output only the next line.
raise SchemaException(
Continue the code snippet: <|code_start|> class Command(BaseCommand): help = 'Pings configured domain checks for their current status.' def add_arguments(self, parser): parser.add_argument( '--minutes', type=int, dest='minutes', default=5, help='Time cutoff from the last check (in minutes).') parser.add_argument( '--timeout', type=int, dest='timeout', default=10, help='Timeout for server response (in seconds).') def handle(self, *args, **options): verbosity = options['verbosity'] if verbosity > 0: self.stdout.write('Refreshing domain statuses\n') count = 0 cutoff = datetime.timedelta(minutes=options['minutes']) <|code_end|> . Use current file imports: import datetime from django.core.management import BaseCommand from ...models import DomainCheck and context (classes, functions, or code) from other files: # Path: domainchecks/models.py # class DomainCheck(models.Model): # """Configured website check.""" # # PROTOCOL_HTTP = 'http' # PROTOCOL_HTTPS = 'https' # # PROTOCOL_CHOICES = ( # (PROTOCOL_HTTP, 'HTTP'), # (PROTOCOL_HTTPS, 'HTTPS'), # ) # # METHOD_GET = 'get' # METHOD_POST = 'post' # METHOD_PUT = 'put' # METHOD_DELETE = 'delete' # METHOD_HEAD = 'head' # # METHOD_CHOICES = ( # (METHOD_GET, 'GET'), # (METHOD_POST, 'POST'), # (METHOD_PUT, 'PUT'), # (METHOD_DELETE, 'DELETE'), # (METHOD_HEAD, 'HEAD'), # ) # # domain = models.ForeignKey(Domain) # path = models.CharField(max_length=1024) # protocol = models.CharField( # max_length=5, choices=PROTOCOL_CHOICES, default=PROTOCOL_HTTP) # method = models.CharField( # max_length=6, choices=METHOD_CHOICES, default=METHOD_GET) # is_active = models.BooleanField(default=True) # # objects = DomainCheckQuerySet.as_manager() # # def __str__(self): # return '{method} {url}'.format( # method=self.get_method_display(), url=self.url) # # @property # def url(self): # return '{protocol}://{domain}{path}'.format( # protocol=self.protocol, domain=self.domain, path=self.path) # # def run_check(self, timeout=10): # start = time.time() # result = CheckResult(domain_check=self, checked_on=now()) # try: # response = requests.request( # self.method, self.url, allow_redirects=False, timeout=timeout) # result.status_code = response.status_code # response.raise_for_status() # except requests.exceptions.ConnectionError: # # Host could not be resolved or the connection was refused # pass # except requests.exceptions.Timeout: # # Request timed out # pass # except requests.exceptions.RequestException: # # Server responded with 4XX or 5XX status code # result.response_body = response.text # else: # result.response_body = response.text # finally: # result.response_time = time.time() - start # result.save() . Output only the next line.
for check in DomainCheck.objects.active().stale(cutoff=cutoff):
Given the following code snippet before the placeholder: <|code_start|>"""statuspage URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout_then_login, name='logout'), url(r'^password/change/$', auth_views.password_change, {'template_name': 'password-change.html'}, name='password_change'), url(r'^password/change/done/$', auth_views.password_change_done, {'template_name': 'password-change-done.html'}, name='password_change_done'), <|code_end|> , predict the next line using imports from the current file: from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views as auth_views from .views import RegistrationView and context including class names, function names, and sometimes code from other files: # Path: statuspage/views.py # class RegistrationView(CreateView): # """User creation/registration.""" # form_class = UserCreationForm # template_name = 'register.html' # success_url = settings.LOGIN_REDIRECT_URL # # def form_valid(self, form): # response = super().form_valid(form) # # Login the new user # user = authenticate( # username=form.cleaned_data['username'], # password=form.cleaned_data['password1']) # login(self.request, user) # return response . Output only the next line.
url(r'register/$', RegistrationView.as_view(), name='register'),
Based on the snippet: <|code_start|> else: return DomainCheck.objects.none() class StatusDetail(ListView): template_name = 'domainchecks/public-status-detail.html' allow_empty = False context_object_name = 'checks' def get_queryset(self): return DomainCheck.objects.active().filter( domain__name=self.kwargs['domain']).status().order_by('path') class PrivateStatusDetail(StatusDetail): template_name = 'domainchecks/status-detail.html' def get_queryset(self): domain = get_object_or_404(Domain, name=self.kwargs['domain']) if domain.owner != self.request.user: raise PermissionDenied('Must be the domain owner to view this page.') return super().get_queryset() class CheckTimeline(ListView): def get_queryset(self): check = get_object_or_404( DomainCheck.objects.active(), pk=self.kwargs['check']) qs = CheckResult.objects.filter(domain_check=check) <|code_end|> , predict the immediate next line with the help of imports: from django.core.exceptions import PermissionDenied from django.http import JsonResponse from django.views.generic import CreateView, ListView, UpdateView from django.shortcuts import get_object_or_404 from .forms import CheckResultFilter, DomainForm from .models import Domain, DomainCheck, CheckResult and context (classes, functions, sometimes code) from other files: # Path: domainchecks/forms.py # class CheckResultFilter(django_filters.FilterSet): # """Filter check results for a time range.""" # # start = django_filters.DateTimeFilter( # name='checked_on', lookup_type='gte', required=True) # end = django_filters.DateTimeFilter( # name='checked_on', lookup_type='lte', required=True) # # class Meta: # model = models.CheckResult # form = CheckFilterForm # order_by = ('-checked_on', ) # # class DomainForm(forms.ModelForm): # """Form to allow users to create/edit their own domains.""" # # class Meta: # model = models.Domain # fields = ('name', ) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.checks = DomainCheckFormSet( # instance=self.instance, prefix='checks', # data=self.data if self.is_bound else None) # # def is_valid(self): # domain_valid = super().is_valid() # checks_valid = self.checks.is_valid() # return domain_valid and checks_valid # # def save(self, commit=True): # domain = super().save(commit=commit) # domain._checks = self.checks.save(commit=commit) # return domain # # Path: domainchecks/models.py # class Domain(models.Model): # """Domain managed by a user.""" # # name = models.CharField(max_length=253, unique=True) # owner = models.ForeignKey(settings.AUTH_USER_MODEL) # # def __str__(self): # return self.name # # def get_absolute_url(self): # return reverse('status-detail', kwargs={'domain': self.name}) # # class DomainCheck(models.Model): # """Configured website check.""" # # PROTOCOL_HTTP = 'http' # PROTOCOL_HTTPS = 'https' # # PROTOCOL_CHOICES = ( # (PROTOCOL_HTTP, 'HTTP'), # (PROTOCOL_HTTPS, 'HTTPS'), # ) # # METHOD_GET = 'get' # METHOD_POST = 'post' # METHOD_PUT = 'put' # METHOD_DELETE = 'delete' # METHOD_HEAD = 'head' # # METHOD_CHOICES = ( # (METHOD_GET, 'GET'), # (METHOD_POST, 'POST'), # (METHOD_PUT, 'PUT'), # (METHOD_DELETE, 'DELETE'), # (METHOD_HEAD, 'HEAD'), # ) # # domain = models.ForeignKey(Domain) # path = models.CharField(max_length=1024) # protocol = models.CharField( # max_length=5, choices=PROTOCOL_CHOICES, default=PROTOCOL_HTTP) # method = models.CharField( # max_length=6, choices=METHOD_CHOICES, default=METHOD_GET) # is_active = models.BooleanField(default=True) # # objects = DomainCheckQuerySet.as_manager() # # def __str__(self): # return '{method} {url}'.format( # method=self.get_method_display(), url=self.url) # # @property # def url(self): # return '{protocol}://{domain}{path}'.format( # protocol=self.protocol, domain=self.domain, path=self.path) # # def run_check(self, timeout=10): # start = time.time() # result = CheckResult(domain_check=self, checked_on=now()) # try: # response = requests.request( # self.method, self.url, allow_redirects=False, timeout=timeout) # result.status_code = response.status_code # response.raise_for_status() # except requests.exceptions.ConnectionError: # # Host could not be resolved or the connection was refused # pass # except requests.exceptions.Timeout: # # Request timed out # pass # except requests.exceptions.RequestException: # # Server responded with 4XX or 5XX status code # result.response_body = response.text # else: # result.response_body = response.text # finally: # result.response_time = time.time() - start # result.save() # # class CheckResult(models.Model): # """Result of a status check on a website.""" # # domain_check = models.ForeignKey(DomainCheck) # checked_on = models.DateTimeField() # status_code = models.PositiveIntegerField(null=True) # response_time = models.FloatField(null=True) # response_body = models.TextField(default='') . Output only the next line.
results = CheckResultFilter(self.request.GET, queryset=qs, strict=True)
Here is a snippet: <|code_start|> if domain.owner != self.request.user: raise PermissionDenied('Must be the domain owner to view this page.') return super().get_queryset() class CheckTimeline(ListView): def get_queryset(self): check = get_object_or_404( DomainCheck.objects.active(), pk=self.kwargs['check']) qs = CheckResult.objects.filter(domain_check=check) results = CheckResultFilter(self.request.GET, queryset=qs, strict=True) self._filters_valid = results.form.is_valid() return results.qs.values('checked_on', 'response_time', 'status_code') def render_to_response(self, context, **response_kwargs): results = self.get_results(context) if not getattr(self, '_filters_valid', False): response_kwargs['status'] = 400 return JsonResponse(results, **response_kwargs) def get_results(self, context): results = list(context['object_list']) return { 'results': results, } class CreateDomain(CreateView): model = Domain <|code_end|> . Write the next line using the current file imports: from django.core.exceptions import PermissionDenied from django.http import JsonResponse from django.views.generic import CreateView, ListView, UpdateView from django.shortcuts import get_object_or_404 from .forms import CheckResultFilter, DomainForm from .models import Domain, DomainCheck, CheckResult and context from other files: # Path: domainchecks/forms.py # class CheckResultFilter(django_filters.FilterSet): # """Filter check results for a time range.""" # # start = django_filters.DateTimeFilter( # name='checked_on', lookup_type='gte', required=True) # end = django_filters.DateTimeFilter( # name='checked_on', lookup_type='lte', required=True) # # class Meta: # model = models.CheckResult # form = CheckFilterForm # order_by = ('-checked_on', ) # # class DomainForm(forms.ModelForm): # """Form to allow users to create/edit their own domains.""" # # class Meta: # model = models.Domain # fields = ('name', ) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.checks = DomainCheckFormSet( # instance=self.instance, prefix='checks', # data=self.data if self.is_bound else None) # # def is_valid(self): # domain_valid = super().is_valid() # checks_valid = self.checks.is_valid() # return domain_valid and checks_valid # # def save(self, commit=True): # domain = super().save(commit=commit) # domain._checks = self.checks.save(commit=commit) # return domain # # Path: domainchecks/models.py # class Domain(models.Model): # """Domain managed by a user.""" # # name = models.CharField(max_length=253, unique=True) # owner = models.ForeignKey(settings.AUTH_USER_MODEL) # # def __str__(self): # return self.name # # def get_absolute_url(self): # return reverse('status-detail', kwargs={'domain': self.name}) # # class DomainCheck(models.Model): # """Configured website check.""" # # PROTOCOL_HTTP = 'http' # PROTOCOL_HTTPS = 'https' # # PROTOCOL_CHOICES = ( # (PROTOCOL_HTTP, 'HTTP'), # (PROTOCOL_HTTPS, 'HTTPS'), # ) # # METHOD_GET = 'get' # METHOD_POST = 'post' # METHOD_PUT = 'put' # METHOD_DELETE = 'delete' # METHOD_HEAD = 'head' # # METHOD_CHOICES = ( # (METHOD_GET, 'GET'), # (METHOD_POST, 'POST'), # (METHOD_PUT, 'PUT'), # (METHOD_DELETE, 'DELETE'), # (METHOD_HEAD, 'HEAD'), # ) # # domain = models.ForeignKey(Domain) # path = models.CharField(max_length=1024) # protocol = models.CharField( # max_length=5, choices=PROTOCOL_CHOICES, default=PROTOCOL_HTTP) # method = models.CharField( # max_length=6, choices=METHOD_CHOICES, default=METHOD_GET) # is_active = models.BooleanField(default=True) # # objects = DomainCheckQuerySet.as_manager() # # def __str__(self): # return '{method} {url}'.format( # method=self.get_method_display(), url=self.url) # # @property # def url(self): # return '{protocol}://{domain}{path}'.format( # protocol=self.protocol, domain=self.domain, path=self.path) # # def run_check(self, timeout=10): # start = time.time() # result = CheckResult(domain_check=self, checked_on=now()) # try: # response = requests.request( # self.method, self.url, allow_redirects=False, timeout=timeout) # result.status_code = response.status_code # response.raise_for_status() # except requests.exceptions.ConnectionError: # # Host could not be resolved or the connection was refused # pass # except requests.exceptions.Timeout: # # Request timed out # pass # except requests.exceptions.RequestException: # # Server responded with 4XX or 5XX status code # result.response_body = response.text # else: # result.response_body = response.text # finally: # result.response_time = time.time() - start # result.save() # # class CheckResult(models.Model): # """Result of a status check on a website.""" # # domain_check = models.ForeignKey(DomainCheck) # checked_on = models.DateTimeField() # status_code = models.PositiveIntegerField(null=True) # response_time = models.FloatField(null=True) # response_body = models.TextField(default='') , which may include functions, classes, or code. Output only the next line.
form_class = DomainForm
Given the code snippet: <|code_start|> class StatusList(ListView): template_name = 'domainchecks/status-list.html' context_object_name = 'domains' def get_queryset(self): if self.request.user.is_authenticated(): return DomainCheck.objects.active().filter( domain__owner=self.request.user ).values('domain__name').status().order_by('domain__name') else: return DomainCheck.objects.none() class StatusDetail(ListView): template_name = 'domainchecks/public-status-detail.html' allow_empty = False context_object_name = 'checks' def get_queryset(self): return DomainCheck.objects.active().filter( domain__name=self.kwargs['domain']).status().order_by('path') class PrivateStatusDetail(StatusDetail): template_name = 'domainchecks/status-detail.html' def get_queryset(self): <|code_end|> , generate the next line using the imports in this file: from django.core.exceptions import PermissionDenied from django.http import JsonResponse from django.views.generic import CreateView, ListView, UpdateView from django.shortcuts import get_object_or_404 from .forms import CheckResultFilter, DomainForm from .models import Domain, DomainCheck, CheckResult and context (functions, classes, or occasionally code) from other files: # Path: domainchecks/forms.py # class CheckResultFilter(django_filters.FilterSet): # """Filter check results for a time range.""" # # start = django_filters.DateTimeFilter( # name='checked_on', lookup_type='gte', required=True) # end = django_filters.DateTimeFilter( # name='checked_on', lookup_type='lte', required=True) # # class Meta: # model = models.CheckResult # form = CheckFilterForm # order_by = ('-checked_on', ) # # class DomainForm(forms.ModelForm): # """Form to allow users to create/edit their own domains.""" # # class Meta: # model = models.Domain # fields = ('name', ) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.checks = DomainCheckFormSet( # instance=self.instance, prefix='checks', # data=self.data if self.is_bound else None) # # def is_valid(self): # domain_valid = super().is_valid() # checks_valid = self.checks.is_valid() # return domain_valid and checks_valid # # def save(self, commit=True): # domain = super().save(commit=commit) # domain._checks = self.checks.save(commit=commit) # return domain # # Path: domainchecks/models.py # class Domain(models.Model): # """Domain managed by a user.""" # # name = models.CharField(max_length=253, unique=True) # owner = models.ForeignKey(settings.AUTH_USER_MODEL) # # def __str__(self): # return self.name # # def get_absolute_url(self): # return reverse('status-detail', kwargs={'domain': self.name}) # # class DomainCheck(models.Model): # """Configured website check.""" # # PROTOCOL_HTTP = 'http' # PROTOCOL_HTTPS = 'https' # # PROTOCOL_CHOICES = ( # (PROTOCOL_HTTP, 'HTTP'), # (PROTOCOL_HTTPS, 'HTTPS'), # ) # # METHOD_GET = 'get' # METHOD_POST = 'post' # METHOD_PUT = 'put' # METHOD_DELETE = 'delete' # METHOD_HEAD = 'head' # # METHOD_CHOICES = ( # (METHOD_GET, 'GET'), # (METHOD_POST, 'POST'), # (METHOD_PUT, 'PUT'), # (METHOD_DELETE, 'DELETE'), # (METHOD_HEAD, 'HEAD'), # ) # # domain = models.ForeignKey(Domain) # path = models.CharField(max_length=1024) # protocol = models.CharField( # max_length=5, choices=PROTOCOL_CHOICES, default=PROTOCOL_HTTP) # method = models.CharField( # max_length=6, choices=METHOD_CHOICES, default=METHOD_GET) # is_active = models.BooleanField(default=True) # # objects = DomainCheckQuerySet.as_manager() # # def __str__(self): # return '{method} {url}'.format( # method=self.get_method_display(), url=self.url) # # @property # def url(self): # return '{protocol}://{domain}{path}'.format( # protocol=self.protocol, domain=self.domain, path=self.path) # # def run_check(self, timeout=10): # start = time.time() # result = CheckResult(domain_check=self, checked_on=now()) # try: # response = requests.request( # self.method, self.url, allow_redirects=False, timeout=timeout) # result.status_code = response.status_code # response.raise_for_status() # except requests.exceptions.ConnectionError: # # Host could not be resolved or the connection was refused # pass # except requests.exceptions.Timeout: # # Request timed out # pass # except requests.exceptions.RequestException: # # Server responded with 4XX or 5XX status code # result.response_body = response.text # else: # result.response_body = response.text # finally: # result.response_time = time.time() - start # result.save() # # class CheckResult(models.Model): # """Result of a status check on a website.""" # # domain_check = models.ForeignKey(DomainCheck) # checked_on = models.DateTimeField() # status_code = models.PositiveIntegerField(null=True) # response_time = models.FloatField(null=True) # response_body = models.TextField(default='') . Output only the next line.
domain = get_object_or_404(Domain, name=self.kwargs['domain'])
Predict the next line for this snippet: <|code_start|> class StatusList(ListView): template_name = 'domainchecks/status-list.html' context_object_name = 'domains' def get_queryset(self): if self.request.user.is_authenticated(): <|code_end|> with the help of current file imports: from django.core.exceptions import PermissionDenied from django.http import JsonResponse from django.views.generic import CreateView, ListView, UpdateView from django.shortcuts import get_object_or_404 from .forms import CheckResultFilter, DomainForm from .models import Domain, DomainCheck, CheckResult and context from other files: # Path: domainchecks/forms.py # class CheckResultFilter(django_filters.FilterSet): # """Filter check results for a time range.""" # # start = django_filters.DateTimeFilter( # name='checked_on', lookup_type='gte', required=True) # end = django_filters.DateTimeFilter( # name='checked_on', lookup_type='lte', required=True) # # class Meta: # model = models.CheckResult # form = CheckFilterForm # order_by = ('-checked_on', ) # # class DomainForm(forms.ModelForm): # """Form to allow users to create/edit their own domains.""" # # class Meta: # model = models.Domain # fields = ('name', ) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.checks = DomainCheckFormSet( # instance=self.instance, prefix='checks', # data=self.data if self.is_bound else None) # # def is_valid(self): # domain_valid = super().is_valid() # checks_valid = self.checks.is_valid() # return domain_valid and checks_valid # # def save(self, commit=True): # domain = super().save(commit=commit) # domain._checks = self.checks.save(commit=commit) # return domain # # Path: domainchecks/models.py # class Domain(models.Model): # """Domain managed by a user.""" # # name = models.CharField(max_length=253, unique=True) # owner = models.ForeignKey(settings.AUTH_USER_MODEL) # # def __str__(self): # return self.name # # def get_absolute_url(self): # return reverse('status-detail', kwargs={'domain': self.name}) # # class DomainCheck(models.Model): # """Configured website check.""" # # PROTOCOL_HTTP = 'http' # PROTOCOL_HTTPS = 'https' # # PROTOCOL_CHOICES = ( # (PROTOCOL_HTTP, 'HTTP'), # (PROTOCOL_HTTPS, 'HTTPS'), # ) # # METHOD_GET = 'get' # METHOD_POST = 'post' # METHOD_PUT = 'put' # METHOD_DELETE = 'delete' # METHOD_HEAD = 'head' # # METHOD_CHOICES = ( # (METHOD_GET, 'GET'), # (METHOD_POST, 'POST'), # (METHOD_PUT, 'PUT'), # (METHOD_DELETE, 'DELETE'), # (METHOD_HEAD, 'HEAD'), # ) # # domain = models.ForeignKey(Domain) # path = models.CharField(max_length=1024) # protocol = models.CharField( # max_length=5, choices=PROTOCOL_CHOICES, default=PROTOCOL_HTTP) # method = models.CharField( # max_length=6, choices=METHOD_CHOICES, default=METHOD_GET) # is_active = models.BooleanField(default=True) # # objects = DomainCheckQuerySet.as_manager() # # def __str__(self): # return '{method} {url}'.format( # method=self.get_method_display(), url=self.url) # # @property # def url(self): # return '{protocol}://{domain}{path}'.format( # protocol=self.protocol, domain=self.domain, path=self.path) # # def run_check(self, timeout=10): # start = time.time() # result = CheckResult(domain_check=self, checked_on=now()) # try: # response = requests.request( # self.method, self.url, allow_redirects=False, timeout=timeout) # result.status_code = response.status_code # response.raise_for_status() # except requests.exceptions.ConnectionError: # # Host could not be resolved or the connection was refused # pass # except requests.exceptions.Timeout: # # Request timed out # pass # except requests.exceptions.RequestException: # # Server responded with 4XX or 5XX status code # result.response_body = response.text # else: # result.response_body = response.text # finally: # result.response_time = time.time() - start # result.save() # # class CheckResult(models.Model): # """Result of a status check on a website.""" # # domain_check = models.ForeignKey(DomainCheck) # checked_on = models.DateTimeField() # status_code = models.PositiveIntegerField(null=True) # response_time = models.FloatField(null=True) # response_body = models.TextField(default='') , which may contain function names, class names, or code. Output only the next line.
return DomainCheck.objects.active().filter(
Using the snippet: <|code_start|> ).values('domain__name').status().order_by('domain__name') else: return DomainCheck.objects.none() class StatusDetail(ListView): template_name = 'domainchecks/public-status-detail.html' allow_empty = False context_object_name = 'checks' def get_queryset(self): return DomainCheck.objects.active().filter( domain__name=self.kwargs['domain']).status().order_by('path') class PrivateStatusDetail(StatusDetail): template_name = 'domainchecks/status-detail.html' def get_queryset(self): domain = get_object_or_404(Domain, name=self.kwargs['domain']) if domain.owner != self.request.user: raise PermissionDenied('Must be the domain owner to view this page.') return super().get_queryset() class CheckTimeline(ListView): def get_queryset(self): check = get_object_or_404( DomainCheck.objects.active(), pk=self.kwargs['check']) <|code_end|> , determine the next line of code. You have imports: from django.core.exceptions import PermissionDenied from django.http import JsonResponse from django.views.generic import CreateView, ListView, UpdateView from django.shortcuts import get_object_or_404 from .forms import CheckResultFilter, DomainForm from .models import Domain, DomainCheck, CheckResult and context (class names, function names, or code) available: # Path: domainchecks/forms.py # class CheckResultFilter(django_filters.FilterSet): # """Filter check results for a time range.""" # # start = django_filters.DateTimeFilter( # name='checked_on', lookup_type='gte', required=True) # end = django_filters.DateTimeFilter( # name='checked_on', lookup_type='lte', required=True) # # class Meta: # model = models.CheckResult # form = CheckFilterForm # order_by = ('-checked_on', ) # # class DomainForm(forms.ModelForm): # """Form to allow users to create/edit their own domains.""" # # class Meta: # model = models.Domain # fields = ('name', ) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.checks = DomainCheckFormSet( # instance=self.instance, prefix='checks', # data=self.data if self.is_bound else None) # # def is_valid(self): # domain_valid = super().is_valid() # checks_valid = self.checks.is_valid() # return domain_valid and checks_valid # # def save(self, commit=True): # domain = super().save(commit=commit) # domain._checks = self.checks.save(commit=commit) # return domain # # Path: domainchecks/models.py # class Domain(models.Model): # """Domain managed by a user.""" # # name = models.CharField(max_length=253, unique=True) # owner = models.ForeignKey(settings.AUTH_USER_MODEL) # # def __str__(self): # return self.name # # def get_absolute_url(self): # return reverse('status-detail', kwargs={'domain': self.name}) # # class DomainCheck(models.Model): # """Configured website check.""" # # PROTOCOL_HTTP = 'http' # PROTOCOL_HTTPS = 'https' # # PROTOCOL_CHOICES = ( # (PROTOCOL_HTTP, 'HTTP'), # (PROTOCOL_HTTPS, 'HTTPS'), # ) # # METHOD_GET = 'get' # METHOD_POST = 'post' # METHOD_PUT = 'put' # METHOD_DELETE = 'delete' # METHOD_HEAD = 'head' # # METHOD_CHOICES = ( # (METHOD_GET, 'GET'), # (METHOD_POST, 'POST'), # (METHOD_PUT, 'PUT'), # (METHOD_DELETE, 'DELETE'), # (METHOD_HEAD, 'HEAD'), # ) # # domain = models.ForeignKey(Domain) # path = models.CharField(max_length=1024) # protocol = models.CharField( # max_length=5, choices=PROTOCOL_CHOICES, default=PROTOCOL_HTTP) # method = models.CharField( # max_length=6, choices=METHOD_CHOICES, default=METHOD_GET) # is_active = models.BooleanField(default=True) # # objects = DomainCheckQuerySet.as_manager() # # def __str__(self): # return '{method} {url}'.format( # method=self.get_method_display(), url=self.url) # # @property # def url(self): # return '{protocol}://{domain}{path}'.format( # protocol=self.protocol, domain=self.domain, path=self.path) # # def run_check(self, timeout=10): # start = time.time() # result = CheckResult(domain_check=self, checked_on=now()) # try: # response = requests.request( # self.method, self.url, allow_redirects=False, timeout=timeout) # result.status_code = response.status_code # response.raise_for_status() # except requests.exceptions.ConnectionError: # # Host could not be resolved or the connection was refused # pass # except requests.exceptions.Timeout: # # Request timed out # pass # except requests.exceptions.RequestException: # # Server responded with 4XX or 5XX status code # result.response_body = response.text # else: # result.response_body = response.text # finally: # result.response_time = time.time() - start # result.save() # # class CheckResult(models.Model): # """Result of a status check on a website.""" # # domain_check = models.ForeignKey(DomainCheck) # checked_on = models.DateTimeField() # status_code = models.PositiveIntegerField(null=True) # response_time = models.FloatField(null=True) # response_body = models.TextField(default='') . Output only the next line.
qs = CheckResult.objects.filter(domain_check=check)
Given the following code snippet before the placeholder: <|code_start|>"""A simple demonstration of LKD to read data from a system bus using any custom driver. Here we read the BIOS_CNTL (bus = 0x00, device = 0x1F, function = 0x00, offset = 0xDC) PCI register which is in charge of protecting the SPI Flash, containing the BIOS, on the Platform Controller HUB (PCH)""" if os.getcwd().endswith("example"): sys.path.append(os.path.realpath("..")) else: sys.path.append(os.path.realpath(".")) # Indicates PCI configuration space. # Value from _BUS_DATA_TYPE # https://msdn.microsoft.com/en-us/library/windows/hardware/ff540700(v=vs.85).aspx PCIConfiguration = 4 # LPC device PCI configuration space bus_num = 0 device_num = 0x1F function_num = 0 # BIOS_CNTL register offset_bios_cntl = 0xDC SMM_BWP_mask = 1 << 5 # 0x20 BLE_mask = 1 << 1 # 0x2 BIOSWE_mask = 1 << 0 # 0x1 if __name__ == '__main__': <|code_end|> , predict the next line using imports from the current file: import os import sys from dbginterface import LocalKernelDebugger and context including class names, function names, and sometimes code from other files: # Path: dbginterface.py # def LocalKernelDebugger(quiet=True): # """| Check that all conditions to Local Kernel Debugging are met # | and return a LKD (subclass of :class:`LocalKernelDebuggerBase` # """ # if not windows.utils.check_debug(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging on kernel not in DEBUG mode") # if not windows.utils.check_is_elevated(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from non-Admin process") # windows.utils.enable_privilege(SE_DEBUG_NAME, True) # if windows.system.bitness == 64: # if windows.current_process.is_wow_64: # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from SysWow64 process (please launch from 64bits python)") # return LocalKernelDebugger64(quiet) # return LocalKernelDebugger32(quiet) . Output only the next line.
kdbg = LocalKernelDebugger()
Continue the code snippet: <|code_start|> # Re-activate IA32_PMC0 kdbg.write_msr(MSR_PERF_GLOBAL_CTRL, 1) # PEBS records getters def get_number_pebs_records(self, proc_nb): """Get the number of PEBS entries stored in the buffer for proc `proc_nb`""" ds_addr, ds_content = self.get_DsManagementArea(proc_nb) return (ds_content.PEBSIndex - ds_content.PEBSBufferBase) / ctypes.sizeof(self.PEBSRecord) def get_pebs_records(self, proc_nb, max_dump=0xffffffffffffffff): """Get the PEBS entries stored in the buffer for proc `proc_nb`""" ds_addr, ds_content = self.get_DsManagementArea(proc_nb) nb_pebs_entry = self.get_number_pebs_records(proc_nb) print("Buffer contains {0} entries".format(nb_pebs_entry)) nb_pebs_entry = min(nb_pebs_entry, max_dump) print("Dumping {0} first entries".format(nb_pebs_entry)) pebs_entries_buffer = (self.PEBSRecord * nb_pebs_entry)() kdbg.read_virtual_memory_into(ds_content.PEBSBufferBase, pebs_entries_buffer) return pebs_entries_buffer def dump_PEBS_records(self): ds_addr, ds_content = self.get_DsManagementArea(proc_nb) print("PEBSBufferBase = {0}".format(hex(ds_content.PEBSBufferBase))) x = self.get_pebs_records(0) for pebs_record in x: print(" {0} = {1}".format("rip", hex(pebs_record.rip))) # BTS <|code_end|> . Use current file imports: import ctypes import sys import os import time from windows.generated_def.winstructs import * from dbginterface import LocalKernelDebugger and context (classes, functions, or code) from other files: # Path: dbginterface.py # def LocalKernelDebugger(quiet=True): # """| Check that all conditions to Local Kernel Debugging are met # | and return a LKD (subclass of :class:`LocalKernelDebuggerBase` # """ # if not windows.utils.check_debug(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging on kernel not in DEBUG mode") # if not windows.utils.check_is_elevated(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from non-Admin process") # windows.utils.enable_privilege(SE_DEBUG_NAME, True) # if windows.system.bitness == 64: # if windows.current_process.is_wow_64: # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from SysWow64 process (please launch from 64bits python)") # return LocalKernelDebugger64(quiet) # return LocalKernelDebugger32(quiet) . Output only the next line.
kdbg = LocalKernelDebugger()
Next line prediction: <|code_start|> if to_string: old_output = self._output_callback self._init_string_output_callback() self.DebugControl.Execute(0, str, 0) if to_string: if old_output is None: old_output = self._standard_output_callback self.set_output_callbacks(old_output) return self._output_string return None def _standard_output_callback(self, x, y, msg): if not self.quiet: print msg, return 0 def _init_string_output_callback(self): self._output_string = "" self.set_output_callbacks(self._string_output_callback) def _string_output_callback(self, x, y, msg): self._output_string += msg return 0 def set_output_callbacks(self, callback): r"""| Register a new output callback, that must respect the interface of | :func:`IDebugOutputCallbacks::Output` `<https://msdn.microsoft.com/en-us/library/windows/hardware/ff550815%28v=vs.85%29.aspx>`_. | (see :file:`example\\output_demo.py`) """ self._output_callback = callback <|code_end|> . Use current file imports: (import os import struct import itertools import functools import ctypes import resource_emulation import driver_upgrade import windows import windows.hooks import windows.winproxy as winproxy from os.path import realpath, dirname from ctypes import byref, WINFUNCTYPE, HRESULT, WinError from simple_com import COMInterface, IDebugOutputCallbacksVtable from driver_upgrade import DU_MEMALLOC_IOCTL, DU_KCALL_IOCTL, DU_OUT_IOCTL, DU_IN_IOCTL from windows.generated_def.winstructs import * from dbgdef import * from dbgtype import DbgEngType) and context including class names, function names, or small code snippets from other files: # Path: simple_com.py # class COMInterface(ctypes.c_void_p): # _functions_ = { # "QueryInterface": ctypes.WINFUNCTYPE(HRESULT, ctypes.c_void_p, ctypes.c_void_p)(0, "QueryInterface"), # "AddRef": ctypes.WINFUNCTYPE(HRESULT)(1, "AddRef"), # "Release": ctypes.WINFUNCTYPE(HRESULT)(2, "Release") # } # # def __getattr__(self, name): # if name in self._functions_: # return functools.partial(self._functions_[name], self) # return super(COMInterface, self).__getattribute__(name) # # class IDebugOutputCallbacksVtable(ComVtable): # _funcs_ = ComVtable._funcs_ + [("Output", [ctypes.HRESULT, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_char_p], None)] # # Path: driver_upgrade.py # DU_MEMALLOC_IOCTL = 0x220027 # # DU_KCALL_IOCTL = 0x220037 # # DU_OUT_IOCTL = 0x220057 # # DU_IN_IOCTL = 0x220067 # # Path: dbgtype.py # class DbgEngType(DbgEngTypeBase): # @property # def name(self): # return self.kdbg.get_type_name(self.module, self.typeid) # # @property # def is_array(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("[]") # # @property # def is_pointer(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("*") # # @property # def fields(self): # children = self.kdbg.get_childs_types(self.module, self.typeid) # return [DbgEngField(self.module, x, self.kdbg) for x in children.Types] # # @property # def fields_dict(self): # return {x.name: x for x in self.fields} # # @property # def number_elt(self): # return self.SymGetTypeInfo(TI_GET_COUNT) # # def __repr__(self): # return '<DbgEngType "{0}">'.format(self.name) # # def __call__(self, addr): # return get_mapped_type(self, addr) . Output only the next line.
my_idebugoutput_vtable = IDebugOutputCallbacksVtable.create_vtable(Output=callback)
Continue the code snippet: <|code_start|> windows.winproxy.DeviceIoControl(h, DU_KCALL_IOCTL, buffer, len(buffer), byref(res), ctypes.sizeof(res)) return res.value @require_upgraded_driver def do_in(self, port, size): """Perform IN instruction in kernel mode""" if size not in [1, 2, 4]: raise ValueError("Invalid IN size: {0}".format(size)) h = self._get_kldbgdrv_handle() buffer = struct.pack("<II", size, port) res = DWORD(0x44444444) windows.winproxy.DeviceIoControl(h, DU_IN_IOCTL, buffer, len(buffer), byref(res), ctypes.sizeof(res)) return res.value @require_upgraded_driver def do_out(self, port, value, size): """Perform OUT instruction in kernel mode""" if size not in [1, 2, 4]: raise ValueError("Invalid OUT size: {0}".format(size)) h = self._get_kldbgdrv_handle() buffer = struct.pack("<III", size, port, value) windows.winproxy.DeviceIoControl(h, DU_OUT_IOCTL, buffer, len(buffer), 0, 0) return None @require_upgraded_driver def alloc_memory(self, size=0x1000, type=0, tag=0x45544942): """Allocation <size> of NonPaged kernel memory""" h = self._get_kldbgdrv_handle() buffer = struct.pack("<III", type, size, tag) res = DWORD(0x44444444) <|code_end|> . Use current file imports: import os import struct import itertools import functools import ctypes import resource_emulation import driver_upgrade import windows import windows.hooks import windows.winproxy as winproxy from os.path import realpath, dirname from ctypes import byref, WINFUNCTYPE, HRESULT, WinError from simple_com import COMInterface, IDebugOutputCallbacksVtable from driver_upgrade import DU_MEMALLOC_IOCTL, DU_KCALL_IOCTL, DU_OUT_IOCTL, DU_IN_IOCTL from windows.generated_def.winstructs import * from dbgdef import * from dbgtype import DbgEngType and context (classes, functions, or code) from other files: # Path: simple_com.py # class COMInterface(ctypes.c_void_p): # _functions_ = { # "QueryInterface": ctypes.WINFUNCTYPE(HRESULT, ctypes.c_void_p, ctypes.c_void_p)(0, "QueryInterface"), # "AddRef": ctypes.WINFUNCTYPE(HRESULT)(1, "AddRef"), # "Release": ctypes.WINFUNCTYPE(HRESULT)(2, "Release") # } # # def __getattr__(self, name): # if name in self._functions_: # return functools.partial(self._functions_[name], self) # return super(COMInterface, self).__getattribute__(name) # # class IDebugOutputCallbacksVtable(ComVtable): # _funcs_ = ComVtable._funcs_ + [("Output", [ctypes.HRESULT, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_char_p], None)] # # Path: driver_upgrade.py # DU_MEMALLOC_IOCTL = 0x220027 # # DU_KCALL_IOCTL = 0x220037 # # DU_OUT_IOCTL = 0x220057 # # DU_IN_IOCTL = 0x220067 # # Path: dbgtype.py # class DbgEngType(DbgEngTypeBase): # @property # def name(self): # return self.kdbg.get_type_name(self.module, self.typeid) # # @property # def is_array(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("[]") # # @property # def is_pointer(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("*") # # @property # def fields(self): # children = self.kdbg.get_childs_types(self.module, self.typeid) # return [DbgEngField(self.module, x, self.kdbg) for x in children.Types] # # @property # def fields_dict(self): # return {x.name: x for x in self.fields} # # @property # def number_elt(self): # return self.SymGetTypeInfo(TI_GET_COUNT) # # def __repr__(self): # return '<DbgEngType "{0}">'.format(self.name) # # def __call__(self, addr): # return get_mapped_type(self, addr) . Output only the next line.
windows.winproxy.DeviceIoControl(h, DU_MEMALLOC_IOCTL, buffer, len(buffer), byref(res), 4)
Given snippet: <|code_start|> FindResourceW_addr_jump = dbgengmod.DllBase + self.FindResourceW_addr_jump_offset DummyFindResourceWIAT = DummyIATEntry.create(FindResourceW_addr_jump, "kernel32.dll", "FindResourceW") # Add our driver to emulated resources resource_emulation.resource_list.append(self.DRIVER_RESOURCE) # Setup Resource emulation into dbgeng.dll DummyFindResourceWIAT.set_hook(resource_emulation.FindResourceWHook) SizeofResourceIAT.set_hook(resource_emulation.SizeofResourceHook) LoadResourceIAT.set_hook(resource_emulation.LoadResourceHook) LockResourceIAT.set_hook(resource_emulation.LockResourceHook) def _setup_name_imposture(self, dbgengmod, k32import): GetModuleFileNameW_addr_jump = dbgengmod.DllBase + self.GetModuleFileNameW_addr_jump_offset DummyGetModuleFileNameWIAT = DummyIATEntry.create(GetModuleFileNameW_addr_jump, "kernel32.dll", "GetModuleFileNameW") DummyGetModuleFileNameWIAT.set_hook(EmulateWinDBGName) # Driver upgrade stuff def _upgrade_driver(self): self.upgrader = driver_upgrade.DriverUpgrader32(self) self.upgrader.upgrade_driver() # upgraded driver API @require_upgraded_driver def kcall(self, target, *args): """Call target in kernel mode with given arguments""" target = self.resolve_symbol(target) args = [arg if arg is not None else 0 for arg in args] buffer = struct.pack("<" + "I" * (len(args) + 1), target, *args) h = self._get_kldbgdrv_handle() res = DWORD(0x44444444) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import struct import itertools import functools import ctypes import resource_emulation import driver_upgrade import windows import windows.hooks import windows.winproxy as winproxy from os.path import realpath, dirname from ctypes import byref, WINFUNCTYPE, HRESULT, WinError from simple_com import COMInterface, IDebugOutputCallbacksVtable from driver_upgrade import DU_MEMALLOC_IOCTL, DU_KCALL_IOCTL, DU_OUT_IOCTL, DU_IN_IOCTL from windows.generated_def.winstructs import * from dbgdef import * from dbgtype import DbgEngType and context: # Path: simple_com.py # class COMInterface(ctypes.c_void_p): # _functions_ = { # "QueryInterface": ctypes.WINFUNCTYPE(HRESULT, ctypes.c_void_p, ctypes.c_void_p)(0, "QueryInterface"), # "AddRef": ctypes.WINFUNCTYPE(HRESULT)(1, "AddRef"), # "Release": ctypes.WINFUNCTYPE(HRESULT)(2, "Release") # } # # def __getattr__(self, name): # if name in self._functions_: # return functools.partial(self._functions_[name], self) # return super(COMInterface, self).__getattribute__(name) # # class IDebugOutputCallbacksVtable(ComVtable): # _funcs_ = ComVtable._funcs_ + [("Output", [ctypes.HRESULT, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_char_p], None)] # # Path: driver_upgrade.py # DU_MEMALLOC_IOCTL = 0x220027 # # DU_KCALL_IOCTL = 0x220037 # # DU_OUT_IOCTL = 0x220057 # # DU_IN_IOCTL = 0x220067 # # Path: dbgtype.py # class DbgEngType(DbgEngTypeBase): # @property # def name(self): # return self.kdbg.get_type_name(self.module, self.typeid) # # @property # def is_array(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("[]") # # @property # def is_pointer(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("*") # # @property # def fields(self): # children = self.kdbg.get_childs_types(self.module, self.typeid) # return [DbgEngField(self.module, x, self.kdbg) for x in children.Types] # # @property # def fields_dict(self): # return {x.name: x for x in self.fields} # # @property # def number_elt(self): # return self.SymGetTypeInfo(TI_GET_COUNT) # # def __repr__(self): # return '<DbgEngType "{0}">'.format(self.name) # # def __call__(self, addr): # return get_mapped_type(self, addr) which might include code, classes, or functions. Output only the next line.
windows.winproxy.DeviceIoControl(h, DU_KCALL_IOCTL, buffer, len(buffer), byref(res), ctypes.sizeof(res))
Next line prediction: <|code_start|> # upgraded driver API @require_upgraded_driver def kcall(self, target, *args): """Call target in kernel mode with given arguments""" target = self.resolve_symbol(target) args = [arg if arg is not None else 0 for arg in args] buffer = struct.pack("<" + "I" * (len(args) + 1), target, *args) h = self._get_kldbgdrv_handle() res = DWORD(0x44444444) windows.winproxy.DeviceIoControl(h, DU_KCALL_IOCTL, buffer, len(buffer), byref(res), ctypes.sizeof(res)) return res.value @require_upgraded_driver def do_in(self, port, size): """Perform IN instruction in kernel mode""" if size not in [1, 2, 4]: raise ValueError("Invalid IN size: {0}".format(size)) h = self._get_kldbgdrv_handle() buffer = struct.pack("<II", size, port) res = DWORD(0x44444444) windows.winproxy.DeviceIoControl(h, DU_IN_IOCTL, buffer, len(buffer), byref(res), ctypes.sizeof(res)) return res.value @require_upgraded_driver def do_out(self, port, value, size): """Perform OUT instruction in kernel mode""" if size not in [1, 2, 4]: raise ValueError("Invalid OUT size: {0}".format(size)) h = self._get_kldbgdrv_handle() buffer = struct.pack("<III", size, port, value) <|code_end|> . Use current file imports: (import os import struct import itertools import functools import ctypes import resource_emulation import driver_upgrade import windows import windows.hooks import windows.winproxy as winproxy from os.path import realpath, dirname from ctypes import byref, WINFUNCTYPE, HRESULT, WinError from simple_com import COMInterface, IDebugOutputCallbacksVtable from driver_upgrade import DU_MEMALLOC_IOCTL, DU_KCALL_IOCTL, DU_OUT_IOCTL, DU_IN_IOCTL from windows.generated_def.winstructs import * from dbgdef import * from dbgtype import DbgEngType) and context including class names, function names, or small code snippets from other files: # Path: simple_com.py # class COMInterface(ctypes.c_void_p): # _functions_ = { # "QueryInterface": ctypes.WINFUNCTYPE(HRESULT, ctypes.c_void_p, ctypes.c_void_p)(0, "QueryInterface"), # "AddRef": ctypes.WINFUNCTYPE(HRESULT)(1, "AddRef"), # "Release": ctypes.WINFUNCTYPE(HRESULT)(2, "Release") # } # # def __getattr__(self, name): # if name in self._functions_: # return functools.partial(self._functions_[name], self) # return super(COMInterface, self).__getattribute__(name) # # class IDebugOutputCallbacksVtable(ComVtable): # _funcs_ = ComVtable._funcs_ + [("Output", [ctypes.HRESULT, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_char_p], None)] # # Path: driver_upgrade.py # DU_MEMALLOC_IOCTL = 0x220027 # # DU_KCALL_IOCTL = 0x220037 # # DU_OUT_IOCTL = 0x220057 # # DU_IN_IOCTL = 0x220067 # # Path: dbgtype.py # class DbgEngType(DbgEngTypeBase): # @property # def name(self): # return self.kdbg.get_type_name(self.module, self.typeid) # # @property # def is_array(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("[]") # # @property # def is_pointer(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("*") # # @property # def fields(self): # children = self.kdbg.get_childs_types(self.module, self.typeid) # return [DbgEngField(self.module, x, self.kdbg) for x in children.Types] # # @property # def fields_dict(self): # return {x.name: x for x in self.fields} # # @property # def number_elt(self): # return self.SymGetTypeInfo(TI_GET_COUNT) # # def __repr__(self): # return '<DbgEngType "{0}">'.format(self.name) # # def __call__(self, addr): # return get_mapped_type(self, addr) . Output only the next line.
windows.winproxy.DeviceIoControl(h, DU_OUT_IOCTL, buffer, len(buffer), 0, 0)
Using the snippet: <|code_start|> def _setup_name_imposture(self, dbgengmod, k32import): GetModuleFileNameW_addr_jump = dbgengmod.DllBase + self.GetModuleFileNameW_addr_jump_offset DummyGetModuleFileNameWIAT = DummyIATEntry.create(GetModuleFileNameW_addr_jump, "kernel32.dll", "GetModuleFileNameW") DummyGetModuleFileNameWIAT.set_hook(EmulateWinDBGName) # Driver upgrade stuff def _upgrade_driver(self): self.upgrader = driver_upgrade.DriverUpgrader32(self) self.upgrader.upgrade_driver() # upgraded driver API @require_upgraded_driver def kcall(self, target, *args): """Call target in kernel mode with given arguments""" target = self.resolve_symbol(target) args = [arg if arg is not None else 0 for arg in args] buffer = struct.pack("<" + "I" * (len(args) + 1), target, *args) h = self._get_kldbgdrv_handle() res = DWORD(0x44444444) windows.winproxy.DeviceIoControl(h, DU_KCALL_IOCTL, buffer, len(buffer), byref(res), ctypes.sizeof(res)) return res.value @require_upgraded_driver def do_in(self, port, size): """Perform IN instruction in kernel mode""" if size not in [1, 2, 4]: raise ValueError("Invalid IN size: {0}".format(size)) h = self._get_kldbgdrv_handle() buffer = struct.pack("<II", size, port) res = DWORD(0x44444444) <|code_end|> , determine the next line of code. You have imports: import os import struct import itertools import functools import ctypes import resource_emulation import driver_upgrade import windows import windows.hooks import windows.winproxy as winproxy from os.path import realpath, dirname from ctypes import byref, WINFUNCTYPE, HRESULT, WinError from simple_com import COMInterface, IDebugOutputCallbacksVtable from driver_upgrade import DU_MEMALLOC_IOCTL, DU_KCALL_IOCTL, DU_OUT_IOCTL, DU_IN_IOCTL from windows.generated_def.winstructs import * from dbgdef import * from dbgtype import DbgEngType and context (class names, function names, or code) available: # Path: simple_com.py # class COMInterface(ctypes.c_void_p): # _functions_ = { # "QueryInterface": ctypes.WINFUNCTYPE(HRESULT, ctypes.c_void_p, ctypes.c_void_p)(0, "QueryInterface"), # "AddRef": ctypes.WINFUNCTYPE(HRESULT)(1, "AddRef"), # "Release": ctypes.WINFUNCTYPE(HRESULT)(2, "Release") # } # # def __getattr__(self, name): # if name in self._functions_: # return functools.partial(self._functions_[name], self) # return super(COMInterface, self).__getattribute__(name) # # class IDebugOutputCallbacksVtable(ComVtable): # _funcs_ = ComVtable._funcs_ + [("Output", [ctypes.HRESULT, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_char_p], None)] # # Path: driver_upgrade.py # DU_MEMALLOC_IOCTL = 0x220027 # # DU_KCALL_IOCTL = 0x220037 # # DU_OUT_IOCTL = 0x220057 # # DU_IN_IOCTL = 0x220067 # # Path: dbgtype.py # class DbgEngType(DbgEngTypeBase): # @property # def name(self): # return self.kdbg.get_type_name(self.module, self.typeid) # # @property # def is_array(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("[]") # # @property # def is_pointer(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("*") # # @property # def fields(self): # children = self.kdbg.get_childs_types(self.module, self.typeid) # return [DbgEngField(self.module, x, self.kdbg) for x in children.Types] # # @property # def fields_dict(self): # return {x.name: x for x in self.fields} # # @property # def number_elt(self): # return self.SymGetTypeInfo(TI_GET_COUNT) # # def __repr__(self): # return '<DbgEngType "{0}">'.format(self.name) # # def __call__(self, addr): # return get_mapped_type(self, addr) . Output only the next line.
windows.winproxy.DeviceIoControl(h, DU_IN_IOCTL, buffer, len(buffer), byref(res), ctypes.sizeof(res))
Predict the next line after this snippet: <|code_start|> self.DebugDataSpaces.Release() del self.DebugDataSpaces def current_processor(self): """:returns: The number of the processor we are currently on -- :class:`int`""" return windows.winproxy.GetCurrentProcessorNumber() def set_current_processor(self, proc_nb): """Set the processor we want to be executed on :param proc_nb: the number of the processor :type proc_nb: int""" return windows.winproxy.SetThreadAffinityMask(dwThreadAffinityMask=(1 << proc_nb)) def number_processor(self): """:returns: The number of processors on the machine -- :class:`int`""" return self.read_dword("nt!KeNumberProcessors") def on_each_processor(self): """Iter execution on every processor :yield: current processor number""" for nb_proc in self.number_processor(): self.set_current_processor(nb_proc) yield nb_proc # type stuff @experimental def get_type(self, module, typeid): module, typeid = self.resolve_type(module, typeid) <|code_end|> using the current file's imports: import os import struct import itertools import functools import ctypes import resource_emulation import driver_upgrade import windows import windows.hooks import windows.winproxy as winproxy from os.path import realpath, dirname from ctypes import byref, WINFUNCTYPE, HRESULT, WinError from simple_com import COMInterface, IDebugOutputCallbacksVtable from driver_upgrade import DU_MEMALLOC_IOCTL, DU_KCALL_IOCTL, DU_OUT_IOCTL, DU_IN_IOCTL from windows.generated_def.winstructs import * from dbgdef import * from dbgtype import DbgEngType and any relevant context from other files: # Path: simple_com.py # class COMInterface(ctypes.c_void_p): # _functions_ = { # "QueryInterface": ctypes.WINFUNCTYPE(HRESULT, ctypes.c_void_p, ctypes.c_void_p)(0, "QueryInterface"), # "AddRef": ctypes.WINFUNCTYPE(HRESULT)(1, "AddRef"), # "Release": ctypes.WINFUNCTYPE(HRESULT)(2, "Release") # } # # def __getattr__(self, name): # if name in self._functions_: # return functools.partial(self._functions_[name], self) # return super(COMInterface, self).__getattribute__(name) # # class IDebugOutputCallbacksVtable(ComVtable): # _funcs_ = ComVtable._funcs_ + [("Output", [ctypes.HRESULT, ctypes.c_void_p, ctypes.c_ulong, ctypes.c_char_p], None)] # # Path: driver_upgrade.py # DU_MEMALLOC_IOCTL = 0x220027 # # DU_KCALL_IOCTL = 0x220037 # # DU_OUT_IOCTL = 0x220057 # # DU_IN_IOCTL = 0x220067 # # Path: dbgtype.py # class DbgEngType(DbgEngTypeBase): # @property # def name(self): # return self.kdbg.get_type_name(self.module, self.typeid) # # @property # def is_array(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("[]") # # @property # def is_pointer(self): # "Todo: Il doit bien y avoir un truc moins crade :D" # return self.name.endswith("*") # # @property # def fields(self): # children = self.kdbg.get_childs_types(self.module, self.typeid) # return [DbgEngField(self.module, x, self.kdbg) for x in children.Types] # # @property # def fields_dict(self): # return {x.name: x for x in self.fields} # # @property # def number_elt(self): # return self.SymGetTypeInfo(TI_GET_COUNT) # # def __repr__(self): # return '<DbgEngType "{0}">'.format(self.name) # # def __call__(self, addr): # return get_mapped_type(self, addr) . Output only the next line.
return DbgEngType(module, typeid, self)
Predict the next line for this snippet: <|code_start|> # COM IID for the interface we need IID_IDebugClient_raw = 0x27fe5639, 0x8407, 0x4f47, 0x83, 0x64, 0xee, 0x11, 0x8f, 0xb0, 0x8a, 0xc8 IID_IDebugDataSpaces_raw = 0x88f7dfab, 0x3ea7, 0x4c3a, 0xae, 0xfb, 0xc4, 0xe8, 0x10, 0x61, 0x73, 0xaa IID_IDebugDataSpaces2_raw = 0x7a5e852f, 0x96e9, 0x468f, 0xac, 0x1b, 0x0b, 0x3a, 0xdd, 0xc4, 0xa0, 0x49 IID_IDebugSymbols_raw = 0x8c31e98c, 0x983a, 0x48a5, 0x90, 0x16, 0x6f, 0xe5, 0xd6, 0x67, 0xa9, 0x50 IID_IDebugSymbols2_raw = 0x3a707211, 0xafdd, 0x4495, 0xad, 0x4f, 0x56, 0xfe, 0xcd, 0xf8, 0x16, 0x3f IID_IDebugSymbols3_raw = 0xf02fbecc, 0x50ac, 0x4f36, 0x9a, 0xd9, 0xc9, 0x75, 0xe8, 0xf3, 0x2f, 0xf8 IID_IDebugControl_raw = 0x5182e668, 0x105e, 0x416e, 0xad, 0x92, 0x24, 0xef, 0x80, 0x04, 0x24, 0xba <|code_end|> with the help of current file imports: from simple_com import get_IID_from_raw and context from other files: # Path: simple_com.py # def get_IID_from_raw(raw): # return "".join([struct.pack(i, j) for i, j in zip(IID_PACK, raw)]) , which may contain function names, class names, or code. Output only the next line.
IID_IDebugClient = get_IID_from_raw(IID_IDebugClient_raw)
Predict the next line after this snippet: <|code_start|>"""A demonstration of LKD that display all files opened by hooking nt!NtCreateFile""" if os.getcwd().endswith("example"): sys.path.append(os.path.realpath("..")) else: sys.path.append(os.path.realpath(".")) <|code_end|> using the current file's imports: import sys import time import ctypes import os import windows import windows.native_exec.simple_x86 as x86 import windows.native_exec.simple_x64 as x64 import pdb;pdb.set_trace() from dbginterface import LocalKernelDebugger and any relevant context from other files: # Path: dbginterface.py # def LocalKernelDebugger(quiet=True): # """| Check that all conditions to Local Kernel Debugging are met # | and return a LKD (subclass of :class:`LocalKernelDebuggerBase` # """ # if not windows.utils.check_debug(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging on kernel not in DEBUG mode") # if not windows.utils.check_is_elevated(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from non-Admin process") # windows.utils.enable_privilege(SE_DEBUG_NAME, True) # if windows.system.bitness == 64: # if windows.current_process.is_wow_64: # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from SysWow64 process (please launch from 64bits python)") # return LocalKernelDebugger64(quiet) # return LocalKernelDebugger32(quiet) . Output only the next line.
kdbg = LocalKernelDebugger()
Predict the next line after this snippet: <|code_start|>"""A simple demonstration of the type exploration in LDK""" if os.getcwd().endswith("example"): sys.path.append(os.path.realpath("..")) else: sys.path.append(os.path.realpath(".")) # This demo works on 32bits kernel only because # in _KPCR fieldnames are not the same (IDT / IdtBase, ...) if windows.system.bitness != 32: raise ValueError("Test for kernel32 only") # A lot of IDebugSymbols functions need a type identifier (TypeId) to # perform operation on said type # We tried our best to also accept the type name in this case and get # the type id automatically # (like the functions that take an address also accept a symbol) <|code_end|> using the current file's imports: import sys import os import windows from dbginterface import LocalKernelDebugger and any relevant context from other files: # Path: dbginterface.py # def LocalKernelDebugger(quiet=True): # """| Check that all conditions to Local Kernel Debugging are met # | and return a LKD (subclass of :class:`LocalKernelDebuggerBase` # """ # if not windows.utils.check_debug(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging on kernel not in DEBUG mode") # if not windows.utils.check_is_elevated(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from non-Admin process") # windows.utils.enable_privilege(SE_DEBUG_NAME, True) # if windows.system.bitness == 64: # if windows.current_process.is_wow_64: # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from SysWow64 process (please launch from 64bits python)") # return LocalKernelDebugger64(quiet) # return LocalKernelDebugger32(quiet) . Output only the next line.
kdbg = LocalKernelDebugger()
Next line prediction: <|code_start|>"""A simple demonstration of the output possibilities of the LDK""" if os.getcwd().endswith("example"): sys.path.append(os.path.realpath("..")) else: sys.path.append(os.path.realpath(".")) # A default LKD can be quiet or not # A quiet LKD will have no output # A noisy one will have the exact same output as windbg <|code_end|> . Use current file imports: (import sys import os from dbginterface import LocalKernelDebugger) and context including class names, function names, or small code snippets from other files: # Path: dbginterface.py # def LocalKernelDebugger(quiet=True): # """| Check that all conditions to Local Kernel Debugging are met # | and return a LKD (subclass of :class:`LocalKernelDebuggerBase` # """ # if not windows.utils.check_debug(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging on kernel not in DEBUG mode") # if not windows.utils.check_is_elevated(): # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from non-Admin process") # windows.utils.enable_privilege(SE_DEBUG_NAME, True) # if windows.system.bitness == 64: # if windows.current_process.is_wow_64: # raise LocalKernelDebuggerError("Cannot perform LocalKernelDebugging from SysWow64 process (please launch from 64bits python)") # return LocalKernelDebugger64(quiet) # return LocalKernelDebugger32(quiet) . Output only the next line.
kdbg = LocalKernelDebugger(quiet=True)