Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|> def serve_data(): SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer(('127.0.0.1', 18081), SimpleRequestHandler) http_server_thread = threading.Thread(target=server.handle_request) #http_server_thread.setDaemon(True) http_server_thread.start() return server @pytest.fixture(scope='module') def agent_instance(request): a = Agent_Connections('testnode', "127.0.0.1", 1340, None, run=False) def fin(): pass a.destroy() return a @pytest.fixture(scope='function') def serve_http(request): s = serve_data() def fin(): s.server_close() request.addfinalizer(fin) return s def test_agent_connections(agent_instance): <|code_end|> . Use current file imports: import pytest import unittest import sys import os import SocketServer import threading import time from vespa.node import Node from vespa.agent import Agent from vespa.agent_connections import Agent_Connections and context (classes, functions, or code) from other files: # Path: vespa/node.py # class Node(PThread): # # Overrides threading.Thread.run() # def run(self): # profiler = cProfile.Profile() # try: # return profiler.runcall(PThread.run, self) # finally: # profiler.dump_stats('myprofile-%s.profile' % (self.name)) # # Path: vespa/agent.py # class Agent(Node): # def __init__(self, name, host, port, master, run=True): # super(Agent, self,).__init__(name, host, port, master, run) # # Path: vespa/agent_connections.py # class Agent_Connections(Agent): # """An agent gathering network links through psutil python module or # system lsof command # # :return: The wrapper # :rtype: Node # """ # # def __init__(self, name, host, port, master, run=True): # # self.proc = None # super(Agent_Connections, self,).__init__(name, host, port, master, run) # self.backend = self.desc() # self.daemonname = "vlc" # # def launch(self): # """Return network connections to orchestrator layer every second using # either psutil or lsof # """ # import time # # while not self.quitting: # infos = self.__get_conns() # addresses = {} # intruders = [] # # for conn in infos: # if conn.remote_address: # addresses[ # conn.remote_address[0].replace( # ":", # "").replace( # "f", # "")] = 0 # # for conn in infos: # if conn.remote_address: # addresses[ # conn.remote_address[0].replace( # ":", # "").replace( # "f", # "")] += 1 # # for item in addresses: # intruders.append({'ip': item, 'value': addresses[item]}) # # self.sendAlert("ip_connections#%s" % intruders) # # debug_info("Intruders: %s" % intruders) # # time.sleep(1) # # def _get_conns(self): # """Gather psutil connections # # :return: List of network links # :rtype: list # """ # res = [] # for p in psutil.process_iter(): # try: # res += p.get_connections(kind='inet') # except: # continue # return res # # def _get_conns_lsof(self): # """Gather network connections with lsof # # :return: Dict of network links # :rtype: dict # """ # lines = os.popen('lsof -ni').readlines() # # from subprocess import Popen, PIPE # p1 = Popen(['lsof', '-ni'], stdout=PIPE) # p2 = Popen(["grep", "LISTEN"], stdin=p1.stdout, stdout=PIPE) # output = p2.communicate()[0] # cols = ("COMMAND PID USER FD TYPE DEVICE SIZE/OFF" # "NODE NAME").split() # res = {} # # for l in output.split("\n"): # d = dict(zip(cols, l.split())) # if not d: # continue # if d['COMMAND'] not in res: # res[d['COMMAND']] = [] # res[d['COMMAND']].append(d) # # return res . Output only the next line.
assert isinstance(agent_instance, Agent)
Given snippet: <|code_start|> DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT) sys.path.append(DOSSIER_PARENT) TEST_STRING = "hello" class SimpleRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(102400) # token receive self.request.send("'%s'EndOfTransmission" % TEST_STRING) time.sleep(0.1) # make sure it finishes receiving request before closing self.request.close() def serve_data(): SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer(('127.0.0.1', 18081), SimpleRequestHandler) http_server_thread = threading.Thread(target=server.handle_request) #http_server_thread.setDaemon(True) http_server_thread.start() return server @pytest.fixture(scope='module') def agent_instance(request): <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest import unittest import sys import os import SocketServer import threading import time from vespa.node import Node from vespa.agent import Agent from vespa.agent_connections import Agent_Connections and context: # Path: vespa/node.py # class Node(PThread): # # Overrides threading.Thread.run() # def run(self): # profiler = cProfile.Profile() # try: # return profiler.runcall(PThread.run, self) # finally: # profiler.dump_stats('myprofile-%s.profile' % (self.name)) # # Path: vespa/agent.py # class Agent(Node): # def __init__(self, name, host, port, master, run=True): # super(Agent, self,).__init__(name, host, port, master, run) # # Path: vespa/agent_connections.py # class Agent_Connections(Agent): # """An agent gathering network links through psutil python module or # system lsof command # # :return: The wrapper # :rtype: Node # """ # # def __init__(self, name, host, port, master, run=True): # # self.proc = None # super(Agent_Connections, self,).__init__(name, host, port, master, run) # self.backend = self.desc() # self.daemonname = "vlc" # # def launch(self): # """Return network connections to orchestrator layer every second using # either psutil or lsof # """ # import time # # while not self.quitting: # infos = self.__get_conns() # addresses = {} # intruders = [] # # for conn in infos: # if conn.remote_address: # addresses[ # conn.remote_address[0].replace( # ":", # "").replace( # "f", # "")] = 0 # # for conn in infos: # if conn.remote_address: # addresses[ # conn.remote_address[0].replace( # ":", # "").replace( # "f", # "")] += 1 # # for item in addresses: # intruders.append({'ip': item, 'value': addresses[item]}) # # self.sendAlert("ip_connections#%s" % intruders) # # debug_info("Intruders: %s" % intruders) # # time.sleep(1) # # def _get_conns(self): # """Gather psutil connections # # :return: List of network links # :rtype: list # """ # res = [] # for p in psutil.process_iter(): # try: # res += p.get_connections(kind='inet') # except: # continue # return res # # def _get_conns_lsof(self): # """Gather network connections with lsof # # :return: Dict of network links # :rtype: dict # """ # lines = os.popen('lsof -ni').readlines() # # from subprocess import Popen, PIPE # p1 = Popen(['lsof', '-ni'], stdout=PIPE) # p2 = Popen(["grep", "LISTEN"], stdin=p1.stdout, stdout=PIPE) # output = p2.communicate()[0] # cols = ("COMMAND PID USER FD TYPE DEVICE SIZE/OFF" # "NODE NAME").split() # res = {} # # for l in output.split("\n"): # d = dict(zip(cols, l.split())) # if not d: # continue # if d['COMMAND'] not in res: # res[d['COMMAND']] = [] # res[d['COMMAND']].append(d) # # return res which might include code, classes, or functions. Output only the next line.
a = Agent_Connections('testnode', "127.0.0.1", 1340, None, run=False)
Next line prediction: <|code_start|> DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT) sys.path.append(DOSSIER_PARENT) sys.path.append("%s/vespa" % DOSSIER_PARENT) class TestInitModel(unittest.TestCase): @pytest.fixture(autouse=True) def initdir(self, tmpdir): tmpdir.chdir() p = tmpdir.join("config.ini") conf = ('[%s]\nType= Machine\nInterfaces= 127.0.0.1\n\n' '[VO]\nLocation= %s\nMaster=\nPort=1337\n' % (socket.gethostname(), socket.gethostname())) p.write(conf) def test_init_model(self): <|code_end|> . Use current file imports: (import py import pytest import unittest import sys import os import socket import time import tempfile from vespa import * from vespa.model import Model) and context including class names, function names, or small code snippets from other files: # Path: vespa/model.py # class Model(Node): # def __init__(self): # super(Node, self,).__init__("model", localhost, 4100, None) # self.name = "model" # # config = ConfigObj("%s" % config_filename) # self.config = config # debug_init("Loaded configuration from %s" % config_filename) # # # Config file modifications # for obj in config: # if 'Type' not in obj: # config[obj]['Type'] = obj # # # Looking for VO (mandatory) # try: # vo_object = self.find_vo(config) # debug_init("Found VO") # except KeyError: # debug5("%s: Unable to find VO, exiting" % self.name) # raise # Exception("Model %s need a VO" % self.name) # # # Instanciating object # self.create_object_instance(config, vo_object, self) # # def find_vo(self, config): # """ # Return VO object from config file # # One and only one VO # """ # vo_object = None # # debug_init("%s: Finding VO" % self.name) # for obj in config: # if config[obj]['Type'] == 'VO': # debug_init("%s: Found VO" % self.name) # vo_object = obj # break # # return config[vo_object] # # def create_object_instance(self, config, obj, master): # debug_init("Creating object: %s" % obj['Type']) # obj_location = config[obj['Location']]['Interfaces'] # # # is_local = # # obj_location == config[config['VO']['Location']]['Interfaces'] # is_local = obj['Location'] == socket.gethostname() # # debug_init("Object is local: [%s == %s] %s" % # (obj['Location'], socket.gethostname(), is_local)) # # try: # obj_instance = eval(obj['Type'])(obj['Type'], # obj_location, int(obj['Port']), # master.desc(), is_local) # except NameError: # debug5("Agent into model.py ? Anyway, trying auto import!") # a = __import__(obj['Type'].lower(), fromlist=[obj['Type']]) # b = getattr(a, obj['Type']) # obj_instance = b(obj['Type'], obj_location, int(obj['Port']), # master.desc(), is_local) # # debug_init("Registering object") # """ # if master == self: # self.register(obj['Type'], obj_location, obj['Port']) # else: # """ # if is_local: # self.sendRemoteWake(master.desc(), "register|%s" % obj_instance) # # debug_init("Adding slaves") # # Adding slaves to object # for slave in config: # debug_init("-> %s [%s]" % (config[slave], obj['Type'])) # if 'Master' in config[slave]: # debug_init(" %s" % config[slave]['Master']) # if ('Master' in config[slave] # and config[slave]['Master'] == obj['Type']): # self.create_object_instance(config, config[slave], # obj_instance) # # def sendRemoteWake(self, remote, msg): # """ # Force sending content to a remote host. Loop until it is done # """ # while True: # # self.sendRemote(remote, msg) # # return # try: # debug_comm("Waiting for %s" % repr(remote)) # self.sendRemote(remote, msg) # return # except IOError: # time.sleep(2) # continue # # def findNode(self, name): # """ # Return a tuple if the node "name" is found, raise an Exception # otherwise. # TODO: Refactor (3x) # """ # for vo in self.slaves: # vo_name, vo_host, vo_port = vo # if vo_name == name: # return vo # vo_slaves_raw = self.sendRemote(vo, "list_slaves|") # try: # vo_slaves = eval(vo_slaves_raw) # except SyntaxError: # vo_slaves = [] # for ho in vo_slaves: # ho_name, ho_host, ho_port = ho # if ho_name == name: # return ho # ho_slaves_raw = self.sendRemote(ho, "list_slaves|") # try: # ho_slaves = eval(ho_slaves_raw) # except SyntaxError: # ho_slaves = [] # for agent in ho_slaves: # agent_name, agent_host, agent_port = agent # if agent_name == name: # return agent # raise Exception("Node %s not present in Model %s." % (name, self.name)) . Output only the next line.
m = Model()
Based on the snippet: <|code_start|> def serve_data(): SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer(('127.0.0.1', 18081), SimpleRequestHandler) http_server_thread = threading.Thread(target=server.handle_request) #http_server_thread.setDaemon(True) http_server_thread.start() return server @pytest.fixture(scope='module') def agent_instance(request): a = Agent_Bandwidth('testnode', "127.0.0.1", 1340, None, run=False) def fin(): pass a.destroy() return a @pytest.fixture(scope='function') def serve_http(request): s = serve_data() def fin(): s.server_close() request.addfinalizer(fin) return s def test_agent_bandwidth(agent_instance): <|code_end|> , predict the immediate next line with the help of imports: import pytest import unittest import sys import os import SocketServer import threading import time from vespa.node import Node from vespa.agent import Agent from vespa.agent_bandwidth import Agent_Bandwidth and context (classes, functions, sometimes code) from other files: # Path: vespa/node.py # class Node(PThread): # # Overrides threading.Thread.run() # def run(self): # profiler = cProfile.Profile() # try: # return profiler.runcall(PThread.run, self) # finally: # profiler.dump_stats('myprofile-%s.profile' % (self.name)) # # Path: vespa/agent.py # class Agent(Node): # def __init__(self, name, host, port, master, run=True): # super(Agent, self,).__init__(name, host, port, master, run) # # Path: vespa/agent_bandwidth.py # class Agent_Bandwidth(Agent): # """Provide a wrapper around Linux interfaces /proc files. The Agent can # extract information of specific interfaces, i.e. eth0 or lo. # # :return: The agent to grab informations # :rtype: Node # """ # # def __init__(self, name, host, port, master, run=True): # # self.proc = None # self.devfile = "/proc/net/dev" # self.iface = "eth0" # super(Agent_Bandwidth, self,).__init__(name, host, port, master, run) # self.backend = self.desc() # # def launch(self): # """Send _recv_bytes_ and _trans_bytes_ back to the master every # second # """ # # import time # # while not self.quitting: # infos = self._get_ifaces() # tm = time.time() # # r = infos[self.iface]['recv_bytes'] # # self.sendRemote(self.master, "alert|%s>recv_bytes#%s#%s" % # # (self.name, tm, r), needack=False) # self.sendAlert("recv_bytes#%s#%s" % (tm, r)) # # t = infos[self.iface]['trans_bytes'] # # self.sendRemote(self.master, "alert|%s>trans_bytes#%s#%s" % # # (self.name, tm, t), needack=False) # self.sendAlert("trans_bytes#%s#%s" % (tm, t)) # # time.sleep(1) # # def _get_ifaces(self): # """Function parsing the /proc/net/dev file and feeding a table # # :return: The table mapping the device file # :rtype: list # """ # # lines = open(self.devfile, "r").readlines() # # columnLine = lines[1] # _, receiveCols, transmitCols = columnLine.split("|") # receiveCols = map(lambda a: "recv_" + a, receiveCols.split()) # transmitCols = map(lambda a: "trans_" + a, transmitCols.split()) # # cols = receiveCols + transmitCols # # faces = {} # for line in lines[2:]: # if line.find(":") < 0: # continue # face, data = line.split(":") # faceData = dict(zip(cols, data.split())) # faces[face.strip()] = faceData # # return faces # # def get_mac(self): # """Grab the mac address of the class defined _self.iface_ # # :return: The string containing the mac address, colon separated # :rtype: str # """ # # return self._get_mac(self.iface) # # def _get_mac(self, ifname): # """Send an ioctl to recover the mac address of a specific interface # # :return: The string containing the mac address, colon separated # :rtype: str # """ # # s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # info = fcntl.ioctl( # s.fileno(), # 0x8927, # struct.pack( # '256s', # ifname[ # :15])) # return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1] . Output only the next line.
assert isinstance(agent_instance, Agent)
Next line prediction: <|code_start|> DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT) sys.path.append(DOSSIER_PARENT) TEST_STRING = "hello" class SimpleRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(102400) # token receive self.request.send("'%s'EndOfTransmission" % TEST_STRING) time.sleep(0.1) # make sure it finishes receiving request before closing self.request.close() def serve_data(): SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer(('127.0.0.1', 18081), SimpleRequestHandler) http_server_thread = threading.Thread(target=server.handle_request) #http_server_thread.setDaemon(True) http_server_thread.start() return server @pytest.fixture(scope='module') def agent_instance(request): <|code_end|> . Use current file imports: (import pytest import unittest import sys import os import SocketServer import threading import time from vespa.node import Node from vespa.agent import Agent from vespa.agent_bandwidth import Agent_Bandwidth) and context including class names, function names, or small code snippets from other files: # Path: vespa/node.py # class Node(PThread): # # Overrides threading.Thread.run() # def run(self): # profiler = cProfile.Profile() # try: # return profiler.runcall(PThread.run, self) # finally: # profiler.dump_stats('myprofile-%s.profile' % (self.name)) # # Path: vespa/agent.py # class Agent(Node): # def __init__(self, name, host, port, master, run=True): # super(Agent, self,).__init__(name, host, port, master, run) # # Path: vespa/agent_bandwidth.py # class Agent_Bandwidth(Agent): # """Provide a wrapper around Linux interfaces /proc files. The Agent can # extract information of specific interfaces, i.e. eth0 or lo. # # :return: The agent to grab informations # :rtype: Node # """ # # def __init__(self, name, host, port, master, run=True): # # self.proc = None # self.devfile = "/proc/net/dev" # self.iface = "eth0" # super(Agent_Bandwidth, self,).__init__(name, host, port, master, run) # self.backend = self.desc() # # def launch(self): # """Send _recv_bytes_ and _trans_bytes_ back to the master every # second # """ # # import time # # while not self.quitting: # infos = self._get_ifaces() # tm = time.time() # # r = infos[self.iface]['recv_bytes'] # # self.sendRemote(self.master, "alert|%s>recv_bytes#%s#%s" % # # (self.name, tm, r), needack=False) # self.sendAlert("recv_bytes#%s#%s" % (tm, r)) # # t = infos[self.iface]['trans_bytes'] # # self.sendRemote(self.master, "alert|%s>trans_bytes#%s#%s" % # # (self.name, tm, t), needack=False) # self.sendAlert("trans_bytes#%s#%s" % (tm, t)) # # time.sleep(1) # # def _get_ifaces(self): # """Function parsing the /proc/net/dev file and feeding a table # # :return: The table mapping the device file # :rtype: list # """ # # lines = open(self.devfile, "r").readlines() # # columnLine = lines[1] # _, receiveCols, transmitCols = columnLine.split("|") # receiveCols = map(lambda a: "recv_" + a, receiveCols.split()) # transmitCols = map(lambda a: "trans_" + a, transmitCols.split()) # # cols = receiveCols + transmitCols # # faces = {} # for line in lines[2:]: # if line.find(":") < 0: # continue # face, data = line.split(":") # faceData = dict(zip(cols, data.split())) # faces[face.strip()] = faceData # # return faces # # def get_mac(self): # """Grab the mac address of the class defined _self.iface_ # # :return: The string containing the mac address, colon separated # :rtype: str # """ # # return self._get_mac(self.iface) # # def _get_mac(self, ifname): # """Send an ioctl to recover the mac address of a specific interface # # :return: The string containing the mac address, colon separated # :rtype: str # """ # # s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # info = fcntl.ioctl( # s.fileno(), # 0x8927, # struct.pack( # '256s', # ifname[ # :15])) # return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1] . Output only the next line.
a = Agent_Bandwidth('testnode', "127.0.0.1", 1340, None, run=False)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # # Module name: agent_av.py # Version: 1.0 # Created: 29/04/2014 by Aurélien Wailly <aurelien.wailly@orange.com> # # Copyright (C) 2010-2014 Orange # # This file is part of VESPA. # # VESPA is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation version 2.1. # # VESPA 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with VESPA. If not, see <http://www.gnu.org/licenses/>. """ Agent representation """ EOT_FLAG = "EndOfTransmission" LIST_ITEM_SEPARATOR = ':' LIST_SEPARATOR = '\r' <|code_end|> . Write the next line using the current file imports: import socket from .log_pipe import debug1 from .agent import Agent and context from other files: # Path: vespa/log_pipe.py # def debug1(str): # print repr(str) # pass # # Path: vespa/agent.py # class Agent(Node): # def __init__(self, name, host, port, master, run=True): # super(Agent, self,).__init__(name, host, port, master, run) , which may include functions, classes, or code. Output only the next line.
class Agent_AV(Agent):
Continue the code snippet: <|code_start|>def agent_instance(): vm = ("test_vm", "127.0.0.1", 18081) a = Agent_AV('testnode', "127.0.0.1", 1348, None, vm) return a @pytest.fixture(scope='function') def serve_http(request): s = serve_data(SimpleRequestHandler) def fin(): s.server_close() request.addfinalizer(fin) return s @pytest.fixture(scope='function') def serve_http_no_list(request): s = serve_data(NoListRequestHandler) def fin(): s.server_close() request.addfinalizer(fin) return s @pytest.fixture(scope='function') def serve_http_no_colon(request): s = serve_data(NoColonRequestHandler) def fin(): s.server_close() request.addfinalizer(fin) return s def test_agent_av_instance(agent_instance): <|code_end|> . Use current file imports: import pytest import sys import os import SocketServer import threading import time from vespa.node import Node from vespa.agent import Agent from vespa.agent_av import Agent_AV and context (classes, functions, or code) from other files: # Path: vespa/node.py # class Node(PThread): # # Overrides threading.Thread.run() # def run(self): # profiler = cProfile.Profile() # try: # return profiler.runcall(PThread.run, self) # finally: # profiler.dump_stats('myprofile-%s.profile' % (self.name)) # # Path: vespa/agent.py # class Agent(Node): # def __init__(self, name, host, port, master, run=True): # super(Agent, self,).__init__(name, host, port, master, run) # # Path: vespa/agent_av.py # class Agent_AV(Agent): # """Create an Agent able to communicate with the ClamAV backend (need a # driver). # # :return: The Agent instance to offer the ClamAV support # :rtype: Node # """ # # def __init__(self, name, host, port, master, vm): # super(Agent_AV, self).__init__(name, host, port, master, run=False) # self.have_backend = True # self.is_backend_reachable = True # self.backend = vm # # def send(self, msg): # """Overload the internal send to capture and send messages to the # backend # # :param str msg: The massage to process and to send # :return: The backend response # :rtype: str # """ # command = msg.split("|")[0] # # Preprocessing # if command == 'import_list': # predefined_list = [("lala", "lolo")] # for item, status in predefined_list: # msg += item + "#" # elif command == 'register_handler': # msg += '%s#%s#' % (self.host, self.port) # # Normal socket connection # if self.is_backend_reachable: # data = super(Agent_AV, self).send(msg) # # Hypervisor sysrq # else: # if command == 'clean_image': # # conn_local = libvirt.open("qemu+ssh://" + self.agent_hy.host # # + "/system") # # dom = self.agent_hy.__get_dom_name(self.vm, conn_local) # # dom.sendKey(8, 10, [ 0x12, 0x42 ], 2, 0) # args = (8, 10, [0x12, 0x42], 2, 0) # data = self.sendRemote( # self.agent_hy, "send_key|%s#%s" % # (self.backend, args)) # else: # data = super(Agent_AV, self).send(msg) # # data = [ "Unsupported sysrq method" ] # # self.sendRemote(master, data) # return data # # def dump_analyzed_file_list(self): # """Gather list of files analyzed bi the ClamAV antivirus # # :return: The list of analyzed files # :rtype: list # """ # agent_vm = self # self.findAgent('agent_av') # raw_msg = agent_vm.send("dump_list|") # command = raw_msg.split('|')[0] # title_list = raw_msg.split('|')[1] # file_list_raw = raw_msg.split('|')[2] # file_list = [] # file_list.append( # (title_list.split(LIST_ITEM_SEPARATOR)[0], # title_list.split(LIST_ITEM_SEPARATOR)[1])) # # It can be an error # if LIST_SEPARATOR not in file_list_raw: # return [file_list_raw] # # Otherwise, it can be a list # for scan_result in file_list_raw.split(LIST_SEPARATOR): # # It can be an error, last line is messy # if ':' not in scan_result: # continue # name = ":".join( # scan_result.split(LIST_ITEM_SEPARATOR)[ # 0:2]).strip() # status = scan_result.split(LIST_ITEM_SEPARATOR)[2].strip() # file_list.append((name, status)) # return file_list # # def isolate_warning(self, vm): # """Set up the agent for interactions with the hypervisor # # :param str vm: The tuple (name, host, port) describing the backend # """ # self.is_backend_reachable = False # self.agent_hy = eval(vm) # # def connect_warning(self): # """Set up the agent for interactions with the VM # """ # self.is_backend_reachable = True # self.agent_hy = False . Output only the next line.
assert isinstance(agent_instance, Agent)
Here is a snippet: <|code_start|> self.request.close() class NoListRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(102400) # token receive self.request.send("'%s'EndOfTransmission" % TEST_STRING.split("\\")[0]) time.sleep(0.1) # make sure it finishes receiving request before closing self.request.close() class NoColonRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(102400) # token receive sstr = TEST_STRING.split("|") new_string = sstr[0:2] + [sstr[2].replace(":", "")] new_string = "|".join(new_string) self.request.send("'%s'EndOfTransmission" % new_string) time.sleep(0.1) # make sure it finishes receiving request before closing self.request.close() def serve_data(request_handler): SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer(('127.0.0.1', 18081), request_handler) http_server_thread = threading.Thread(target=server.handle_request) #http_server_thread.setDaemon(True) http_server_thread.start() return server @pytest.fixture(scope='module') def agent_instance(): vm = ("test_vm", "127.0.0.1", 18081) <|code_end|> . Write the next line using the current file imports: import pytest import sys import os import SocketServer import threading import time from vespa.node import Node from vespa.agent import Agent from vespa.agent_av import Agent_AV and context from other files: # Path: vespa/node.py # class Node(PThread): # # Overrides threading.Thread.run() # def run(self): # profiler = cProfile.Profile() # try: # return profiler.runcall(PThread.run, self) # finally: # profiler.dump_stats('myprofile-%s.profile' % (self.name)) # # Path: vespa/agent.py # class Agent(Node): # def __init__(self, name, host, port, master, run=True): # super(Agent, self,).__init__(name, host, port, master, run) # # Path: vespa/agent_av.py # class Agent_AV(Agent): # """Create an Agent able to communicate with the ClamAV backend (need a # driver). # # :return: The Agent instance to offer the ClamAV support # :rtype: Node # """ # # def __init__(self, name, host, port, master, vm): # super(Agent_AV, self).__init__(name, host, port, master, run=False) # self.have_backend = True # self.is_backend_reachable = True # self.backend = vm # # def send(self, msg): # """Overload the internal send to capture and send messages to the # backend # # :param str msg: The massage to process and to send # :return: The backend response # :rtype: str # """ # command = msg.split("|")[0] # # Preprocessing # if command == 'import_list': # predefined_list = [("lala", "lolo")] # for item, status in predefined_list: # msg += item + "#" # elif command == 'register_handler': # msg += '%s#%s#' % (self.host, self.port) # # Normal socket connection # if self.is_backend_reachable: # data = super(Agent_AV, self).send(msg) # # Hypervisor sysrq # else: # if command == 'clean_image': # # conn_local = libvirt.open("qemu+ssh://" + self.agent_hy.host # # + "/system") # # dom = self.agent_hy.__get_dom_name(self.vm, conn_local) # # dom.sendKey(8, 10, [ 0x12, 0x42 ], 2, 0) # args = (8, 10, [0x12, 0x42], 2, 0) # data = self.sendRemote( # self.agent_hy, "send_key|%s#%s" % # (self.backend, args)) # else: # data = super(Agent_AV, self).send(msg) # # data = [ "Unsupported sysrq method" ] # # self.sendRemote(master, data) # return data # # def dump_analyzed_file_list(self): # """Gather list of files analyzed bi the ClamAV antivirus # # :return: The list of analyzed files # :rtype: list # """ # agent_vm = self # self.findAgent('agent_av') # raw_msg = agent_vm.send("dump_list|") # command = raw_msg.split('|')[0] # title_list = raw_msg.split('|')[1] # file_list_raw = raw_msg.split('|')[2] # file_list = [] # file_list.append( # (title_list.split(LIST_ITEM_SEPARATOR)[0], # title_list.split(LIST_ITEM_SEPARATOR)[1])) # # It can be an error # if LIST_SEPARATOR not in file_list_raw: # return [file_list_raw] # # Otherwise, it can be a list # for scan_result in file_list_raw.split(LIST_SEPARATOR): # # It can be an error, last line is messy # if ':' not in scan_result: # continue # name = ":".join( # scan_result.split(LIST_ITEM_SEPARATOR)[ # 0:2]).strip() # status = scan_result.split(LIST_ITEM_SEPARATOR)[2].strip() # file_list.append((name, status)) # return file_list # # def isolate_warning(self, vm): # """Set up the agent for interactions with the hypervisor # # :param str vm: The tuple (name, host, port) describing the backend # """ # self.is_backend_reachable = False # self.agent_hy = eval(vm) # # def connect_warning(self): # """Set up the agent for interactions with the VM # """ # self.is_backend_reachable = True # self.agent_hy = False , which may include functions, classes, or code. Output only the next line.
a = Agent_AV('testnode', "127.0.0.1", 1348, None, vm)
Given the following code snippet before the placeholder: <|code_start|> DOSSIER_COURANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURANT) sys.path.append(DOSSIER_PARENT) TEST_ARG1 = 'aloha:kikoo:lala' TEST_STRING = 'hello|ola:alo|%s\\r%s' % (TEST_ARG1, TEST_ARG1) HOST = '127.0.0.1' PORT = 8080 class Model_light(object): def __init__(self): self.slaves = [("voname", "vo_host", 1234)] self.config = "configgoeshere" def sendRemote(self, dst, msg): if msg == "list_slaves|": fstr = repr(self.slaves) else: fstr = repr([ "%s :: %s" % (dst, msg) ]) return fstr def destroy(self): pass @pytest.fixture(scope='module') def controller_instance(): <|code_end|> , predict the next line using imports from the current file: import pytest import sys import os import socket import SocketServer import threading import time import requests from vespa.controller import Controller and context including class names, function names, and sometimes code from other files: # Path: vespa/controller.py # class Controller(object): # def __init__(self, model, view, testmode=False): # self.model = model # self.view = view # self.testmode = testmode # # def handler(self, signum, false): # if signum == 2: # debug_init("Controller received shutting down") # self._shutdown() # # def _shutdown(self): # self.model.destroy() # # if not self.testmode: # exit(0) # # self.server.stop() # # def start(self): # debug5("Started Controller") # # if not self.testmode: # signal.signal(signal.SIGINT, self.handler) # # self.server = HttpServer("test server", "0.0.0.0", 8080, # server_handler, self) # self.server.start() . Output only the next line.
s = Controller(Model_light(), None, testmode=True)
Given the code snippet: <|code_start|> DOSSIER_COURRANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURRANT) sys.path.append(DOSSIER_PARENT) sys.path.append("%s/vespa" % DOSSIER_PARENT) class TestInit(unittest.TestCase): @pytest.fixture(autouse=True) def initdir(self, tmpdir): tmpdir.chdir() p = tmpdir.join("config.ini") conf = ('[%s]\nType= Machine\nInterfaces= 127.0.0.1\n\n' '[VO]\nLocation= %s\nMaster=\nPort=1338\n' % (socket.gethostname(), socket.gethostname())) p.write(conf) def test_init_view(self): <|code_end|> , generate the next line using the imports in this file: import unittest import pytest import sys import os import socket import time from vespa import * from vespa.model import Model from vespa.view import View and context (functions, classes, or occasionally code) from other files: # Path: vespa/model.py # class Model(Node): # def __init__(self): # super(Node, self,).__init__("model", localhost, 4100, None) # self.name = "model" # # config = ConfigObj("%s" % config_filename) # self.config = config # debug_init("Loaded configuration from %s" % config_filename) # # # Config file modifications # for obj in config: # if 'Type' not in obj: # config[obj]['Type'] = obj # # # Looking for VO (mandatory) # try: # vo_object = self.find_vo(config) # debug_init("Found VO") # except KeyError: # debug5("%s: Unable to find VO, exiting" % self.name) # raise # Exception("Model %s need a VO" % self.name) # # # Instanciating object # self.create_object_instance(config, vo_object, self) # # def find_vo(self, config): # """ # Return VO object from config file # # One and only one VO # """ # vo_object = None # # debug_init("%s: Finding VO" % self.name) # for obj in config: # if config[obj]['Type'] == 'VO': # debug_init("%s: Found VO" % self.name) # vo_object = obj # break # # return config[vo_object] # # def create_object_instance(self, config, obj, master): # debug_init("Creating object: %s" % obj['Type']) # obj_location = config[obj['Location']]['Interfaces'] # # # is_local = # # obj_location == config[config['VO']['Location']]['Interfaces'] # is_local = obj['Location'] == socket.gethostname() # # debug_init("Object is local: [%s == %s] %s" % # (obj['Location'], socket.gethostname(), is_local)) # # try: # obj_instance = eval(obj['Type'])(obj['Type'], # obj_location, int(obj['Port']), # master.desc(), is_local) # except NameError: # debug5("Agent into model.py ? Anyway, trying auto import!") # a = __import__(obj['Type'].lower(), fromlist=[obj['Type']]) # b = getattr(a, obj['Type']) # obj_instance = b(obj['Type'], obj_location, int(obj['Port']), # master.desc(), is_local) # # debug_init("Registering object") # """ # if master == self: # self.register(obj['Type'], obj_location, obj['Port']) # else: # """ # if is_local: # self.sendRemoteWake(master.desc(), "register|%s" % obj_instance) # # debug_init("Adding slaves") # # Adding slaves to object # for slave in config: # debug_init("-> %s [%s]" % (config[slave], obj['Type'])) # if 'Master' in config[slave]: # debug_init(" %s" % config[slave]['Master']) # if ('Master' in config[slave] # and config[slave]['Master'] == obj['Type']): # self.create_object_instance(config, config[slave], # obj_instance) # # def sendRemoteWake(self, remote, msg): # """ # Force sending content to a remote host. Loop until it is done # """ # while True: # # self.sendRemote(remote, msg) # # return # try: # debug_comm("Waiting for %s" % repr(remote)) # self.sendRemote(remote, msg) # return # except IOError: # time.sleep(2) # continue # # def findNode(self, name): # """ # Return a tuple if the node "name" is found, raise an Exception # otherwise. # TODO: Refactor (3x) # """ # for vo in self.slaves: # vo_name, vo_host, vo_port = vo # if vo_name == name: # return vo # vo_slaves_raw = self.sendRemote(vo, "list_slaves|") # try: # vo_slaves = eval(vo_slaves_raw) # except SyntaxError: # vo_slaves = [] # for ho in vo_slaves: # ho_name, ho_host, ho_port = ho # if ho_name == name: # return ho # ho_slaves_raw = self.sendRemote(ho, "list_slaves|") # try: # ho_slaves = eval(ho_slaves_raw) # except SyntaxError: # ho_slaves = [] # for agent in ho_slaves: # agent_name, agent_host, agent_port = agent # if agent_name == name: # return agent # raise Exception("Node %s not present in Model %s." % (name, self.name)) # # Path: vespa/view.py # class View(object): # def __init__(self, model): # self.model = model . Output only the next line.
m = Model()
Given the code snippet: <|code_start|> DOSSIER_COURRANT = os.path.dirname(os.path.abspath(__file__)) DOSSIER_PARENT = os.path.dirname(DOSSIER_COURRANT) sys.path.append(DOSSIER_PARENT) sys.path.append("%s/vespa" % DOSSIER_PARENT) class TestInit(unittest.TestCase): @pytest.fixture(autouse=True) def initdir(self, tmpdir): tmpdir.chdir() p = tmpdir.join("config.ini") conf = ('[%s]\nType= Machine\nInterfaces= 127.0.0.1\n\n' '[VO]\nLocation= %s\nMaster=\nPort=1338\n' % (socket.gethostname(), socket.gethostname())) p.write(conf) def test_init_view(self): m = Model() <|code_end|> , generate the next line using the imports in this file: import unittest import pytest import sys import os import socket import time from vespa import * from vespa.model import Model from vespa.view import View and context (functions, classes, or occasionally code) from other files: # Path: vespa/model.py # class Model(Node): # def __init__(self): # super(Node, self,).__init__("model", localhost, 4100, None) # self.name = "model" # # config = ConfigObj("%s" % config_filename) # self.config = config # debug_init("Loaded configuration from %s" % config_filename) # # # Config file modifications # for obj in config: # if 'Type' not in obj: # config[obj]['Type'] = obj # # # Looking for VO (mandatory) # try: # vo_object = self.find_vo(config) # debug_init("Found VO") # except KeyError: # debug5("%s: Unable to find VO, exiting" % self.name) # raise # Exception("Model %s need a VO" % self.name) # # # Instanciating object # self.create_object_instance(config, vo_object, self) # # def find_vo(self, config): # """ # Return VO object from config file # # One and only one VO # """ # vo_object = None # # debug_init("%s: Finding VO" % self.name) # for obj in config: # if config[obj]['Type'] == 'VO': # debug_init("%s: Found VO" % self.name) # vo_object = obj # break # # return config[vo_object] # # def create_object_instance(self, config, obj, master): # debug_init("Creating object: %s" % obj['Type']) # obj_location = config[obj['Location']]['Interfaces'] # # # is_local = # # obj_location == config[config['VO']['Location']]['Interfaces'] # is_local = obj['Location'] == socket.gethostname() # # debug_init("Object is local: [%s == %s] %s" % # (obj['Location'], socket.gethostname(), is_local)) # # try: # obj_instance = eval(obj['Type'])(obj['Type'], # obj_location, int(obj['Port']), # master.desc(), is_local) # except NameError: # debug5("Agent into model.py ? Anyway, trying auto import!") # a = __import__(obj['Type'].lower(), fromlist=[obj['Type']]) # b = getattr(a, obj['Type']) # obj_instance = b(obj['Type'], obj_location, int(obj['Port']), # master.desc(), is_local) # # debug_init("Registering object") # """ # if master == self: # self.register(obj['Type'], obj_location, obj['Port']) # else: # """ # if is_local: # self.sendRemoteWake(master.desc(), "register|%s" % obj_instance) # # debug_init("Adding slaves") # # Adding slaves to object # for slave in config: # debug_init("-> %s [%s]" % (config[slave], obj['Type'])) # if 'Master' in config[slave]: # debug_init(" %s" % config[slave]['Master']) # if ('Master' in config[slave] # and config[slave]['Master'] == obj['Type']): # self.create_object_instance(config, config[slave], # obj_instance) # # def sendRemoteWake(self, remote, msg): # """ # Force sending content to a remote host. Loop until it is done # """ # while True: # # self.sendRemote(remote, msg) # # return # try: # debug_comm("Waiting for %s" % repr(remote)) # self.sendRemote(remote, msg) # return # except IOError: # time.sleep(2) # continue # # def findNode(self, name): # """ # Return a tuple if the node "name" is found, raise an Exception # otherwise. # TODO: Refactor (3x) # """ # for vo in self.slaves: # vo_name, vo_host, vo_port = vo # if vo_name == name: # return vo # vo_slaves_raw = self.sendRemote(vo, "list_slaves|") # try: # vo_slaves = eval(vo_slaves_raw) # except SyntaxError: # vo_slaves = [] # for ho in vo_slaves: # ho_name, ho_host, ho_port = ho # if ho_name == name: # return ho # ho_slaves_raw = self.sendRemote(ho, "list_slaves|") # try: # ho_slaves = eval(ho_slaves_raw) # except SyntaxError: # ho_slaves = [] # for agent in ho_slaves: # agent_name, agent_host, agent_port = agent # if agent_name == name: # return agent # raise Exception("Node %s not present in Model %s." % (name, self.name)) # # Path: vespa/view.py # class View(object): # def __init__(self, model): # self.model = model . Output only the next line.
v = View(m)
Using the snippet: <|code_start|> pass def file_name(name, suffix=JSON_FILE_SUFFIX): """ Return file name based on name and suffix. """ return name + '.' + suffix class Manifest(FileJSON): """ Manifest file. """ def __init__(self, directory): super(Manifest, self).__init__(os.path.abspath(directory), file_name(MANIFEST_FILE_NAME)) def check(self): """ Check manifest. """ manifest = self.read() result = True errors = [] names = [file_name(CATEGORIES_FILE_NAME)] for name in names: if not name in manifest: <|code_end|> , determine the next line of code. You have imports: import hashlib import os import shutil from .exceptions import DBLayoutError, DBStructureError, FileJSONError, IntegrityError from .fileutils import FileJSON, hash_file from .file_bson.file_bson import FileBSON and context (class names, function names, or code) available: # Path: g_sorcery/exceptions.py # class DBLayoutError(GSorceryError): # pass # # class DBStructureError(DBError): # pass # # class FileJSONError(GSorceryError): # pass # # class IntegrityError(DBError): # pass # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # def hash_file(name, hasher, blocksize=65536): # """ # Get a file hash. # # Args: # name: file name. # hasher: Hasher. # blocksize: Blocksize. # # Returns: # Hash value. # """ # with open(name, 'rb') as f: # buf = f.read(blocksize) # while len(buf) > 0: # hasher.update(buf) # buf = f.read(blocksize) # return hasher.hexdigest() . Output only the next line.
raise DBLayoutError('Bad manifest: no ' + name + ' entry')
Based on the snippet: <|code_start|> for name, value in manifest.items(): if hash_file(os.path.join(self.directory, name), hashlib.md5()) != \ value: errors.append(name) if errors: result = False return (result, errors) def digest(self, mandatory_files): """ Generate manifest. """ if not file_name(CATEGORIES_FILE_NAME) in mandatory_files: raise DBLayoutError('Categories file: ' + file_name(CATEGORIES_FILE_NAME) \ + ' is not in the list of mandatory files') categories = Categories(self.directory) categories = categories.read() manifest = {} for name in mandatory_files: manifest[name] = hash_file(os.path.join(self.directory, name), hashlib.md5()) for category in categories: category_path = os.path.join(self.directory, category) if not os.path.isdir(category_path): <|code_end|> , predict the immediate next line with the help of imports: import hashlib import os import shutil from .exceptions import DBLayoutError, DBStructureError, FileJSONError, IntegrityError from .fileutils import FileJSON, hash_file from .file_bson.file_bson import FileBSON and context (classes, functions, sometimes code) from other files: # Path: g_sorcery/exceptions.py # class DBLayoutError(GSorceryError): # pass # # class DBStructureError(DBError): # pass # # class FileJSONError(GSorceryError): # pass # # class IntegrityError(DBError): # pass # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # def hash_file(name, hasher, blocksize=65536): # """ # Get a file hash. # # Args: # name: file name. # hasher: Hasher. # blocksize: Blocksize. # # Returns: # Hash value. # """ # with open(name, 'rb') as f: # buf = f.read(blocksize) # while len(buf) > 0: # hasher.update(buf) # buf = f.read(blocksize) # return hasher.hexdigest() . Output only the next line.
raise DBStructureError('Empty category: ' + category)
Using the snippet: <|code_start|> hash_file(os.path.join(root, f), hashlib.md5()) self.write(manifest) class Metadata(FileJSON): """ Metadata file. """ def __init__(self, directory): super(Metadata, self).__init__(os.path.abspath(directory), file_name(METADATA_FILE_NAME), ['db_version', 'layout_version', 'category_format']) def read(self): """ Read metadata file. If file doesn't exist, we have a legacy DB with DB layout v. 0. Fill metadata appropriately. """ if not os.path.exists(self.directory): os.makedirs(self.directory) content = {} if not os.path.isfile(self.path): content = {'db_version': 0, 'layout_version': 0, 'category_format': JSON_FILE_SUFFIX} else: content = self.read_content() for key in self.mandatories: if not key in content: <|code_end|> , determine the next line of code. You have imports: import hashlib import os import shutil from .exceptions import DBLayoutError, DBStructureError, FileJSONError, IntegrityError from .fileutils import FileJSON, hash_file from .file_bson.file_bson import FileBSON and context (class names, function names, or code) available: # Path: g_sorcery/exceptions.py # class DBLayoutError(GSorceryError): # pass # # class DBStructureError(DBError): # pass # # class FileJSONError(GSorceryError): # pass # # class IntegrityError(DBError): # pass # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # def hash_file(name, hasher, blocksize=65536): # """ # Get a file hash. # # Args: # name: file name. # hasher: Hasher. # blocksize: Blocksize. # # Returns: # Hash value. # """ # with open(name, 'rb') as f: # buf = f.read(blocksize) # while len(buf) > 0: # hasher.update(buf) # buf = f.read(blocksize) # return hasher.hexdigest() . Output only the next line.
raise FileJSONError('lack of mandatory key: ' + key)
Predict the next line for this snippet: <|code_start|> categories.json: information about categories category1 packages.json: information about available packages category2 ... For DB layout v. 1: db dir manifest.json: database manifest categories.json: information about categories metadata.json: DB metadata category1 packages.[b|j]son: information about available packages category2 ... Packages file can be in json or bson formats. """ def __init__(self, directory): self.directory = os.path.abspath(directory) self.manifest = Manifest(self.directory) def check_manifest(self): """ Check manifest. """ sane, errors = self.manifest.check() if not sane: <|code_end|> with the help of current file imports: import hashlib import os import shutil from .exceptions import DBLayoutError, DBStructureError, FileJSONError, IntegrityError from .fileutils import FileJSON, hash_file from .file_bson.file_bson import FileBSON and context from other files: # Path: g_sorcery/exceptions.py # class DBLayoutError(GSorceryError): # pass # # class DBStructureError(DBError): # pass # # class FileJSONError(GSorceryError): # pass # # class IntegrityError(DBError): # pass # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # def hash_file(name, hasher, blocksize=65536): # """ # Get a file hash. # # Args: # name: file name. # hasher: Hasher. # blocksize: Blocksize. # # Returns: # Hash value. # """ # with open(name, 'rb') as f: # buf = f.read(blocksize) # while len(buf) > 0: # hasher.update(buf) # buf = f.read(blocksize) # return hasher.hexdigest() , which may contain function names, class names, or code. Output only the next line.
raise IntegrityError('Manifest error: ' + str(errors))
Using the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ db_layout.py ~~~~~~~~~~~~ package database file layout :copyright: (c) 2013-2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ CATEGORIES_FILE_NAME = 'categories' MANIFEST_FILE_NAME = 'manifest' METADATA_FILE_NAME = 'metadata' PACKAGES_FILE_NAME = 'packages' JSON_FILE_SUFFIX = 'json' BSON_FILE_SUFFIX = 'bson' SUPPORTED_DB_LAYOUTS=[0, 1] <|code_end|> , determine the next line of code. You have imports: import hashlib import os import shutil from .exceptions import DBLayoutError, DBStructureError, FileJSONError, IntegrityError from .fileutils import FileJSON, hash_file from .file_bson.file_bson import FileBSON and context (class names, function names, or code) available: # Path: g_sorcery/exceptions.py # class DBLayoutError(GSorceryError): # pass # # class DBStructureError(DBError): # pass # # class FileJSONError(GSorceryError): # pass # # class IntegrityError(DBError): # pass # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # def hash_file(name, hasher, blocksize=65536): # """ # Get a file hash. # # Args: # name: file name. # hasher: Hasher. # blocksize: Blocksize. # # Returns: # Hash value. # """ # with open(name, 'rb') as f: # buf = f.read(blocksize) # while len(buf) > 0: # hasher.update(buf) # buf = f.read(blocksize) # return hasher.hexdigest() . Output only the next line.
class CategoryJSON(FileJSON):
Given the following code snippet before the placeholder: <|code_start|>def file_name(name, suffix=JSON_FILE_SUFFIX): """ Return file name based on name and suffix. """ return name + '.' + suffix class Manifest(FileJSON): """ Manifest file. """ def __init__(self, directory): super(Manifest, self).__init__(os.path.abspath(directory), file_name(MANIFEST_FILE_NAME)) def check(self): """ Check manifest. """ manifest = self.read() result = True errors = [] names = [file_name(CATEGORIES_FILE_NAME)] for name in names: if not name in manifest: raise DBLayoutError('Bad manifest: no ' + name + ' entry') for name, value in manifest.items(): <|code_end|> , predict the next line using imports from the current file: import hashlib import os import shutil from .exceptions import DBLayoutError, DBStructureError, FileJSONError, IntegrityError from .fileutils import FileJSON, hash_file from .file_bson.file_bson import FileBSON and context including class names, function names, and sometimes code from other files: # Path: g_sorcery/exceptions.py # class DBLayoutError(GSorceryError): # pass # # class DBStructureError(DBError): # pass # # class FileJSONError(GSorceryError): # pass # # class IntegrityError(DBError): # pass # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # def hash_file(name, hasher, blocksize=65536): # """ # Get a file hash. # # Args: # name: file name. # hasher: Hasher. # blocksize: Blocksize. # # Returns: # Hash value. # """ # with open(name, 'rb') as f: # buf = f.read(blocksize) # while len(buf) > 0: # hasher.update(buf) # buf = f.read(blocksize) # return hasher.hexdigest() . Output only the next line.
if hash_file(os.path.join(self.directory, name), hashlib.md5()) != \
Based on the snippet: <|code_start|> Returns: A dictionary with one entry. Key if a file name, content is content returned by parser. """ data = None if open_file: with open(f_name, open_mode) as f: data = parser(f) else: data = parser(f_name) return {os.path.basename(f_name): data} def load_remote_file(uri, parser, open_file = True, open_mode = 'r', output = "", timeout = None): """ Load files from an URI. Args: uri: URI. parser: Parser that will be applied to downloaded files. open_file: Whether parser accepts a file descriptor. open_mode: Open mode for a file. output: What output name should downloaded file have. timeout: URI access timeout. (it will be a key identifying data loaded from this file) Returns: Dictionary with a loaded data. Key is filename, content is data returned by parser. """ <|code_end|> , predict the immediate next line with the help of imports: import glob import json import hashlib import os import tarfile from .compatibility import TemporaryDirectory from .exceptions import FileJSONError, DownloadingError from .serialization import JSONSerializer, deserializeHook and context (classes, functions, sometimes code) from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # class DownloadingError(GSorceryError): # pass # # Path: g_sorcery/serialization.py # class JSONSerializer(json.JSONEncoder): # """ # Custom JSON encoder. # # Each serializable class should have a method serialize # that returns JSON serializable value. If class additionally # has a classmethod deserialize that it can be deserialized # and additional metainformation is added to the resulting JSON. # """ # def default(self, obj): # res = step_to_raw_serializable(obj) # if res: # return res # else: # return json.JSONEncoder.default(self, obj) # # def deserializeHook(json_object): # """ # Custom JSON decoder. # # Each class that can be deserialized should have classmethod deserialize # that takes value (previously returned by serialize method) and transforms # it into class instance. # """ # return step_from_raw_serializable(json_object) . Output only the next line.
download_dir = TemporaryDirectory()
Here is a snippet: <|code_start|> def __init__(self, directory, name, mandatories=None): """ Args: directory: File directory. name: File name. mandatories: List of requiered keys. """ self.directory = os.path.abspath(directory) self.name = name self.path = os.path.join(directory, name) if not mandatories: self.mandatories = [] else: self.mandatories = mandatories def read(self): """ Read file. """ if not os.path.exists(self.directory): os.makedirs(self.directory) content = {} if not os.path.isfile(self.path): for key in self.mandatories: content[key] = "" self.write_content(content) else: content = self.read_content() for key in self.mandatories: if not key in content: <|code_end|> . Write the next line using the current file imports: import glob import json import hashlib import os import tarfile from .compatibility import TemporaryDirectory from .exceptions import FileJSONError, DownloadingError from .serialization import JSONSerializer, deserializeHook and context from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # class DownloadingError(GSorceryError): # pass # # Path: g_sorcery/serialization.py # class JSONSerializer(json.JSONEncoder): # """ # Custom JSON encoder. # # Each serializable class should have a method serialize # that returns JSON serializable value. If class additionally # has a classmethod deserialize that it can be deserialized # and additional metainformation is added to the resulting JSON. # """ # def default(self, obj): # res = step_to_raw_serializable(obj) # if res: # return res # else: # return json.JSONEncoder.default(self, obj) # # def deserializeHook(json_object): # """ # Custom JSON decoder. # # Each class that can be deserialized should have classmethod deserialize # that takes value (previously returned by serialize method) and transforms # it into class instance. # """ # return step_from_raw_serializable(json_object) , which may include functions, classes, or code. Output only the next line.
raise FileJSONError('lack of mandatory key: ' + key)
Next line prediction: <|code_start|> content returned by parser. """ data = None if open_file: with open(f_name, open_mode) as f: data = parser(f) else: data = parser(f_name) return {os.path.basename(f_name): data} def load_remote_file(uri, parser, open_file = True, open_mode = 'r', output = "", timeout = None): """ Load files from an URI. Args: uri: URI. parser: Parser that will be applied to downloaded files. open_file: Whether parser accepts a file descriptor. open_mode: Open mode for a file. output: What output name should downloaded file have. timeout: URI access timeout. (it will be a key identifying data loaded from this file) Returns: Dictionary with a loaded data. Key is filename, content is data returned by parser. """ download_dir = TemporaryDirectory() loaded_data = {} if wget(uri, download_dir.name, output, timeout=timeout): <|code_end|> . Use current file imports: (import glob import json import hashlib import os import tarfile from .compatibility import TemporaryDirectory from .exceptions import FileJSONError, DownloadingError from .serialization import JSONSerializer, deserializeHook) and context including class names, function names, or small code snippets from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # class DownloadingError(GSorceryError): # pass # # Path: g_sorcery/serialization.py # class JSONSerializer(json.JSONEncoder): # """ # Custom JSON encoder. # # Each serializable class should have a method serialize # that returns JSON serializable value. If class additionally # has a classmethod deserialize that it can be deserialized # and additional metainformation is added to the resulting JSON. # """ # def default(self, obj): # res = step_to_raw_serializable(obj) # if res: # return res # else: # return json.JSONEncoder.default(self, obj) # # def deserializeHook(json_object): # """ # Custom JSON decoder. # # Each class that can be deserialized should have classmethod deserialize # that takes value (previously returned by serialize method) and transforms # it into class instance. # """ # return step_from_raw_serializable(json_object) . Output only the next line.
raise DownloadingError("wget failed: " + uri)
Here is a snippet: <|code_start|> os.makedirs(self.directory) self.write_content(content) def write_content(self, content): """ Real write operation with serialization. Should be overridden. """ pass class FileJSON(FileJSONData): """ Class for JSON files. Supports custom JSON serialization provided by g_sorcery.serialization. """ def read_content(self): """ Read JSON file. """ content = {} with open(self.path, 'r') as f: content = json.load(f, object_hook=deserializeHook) return content def write_content(self, content): """ Write JSON file. """ with open(self.path, 'w') as f: <|code_end|> . Write the next line using the current file imports: import glob import json import hashlib import os import tarfile from .compatibility import TemporaryDirectory from .exceptions import FileJSONError, DownloadingError from .serialization import JSONSerializer, deserializeHook and context from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # class DownloadingError(GSorceryError): # pass # # Path: g_sorcery/serialization.py # class JSONSerializer(json.JSONEncoder): # """ # Custom JSON encoder. # # Each serializable class should have a method serialize # that returns JSON serializable value. If class additionally # has a classmethod deserialize that it can be deserialized # and additional metainformation is added to the resulting JSON. # """ # def default(self, obj): # res = step_to_raw_serializable(obj) # if res: # return res # else: # return json.JSONEncoder.default(self, obj) # # def deserializeHook(json_object): # """ # Custom JSON decoder. # # Each class that can be deserialized should have classmethod deserialize # that takes value (previously returned by serialize method) and transforms # it into class instance. # """ # return step_from_raw_serializable(json_object) , which may include functions, classes, or code. Output only the next line.
json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer)
Predict the next line after this snippet: <|code_start|> def write(self, content): """ Write file. """ for key in self.mandatories: if not key in content: raise FileJSONError('lack of mandatory key: ' + key) if not os.path.exists(self.directory): os.makedirs(self.directory) self.write_content(content) def write_content(self, content): """ Real write operation with serialization. Should be overridden. """ pass class FileJSON(FileJSONData): """ Class for JSON files. Supports custom JSON serialization provided by g_sorcery.serialization. """ def read_content(self): """ Read JSON file. """ content = {} with open(self.path, 'r') as f: <|code_end|> using the current file's imports: import glob import json import hashlib import os import tarfile from .compatibility import TemporaryDirectory from .exceptions import FileJSONError, DownloadingError from .serialization import JSONSerializer, deserializeHook and any relevant context from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # class DownloadingError(GSorceryError): # pass # # Path: g_sorcery/serialization.py # class JSONSerializer(json.JSONEncoder): # """ # Custom JSON encoder. # # Each serializable class should have a method serialize # that returns JSON serializable value. If class additionally # has a classmethod deserialize that it can be deserialized # and additional metainformation is added to the resulting JSON. # """ # def default(self, obj): # res = step_to_raw_serializable(obj) # if res: # return res # else: # return json.JSONEncoder.default(self, obj) # # def deserializeHook(json_object): # """ # Custom JSON decoder. # # Each class that can be deserialized should have classmethod deserialize # that takes value (previously returned by serialize method) and transforms # it into class instance. # """ # return step_from_raw_serializable(json_object) . Output only the next line.
content = json.load(f, object_hook=deserializeHook)
Given the following code snippet before the placeholder: <|code_start|> git_syncer.py ~~~~~~~~~~~~~ git sync helper :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class GITSyncer(Syncer): """ Class used to sync with git repos. """ def sync(self, db_uri, repository_config): """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ if self.persistent_datadir is None: <|code_end|> , predict the next line using imports from the current file: import os import shutil import subprocess from g_sorcery.compatibility import TemporaryDirectory from g_sorcery.exceptions import SyncError from g_sorcery.syncer import Syncer, SyncedData, TmpSyncedData and context including class names, function names, and sometimes code from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class SyncError(DBError): # pass # # Path: g_sorcery/syncer.py # class Syncer(object): # """ # Class used to sync data with remote source. # """ # # def __init__(self, persistent_datadir): # self.persistent_datadir = persistent_datadir # # def sync(self, db_uri, repository_config): # """ # Synchronize local directory with remote source. # # Args: # db_uri: URI for synchronization with remote source. # repository_config: repository config. # # Returns: # SyncedData object that gives access to the directory with data. # """ # raise NotImplementedError # # class SyncedData(object): # """ # Synced data. # # Directory with sync data is guaranted to exist only as long as this # object does. # """ # def __init__(self, directory): # self.directory = os.path.abspath(directory) # # def get_path(self): # return self.directory # # class TmpSyncedData(SyncedData): # """ # Synced data that lives in a temporary directory. # """ # # def __init__(self, directory, tmpdirobj): # super(TmpSyncedData, self).__init__(directory) # self.tmpdirobj = tmpdirobj . Output only the next line.
tmp_dir = TemporaryDirectory()
Predict the next line after this snippet: <|code_start|> Returns: SyncedData object that gives access to the directory with data. """ if self.persistent_datadir is None: tmp_dir = TemporaryDirectory() path = os.path.join(tmp_dir.name, "remote") else: path = self.persistent_datadir try: branch = repository_config["branch"] except KeyError: branch = "master" if os.path.exists(path): if self.branch_not_changed(path, branch) and self.remote_url_not_changed(path, db_uri): self.pull(path) else: shutil.rmtree(path) self.clone(db_uri, branch, path) else: self.clone(db_uri, branch, path) if self.persistent_datadir is None: return TmpSyncedData(path, tmp_dir) else: return SyncedData(path) def clone(self, db_uri, branch, path): if os.system("git clone --depth 1 --branch " + branch + " " + db_uri + " " + path): <|code_end|> using the current file's imports: import os import shutil import subprocess from g_sorcery.compatibility import TemporaryDirectory from g_sorcery.exceptions import SyncError from g_sorcery.syncer import Syncer, SyncedData, TmpSyncedData and any relevant context from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class SyncError(DBError): # pass # # Path: g_sorcery/syncer.py # class Syncer(object): # """ # Class used to sync data with remote source. # """ # # def __init__(self, persistent_datadir): # self.persistent_datadir = persistent_datadir # # def sync(self, db_uri, repository_config): # """ # Synchronize local directory with remote source. # # Args: # db_uri: URI for synchronization with remote source. # repository_config: repository config. # # Returns: # SyncedData object that gives access to the directory with data. # """ # raise NotImplementedError # # class SyncedData(object): # """ # Synced data. # # Directory with sync data is guaranted to exist only as long as this # object does. # """ # def __init__(self, directory): # self.directory = os.path.abspath(directory) # # def get_path(self): # return self.directory # # class TmpSyncedData(SyncedData): # """ # Synced data that lives in a temporary directory. # """ # # def __init__(self, directory, tmpdirobj): # super(TmpSyncedData, self).__init__(directory) # self.tmpdirobj = tmpdirobj . Output only the next line.
raise SyncError("sync failed (clonning): " + db_uri)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ git_syncer.py ~~~~~~~~~~~~~ git sync helper :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , predict the next line using imports from the current file: import os import shutil import subprocess from g_sorcery.compatibility import TemporaryDirectory from g_sorcery.exceptions import SyncError from g_sorcery.syncer import Syncer, SyncedData, TmpSyncedData and context including class names, function names, and sometimes code from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class SyncError(DBError): # pass # # Path: g_sorcery/syncer.py # class Syncer(object): # """ # Class used to sync data with remote source. # """ # # def __init__(self, persistent_datadir): # self.persistent_datadir = persistent_datadir # # def sync(self, db_uri, repository_config): # """ # Synchronize local directory with remote source. # # Args: # db_uri: URI for synchronization with remote source. # repository_config: repository config. # # Returns: # SyncedData object that gives access to the directory with data. # """ # raise NotImplementedError # # class SyncedData(object): # """ # Synced data. # # Directory with sync data is guaranted to exist only as long as this # object does. # """ # def __init__(self, directory): # self.directory = os.path.abspath(directory) # # def get_path(self): # return self.directory # # class TmpSyncedData(SyncedData): # """ # Synced data that lives in a temporary directory. # """ # # def __init__(self, directory, tmpdirobj): # super(TmpSyncedData, self).__init__(directory) # self.tmpdirobj = tmpdirobj . Output only the next line.
class GITSyncer(Syncer):
Based on the snippet: <|code_start|> Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ if self.persistent_datadir is None: tmp_dir = TemporaryDirectory() path = os.path.join(tmp_dir.name, "remote") else: path = self.persistent_datadir try: branch = repository_config["branch"] except KeyError: branch = "master" if os.path.exists(path): if self.branch_not_changed(path, branch) and self.remote_url_not_changed(path, db_uri): self.pull(path) else: shutil.rmtree(path) self.clone(db_uri, branch, path) else: self.clone(db_uri, branch, path) if self.persistent_datadir is None: return TmpSyncedData(path, tmp_dir) else: <|code_end|> , predict the immediate next line with the help of imports: import os import shutil import subprocess from g_sorcery.compatibility import TemporaryDirectory from g_sorcery.exceptions import SyncError from g_sorcery.syncer import Syncer, SyncedData, TmpSyncedData and context (classes, functions, sometimes code) from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class SyncError(DBError): # pass # # Path: g_sorcery/syncer.py # class Syncer(object): # """ # Class used to sync data with remote source. # """ # # def __init__(self, persistent_datadir): # self.persistent_datadir = persistent_datadir # # def sync(self, db_uri, repository_config): # """ # Synchronize local directory with remote source. # # Args: # db_uri: URI for synchronization with remote source. # repository_config: repository config. # # Returns: # SyncedData object that gives access to the directory with data. # """ # raise NotImplementedError # # class SyncedData(object): # """ # Synced data. # # Directory with sync data is guaranted to exist only as long as this # object does. # """ # def __init__(self, directory): # self.directory = os.path.abspath(directory) # # def get_path(self): # return self.directory # # class TmpSyncedData(SyncedData): # """ # Synced data that lives in a temporary directory. # """ # # def __init__(self, directory, tmpdirobj): # super(TmpSyncedData, self).__init__(directory) # self.tmpdirobj = tmpdirobj . Output only the next line.
return SyncedData(path)
Here is a snippet: <|code_start|> """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ if self.persistent_datadir is None: tmp_dir = TemporaryDirectory() path = os.path.join(tmp_dir.name, "remote") else: path = self.persistent_datadir try: branch = repository_config["branch"] except KeyError: branch = "master" if os.path.exists(path): if self.branch_not_changed(path, branch) and self.remote_url_not_changed(path, db_uri): self.pull(path) else: shutil.rmtree(path) self.clone(db_uri, branch, path) else: self.clone(db_uri, branch, path) if self.persistent_datadir is None: <|code_end|> . Write the next line using the current file imports: import os import shutil import subprocess from g_sorcery.compatibility import TemporaryDirectory from g_sorcery.exceptions import SyncError from g_sorcery.syncer import Syncer, SyncedData, TmpSyncedData and context from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class SyncError(DBError): # pass # # Path: g_sorcery/syncer.py # class Syncer(object): # """ # Class used to sync data with remote source. # """ # # def __init__(self, persistent_datadir): # self.persistent_datadir = persistent_datadir # # def sync(self, db_uri, repository_config): # """ # Synchronize local directory with remote source. # # Args: # db_uri: URI for synchronization with remote source. # repository_config: repository config. # # Returns: # SyncedData object that gives access to the directory with data. # """ # raise NotImplementedError # # class SyncedData(object): # """ # Synced data. # # Directory with sync data is guaranted to exist only as long as this # object does. # """ # def __init__(self, directory): # self.directory = os.path.abspath(directory) # # def get_path(self): # return self.directory # # class TmpSyncedData(SyncedData): # """ # Synced data that lives in a temporary directory. # """ # # def __init__(self, directory, tmpdirobj): # super(TmpSyncedData, self).__init__(directory) # self.tmpdirobj = tmpdirobj , which may include functions, classes, or code. Output only the next line.
return TmpSyncedData(path, tmp_dir)
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ mangler.py ~~~~~~~~~~ package manager interaction :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class PackageManager(object): """ Base class for package manager abstraction """ executable = "" <|code_end|> , generate the next line using the imports in this file: import os from .logger import Logger and context (functions, classes, or occasionally code) from other files: # Path: g_sorcery/logger.py # class Logger(object): # """ # A simple logger object. Uses portage out facilities. # """ # def __init__(self): # self.out = portage.output.EOutput() # # def error(self, message): # self.out.eerror(message) # # def info(self, message): # self.out.einfo(message) # # def warn(self, message): # self.out.ewarn(message) . Output only the next line.
logger = Logger()
Next line prediction: <|code_start|> def generate(self, values): """ Generate an XML tree filled with values from a given dictionary. Args: values: Data dictionary. Returns: XML tree being an istance of xml.etree.ElementTree.Element """ root = ET.Element(self.external) for tag in self.schema: self.add_tag(root, tag, values) return root def add_tag(self, root, tag, values): """ Add a tag. Args: root: A parent tag. tag: Tag from schema to be added. values: Data dictionary. """ name = tag['name'] if not name in values: if tag['required']: <|code_end|> . Use current file imports: (from .exceptions import XMLGeneratorError import xml.etree.ElementTree as ET import xml.dom.minidom as minidom) and context including class names, function names, or small code snippets from other files: # Path: g_sorcery/exceptions.py # class XMLGeneratorError(GSorceryError): # pass . Output only the next line.
raise XMLGeneratorError('Required tag not found: ' + name)
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ file_bson.py ~~~~~~~~~~~~ bson file format support :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class FileBSON(FileJSONData): """ Class for BSON files. Supports custom JSON serialization provided by g_sorcery.serialization. """ def read_content(self): """ Read BSON file. """ content = {} bcnt = None with open(self.path, 'rb') as f: bcnt = bson.BSON(f.read()) if not bcnt: <|code_end|> , predict the immediate next line with the help of imports: import bson from g_sorcery.exceptions import FileJSONError from g_sorcery.fileutils import FileJSONData from g_sorcery.serialization import from_raw_serializable, to_raw_serializable and context (classes, functions, sometimes code) from other files: # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/fileutils.py # class FileJSONData(object): # """ # Class for files with JSON compatible data. # """ # def __init__(self, directory, name, mandatories=None): # """ # Args: # directory: File directory. # name: File name. # mandatories: List of requiered keys. # """ # self.directory = os.path.abspath(directory) # self.name = name # self.path = os.path.join(directory, name) # if not mandatories: # self.mandatories = [] # else: # self.mandatories = mandatories # # def read(self): # """ # Read file. # """ # if not os.path.exists(self.directory): # os.makedirs(self.directory) # content = {} # if not os.path.isfile(self.path): # for key in self.mandatories: # content[key] = "" # self.write_content(content) # else: # content = self.read_content() # for key in self.mandatories: # if not key in content: # raise FileJSONError('lack of mandatory key: ' + key) # # return content # # def read_content(self): # """ # Real read operation with deserialization. Should be overridden. # """ # return [] # # def write(self, content): # """ # Write file. # """ # for key in self.mandatories: # if not key in content: # raise FileJSONError('lack of mandatory key: ' + key) # if not os.path.exists(self.directory): # os.makedirs(self.directory) # self.write_content(content) # # def write_content(self, content): # """ # Real write operation with serialization. Should be overridden. # """ # pass # # Path: g_sorcery/serialization.py # def from_raw_serializable(sobj): # """ # Build object from the raw serializable object. # """ # if isinstance(sobj, dict): # res = {k: from_raw_serializable(v) for k, v in sobj.items()} # return step_from_raw_serializable(res) # elif isinstance(sobj, list): # return [from_raw_serializable(item) for item in sobj] # else: # return sobj # # def to_raw_serializable(obj): # """ # Convert object to the raw serializable type. # Logic is the same as in the standard json encoder. # """ # if isinstance(obj, basestring) \ # or obj is None \ # or obj is True \ # or obj is False \ # or isinstance(obj, int) \ # or isinstance(obj, float): # return obj # elif isinstance(obj, dict): # return {k: to_raw_serializable(v) for k, v in obj.items()} # elif isinstance(obj, (list, tuple)): # return [to_raw_serializable(item) for item in obj] # # else: # sobj = step_to_raw_serializable(obj) # if not sobj: # raise TypeError('Non serializable object: ', obj) # return to_raw_serializable(sobj) . Output only the next line.
raise FileJSONError('failed to read: ', self.path)
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ file_bson.py ~~~~~~~~~~~~ bson file format support :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , predict the immediate next line with the help of imports: import bson from g_sorcery.exceptions import FileJSONError from g_sorcery.fileutils import FileJSONData from g_sorcery.serialization import from_raw_serializable, to_raw_serializable and context (classes, functions, sometimes code) from other files: # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/fileutils.py # class FileJSONData(object): # """ # Class for files with JSON compatible data. # """ # def __init__(self, directory, name, mandatories=None): # """ # Args: # directory: File directory. # name: File name. # mandatories: List of requiered keys. # """ # self.directory = os.path.abspath(directory) # self.name = name # self.path = os.path.join(directory, name) # if not mandatories: # self.mandatories = [] # else: # self.mandatories = mandatories # # def read(self): # """ # Read file. # """ # if not os.path.exists(self.directory): # os.makedirs(self.directory) # content = {} # if not os.path.isfile(self.path): # for key in self.mandatories: # content[key] = "" # self.write_content(content) # else: # content = self.read_content() # for key in self.mandatories: # if not key in content: # raise FileJSONError('lack of mandatory key: ' + key) # # return content # # def read_content(self): # """ # Real read operation with deserialization. Should be overridden. # """ # return [] # # def write(self, content): # """ # Write file. # """ # for key in self.mandatories: # if not key in content: # raise FileJSONError('lack of mandatory key: ' + key) # if not os.path.exists(self.directory): # os.makedirs(self.directory) # self.write_content(content) # # def write_content(self, content): # """ # Real write operation with serialization. Should be overridden. # """ # pass # # Path: g_sorcery/serialization.py # def from_raw_serializable(sobj): # """ # Build object from the raw serializable object. # """ # if isinstance(sobj, dict): # res = {k: from_raw_serializable(v) for k, v in sobj.items()} # return step_from_raw_serializable(res) # elif isinstance(sobj, list): # return [from_raw_serializable(item) for item in sobj] # else: # return sobj # # def to_raw_serializable(obj): # """ # Convert object to the raw serializable type. # Logic is the same as in the standard json encoder. # """ # if isinstance(obj, basestring) \ # or obj is None \ # or obj is True \ # or obj is False \ # or isinstance(obj, int) \ # or isinstance(obj, float): # return obj # elif isinstance(obj, dict): # return {k: to_raw_serializable(v) for k, v in obj.items()} # elif isinstance(obj, (list, tuple)): # return [to_raw_serializable(item) for item in obj] # # else: # sobj = step_to_raw_serializable(obj) # if not sobj: # raise TypeError('Non serializable object: ', obj) # return to_raw_serializable(sobj) . Output only the next line.
class FileBSON(FileJSONData):
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ file_bson.py ~~~~~~~~~~~~ bson file format support :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class FileBSON(FileJSONData): """ Class for BSON files. Supports custom JSON serialization provided by g_sorcery.serialization. """ def read_content(self): """ Read BSON file. """ content = {} bcnt = None with open(self.path, 'rb') as f: bcnt = bson.BSON(f.read()) if not bcnt: raise FileJSONError('failed to read: ', self.path) rawcnt = bcnt.decode() <|code_end|> , generate the next line using the imports in this file: import bson from g_sorcery.exceptions import FileJSONError from g_sorcery.fileutils import FileJSONData from g_sorcery.serialization import from_raw_serializable, to_raw_serializable and context (functions, classes, or occasionally code) from other files: # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/fileutils.py # class FileJSONData(object): # """ # Class for files with JSON compatible data. # """ # def __init__(self, directory, name, mandatories=None): # """ # Args: # directory: File directory. # name: File name. # mandatories: List of requiered keys. # """ # self.directory = os.path.abspath(directory) # self.name = name # self.path = os.path.join(directory, name) # if not mandatories: # self.mandatories = [] # else: # self.mandatories = mandatories # # def read(self): # """ # Read file. # """ # if not os.path.exists(self.directory): # os.makedirs(self.directory) # content = {} # if not os.path.isfile(self.path): # for key in self.mandatories: # content[key] = "" # self.write_content(content) # else: # content = self.read_content() # for key in self.mandatories: # if not key in content: # raise FileJSONError('lack of mandatory key: ' + key) # # return content # # def read_content(self): # """ # Real read operation with deserialization. Should be overridden. # """ # return [] # # def write(self, content): # """ # Write file. # """ # for key in self.mandatories: # if not key in content: # raise FileJSONError('lack of mandatory key: ' + key) # if not os.path.exists(self.directory): # os.makedirs(self.directory) # self.write_content(content) # # def write_content(self, content): # """ # Real write operation with serialization. Should be overridden. # """ # pass # # Path: g_sorcery/serialization.py # def from_raw_serializable(sobj): # """ # Build object from the raw serializable object. # """ # if isinstance(sobj, dict): # res = {k: from_raw_serializable(v) for k, v in sobj.items()} # return step_from_raw_serializable(res) # elif isinstance(sobj, list): # return [from_raw_serializable(item) for item in sobj] # else: # return sobj # # def to_raw_serializable(obj): # """ # Convert object to the raw serializable type. # Logic is the same as in the standard json encoder. # """ # if isinstance(obj, basestring) \ # or obj is None \ # or obj is True \ # or obj is False \ # or isinstance(obj, int) \ # or isinstance(obj, float): # return obj # elif isinstance(obj, dict): # return {k: to_raw_serializable(v) for k, v in obj.items()} # elif isinstance(obj, (list, tuple)): # return [to_raw_serializable(item) for item in obj] # # else: # sobj = step_to_raw_serializable(obj) # if not sobj: # raise TypeError('Non serializable object: ', obj) # return to_raw_serializable(sobj) . Output only the next line.
content = from_raw_serializable(rawcnt)
Using the snippet: <|code_start|> :copyright: (c) 2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class FileBSON(FileJSONData): """ Class for BSON files. Supports custom JSON serialization provided by g_sorcery.serialization. """ def read_content(self): """ Read BSON file. """ content = {} bcnt = None with open(self.path, 'rb') as f: bcnt = bson.BSON(f.read()) if not bcnt: raise FileJSONError('failed to read: ', self.path) rawcnt = bcnt.decode() content = from_raw_serializable(rawcnt) return content def write_content(self, content): """ Write BSON file. """ <|code_end|> , determine the next line of code. You have imports: import bson from g_sorcery.exceptions import FileJSONError from g_sorcery.fileutils import FileJSONData from g_sorcery.serialization import from_raw_serializable, to_raw_serializable and context (class names, function names, or code) available: # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/fileutils.py # class FileJSONData(object): # """ # Class for files with JSON compatible data. # """ # def __init__(self, directory, name, mandatories=None): # """ # Args: # directory: File directory. # name: File name. # mandatories: List of requiered keys. # """ # self.directory = os.path.abspath(directory) # self.name = name # self.path = os.path.join(directory, name) # if not mandatories: # self.mandatories = [] # else: # self.mandatories = mandatories # # def read(self): # """ # Read file. # """ # if not os.path.exists(self.directory): # os.makedirs(self.directory) # content = {} # if not os.path.isfile(self.path): # for key in self.mandatories: # content[key] = "" # self.write_content(content) # else: # content = self.read_content() # for key in self.mandatories: # if not key in content: # raise FileJSONError('lack of mandatory key: ' + key) # # return content # # def read_content(self): # """ # Real read operation with deserialization. Should be overridden. # """ # return [] # # def write(self, content): # """ # Write file. # """ # for key in self.mandatories: # if not key in content: # raise FileJSONError('lack of mandatory key: ' + key) # if not os.path.exists(self.directory): # os.makedirs(self.directory) # self.write_content(content) # # def write_content(self, content): # """ # Real write operation with serialization. Should be overridden. # """ # pass # # Path: g_sorcery/serialization.py # def from_raw_serializable(sobj): # """ # Build object from the raw serializable object. # """ # if isinstance(sobj, dict): # res = {k: from_raw_serializable(v) for k, v in sobj.items()} # return step_from_raw_serializable(res) # elif isinstance(sobj, list): # return [from_raw_serializable(item) for item in sobj] # else: # return sobj # # def to_raw_serializable(obj): # """ # Convert object to the raw serializable type. # Logic is the same as in the standard json encoder. # """ # if isinstance(obj, basestring) \ # or obj is None \ # or obj is True \ # or obj is False \ # or isinstance(obj, int) \ # or isinstance(obj, float): # return obj # elif isinstance(obj, dict): # return {k: to_raw_serializable(v) for k, v in obj.items()} # elif isinstance(obj, (list, tuple)): # return [to_raw_serializable(item) for item in obj] # # else: # sobj = step_to_raw_serializable(obj) # if not sobj: # raise TypeError('Non serializable object: ', obj) # return to_raw_serializable(sobj) . Output only the next line.
rawcnt = to_raw_serializable(content)
Continue the code snippet: <|code_start|>""" def step_to_raw_serializable(obj): """ Make one step of convertion of object to the type that is serializable by the json library. None return value signifies an error. """ if hasattr(obj, "serialize"): if hasattr(obj, "deserialize"): module = obj.__class__.__module__ name = obj.__class__.__name__ value = obj.serialize() return {"python_module" : module, "python_class" : name, "value" : value} else: return obj.serialize() return None def to_raw_serializable(obj): """ Convert object to the raw serializable type. Logic is the same as in the standard json encoder. """ <|code_end|> . Use current file imports: import json import importlib from .compatibility import basestring and context (classes, functions, or code) from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # def __del__(self): . Output only the next line.
if isinstance(obj, basestring) \
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ base.py ~~~~~~~ base class for tests :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class BaseTest(unittest.TestCase): def setUp(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from g_sorcery.compatibility import TemporaryDirectory and context: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) which might include code, classes, or functions. Output only the next line.
self.tempdir = TemporaryDirectory()
Next line prediction: <|code_start|> List of all eclasses with string entries. """ result = [] for directory in [self.eclass_dir, os.path.join(get_pkgpath(), 'data')]: if directory: for f_name in glob.iglob(os.path.join(directory, '*.eclass')): result.append(os.path.basename(f_name)[:-7]) return list(set(result)) def generate(self, eclass): """ Generate a given eclass. Args: eclass: String containing eclass name. Returns: Eclass source as a list of strings. """ for directory in [self.eclass_dir, os.path.join(get_pkgpath(), 'data')]: f_name = os.path.join(directory, eclass + '.eclass') if os.path.isfile(f_name): with open(f_name, 'r') as f: eclass = f.read().split('\n') if eclass[-1] == '': eclass = eclass[:-1] return eclass <|code_end|> . Use current file imports: (import glob import os from .exceptions import EclassError from .fileutils import get_pkgpath) and context including class names, function names, or small code snippets from other files: # Path: g_sorcery/exceptions.py # class EclassError(GSorceryError): # pass # # Path: g_sorcery/fileutils.py # def get_pkgpath(root = None): # """ # Get package path. # # Args: # root: module file path # # Returns: # Package path. # """ # if not root: # root = __file__ # if os.path.islink(root): # root = os.path.realpath(root) # return os.path.dirname(os.path.abspath(root)) . Output only the next line.
raise EclassError('No eclass ' + eclass)
Continue the code snippet: <|code_start|> ~~~~~~~~~ eclass generation :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class EclassGenerator(object): """ Generates eclasses from files in a given dir. """ def __init__(self, eclass_dir): """ __init__ in a subclass should take no parameters. """ self.eclass_dir = eclass_dir def list(self): """ List all eclasses. Returns: List of all eclasses with string entries. """ result = [] <|code_end|> . Use current file imports: import glob import os from .exceptions import EclassError from .fileutils import get_pkgpath and context (classes, functions, or code) from other files: # Path: g_sorcery/exceptions.py # class EclassError(GSorceryError): # pass # # Path: g_sorcery/fileutils.py # def get_pkgpath(root = None): # """ # Get package path. # # Args: # root: module file path # # Returns: # Package path. # """ # if not root: # root = __file__ # if os.path.islink(root): # root = os.path.realpath(root) # return os.path.dirname(os.path.abspath(root)) . Output only the next line.
for directory in [self.eclass_dir, os.path.join(get_pkgpath(), 'data')]:
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ server.py ~~~~~~~~~ test server :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , predict the immediate next line with the help of imports: import os import threading from g_sorcery.compatibility import py2k from SocketServer import TCPServer as HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler from http.server import HTTPServer from http.server import SimpleHTTPRequestHandler and context (classes, functions, sometimes code) from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # def __del__(self): . Output only the next line.
if py2k:
Given the following code snippet before the placeholder: <|code_start|> cfg_path = path break if not cfg_path: logger.error('no config file for ' + name + ' backend\n') return -1 cfg_f = FileJSON(cfg_path, cfg, ['package']) try: config = cfg_f.read() except FileJSONError as e: logger.error('error loading config file for ' \ + name + ': ' + str(e) + '\n') return -1 backend = get_backend(config['package']) if not backend: logger.error("backend initialization failed, exiting") return -1 config_file = None for path in '.', '~', '/etc/g-sorcery': config_file = os.path.join(path, "g-sorcery.cfg") if (os.path.isfile(config_file)): break else: config_file = None if not config_file: logger.error('no global config file\n') return -1 <|code_end|> , predict the next line using imports from the current file: import importlib import os import sys from .compatibility import configparser from .fileutils import FileJSON from .exceptions import FileJSONError from .logger import Logger and context including class names, function names, and sometimes code from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # def __del__(self): # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/logger.py # class Logger(object): # """ # A simple logger object. Uses portage out facilities. # """ # def __init__(self): # self.out = portage.output.EOutput() # # def error(self, message): # self.out.eerror(message) # # def info(self, message): # self.out.einfo(message) # # def warn(self, message): # self.out.ewarn(message) . Output only the next line.
global_config = configparser.ConfigParser()
Given the code snippet: <|code_start|> """ g_sorcery.py ~~~~~~~~~~~~ the main module :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ def main(): logger = Logger() if len(sys.argv) < 2: logger.error("no backend specified") return -1 name = sys.argv[1] cfg = name + '.json' cfg_path = None for path in '.', '~', '/etc/g-sorcery': current = os.path.join(path, cfg) if (os.path.isfile(current)): cfg_path = path break if not cfg_path: logger.error('no config file for ' + name + ' backend\n') return -1 <|code_end|> , generate the next line using the imports in this file: import importlib import os import sys from .compatibility import configparser from .fileutils import FileJSON from .exceptions import FileJSONError from .logger import Logger and context (functions, classes, or occasionally code) from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # def __del__(self): # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/logger.py # class Logger(object): # """ # A simple logger object. Uses portage out facilities. # """ # def __init__(self): # self.out = portage.output.EOutput() # # def error(self, message): # self.out.eerror(message) # # def info(self, message): # self.out.einfo(message) # # def warn(self, message): # self.out.ewarn(message) . Output only the next line.
cfg_f = FileJSON(cfg_path, cfg, ['package'])
Predict the next line after this snippet: <|code_start|> ~~~~~~~~~~~~ the main module :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ def main(): logger = Logger() if len(sys.argv) < 2: logger.error("no backend specified") return -1 name = sys.argv[1] cfg = name + '.json' cfg_path = None for path in '.', '~', '/etc/g-sorcery': current = os.path.join(path, cfg) if (os.path.isfile(current)): cfg_path = path break if not cfg_path: logger.error('no config file for ' + name + ' backend\n') return -1 cfg_f = FileJSON(cfg_path, cfg, ['package']) try: config = cfg_f.read() <|code_end|> using the current file's imports: import importlib import os import sys from .compatibility import configparser from .fileutils import FileJSON from .exceptions import FileJSONError from .logger import Logger and any relevant context from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # def __del__(self): # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/logger.py # class Logger(object): # """ # A simple logger object. Uses portage out facilities. # """ # def __init__(self): # self.out = portage.output.EOutput() # # def error(self, message): # self.out.eerror(message) # # def info(self, message): # self.out.einfo(message) # # def warn(self, message): # self.out.ewarn(message) . Output only the next line.
except FileJSONError as e:
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ g_sorcery.py ~~~~~~~~~~~~ the main module :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ def main(): <|code_end|> . Use current file imports: import importlib import os import sys from .compatibility import configparser from .fileutils import FileJSON from .exceptions import FileJSONError from .logger import Logger and context (classes, functions, or code) from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # def __del__(self): # # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/logger.py # class Logger(object): # """ # A simple logger object. Uses portage out facilities. # """ # def __init__(self): # self.out = portage.output.EOutput() # # def error(self, message): # self.out.eerror(message) # # def info(self, message): # self.out.einfo(message) # # def warn(self, message): # self.out.ewarn(message) . Output only the next line.
logger = Logger()
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_eclass.py ~~~~~~~~~~~~~~ eclass test suite :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class TestEclassGenerator(BaseTest): def test_eclass_generator(self): eclasses = ["test1", "test2"] for eclass in eclasses: os.system("echo 'eclass " + eclass + "' > " + os.path.join(self.tempdir.name, eclass + ".eclass")) <|code_end|> , predict the next line using imports from the current file: import os import unittest from g_sorcery.eclass import EclassGenerator from tests.base import BaseTest and context including class names, function names, and sometimes code from other files: # Path: g_sorcery/eclass.py # class EclassGenerator(object): # """ # Generates eclasses from files in a given dir. # """ # # def __init__(self, eclass_dir): # """ # __init__ in a subclass should take no parameters. # """ # self.eclass_dir = eclass_dir # # def list(self): # """ # List all eclasses. # # Returns: # List of all eclasses with string entries. # """ # result = [] # # for directory in [self.eclass_dir, os.path.join(get_pkgpath(), 'data')]: # if directory: # for f_name in glob.iglob(os.path.join(directory, '*.eclass')): # result.append(os.path.basename(f_name)[:-7]) # # return list(set(result)) # # def generate(self, eclass): # """ # Generate a given eclass. # # Args: # eclass: String containing eclass name. # # Returns: # Eclass source as a list of strings. # """ # for directory in [self.eclass_dir, os.path.join(get_pkgpath(), 'data')]: # f_name = os.path.join(directory, eclass + '.eclass') # if os.path.isfile(f_name): # with open(f_name, 'r') as f: # eclass = f.read().split('\n') # if eclass[-1] == '': # eclass = eclass[:-1] # return eclass # # raise EclassError('No eclass ' + eclass) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir . Output only the next line.
eclass_g = EclassGenerator(self.tempdir.name)
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_eclass.py ~~~~~~~~~~~~~~ eclass test suite :copyright: (c) 2013 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , predict the immediate next line with the help of imports: import os import unittest from g_sorcery.eclass import EclassGenerator from tests.base import BaseTest and context (classes, functions, sometimes code) from other files: # Path: g_sorcery/eclass.py # class EclassGenerator(object): # """ # Generates eclasses from files in a given dir. # """ # # def __init__(self, eclass_dir): # """ # __init__ in a subclass should take no parameters. # """ # self.eclass_dir = eclass_dir # # def list(self): # """ # List all eclasses. # # Returns: # List of all eclasses with string entries. # """ # result = [] # # for directory in [self.eclass_dir, os.path.join(get_pkgpath(), 'data')]: # if directory: # for f_name in glob.iglob(os.path.join(directory, '*.eclass')): # result.append(os.path.basename(f_name)[:-7]) # # return list(set(result)) # # def generate(self, eclass): # """ # Generate a given eclass. # # Args: # eclass: String containing eclass name. # # Returns: # Eclass source as a list of strings. # """ # for directory in [self.eclass_dir, os.path.join(get_pkgpath(), 'data')]: # f_name = os.path.join(directory, eclass + '.eclass') # if os.path.isfile(f_name): # with open(f_name, 'r') as f: # eclass = f.read().split('\n') # if eclass[-1] == '': # eclass = eclass[:-1] # return eclass # # raise EclassError('No eclass ' + eclass) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir . Output only the next line.
class TestEclassGenerator(BaseTest):
Given the following code snippet before the placeholder: <|code_start|> def sync(self, db_uri, repository_config): """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ raise NotImplementedError class TGZSyncer(Syncer): """ Class used to download and unpack tarballs. """ def sync(self, db_uri, repository_config): """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ <|code_end|> , predict the next line using imports from the current file: import glob import os from .compatibility import TemporaryDirectory from .exceptions import SyncError from .fileutils import wget from .git_syncer.git_syncer import GITSyncer and context including class names, function names, and sometimes code from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class SyncError(DBError): # pass # # Path: g_sorcery/fileutils.py # def wget(uri, directory, output="", timeout = None): # """ # Fetch a file. # # Args: # uri: URI. # directory: Directory where file should be saved. # output: Name of output file. # timeout: Timeout for wget. # # Returns: # Nonzero in case of a failure. # """ # if timeout is None: # timeout_str = ' ' # else: # timeout_str = ' -T ' + str(timeout) # # if output: # ret = os.system('wget ' + uri + # ' -O ' + os.path.join(directory, output) + timeout_str) # else: # ret = os.system('wget -P ' + directory + ' ' + uri + timeout_str) # return ret . Output only the next line.
download_dir = TemporaryDirectory()
Given the following code snippet before the placeholder: <|code_start|> Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ raise NotImplementedError class TGZSyncer(Syncer): """ Class used to download and unpack tarballs. """ def sync(self, db_uri, repository_config): """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ download_dir = TemporaryDirectory() if wget(db_uri, download_dir.name): <|code_end|> , predict the next line using imports from the current file: import glob import os from .compatibility import TemporaryDirectory from .exceptions import SyncError from .fileutils import wget from .git_syncer.git_syncer import GITSyncer and context including class names, function names, and sometimes code from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class SyncError(DBError): # pass # # Path: g_sorcery/fileutils.py # def wget(uri, directory, output="", timeout = None): # """ # Fetch a file. # # Args: # uri: URI. # directory: Directory where file should be saved. # output: Name of output file. # timeout: Timeout for wget. # # Returns: # Nonzero in case of a failure. # """ # if timeout is None: # timeout_str = ' ' # else: # timeout_str = ' -T ' + str(timeout) # # if output: # ret = os.system('wget ' + uri + # ' -O ' + os.path.join(directory, output) + timeout_str) # else: # ret = os.system('wget -P ' + directory + ' ' + uri + timeout_str) # return ret . Output only the next line.
raise SyncError('sync failed: ' + db_uri)
Using the snippet: <|code_start|> """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ raise NotImplementedError class TGZSyncer(Syncer): """ Class used to download and unpack tarballs. """ def sync(self, db_uri, repository_config): """ Synchronize local directory with remote source. Args: db_uri: URI for synchronization with remote source. repository_config: repository config. Returns: SyncedData object that gives access to the directory with data. """ download_dir = TemporaryDirectory() <|code_end|> , determine the next line of code. You have imports: import glob import os from .compatibility import TemporaryDirectory from .exceptions import SyncError from .fileutils import wget from .git_syncer.git_syncer import GITSyncer and context (class names, function names, or code) available: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # self.name = mkdtemp() # # def __del__(self): # shutil.rmtree(self.name) # # Path: g_sorcery/exceptions.py # class SyncError(DBError): # pass # # Path: g_sorcery/fileutils.py # def wget(uri, directory, output="", timeout = None): # """ # Fetch a file. # # Args: # uri: URI. # directory: Directory where file should be saved. # output: Name of output file. # timeout: Timeout for wget. # # Returns: # Nonzero in case of a failure. # """ # if timeout is None: # timeout_str = ' ' # else: # timeout_str = ' -T ' + str(timeout) # # if output: # ret = os.system('wget ' + uri + # ' -O ' + os.path.join(directory, output) + timeout_str) # else: # ret = os.system('wget -P ' + directory + ' ' + uri + timeout_str) # return ret . Output only the next line.
if wget(db_uri, download_dir.name):
Continue the code snippet: <|code_start|> self.directory = os.path.join(self.tempdir.name, 'tst') self.name = 'tst.json' self.path = os.path.join(self.directory, self.name) def test_write_read(self): fj = FileBSON(self.directory, self.name, ["mandatory"]) content = {"mandatory":"1", "test":"2"} fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_serializable(self): fj = FileBSON(self.directory, self.name, []) content = SerializableClass("1", "2") fj.write(content) content_r = fj.read() self.assertEqual(content_r, {"field1":"1", "field2":"2"}) self.assertRaises(TypeError, fj.write, NonSerializableClass()) def test_deserializable(self): fj = FileBSON(self.directory, self.name, []) content = DeserializableClass("1", "2") fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_deserializable_collection(self): fj = FileBSON(self.directory, self.name, []) content1 = DeserializableClass("1", "2") content2 = DeserializableClass("3", "4") <|code_end|> . Use current file imports: import os import unittest from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass from g_sorcery.file_bson.file_bson import FileBSON and context (classes, functions, or code) from other files: # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) . Output only the next line.
content = serializable_elist([content1, content2])
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_FileBSON.py ~~~~~~~~~~~~~~~~ FileBSON test suite :copyright: (c) 2013-2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ BSON_INSTALLED = False try: BSON_INSTALLED = True except ImportError as e: pass if BSON_INSTALLED: <|code_end|> , predict the next line using imports from the current file: import os import unittest from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass from g_sorcery.file_bson.file_bson import FileBSON and context including class names, function names, and sometimes code from other files: # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) . Output only the next line.
class TestFileJSON(BaseTest):
Predict the next line for this snippet: <|code_start|> BSON_INSTALLED = False try: BSON_INSTALLED = True except ImportError as e: pass if BSON_INSTALLED: class TestFileJSON(BaseTest): def setUp(self): super(TestFileJSON, self).setUp() self.directory = os.path.join(self.tempdir.name, 'tst') self.name = 'tst.json' self.path = os.path.join(self.directory, self.name) def test_write_read(self): fj = FileBSON(self.directory, self.name, ["mandatory"]) content = {"mandatory":"1", "test":"2"} fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_serializable(self): fj = FileBSON(self.directory, self.name, []) content = SerializableClass("1", "2") fj.write(content) content_r = fj.read() self.assertEqual(content_r, {"field1":"1", "field2":"2"}) <|code_end|> with the help of current file imports: import os import unittest from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass from g_sorcery.file_bson.file_bson import FileBSON and context from other files: # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) , which may contain function names, class names, or code. Output only the next line.
self.assertRaises(TypeError, fj.write, NonSerializableClass())
Based on the snippet: <|code_start|>""" BSON_INSTALLED = False try: BSON_INSTALLED = True except ImportError as e: pass if BSON_INSTALLED: class TestFileJSON(BaseTest): def setUp(self): super(TestFileJSON, self).setUp() self.directory = os.path.join(self.tempdir.name, 'tst') self.name = 'tst.json' self.path = os.path.join(self.directory, self.name) def test_write_read(self): fj = FileBSON(self.directory, self.name, ["mandatory"]) content = {"mandatory":"1", "test":"2"} fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_serializable(self): fj = FileBSON(self.directory, self.name, []) <|code_end|> , predict the immediate next line with the help of imports: import os import unittest from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass from g_sorcery.file_bson.file_bson import FileBSON and context (classes, functions, sometimes code) from other files: # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) . Output only the next line.
content = SerializableClass("1", "2")
Using the snippet: <|code_start|> BSON_INSTALLED = True except ImportError as e: pass if BSON_INSTALLED: class TestFileJSON(BaseTest): def setUp(self): super(TestFileJSON, self).setUp() self.directory = os.path.join(self.tempdir.name, 'tst') self.name = 'tst.json' self.path = os.path.join(self.directory, self.name) def test_write_read(self): fj = FileBSON(self.directory, self.name, ["mandatory"]) content = {"mandatory":"1", "test":"2"} fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_serializable(self): fj = FileBSON(self.directory, self.name, []) content = SerializableClass("1", "2") fj.write(content) content_r = fj.read() self.assertEqual(content_r, {"field1":"1", "field2":"2"}) self.assertRaises(TypeError, fj.write, NonSerializableClass()) def test_deserializable(self): fj = FileBSON(self.directory, self.name, []) <|code_end|> , determine the next line of code. You have imports: import os import unittest from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass from g_sorcery.file_bson.file_bson import FileBSON and context (class names, function names, or code) available: # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) . Output only the next line.
content = DeserializableClass("1", "2")
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_FileJSON.py ~~~~~~~~~~~~~~~~ FileJSON test suite :copyright: (c) 2013-2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ class TestFileJSON(BaseTest): def setUp(self): super(TestFileJSON, self).setUp() self.directory = os.path.join(self.tempdir.name, 'tst') self.name = 'tst.json' self.path = os.path.join(self.directory, self.name) def test_read_nonexistent(self): <|code_end|> with the help of current file imports: import json import os import unittest from g_sorcery.fileutils import FileJSON from g_sorcery.exceptions import FileJSONError from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass and context from other files: # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) , which may contain function names, class names, or code. Output only the next line.
fj = FileJSON(self.directory, self.name, [])
Here is a snippet: <|code_start|> :license: GPL-2, see LICENSE for more details. """ class TestFileJSON(BaseTest): def setUp(self): super(TestFileJSON, self).setUp() self.directory = os.path.join(self.tempdir.name, 'tst') self.name = 'tst.json' self.path = os.path.join(self.directory, self.name) def test_read_nonexistent(self): fj = FileJSON(self.directory, self.name, []) content = fj.read() self.assertEqual(content, {}) self.assertTrue(os.path.isfile(self.path)) def test_read_nonexistent_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory1", "mandatory2"]) content = fj.read() self.assertEqual(content, {"mandatory1":"", "mandatory2":""}) self.assertTrue(os.path.isfile(self.path)) def test_read_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) os.makedirs(self.directory) with open(self.path, 'w') as f: json.dump({"test":"test"}, f) <|code_end|> . Write the next line using the current file imports: import json import os import unittest from g_sorcery.fileutils import FileJSON from g_sorcery.exceptions import FileJSONError from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass and context from other files: # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) , which may include functions, classes, or code. Output only the next line.
self.assertRaises(FileJSONError, fj.read)
Predict the next line for this snippet: <|code_start|> def test_write_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) self.assertRaises(FileJSONError, fj.write, {"test":"test"}) def test_write_read(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) content = {"mandatory":"1", "test":"2"} fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_serializable(self): fj = FileJSON(self.directory, self.name, []) content = SerializableClass("1", "2") fj.write(content) content_r = fj.read() self.assertEqual(content_r, {"field1":"1", "field2":"2"}) self.assertRaises(TypeError, fj.write, NonSerializableClass()) def test_deserializable(self): fj = FileJSON(self.directory, self.name, []) content = DeserializableClass("1", "2") fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_deserializable_collection(self): fj = FileJSON(self.directory, self.name, []) content1 = DeserializableClass("1", "2") content2 = DeserializableClass("3", "4") <|code_end|> with the help of current file imports: import json import os import unittest from g_sorcery.fileutils import FileJSON from g_sorcery.exceptions import FileJSONError from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass and context from other files: # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) , which may contain function names, class names, or code. Output only the next line.
content = serializable_elist([content1, content2])
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_FileJSON.py ~~~~~~~~~~~~~~~~ FileJSON test suite :copyright: (c) 2013-2015 by Jauhien Piatlicki :license: GPL-2, see LICENSE for more details. """ <|code_end|> , generate the next line using the imports in this file: import json import os import unittest from g_sorcery.fileutils import FileJSON from g_sorcery.exceptions import FileJSONError from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass and context (functions, classes, or occasionally code) from other files: # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) . Output only the next line.
class TestFileJSON(BaseTest):
Predict the next line after this snippet: <|code_start|> def test_read_nonexistent_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory1", "mandatory2"]) content = fj.read() self.assertEqual(content, {"mandatory1":"", "mandatory2":""}) self.assertTrue(os.path.isfile(self.path)) def test_read_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) os.makedirs(self.directory) with open(self.path, 'w') as f: json.dump({"test":"test"}, f) self.assertRaises(FileJSONError, fj.read) def test_write_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) self.assertRaises(FileJSONError, fj.write, {"test":"test"}) def test_write_read(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) content = {"mandatory":"1", "test":"2"} fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_serializable(self): fj = FileJSON(self.directory, self.name, []) content = SerializableClass("1", "2") fj.write(content) content_r = fj.read() self.assertEqual(content_r, {"field1":"1", "field2":"2"}) <|code_end|> using the current file's imports: import json import os import unittest from g_sorcery.fileutils import FileJSON from g_sorcery.exceptions import FileJSONError from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass and any relevant context from other files: # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) . Output only the next line.
self.assertRaises(TypeError, fj.write, NonSerializableClass())
Predict the next line for this snippet: <|code_start|> content = fj.read() self.assertEqual(content, {}) self.assertTrue(os.path.isfile(self.path)) def test_read_nonexistent_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory1", "mandatory2"]) content = fj.read() self.assertEqual(content, {"mandatory1":"", "mandatory2":""}) self.assertTrue(os.path.isfile(self.path)) def test_read_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) os.makedirs(self.directory) with open(self.path, 'w') as f: json.dump({"test":"test"}, f) self.assertRaises(FileJSONError, fj.read) def test_write_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) self.assertRaises(FileJSONError, fj.write, {"test":"test"}) def test_write_read(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) content = {"mandatory":"1", "test":"2"} fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_serializable(self): fj = FileJSON(self.directory, self.name, []) <|code_end|> with the help of current file imports: import json import os import unittest from g_sorcery.fileutils import FileJSON from g_sorcery.exceptions import FileJSONError from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass and context from other files: # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) , which may contain function names, class names, or code. Output only the next line.
content = SerializableClass("1", "2")
Given snippet: <|code_start|> self.assertTrue(os.path.isfile(self.path)) def test_read_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) os.makedirs(self.directory) with open(self.path, 'w') as f: json.dump({"test":"test"}, f) self.assertRaises(FileJSONError, fj.read) def test_write_luck_of_mandatory_key(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) self.assertRaises(FileJSONError, fj.write, {"test":"test"}) def test_write_read(self): fj = FileJSON(self.directory, self.name, ["mandatory"]) content = {"mandatory":"1", "test":"2"} fj.write(content) content_r = fj.read() self.assertEqual(content, content_r) def test_serializable(self): fj = FileJSON(self.directory, self.name, []) content = SerializableClass("1", "2") fj.write(content) content_r = fj.read() self.assertEqual(content_r, {"field1":"1", "field2":"2"}) self.assertRaises(TypeError, fj.write, NonSerializableClass()) def test_deserializable(self): fj = FileJSON(self.directory, self.name, []) <|code_end|> , continue by predicting the next line. Consider current file imports: import json import os import unittest from g_sorcery.fileutils import FileJSON from g_sorcery.exceptions import FileJSONError from g_sorcery.g_collections import serializable_elist from tests.base import BaseTest from tests.serializable import NonSerializableClass, SerializableClass, DeserializableClass and context: # Path: g_sorcery/fileutils.py # class FileJSON(FileJSONData): # """ # Class for JSON files. Supports custom JSON serialization # provided by g_sorcery.serialization. # """ # # def read_content(self): # """ # Read JSON file. # """ # content = {} # with open(self.path, 'r') as f: # content = json.load(f, object_hook=deserializeHook) # return content # # def write_content(self, content): # """ # Write JSON file. # """ # with open(self.path, 'w') as f: # json.dump(content, f, indent=2, sort_keys=True, cls=JSONSerializer) # # Path: g_sorcery/exceptions.py # class FileJSONError(GSorceryError): # pass # # Path: g_sorcery/g_collections.py # class serializable_elist(object): # """ # A JSON serializable version of elist. # """ # # __slots__ = ('data') # # def __init__(self, iterable=None, separator=' '): # ''' # iterable: initialize from iterable's items # separator: string used to join list members with for __str__() # ''' # self.data = elist(iterable or [], separator) # # def __eq__(self, other): # return self.data == other.data # # def __iter__(self): # return iter(self.data) # # def __str__(self): # '''Custom output function # ''' # return str(self.data) # # def append(self, x): # self.data.append(x) # # def serialize(self): # return {"separator": self.data._sep_, "data" : self.data} # # @classmethod # def deserialize(cls, value): # return serializable_elist(value["data"], separator = value["separator"]) # # Path: tests/base.py # class BaseTest(unittest.TestCase): # # def setUp(self): # self.tempdir = TemporaryDirectory() # # def tearDown(self): # del self.tempdir # # Path: tests/serializable.py # class NonSerializableClass(object): # pass # # class SerializableClass(object): # # __slots__ = ("field1", "field2") # # def __init__(self, field1, field2): # self.field1 = field1 # self.field2 = field2 # # def __eq__(self, other): # return self.field1 == other.field1 \ # and self.field2 == other.field2 # # def serialize(self): # return {"field1": self.field1, "field2": self.field2} # # class DeserializableClass(SerializableClass): # # @classmethod # def deserialize(cls, value): # return DeserializableClass(value["field1"], value["field2"]) which might include code, classes, or functions. Output only the next line.
content = DeserializableClass("1", "2")
Using the snippet: <|code_start|> self.template.append("") if hasattr(layout, "vars_after_inherit"): self._append_vars_to_template(layout.vars_after_inherit) self.template.append("") self.template.append('DESCRIPTION="%(description)s"') self.template.append("") if hasattr(layout, "vars_after_description"): self._append_vars_to_template(layout.vars_after_description) self.template.append("") self.template.append('SLOT="0"') self.template.append('KEYWORDS="~amd64 ~x86"') self.template.append("") if hasattr(layout, "vars_after_keywords"): self._append_vars_to_template(layout.vars_after_keywords) self.template.append("") def _append_vars_to_template(self, variables): """ Add a list of variables to the end of template. Args: variables: List of variables. """ for var in variables: <|code_end|> , determine the next line of code. You have imports: from .compatibility import basestring from .exceptions import DependencyError and context (class names, function names, or code) available: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # def __del__(self): # # Path: g_sorcery/exceptions.py # class DependencyError(GSorceryError): # pass . Output only the next line.
if isinstance(var, basestring):
Predict the next line after this snippet: <|code_start|> A hook allowing changing ebuild_data before ebuild generation. Args: ebuild_data: Dictinary with ebuild data. Returns: Dictinary with ebuild data. """ return ebuild_data def process(self, ebuild, ebuild_data): """ Fill ebuild template with data. Args: ebuild: Ebuild template. ebuild_data: Dictionary with ebuild data. Returns: Ebuild source as a list of strings. """ result = [] for line in ebuild: error = "" try: line = line % ebuild_data except ValueError as e: error = str(e) if error: error = "substitution failed in line '" + line + "': " + error <|code_end|> using the current file's imports: from .compatibility import basestring from .exceptions import DependencyError and any relevant context from other files: # Path: g_sorcery/compatibility.py # class TemporaryDirectory(object): # def __init__(self): # def __del__(self): # # Path: g_sorcery/exceptions.py # class DependencyError(GSorceryError): # pass . Output only the next line.
raise DependencyError(error)
Given the following code snippet before the placeholder: <|code_start|> def _consume_done_putters(self): # Delete waiters at the head of the put() queue who've timed out. while self._putters and self._putters[0][1].done(): self._putters.popleft() def qsize(self): """Number of items in the queue.""" return len(self._queue) @property def maxsize(self): """Number of items allowed in the queue.""" return self._maxsize def empty(self): """Return True if the queue is empty, False otherwise.""" return not self._queue def full(self): """Return True if there are maxsize items in the queue. Note: if the Queue was initialized with maxsize=0 (the default), then full() is never True. """ if self._maxsize <= 0: return False else: return self.qsize() >= self._maxsize <|code_end|> , predict the next line using imports from the current file: import collections import heapq from . import events from . import futures from . import locks from .tasks import coroutine and context including class names, function names, and sometimes code from other files: # Path: external/asyncio/tasks.py # def coroutine(func): # """Decorator to mark coroutines. # # If the coroutine is not yielded from before it is destroyed, # an error message is logged. # """ # if inspect.isgeneratorfunction(func): # coro = func # else: # @functools.wraps(func) # def coro(*args, **kw): # res = func(*args, **kw) # if isinstance(res, futures.Future) or inspect.isgenerator(res): # res = yield from res # return res # # if not _DEBUG: # wrapper = coro # else: # @functools.wraps(func) # def wrapper(*args, **kwds): # w = CoroWrapper(coro(*args, **kwds), func) # w.__name__ = func.__name__ # if _PY35: # w.__qualname__ = func.__qualname__ # w.__doc__ = func.__doc__ # return w # # wrapper._is_coroutine = True # For iscoroutinefunction(). # return wrapper . Output only the next line.
@coroutine
Based on the snippet: <|code_start|> fname_noext, ext = os.path.splitext(filename) for part in dirname.strip('/').split(os.path.sep)[2:][-2:] + [fname_noext]: for match in PATH_SPLIT.split(part): if match: yield match # FIXME: this is flawed. Can use placeholders by taking a n-tuple and # replacing ? to (?, ?, ..., n) and then extend the query params list with the # given tuple/list value. def _list_to_printable(value): """ Takes a list of mixed types and outputs a unicode string. For example, a list [42, 'foo', None, "foo's' string"], this returns the string: (42, 'foo', NULL, 'foo''s'' string') Single quotes are escaped as ''. This is suitable for use in SQL queries. """ fixed_items = [] for item in value: if isinstance(item, (int, float)): fixed_items.append(str(item)) elif item == None: fixed_items.append("NULL") elif isinstance(item, UNICODE_TYPE): fixed_items.append("'%s'" % item.replace("'", "''")) elif isinstance(item, BYTES_TYPE): <|code_end|> , predict the immediate next line with the help of imports: import sys import os import time import re import logging import math import copyreg import pickle import struct import _weakref import threading import functools import string import sqlite3 as sqlite import asyncio import io import _objectrow from .utils import tostr and context (classes, functions, sometimes code) from other files: # Path: stagehand/toolbox/utils.py # def tostr(value, encoding=None, desperate=True, coerce=False, fs=False): # """ # Convert (if necessary) the given value to a unicode string. # # :param value: the value to be converted to a unicode string # :param encoding: the character set to first try to decode as; if None, will # use the system default (from the locale). # :type encoding: str # :param desperate: if True and decoding to the given (or default) charset # fails, will also try utf-8 and latin-1 (in that order), # and if those fail, will decode as the preferred charset, # replacing unknown characters with \\\\uFFFD. # :type desperate: bool # :param coerce: if True, will coerce numeric types to a unicode string; if # False, such values will be returned untouched. # :type coerce: bool # :param fs: indicates value is a file name or other environment string; if True, # the encoding (if not explicitly specified) will be the encoding # given by ``sys.getfilesystemencoding()`` and the error handler # used will be ``surrogateescape`` if supported. # :type fs: bool # :returns: the value as a unicode string, or the original value if coerce is # False and the value was not a bytes or string. # """ # if isinstance(value, str): # # Nothing to do. # return value # elif isinstance(value, (int, float)): # return str(value) if coerce else value # elif not isinstance(value, (bytearray, bytes)): # # Need to coerce this value. Try the direct approach. # try: # return str(value) # except UnicodeError: # # Could be that value.__repr__ returned a non-unicode and # # non-8bit-clean string. Be a bit more brute force about it. # return tostr(repr(value), desperate=desperate) # # errors = 'strict' # if fs: # if not encoding: # encoding = sys.getfilesystemencoding() # errors = 'surrogateescape' # # # We now have a bytes object to decode. # for c in (encoding or ENCODING, 'utf-8', 'latin-1'): # try: # return value.decode(c, errors) # except UnicodeError: # pass # if not desperate: # raise UnicodeError("Couldn't decode value to unicode (and not desperate enough to keep trying)") # # return value.decode(encoding or ENCODING, 'replace') . Output only the next line.
fixed_items.append("'%s'" % tostr(item.replace("'", "''")))
Given the code snippet: <|code_start|>def win32_version_error(): """ Pops up a message box on Windows indicating the Python version is incompatible. """ if sys.hexversion >= 0x03000000: # Python 3 strings are unicode, so use the Unicode variant. MessageBox = windll.user32.MessageBoxW else: # Python 2 strings are non-unicode, so use the ANSI variant. MessageBox = windll.user32.MessageBoxA ver = sys.version.split()[0] MessageBox(None, 'Stagehand requires Python 3.3 or later, but you have %s.\n\n' 'You can download Python at www.python.org.' % ver, 'Incompatible Python Version', 0x00000010) # Are we running a new enough Python? if sys.hexversion < 0x03030000: if sys.platform == 'win32': win32_version_error() else: print('fatal: Python 3.3 or later is required') print('\nNote you can always run stagehand directly through an interpreter:') print('$ python3.4 {}'.format(sys.argv[0])) sys.exit(1) # If we get this far, preflight checks pass. Let's start. <|code_end|> , generate the next line using the imports in this file: import sys import os import stagehand from ctypes import windll from stagehand.main import main and context (functions, classes, or occasionally code) from other files: # Path: stagehand/main.py # def main(): # p = FullHelpParser(prog='stagehand') # p.add_argument('-q', '--quiet', dest='quiet', action='store_true', # help='disable all logging') # p.add_argument('-v', '--verbose', dest='verbose', action='append_const', default=[], const=1, # help='log more detail (twice or thrice logs even more)') # p.add_argument('-b', '--bg', dest='background', action='store_true', # help='run stagehand in the background (daemonize)') # p.add_argument('-p', '--port', dest='port', action='store', type=int, default=0, # help='port the embedded webserver listens on (default is %d)' % config.web.port) # p.add_argument('-d', '--data', dest='data', action='store', metavar='PATH', # help="path to Stagehand's static data directory") # p.add_argument('-s', '--stop', dest='stop', action='store_true', # help='stop a currently running instance of Stagehand') # p.add_argument('--version', action='version', version='%(prog)s ' + __version__) # args = p.parse_args() # # paths = init_default_paths(args.data) # # if os.path.exists(paths.config): # config.load(paths.config) # if config.misc.logdir != config.misc.logdir.default: # # If logdir configurable is non-default, then apply it. # paths.logs = build_path(config.misc.logdir) # # create_paths(paths) # # handler = logging.FileHandler(os.path.join(paths.logs, 'stagehand.log')) # handler.setFormatter(logging.getLogger().handlers[0].formatter) # logging.getLogger().addHandler(handler) # # handler = logging.FileHandler(os.path.join(paths.logs, 'http.log')) # handler.setFormatter(logging.getLogger().handlers[0].formatter) # logging.getLogger('stagehand.http').addHandler(handler) # # if args.stop: # if call_rest_api('/api/shutdown') is None: # log.info('Stagehand is not running.') # return # # # # Make sure Stagehand isn't already running. # if call_rest_api('/api/pid') is not None: # return log.error('Stagehand is already running') # # # # Default log levels. # # # XXX: these should be INFO, WARNING, INFO but increase levels temporarily # # for development. # log.setLevel(logging.DEBUG) # logging.getLogger('stagehand.http').setLevel(logging.INFO) # logging.getLogger('http').setLevel(logging.DEBUG) # # if args.quiet: # log.setLevel(logging.CRITICAL) # elif len(args.verbose) == 1: # log.setLevel(logging.DEBUG) # logging.getLogger('stagehand.web').setLevel(logging.INFO) # elif len(args.verbose) >= 2: # log.setLevel(logging.DEBUG2) # if len(args.verbose) == 3: # logging.getLogger('stagehand.web').setLevel(logging.DEBUG2) # logging.getLogger('stagehand.http').setLevel(logging.DEBUG) # else: # logging.getLogger('stagehand.web').setLevel(logging.DEBUG) # logging.getLogger('stagehand.http').setLevel(logging.INFO) # # httplog = logging.getLogger('stagehand.http') # handler = logging.StreamHandler() # handler.setFormatter(logging.Formatter('%(asctime)s [HTTP] %(message)s')) # httplog.addHandler(handler) # httplog.propagate = False # # if args.background: # daemonize(chdir=None) # # loop = asyncio.get_event_loop() # mgr = Manager(paths, loop=loop) # # Take care to start platform plugins before any logging is done. At least # # for win32, for reasons yet unclear, it seems that performing any output # # before the window is created can cause it to fail. # loop.run_until_complete(platform.start(mgr)) # # log.info('starting Stagehand %s', __version__) # # config.web.add_monitor(functools.partial(web_config_changed, mgr, args)) # asyncio.async(web_start_server(mgr, args)) # asyncio.async(mgr.start()) # # if sys.platform != 'win32': # loop.add_signal_handler(signal.SIGHUP, reload, mgr) # loop.add_signal_handler(signal.SIGUSR1, resync, mgr) # # try: # loop.run_forever() # finally: # mgr.commit() # platform.stop() # # Return manager for interactive interpreter # return mgr . Output only the next line.
main()
Using the snippet: <|code_start|> idlen = struct.unpack('<B', s[pos:pos+1])[0] idstring = s[pos+1:pos+1+idlen] idstring = str(idstring, 'utf-16').replace('\0', '') log.debug("Language: %d/%d: %s" % (i+1, count, idstring)) self._languages.append(idstring) pos += 1+idlen elif guid == GUIDS['ASF_Stream_Bitrate_Properties_Object']: # This record contains stream bitrate with payload overhead. For # audio streams, we should have the average bitrate from # ASF_Stream_Properties_Object. For video streams, we get it from # ASF_Extended_Stream_Properties_Object. So this record is not # used. pass elif guid == GUIDS['ASF_Content_Encryption_Object'] or \ guid == GUIDS['ASF_Extended_Content_Encryption_Object']: self._set('encrypted', True) else: # Just print the type: for h in list(GUIDS.keys()): if GUIDS[h] == guid: log.debug("Unparsed %s [%d]" % (h,objsize)) break else: u = "%.8X-%.4X-%.4X-%.2X%.2X-%s" % guid log.debug("unknown: len=%d [%d]" % (len(u), objsize)) return r <|code_end|> , determine the next line of code. You have imports: import struct import uuid import string import logging from . import core from ..audio import core as audiocore and context (class names, function names, or code) available: # Path: external/metadata/audio/core.py # AUDIOCORE = ['channels', 'samplerate', 'length', 'encoder', 'codec', 'format', # 'samplebits', 'bitrate', 'fourcc', 'trackno', 'id', 'userdate', # 'enabled', 'default', 'codec_private' ] # MUSICCORE = ['trackof', 'album', 'genre', 'discs', 'thumbnail' ] # class Audio(Media): # class Music(Audio): # def _finalize(self): . Output only the next line.
class AsfAudio(audiocore.Audio):
Given the following code snippet before the placeholder: <|code_start|> def _do_close_connection(wr, connection=connection, msg=msg): warnings.warn(msg, ResourceWarning) connection.close() self._connection_wr = weakref.ref(self, _do_close_connection) @asyncio.coroutine def start(self, connection, read_until_eof=False): """Start response processing.""" self._setup_connection(connection) while True: httpstream = self._reader.set_parser(self._response_parser) # read response self.message = yield from httpstream.read() if self.message.code != 100: break if self._continue is not None and not self._continue.done(): self._continue.set_result(True) self._continue = None # response status self.version = self.message.version self.status = self.message.code self.reason = self.message.reason # headers <|code_end|> , predict the next line using imports from the current file: import asyncio import base64 import collections import http.cookies import json import io import inspect import itertools import logging import mimetypes import os import random import time import uuid import urllib.parse import weakref import warnings import aiohttp from .multidict import CaseInsensitiveMultiDict, MultiDict, MutableMultiDict and context including class names, function names, and sometimes code from other files: # Path: external/aiohttp/multidict.py # class CaseInsensitiveMultiDict(MultiDict): # """Case insensitive multi dict.""" # # def getall(self, key, default=_marker): # return super().getall(key.upper(), default) # # def get(self, key, default=None): # key = key.upper() # if key in self._items and self._items[key]: # return self._items[key][0] # else: # return default # # def getone(self, key): # return self._items[key.upper()][0] # # def __getitem__(self, key): # return self._items[key.upper()][0] # # def __contains__(self, key): # return key.upper() in self._items # # class MultiDict(abc.Mapping): # """Read-only ordered dictionary that can hava multiple values for each key. # # This type of MultiDict must be used for request headers and query args. # """ # # def __init__(self, *args, **kwargs): # if len(args) > 1: # raise TypeError("MultiDict takes at most 2 positional " # "arguments ({} given)".format(len(args) + 1)) # self._items = OrderedDict() # if args: # if hasattr(args[0], 'items'): # args = list(args[0].items()) # else: # args = list(args[0]) # # for key, value in chain(args, kwargs.items()): # if key in self._items: # self._items[key].append(value) # else: # self._items[key] = [value] # # def get(self, key, default=None): # """Return first value stored at key.""" # if key in self._items and self._items[key]: # return self._items[key][0] # else: # return default # # def getall(self, key, default=_marker): # """Returns all values stored at key as a tuple. # # Raises KeyError if key doesn't exist.""" # if key in self._items: # return tuple(self._items[key]) # else: # if default is not _marker: # return default # else: # raise KeyError(key) # # def getone(self, key): # """Return first value stored at key.""" # return self._items[key][0] # # # extra methods # # # def copy(self): # """Returns a copy itself.""" # cls = self.__class__ # return cls(self.items(getall=True)) # # # Mapping interface # # # def __getitem__(self, key): # return self._items[key][0] # # def __iter__(self): # return iter(self._items) # # def __len__(self): # return len(self._items) # # def items(self, *, getall=False): # return _ItemsView(self._items, getall=getall) # # def values(self, *, getall=False): # return _ValuesView(self._items, getall=getall) # # def __eq__(self, other): # if not isinstance(other, abc.Mapping): # return NotImplemented # if isinstance(other, MultiDict): # return self._items == other._items # return dict(self.items()) == dict(other.items()) # # def __contains__(self, key): # return key in self._items # # def __repr__(self): # return '<{} {!r}>'.format(self.__class__.__name__, self._items) # # class MutableMultiDict(BaseMutableMultiDict, MultiDict): # """An ordered dictionary that can have multiple values for each key.""" . Output only the next line.
self.headers = CaseInsensitiveMultiDict(
Using the snippet: <|code_start|> if isinstance(params, dict): params = list(params.items()) # for GET request include data to query params if data and self.method in self.GET_METHODS: if isinstance(data, dict): data = data.items() params = list(itertools.chain(params or (), data)) if params: params = urllib.parse.urlencode(params) if query: query = '%s&%s' % (query, params) else: query = params if not self.using_proxy: scheme = '' netloc = '' self.path = urllib.parse.urlunsplit( (scheme, netloc, urllib.parse.quote(path, safe='/%'), query, fragment)) def update_headers(self, headers): """Update request headers.""" self.headers = MutableMultiDict() if headers: if isinstance(headers, dict): headers = headers.items() <|code_end|> , determine the next line of code. You have imports: import asyncio import base64 import collections import http.cookies import json import io import inspect import itertools import logging import mimetypes import os import random import time import uuid import urllib.parse import weakref import warnings import aiohttp from .multidict import CaseInsensitiveMultiDict, MultiDict, MutableMultiDict and context (class names, function names, or code) available: # Path: external/aiohttp/multidict.py # class CaseInsensitiveMultiDict(MultiDict): # """Case insensitive multi dict.""" # # def getall(self, key, default=_marker): # return super().getall(key.upper(), default) # # def get(self, key, default=None): # key = key.upper() # if key in self._items and self._items[key]: # return self._items[key][0] # else: # return default # # def getone(self, key): # return self._items[key.upper()][0] # # def __getitem__(self, key): # return self._items[key.upper()][0] # # def __contains__(self, key): # return key.upper() in self._items # # class MultiDict(abc.Mapping): # """Read-only ordered dictionary that can hava multiple values for each key. # # This type of MultiDict must be used for request headers and query args. # """ # # def __init__(self, *args, **kwargs): # if len(args) > 1: # raise TypeError("MultiDict takes at most 2 positional " # "arguments ({} given)".format(len(args) + 1)) # self._items = OrderedDict() # if args: # if hasattr(args[0], 'items'): # args = list(args[0].items()) # else: # args = list(args[0]) # # for key, value in chain(args, kwargs.items()): # if key in self._items: # self._items[key].append(value) # else: # self._items[key] = [value] # # def get(self, key, default=None): # """Return first value stored at key.""" # if key in self._items and self._items[key]: # return self._items[key][0] # else: # return default # # def getall(self, key, default=_marker): # """Returns all values stored at key as a tuple. # # Raises KeyError if key doesn't exist.""" # if key in self._items: # return tuple(self._items[key]) # else: # if default is not _marker: # return default # else: # raise KeyError(key) # # def getone(self, key): # """Return first value stored at key.""" # return self._items[key][0] # # # extra methods # # # def copy(self): # """Returns a copy itself.""" # cls = self.__class__ # return cls(self.items(getall=True)) # # # Mapping interface # # # def __getitem__(self, key): # return self._items[key][0] # # def __iter__(self): # return iter(self._items) # # def __len__(self): # return len(self._items) # # def items(self, *, getall=False): # return _ItemsView(self._items, getall=getall) # # def values(self, *, getall=False): # return _ValuesView(self._items, getall=getall) # # def __eq__(self, other): # if not isinstance(other, abc.Mapping): # return NotImplemented # if isinstance(other, MultiDict): # return self._items == other._items # return dict(self.items()) == dict(other.items()) # # def __contains__(self, key): # return key in self._items # # def __repr__(self): # return '<{} {!r}>'.format(self.__class__.__name__, self._items) # # class MutableMultiDict(BaseMutableMultiDict, MultiDict): # """An ordered dictionary that can have multiple values for each key.""" . Output only the next line.
elif isinstance(headers, MultiDict):
Given snippet: <|code_start|> scheme, netloc, path, query, fragment = urllib.parse.urlsplit(self.url) if not path: path = '/' if isinstance(params, dict): params = list(params.items()) # for GET request include data to query params if data and self.method in self.GET_METHODS: if isinstance(data, dict): data = data.items() params = list(itertools.chain(params or (), data)) if params: params = urllib.parse.urlencode(params) if query: query = '%s&%s' % (query, params) else: query = params if not self.using_proxy: scheme = '' netloc = '' self.path = urllib.parse.urlunsplit( (scheme, netloc, urllib.parse.quote(path, safe='/%'), query, fragment)) def update_headers(self, headers): """Update request headers.""" <|code_end|> , continue by predicting the next line. Consider current file imports: import asyncio import base64 import collections import http.cookies import json import io import inspect import itertools import logging import mimetypes import os import random import time import uuid import urllib.parse import weakref import warnings import aiohttp from .multidict import CaseInsensitiveMultiDict, MultiDict, MutableMultiDict and context: # Path: external/aiohttp/multidict.py # class CaseInsensitiveMultiDict(MultiDict): # """Case insensitive multi dict.""" # # def getall(self, key, default=_marker): # return super().getall(key.upper(), default) # # def get(self, key, default=None): # key = key.upper() # if key in self._items and self._items[key]: # return self._items[key][0] # else: # return default # # def getone(self, key): # return self._items[key.upper()][0] # # def __getitem__(self, key): # return self._items[key.upper()][0] # # def __contains__(self, key): # return key.upper() in self._items # # class MultiDict(abc.Mapping): # """Read-only ordered dictionary that can hava multiple values for each key. # # This type of MultiDict must be used for request headers and query args. # """ # # def __init__(self, *args, **kwargs): # if len(args) > 1: # raise TypeError("MultiDict takes at most 2 positional " # "arguments ({} given)".format(len(args) + 1)) # self._items = OrderedDict() # if args: # if hasattr(args[0], 'items'): # args = list(args[0].items()) # else: # args = list(args[0]) # # for key, value in chain(args, kwargs.items()): # if key in self._items: # self._items[key].append(value) # else: # self._items[key] = [value] # # def get(self, key, default=None): # """Return first value stored at key.""" # if key in self._items and self._items[key]: # return self._items[key][0] # else: # return default # # def getall(self, key, default=_marker): # """Returns all values stored at key as a tuple. # # Raises KeyError if key doesn't exist.""" # if key in self._items: # return tuple(self._items[key]) # else: # if default is not _marker: # return default # else: # raise KeyError(key) # # def getone(self, key): # """Return first value stored at key.""" # return self._items[key][0] # # # extra methods # # # def copy(self): # """Returns a copy itself.""" # cls = self.__class__ # return cls(self.items(getall=True)) # # # Mapping interface # # # def __getitem__(self, key): # return self._items[key][0] # # def __iter__(self): # return iter(self._items) # # def __len__(self): # return len(self._items) # # def items(self, *, getall=False): # return _ItemsView(self._items, getall=getall) # # def values(self, *, getall=False): # return _ValuesView(self._items, getall=getall) # # def __eq__(self, other): # if not isinstance(other, abc.Mapping): # return NotImplemented # if isinstance(other, MultiDict): # return self._items == other._items # return dict(self.items()) == dict(other.items()) # # def __contains__(self, key): # return key in self._items # # def __repr__(self): # return '<{} {!r}>'.format(self.__class__.__name__, self._items) # # class MutableMultiDict(BaseMutableMultiDict, MultiDict): # """An ordered dictionary that can have multiple values for each key.""" which might include code, classes, or functions. Output only the next line.
self.headers = MutableMultiDict()
Next line prediction: <|code_start|>#!/usr/bin/env python3 NAME = 'stagehand' VERSION = '0.3.2' # Import a couple modules from the source tree needed to build, but disable # generation of spurious pyc files. sys.dont_write_bytecode = True sys.dont_write_bytecode = False if sys.hexversion < 0x03030000: print('fatal: Python 3.3 or later is required') sys.exit(1) class build_py(_build_py): def build_packages(self): super().build_packages() # Dynamically create script for non-zip installs. with open(os.path.join('build', 'stagehand'), 'w') as f: f.write('#!/usr/bin/env python3\nimport stagehand.bootstrap\n') for package in self.packages: package_dir = self.get_package_dir(package) for f in glob.glob(os.path.join(package_dir, '*.cxml')): module = os.path.splitext(os.path.basename(f))[0] outfile = self.get_module_outfile(self.build_lib, package.split('.'), module) log.info('generating %s -> %s', f, outfile) <|code_end|> . Use current file imports: (import sys import os import platform import glob import shutil from distutils.command.build_scripts import build_scripts as _build_scripts from distutils.command.build_py import build_py as _build_py from distutils.cmd import Command from distutils.core import setup from distutils import log from stagehand.toolbox import xmlconfig from stagehand import coffee) and context including class names, function names, or small code snippets from other files: # Path: stagehand/toolbox/xmlconfig.py # def get_value(value, type): # def format_content(node): # def nodefilter(node, *names): # def __init__(self, package): # def _get_schema(self, node): # def parse(self, node, fd, deep=''): # def _parse_var(self, node, fd, deep, first, defaults_list): # def _parse_config(self, node, fd, deep, first, defaults): # def _parse_group(self, node, fd, deep, first, defaults): # def _parse_list(self, node, fd, deep, first, defaults): # def _parse_dict(self, node, fd, deep, first, defaults): # def _convert(xml, out, package, cfgmodule): # def convert(infile, outfile, package, cfgmodule='config'): # def to_code(xml, package=None, cfgmodule='config'): # def to_object(xml, package=None, cfgmodule='config'): # class Parser: # # Path: stagehand/coffee.py # class CSCompileError(ValueError): # def cscompile(src, dst=None, is_html=None): # def subfunc(match): # def cscompile_with_cache(src, cachedir, is_html=None): . Output only the next line.
xmlconfig.convert(f, outfile, package, 'stagehand.toolbox.config')
Using the snippet: <|code_start|> def _compile_coffee(self): # If the user extracts a tarball without preserving mtime, it may be possible # for a not-actually-stale compiled coffee file to have a slightly older mtime # than the source. Here we determine the mtimes of newest and oldest data # files and if the range is within 10 seconds we assume that's the case and # avoid compiling, since we don't want to require users to have coffee # installed. oldest = newest = 0 for path, files in self.distribution.data_files: for f in files: age = os.path.getmtime(f) oldest = min(oldest, age) or age newest = max(newest, age) or age # Assume untarring isn't going to take more than 10 seconds, so if # the range is within this then we don't compile. force_no_compile = newest - oldest < 10 for path, files in self.distribution.data_files: for f in files: if os.path.splitext(f)[1] not in ('.tmpl', '.coffee'): continue fc = f + '.compiled' if os.path.exists(fc) and force_no_compile: # Touch the compiled file to ensure it is newer than the source. os.utime(fc, None) elif not os.path.exists(fc) or os.path.getmtime(f) > os.path.getmtime(fc): is_html = False if f.endswith('.coffee') else True print('compiling coffeescript %s -> %s' % (f, fc)) try: <|code_end|> , determine the next line of code. You have imports: import sys import os import platform import glob import shutil from distutils.command.build_scripts import build_scripts as _build_scripts from distutils.command.build_py import build_py as _build_py from distutils.cmd import Command from distutils.core import setup from distutils import log from stagehand.toolbox import xmlconfig from stagehand import coffee and context (class names, function names, or code) available: # Path: stagehand/toolbox/xmlconfig.py # def get_value(value, type): # def format_content(node): # def nodefilter(node, *names): # def __init__(self, package): # def _get_schema(self, node): # def parse(self, node, fd, deep=''): # def _parse_var(self, node, fd, deep, first, defaults_list): # def _parse_config(self, node, fd, deep, first, defaults): # def _parse_group(self, node, fd, deep, first, defaults): # def _parse_list(self, node, fd, deep, first, defaults): # def _parse_dict(self, node, fd, deep, first, defaults): # def _convert(xml, out, package, cfgmodule): # def convert(infile, outfile, package, cfgmodule='config'): # def to_code(xml, package=None, cfgmodule='config'): # def to_object(xml, package=None, cfgmodule='config'): # class Parser: # # Path: stagehand/coffee.py # class CSCompileError(ValueError): # def cscompile(src, dst=None, is_html=None): # def subfunc(match): # def cscompile_with_cache(src, cachedir, is_html=None): . Output only the next line.
coffee.cscompile(f, fc, is_html)
Given the code snippet: <|code_start|> with ASCII equivalents. """ if not u: return u # Double quotes u = u.replace('\u201c', '"').replace('\u201d', '"') # Single quotes u = u.replace('\u2018', "'").replace('\u2019', "'") # Endash u = u.replace('\u2014', '--') # Ellipses u = u.replace('\u2026', '...') return u def remove_stop_words(s): """ Removes (English) stop words from the given string. """ stopwords = 'a', 'the' words = [word for word in s.split() if word.lower() not in stopwords] # Join remaining words and remove whitespace. return ' '.join(words) def cfgdesc2html(item): """ Given a config item, returns the description with paragraph breaks (double newline) converted to <br> for use in HTML. """ <|code_end|> , generate the next line using the imports in this file: import os import sys import re import codecs import xml.sax import xml.sax.saxutils import asyncio import importlib from io import StringIO from zipfile import ZipFile from datetime import datetime from .toolbox.config import get_description from .config import config from .config import config and context (functions, classes, or occasionally code) from other files: # Path: stagehand/toolbox/config.py # def get_description(var): # """ # Get the description for the given config variable or group. # """ # if isinstance(var, (Group, Container)): # return var._desc # elif isinstance(var, VarProxy): # return var._item._desc # elif isinstance(var, Var): # return var._desc # else: # raise ValueError('Supplied config variable is not a config variable') . Output only the next line.
desc = get_description(item)
Given snippet: <|code_start|># Please see the file AUTHORS for a complete list of authors. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MER- # CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # ----------------------------------------------------------------------------- # python imports # kaa imports # extra cdrom parser # get logging object log = logging.getLogger('metadata') class Disc(Collection): _keys = Collection._keys + [ 'mixed', 'label' ] <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from ..core import ParseError, Collection, MEDIA_DISC from ..video.core import VideoStream from . import cdrom and context: # Path: external/metadata/core.py # class ParseError(Exception): # pass # # class Collection(Media): # """ # Collection of Digial Media like CD, DVD, Directory, Playlist # """ # _keys = Media._keys + [ 'id', 'tracks' ] # # def __init__(self): # Media.__init__(self) # self.tracks = [] # # MEDIA_DISC = 'MEDIA_DISC' # # Path: external/metadata/video/core.py # class VideoStream(Media): # """ # Video Tracks in a Multiplexed Container. # """ # _keys = Media._keys + VIDEOCORE # media = MEDIA_VIDEO which might include code, classes, or functions. Output only the next line.
media = MEDIA_DISC
Predict the next line after this snippet: <|code_start|> ('uCallbackMessage', c_uint), ('hIcon', HICON), ('szTip', c_wchar * 128), ('dwState', DWORD), ('dwStateMask', DWORD), ('szInfo', c_wchar * 256), ('uVersion', c_uint), # unioned with uTimeout ('szInfoTitle', c_wchar * 64), ('dwInfoFlags', DWORD), ('guidItem', GUID), ('hBalloonIcon', HICON) ] user32.DefWindowProcW.argtypes = [HWND, c_uint, WPARAM, LPARAM] ID_OPEN = 2000 ID_SETTINGS = 2001 ID_OPEN_TVDIR = 2002 ID_OPEN_LOGS = 2003 ID_EXIT = 2010 class Plugin: def __init__(self, manager): self.manager = manager self.hwnd = None self.running_event = threading.Event() def get_icon_path(self): try: <|code_end|> using the current file's imports: from sys import platform, exit from ctypes import (windll, Structure, sizeof, WINFUNCTYPE, pointer, byref, c_uint, c_int, c_char, c_wchar) from ctypes.wintypes import (HWND, HANDLE, HICON, HBRUSH, HMENU, POINT, LPCWSTR, WPARAM, LPARAM, MSG, RECT, DWORD, WORD) from stagehand.config import config from stagehand.utils import get_file_from_zip from stagehand.toolbox.utils import get_temp_path, tobytes import os import asyncio import webbrowser import threading and any relevant context from other files: # Path: stagehand/utils.py # def get_file_from_zip(root, filename, ims=None): # try: # zipfile, files = get_file_from_zip.zipfile, get_file_from_zip.files # except AttributeError: # get_file_from_zip.zipfile = zipfile = ZipFile(__loader__.archive) # get_file_from_zip.files = files = dict((i.filename, i) for i in get_file_from_zip.zipfile.infolist()) # # # Don't use os.path.join here because zipfile uses / as a path sep even on # # Windows. # filename = (root.rstrip(os.path.sep) + '/' + filename).replace(os.path.sep, '/') # if filename not in files: # raise FileNotFoundError # # info = files[filename] # mtime = datetime(*info.date_time) # if ims and datetime.utcfromtimestamp(ims) >= mtime: # return info, mtime, None # else: # return info, mtime, zipfile.open(filename) # # Path: stagehand/toolbox/utils.py # def get_temp_path(appname): # try: # return get_temp_path.paths[appname] # except KeyError: # # create tmp directory for the user # base = gettempdir() # try: # user = getpass.getuser() # except Exception: # user = os.getuid() # path = os.path.join(base, '{}-{}'.format(appname, user)) # if not os.path.isdir(path): # try: # os.mkdir(path, 0o0700) # except OSError: # # Probably the directory already exists. Verify. # if not os.path.isdir(path): # raise IOError('Security Error: %s is not a directory, aborted' % path) # # # On non-Windows, verify the permissions. # if sys.platform != 'win32': # if os.path.islink(path): # raise IOError('Security Error: %s is a link, aborted' % path) # if stat.S_IMODE(os.stat(path).st_mode) % 0o01000 != 0o0700: # raise IOError('Security Error: %s has wrong permissions, aborted' % path) # if os.stat(path)[stat.ST_UID] != os.getuid(): # raise IOError('Security Error: %s does not belong to you, aborted' % path) # # get_temp_path.paths[appname] = path # return path # # def tobytes(value, encoding=None, desperate=True, coerce=False, fs=False): # """ # Convert (if necessary) the given value to a "string of bytes", agnostic to # any character encoding. # # :param value: the value to be converted to a string of bytes # :param encoding: the character set to first try to encode to; if None, will # use the system default (from the locale). # :type encoding: str # :param desperate: if True and encoding to the given (or default) charset # fails, will also try utf-8 and latin-1 (in that order), # and if those fail, will encode to the preferred charset, # replacing unknown characters with \\\\uFFFD. # :type desperate: bool # :param coerce: if True, will coerce numeric types to a bytes object; if # False, such values will be returned untouched. # :type coerce: bool # :param fs: indicates value is a file name or other environment string; if True, # the encoding (if not explicitly specified) will be the encoding # given by ``sys.getfilesystemencoding()`` and the error handler # used will be ``surrogateescape`` if supported. # :type fs: bool # :returns: the value as a bytes object, or the original value if coerce is # False and the value was not a bytes or string. # """ # if isinstance(value, bytes): # # Nothing to do. # return value # elif isinstance(value, (int, float)): # return bytes(str(value), 'ascii') if coerce else value # elif not isinstance(value, str): # # Need to coerce to a unicode before converting to bytes. We can't just # # feed it to bytes() in case the default character set can't encode it. # value = tostr(value, coerce=coerce) # # errors = 'strict' # if fs: # if not encoding: # encoding = sys.getfilesystemencoding() # errors = 'surrogateescape' # # for c in (encoding or ENCODING, 'utf-8', 'latin-1'): # try: # return value.encode(c, errors) # except UnicodeError: # pass # if not desperate: # raise UnicodeError("Couldn't encode value to bytes (and not desperate enough to keep trying)") # # return value.encode(encoding or ENCODING, 'replace') . Output only the next line.
info, mtime, f = get_file_from_zip('data', 'win32tray.ico')
Predict the next line for this snippet: <|code_start|> ('dwStateMask', DWORD), ('szInfo', c_wchar * 256), ('uVersion', c_uint), # unioned with uTimeout ('szInfoTitle', c_wchar * 64), ('dwInfoFlags', DWORD), ('guidItem', GUID), ('hBalloonIcon', HICON) ] user32.DefWindowProcW.argtypes = [HWND, c_uint, WPARAM, LPARAM] ID_OPEN = 2000 ID_SETTINGS = 2001 ID_OPEN_TVDIR = 2002 ID_OPEN_LOGS = 2003 ID_EXIT = 2010 class Plugin: def __init__(self, manager): self.manager = manager self.hwnd = None self.running_event = threading.Event() def get_icon_path(self): try: info, mtime, f = get_file_from_zip('data', 'win32tray.ico') except AttributeError: return os.path.join(self.manager.paths.data, 'win32tray.ico') else: <|code_end|> with the help of current file imports: from sys import platform, exit from ctypes import (windll, Structure, sizeof, WINFUNCTYPE, pointer, byref, c_uint, c_int, c_char, c_wchar) from ctypes.wintypes import (HWND, HANDLE, HICON, HBRUSH, HMENU, POINT, LPCWSTR, WPARAM, LPARAM, MSG, RECT, DWORD, WORD) from stagehand.config import config from stagehand.utils import get_file_from_zip from stagehand.toolbox.utils import get_temp_path, tobytes import os import asyncio import webbrowser import threading and context from other files: # Path: stagehand/utils.py # def get_file_from_zip(root, filename, ims=None): # try: # zipfile, files = get_file_from_zip.zipfile, get_file_from_zip.files # except AttributeError: # get_file_from_zip.zipfile = zipfile = ZipFile(__loader__.archive) # get_file_from_zip.files = files = dict((i.filename, i) for i in get_file_from_zip.zipfile.infolist()) # # # Don't use os.path.join here because zipfile uses / as a path sep even on # # Windows. # filename = (root.rstrip(os.path.sep) + '/' + filename).replace(os.path.sep, '/') # if filename not in files: # raise FileNotFoundError # # info = files[filename] # mtime = datetime(*info.date_time) # if ims and datetime.utcfromtimestamp(ims) >= mtime: # return info, mtime, None # else: # return info, mtime, zipfile.open(filename) # # Path: stagehand/toolbox/utils.py # def get_temp_path(appname): # try: # return get_temp_path.paths[appname] # except KeyError: # # create tmp directory for the user # base = gettempdir() # try: # user = getpass.getuser() # except Exception: # user = os.getuid() # path = os.path.join(base, '{}-{}'.format(appname, user)) # if not os.path.isdir(path): # try: # os.mkdir(path, 0o0700) # except OSError: # # Probably the directory already exists. Verify. # if not os.path.isdir(path): # raise IOError('Security Error: %s is not a directory, aborted' % path) # # # On non-Windows, verify the permissions. # if sys.platform != 'win32': # if os.path.islink(path): # raise IOError('Security Error: %s is a link, aborted' % path) # if stat.S_IMODE(os.stat(path).st_mode) % 0o01000 != 0o0700: # raise IOError('Security Error: %s has wrong permissions, aborted' % path) # if os.stat(path)[stat.ST_UID] != os.getuid(): # raise IOError('Security Error: %s does not belong to you, aborted' % path) # # get_temp_path.paths[appname] = path # return path # # def tobytes(value, encoding=None, desperate=True, coerce=False, fs=False): # """ # Convert (if necessary) the given value to a "string of bytes", agnostic to # any character encoding. # # :param value: the value to be converted to a string of bytes # :param encoding: the character set to first try to encode to; if None, will # use the system default (from the locale). # :type encoding: str # :param desperate: if True and encoding to the given (or default) charset # fails, will also try utf-8 and latin-1 (in that order), # and if those fail, will encode to the preferred charset, # replacing unknown characters with \\\\uFFFD. # :type desperate: bool # :param coerce: if True, will coerce numeric types to a bytes object; if # False, such values will be returned untouched. # :type coerce: bool # :param fs: indicates value is a file name or other environment string; if True, # the encoding (if not explicitly specified) will be the encoding # given by ``sys.getfilesystemencoding()`` and the error handler # used will be ``surrogateescape`` if supported. # :type fs: bool # :returns: the value as a bytes object, or the original value if coerce is # False and the value was not a bytes or string. # """ # if isinstance(value, bytes): # # Nothing to do. # return value # elif isinstance(value, (int, float)): # return bytes(str(value), 'ascii') if coerce else value # elif not isinstance(value, str): # # Need to coerce to a unicode before converting to bytes. We can't just # # feed it to bytes() in case the default character set can't encode it. # value = tostr(value, coerce=coerce) # # errors = 'strict' # if fs: # if not encoding: # encoding = sys.getfilesystemencoding() # errors = 'surrogateescape' # # for c in (encoding or ENCODING, 'utf-8', 'latin-1'): # try: # return value.encode(c, errors) # except UnicodeError: # pass # if not desperate: # raise UnicodeError("Couldn't encode value to bytes (and not desperate enough to keep trying)") # # return value.encode(encoding or ENCODING, 'replace') , which may contain function names, class names, or code. Output only the next line.
path = os.path.join(get_temp_path('stagehand'), 'win32tray.ico')
Here is a snippet: <|code_start|> @asyncio.coroutine def parse_xml(what, nest=[]): results = [] def handle(element): info = {} attrs = dict((a, getattr(element, a)) for a in element.attributes) if element.content: results.append((element.tagname, attrs, element.content)) else: for child in element: if child.tagname in nest: handle(child) elif child.content: info[child.tagname] = child.content results.append((element.tagname, attrs, info)) e = ElementParser() e.handle = handle parser = xml.sax.make_parser() parser.setContentHandler(e) if isinstance(what, str) and what.startswith('http'): <|code_end|> . Write the next line using the current file imports: import xml.sax import asyncio from ..toolbox.net import download from ..utils import ElementParser and context from other files: # Path: stagehand/toolbox/net.py # @asyncio.coroutine # def download(url, target=None, resume=True, retry=0, progress=None, noraise=True, **kwargs): # while retry >= 0: # status = 0 # try: # status, response = yield from _download(url, target, resume, progress, **kwargs) # return status, response # except (aiohttp.HttpException, aiohttp.ConnectionError, OSError) as e: # if isinstance(e, aiohttp.HttpException): # status = e.code # if status == 416 and resume: # # Server reported range not satisfiable and we're trying to # # resume. Retry again without resumption without counting # # against the retry counter. # resume = False # continue # elif retry == 0: # # Done retrying, reraise this exception. # if noraise: # return 0, str(e) # else: # raise # errmsg = str(e) # # if status != 0: # errmsg = 'status %d' % status # if status < 500 or status >= 600: # # Not a temporary error that we can retry. We're done. # return status, None # # log.warning('download failed (%d retries left): %s', retry, errmsg) # retry -= 1 # # # We shouldn't actually ever get here. # log.warning('BUG: download retry loop did not terminate properly') # return 0, None # # Path: stagehand/utils.py # class ElementParser(xml.sax.ContentHandler): # """ # Handler for the SAX parser. The member function 'handle' will be # called everytime an element given on init is closed. The parameter # is the tree with this element as root. An element can either have # children or text content. The ElementParser is usefull for simple # xml files found in config files and information like epg data. # """ # def __init__(self, *names): # """ # Create handler with a list of element names. # """ # self._names = names # self._elements = [] # self.attr = {} # # def startElement(self, name, attr): # """ # SAX callback # """ # element = Element(name) # element._attr = dict(attr) # if len(self._elements): # self._elements[-1].append(element) # else: # self.attr = dict(attr) # self._elements.append(element) # # def endElement(self, name): # """ # SAX callback # """ # element = self._elements.pop() # element._content = element._content.strip() # if name in self._names or (not self._names and len(self._elements) == 1): # self.handle(element) # if not self._elements: # self.finalize() # # def characters(self, c): # """ # SAX callback # """ # if len(self._elements): # self._elements[-1]._content += c # # def handle(self, element): # """ # ElementParser callback for a complete element. # """ # pass # # def finalize(self): # """ # ElementParser callback at the end of parsing. # """ # pass , which may include functions, classes, or code. Output only the next line.
status, data = yield from download(what, retry=4)
Using the snippet: <|code_start|> @asyncio.coroutine def parse_xml(what, nest=[]): results = [] def handle(element): info = {} attrs = dict((a, getattr(element, a)) for a in element.attributes) if element.content: results.append((element.tagname, attrs, element.content)) else: for child in element: if child.tagname in nest: handle(child) elif child.content: info[child.tagname] = child.content results.append((element.tagname, attrs, info)) <|code_end|> , determine the next line of code. You have imports: import xml.sax import asyncio from ..toolbox.net import download from ..utils import ElementParser and context (class names, function names, or code) available: # Path: stagehand/toolbox/net.py # @asyncio.coroutine # def download(url, target=None, resume=True, retry=0, progress=None, noraise=True, **kwargs): # while retry >= 0: # status = 0 # try: # status, response = yield from _download(url, target, resume, progress, **kwargs) # return status, response # except (aiohttp.HttpException, aiohttp.ConnectionError, OSError) as e: # if isinstance(e, aiohttp.HttpException): # status = e.code # if status == 416 and resume: # # Server reported range not satisfiable and we're trying to # # resume. Retry again without resumption without counting # # against the retry counter. # resume = False # continue # elif retry == 0: # # Done retrying, reraise this exception. # if noraise: # return 0, str(e) # else: # raise # errmsg = str(e) # # if status != 0: # errmsg = 'status %d' % status # if status < 500 or status >= 600: # # Not a temporary error that we can retry. We're done. # return status, None # # log.warning('download failed (%d retries left): %s', retry, errmsg) # retry -= 1 # # # We shouldn't actually ever get here. # log.warning('BUG: download retry loop did not terminate properly') # return 0, None # # Path: stagehand/utils.py # class ElementParser(xml.sax.ContentHandler): # """ # Handler for the SAX parser. The member function 'handle' will be # called everytime an element given on init is closed. The parameter # is the tree with this element as root. An element can either have # children or text content. The ElementParser is usefull for simple # xml files found in config files and information like epg data. # """ # def __init__(self, *names): # """ # Create handler with a list of element names. # """ # self._names = names # self._elements = [] # self.attr = {} # # def startElement(self, name, attr): # """ # SAX callback # """ # element = Element(name) # element._attr = dict(attr) # if len(self._elements): # self._elements[-1].append(element) # else: # self.attr = dict(attr) # self._elements.append(element) # # def endElement(self, name): # """ # SAX callback # """ # element = self._elements.pop() # element._content = element._content.strip() # if name in self._names or (not self._names and len(self._elements) == 1): # self.handle(element) # if not self._elements: # self.finalize() # # def characters(self, c): # """ # SAX callback # """ # if len(self._elements): # self._elements[-1]._content += c # # def handle(self, element): # """ # ElementParser callback for a complete element. # """ # pass # # def finalize(self): # """ # ElementParser callback at the end of parsing. # """ # pass . Output only the next line.
e = ElementParser()
Given snippet: <|code_start|> return 'RemoteException({})'.format(repr(self._remote_exc)) class RPCError(Exception): pass class NotConnectedError(RPCError): """ Raised when an attempt is made to call a method on a channel that is not connected. """ pass class AuthenticationError(RPCError): pass class InvalidCallError(RPCError): pass class Server: """ RPC server class. RPC servers accept incoming connections from client, however RPC calls can be issued in either direction on channels. """ def __init__(self, auth_secret=b'', *, loop=None): super().__init__() self.signals = Signals('client-connected') <|code_end|> , continue by predicting the next line. Consider current file imports: import types import socket import logging import pickle import struct import sys import hashlib import time import traceback import os import asyncio from .utils import tobytes from .core import Signals and context: # Path: stagehand/toolbox/utils.py # def tobytes(value, encoding=None, desperate=True, coerce=False, fs=False): # """ # Convert (if necessary) the given value to a "string of bytes", agnostic to # any character encoding. # # :param value: the value to be converted to a string of bytes # :param encoding: the character set to first try to encode to; if None, will # use the system default (from the locale). # :type encoding: str # :param desperate: if True and encoding to the given (or default) charset # fails, will also try utf-8 and latin-1 (in that order), # and if those fail, will encode to the preferred charset, # replacing unknown characters with \\\\uFFFD. # :type desperate: bool # :param coerce: if True, will coerce numeric types to a bytes object; if # False, such values will be returned untouched. # :type coerce: bool # :param fs: indicates value is a file name or other environment string; if True, # the encoding (if not explicitly specified) will be the encoding # given by ``sys.getfilesystemencoding()`` and the error handler # used will be ``surrogateescape`` if supported. # :type fs: bool # :returns: the value as a bytes object, or the original value if coerce is # False and the value was not a bytes or string. # """ # if isinstance(value, bytes): # # Nothing to do. # return value # elif isinstance(value, (int, float)): # return bytes(str(value), 'ascii') if coerce else value # elif not isinstance(value, str): # # Need to coerce to a unicode before converting to bytes. We can't just # # feed it to bytes() in case the default character set can't encode it. # value = tostr(value, coerce=coerce) # # errors = 'strict' # if fs: # if not encoding: # encoding = sys.getfilesystemencoding() # errors = 'surrogateescape' # # for c in (encoding or ENCODING, 'utf-8', 'latin-1'): # try: # return value.encode(c, errors) # except UnicodeError: # pass # if not desperate: # raise UnicodeError("Couldn't encode value to bytes (and not desperate enough to keep trying)") # # return value.encode(encoding or ENCODING, 'replace') # # Path: stagehand/toolbox/core.py # class Signals(dict): # """ # A collection of one or more Signal objects, which behaves like a dictionary # (with key order preserved). # # The initializer takes zero or more arguments, where each argument can be a: # * dict (of name=Signal() pairs) or other Signals object # * tuple/list of (name, Signal) tuples # * str representing the name of the signal # """ # def __init__(self, *signals): # super().__init__() # # Preserve order of keys. # self._keys = [] # for s in signals: # if isinstance(s, dict): # # parameter is a dict/Signals object # self.update(s) # self._keys.extend(s.keys()) # elif isinstance(s, str): # # parameter is a string # self[s] = Signal() # self._keys.append(s) # elif isinstance(s, (tuple, list)) and len(s) == 2: # # In form (key, value) # if isinstance(s[0], basestring) and isinstance(s[1], Signal): # self[s[0]] = s[1] # self._keys.append(s[0]) # else: # raise TypeError('With form (k, v), key must be string and v must be Signal') # # else: # # parameter is something else, bad # raise TypeError('signal key must be string') # # # def __delitem__(self, key): # super().__delitem__(key) # self._keys.remove(key) # # # def keys(self): # """ # List of signal names (strings). # """ # return self._keys # # # def values(self): # """ # List of Signal objects. # """ # return [self[k] for k in self._keys] # # # def __add__(self, signals): # return Signals(self, *signals) # # # def add(self, *signals): # """ # Creates a new Signals object by merging all signals defined in # self and the signals specified in the arguments. # # The same types of arguments accepted by the initializer are allowed # here. # """ # return Signals(self, *signals) # # # def subset(self, *names): # """ # Returns a new Signals object by taking a subset of the supplied # signal names. # # The keys of the new Signals object are ordered as specified in the # names parameter. # # >>> yield signals.subset('pass', 'fail').any() # """ # return Signals(*[(k, self[k]) for k in names]) # # # def futures(self): # return [self[k].future() for k in self._keys] # # # def any(self): # return asyncio.wait(self.futures(), return_when=asyncio.FIRST_COMPLETED) # # # def all(self, return_exceptions=True): # return asyncio.gather(*self.futures(), return_exceptions=return_exceptions) which might include code, classes, or functions. Output only the next line.
self._auth_secret = tobytes(auth_secret)
Given snippet: <|code_start|> def __repr__(self): return 'RemoteException({})'.format(repr(self._remote_exc)) class RPCError(Exception): pass class NotConnectedError(RPCError): """ Raised when an attempt is made to call a method on a channel that is not connected. """ pass class AuthenticationError(RPCError): pass class InvalidCallError(RPCError): pass class Server: """ RPC server class. RPC servers accept incoming connections from client, however RPC calls can be issued in either direction on channels. """ def __init__(self, auth_secret=b'', *, loop=None): super().__init__() <|code_end|> , continue by predicting the next line. Consider current file imports: import types import socket import logging import pickle import struct import sys import hashlib import time import traceback import os import asyncio from .utils import tobytes from .core import Signals and context: # Path: stagehand/toolbox/utils.py # def tobytes(value, encoding=None, desperate=True, coerce=False, fs=False): # """ # Convert (if necessary) the given value to a "string of bytes", agnostic to # any character encoding. # # :param value: the value to be converted to a string of bytes # :param encoding: the character set to first try to encode to; if None, will # use the system default (from the locale). # :type encoding: str # :param desperate: if True and encoding to the given (or default) charset # fails, will also try utf-8 and latin-1 (in that order), # and if those fail, will encode to the preferred charset, # replacing unknown characters with \\\\uFFFD. # :type desperate: bool # :param coerce: if True, will coerce numeric types to a bytes object; if # False, such values will be returned untouched. # :type coerce: bool # :param fs: indicates value is a file name or other environment string; if True, # the encoding (if not explicitly specified) will be the encoding # given by ``sys.getfilesystemencoding()`` and the error handler # used will be ``surrogateescape`` if supported. # :type fs: bool # :returns: the value as a bytes object, or the original value if coerce is # False and the value was not a bytes or string. # """ # if isinstance(value, bytes): # # Nothing to do. # return value # elif isinstance(value, (int, float)): # return bytes(str(value), 'ascii') if coerce else value # elif not isinstance(value, str): # # Need to coerce to a unicode before converting to bytes. We can't just # # feed it to bytes() in case the default character set can't encode it. # value = tostr(value, coerce=coerce) # # errors = 'strict' # if fs: # if not encoding: # encoding = sys.getfilesystemencoding() # errors = 'surrogateescape' # # for c in (encoding or ENCODING, 'utf-8', 'latin-1'): # try: # return value.encode(c, errors) # except UnicodeError: # pass # if not desperate: # raise UnicodeError("Couldn't encode value to bytes (and not desperate enough to keep trying)") # # return value.encode(encoding or ENCODING, 'replace') # # Path: stagehand/toolbox/core.py # class Signals(dict): # """ # A collection of one or more Signal objects, which behaves like a dictionary # (with key order preserved). # # The initializer takes zero or more arguments, where each argument can be a: # * dict (of name=Signal() pairs) or other Signals object # * tuple/list of (name, Signal) tuples # * str representing the name of the signal # """ # def __init__(self, *signals): # super().__init__() # # Preserve order of keys. # self._keys = [] # for s in signals: # if isinstance(s, dict): # # parameter is a dict/Signals object # self.update(s) # self._keys.extend(s.keys()) # elif isinstance(s, str): # # parameter is a string # self[s] = Signal() # self._keys.append(s) # elif isinstance(s, (tuple, list)) and len(s) == 2: # # In form (key, value) # if isinstance(s[0], basestring) and isinstance(s[1], Signal): # self[s[0]] = s[1] # self._keys.append(s[0]) # else: # raise TypeError('With form (k, v), key must be string and v must be Signal') # # else: # # parameter is something else, bad # raise TypeError('signal key must be string') # # # def __delitem__(self, key): # super().__delitem__(key) # self._keys.remove(key) # # # def keys(self): # """ # List of signal names (strings). # """ # return self._keys # # # def values(self): # """ # List of Signal objects. # """ # return [self[k] for k in self._keys] # # # def __add__(self, signals): # return Signals(self, *signals) # # # def add(self, *signals): # """ # Creates a new Signals object by merging all signals defined in # self and the signals specified in the arguments. # # The same types of arguments accepted by the initializer are allowed # here. # """ # return Signals(self, *signals) # # # def subset(self, *names): # """ # Returns a new Signals object by taking a subset of the supplied # signal names. # # The keys of the new Signals object are ordered as specified in the # names parameter. # # >>> yield signals.subset('pass', 'fail').any() # """ # return Signals(*[(k, self[k]) for k in names]) # # # def futures(self): # return [self[k].future() for k in self._keys] # # # def any(self): # return asyncio.wait(self.futures(), return_when=asyncio.FIRST_COMPLETED) # # # def all(self, return_exceptions=True): # return asyncio.gather(*self.futures(), return_exceptions=return_exceptions) which might include code, classes, or functions. Output only the next line.
self.signals = Signals('client-connected')
Given the code snippet: <|code_start|> """ Strips punctutation and (optionally) parentheticals from a title to improve searching. :param title: the string to massage :param apostrophe: one of the CLEAN_APOSTROPHE_* constants (below) :param parens: if True, remove anything inside round parens. Otherwise, the parens will be stripped but the contents left. *apostrophe* can be: * CLEAN_APOSTROPHE_LEAVE: don't do anything: foo's -> foo's * CLEAN_APOSTROPHE_REMOVE: strip them: foo's -> foos * CLEAN_APOSTROPHE_REGEXP: convert to regexp: foo's -> (foos|foo's) """ if parens: # Remove anything in parens from the title (e.g. "The Office (US)") title = re.sub(r'\s*\([^)]*\)', '', title) # Substitute certain punctuation with spaces title = re.sub(r'[&()\[\]*+,-./:;<=>?@\\^_{|}"]', ' ', title) # And outright remove others title = re.sub(r'[!"#$%:;<=>`]', '', title) # Treat apostrophe separately if apostrophe == self.CLEAN_APOSTROPHE_REMOVE: title = title.replace("'", '') elif apostrophe == self.CLEAN_APOSTROPHE_REGEXP: # Replace "foo's" with "(foos|foo's)" def replace_apostrophe(match): return '(%s|%s)' % (match.group(1).replace("'", ''), match.group(1)) title = re.sub(r"(\S+'\S*)", replace_apostrophe, title) <|code_end|> , generate the next line using the imports in this file: import os import re import asyncio import functools import logging from ..config import config from ..utils import remove_stop_words from . import plugins and context (functions, classes, or occasionally code) from other files: # Path: stagehand/utils.py # def remove_stop_words(s): # """ # Removes (English) stop words from the given string. # """ # stopwords = 'a', 'the' # words = [word for word in s.split() if word.lower() not in stopwords] # # Join remaining words and remove whitespace. # return ' '.join(words) . Output only the next line.
title = remove_stop_words(title)
Given the code snippet: <|code_start|># # file: gadgetize.py # input a file with a compiled circuit (h,s,CNOT,t) only # output stabilizer projectors g(x,y) and h(x) # # count the number of random bits to generate # this is the number of Ts plus measured ancillas # assumes circuit consists only of gates in the gate set, i.e. is compiled def countY(circuit): Ts = 0 Tcache = [] # recent T gates to check for any consecutive Ts Ms = [] MTs = [] # measurements depending on which a T is performed # depending on postselection we might not need those T # these are not counted in Ts variable lineNr = 0 for line in circuit.splitlines(): lineNr += 1 <|code_end|> , generate the next line using the imports in this file: from libcirc.compile.compilecirc import standardGate import numpy as np and context (functions, classes, or occasionally code) from other files: # Path: libcirc/compile/compilecirc.py # def standardGate(line, listMode=False, lineMode=False): # if line == "main": # if listMode or lineMode: # raise ValueError("Can't bring 'main' into list form.") # return "main" # # if not lineMode: # toRemove = ["_", "M"] # for r in toRemove: # line = line.replace(r, "") # # elems = [] # for letter in line: # if not letter.islower(): elems.append(letter) # else: elems = elems[:-1] + [elems[-1] + letter] # # if lineMode: return elems # if listMode: return sorted(elems) # return "".join(sorted(elems)) . Output only the next line.
gate = standardGate(line, lineMode=True)
Next line prediction: <|code_start|>checking is not being performed.""" _LOGGER = logging.getLogger(__name__) def do_nothing(): """Simple default callback.""" def header_required(response, name, get_headers, callback=do_nothing): """Checks that a specific header is in a headers dictionary. Args: response (object): An HTTP response object, expected to have a ``headers`` attribute that is a ``Mapping[str, str]``. name (str): The name of a required header. get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers from an HTTP response. callback (Optional[Callable]): A callback that takes no arguments, to be executed when an exception is being raised. Returns: str: The desired header. Raises: ~google.resumable_media.common.InvalidResponse: If the header is missing. """ headers = get_headers(response) if name not in headers: callback() <|code_end|> . Use current file imports: (import base64 import hashlib import logging import random import warnings import google_crc32c # type: ignore import crcmod # type: ignore from urllib.parse import parse_qs from urllib.parse import urlencode from urllib.parse import urlsplit from urllib.parse import urlunsplit from google.resumable_media import common) and context including class names, function names, or small code snippets from other files: # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): . Output only the next line.
raise common.InvalidResponse(
Continue the code snippet: <|code_start|> Returns: object: The return value of ``func``. """ total_sleep = 0.0 num_retries = 0 # base_wait will be multiplied by the multiplier on the first retry. base_wait = float(retry_strategy.initial_delay) / retry_strategy.multiplier # Set the retriable_exception_type if possible. We expect requests to be # present here and the transport to be using requests.exceptions errors, # but due to loose coupling with the transport layer we can't guarantee it. while True: # return on success or when retries exhausted. error = None try: response = func() except _CONNECTION_ERROR_CLASSES as e: error = e # Fall through to retry, if there are retries left. except common.InvalidResponse as e: # An InvalidResponse is only retriable if its status code matches. # The `process_response()` method on a Download or Upload method # will convert the status code into an exception. if get_status_code(e.response) in common.RETRYABLE: error = e # Fall through to retry, if there are retries left. else: raise # If the status code is not retriable, raise w/o retry. else: return response <|code_end|> . Use current file imports: import requests.exceptions import urllib3.exceptions # type: ignore import time from google.resumable_media import common from google.resumable_media import _helpers and context (classes, functions, or code) from other files: # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): # # Path: google/resumable_media/_helpers.py # RANGE_HEADER = "range" # CONTENT_RANGE_HEADER = "content-range" # _SLOW_CRC32C_WARNING = ( # "Currently using crcmod in pure python form. This is a slow " # "implementation. Python 3 has a faster implementation, `google-crc32c`, " # "which will be used if it is installed." # ) # _GENERATION_HEADER = "x-goog-generation" # _HASH_HEADER = "x-goog-hash" # _MISSING_CHECKSUM = """\ # No {checksum_type} checksum was returned from the service while downloading {} # (which happens for composite objects), so client-side content integrity # checking is not being performed.""" # _LOGGER = logging.getLogger(__name__) # def do_nothing(): # def header_required(response, name, get_headers, callback=do_nothing): # def require_status_code(response, status_codes, get_status_code, callback=do_nothing): # def calculate_retry_wait(base_wait, max_sleep, multiplier=2.0): # def _get_crc32c_object(): # def _is_fast_crcmod(): # def _get_metadata_key(checksum_type): # def prepare_checksum_digest(digest_bytestring): # def _get_expected_checksum(response, get_headers, media_url, checksum_type): # def _parse_checksum_header(header_value, response, checksum_label): # def _get_checksum_object(checksum_type): # def _parse_generation_header(response, get_headers): # def _get_generation_from_url(media_url): # def add_query_parameters(media_url, query_params): # def update(self, unused_chunk): # class _DoNothingHash(object): . Output only the next line.
base_wait, wait_time = _helpers.calculate_retry_wait(
Given the code snippet: <|code_start|> def test_do_nothing(): ret_val = _helpers.do_nothing() assert ret_val is None class Test_header_required(object): def _success_helper(self, **kwargs): name = "some-header" value = "The Right Hand Side" headers = {name: value, "other-name": "other-value"} response = mock.Mock( _headers=headers, headers=headers, spec=["_headers", "headers"] ) result = _helpers.header_required(response, name, _get_headers, **kwargs) assert result == value def test_success(self): self._success_helper() def test_success_with_callback(self): callback = mock.Mock(spec=[]) self._success_helper(callback=callback) callback.assert_not_called() def _failure_helper(self, **kwargs): response = mock.Mock(_headers={}, headers={}, spec=["_headers", "headers"]) name = "any-name" <|code_end|> , generate the next line using the imports in this file: import http.client import mock import pytest # type: ignore from google._async_resumable_media import _helpers from google.resumable_media import common and context (functions, classes, or occasionally code) from other files: # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): . Output only the next line.
with pytest.raises(common.InvalidResponse) as exc_info:
Given the following code snippet before the placeholder: <|code_start|> class TestRawRequestsMixin(object): def test__get_body_wo_content_consumed(self): body = b"This is the payload." raw = mock.Mock(spec=["stream"]) raw.stream.return_value = iter([body]) response = mock.Mock(raw=raw, _content=False, spec=["raw", "_content"]) assert body == _request_helpers.RawRequestsMixin._get_body(response) raw.stream.assert_called_once_with( _request_helpers._SINGLE_GET_CHUNK_SIZE, decode_content=False ) def test__get_body_w_content_consumed(self): body = b"This is the payload." response = mock.Mock(_content=body, spec=["_content"]) assert body == _request_helpers.RawRequestsMixin._get_body(response) def _make_response(status_code): return mock.Mock(status_code=status_code, spec=["status_code"]) def _get_status_code(response): return response.status_code class Test_wait_and_retry(object): def test_success_no_retry(self): truthy = http.client.OK <|code_end|> , predict the next line using imports from the current file: import http.client import mock import pytest # type: ignore import requests.exceptions import urllib3.exceptions # type: ignore from google.resumable_media import common from google.resumable_media.requests import _request_helpers and context including class names, function names, and sometimes code from other files: # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): # # Path: google/resumable_media/requests/_request_helpers.py # _DEFAULT_RETRY_STRATEGY = common.RetryStrategy() # _SINGLE_GET_CHUNK_SIZE = 8192 # _DEFAULT_CONNECT_TIMEOUT = 61 # _DEFAULT_READ_TIMEOUT = 60 # _CONNECTION_ERROR_CLASSES = ( # requests.exceptions.ConnectionError, # requests.exceptions.ChunkedEncodingError, # urllib3.exceptions.ProtocolError, # ConnectionError, # Python 3.x only, superclass of ConnectionResetError. # ) # class RequestsMixin(object): # class RawRequestsMixin(RequestsMixin): # def _get_status_code(response): # def _get_headers(response): # def _get_body(response): # def _get_body(response): # def wait_and_retry(func, get_status_code, retry_strategy): . Output only the next line.
assert truthy not in common.RETRYABLE
Given snippet: <|code_start|># Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. EXPECTED_TIMEOUT = (61, 60) class TestRequestsMixin(object): def test__get_status_code(self): status_code = int(http.client.OK) response = _make_response(status_code) <|code_end|> , continue by predicting the next line. Consider current file imports: import http.client import mock import pytest # type: ignore import requests.exceptions import urllib3.exceptions # type: ignore from google.resumable_media import common from google.resumable_media.requests import _request_helpers and context: # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): # # Path: google/resumable_media/requests/_request_helpers.py # _DEFAULT_RETRY_STRATEGY = common.RetryStrategy() # _SINGLE_GET_CHUNK_SIZE = 8192 # _DEFAULT_CONNECT_TIMEOUT = 61 # _DEFAULT_READ_TIMEOUT = 60 # _CONNECTION_ERROR_CLASSES = ( # requests.exceptions.ConnectionError, # requests.exceptions.ChunkedEncodingError, # urllib3.exceptions.ProtocolError, # ConnectionError, # Python 3.x only, superclass of ConnectionResetError. # ) # class RequestsMixin(object): # class RawRequestsMixin(RequestsMixin): # def _get_status_code(response): # def _get_headers(response): # def _get_body(response): # def _get_body(response): # def wait_and_retry(func, get_status_code, retry_strategy): which might include code, classes, or functions. Output only the next line.
assert status_code == _request_helpers.RequestsMixin._get_status_code(response)
Using the snippet: <|code_start|> def test_do_nothing(): ret_val = _helpers.do_nothing() assert ret_val is None class Test_header_required(object): def _success_helper(self, **kwargs): name = "some-header" value = "The Right Hand Side" headers = {name: value, "other-name": "other-value"} response = mock.Mock(headers=headers, spec=["headers"]) result = _helpers.header_required(response, name, _get_headers, **kwargs) assert result == value def test_success(self): self._success_helper() def test_success_with_callback(self): callback = mock.Mock(spec=[]) self._success_helper(callback=callback) callback.assert_not_called() def _failure_helper(self, **kwargs): response = mock.Mock(headers={}, spec=["headers"]) name = "any-name" <|code_end|> , determine the next line of code. You have imports: import hashlib import http.client import mock import pytest # type: ignore from google.resumable_media import _helpers from google.resumable_media import common and context (class names, function names, or code) available: # Path: google/resumable_media/_helpers.py # RANGE_HEADER = "range" # CONTENT_RANGE_HEADER = "content-range" # _SLOW_CRC32C_WARNING = ( # "Currently using crcmod in pure python form. This is a slow " # "implementation. Python 3 has a faster implementation, `google-crc32c`, " # "which will be used if it is installed." # ) # _GENERATION_HEADER = "x-goog-generation" # _HASH_HEADER = "x-goog-hash" # _MISSING_CHECKSUM = """\ # No {checksum_type} checksum was returned from the service while downloading {} # (which happens for composite objects), so client-side content integrity # checking is not being performed.""" # _LOGGER = logging.getLogger(__name__) # def do_nothing(): # def header_required(response, name, get_headers, callback=do_nothing): # def require_status_code(response, status_codes, get_status_code, callback=do_nothing): # def calculate_retry_wait(base_wait, max_sleep, multiplier=2.0): # def _get_crc32c_object(): # def _is_fast_crcmod(): # def _get_metadata_key(checksum_type): # def prepare_checksum_digest(digest_bytestring): # def _get_expected_checksum(response, get_headers, media_url, checksum_type): # def _parse_checksum_header(header_value, response, checksum_label): # def _get_checksum_object(checksum_type): # def _parse_generation_header(response, get_headers): # def _get_generation_from_url(media_url): # def add_query_parameters(media_url, query_params): # def update(self, unused_chunk): # class _DoNothingHash(object): # # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): . Output only the next line.
with pytest.raises(common.InvalidResponse) as exc_info:
Here is a snippet: <|code_start|># Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # async version takes a single timeout, not a tuple of connect, read timeouts. EXPECTED_TIMEOUT = aiohttp.ClientTimeout(connect=61, sock_read=60) class TestRequestsMixin(object): def test__get_status_code(self): status_code = int(http.client.OK) response = _make_response(status_code) <|code_end|> . Write the next line using the current file imports: import http.client import io import aiohttp # type: ignore import mock import pytest # type: ignore from google._async_resumable_media.requests import _request_helpers as _helpers and context from other files: # Path: google/_async_resumable_media/requests/_request_helpers.py # _DEFAULT_RETRY_STRATEGY = common.RetryStrategy() # _SINGLE_GET_CHUNK_SIZE = 8192 # _DEFAULT_CONNECT_TIMEOUT = 61 # _DEFAULT_READ_TIMEOUT = 60 # _DEFAULT_TIMEOUT = aiohttp.ClientTimeout( # connect=_DEFAULT_CONNECT_TIMEOUT, sock_read=_DEFAULT_READ_TIMEOUT # ) # class RequestsMixin(object): # class RawRequestsMixin(RequestsMixin): # def _get_status_code(response): # def _get_headers(response): # async def _get_body(response): # async def _get_body(response): # async def http_request( # transport, # method, # url, # data=None, # headers=None, # retry_strategy=_DEFAULT_RETRY_STRATEGY, # **transport_kwargs # ): , which may include functions, classes, or code. Output only the next line.
assert status_code == _helpers.RequestsMixin._get_status_code(response)
Given the following code snippet before the placeholder: <|code_start|># Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class TestInvalidResponse(object): def test_constructor(self): response = mock.sentinel.response <|code_end|> , predict the next line using imports from the current file: import mock import pytest # type: ignore from google.resumable_media import common and context including class names, function names, and sometimes code from other files: # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): . Output only the next line.
error = common.InvalidResponse(response, 1, "a", [b"m"], True)
Predict the next line for this snippet: <|code_start|> * the URL for the request * the body of the request (always :data:`None`) * headers for the request Raises: ValueError: If the current :class:`Download` has already finished. .. _sans-I/O: https://sans-io.readthedocs.io/ """ if self.finished: raise ValueError("A download can only be used once.") add_bytes_range(self.start, self.end, self._headers) return _GET, self.media_url, None, self._headers def _process_response(self, response): """Process the response from an HTTP request. This is everything that must be done after a request that doesn't require network I/O (or other I/O). This is based on the `sans-I/O`_ philosophy. Args: response (object): The HTTP response object. .. _sans-I/O: https://sans-io.readthedocs.io/ """ # Tombstone the current Download so it cannot be used again. self._finished = True <|code_end|> with the help of current file imports: import http.client import re from google.resumable_media import _helpers from google.resumable_media import common and context from other files: # Path: google/resumable_media/_helpers.py # RANGE_HEADER = "range" # CONTENT_RANGE_HEADER = "content-range" # _SLOW_CRC32C_WARNING = ( # "Currently using crcmod in pure python form. This is a slow " # "implementation. Python 3 has a faster implementation, `google-crc32c`, " # "which will be used if it is installed." # ) # _GENERATION_HEADER = "x-goog-generation" # _HASH_HEADER = "x-goog-hash" # _MISSING_CHECKSUM = """\ # No {checksum_type} checksum was returned from the service while downloading {} # (which happens for composite objects), so client-side content integrity # checking is not being performed.""" # _LOGGER = logging.getLogger(__name__) # def do_nothing(): # def header_required(response, name, get_headers, callback=do_nothing): # def require_status_code(response, status_codes, get_status_code, callback=do_nothing): # def calculate_retry_wait(base_wait, max_sleep, multiplier=2.0): # def _get_crc32c_object(): # def _is_fast_crcmod(): # def _get_metadata_key(checksum_type): # def prepare_checksum_digest(digest_bytestring): # def _get_expected_checksum(response, get_headers, media_url, checksum_type): # def _parse_checksum_header(header_value, response, checksum_label): # def _get_checksum_object(checksum_type): # def _parse_generation_header(response, get_headers): # def _get_generation_from_url(media_url): # def add_query_parameters(media_url, query_params): # def update(self, unused_chunk): # class _DoNothingHash(object): # # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): , which may contain function names, class names, or code. Output only the next line.
_helpers.require_status_code(
Next line prediction: <|code_start|> class DownloadBase(object): """Base class for download helpers. Defines core shared behavior across different download types. Args: media_url (str): The URL containing the media to be downloaded. stream (IO[bytes]): A write-able stream (i.e. file-like object) that the downloaded resource can be written to. start (int): The first byte in a range to be downloaded. end (int): The last byte in a range to be downloaded. headers (Optional[Mapping[str, str]]): Extra headers that should be sent with the request, e.g. headers for encrypted data. Attributes: media_url (str): The URL containing the media to be downloaded. start (Optional[int]): The first byte in a range to be downloaded. end (Optional[int]): The last byte in a range to be downloaded. """ def __init__(self, media_url, stream=None, start=None, end=None, headers=None): self.media_url = media_url self._stream = stream self.start = start self.end = end if headers is None: headers = {} self._headers = headers self._finished = False <|code_end|> . Use current file imports: (import http.client import re from google.resumable_media import _helpers from google.resumable_media import common) and context including class names, function names, or small code snippets from other files: # Path: google/resumable_media/_helpers.py # RANGE_HEADER = "range" # CONTENT_RANGE_HEADER = "content-range" # _SLOW_CRC32C_WARNING = ( # "Currently using crcmod in pure python form. This is a slow " # "implementation. Python 3 has a faster implementation, `google-crc32c`, " # "which will be used if it is installed." # ) # _GENERATION_HEADER = "x-goog-generation" # _HASH_HEADER = "x-goog-hash" # _MISSING_CHECKSUM = """\ # No {checksum_type} checksum was returned from the service while downloading {} # (which happens for composite objects), so client-side content integrity # checking is not being performed.""" # _LOGGER = logging.getLogger(__name__) # def do_nothing(): # def header_required(response, name, get_headers, callback=do_nothing): # def require_status_code(response, status_codes, get_status_code, callback=do_nothing): # def calculate_retry_wait(base_wait, max_sleep, multiplier=2.0): # def _get_crc32c_object(): # def _is_fast_crcmod(): # def _get_metadata_key(checksum_type): # def prepare_checksum_digest(digest_bytestring): # def _get_expected_checksum(response, get_headers, media_url, checksum_type): # def _parse_checksum_header(header_value, response, checksum_label): # def _get_checksum_object(checksum_type): # def _parse_generation_header(response, get_headers): # def _get_generation_from_url(media_url): # def add_query_parameters(media_url, query_params): # def update(self, unused_chunk): # class _DoNothingHash(object): # # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): . Output only the next line.
self._retry_strategy = common.RetryStrategy()
Predict the next line after this snippet: <|code_start|># Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. EXAMPLE_URL = ( "https://www.googleapis.com/download/storage/v1/b/{BUCKET}/o/{OBJECT}?alt=media" ) class TestDownloadBase(object): def test_constructor_defaults(self): <|code_end|> using the current file's imports: import http.client import io import mock import pytest # type: ignore from google.resumable_media import _download from google.resumable_media import common and any relevant context from other files: # Path: google/resumable_media/_download.py # _CONTENT_RANGE_RE = re.compile( # r"bytes (?P<start_byte>\d+)-(?P<end_byte>\d+)/(?P<total_bytes>\d+)", # flags=re.IGNORECASE, # ) # _ACCEPTABLE_STATUS_CODES = (http.client.OK, http.client.PARTIAL_CONTENT) # _GET = "GET" # _ZERO_CONTENT_RANGE_HEADER = "bytes */0" # class DownloadBase(object): # class Download(DownloadBase): # class ChunkedDownload(DownloadBase): # def __init__(self, media_url, stream=None, start=None, end=None, headers=None): # def finished(self): # def _get_status_code(response): # def _get_headers(response): # def _get_body(response): # def __init__( # self, media_url, stream=None, start=None, end=None, headers=None, checksum="md5" # ): # def _prepare_request(self): # def _process_response(self, response): # def consume(self, transport, timeout=None): # def __init__(self, media_url, chunk_size, stream, start=0, end=None, headers=None): # def bytes_downloaded(self): # def total_bytes(self): # def invalid(self): # def _get_byte_range(self): # def _prepare_request(self): # def _make_invalid(self): # def _process_response(self, response): # def consume_next_chunk(self, transport, timeout=None): # def add_bytes_range(start, end, headers): # def get_range_info(response, get_headers, callback=_helpers.do_nothing): # def _check_for_zero_content_range(response, get_status_code, get_headers): # # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): . Output only the next line.
download = _download.DownloadBase(EXAMPLE_URL)
Given snippet: <|code_start|> headers = {"spoonge": "borb"} download = _download.Download(EXAMPLE_URL, start=11, end=111, headers=headers) method, url, payload, new_headers = download._prepare_request() assert method == "GET" assert url == EXAMPLE_URL assert payload is None assert new_headers is headers assert headers == {"range": "bytes=11-111", "spoonge": "borb"} def test__process_response(self): download = _download.Download(EXAMPLE_URL) _fix_up_virtual(download) # Make sure **not finished** before. assert not download.finished response = mock.Mock(status_code=int(http.client.OK), spec=["status_code"]) ret_val = download._process_response(response) assert ret_val is None # Make sure **finished** after. assert download.finished def test__process_response_bad_status(self): download = _download.Download(EXAMPLE_URL) _fix_up_virtual(download) # Make sure **not finished** before. assert not download.finished response = mock.Mock( status_code=int(http.client.NOT_FOUND), spec=["status_code"] ) <|code_end|> , continue by predicting the next line. Consider current file imports: import http.client import io import mock import pytest # type: ignore from google.resumable_media import _download from google.resumable_media import common and context: # Path: google/resumable_media/_download.py # _CONTENT_RANGE_RE = re.compile( # r"bytes (?P<start_byte>\d+)-(?P<end_byte>\d+)/(?P<total_bytes>\d+)", # flags=re.IGNORECASE, # ) # _ACCEPTABLE_STATUS_CODES = (http.client.OK, http.client.PARTIAL_CONTENT) # _GET = "GET" # _ZERO_CONTENT_RANGE_HEADER = "bytes */0" # class DownloadBase(object): # class Download(DownloadBase): # class ChunkedDownload(DownloadBase): # def __init__(self, media_url, stream=None, start=None, end=None, headers=None): # def finished(self): # def _get_status_code(response): # def _get_headers(response): # def _get_body(response): # def __init__( # self, media_url, stream=None, start=None, end=None, headers=None, checksum="md5" # ): # def _prepare_request(self): # def _process_response(self, response): # def consume(self, transport, timeout=None): # def __init__(self, media_url, chunk_size, stream, start=0, end=None, headers=None): # def bytes_downloaded(self): # def total_bytes(self): # def invalid(self): # def _get_byte_range(self): # def _prepare_request(self): # def _make_invalid(self): # def _process_response(self, response): # def consume_next_chunk(self, transport, timeout=None): # def add_bytes_range(start, end, headers): # def get_range_info(response, get_headers, callback=_helpers.do_nothing): # def _check_for_zero_content_range(response, get_status_code, get_headers): # # Path: google/resumable_media/common.py # _SLEEP_RETRY_ERROR_MSG = ( # "At most one of `max_cumulative_retry` and `max_retries` " "can be specified." # ) # UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 # PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore # TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS # MAX_SLEEP = 64.0 # MAX_CUMULATIVE_RETRY = 600.0 # RETRYABLE = ( # http.client.TOO_MANY_REQUESTS, # 429 # http.client.REQUEST_TIMEOUT, # 408 # http.client.INTERNAL_SERVER_ERROR, # 500 # http.client.BAD_GATEWAY, # 502 # http.client.SERVICE_UNAVAILABLE, # 503 # http.client.GATEWAY_TIMEOUT, # 504 # ) # class InvalidResponse(Exception): # class DataCorruption(Exception): # class RetryStrategy(object): # def __init__(self, response, *args): # def __init__(self, response, *args): # def __init__( # self, # max_sleep=MAX_SLEEP, # max_cumulative_retry=None, # max_retries=None, # initial_delay=1.0, # multiplier=2.0, # ): # def retry_allowed(self, total_sleep, num_retries): which might include code, classes, or functions. Output only the next line.
with pytest.raises(common.InvalidResponse) as exc_info:
Given the code snippet: <|code_start|> ('willcom', extra_willcom_ips), ('crawler', extra_crawler_ips), ('nonmobile', None), ): extra = self._extra_ips.setdefault(carrier, []) if not ips: # extra_ip is None or empty sequence continue if not isinstance(ips, (list, tuple)): ips = [ips] for addr in ips: self.add_ip(carrier, addr) # factary classes self.docomo_factory = docomo_factory or DoCoMoUserAgentFactory self.ezweb_factory = ezweb_factory or EZwebUserAgentFactory self.softbank_factory = softbank_factory or SoftBankUserAgentFactory self.willcom_factory = willcom_factory or WillcomUserAgentFactory if proxy_ips: if not isinstance(proxy_ips, (list, tuple)): proxy_ips = [proxy_ips] self._proxy_ips = proxy_ips def get_proxy_ips(self): hosts = [] if self._proxy_ips: for addr in self._proxy_ips: try: <|code_end|> , generate the next line using the imports in this file: from uamobile.cidr import IP, get_ip from uamobile.factory.docomo import * from uamobile.factory.ezweb import * from uamobile.factory.softbank import * from uamobile.factory.willcom import * and context (functions, classes, or occasionally code) from other files: # Path: uamobile/cidr.py # def get_ip_addrs(carrier): # def get_ip(carrier, _memo={}): . Output only the next line.
hosts.append(IP(addr))
Predict the next line for this snippet: <|code_start|> # extra_ip is None or empty sequence continue if not isinstance(ips, (list, tuple)): ips = [ips] for addr in ips: self.add_ip(carrier, addr) # factary classes self.docomo_factory = docomo_factory or DoCoMoUserAgentFactory self.ezweb_factory = ezweb_factory or EZwebUserAgentFactory self.softbank_factory = softbank_factory or SoftBankUserAgentFactory self.willcom_factory = willcom_factory or WillcomUserAgentFactory if proxy_ips: if not isinstance(proxy_ips, (list, tuple)): proxy_ips = [proxy_ips] self._proxy_ips = proxy_ips def get_proxy_ips(self): hosts = [] if self._proxy_ips: for addr in self._proxy_ips: try: hosts.append(IP(addr)) except ValueError: raise ValueError('"%s" is not valid reverse proxy address' % addr) return hosts <|code_end|> with the help of current file imports: from uamobile.cidr import IP, get_ip from uamobile.factory.docomo import * from uamobile.factory.ezweb import * from uamobile.factory.softbank import * from uamobile.factory.willcom import * and context from other files: # Path: uamobile/cidr.py # def get_ip_addrs(carrier): # def get_ip(carrier, _memo={}): , which may contain function names, class names, or code. Output only the next line.
def get_ip(self, carrier):
Here is a snippet: <|code_start|> def supports_cookie(self): """ returns True if the agent supports HTTP cookie. """ raise NotImplementedError def _get_real_ip(self): """ get real IP address of client from REMOTE_ADDR and HTTP_X_FORWARDED_FOR variables """ try: remote_addr = self.environ['REMOTE_ADDR'] except KeyError: return None forwared_for = self.environ.get('HTTP_X_FORWARDED_FOR') proxy_ips = self.context.get_proxy_ips() if forwared_for and proxy_ips: forwared_for = forwared_for.split(',', 1)[0].strip() # check REMOTE_ADDR is included in trusted reverse # proxy address for addr in proxy_ips: if remote_addr in addr: # override remote addr remote_addr = forwared_for break try: <|code_end|> . Write the next line using the current file imports: from uamobile import cidr and context from other files: # Path: uamobile/cidr.py # def get_ip_addrs(carrier): # def get_ip(carrier, _memo={}): , which may include functions, classes, or code. Output only the next line.
return cidr.IP(remote_addr)
Here is a snippet: <|code_start|> assert ua.is_docomo() assert ua.is_bogus() ua = detect({'HTTP_USER_AGENT': 'DoCoMo/2.0 P01A(c100;TB;W24H15)', 'REMOTE_ADDR' : '127.0.0.1', 'HTTP_X_FORWARDED_FOR': 'unknown,210.153.84.0', }, context=context) assert ua.is_docomo() assert ua.is_bogus() def test_extra_ip(): ctxt1 = Context(extra_docomo_ips=['192.168.0.0/24']) ua = detect({'HTTP_USER_AGENT': 'DoCoMo/2.0 P01A(c100;TB;W24H15)', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt1) assert ua.is_docomo() assert ua.is_bogus() is False ctxt2 = Context(extra_docomo_ips=[]) ua = detect({'HTTP_USER_AGENT': 'DoCoMo/2.0 P01A(c100;TB;W24H15)', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt2) assert ua.is_docomo() assert ua.is_bogus() is True def test_my_factory(): <|code_end|> . Write the next line using the current file imports: from tests import msg from uamobile import * from uamobile.docomo import DoCoMoUserAgent from uamobile.factory.docomo import DoCoMoUserAgentFactory and context from other files: # Path: uamobile/docomo.py # class DoCoMoUserAgent(UserAgent): # """ # NTT DoCoMo implementation # see also http://www.nttdocomo.co.jp/service/imode/make/content/spec/useragent/index.html # # property "cache" returns cache size as kilobytes unit. # # property "status" means: # TB | Browsers # TC | Browsers with image off (only Available in HTTP 5.0) # TD | Fetching JAR # TJ | i-Appli # """ # carrier = 'DoCoMo' # short_carrier = 'D' # # def __init__(self, *args, **kwds): # super(DoCoMoUserAgent, self).__init__(*args, **kwds) # self.ser = None # self.icc = None # self.status = None # self.s = None # self.c = 5 # self.series = None # self.vendor = None # self.html_version = None # # def strip_serialnumber(self): # """ # strip Device ID(Hardware ID) and FOMA card ID. # """ # if not self.serialnumber and not self.card_id: # return super(DoCoMoUserAgent, self).strip_serialnumber() # # # User-Agent contains device ID or FOMA card ID # ua = self.useragent # if self.is_foma(): # # TODO # # should we simply use regular expression? # if self.serialnumber: # ua = ua.replace('ser%s' % self.serialnumber, '') # # if self.card_id: # ua = ua.replace('icc%s' % self.card_id, '') # # return ua.replace(';;', ';').replace(';)', ')').replace('(;', '(') # else: # return ua.replace('/ser%s' % self.serialnumber, '') # # def is_docomo(self): # return True # # def get_cache_size(self): # return self.c # cache_size = property(get_cache_size) # # def get_bandwidth(self): # return self.s # bandwidth = property(get_bandwidth) # # def get_card_id(self): # return self.icc # card_id = property(get_card_id) # # def get_serialnumber(self): # return self.ser # serialnumber = property(get_serialnumber) # # def is_gps(self): # return self.model in ('F661i', 'F505iGPS') # # def is_foma(self): # return self.version == '2.0' # # def get_flash_version(self): # """ # returns Flash Lite version. # """ # from uamobile.data.flash.docomo import DATA # try: # return DATA[self.model] # except KeyError: # pass # # if self.cache_size >= 500: # # for P07A3, N07A3, etc # return '3.1' # else: # return None # flash_version = property(get_flash_version) # # def supports_cookie(self): # """ # Return true if the device supports Cookie. # for cookie support of i-mode browsers, see # http://www.nttdocomo.co.jp/info/news_release/page/090519_00.html#p03 # """ # return (self.cache_size == 500) # # def get_guid(self): # """ # Get iMode ID(guid). For iMode ID, see # http://www.nttdocomo.co.jp/service/imode/make/content/ip/index.html#imodeid # """ # try: # return self.environ['HTTP_X_DCMGUID'] # except KeyError: # return None # guid = property(get_guid) # # def get_ue_version(self): # """ # return UE-Version # see http://www.nttdocomo.co.jp/service/imode/make/content/ip/xheader/index.html # """ # return self.environ.get('HTTP_X_UE_VERSION') # ue_version = property(get_ue_version) # # def make_display(self): # """ # create a new Display object. # """ # try: # params = DISPLAYMAP_DOCOMO[self.model] # except KeyError: # params = {} # # if self.display_bytes: # try: # params['width_bytes'], params['height_bytes'] = self.display_bytes # except ValueError: # pass # # return Display(**params) # # Path: uamobile/factory/docomo.py # class DoCoMoUserAgentFactory(AbstractUserAgentFactory): # device_class = DoCoMoUserAgent # parser = CachingDoCoMoUserAgentParser() , which may include functions, classes, or code. Output only the next line.
class MyDoCoMoUserAgent(DoCoMoUserAgent):
Here is a snippet: <|code_start|> 'REMOTE_ADDR' : '127.0.0.1', 'HTTP_X_FORWARDED_FOR': 'unknown,210.153.84.0', }, context=context) assert ua.is_docomo() assert ua.is_bogus() def test_extra_ip(): ctxt1 = Context(extra_docomo_ips=['192.168.0.0/24']) ua = detect({'HTTP_USER_AGENT': 'DoCoMo/2.0 P01A(c100;TB;W24H15)', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt1) assert ua.is_docomo() assert ua.is_bogus() is False ctxt2 = Context(extra_docomo_ips=[]) ua = detect({'HTTP_USER_AGENT': 'DoCoMo/2.0 P01A(c100;TB;W24H15)', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt2) assert ua.is_docomo() assert ua.is_bogus() is True def test_my_factory(): class MyDoCoMoUserAgent(DoCoMoUserAgent): def get_uid(self): return self.environ.get('HTTP_X_DOCOMO_UID') <|code_end|> . Write the next line using the current file imports: from tests import msg from uamobile import * from uamobile.docomo import DoCoMoUserAgent from uamobile.factory.docomo import DoCoMoUserAgentFactory and context from other files: # Path: uamobile/docomo.py # class DoCoMoUserAgent(UserAgent): # """ # NTT DoCoMo implementation # see also http://www.nttdocomo.co.jp/service/imode/make/content/spec/useragent/index.html # # property "cache" returns cache size as kilobytes unit. # # property "status" means: # TB | Browsers # TC | Browsers with image off (only Available in HTTP 5.0) # TD | Fetching JAR # TJ | i-Appli # """ # carrier = 'DoCoMo' # short_carrier = 'D' # # def __init__(self, *args, **kwds): # super(DoCoMoUserAgent, self).__init__(*args, **kwds) # self.ser = None # self.icc = None # self.status = None # self.s = None # self.c = 5 # self.series = None # self.vendor = None # self.html_version = None # # def strip_serialnumber(self): # """ # strip Device ID(Hardware ID) and FOMA card ID. # """ # if not self.serialnumber and not self.card_id: # return super(DoCoMoUserAgent, self).strip_serialnumber() # # # User-Agent contains device ID or FOMA card ID # ua = self.useragent # if self.is_foma(): # # TODO # # should we simply use regular expression? # if self.serialnumber: # ua = ua.replace('ser%s' % self.serialnumber, '') # # if self.card_id: # ua = ua.replace('icc%s' % self.card_id, '') # # return ua.replace(';;', ';').replace(';)', ')').replace('(;', '(') # else: # return ua.replace('/ser%s' % self.serialnumber, '') # # def is_docomo(self): # return True # # def get_cache_size(self): # return self.c # cache_size = property(get_cache_size) # # def get_bandwidth(self): # return self.s # bandwidth = property(get_bandwidth) # # def get_card_id(self): # return self.icc # card_id = property(get_card_id) # # def get_serialnumber(self): # return self.ser # serialnumber = property(get_serialnumber) # # def is_gps(self): # return self.model in ('F661i', 'F505iGPS') # # def is_foma(self): # return self.version == '2.0' # # def get_flash_version(self): # """ # returns Flash Lite version. # """ # from uamobile.data.flash.docomo import DATA # try: # return DATA[self.model] # except KeyError: # pass # # if self.cache_size >= 500: # # for P07A3, N07A3, etc # return '3.1' # else: # return None # flash_version = property(get_flash_version) # # def supports_cookie(self): # """ # Return true if the device supports Cookie. # for cookie support of i-mode browsers, see # http://www.nttdocomo.co.jp/info/news_release/page/090519_00.html#p03 # """ # return (self.cache_size == 500) # # def get_guid(self): # """ # Get iMode ID(guid). For iMode ID, see # http://www.nttdocomo.co.jp/service/imode/make/content/ip/index.html#imodeid # """ # try: # return self.environ['HTTP_X_DCMGUID'] # except KeyError: # return None # guid = property(get_guid) # # def get_ue_version(self): # """ # return UE-Version # see http://www.nttdocomo.co.jp/service/imode/make/content/ip/xheader/index.html # """ # return self.environ.get('HTTP_X_UE_VERSION') # ue_version = property(get_ue_version) # # def make_display(self): # """ # create a new Display object. # """ # try: # params = DISPLAYMAP_DOCOMO[self.model] # except KeyError: # params = {} # # if self.display_bytes: # try: # params['width_bytes'], params['height_bytes'] = self.display_bytes # except ValueError: # pass # # return Display(**params) # # Path: uamobile/factory/docomo.py # class DoCoMoUserAgentFactory(AbstractUserAgentFactory): # device_class = DoCoMoUserAgent # parser = CachingDoCoMoUserAgentParser() , which may include functions, classes, or code. Output only the next line.
class MyDoCoMoUserAgentFactory(DoCoMoUserAgentFactory):
Predict the next line after this snippet: <|code_start|> assert ua.is_softbank() res = ua.is_bogus() assert res == expected, '%s expected, actual %s' % (expected, res) for ip, expected in ( ('210.230.128.224', True), ('123.108.237.0', False), ): yield func, ip, expected def test_extra_ip(): ctxt1 = Context(extra_softbank_ips=['192.168.0.0/24']) ua = detect({'HTTP_USER_AGENT': 'SoftBank/1.0/816SH/SHJ001 Browser/NetFront/3.4 Profile/MIDP-2.0 Configuration/CLDC-1.1', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt1) assert ua.is_softbank() assert ua.is_bogus() is False ctxt2 = Context(extra_softbank_ips=[]) ua = detect({'HTTP_USER_AGENT': 'SoftBank/1.0/816SH/SHJ001 Browser/NetFront/3.4 Profile/MIDP-2.0 Configuration/CLDC-1.1', 'REMOTE_ADDR' : '192.168.0.1', }, context=ctxt2) assert ua.is_softbank() assert ua.is_bogus() is True def test_my_factory(): <|code_end|> using the current file's imports: from tests import msg from uamobile import * from uamobile.softbank import SoftBankUserAgent from uamobile.factory.softbank import SoftBankUserAgentFactory and any relevant context from other files: # Path: uamobile/softbank.py # class SoftBankUserAgent(UserAgent): # carrier = 'SoftBank' # short_carrier = 'S' # serialnumber = None # # def get_flash_version(self): # """ # returns Flash Lite version. # """ # from uamobile.data.flash.softbank import DATA # # if self.model.startswith('V'): # model = self.model[1:] # else: # model = self.model # # try: # return DATA[model] # except KeyError: # pass # # try: # # for 831SHs, 830SHp, etc # return DATA[model[:-1]] # except KeyError: # if self.vendor == 'MOT': # # MOT-V980/80.2F.2E. MIB/2.2.1 Profile/MIDP-2.0 Configuration/CLDC-1.1 # return None # else: # return '2.0' # flash_version = property(get_flash_version) # # def supports_cookie(self): # """ # returns True if the device supports HTTP Cookie. # For more information, see # http://www2.developers.softbankmobile.co.jp/dp/tool_dl/download.php?docid=119 # """ # return self.is_3g() or self.is_type_w() # # def strip_serialnumber(self): # """ # strip Device ID(Hardware ID) # """ # if not self.serialnumber: # return super(SoftBankUserAgent, self).strip_serialnumber() # # return self.useragent.replace('/SN%s' % self.serialnumber, '') # # def is_softbank(self): # return True # # def is_vodafone(self): # return True # # def is_jphone(self): # return True # # def is_3g(self): # return self._is_3g # # def is_type_c(self): # """ # returns True if the type is C. # """ # return not self._is_3g and (self.version.startswith('3.') or self.version.startswith('2.')) # # def is_type_p(self): # """ # returns True if the type is P. # """ # return not self._is_3g and self.version.startswith('4.') # # def is_type_w(self): # """ # returns True if the type is W. # """ # return not self._is_3g and self.version.startswith('5.') # # def get_jphone_uid(self): # """ # returns the x-jphone-uid # for the information about x-jphone-uid, see # http://developers.softbankmobile.co.jp/dp/tool_dl/web/tech.php # """ # try: # return self.environ['HTTP_X_JPHONE_UID'] # except KeyError: # return None # jphone_uid = property(get_jphone_uid) # # def get_msname(self): # return self.environ.get('HTTP_X_JPHONE_MSNAME') # msname = property(get_msname) # # def get_smaf(self): # return self.environ.get('HTTP_X_JPHONE_SMAF') # smaf = property(get_smaf) # # def make_display(self): # """ # create a new Display object. # """ # try: # width, height = map(int, self.environ.get('HTTP_X_JPHONE_DISPLAY', '').split('*', 1)) # except ValueError: # # x-jphone-display is absent, or invalid format # width = None # height = None # # # assuming that WSGI environment variable is always string if the key exists # color_string = self.environ.get('HTTP_X_JPHONE_COLOR', '') # color = color_string.startswith('C') # # try: # depth = int(color_string[1:]) # except (ValueError, TypeError): # depth = 0 # # return Display(width=width, height=height, color=color, depth=depth) # # def get_java_info(self): # import warnings # warnings.warn("'java_info' is depracted. use 'info' instead", DeprecationWarning) # return self.info # java_info = property(get_java_info) . Output only the next line.
class MySoftBankUserAgent(SoftBankUserAgent):
Given snippet: <|code_start|># -*- coding: utf-8 -*- VODAFONE_VENDOR_RE = re.compile(r'V\d+([A-Z]+)') JPHONE_VENDOR_RE = re.compile(r'J-([A-Z]+)') SOFTBANK_CRAWLER_RE = re.compile(r'\([^)]+\)') <|code_end|> , continue by predicting the next line. Consider current file imports: import re from uamobile.parser.base import UserAgentParser and context: # Path: uamobile/parser/base.py # class UserAgentParser(object): # def parse(self, useragent): # raise NotImplementedError() which might include code, classes, or functions. Output only the next line.
class SoftBankUserAgentParser(UserAgentParser):
Using the snippet: <|code_start|> """ try: return self.environ['HTTP_X_DCMGUID'] except KeyError: return None guid = property(get_guid) def get_ue_version(self): """ return UE-Version see http://www.nttdocomo.co.jp/service/imode/make/content/ip/xheader/index.html """ return self.environ.get('HTTP_X_UE_VERSION') ue_version = property(get_ue_version) def make_display(self): """ create a new Display object. """ try: params = DISPLAYMAP_DOCOMO[self.model] except KeyError: params = {} if self.display_bytes: try: params['width_bytes'], params['height_bytes'] = self.display_bytes except ValueError: pass <|code_end|> , determine the next line of code. You have imports: from uamobile.base import UserAgent, Display from uamobile.docomodisplaymap import DISPLAYMAP_DOCOMO from uamobile.data.flash.docomo import DATA and context (class names, function names, or code) available: # Path: uamobile/base.py # class UserAgent(object): # """ # Base class representing HTTTP user agent. # """ # # def __init__(self, environ, context): # try: # self.useragent = environ['HTTP_USER_AGENT'] # except KeyError, e: # self.useragent = '' # self.environ = environ # self.context = context # # self.model = '' # self.version = '' # self._display = None # # def __repr__(self): # return '<%s "%s">' % (self.__class__.__name__, self.useragent) # # def __str__(self): # return self.useragent # # def strip_serialnumber(self): # """ # strip serialnumber such as FOMA card ID of docomo # adn return a normalized User-Agent string. # """ # return self.useragent # # def get_display(self): # """ # returns Display object. # """ # if self._display is None: # self._display = self.make_display() # return self._display # display = property(get_display) # # def make_display(self): # raise NotImplementedError # # def is_docomo(self): # """ # returns True if the agent is DoCoMo. # """ # return False # # def is_ezweb(self): # """ # returns True if the agent is EZweb. # """ # return False # # def is_tuka(self): # """ # returns True if the agent is TU-Ka. # """ # return False # # def is_softbank(self): # """ # returns True if the agent is Softbank. # """ # return False # # def is_vodafone(self): # """ # returns True if the agent is Vodafone (now SotBank). # """ # return False # # def is_jphone(self): # """ # returns True if the agent is J-PHONE (now softbank). # """ # return False # # def is_willcom(self): # """ # returns True if the agent is Willcom. # """ # return False # # def is_airhphone(self): # """ # returns True if the agent is AirH'PHONE. # """ # return False # # def is_wap1(self): # return False # # def is_wap2(self): # return False # # def is_nonmobile(self): # return False # # def supports_flash(self): # """ # returns True if the agent supports Flash # """ # return self.flash_version is not None # # def supports_cookie(self): # """ # returns True if the agent supports HTTP cookie. # """ # raise NotImplementedError # # def _get_real_ip(self): # """ # get real IP address of client from REMOTE_ADDR and # HTTP_X_FORWARDED_FOR variables # """ # try: # remote_addr = self.environ['REMOTE_ADDR'] # except KeyError: # return None # # forwared_for = self.environ.get('HTTP_X_FORWARDED_FOR') # proxy_ips = self.context.get_proxy_ips() # if forwared_for and proxy_ips: # forwared_for = forwared_for.split(',', 1)[0].strip() # # # check REMOTE_ADDR is included in trusted reverse # # proxy address # for addr in proxy_ips: # if remote_addr in addr: # # override remote addr # remote_addr = forwared_for # break # # try: # return cidr.IP(remote_addr) # except ValueError: # # invalid ip address, like 'unknown' # return None # # def get_real_ip(self): # try: # return self._real_ip # except AttributeError: # self._real_ip = self._get_real_ip() # return self._real_ip # # def is_crawler(self): # """ # return True if the client is a mobile crawler # """ # remote_addr = self.get_real_ip() # if remote_addr is None: # # who knows? # return False # # for addr in self.context.get_ip('crawler'): # if remote_addr in addr: # return True # # return False # # def is_bogus(self): # """ # return True if the client isn't accessing via gateways of # japanese mobile carrier # """ # remote_addr = self.get_real_ip() # if remote_addr is None: # return True # # for addr in self.context.get_ip(self.carrier): # if remote_addr in addr: # return False # # return True # # class Display(object): # """ # Display information for mobile devices. # """ # # def __init__(self, width=240, height=320, depth=262144, color=1, # width_bytes=None, height_bytes=None): # self.width = width # self.height = height # self.depth = depth # self.color = color # self.width_bytes = width_bytes # self.height_bytes = height_bytes # # def is_qvga(self): # return self.width >= 240 # # def is_vga(self): # return self.width >= 480 . Output only the next line.
return Display(**params)