Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Using the snippet: <|code_start|> # digital pin directions INPUT = 0 """ INPUT direction constant""" OUTPUT = 1 """ OUTPUT direction constant""" # GPIO resistors HIGH_Z = NONE = 0 """ no-pull (high-z) resistor constant """ PULL_UP = 1 """ pull-up resistor constant """ PULL_DOWN = 2 """ pull-down resistor constant """ # digital pin events LOW = 0 HIGH = 1 CHANGE = 2 RISE = 3 FALL = 4 def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_GPIO: self.logical_pin = self.board.pinout[pin].pinID else: errmsg("UPER API: Pin No:%d is not GPIO pin.", pin) raise IoTPy_APIError("Trying to assign GPIO function to non GPIO pin.") # Configure default state to be input with pull-up resistor <|code_end|> , determine the next line of code. You have imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_GPIO from IoTPy.sfp import encode_sfp, decode_sfp import struct and context (class names, function names, or code) available: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_GPIO = 0x1 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
self.board.low_level_io(0, encode_sfp(1, [self.logical_pin])) # set primary
Predict the next line after this snippet: <|code_start|> mode = 4 # PULL_UP elif resistor == self.PULL_DOWN: mode = 2 # PULL_DOWN else: mode = 0 # HIGH_Z else: mode = 1 # OUTPUT self.board.low_level_io(0, encode_sfp(3, [self.logical_pin, mode])) def write(self, value): """ Write a digital value (0 or 1). If GPIO pin is not configured as output, set it's GPIO mode to GPIO.OUTPUT. :param value: Digital output value (0 or 1) :type value: int """ if self.direction != self.OUTPUT: self.setup(self.OUTPUT) self.board.low_level_io(0, encode_sfp(4, [self.logical_pin, value])) def read(self): """ Read a digital signal value. If GPIO pis in not configure as input, set it to GPIO.PULL_UP pin mode. :return: Digital signal value: 0 (LOW) or 1 (HIGH). :rtype: int """ if self.direction != self.INPUT: self.setup(self.INPUT, self.resistor) <|code_end|> using the current file's imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_GPIO from IoTPy.sfp import encode_sfp, decode_sfp import struct and any relevant context from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_GPIO = 0x1 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
return decode_sfp(self.board.low_level_io(1, encode_sfp(5, [self.logical_pin])))[1][1]
Given the following code snippet before the placeholder: <|code_start|> def detect_sfp_serial(uid=None): ports_list = [] my_platform = platform.system() if uid: uid = UUID(uid) if my_platform == "Windows": for i in range(256): try: serial_tmp = serial.Serial('COM'+str(i)) ports_list.append(serial_tmp.portstr) serial_tmp.close() except serial.SerialException: pass elif my_platform == "Darwin": ports_list = glob.glob("/dev/tty.usbmodem*") elif my_platform == "Linux": ports_list = glob.glob("/dev/ttyACM*") for my_port in ports_list: try: port_to_try = serial.Serial( port=my_port, baudrate=230400, # virtual com port on USB is always max speed parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) <|code_end|> , predict the next line using imports from the current file: import platform import glob import serial from IoTPy.sfp import encode_sfp, decode_sfp from IoTPy.errors import IoTPy_APIError from uuid import UUID and context including class names, function names, and sometimes code from other files: # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args # # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass . Output only the next line.
komanda_siuntimui = encode_sfp(255, [])
Based on the snippet: <|code_start|> if my_platform == "Windows": for i in range(256): try: serial_tmp = serial.Serial('COM'+str(i)) ports_list.append(serial_tmp.portstr) serial_tmp.close() except serial.SerialException: pass elif my_platform == "Darwin": ports_list = glob.glob("/dev/tty.usbmodem*") elif my_platform == "Linux": ports_list = glob.glob("/dev/ttyACM*") for my_port in ports_list: try: port_to_try = serial.Serial( port=my_port, baudrate=230400, # virtual com port on USB is always max speed parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) komanda_siuntimui = encode_sfp(255, []) port_to_try.write(komanda_siuntimui) response = port_to_try.read(1) # read one, blocking n = port_to_try.inWaiting() # look if there is more if n: response = response + port_to_try.read(n) <|code_end|> , predict the immediate next line with the help of imports: import platform import glob import serial from IoTPy.sfp import encode_sfp, decode_sfp from IoTPy.errors import IoTPy_APIError from uuid import UUID and context (classes, functions, sometimes code) from other files: # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args # # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass . Output only the next line.
sfp = decode_sfp(response)
Continue the code snippet: <|code_start|> elif my_platform == "Linux": ports_list = glob.glob("/dev/ttyACM*") for my_port in ports_list: try: port_to_try = serial.Serial( port=my_port, baudrate=230400, # virtual com port on USB is always max speed parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) komanda_siuntimui = encode_sfp(255, []) port_to_try.write(komanda_siuntimui) response = port_to_try.read(1) # read one, blocking n = port_to_try.inWaiting() # look if there is more if n: response = response + port_to_try.read(n) sfp = decode_sfp(response) if sfp[0] == 255: # device info sfp packet dev_uid = UUID(bytes=sfp[1][1]) if not uid or uid == dev_uid: return port_to_try port_to_try.close() except: pass <|code_end|> . Use current file imports: import platform import glob import serial from IoTPy.sfp import encode_sfp, decode_sfp from IoTPy.errors import IoTPy_APIError from uuid import UUID and context (classes, functions, or code) from other files: # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args # # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass . Output only the next line.
raise IoTPy_APIError("No SFP device was found on serial ports.")
Predict the next line after this snippet: <|code_start|> class OneWire(object): def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_GPIO: self.logical_pin = self.board.pinout[pin].pinID else: <|code_end|> using the current file's imports: from IoTPy.errors import IoTPy_APIError from IoTPy.pinmaps import CAP_GPIO from IoTPy.sfp import encode_sfp and any relevant context from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # Path: IoTPy/pinmaps.py # CAP_GPIO = 0x1 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command . Output only the next line.
raise IoTPy_APIError("Trying to assign OneWire function to non GPIO pin.")
Using the snippet: <|code_start|> class OneWire(object): def __init__(self, board, pin): self.board = board <|code_end|> , determine the next line of code. You have imports: from IoTPy.errors import IoTPy_APIError from IoTPy.pinmaps import CAP_GPIO from IoTPy.sfp import encode_sfp and context (class names, function names, or code) available: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # Path: IoTPy/pinmaps.py # CAP_GPIO = 0x1 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command . Output only the next line.
if self.board.pinout[pin].capabilities & CAP_GPIO:
Given the following code snippet before the placeholder: <|code_start|> class OneWire(object): def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_GPIO: self.logical_pin = self.board.pinout[pin].pinID else: raise IoTPy_APIError("Trying to assign OneWire function to non GPIO pin.") #self.board.low_level_io(0, encode_sfp(1, [self.logical_pin])) # set primary #self.board.low_level_io(0, encode_sfp(3, [self.logical_pin, 1])) # gpio mode output <|code_end|> , predict the next line using imports from the current file: from IoTPy.errors import IoTPy_APIError from IoTPy.pinmaps import CAP_GPIO from IoTPy.sfp import encode_sfp and context including class names, function names, and sometimes code from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # Path: IoTPy/pinmaps.py # CAP_GPIO = 0x1 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command . Output only the next line.
self.board.low_level_io(0, encode_sfp(100, [self.logical_pin]))
Predict the next line for this snippet: <|code_start|> """ def __init__(self, board, port=0): self.board = board self.port = port self.board.low_level_io(0, encode_sfp(2, [34])) self.board.low_level_io(0, encode_sfp(2, [35])) self.board.low_level_io(0, encode_sfp(40, [])) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.board.low_level_io(0, encode_sfp(42, [])) def scan(self): """ Scan I2C interface for connected devices. :return: A list of active I2C device addresses. :rtype: list """ dev_list = [] for address in range(1, 128): try: result = self.board.low_level_io(1, encode_sfp(41, [address, b'', 0])) if result[-1] == 'X': dev_list.append(address) except IoTPy_APIError: errmsg("UPER API: I2C bus not connected.") <|code_end|> with the help of current file imports: from IoTPy.errors import IoTPy_IOError, IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp, decode_sfp and context from other files: # Path: IoTPy/errors.py # class IoTPy_IOError(Exception): # pass # # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args , which may contain function names, class names, or code. Output only the next line.
raise IoTPy_IOError("I2C bus not connected.")
Given the following code snippet before the placeholder: <|code_start|> :param port: I2C module number :type port: int """ def __init__(self, board, port=0): self.board = board self.port = port self.board.low_level_io(0, encode_sfp(2, [34])) self.board.low_level_io(0, encode_sfp(2, [35])) self.board.low_level_io(0, encode_sfp(40, [])) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.board.low_level_io(0, encode_sfp(42, [])) def scan(self): """ Scan I2C interface for connected devices. :return: A list of active I2C device addresses. :rtype: list """ dev_list = [] for address in range(1, 128): try: result = self.board.low_level_io(1, encode_sfp(41, [address, b'', 0])) if result[-1] == 'X': dev_list.append(address) <|code_end|> , predict the next line using imports from the current file: from IoTPy.errors import IoTPy_IOError, IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp, decode_sfp and context including class names, function names, and sometimes code from other files: # Path: IoTPy/errors.py # class IoTPy_IOError(Exception): # pass # # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
except IoTPy_APIError:
Next line prediction: <|code_start|> :type port: int """ def __init__(self, board, port=0): self.board = board self.port = port self.board.low_level_io(0, encode_sfp(2, [34])) self.board.low_level_io(0, encode_sfp(2, [35])) self.board.low_level_io(0, encode_sfp(40, [])) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.board.low_level_io(0, encode_sfp(42, [])) def scan(self): """ Scan I2C interface for connected devices. :return: A list of active I2C device addresses. :rtype: list """ dev_list = [] for address in range(1, 128): try: result = self.board.low_level_io(1, encode_sfp(41, [address, b'', 0])) if result[-1] == 'X': dev_list.append(address) except IoTPy_APIError: <|code_end|> . Use current file imports: (from IoTPy.errors import IoTPy_IOError, IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp, decode_sfp) and context including class names, function names, or small code snippets from other files: # Path: IoTPy/errors.py # class IoTPy_IOError(Exception): # pass # # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
errmsg("UPER API: I2C bus not connected.")
Here is a snippet: <|code_start|> class I2C(object): """ I2C communication module. :param board: IoBoard with I2C capability. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param port: I2C module number :type port: int """ def __init__(self, board, port=0): self.board = board self.port = port <|code_end|> . Write the next line using the current file imports: from IoTPy.errors import IoTPy_IOError, IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp, decode_sfp and context from other files: # Path: IoTPy/errors.py # class IoTPy_IOError(Exception): # pass # # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args , which may include functions, classes, or code. Output only the next line.
self.board.low_level_io(0, encode_sfp(2, [34]))
Given the following code snippet before the placeholder: <|code_start|> except IoTPy_APIError: errmsg("UPER API: I2C bus not connected.") raise IoTPy_IOError("I2C bus not connected.") return dev_list def read(self, address, count): return self.transaction(address, b'', count) def write(self, address, data): return self.transaction(address, data, 0) def transaction(self, address, write_data, read_length): """ Perform I2C data transaction. I2C data transaction consists of (optional) write transaction, followed by (optional) read transaction. :param address: I2C device address. :type address: int :param write_data: A byte sequence to be transmitted. If write_data is empty string, no write transaction \ will be executed. :type write_data: str :param read_length: A number of bytes to be received. If read_length is 0, no read transaction will be executed. :type read_length: int :return: Received data and I2C transaction status/error code. :rtype: (str, int) :raise: IoTPy_APIError, IoTPy_ThingError """ try: <|code_end|> , predict the next line using imports from the current file: from IoTPy.errors import IoTPy_IOError, IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp, decode_sfp and context including class names, function names, and sometimes code from other files: # Path: IoTPy/errors.py # class IoTPy_IOError(Exception): # pass # # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
result = decode_sfp(self.board.low_level_io(1, encode_sfp(41, [address, write_data, read_length])))
Next line prediction: <|code_start|> def on_rotation(direction, position): print("Rotated by %i, current position is %i" % (direction, position)) with UPER1() as board, \ board.digital(1) as chan0, board.digital(2) as chan1, \ <|code_end|> . Use current file imports: (from time import sleep from IoTPy.ioboard.boards.uper import UPER1 from IoTPy.things.rotary_encoder import RotaryEncoder) and context including class names, function names, or small code snippets from other files: # Path: IoTPy/things/rotary_encoder.py # class RotaryEncoder: # # FORWARD = 1 # BACKWARD = -1 # # _backward_states = [ # [[0, 0], [1, 0], [1, 1]], # missing 1st # [[0, 1], [1, 0], [1, 1]], # missing 2nd # [[0, 1], [0, 0], [1, 1]], # missing 3rd # [[0, 1], [0, 0], [1, 0]], # missing 4th # ] # # _forward_states = [ # [[0, 0], [0, 1], [1, 1]], # missing 1st or perfect # [[1, 0], [0, 1], [1, 1]], # missing 2nd # [[1, 0], [0, 0], [1, 1]], # missing 3rd # [[1, 0], [0, 0], [0, 1]], # missing 4th # ] # # _null_state = [[-1, -1], [-1, -1], [-1, -1]] # # def __init__(self, chan0, chan1, callback=None): # #obj = {'previous_states': list(self._null_state), 'position': 0} # # self._previous_states = list(self._null_state) # self.position = 0 # # self._chan0 = chan0 # self._chan1 = chan1 # # self._user_callback = callback # # self._id0 = chan0.attach_irq(GPIO.CHANGE, self.call_back, None, 3) # self._id1 = chan1.attach_irq(GPIO.CHANGE, self.call_back, None, 3) # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self._chan0.detach_irq() # self._chan1.detach_irq() # # def call_back(self, event, obj): # pins = event['values'] # pin1 = (pins >> self._id0) & 0x01 # pin2 = (pins >> self._id1) & 0x01 # # if [pin1, pin2] != self._previous_states[2]: # self._previous_states[0:2] = self._previous_states[1:3] # self._previous_states[2] = [pin1, pin2] # # if self._previous_states in self._forward_states: # self.position += 1 # self._previous_states = list(self._null_state) # if self._user_callback: # self._user_callback(RotaryEncoder.FORWARD, self.position) # elif self._previous_states in self._backward_states: # self.position -= 1 # self._previous_states = list(self._null_state) # if self._user_callback: # self._user_callback(RotaryEncoder.BACKWARD, self.position) . Output only the next line.
RotaryEncoder(chan0, chan1, on_rotation) as encoder:
Based on the snippet: <|code_start|> class Si7013: """ Si7013 humidity and temperature sensor class. :param interface: I2C communication interface. :type interface: :class:`IoTPy.pyuper.i2c.I2C` :param int address: Si7013 sensor I2C address. Optional, default 0x40 (64) """ def __init__(self, interface, address=0x40): self.interface = interface self.address = address def __enter__(self): return self def temperature(self): """ Read, convert and return temperature. :return: Temperature value in celsius. :rtype: float :raise: IoTPy_ThingError """ try: data, err = self.interface.transaction(self.address, SI70xx_CMD_TEMP_HOLD, 2) result_integer = unpack('>H', data[:2])[0] temp = (175.72 * result_integer)/65536 - 46.85 <|code_end|> , predict the immediate next line with the help of imports: from struct import unpack from IoTPy.errors import IoTPy_ThingError and context (classes, functions, sometimes code) from other files: # Path: IoTPy/errors.py # class IoTPy_ThingError(Exception): # pass . Output only the next line.
except IoTPy_ThingError:
Continue the code snippet: <|code_start|> class SocketTransport(object): def __init__(self, host='127.0.0.1', port=7777): self.host = host self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print(self.host, self.port) self.socket.connect((self.host, self.port)) def read(self): return self.socket.recv(1024) def write(self, data): self.socket.send(data) def close(self): self.socket.shutdown(socket.SHUT_RDWR) self.socket.close() class SerialTransport(object): def __init__(self, serial_port=None, uid=None): self.serial_port = serial_port if not self.serial_port: <|code_end|> . Use current file imports: import socket from IoTPy.detect_sfp_serial import detect_sfp_serial from IoTPy.errors import IoTPy_IOError and context (classes, functions, or code) from other files: # Path: IoTPy/detect_sfp_serial.py # def detect_sfp_serial(uid=None): # ports_list = [] # my_platform = platform.system() # if uid: # uid = UUID(uid) # # if my_platform == "Windows": # for i in range(256): # try: # serial_tmp = serial.Serial('COM'+str(i)) # ports_list.append(serial_tmp.portstr) # serial_tmp.close() # except serial.SerialException: # pass # elif my_platform == "Darwin": # ports_list = glob.glob("/dev/tty.usbmodem*") # elif my_platform == "Linux": # ports_list = glob.glob("/dev/ttyACM*") # # for my_port in ports_list: # try: # port_to_try = serial.Serial( # port=my_port, # baudrate=230400, # virtual com port on USB is always max speed # parity=serial.PARITY_ODD, # stopbits=serial.STOPBITS_ONE, # bytesize=serial.EIGHTBITS, # timeout=1 # ) # komanda_siuntimui = encode_sfp(255, []) # port_to_try.write(komanda_siuntimui) # response = port_to_try.read(1) # read one, blocking # n = port_to_try.inWaiting() # look if there is more # if n: # response = response + port_to_try.read(n) # sfp = decode_sfp(response) # # if sfp[0] == 255: # device info sfp packet # dev_uid = UUID(bytes=sfp[1][1]) # if not uid or uid == dev_uid: # return port_to_try # # port_to_try.close() # except: # pass # # raise IoTPy_APIError("No SFP device was found on serial ports.") # # Path: IoTPy/errors.py # class IoTPy_IOError(Exception): # pass . Output only the next line.
self.serial_port = detect_sfp_serial(uid)
Based on the snippet: <|code_start|> """thread safe socket write with no data escaping. used to send telnet stuff""" self._write_lock.acquire() try: self.socket.sendall(data) finally: self._write_lock.release() def writer(self): """loop forever and copy socket->serial""" while self.alive: try: data = self.socket.recv(1024) if not data: break self.serial.write(data) # get a bunch of bytes and send them except socket.error as msg: sys.stderr.write('ERROR: %s\n' % msg) # probably got disconnected break self.alive = False self.thread_read.join() def stop(self): """Stop copying""" if self.alive: self.alive = False self.thread_read.join() LOCAL_PORT = 7777 <|code_end|> , predict the immediate next line with the help of imports: import sys import threading import socket from IoTPy.detect_sfp_serial import detect_sfp_serial and context (classes, functions, sometimes code) from other files: # Path: IoTPy/detect_sfp_serial.py # def detect_sfp_serial(uid=None): # ports_list = [] # my_platform = platform.system() # if uid: # uid = UUID(uid) # # if my_platform == "Windows": # for i in range(256): # try: # serial_tmp = serial.Serial('COM'+str(i)) # ports_list.append(serial_tmp.portstr) # serial_tmp.close() # except serial.SerialException: # pass # elif my_platform == "Darwin": # ports_list = glob.glob("/dev/tty.usbmodem*") # elif my_platform == "Linux": # ports_list = glob.glob("/dev/ttyACM*") # # for my_port in ports_list: # try: # port_to_try = serial.Serial( # port=my_port, # baudrate=230400, # virtual com port on USB is always max speed # parity=serial.PARITY_ODD, # stopbits=serial.STOPBITS_ONE, # bytesize=serial.EIGHTBITS, # timeout=1 # ) # komanda_siuntimui = encode_sfp(255, []) # port_to_try.write(komanda_siuntimui) # response = port_to_try.read(1) # read one, blocking # n = port_to_try.inWaiting() # look if there is more # if n: # response = response + port_to_try.read(n) # sfp = decode_sfp(response) # # if sfp[0] == 255: # device info sfp packet # dev_uid = UUID(bytes=sfp[1][1]) # if not uid or uid == dev_uid: # return port_to_try # # port_to_try.close() # except: # pass # # raise IoTPy_APIError("No SFP device was found on serial ports.") . Output only the next line.
ser = detect_sfp_serial()
Given snippet: <|code_start|> class ADC(object): """ ADC (Analog to Digital Converter) pin module. :param board: IoBoard to which the pin belongs to. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param pin: ADC capable pin number. :type pin: int """ def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_ADC: self.logical_pin = self.board.pinout[pin].pinID else: errmsg("IO API: Pin "+str(pin)+" is not an ADC pin.") <|code_end|> , continue by predicting the next line. Consider current file imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_ADC from IoTPy.sfp import encode_sfp, decode_sfp and context: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_ADC = 0x2 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args which might include code, classes, or functions. Output only the next line.
raise IoTPy_APIError("Trying to assign ADC function to non ADC pin.")
Given snippet: <|code_start|> class ADC(object): """ ADC (Analog to Digital Converter) pin module. :param board: IoBoard to which the pin belongs to. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param pin: ADC capable pin number. :type pin: int """ def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_ADC: self.logical_pin = self.board.pinout[pin].pinID else: <|code_end|> , continue by predicting the next line. Consider current file imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_ADC from IoTPy.sfp import encode_sfp, decode_sfp and context: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_ADC = 0x2 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args which might include code, classes, or functions. Output only the next line.
errmsg("IO API: Pin "+str(pin)+" is not an ADC pin.")
Based on the snippet: <|code_start|> class ADC(object): """ ADC (Analog to Digital Converter) pin module. :param board: IoBoard to which the pin belongs to. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param pin: ADC capable pin number. :type pin: int """ def __init__(self, board, pin): self.board = board <|code_end|> , predict the immediate next line with the help of imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_ADC from IoTPy.sfp import encode_sfp, decode_sfp and context (classes, functions, sometimes code) from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_ADC = 0x2 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
if self.board.pinout[pin].capabilities & CAP_ADC:
Given snippet: <|code_start|> class ADC(object): """ ADC (Analog to Digital Converter) pin module. :param board: IoBoard to which the pin belongs to. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param pin: ADC capable pin number. :type pin: int """ def __init__(self, board, pin): self.board = board if self.board.pinout[pin].capabilities & CAP_ADC: self.logical_pin = self.board.pinout[pin].pinID else: errmsg("IO API: Pin "+str(pin)+" is not an ADC pin.") raise IoTPy_APIError("Trying to assign ADC function to non ADC pin.") self.adc_pin = self.board.pinout[pin].extra[0] <|code_end|> , continue by predicting the next line. Consider current file imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_ADC from IoTPy.sfp import encode_sfp, decode_sfp and context: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_ADC = 0x2 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args which might include code, classes, or functions. Output only the next line.
self.board.low_level_io(0, encode_sfp(3, [self.logical_pin, 0])) # set GPIO to HIGH_Z
Here is a snippet: <|code_start|> else: errmsg("IO API: Pin "+str(pin)+" is not an ADC pin.") raise IoTPy_APIError("Trying to assign ADC function to non ADC pin.") self.adc_pin = self.board.pinout[pin].extra[0] self.board.low_level_io(0, encode_sfp(3, [self.logical_pin, 0])) # set GPIO to HIGH_Z self.board.low_level_io(0, encode_sfp(2, [self.logical_pin])) # set secondary pin function self.primary = False def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass def read(self): """ Read fractional analog value :return: A normalized analog value from 0.0 (min) to 1.0 (max) :rtype: float """ return self.read_raw()/1023.0 def read_raw(self): """ Read ADC value :return: Raw ADC value. :rtype: int """ <|code_end|> . Write the next line using the current file imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.pinmaps import CAP_ADC from IoTPy.sfp import encode_sfp, decode_sfp and context from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/pinmaps.py # CAP_ADC = 0x2 # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args , which may include functions, classes, or code. Output only the next line.
return decode_sfp(self.board.low_level_io(1, encode_sfp(10, [self.adc_pin])))[1][1]
Predict the next line after this snippet: <|code_start|> :param divider: SPI clock divider. SPI clock speed will be maximum clock speed (2MHz) divided by this value. Optional, default 1. :type divider: int :param mode: Standard SPI mode number (SPI.MODE_0 to SPI.MODE_3). Optional, default SPI.MODE_0. :type mode: int """ MODE_0 = 0 MODE_1 = 1 MODE_2 = 2 MODE_3 = 3 def __init__(self, board, port=0, divider=1, mode=MODE_0): divider = min(max(divider, 1), 256) self.board = board self.port = port self.divider = divider self.mode = mode if self.port == 1: self.board.low_level_io(0, encode_sfp(2, [4])) self.board.low_level_io(0, encode_sfp(2, [5])) self.board.low_level_io(0, encode_sfp(2, [11])) self.board.low_level_io(0, encode_sfp(30, [self.divider, self.mode])) elif self.port == 0: self.board.low_level_io(0, encode_sfp(2, [12])) self.board.low_level_io(0, encode_sfp(2, [13])) self.board.low_level_io(0, encode_sfp(2, [14])) self.board.low_level_io(0, encode_sfp(20, [self.divider, self.mode])) else: errmsg("UPER API: Wrong SPI port number.", self.port) <|code_end|> using the current file's imports: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp, decode_sfp and any relevant context from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
raise IoTPy_APIError("SPI port must be 0 or 1, trying to assign something else.")
Given the code snippet: <|code_start|> :type port: int :param divider: SPI clock divider. SPI clock speed will be maximum clock speed (2MHz) divided by this value. Optional, default 1. :type divider: int :param mode: Standard SPI mode number (SPI.MODE_0 to SPI.MODE_3). Optional, default SPI.MODE_0. :type mode: int """ MODE_0 = 0 MODE_1 = 1 MODE_2 = 2 MODE_3 = 3 def __init__(self, board, port=0, divider=1, mode=MODE_0): divider = min(max(divider, 1), 256) self.board = board self.port = port self.divider = divider self.mode = mode if self.port == 1: self.board.low_level_io(0, encode_sfp(2, [4])) self.board.low_level_io(0, encode_sfp(2, [5])) self.board.low_level_io(0, encode_sfp(2, [11])) self.board.low_level_io(0, encode_sfp(30, [self.divider, self.mode])) elif self.port == 0: self.board.low_level_io(0, encode_sfp(2, [12])) self.board.low_level_io(0, encode_sfp(2, [13])) self.board.low_level_io(0, encode_sfp(2, [14])) self.board.low_level_io(0, encode_sfp(20, [self.divider, self.mode])) else: <|code_end|> , generate the next line using the imports in this file: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp, decode_sfp and context (functions, classes, or occasionally code) from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
errmsg("UPER API: Wrong SPI port number.", self.port)
Given the following code snippet before the placeholder: <|code_start|> class SPI(object): """ SPI communication module. :param board: IoBoard with SPI capability. :type board: :class:`IoTPy.pyuper.ioboard.IoBoard` :param port: SPI module number. Optional, default 0 (SPI0 module). :type port: int :param divider: SPI clock divider. SPI clock speed will be maximum clock speed (2MHz) divided by this value. Optional, default 1. :type divider: int :param mode: Standard SPI mode number (SPI.MODE_0 to SPI.MODE_3). Optional, default SPI.MODE_0. :type mode: int """ MODE_0 = 0 MODE_1 = 1 MODE_2 = 2 MODE_3 = 3 def __init__(self, board, port=0, divider=1, mode=MODE_0): divider = min(max(divider, 1), 256) self.board = board self.port = port self.divider = divider self.mode = mode if self.port == 1: <|code_end|> , predict the next line using imports from the current file: from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp, decode_sfp and context including class names, function names, and sometimes code from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
self.board.low_level_io(0, encode_sfp(2, [4]))
Next line prediction: <|code_start|> self.board.low_level_io(0, encode_sfp(2, [14])) self.board.low_level_io(0, encode_sfp(20, [self.divider, self.mode])) else: errmsg("UPER API: Wrong SPI port number.", self.port) raise IoTPy_APIError("SPI port must be 0 or 1, trying to assign something else.") def __enter__(self): return self def read(self, count, value=0): return self.transaction(chr(value)*count, True) def write(self, data): self.transaction(data, False) def transaction(self, write_data, read_from_slave=True): """ Perform SPI data transaction. :param write_data: Data to be shifted on MOSI line. :type write_data: str :param read_from_slave: Flag indicating whether the data received on MISO line should be ignored or not. Optional, default True. :type read_from_slave: bool :return: Data received on MISO line, if read_from_slave is True. :rtype: str """ res = self.board.low_level_io(read_from_slave, encode_sfp(21 + self.port * 10, [write_data, int(read_from_slave)])) if res: <|code_end|> . Use current file imports: (from IoTPy.errors import IoTPy_APIError, errmsg from IoTPy.sfp import encode_sfp, decode_sfp) and context including class names, function names, or small code snippets from other files: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass # # def errmsg(fmt, *args): # if not fmt.endswith('\n'): # fmt += '\n' # sys.stderr.write(os.path.basename(sys.argv[0])) # sys.stderr.write(': ') # if len(args): # sys.stderr.write(fmt % args) # else: # sys.stderr.write(fmt) # sys.stderr.flush() # # Path: IoTPy/sfp.py # def encode_sfp(command, args): # """ # Construct binary SFP command. # # :param command: SFP command ID. # :type command: int # :param args: A list of SFP arguments, which can be either an integer or a byte collection (string). # :type args: list # :return: Binary SFP command. # :rtype: str # """ # functions = { # binary_type: _encode_bytes, # integer_types[0]: _encode_int # [0] - kinda hack to get class int # } # # sfp_command = pack('B', command) + b''.join(functions[type(arg)](arg) for arg in args) # sfp_command = b'\xd4' + pack('>H', len(sfp_command)) + sfp_command # return sfp_command # # def decode_sfp(io_buffer): # """ # Decode SFP command from byte buffer. # # :param io_buffer: A byte buffer which stores SFP command. # :type io_buffer: bytes string # :return: SFP function ID and arguments list. # """ # if io_buffer[0:1] != b'\xd4': # return # command_length = unpack('>H', io_buffer[1:3])[0] + 3 # get SFP command length located in two bytes # sfp_command = unpack('B', io_buffer[3:4])[0] # get SFP command code # pointer = 4 # args = [] # while pointer < command_length: # arg_type = ord(io_buffer[pointer:pointer + 1]) # pointer += 1 # if arg_type < 64: # short int # args.append(arg_type) # elif arg_type < 128: # short str # arg_len = arg_type & 0x3f # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # else: # arg_len = arg_type & 0x0f # if arg_len < 4: # decoding integers # if arg_len == 0: # args.append(ord(io_buffer[pointer:pointer + 1])) # elif arg_len == 1: # args.append(unpack('>H', io_buffer[pointer:pointer + 2])[0]) # elif arg_len == 2: # args.append(unpack('>I', b'\x00' + io_buffer[pointer:pointer + 3])[0]) # elif arg_len == 3: # args.append(unpack('>I', io_buffer[pointer:pointer + 4])[0]) # pointer += arg_len + 1 # else: # if arg_type == 0xc4: # decoding strings # arg_len = ord(io_buffer[pointer:pointer + 1]) # elif arg_type == 0xc5: # arg_len = unpack('>H', io_buffer[pointer:pointer + 2])[0] # pointer += 1 # else: # raise IoTPy_APIError("UPER API: Bad parameter type in decodeSFP method.") # pointer += 1 # args.append(io_buffer[pointer:pointer + arg_len]) # pointer += arg_len # return sfp_command, args . Output only the next line.
return decode_sfp(res)[1][0]
Based on the snippet: <|code_start|> HOST = None # Symbolic name meaning all available interfaces PORT = 7777 # Arbitrary non-privileged port s = None <|code_end|> , predict the immediate next line with the help of imports: import socket import sys from time import sleep from IoTPy.sfp_processor import SfpMachine from IoTPy.sfp import command_slicer and context (classes, functions, sometimes code) from other files: # Path: IoTPy/sfp_processor.py # class SfpMachine(object): # # def __init__(self): # self.pin_states = {} # self.pin_id_list = [] # for pin in pin_list: # pin_id = pin[0] # pin_caps = pin[1] # pin_extras = pin[2] # if pin_caps & CAP_ADC: # secondary_function = AnalogPin() # elif pin_caps & CAP_PWM: # secondary_function = PwmPin() # else: # secondary_function = None # self.pin_states[pin_id] = (pin_caps, pin_extras, DigitalPin(), secondary_function) # self.pin_id_list.append(pin_id) # self.sfp_comands = {} # self.sfp_comands[1] = self.set_primary # self.sfp_comands[2] = self.set_secondary # self.sfp_comands[3] = self.set_pin_mode # self.sfp_comands[4] = self.digital_write # self.sfp_comands[5] = self.digital_read # self.sfp_comands[6] = self.attach_interrupt # self.sfp_comands[7] = self.detach_interrupt # # self.sfp_comands[9] = # self.sfp_comands[255] = self.get_device_info # # def set_primary(self, arg_list): # pin_id = arg_list[0] # if pin_id in self.pin_id_list: # self.pin_states[pin_id][2].set_primary() # # def set_secondary(self, arg_list): # pin_id = arg_list[0] # if pin_id in self.pin_id_list: # self.pin_states[pin_id][2].set_secondary() # # def set_pin_mode(self, arg_list): # pin_id = arg_list[0] # mode = arg_list[1] # if pin_id in self.pin_id_list: # self.pin_states[pin_id][2].set_mode(mode) # # def digital_write(self, arg_list): # pin_id = arg_list[0] # value = arg_list[1] # if pin_id in self.pin_id_list: # self.pin_states[pin_id][2].write(value) # # def digital_read(self, arg_list): # pin_id = arg_list[0] # if pin_id in self.pin_id_list: # return pin_id, self.pin_states[pin_id][2].read() # # def attach_interrupt(self, arg_list): # pass # # def detach_interrupt(self, arg_list): # pass # # def get_device_info(self, arg_list): # return 44, 0, 44, 0 # # def execute_sfp(self, binary_sfp_command): # decoded_sfp_command = decode_sfp(binary_sfp_command) # results = self.sfp_comands[decoded_sfp_command[0]](decoded_sfp_command[1]) # if results: # return encode_sfp(decoded_sfp_command[0], results) # # Path: IoTPy/sfp.py # def command_slicer(io_buffer): # commands_list = [] # while io_buffer: # if not valid_message(io_buffer): # return io_buffer, commands_list # # cmd, length = unpack('!BH', io_buffer[:3]) # # if len(io_buffer) < (length + 3): # return io_buffer, commands_list # # sfp_command = io_buffer[:length + 3] # SFP header + data # io_buffer = io_buffer[length + 3:] # commands_list.append(sfp_command) # # return io_buffer, commands_list . Output only the next line.
sfp_machine_instance = SfpMachine()
Given snippet: <|code_start|> for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except socket.error as msg: s = None continue try: s.bind(sa) s.listen(1) except socket.error as msg: s.close() s = None continue break if s is None: print('could not open socket') sys.exit(1) while True: conn, addr = s.accept() print('Connected by', addr) io_buffer = b'' while True: received_data = conn.recv(1024) if not received_data: break io_buffer += received_data <|code_end|> , continue by predicting the next line. Consider current file imports: import socket import sys from time import sleep from IoTPy.sfp_processor import SfpMachine from IoTPy.sfp import command_slicer and context: # Path: IoTPy/sfp_processor.py # class SfpMachine(object): # # def __init__(self): # self.pin_states = {} # self.pin_id_list = [] # for pin in pin_list: # pin_id = pin[0] # pin_caps = pin[1] # pin_extras = pin[2] # if pin_caps & CAP_ADC: # secondary_function = AnalogPin() # elif pin_caps & CAP_PWM: # secondary_function = PwmPin() # else: # secondary_function = None # self.pin_states[pin_id] = (pin_caps, pin_extras, DigitalPin(), secondary_function) # self.pin_id_list.append(pin_id) # self.sfp_comands = {} # self.sfp_comands[1] = self.set_primary # self.sfp_comands[2] = self.set_secondary # self.sfp_comands[3] = self.set_pin_mode # self.sfp_comands[4] = self.digital_write # self.sfp_comands[5] = self.digital_read # self.sfp_comands[6] = self.attach_interrupt # self.sfp_comands[7] = self.detach_interrupt # # self.sfp_comands[9] = # self.sfp_comands[255] = self.get_device_info # # def set_primary(self, arg_list): # pin_id = arg_list[0] # if pin_id in self.pin_id_list: # self.pin_states[pin_id][2].set_primary() # # def set_secondary(self, arg_list): # pin_id = arg_list[0] # if pin_id in self.pin_id_list: # self.pin_states[pin_id][2].set_secondary() # # def set_pin_mode(self, arg_list): # pin_id = arg_list[0] # mode = arg_list[1] # if pin_id in self.pin_id_list: # self.pin_states[pin_id][2].set_mode(mode) # # def digital_write(self, arg_list): # pin_id = arg_list[0] # value = arg_list[1] # if pin_id in self.pin_id_list: # self.pin_states[pin_id][2].write(value) # # def digital_read(self, arg_list): # pin_id = arg_list[0] # if pin_id in self.pin_id_list: # return pin_id, self.pin_states[pin_id][2].read() # # def attach_interrupt(self, arg_list): # pass # # def detach_interrupt(self, arg_list): # pass # # def get_device_info(self, arg_list): # return 44, 0, 44, 0 # # def execute_sfp(self, binary_sfp_command): # decoded_sfp_command = decode_sfp(binary_sfp_command) # results = self.sfp_comands[decoded_sfp_command[0]](decoded_sfp_command[1]) # if results: # return encode_sfp(decoded_sfp_command[0], results) # # Path: IoTPy/sfp.py # def command_slicer(io_buffer): # commands_list = [] # while io_buffer: # if not valid_message(io_buffer): # return io_buffer, commands_list # # cmd, length = unpack('!BH', io_buffer[:3]) # # if len(io_buffer) < (length + 3): # return io_buffer, commands_list # # sfp_command = io_buffer[:length + 3] # SFP header + data # io_buffer = io_buffer[length + 3:] # commands_list.append(sfp_command) # # return io_buffer, commands_list which might include code, classes, or functions. Output only the next line.
io_buffer, command_list = command_slicer(io_buffer)
Given snippet: <|code_start|> T = collections.namedtuple(typename, field_names) T.__new__.__defaults__ = (None,) * len(T._fields) if isinstance(default_values, collections.Mapping): prototype = T(**default_values) else: prototype = T(*default_values) T.__new__.__defaults__ = tuple(prototype) return T CAP_RESERVED = 0x0 CAP_GPIO = 0x1 CAP_ADC = 0x2 CAP_PWM = 0x4 CAP_SPI = 0x8 CAP_UART = 0x10 CAP_I2C = 0x20 """ named tuple Pin for storing pinID, capabilities and extra info such us PWM bank or ADC pin no and similar. """ Pin = namedtuple_with_defaults('Pin','pinID, capabilities, extra', [None, CAP_GPIO, None]) class IoPinout(dict): """ A dictionary consisting of integer or basestring keys and named tuple Pin """ def __init__(self, *args, **kw): super(IoPinout,self).__init__(*args, **kw) for key in self: if not (isinstance(key, int) or isinstance(key, string_types)) or not isinstance(self[key], Pin): <|code_end|> , continue by predicting the next line. Consider current file imports: from IoTPy.errors import IoTPy_APIError from six import string_types import collections and context: # Path: IoTPy/errors.py # class IoTPy_APIError(Exception): # pass which might include code, classes, or functions. Output only the next line.
raise IoTPy_APIError("IoPinout must consist of integer or string keys and Pin values.")
Using the snippet: <|code_start|>from __future__ import absolute_import, unicode_literals class CountryStatsForm(ImportFormBase): def get_choice_field_name(self): return 'statistic' def get_choice_field_queryset(self): <|code_end|> , determine the next line of code. You have imports: from django.core.urlresolvers import reverse from custom_importer.forms import ImportFormBase from custom_importer.views import ImporterBase, ExportTemplateBase from country.models import Country from .models import StatDescription, StatValue from .statsimporter import StatisticResource and context (class names, function names, or code) available: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # pass # # description = models.TextField() # code = models.SlugField() # # def __unicode__(self): # return self.description # # class StatValue(models.Model): # class Meta: # unique_together = ('description', 'country', 'year') # # description = models.ForeignKey(StatDescription) # country = models.ForeignKey(Country) # year = models.IntegerField() # value = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) # nopep8 # # def __unicode__(self): # return "%s, %s, %s" % ( # self.country, # self.year, # self.value # ) # # Path: washmap/stats/statsimporter.py # class StatisticResource(ModelResource): # """ # StatDescription # # StatValue # Year # @Country # @StatDescription # # Stat Description # Country | Year | Year | Year ... | # A.. | # B.. | # # """ # # class Meta: # model = None # see StatValueRowInstance instead # fields = () # instance_loader_class = StatValueInstanceLoader # import_id_fields = ['country'] # # country = CountryField(attribute='name', readonly=True) # # def __init__(self, statistic, *args, **kwargs): # self.statistic = statistic # super(StatisticResource, self).__init__(*args, **kwargs) # # def before_import(self, dataset, real_dry_run): # # Presume first column is country column # year_headers = dataset.headers[1:] # # # check they are valid, unique, etc # # for year_header in year_headers: # year = int(year_header) # self.fields['year-%d' % year] = YearField(year, column_name='%s' % year) # nopep8 # # def get_dynamic_fields(self): # year_fields = SortedDict() # # values_qs = StatValue.objects.filter(description=self.statistic) # years = values_qs.values_list('year', flat=True).distinct() # # for year in sorted(years): # year_fields['year-%d' % year] = YearField(year, column_name='%s' % year) # nopep8 # # return year_fields # # def get_queryset(self): # countries = Country.objects.all().order_by('name') # statvalues = [] # for country in countries: # inst = StatValueRowInstance(self.statistic, country) # statvalues.append(inst) # # class dummy_queryset(object): # def iterator(self): # return statvalues # # return dummy_queryset() . Output only the next line.
return StatDescription.objects.all()
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import, unicode_literals class CountryStatsForm(ImportFormBase): def get_choice_field_name(self): return 'statistic' def get_choice_field_queryset(self): return StatDescription.objects.all() class ImportCountryStats(ImporterBase): form_class = CountryStatsForm def get_success_url(self): return reverse('admin:country-stats') def get_export_url(self, statistic): return reverse('admin:country-stats-template', kwargs={'statistic': statistic.id}) def get_import_resource_class(self): <|code_end|> using the current file's imports: from django.core.urlresolvers import reverse from custom_importer.forms import ImportFormBase from custom_importer.views import ImporterBase, ExportTemplateBase from country.models import Country from .models import StatDescription, StatValue from .statsimporter import StatisticResource and any relevant context from other files: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # pass # # description = models.TextField() # code = models.SlugField() # # def __unicode__(self): # return self.description # # class StatValue(models.Model): # class Meta: # unique_together = ('description', 'country', 'year') # # description = models.ForeignKey(StatDescription) # country = models.ForeignKey(Country) # year = models.IntegerField() # value = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) # nopep8 # # def __unicode__(self): # return "%s, %s, %s" % ( # self.country, # self.year, # self.value # ) # # Path: washmap/stats/statsimporter.py # class StatisticResource(ModelResource): # """ # StatDescription # # StatValue # Year # @Country # @StatDescription # # Stat Description # Country | Year | Year | Year ... | # A.. | # B.. | # # """ # # class Meta: # model = None # see StatValueRowInstance instead # fields = () # instance_loader_class = StatValueInstanceLoader # import_id_fields = ['country'] # # country = CountryField(attribute='name', readonly=True) # # def __init__(self, statistic, *args, **kwargs): # self.statistic = statistic # super(StatisticResource, self).__init__(*args, **kwargs) # # def before_import(self, dataset, real_dry_run): # # Presume first column is country column # year_headers = dataset.headers[1:] # # # check they are valid, unique, etc # # for year_header in year_headers: # year = int(year_header) # self.fields['year-%d' % year] = YearField(year, column_name='%s' % year) # nopep8 # # def get_dynamic_fields(self): # year_fields = SortedDict() # # values_qs = StatValue.objects.filter(description=self.statistic) # years = values_qs.values_list('year', flat=True).distinct() # # for year in sorted(years): # year_fields['year-%d' % year] = YearField(year, column_name='%s' % year) # nopep8 # # return year_fields # # def get_queryset(self): # countries = Country.objects.all().order_by('name') # statvalues = [] # for country in countries: # inst = StatValueRowInstance(self.statistic, country) # statvalues.append(inst) # # class dummy_queryset(object): # def iterator(self): # return statvalues # # return dummy_queryset() . Output only the next line.
return StatisticResource
Based on the snippet: <|code_start|>from __future__ import unicode_literals, absolute_import def color_data(data): def _get_color(value, palette): if value < 0: return GRAY index = int((value-0.01) / 10) return palette[index] data['wat_color'] = data['wat_value'].apply( _get_color, args=([WATER_COLOR_RANGE]) ) data['san_color'] = data['san_value'].apply( <|code_end|> , predict the immediate next line with the help of imports: from pandas import DataFrame from numpy import where from country.models import Country from main.utils import build_coords_lists from stats.models import StatValue from .chart_constants import SANITATION_COLOR_RANGE, WATER_COLOR_RANGE, GRAY and context (classes, functions, sometimes code) from other files: # Path: washmap/washmap/chart_constants.py # SANITATION_COLOR_RANGE = ["#d45500", "#da670f", "#eb7e1f", "#eb941f", "#ebb01f", "#f2c83d", "#d3cc4f", "#86c26f", "#4db181", "#15b598"] # # WATER_COLOR_RANGE = ["#8c9494", "#8398a2", "#7c9baa", "#73a1b4", "#6aa6bd", "#62abc7", "#5aafd0", "#52b4d9", "#49bae4", "#3fc0f0"] # # GRAY = "#CCCCCC" . Output only the next line.
_get_color, args=([SANITATION_COLOR_RANGE])
Using the snippet: <|code_start|>from __future__ import unicode_literals, absolute_import def color_data(data): def _get_color(value, palette): if value < 0: return GRAY index = int((value-0.01) / 10) return palette[index] data['wat_color'] = data['wat_value'].apply( <|code_end|> , determine the next line of code. You have imports: from pandas import DataFrame from numpy import where from country.models import Country from main.utils import build_coords_lists from stats.models import StatValue from .chart_constants import SANITATION_COLOR_RANGE, WATER_COLOR_RANGE, GRAY and context (class names, function names, or code) available: # Path: washmap/washmap/chart_constants.py # SANITATION_COLOR_RANGE = ["#d45500", "#da670f", "#eb7e1f", "#eb941f", "#ebb01f", "#f2c83d", "#d3cc4f", "#86c26f", "#4db181", "#15b598"] # # WATER_COLOR_RANGE = ["#8c9494", "#8398a2", "#7c9baa", "#73a1b4", "#6aa6bd", "#62abc7", "#5aafd0", "#52b4d9", "#49bae4", "#3fc0f0"] # # GRAY = "#CCCCCC" . Output only the next line.
_get_color, args=([WATER_COLOR_RANGE])
Continue the code snippet: <|code_start|>from __future__ import unicode_literals, absolute_import def color_data(data): def _get_color(value, palette): if value < 0: <|code_end|> . Use current file imports: from pandas import DataFrame from numpy import where from country.models import Country from main.utils import build_coords_lists from stats.models import StatValue from .chart_constants import SANITATION_COLOR_RANGE, WATER_COLOR_RANGE, GRAY and context (classes, functions, or code) from other files: # Path: washmap/washmap/chart_constants.py # SANITATION_COLOR_RANGE = ["#d45500", "#da670f", "#eb7e1f", "#eb941f", "#ebb01f", "#f2c83d", "#d3cc4f", "#86c26f", "#4db181", "#15b598"] # # WATER_COLOR_RANGE = ["#8c9494", "#8398a2", "#7c9baa", "#73a1b4", "#6aa6bd", "#62abc7", "#5aafd0", "#52b4d9", "#49bae4", "#3fc0f0"] # # GRAY = "#CCCCCC" . Output only the next line.
return GRAY
Predict the next line for this snippet: <|code_start|>from __future__ import unicode_literals, absolute_import class StatVisibilityTests(TranslationTestMixin, TestCase): counter = 1 def setUp(self): self.zambia = self.create(Country, name='Zambia') self.egypt = self.create(Country, name='Egypt') <|code_end|> with the help of current file imports: from decimal import Decimal from StringIO import StringIO from django.core.urlresolvers import reverse from django.test import TestCase from django_dynamic_fixture import G from django_harness.fast_dispatch import FastDispatchMixin from django_harness.dates import DateUtilsMixin from django_harness.fast_dispatch import FastDispatchMixin from django_harness.html_parsing import HtmlParsingMixin from django_harness.override_settings import override_settings from django_harness.plugin_testing import PluginTestMixin from django_harness.translation import TranslationTestMixin from django_harness.words import WordUtilsMixin from main.models import Country from ..models import StatDescription, StatValue from django.contrib.auth.models import User from django.contrib.auth.models import User from tablib.formats import _csv import tablib and context from other files: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # pass # # description = models.TextField() # code = models.SlugField() # # def __unicode__(self): # return self.description # # class StatValue(models.Model): # class Meta: # unique_together = ('description', 'country', 'year') # # description = models.ForeignKey(StatDescription) # country = models.ForeignKey(Country) # year = models.IntegerField() # value = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) # nopep8 # # def __unicode__(self): # return "%s, %s, %s" % ( # self.country, # self.year, # self.value # ) , which may contain function names, class names, or code. Output only the next line.
water = self.create(StatDescription, description="Water")
Given snippet: <|code_start|>from __future__ import unicode_literals, absolute_import class StatVisibilityTests(TranslationTestMixin, TestCase): counter = 1 def setUp(self): self.zambia = self.create(Country, name='Zambia') self.egypt = self.create(Country, name='Egypt') water = self.create(StatDescription, description="Water") sanitation = self.create(StatDescription, description="Sanitation") <|code_end|> , continue by predicting the next line. Consider current file imports: from decimal import Decimal from StringIO import StringIO from django.core.urlresolvers import reverse from django.test import TestCase from django_dynamic_fixture import G from django_harness.fast_dispatch import FastDispatchMixin from django_harness.dates import DateUtilsMixin from django_harness.fast_dispatch import FastDispatchMixin from django_harness.html_parsing import HtmlParsingMixin from django_harness.override_settings import override_settings from django_harness.plugin_testing import PluginTestMixin from django_harness.translation import TranslationTestMixin from django_harness.words import WordUtilsMixin from main.models import Country from ..models import StatDescription, StatValue from django.contrib.auth.models import User from django.contrib.auth.models import User from tablib.formats import _csv import tablib and context: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # pass # # description = models.TextField() # code = models.SlugField() # # def __unicode__(self): # return self.description # # class StatValue(models.Model): # class Meta: # unique_together = ('description', 'country', 'year') # # description = models.ForeignKey(StatDescription) # country = models.ForeignKey(Country) # year = models.IntegerField() # value = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) # nopep8 # # def __unicode__(self): # return "%s, %s, %s" % ( # self.country, # self.year, # self.value # ) which might include code, classes, or functions. Output only the next line.
self.zambia_water = G(StatValue, country=self.zambia, description=water)
Next line prediction: <|code_start|> wat_stats = get_wat_stats_all_years() san_stats = get_san_stats_all_years() def make_washmap_map(): <|code_end|> . Use current file imports: (from bokeh.models import ( ColumnDataSource, ) from bokeh.models.widgets import Tabs, Panel, Slider from bokeh.plotting import vplot, hplot from .map_data import ( get_data_with_countries, get_wat_stats_all_years, get_san_stats_all_years, get_line_data, ) from .water_map import ( construct_water_map, construct_water_map_tools, construct_san_map, construct_san_map_tools, construct_water_line, construct_san_line, construct_water_text, construct_san_text, construct_key, layout_components, ) from .chart_constants import ( BLUE, GREEN, WATER_COLOR_RANGE, SANITATION_COLOR_RANGE, )) and context including class names, function names, or small code snippets from other files: # Path: washmap/washmap/map_data.py # def get_data_with_countries(wat_stats_df, san_stats_df, year=1990): # countries_df = get_countries() # # # Get data for year, Merge water & sanitation # wat_stats_df = wat_stats_df[wat_stats_df.year == year] # san_stats_df = san_stats_df[san_stats_df.year == year] # wat_san_df = wat_stats_df.merge(san_stats_df) # # # Merge the countries and stats together # merged_df = countries_df.merge(wat_san_df, how='left') # merged_df = merged_df.fillna(value=-99) # # # Color it # colored_df = color_data(merged_df) # colored_df['year'] = year # # # Otherwise things are sad! # colored_df.columns = colored_df.columns.astype('str') # return colored_df # # def get_wat_stats_all_years(): # wat_stats_df = get_stats_from_model('WNTI_%', 'wat_value') # return wat_stats_df # # def get_san_stats_all_years(): # san_stats_df = get_stats_from_model('SNTI_%', 'san_value') # return san_stats_df # # def get_line_data(country_name): # wat_stats = get_line_stats_from_model('WNTI_%', country_name, 'wat_value') # san_stats = get_line_stats_from_model('SNTI_%', country_name, 'san_value') # wat_san = wat_stats.merge(san_stats, on='year') # return wat_san # # Path: washmap/washmap/water_map.py # def construct_water_map(source): # return construct_map(source, fill_string='wat_color') # # def construct_water_map_tools(source): # plot = construct_water_map(source) # tooltips = "<span class='tooltip-text year'>@year</span>" # tooltips += "<span class='tooltip-text country'>@name</span>" # tooltips += "<span class='tooltip-text value'>@wat_value %</span>" # plot.add_tools(HoverTool(tooltips=tooltips)) # plot.add_tools(TapTool()) # return plot # # def construct_san_map(source): # return construct_map(source, fill_string='san_color', selected_color=DARK_GRAY) # nopep8 # # def construct_san_map_tools(source): # plot = construct_san_map(source) # tooltips = "<span class='tooltip-text year'>@year</span>" # tooltips += "<span class='tooltip-text country'>@name</span>" # tooltips += "<span class='tooltip-text value'>@san_value %</span>" # plot.add_tools(HoverTool(tooltips=tooltips)) # plot.add_tools(TapTool()) # return plot # # def construct_water_line(source): # plot = construct_line(source, 'wat_value', BLUE) # return plot # # def construct_san_line(source): # plot = construct_line(source, 'san_value', GREEN) # return plot # # def construct_water_text(source): # plot = construct_text_box(source, 'wat_value', 'wat_color', BLUE) # return plot # # def construct_san_text(source): # plot = construct_text_box(source, 'san_value', 'san_color', GREEN) # return plot # # def construct_key(palette): # xdr = Range1d(0, 250) # ydr = Range1d(0, 50) # # plot = Plot( # x_range=xdr, # y_range=ydr, # title="", # plot_width=250, # plot_height=50, # min_border=0, # **PLOT_FORMATS # ) # # for index, color in enumerate(palette): # width = 19 # rect = Rect( # x=((width * index) + 40), y=40, # width=width, height=10, # fill_color=color, line_color='white' # ) # plot.add_glyph(rect) # # zero = Text(x=30, y=15, text=['0 %'], **FONT_PROPS_SM) # hundred = Text(x=190, y=15, text=['100 %'], **FONT_PROPS_SM) # plot.add_glyph(zero) # plot.add_glyph(hundred) # # return plot # # def layout_components(map_plot, line_plot, text_box, key): # detail = vplot(text_box, line_plot, key) # mapbox = vplot(map_plot) # composed = hplot(mapbox, detail) # return composed # # Path: washmap/washmap/chart_constants.py # BLUE = WATER_COLOR_RANGE[5] # # GREEN = "#43C4AD" # # WATER_COLOR_RANGE = ["#8c9494", "#8398a2", "#7c9baa", "#73a1b4", "#6aa6bd", "#62abc7", "#5aafd0", "#52b4d9", "#49bae4", "#3fc0f0"] # # SANITATION_COLOR_RANGE = ["#d45500", "#da670f", "#eb7e1f", "#eb941f", "#ebb01f", "#f2c83d", "#d3cc4f", "#86c26f", "#4db181", "#15b598"] . Output only the next line.
data = get_data_with_countries(wat_stats, san_stats)
Next line prediction: <|code_start|> wat_stats = get_wat_stats_all_years() san_stats = get_san_stats_all_years() def make_washmap_map(): data = get_data_with_countries(wat_stats, san_stats) source = ColumnDataSource(data) <|code_end|> . Use current file imports: (from bokeh.models import ( ColumnDataSource, ) from bokeh.models.widgets import Tabs, Panel, Slider from bokeh.plotting import vplot, hplot from .map_data import ( get_data_with_countries, get_wat_stats_all_years, get_san_stats_all_years, get_line_data, ) from .water_map import ( construct_water_map, construct_water_map_tools, construct_san_map, construct_san_map_tools, construct_water_line, construct_san_line, construct_water_text, construct_san_text, construct_key, layout_components, ) from .chart_constants import ( BLUE, GREEN, WATER_COLOR_RANGE, SANITATION_COLOR_RANGE, )) and context including class names, function names, or small code snippets from other files: # Path: washmap/washmap/map_data.py # def get_data_with_countries(wat_stats_df, san_stats_df, year=1990): # countries_df = get_countries() # # # Get data for year, Merge water & sanitation # wat_stats_df = wat_stats_df[wat_stats_df.year == year] # san_stats_df = san_stats_df[san_stats_df.year == year] # wat_san_df = wat_stats_df.merge(san_stats_df) # # # Merge the countries and stats together # merged_df = countries_df.merge(wat_san_df, how='left') # merged_df = merged_df.fillna(value=-99) # # # Color it # colored_df = color_data(merged_df) # colored_df['year'] = year # # # Otherwise things are sad! # colored_df.columns = colored_df.columns.astype('str') # return colored_df # # def get_wat_stats_all_years(): # wat_stats_df = get_stats_from_model('WNTI_%', 'wat_value') # return wat_stats_df # # def get_san_stats_all_years(): # san_stats_df = get_stats_from_model('SNTI_%', 'san_value') # return san_stats_df # # def get_line_data(country_name): # wat_stats = get_line_stats_from_model('WNTI_%', country_name, 'wat_value') # san_stats = get_line_stats_from_model('SNTI_%', country_name, 'san_value') # wat_san = wat_stats.merge(san_stats, on='year') # return wat_san # # Path: washmap/washmap/water_map.py # def construct_water_map(source): # return construct_map(source, fill_string='wat_color') # # def construct_water_map_tools(source): # plot = construct_water_map(source) # tooltips = "<span class='tooltip-text year'>@year</span>" # tooltips += "<span class='tooltip-text country'>@name</span>" # tooltips += "<span class='tooltip-text value'>@wat_value %</span>" # plot.add_tools(HoverTool(tooltips=tooltips)) # plot.add_tools(TapTool()) # return plot # # def construct_san_map(source): # return construct_map(source, fill_string='san_color', selected_color=DARK_GRAY) # nopep8 # # def construct_san_map_tools(source): # plot = construct_san_map(source) # tooltips = "<span class='tooltip-text year'>@year</span>" # tooltips += "<span class='tooltip-text country'>@name</span>" # tooltips += "<span class='tooltip-text value'>@san_value %</span>" # plot.add_tools(HoverTool(tooltips=tooltips)) # plot.add_tools(TapTool()) # return plot # # def construct_water_line(source): # plot = construct_line(source, 'wat_value', BLUE) # return plot # # def construct_san_line(source): # plot = construct_line(source, 'san_value', GREEN) # return plot # # def construct_water_text(source): # plot = construct_text_box(source, 'wat_value', 'wat_color', BLUE) # return plot # # def construct_san_text(source): # plot = construct_text_box(source, 'san_value', 'san_color', GREEN) # return plot # # def construct_key(palette): # xdr = Range1d(0, 250) # ydr = Range1d(0, 50) # # plot = Plot( # x_range=xdr, # y_range=ydr, # title="", # plot_width=250, # plot_height=50, # min_border=0, # **PLOT_FORMATS # ) # # for index, color in enumerate(palette): # width = 19 # rect = Rect( # x=((width * index) + 40), y=40, # width=width, height=10, # fill_color=color, line_color='white' # ) # plot.add_glyph(rect) # # zero = Text(x=30, y=15, text=['0 %'], **FONT_PROPS_SM) # hundred = Text(x=190, y=15, text=['100 %'], **FONT_PROPS_SM) # plot.add_glyph(zero) # plot.add_glyph(hundred) # # return plot # # def layout_components(map_plot, line_plot, text_box, key): # detail = vplot(text_box, line_plot, key) # mapbox = vplot(map_plot) # composed = hplot(mapbox, detail) # return composed # # Path: washmap/washmap/chart_constants.py # BLUE = WATER_COLOR_RANGE[5] # # GREEN = "#43C4AD" # # WATER_COLOR_RANGE = ["#8c9494", "#8398a2", "#7c9baa", "#73a1b4", "#6aa6bd", "#62abc7", "#5aafd0", "#52b4d9", "#49bae4", "#3fc0f0"] # # SANITATION_COLOR_RANGE = ["#d45500", "#da670f", "#eb7e1f", "#eb941f", "#ebb01f", "#f2c83d", "#d3cc4f", "#86c26f", "#4db181", "#15b598"] . Output only the next line.
wat_map = construct_water_map(source)
Using the snippet: <|code_start|>from __future__ import absolute_import, unicode_literals def get_stats_groups_descriptions(countries, visible=None): stats = StatValue.objects.filter(country__in=countries) if visible: stats = stats.filter(visible=visible) # nopep8 stats_groups = StatGroup.objects.filter( statdescription__statvalue__in=stats ).distinct().order_by('order') <|code_end|> , determine the next line of code. You have imports: from django.utils import simplejson from collections import Counter from django.db.models import Max, Min from .models import StatValue, StatDescription, StatGroup and context (class names, function names, or code) available: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # class StatValue(models.Model): # class Meta: # def __unicode__(self): # def __unicode__(self): . Output only the next line.
stats_descriptions = StatDescription.objects.filter(
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import, unicode_literals def get_stats_groups_descriptions(countries, visible=None): stats = StatValue.objects.filter(country__in=countries) if visible: stats = stats.filter(visible=visible) # nopep8 <|code_end|> , predict the next line using imports from the current file: from django.utils import simplejson from collections import Counter from django.db.models import Max, Min from .models import StatValue, StatDescription, StatGroup and context including class names, function names, and sometimes code from other files: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # class StatValue(models.Model): # class Meta: # def __unicode__(self): # def __unicode__(self): . Output only the next line.
stats_groups = StatGroup.objects.filter(
Using the snippet: <|code_start|> class StatValueRowInstance(object): """ Maps an import row onto a collection of StatValue objects. Values for 'statistic' (StatDescription) and 'country' are initialized with the instance loader (called per row). YearFields are added for each non-country column. Implements ORM like interface on row: .save .delete """ years = None pk = None # Has to be faked to keep import-export happy def __init__(self, statistic, country): self.statistic = statistic self.country = country self.years = SortedDict() self.load_statvalues() def get_country(self): return self.country def load_statvalues(self): <|code_end|> , determine the next line of code. You have imports: from copy import deepcopy from django.core.exceptions import ValidationError from django.utils.datastructures import SortedDict from decimal import Decimal from import_export.fields import Field from import_export.instance_loaders import ModelInstanceLoader from import_export.resources import ModelResource from import_export.widgets import DecimalWidget from country.models import Country from .models import StatValue and context (class names, function names, or code) available: # Path: washmap/stats/models.py # class StatValue(models.Model): # class Meta: # unique_together = ('description', 'country', 'year') # # description = models.ForeignKey(StatDescription) # country = models.ForeignKey(Country) # year = models.IntegerField() # value = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) # nopep8 # # def __unicode__(self): # return "%s, %s, %s" % ( # self.country, # self.year, # self.value # ) . Output only the next line.
values = StatValue.objects.filter(description=self.statistic,
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, unicode_literals class CountryAdmin(TranslatableAdmin): pass class RegionAdmin(TranslatableAdmin): pass admin.site.register(Region, RegionAdmin) <|code_end|> with the help of current file imports: from django.contrib import admin from hvad.admin import TranslatableAdmin from .models import ( Country, Region, ) and context from other files: # Path: washmap/country/models.py # class Country(TranslatableModel): # # class Meta: # verbose_name_plural = 'Countries' # ordering = ['slug'] # # translations = TranslatedFields( # local_name=models.CharField(max_length=255) # ) # region = models.ForeignKey(Region, null=True, blank=True) # name = models.CharField(max_length=255) # slug = models.SlugField(unique=True) # created_at = models.DateTimeField(null=True, blank=True) # updated_at = models.DateTimeField(null=True, blank=True) # visible = models.IntegerField(null=True, blank=True) # currency_name = models.CharField(max_length=40, blank=True) # last_contributor_id = models.IntegerField(null=True, blank=True) # last_contributed_on = models.DateTimeField(null=True, blank=True) # last_contributed_sector = models.CharField(max_length=255, blank=True) # country_meta = CountryField(null=True, blank=True) # boundary = models.TextField( # blank=True, # help_text="A geojson representation of the geographical boundary" # ) # # @property # def code(self): # return self.country_meta.code # # def __unicode__(self): # return self.local_name # # def get_absolute_url(self): # return reverse('country-comparison', kwargs={'country': self.slug}) # # class Region(TranslatableModel): # translations = TranslatedFields( # local_name=models.CharField(max_length=255) # ) # name = models.CharField(max_length=255) # water_declaration = models.CharField(max_length=255, blank=True) # sanitation_declaration = models.CharField(max_length=255, blank=True) # slug = models.SlugField(unique=True) # created_at = models.DateTimeField(null=True, blank=True) # updated_at = models.DateTimeField(null=True, blank=True) # coords = models.TextField(max_length=255, blank=True) # # def __unicode__(self): # return self.name , which may contain function names, class names, or code. Output only the next line.
admin.site.register(Country, CountryAdmin)
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, unicode_literals class CountryAdmin(TranslatableAdmin): pass class RegionAdmin(TranslatableAdmin): pass <|code_end|> with the help of current file imports: from django.contrib import admin from hvad.admin import TranslatableAdmin from .models import ( Country, Region, ) and context from other files: # Path: washmap/country/models.py # class Country(TranslatableModel): # # class Meta: # verbose_name_plural = 'Countries' # ordering = ['slug'] # # translations = TranslatedFields( # local_name=models.CharField(max_length=255) # ) # region = models.ForeignKey(Region, null=True, blank=True) # name = models.CharField(max_length=255) # slug = models.SlugField(unique=True) # created_at = models.DateTimeField(null=True, blank=True) # updated_at = models.DateTimeField(null=True, blank=True) # visible = models.IntegerField(null=True, blank=True) # currency_name = models.CharField(max_length=40, blank=True) # last_contributor_id = models.IntegerField(null=True, blank=True) # last_contributed_on = models.DateTimeField(null=True, blank=True) # last_contributed_sector = models.CharField(max_length=255, blank=True) # country_meta = CountryField(null=True, blank=True) # boundary = models.TextField( # blank=True, # help_text="A geojson representation of the geographical boundary" # ) # # @property # def code(self): # return self.country_meta.code # # def __unicode__(self): # return self.local_name # # def get_absolute_url(self): # return reverse('country-comparison', kwargs={'country': self.slug}) # # class Region(TranslatableModel): # translations = TranslatedFields( # local_name=models.CharField(max_length=255) # ) # name = models.CharField(max_length=255) # water_declaration = models.CharField(max_length=255, blank=True) # sanitation_declaration = models.CharField(max_length=255, blank=True) # slug = models.SlugField(unique=True) # created_at = models.DateTimeField(null=True, blank=True) # updated_at = models.DateTimeField(null=True, blank=True) # coords = models.TextField(max_length=255, blank=True) # # def __unicode__(self): # return self.name , which may contain function names, class names, or code. Output only the next line.
admin.site.register(Region, RegionAdmin)
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals, absolute_import @pytest.mark.django_db @pytest.mark.urls('country_comparison.test_urls') def test_basic_stat_presence( group_a, stat_a_i, zambia, summary_url, client ): <|code_end|> , predict the next line using imports from the current file: import json import pytest from bs4 import BeautifulSoup from django_dynamic_fixture import G from django.contrib.auth.models import User from django.utils import translation from main.models import Country from country_comparison.views import CountrySummary from ..models import StatValue and context including class names, function names, and sometimes code from other files: # Path: washmap/stats/models.py # class StatValue(models.Model): # class Meta: # unique_together = ('description', 'country', 'year') # # description = models.ForeignKey(StatDescription) # country = models.ForeignKey(Country) # year = models.IntegerField() # value = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) # nopep8 # # def __unicode__(self): # return "%s, %s, %s" % ( # self.country, # self.year, # self.value # ) . Output only the next line.
G(StatValue, description=stat_a_i, country=zambia)
Given the following code snippet before the placeholder: <|code_start|>from __future__ import unicode_literals, absolute_import def construct_map(source, fill_string='water_color', selected_color=ORANGE): assert isinstance(source, ColumnDataSource), "Require ColumnDataSource" # Plot and axes x_start, x_end = (-18, 55) y_start, y_end = (-35, 38) xdr = Range1d(x_start, x_end) ydr = Range1d(y_start, y_end) aspect_ratio = (x_end - x_start) / (y_end - y_start) plot_height = 600 plot_width = int(plot_height * aspect_ratio) plot = Plot( x_range=xdr, y_range=ydr, title="", plot_width=plot_width, plot_height=plot_height, min_border=0, <|code_end|> , predict the next line using imports from the current file: from bokeh.models import ( ColumnDataSource, HoverTool, Line, LinearAxis, Patches, Plot, Range1d, Rect, SingleIntervalTicker, TapTool, Text, Triangle, ) from bokeh.plotting import vplot, hplot from .chart_constants import ( PLOT_FORMATS, ORANGE, BLUE, DARK_GRAY, AXIS_FORMATS, ORANGE_SHADOW, FONT_PROPS_SM, FONT_PROPS_MD, FONT_PROPS_LG, GREEN ) and context including class names, function names, and sometimes code from other files: # Path: washmap/washmap/chart_constants.py # PLOT_FORMATS = dict( # toolbar_location=None, # outline_line_color="#FFFFFF", # title_text_font=FONT, # title_text_align='left', # title_text_color=BLUE, # title_text_baseline='top', # ) # # ORANGE = "#FFA500" # # BLUE = WATER_COLOR_RANGE[5] # # DARK_GRAY = "#6B6B73" # # AXIS_FORMATS = dict( # minor_tick_in=None, # minor_tick_out=None, # major_tick_in=None, # major_label_text_font=FONT, # major_label_text_font_size="10pt", # major_label_text_font_style="bold", # axis_label_text_font=FONT, # axis_label_text_font_size="10pt", # # axis_line_color=GRAY, # major_tick_line_color=GRAY, # major_label_text_color=DARK_GRAY, # # major_tick_line_cap="round", # axis_line_cap="round", # axis_line_width=3, # major_tick_line_width=3, # ) # # ORANGE_SHADOW = "#D48702" # # FONT_PROPS_SM = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='10pt', # ) # # FONT_PROPS_MD = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='18pt', # ) # # FONT_PROPS_LG = dict( # text_font=FONT, # text_font_style="bold", # text_font_size='23pt', # ) # # GREEN = "#43C4AD" . Output only the next line.
**PLOT_FORMATS
Next line prediction: <|code_start|> ) # Add the writing country = Text(x=5, y=50, text='name', **FONT_PROPS_MD) percent = Text(x=15, y=10, text=value_string, text_color=color_string, **FONT_PROPS_LG) # nopep8 percent_sign = Text(x=69, y=10, text=['%'], text_color=color_string, **FONT_PROPS_LG) # nopep8 line_one = Text(x=90, y=28, text=['of people had'], **FONT_PROPS_SM) line_two_p1 = Text(x=90, y=14, text=['access in'], **FONT_PROPS_SM) line_two_p2 = Text(x=136, y=14, text='year', **FONT_PROPS_SM) plot.add_glyph(source, Text(), selection_glyph=country) plot.add_glyph(source, Text(), selection_glyph=percent) plot.add_glyph(source, Text(), selection_glyph=percent_sign) plot.add_glyph(line_one) plot.add_glyph(line_two_p1) plot.add_glyph(source, Text(), selection_glyph=line_two_p2) # Add the orange box with year shadow = Triangle(x=150, y=109, size=25, fill_color=ORANGE_SHADOW, line_color=None) # nopep8 plot.add_glyph(shadow) # Add the blue bar rect = Rect(x=75, y=99, width=150, height=5, fill_color=bar_color, line_color=None) # nopep8 plot.add_glyph(rect) box = Rect(x=200, y=100, width=100, height=40, fill_color=ORANGE, line_color=None) # nopep8 plot.add_glyph(box) year = Text(x=160, y=85, text='year', text_font_size='18pt', text_color="#FFFFF", text_font_style="bold") # nopep8 plot.add_glyph(source, Text(), selection_glyph=year) return plot def construct_water_text(source): <|code_end|> . Use current file imports: (from bokeh.models import ( ColumnDataSource, HoverTool, Line, LinearAxis, Patches, Plot, Range1d, Rect, SingleIntervalTicker, TapTool, Text, Triangle, ) from bokeh.plotting import vplot, hplot from .chart_constants import ( PLOT_FORMATS, ORANGE, BLUE, DARK_GRAY, AXIS_FORMATS, ORANGE_SHADOW, FONT_PROPS_SM, FONT_PROPS_MD, FONT_PROPS_LG, GREEN )) and context including class names, function names, or small code snippets from other files: # Path: washmap/washmap/chart_constants.py # PLOT_FORMATS = dict( # toolbar_location=None, # outline_line_color="#FFFFFF", # title_text_font=FONT, # title_text_align='left', # title_text_color=BLUE, # title_text_baseline='top', # ) # # ORANGE = "#FFA500" # # BLUE = WATER_COLOR_RANGE[5] # # DARK_GRAY = "#6B6B73" # # AXIS_FORMATS = dict( # minor_tick_in=None, # minor_tick_out=None, # major_tick_in=None, # major_label_text_font=FONT, # major_label_text_font_size="10pt", # major_label_text_font_style="bold", # axis_label_text_font=FONT, # axis_label_text_font_size="10pt", # # axis_line_color=GRAY, # major_tick_line_color=GRAY, # major_label_text_color=DARK_GRAY, # # major_tick_line_cap="round", # axis_line_cap="round", # axis_line_width=3, # major_tick_line_width=3, # ) # # ORANGE_SHADOW = "#D48702" # # FONT_PROPS_SM = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='10pt', # ) # # FONT_PROPS_MD = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='18pt', # ) # # FONT_PROPS_LG = dict( # text_font=FONT, # text_font_style="bold", # text_font_size='23pt', # ) # # GREEN = "#43C4AD" . Output only the next line.
plot = construct_text_box(source, 'wat_value', 'wat_color', BLUE)
Predict the next line for this snippet: <|code_start|> plot = Plot( x_range=xdr, y_range=ydr, title="", plot_width=plot_width, plot_height=plot_height, min_border=0, **PLOT_FORMATS ) borders = Patches( xs='xs', ys='ys', fill_color=fill_string, fill_alpha=1, line_color="#FFFFFF", line_width=1, ) selected_borders = Patches( xs='xs', ys='ys', fill_color=fill_string, fill_alpha=1, line_color=selected_color, line_width=3, ) plot.add_glyph(source, borders, selection_glyph=selected_borders, nonselection_glyph=borders) # nopep8 return plot def construct_water_map(source): return construct_map(source, fill_string='wat_color') def construct_san_map(source): <|code_end|> with the help of current file imports: from bokeh.models import ( ColumnDataSource, HoverTool, Line, LinearAxis, Patches, Plot, Range1d, Rect, SingleIntervalTicker, TapTool, Text, Triangle, ) from bokeh.plotting import vplot, hplot from .chart_constants import ( PLOT_FORMATS, ORANGE, BLUE, DARK_GRAY, AXIS_FORMATS, ORANGE_SHADOW, FONT_PROPS_SM, FONT_PROPS_MD, FONT_PROPS_LG, GREEN ) and context from other files: # Path: washmap/washmap/chart_constants.py # PLOT_FORMATS = dict( # toolbar_location=None, # outline_line_color="#FFFFFF", # title_text_font=FONT, # title_text_align='left', # title_text_color=BLUE, # title_text_baseline='top', # ) # # ORANGE = "#FFA500" # # BLUE = WATER_COLOR_RANGE[5] # # DARK_GRAY = "#6B6B73" # # AXIS_FORMATS = dict( # minor_tick_in=None, # minor_tick_out=None, # major_tick_in=None, # major_label_text_font=FONT, # major_label_text_font_size="10pt", # major_label_text_font_style="bold", # axis_label_text_font=FONT, # axis_label_text_font_size="10pt", # # axis_line_color=GRAY, # major_tick_line_color=GRAY, # major_label_text_color=DARK_GRAY, # # major_tick_line_cap="round", # axis_line_cap="round", # axis_line_width=3, # major_tick_line_width=3, # ) # # ORANGE_SHADOW = "#D48702" # # FONT_PROPS_SM = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='10pt', # ) # # FONT_PROPS_MD = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='18pt', # ) # # FONT_PROPS_LG = dict( # text_font=FONT, # text_font_style="bold", # text_font_size='23pt', # ) # # GREEN = "#43C4AD" , which may contain function names, class names, or code. Output only the next line.
return construct_map(source, fill_string='san_color', selected_color=DARK_GRAY) # nopep8
Continue the code snippet: <|code_start|> plot.add_glyph(box) year = Text(x=160, y=85, text='year', text_font_size='18pt', text_color="#FFFFF", text_font_style="bold") # nopep8 plot.add_glyph(source, Text(), selection_glyph=year) return plot def construct_water_text(source): plot = construct_text_box(source, 'wat_value', 'wat_color', BLUE) return plot def construct_san_text(source): plot = construct_text_box(source, 'san_value', 'san_color', GREEN) return plot def construct_line(source, value_string, line_color=BLUE): xdr = Range1d(1990, 2013) ydr = Range1d(0, 100) line_plot = Plot( x_range=xdr, y_range=ydr, title="", plot_width=250, plot_height=150, min_border_top=10, min_border_left=50, **PLOT_FORMATS ) <|code_end|> . Use current file imports: from bokeh.models import ( ColumnDataSource, HoverTool, Line, LinearAxis, Patches, Plot, Range1d, Rect, SingleIntervalTicker, TapTool, Text, Triangle, ) from bokeh.plotting import vplot, hplot from .chart_constants import ( PLOT_FORMATS, ORANGE, BLUE, DARK_GRAY, AXIS_FORMATS, ORANGE_SHADOW, FONT_PROPS_SM, FONT_PROPS_MD, FONT_PROPS_LG, GREEN ) and context (classes, functions, or code) from other files: # Path: washmap/washmap/chart_constants.py # PLOT_FORMATS = dict( # toolbar_location=None, # outline_line_color="#FFFFFF", # title_text_font=FONT, # title_text_align='left', # title_text_color=BLUE, # title_text_baseline='top', # ) # # ORANGE = "#FFA500" # # BLUE = WATER_COLOR_RANGE[5] # # DARK_GRAY = "#6B6B73" # # AXIS_FORMATS = dict( # minor_tick_in=None, # minor_tick_out=None, # major_tick_in=None, # major_label_text_font=FONT, # major_label_text_font_size="10pt", # major_label_text_font_style="bold", # axis_label_text_font=FONT, # axis_label_text_font_size="10pt", # # axis_line_color=GRAY, # major_tick_line_color=GRAY, # major_label_text_color=DARK_GRAY, # # major_tick_line_cap="round", # axis_line_cap="round", # axis_line_width=3, # major_tick_line_width=3, # ) # # ORANGE_SHADOW = "#D48702" # # FONT_PROPS_SM = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='10pt', # ) # # FONT_PROPS_MD = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='18pt', # ) # # FONT_PROPS_LG = dict( # text_font=FONT, # text_font_style="bold", # text_font_size='23pt', # ) # # GREEN = "#43C4AD" . Output only the next line.
xaxis = LinearAxis(SingleIntervalTicker(interval=50), **AXIS_FORMATS)
Continue the code snippet: <|code_start|> def construct_text_box(source, value_string, color_string, bar_color): # Plot and axes xdr = Range1d(0, 220) ydr = Range1d(0, 120) plot = Plot( x_range=xdr, y_range=ydr, title="", plot_width=250, plot_height=120, min_border=0, **PLOT_FORMATS ) # Add the writing country = Text(x=5, y=50, text='name', **FONT_PROPS_MD) percent = Text(x=15, y=10, text=value_string, text_color=color_string, **FONT_PROPS_LG) # nopep8 percent_sign = Text(x=69, y=10, text=['%'], text_color=color_string, **FONT_PROPS_LG) # nopep8 line_one = Text(x=90, y=28, text=['of people had'], **FONT_PROPS_SM) line_two_p1 = Text(x=90, y=14, text=['access in'], **FONT_PROPS_SM) line_two_p2 = Text(x=136, y=14, text='year', **FONT_PROPS_SM) plot.add_glyph(source, Text(), selection_glyph=country) plot.add_glyph(source, Text(), selection_glyph=percent) plot.add_glyph(source, Text(), selection_glyph=percent_sign) plot.add_glyph(line_one) plot.add_glyph(line_two_p1) plot.add_glyph(source, Text(), selection_glyph=line_two_p2) # Add the orange box with year <|code_end|> . Use current file imports: from bokeh.models import ( ColumnDataSource, HoverTool, Line, LinearAxis, Patches, Plot, Range1d, Rect, SingleIntervalTicker, TapTool, Text, Triangle, ) from bokeh.plotting import vplot, hplot from .chart_constants import ( PLOT_FORMATS, ORANGE, BLUE, DARK_GRAY, AXIS_FORMATS, ORANGE_SHADOW, FONT_PROPS_SM, FONT_PROPS_MD, FONT_PROPS_LG, GREEN ) and context (classes, functions, or code) from other files: # Path: washmap/washmap/chart_constants.py # PLOT_FORMATS = dict( # toolbar_location=None, # outline_line_color="#FFFFFF", # title_text_font=FONT, # title_text_align='left', # title_text_color=BLUE, # title_text_baseline='top', # ) # # ORANGE = "#FFA500" # # BLUE = WATER_COLOR_RANGE[5] # # DARK_GRAY = "#6B6B73" # # AXIS_FORMATS = dict( # minor_tick_in=None, # minor_tick_out=None, # major_tick_in=None, # major_label_text_font=FONT, # major_label_text_font_size="10pt", # major_label_text_font_style="bold", # axis_label_text_font=FONT, # axis_label_text_font_size="10pt", # # axis_line_color=GRAY, # major_tick_line_color=GRAY, # major_label_text_color=DARK_GRAY, # # major_tick_line_cap="round", # axis_line_cap="round", # axis_line_width=3, # major_tick_line_width=3, # ) # # ORANGE_SHADOW = "#D48702" # # FONT_PROPS_SM = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='10pt', # ) # # FONT_PROPS_MD = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='18pt', # ) # # FONT_PROPS_LG = dict( # text_font=FONT, # text_font_style="bold", # text_font_size='23pt', # ) # # GREEN = "#43C4AD" . Output only the next line.
shadow = Triangle(x=150, y=109, size=25, fill_color=ORANGE_SHADOW, line_color=None) # nopep8
Given the code snippet: <|code_start|> def construct_san_map_tools(source): plot = construct_san_map(source) tooltips = "<span class='tooltip-text year'>@year</span>" tooltips += "<span class='tooltip-text country'>@name</span>" tooltips += "<span class='tooltip-text value'>@san_value %</span>" plot.add_tools(HoverTool(tooltips=tooltips)) plot.add_tools(TapTool()) return plot def construct_text_box(source, value_string, color_string, bar_color): # Plot and axes xdr = Range1d(0, 220) ydr = Range1d(0, 120) plot = Plot( x_range=xdr, y_range=ydr, title="", plot_width=250, plot_height=120, min_border=0, **PLOT_FORMATS ) # Add the writing country = Text(x=5, y=50, text='name', **FONT_PROPS_MD) percent = Text(x=15, y=10, text=value_string, text_color=color_string, **FONT_PROPS_LG) # nopep8 percent_sign = Text(x=69, y=10, text=['%'], text_color=color_string, **FONT_PROPS_LG) # nopep8 <|code_end|> , generate the next line using the imports in this file: from bokeh.models import ( ColumnDataSource, HoverTool, Line, LinearAxis, Patches, Plot, Range1d, Rect, SingleIntervalTicker, TapTool, Text, Triangle, ) from bokeh.plotting import vplot, hplot from .chart_constants import ( PLOT_FORMATS, ORANGE, BLUE, DARK_GRAY, AXIS_FORMATS, ORANGE_SHADOW, FONT_PROPS_SM, FONT_PROPS_MD, FONT_PROPS_LG, GREEN ) and context (functions, classes, or occasionally code) from other files: # Path: washmap/washmap/chart_constants.py # PLOT_FORMATS = dict( # toolbar_location=None, # outline_line_color="#FFFFFF", # title_text_font=FONT, # title_text_align='left', # title_text_color=BLUE, # title_text_baseline='top', # ) # # ORANGE = "#FFA500" # # BLUE = WATER_COLOR_RANGE[5] # # DARK_GRAY = "#6B6B73" # # AXIS_FORMATS = dict( # minor_tick_in=None, # minor_tick_out=None, # major_tick_in=None, # major_label_text_font=FONT, # major_label_text_font_size="10pt", # major_label_text_font_style="bold", # axis_label_text_font=FONT, # axis_label_text_font_size="10pt", # # axis_line_color=GRAY, # major_tick_line_color=GRAY, # major_label_text_color=DARK_GRAY, # # major_tick_line_cap="round", # axis_line_cap="round", # axis_line_width=3, # major_tick_line_width=3, # ) # # ORANGE_SHADOW = "#D48702" # # FONT_PROPS_SM = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='10pt', # ) # # FONT_PROPS_MD = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='18pt', # ) # # FONT_PROPS_LG = dict( # text_font=FONT, # text_font_style="bold", # text_font_size='23pt', # ) # # GREEN = "#43C4AD" . Output only the next line.
line_one = Text(x=90, y=28, text=['of people had'], **FONT_PROPS_SM)
Here is a snippet: <|code_start|> plot.add_tools(HoverTool(tooltips=tooltips)) plot.add_tools(TapTool()) return plot def construct_san_map_tools(source): plot = construct_san_map(source) tooltips = "<span class='tooltip-text year'>@year</span>" tooltips += "<span class='tooltip-text country'>@name</span>" tooltips += "<span class='tooltip-text value'>@san_value %</span>" plot.add_tools(HoverTool(tooltips=tooltips)) plot.add_tools(TapTool()) return plot def construct_text_box(source, value_string, color_string, bar_color): # Plot and axes xdr = Range1d(0, 220) ydr = Range1d(0, 120) plot = Plot( x_range=xdr, y_range=ydr, title="", plot_width=250, plot_height=120, min_border=0, **PLOT_FORMATS ) # Add the writing <|code_end|> . Write the next line using the current file imports: from bokeh.models import ( ColumnDataSource, HoverTool, Line, LinearAxis, Patches, Plot, Range1d, Rect, SingleIntervalTicker, TapTool, Text, Triangle, ) from bokeh.plotting import vplot, hplot from .chart_constants import ( PLOT_FORMATS, ORANGE, BLUE, DARK_GRAY, AXIS_FORMATS, ORANGE_SHADOW, FONT_PROPS_SM, FONT_PROPS_MD, FONT_PROPS_LG, GREEN ) and context from other files: # Path: washmap/washmap/chart_constants.py # PLOT_FORMATS = dict( # toolbar_location=None, # outline_line_color="#FFFFFF", # title_text_font=FONT, # title_text_align='left', # title_text_color=BLUE, # title_text_baseline='top', # ) # # ORANGE = "#FFA500" # # BLUE = WATER_COLOR_RANGE[5] # # DARK_GRAY = "#6B6B73" # # AXIS_FORMATS = dict( # minor_tick_in=None, # minor_tick_out=None, # major_tick_in=None, # major_label_text_font=FONT, # major_label_text_font_size="10pt", # major_label_text_font_style="bold", # axis_label_text_font=FONT, # axis_label_text_font_size="10pt", # # axis_line_color=GRAY, # major_tick_line_color=GRAY, # major_label_text_color=DARK_GRAY, # # major_tick_line_cap="round", # axis_line_cap="round", # axis_line_width=3, # major_tick_line_width=3, # ) # # ORANGE_SHADOW = "#D48702" # # FONT_PROPS_SM = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='10pt', # ) # # FONT_PROPS_MD = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='18pt', # ) # # FONT_PROPS_LG = dict( # text_font=FONT, # text_font_style="bold", # text_font_size='23pt', # ) # # GREEN = "#43C4AD" , which may include functions, classes, or code. Output only the next line.
country = Text(x=5, y=50, text='name', **FONT_PROPS_MD)
Given the following code snippet before the placeholder: <|code_start|> plot.add_tools(TapTool()) return plot def construct_san_map_tools(source): plot = construct_san_map(source) tooltips = "<span class='tooltip-text year'>@year</span>" tooltips += "<span class='tooltip-text country'>@name</span>" tooltips += "<span class='tooltip-text value'>@san_value %</span>" plot.add_tools(HoverTool(tooltips=tooltips)) plot.add_tools(TapTool()) return plot def construct_text_box(source, value_string, color_string, bar_color): # Plot and axes xdr = Range1d(0, 220) ydr = Range1d(0, 120) plot = Plot( x_range=xdr, y_range=ydr, title="", plot_width=250, plot_height=120, min_border=0, **PLOT_FORMATS ) # Add the writing country = Text(x=5, y=50, text='name', **FONT_PROPS_MD) <|code_end|> , predict the next line using imports from the current file: from bokeh.models import ( ColumnDataSource, HoverTool, Line, LinearAxis, Patches, Plot, Range1d, Rect, SingleIntervalTicker, TapTool, Text, Triangle, ) from bokeh.plotting import vplot, hplot from .chart_constants import ( PLOT_FORMATS, ORANGE, BLUE, DARK_GRAY, AXIS_FORMATS, ORANGE_SHADOW, FONT_PROPS_SM, FONT_PROPS_MD, FONT_PROPS_LG, GREEN ) and context including class names, function names, and sometimes code from other files: # Path: washmap/washmap/chart_constants.py # PLOT_FORMATS = dict( # toolbar_location=None, # outline_line_color="#FFFFFF", # title_text_font=FONT, # title_text_align='left', # title_text_color=BLUE, # title_text_baseline='top', # ) # # ORANGE = "#FFA500" # # BLUE = WATER_COLOR_RANGE[5] # # DARK_GRAY = "#6B6B73" # # AXIS_FORMATS = dict( # minor_tick_in=None, # minor_tick_out=None, # major_tick_in=None, # major_label_text_font=FONT, # major_label_text_font_size="10pt", # major_label_text_font_style="bold", # axis_label_text_font=FONT, # axis_label_text_font_size="10pt", # # axis_line_color=GRAY, # major_tick_line_color=GRAY, # major_label_text_color=DARK_GRAY, # # major_tick_line_cap="round", # axis_line_cap="round", # axis_line_width=3, # major_tick_line_width=3, # ) # # ORANGE_SHADOW = "#D48702" # # FONT_PROPS_SM = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='10pt', # ) # # FONT_PROPS_MD = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='18pt', # ) # # FONT_PROPS_LG = dict( # text_font=FONT, # text_font_style="bold", # text_font_size='23pt', # ) # # GREEN = "#43C4AD" . Output only the next line.
percent = Text(x=15, y=10, text=value_string, text_color=color_string, **FONT_PROPS_LG) # nopep8
Predict the next line after this snippet: <|code_start|> line_one = Text(x=90, y=28, text=['of people had'], **FONT_PROPS_SM) line_two_p1 = Text(x=90, y=14, text=['access in'], **FONT_PROPS_SM) line_two_p2 = Text(x=136, y=14, text='year', **FONT_PROPS_SM) plot.add_glyph(source, Text(), selection_glyph=country) plot.add_glyph(source, Text(), selection_glyph=percent) plot.add_glyph(source, Text(), selection_glyph=percent_sign) plot.add_glyph(line_one) plot.add_glyph(line_two_p1) plot.add_glyph(source, Text(), selection_glyph=line_two_p2) # Add the orange box with year shadow = Triangle(x=150, y=109, size=25, fill_color=ORANGE_SHADOW, line_color=None) # nopep8 plot.add_glyph(shadow) # Add the blue bar rect = Rect(x=75, y=99, width=150, height=5, fill_color=bar_color, line_color=None) # nopep8 plot.add_glyph(rect) box = Rect(x=200, y=100, width=100, height=40, fill_color=ORANGE, line_color=None) # nopep8 plot.add_glyph(box) year = Text(x=160, y=85, text='year', text_font_size='18pt', text_color="#FFFFF", text_font_style="bold") # nopep8 plot.add_glyph(source, Text(), selection_glyph=year) return plot def construct_water_text(source): plot = construct_text_box(source, 'wat_value', 'wat_color', BLUE) return plot def construct_san_text(source): <|code_end|> using the current file's imports: from bokeh.models import ( ColumnDataSource, HoverTool, Line, LinearAxis, Patches, Plot, Range1d, Rect, SingleIntervalTicker, TapTool, Text, Triangle, ) from bokeh.plotting import vplot, hplot from .chart_constants import ( PLOT_FORMATS, ORANGE, BLUE, DARK_GRAY, AXIS_FORMATS, ORANGE_SHADOW, FONT_PROPS_SM, FONT_PROPS_MD, FONT_PROPS_LG, GREEN ) and any relevant context from other files: # Path: washmap/washmap/chart_constants.py # PLOT_FORMATS = dict( # toolbar_location=None, # outline_line_color="#FFFFFF", # title_text_font=FONT, # title_text_align='left', # title_text_color=BLUE, # title_text_baseline='top', # ) # # ORANGE = "#FFA500" # # BLUE = WATER_COLOR_RANGE[5] # # DARK_GRAY = "#6B6B73" # # AXIS_FORMATS = dict( # minor_tick_in=None, # minor_tick_out=None, # major_tick_in=None, # major_label_text_font=FONT, # major_label_text_font_size="10pt", # major_label_text_font_style="bold", # axis_label_text_font=FONT, # axis_label_text_font_size="10pt", # # axis_line_color=GRAY, # major_tick_line_color=GRAY, # major_label_text_color=DARK_GRAY, # # major_tick_line_cap="round", # axis_line_cap="round", # axis_line_width=3, # major_tick_line_width=3, # ) # # ORANGE_SHADOW = "#D48702" # # FONT_PROPS_SM = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='10pt', # ) # # FONT_PROPS_MD = dict( # text_color=DARK_GRAY, # text_font=FONT, # text_font_style="normal", # text_font_size='18pt', # ) # # FONT_PROPS_LG = dict( # text_font=FONT, # text_font_style="bold", # text_font_size='23pt', # ) # # GREEN = "#43C4AD" . Output only the next line.
plot = construct_text_box(source, 'san_value', 'san_color', GREEN)
Predict the next line for this snippet: <|code_start|>from __future__ import unicode_literals, absolute_import """ ======================== FIXTURES ======================= """ @pytest.fixture def tt(): ttm = TranslationTestMixin() ttm.counter = 0 return ttm @pytest.fixture def group_a(tt): <|code_end|> with the help of current file imports: import pytest from django.core.urlresolvers import reverse from django_harness.translation import TranslationTestMixin from main.models import Country from ..models import StatGroup, StatDescription and context from other files: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # class StatValue(models.Model): # class Meta: # def __unicode__(self): # def __unicode__(self): , which may contain function names, class names, or code. Output only the next line.
ttg = tt.create(StatGroup, description="Stat Group A", order=1)
Based on the snippet: <|code_start|>from __future__ import unicode_literals, absolute_import """ ======================== FIXTURES ======================= """ @pytest.fixture def tt(): ttm = TranslationTestMixin() ttm.counter = 0 return ttm @pytest.fixture def group_a(tt): ttg = tt.create(StatGroup, description="Stat Group A", order=1) return ttg @pytest.fixture def stat_a_i(tt, group_a): <|code_end|> , predict the immediate next line with the help of imports: import pytest from django.core.urlresolvers import reverse from django_harness.translation import TranslationTestMixin from main.models import Country from ..models import StatGroup, StatDescription and context (classes, functions, sometimes code) from other files: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # class StatValue(models.Model): # class Meta: # def __unicode__(self): # def __unicode__(self): . Output only the next line.
ttd = tt.create(StatDescription,
Here is a snippet: <|code_start|>from __future__ import absolute_import, unicode_literals class StatValueAdmin(admin.ModelAdmin): list_display = ('description', 'year', 'country', 'value') list_filter = ('description', 'country', 'year') <|code_end|> . Write the next line using the current file imports: from django.contrib import admin from .models import ( StatDescription, StatValue ) and context from other files: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # pass # # description = models.TextField() # code = models.SlugField() # # def __unicode__(self): # return self.description # # class StatValue(models.Model): # class Meta: # unique_together = ('description', 'country', 'year') # # description = models.ForeignKey(StatDescription) # country = models.ForeignKey(Country) # year = models.IntegerField() # value = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) # nopep8 # # def __unicode__(self): # return "%s, %s, %s" % ( # self.country, # self.year, # self.value # ) , which may include functions, classes, or code. Output only the next line.
admin.site.register(StatDescription)
Based on the snippet: <|code_start|>from __future__ import absolute_import, unicode_literals class StatValueAdmin(admin.ModelAdmin): list_display = ('description', 'year', 'country', 'value') list_filter = ('description', 'country', 'year') admin.site.register(StatDescription) <|code_end|> , predict the immediate next line with the help of imports: from django.contrib import admin from .models import ( StatDescription, StatValue ) and context (classes, functions, sometimes code) from other files: # Path: washmap/stats/models.py # class StatDescription(Sortable): # class Meta(Sortable.Meta): # pass # # description = models.TextField() # code = models.SlugField() # # def __unicode__(self): # return self.description # # class StatValue(models.Model): # class Meta: # unique_together = ('description', 'country', 'year') # # description = models.ForeignKey(StatDescription) # country = models.ForeignKey(Country) # year = models.IntegerField() # value = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) # nopep8 # # def __unicode__(self): # return "%s, %s, %s" % ( # self.country, # self.year, # self.value # ) . Output only the next line.
admin.site.register(StatValue, StatValueAdmin)
Predict the next line for this snippet: <|code_start|># encoding: utf-8 from __future__ import unicode_literals, absolute_import @pytest.mark.django_db @pytest.mark.urls('country_comparison.test_urls') def test_basic_stat_presence( group_a, stat_a_i, zambia, comparison_url, client ): <|code_end|> with the help of current file imports: import pytest from bs4 import BeautifulSoup from django_dynamic_fixture import G from main.models import Country from ..models import StatValue and context from other files: # Path: washmap/stats/models.py # class StatValue(models.Model): # class Meta: # unique_together = ('description', 'country', 'year') # # description = models.ForeignKey(StatDescription) # country = models.ForeignKey(Country) # year = models.IntegerField() # value = models.DecimalField(max_digits=20, decimal_places=10, null=True, blank=True) # nopep8 # # def __unicode__(self): # return "%s, %s, %s" % ( # self.country, # self.year, # self.value # ) , which may contain function names, class names, or code. Output only the next line.
G(StatValue, description=stat_a_i, country=zambia)
Given snippet: <|code_start|>from __future__ import unicode_literals, absolute_import urlpatterns = patterns('', url(r'^$', WashMapServerView.as_view()), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import patterns, url from .views import ( WashMapServerView, LineStaticView, WashMapStaticMapView, WashMapStaticMapToolsView, WashMapStaticMapToolsLinkedView, WashMapStaticMapToolsLinkedTabbedView, WashMapStaticAllView, ) and context: # Path: washmap/washmap/views.py # class WashMapServerView(TemplateView): # template_name = 'washmap/chart_from_server.html' # # @app_document_no_tag('washmap', settings.BOKEH_URL) # def make_app(self): # app = WashmapApp.create() # return app # # def get_context_data(self, *args, **kwargs): # context = super(WashMapServerView, self).get_context_data(*args, **kwargs) # nopep8 # applet = self.make_app() # applet_dict = { # 'elementid': 'washmap', # 'root_url': applet._root_url, # 'docid': applet._docid, # 'modelid': applet._id, # 'js_model': applet.js_model, # 'modulename': applet.js_model, # 'classname': applet.js_model, # 'parentname': applet.parent_model, # } # context.update( # applet=applet_dict # ) # return context # # class LineStaticView(TemplateView): # template_name = 'washmap/chart_basic_embed.html' # # def get_context_data(self, *args, **kwargs): # context = super(LineStaticView, self).get_context_data(*args, **kwargs) # line_chart = make_line_chart() # embed_script, embed_div = components(line_chart, Resources()) # context.update( # embed_div=embed_div, # embed_script=embed_script # ) # return context # # class WashMapStaticMapView(WashMapStaticView): # name = 'map' # # def make_plot(self): # plot = make_washmap_map() # return plot # # class WashMapStaticMapToolsView(WashMapStaticView): # # def make_plot(self): # plot = make_washmap_map_tools() # return plot # # class WashMapStaticMapToolsLinkedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked() # return plot # # class WashMapStaticMapToolsLinkedTabbedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked_tabbed() # return plot # # class WashMapStaticAllView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_all() # return plot which might include code, classes, or functions. Output only the next line.
url(r'^line$', LineStaticView.as_view()),
Predict the next line for this snippet: <|code_start|>from __future__ import unicode_literals, absolute_import urlpatterns = patterns('', url(r'^$', WashMapServerView.as_view()), url(r'^line$', LineStaticView.as_view()), <|code_end|> with the help of current file imports: from django.conf.urls import patterns, url from .views import ( WashMapServerView, LineStaticView, WashMapStaticMapView, WashMapStaticMapToolsView, WashMapStaticMapToolsLinkedView, WashMapStaticMapToolsLinkedTabbedView, WashMapStaticAllView, ) and context from other files: # Path: washmap/washmap/views.py # class WashMapServerView(TemplateView): # template_name = 'washmap/chart_from_server.html' # # @app_document_no_tag('washmap', settings.BOKEH_URL) # def make_app(self): # app = WashmapApp.create() # return app # # def get_context_data(self, *args, **kwargs): # context = super(WashMapServerView, self).get_context_data(*args, **kwargs) # nopep8 # applet = self.make_app() # applet_dict = { # 'elementid': 'washmap', # 'root_url': applet._root_url, # 'docid': applet._docid, # 'modelid': applet._id, # 'js_model': applet.js_model, # 'modulename': applet.js_model, # 'classname': applet.js_model, # 'parentname': applet.parent_model, # } # context.update( # applet=applet_dict # ) # return context # # class LineStaticView(TemplateView): # template_name = 'washmap/chart_basic_embed.html' # # def get_context_data(self, *args, **kwargs): # context = super(LineStaticView, self).get_context_data(*args, **kwargs) # line_chart = make_line_chart() # embed_script, embed_div = components(line_chart, Resources()) # context.update( # embed_div=embed_div, # embed_script=embed_script # ) # return context # # class WashMapStaticMapView(WashMapStaticView): # name = 'map' # # def make_plot(self): # plot = make_washmap_map() # return plot # # class WashMapStaticMapToolsView(WashMapStaticView): # # def make_plot(self): # plot = make_washmap_map_tools() # return plot # # class WashMapStaticMapToolsLinkedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked() # return plot # # class WashMapStaticMapToolsLinkedTabbedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked_tabbed() # return plot # # class WashMapStaticAllView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_all() # return plot , which may contain function names, class names, or code. Output only the next line.
url(r'^static_map$', WashMapStaticMapView.as_view()),
Based on the snippet: <|code_start|>from __future__ import unicode_literals, absolute_import urlpatterns = patterns('', url(r'^$', WashMapServerView.as_view()), url(r'^line$', LineStaticView.as_view()), url(r'^static_map$', WashMapStaticMapView.as_view()), <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import patterns, url from .views import ( WashMapServerView, LineStaticView, WashMapStaticMapView, WashMapStaticMapToolsView, WashMapStaticMapToolsLinkedView, WashMapStaticMapToolsLinkedTabbedView, WashMapStaticAllView, ) and context (classes, functions, sometimes code) from other files: # Path: washmap/washmap/views.py # class WashMapServerView(TemplateView): # template_name = 'washmap/chart_from_server.html' # # @app_document_no_tag('washmap', settings.BOKEH_URL) # def make_app(self): # app = WashmapApp.create() # return app # # def get_context_data(self, *args, **kwargs): # context = super(WashMapServerView, self).get_context_data(*args, **kwargs) # nopep8 # applet = self.make_app() # applet_dict = { # 'elementid': 'washmap', # 'root_url': applet._root_url, # 'docid': applet._docid, # 'modelid': applet._id, # 'js_model': applet.js_model, # 'modulename': applet.js_model, # 'classname': applet.js_model, # 'parentname': applet.parent_model, # } # context.update( # applet=applet_dict # ) # return context # # class LineStaticView(TemplateView): # template_name = 'washmap/chart_basic_embed.html' # # def get_context_data(self, *args, **kwargs): # context = super(LineStaticView, self).get_context_data(*args, **kwargs) # line_chart = make_line_chart() # embed_script, embed_div = components(line_chart, Resources()) # context.update( # embed_div=embed_div, # embed_script=embed_script # ) # return context # # class WashMapStaticMapView(WashMapStaticView): # name = 'map' # # def make_plot(self): # plot = make_washmap_map() # return plot # # class WashMapStaticMapToolsView(WashMapStaticView): # # def make_plot(self): # plot = make_washmap_map_tools() # return plot # # class WashMapStaticMapToolsLinkedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked() # return plot # # class WashMapStaticMapToolsLinkedTabbedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked_tabbed() # return plot # # class WashMapStaticAllView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_all() # return plot . Output only the next line.
url(r'^static_map_tools$', WashMapStaticMapToolsView.as_view()),
Based on the snippet: <|code_start|>from __future__ import unicode_literals, absolute_import urlpatterns = patterns('', url(r'^$', WashMapServerView.as_view()), url(r'^line$', LineStaticView.as_view()), url(r'^static_map$', WashMapStaticMapView.as_view()), url(r'^static_map_tools$', WashMapStaticMapToolsView.as_view()), <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import patterns, url from .views import ( WashMapServerView, LineStaticView, WashMapStaticMapView, WashMapStaticMapToolsView, WashMapStaticMapToolsLinkedView, WashMapStaticMapToolsLinkedTabbedView, WashMapStaticAllView, ) and context (classes, functions, sometimes code) from other files: # Path: washmap/washmap/views.py # class WashMapServerView(TemplateView): # template_name = 'washmap/chart_from_server.html' # # @app_document_no_tag('washmap', settings.BOKEH_URL) # def make_app(self): # app = WashmapApp.create() # return app # # def get_context_data(self, *args, **kwargs): # context = super(WashMapServerView, self).get_context_data(*args, **kwargs) # nopep8 # applet = self.make_app() # applet_dict = { # 'elementid': 'washmap', # 'root_url': applet._root_url, # 'docid': applet._docid, # 'modelid': applet._id, # 'js_model': applet.js_model, # 'modulename': applet.js_model, # 'classname': applet.js_model, # 'parentname': applet.parent_model, # } # context.update( # applet=applet_dict # ) # return context # # class LineStaticView(TemplateView): # template_name = 'washmap/chart_basic_embed.html' # # def get_context_data(self, *args, **kwargs): # context = super(LineStaticView, self).get_context_data(*args, **kwargs) # line_chart = make_line_chart() # embed_script, embed_div = components(line_chart, Resources()) # context.update( # embed_div=embed_div, # embed_script=embed_script # ) # return context # # class WashMapStaticMapView(WashMapStaticView): # name = 'map' # # def make_plot(self): # plot = make_washmap_map() # return plot # # class WashMapStaticMapToolsView(WashMapStaticView): # # def make_plot(self): # plot = make_washmap_map_tools() # return plot # # class WashMapStaticMapToolsLinkedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked() # return plot # # class WashMapStaticMapToolsLinkedTabbedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked_tabbed() # return plot # # class WashMapStaticAllView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_all() # return plot . Output only the next line.
url(r'^static_map_tools_linked$', WashMapStaticMapToolsLinkedView.as_view()),
Predict the next line after this snippet: <|code_start|>from __future__ import unicode_literals, absolute_import urlpatterns = patterns('', url(r'^$', WashMapServerView.as_view()), url(r'^line$', LineStaticView.as_view()), url(r'^static_map$', WashMapStaticMapView.as_view()), url(r'^static_map_tools$', WashMapStaticMapToolsView.as_view()), url(r'^static_map_tools_linked$', WashMapStaticMapToolsLinkedView.as_view()), <|code_end|> using the current file's imports: from django.conf.urls import patterns, url from .views import ( WashMapServerView, LineStaticView, WashMapStaticMapView, WashMapStaticMapToolsView, WashMapStaticMapToolsLinkedView, WashMapStaticMapToolsLinkedTabbedView, WashMapStaticAllView, ) and any relevant context from other files: # Path: washmap/washmap/views.py # class WashMapServerView(TemplateView): # template_name = 'washmap/chart_from_server.html' # # @app_document_no_tag('washmap', settings.BOKEH_URL) # def make_app(self): # app = WashmapApp.create() # return app # # def get_context_data(self, *args, **kwargs): # context = super(WashMapServerView, self).get_context_data(*args, **kwargs) # nopep8 # applet = self.make_app() # applet_dict = { # 'elementid': 'washmap', # 'root_url': applet._root_url, # 'docid': applet._docid, # 'modelid': applet._id, # 'js_model': applet.js_model, # 'modulename': applet.js_model, # 'classname': applet.js_model, # 'parentname': applet.parent_model, # } # context.update( # applet=applet_dict # ) # return context # # class LineStaticView(TemplateView): # template_name = 'washmap/chart_basic_embed.html' # # def get_context_data(self, *args, **kwargs): # context = super(LineStaticView, self).get_context_data(*args, **kwargs) # line_chart = make_line_chart() # embed_script, embed_div = components(line_chart, Resources()) # context.update( # embed_div=embed_div, # embed_script=embed_script # ) # return context # # class WashMapStaticMapView(WashMapStaticView): # name = 'map' # # def make_plot(self): # plot = make_washmap_map() # return plot # # class WashMapStaticMapToolsView(WashMapStaticView): # # def make_plot(self): # plot = make_washmap_map_tools() # return plot # # class WashMapStaticMapToolsLinkedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked() # return plot # # class WashMapStaticMapToolsLinkedTabbedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked_tabbed() # return plot # # class WashMapStaticAllView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_all() # return plot . Output only the next line.
url(r'^static_map_tools_linked_tabbed$', WashMapStaticMapToolsLinkedTabbedView.as_view()),
Based on the snippet: <|code_start|>from __future__ import unicode_literals, absolute_import urlpatterns = patterns('', url(r'^$', WashMapServerView.as_view()), url(r'^line$', LineStaticView.as_view()), url(r'^static_map$', WashMapStaticMapView.as_view()), url(r'^static_map_tools$', WashMapStaticMapToolsView.as_view()), url(r'^static_map_tools_linked$', WashMapStaticMapToolsLinkedView.as_view()), url(r'^static_map_tools_linked_tabbed$', WashMapStaticMapToolsLinkedTabbedView.as_view()), <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import patterns, url from .views import ( WashMapServerView, LineStaticView, WashMapStaticMapView, WashMapStaticMapToolsView, WashMapStaticMapToolsLinkedView, WashMapStaticMapToolsLinkedTabbedView, WashMapStaticAllView, ) and context (classes, functions, sometimes code) from other files: # Path: washmap/washmap/views.py # class WashMapServerView(TemplateView): # template_name = 'washmap/chart_from_server.html' # # @app_document_no_tag('washmap', settings.BOKEH_URL) # def make_app(self): # app = WashmapApp.create() # return app # # def get_context_data(self, *args, **kwargs): # context = super(WashMapServerView, self).get_context_data(*args, **kwargs) # nopep8 # applet = self.make_app() # applet_dict = { # 'elementid': 'washmap', # 'root_url': applet._root_url, # 'docid': applet._docid, # 'modelid': applet._id, # 'js_model': applet.js_model, # 'modulename': applet.js_model, # 'classname': applet.js_model, # 'parentname': applet.parent_model, # } # context.update( # applet=applet_dict # ) # return context # # class LineStaticView(TemplateView): # template_name = 'washmap/chart_basic_embed.html' # # def get_context_data(self, *args, **kwargs): # context = super(LineStaticView, self).get_context_data(*args, **kwargs) # line_chart = make_line_chart() # embed_script, embed_div = components(line_chart, Resources()) # context.update( # embed_div=embed_div, # embed_script=embed_script # ) # return context # # class WashMapStaticMapView(WashMapStaticView): # name = 'map' # # def make_plot(self): # plot = make_washmap_map() # return plot # # class WashMapStaticMapToolsView(WashMapStaticView): # # def make_plot(self): # plot = make_washmap_map_tools() # return plot # # class WashMapStaticMapToolsLinkedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked() # return plot # # class WashMapStaticMapToolsLinkedTabbedView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_map_tools_linked_tabbed() # return plot # # class WashMapStaticAllView(WashMapStaticView): # def make_plot(self): # plot = make_washmap_all() # return plot . Output only the next line.
url(r'^static_all$', WashMapStaticAllView.as_view()),
Here is a snippet: <|code_start|> class BreadTestModel2Factory(factory.DjangoModelFactory): FACTORY_FOR = BreadTestModel2 text = factory.fuzzy.FuzzyText(length=10) class BreadTestModelFactory(factory.DjangoModelFactory): FACTORY_FOR = BreadTestModel name = factory.fuzzy.FuzzyText(length=10) age = factory.fuzzy.FuzzyInteger(low=1, high=99) other = factory.SubFactory(BreadTestModel2Factory) class BreadLabelValueTestModelFactory(factory.DjangoModelFactory): <|code_end|> . Write the next line using the current file imports: import factory import factory.fuzzy from .models import BreadLabelValueTestModel, BreadTestModel, BreadTestModel2 and context from other files: # Path: tests/models.py # class BreadLabelValueTestModel(models.Model): # """Model for testing LabelValueReadView, also for GetVerboseNameTest""" # # name = models.CharField(max_length=10) # banana = models.IntegerField(verbose_name="a yellow fruit", default=0) # # def name_reversed(self): # return self.name[::-1] # # class BreadTestModel(models.Model): # name = models.CharField(max_length=10) # age = models.IntegerField() # other = models.ForeignKey( # BreadTestModel2, # blank=True, # null=True, # on_delete=models.CASCADE, # ) # # class Meta: # ordering = [ # "name", # "-age", # If same name, sort oldest first # ] # permissions = [ # ("browse_breadtestmodel", "can browse BreadTestModel"), # ] # # def __str__(self): # return self.name # # def get_name(self): # return self.name # # def method1(self, arg): # # Method that has a required arg # pass # # def method2(self, arg=None): # # method that has an optional arg # pass # # class BreadTestModel2(models.Model): # text = models.CharField(max_length=20) # label_model = models.OneToOneField( # BreadLabelValueTestModel, # null=True, # related_name="model2", # on_delete=models.CASCADE, # ) # model1 = models.OneToOneField( # "BreadTestModel", # null=True, # related_name="model1", # on_delete=models.CASCADE, # ) # # def get_text(self): # return self.text , which may include functions, classes, or code. Output only the next line.
FACTORY_FOR = BreadLabelValueTestModel
Based on the snippet: <|code_start|> class BreadTestModel2Factory(factory.DjangoModelFactory): FACTORY_FOR = BreadTestModel2 text = factory.fuzzy.FuzzyText(length=10) class BreadTestModelFactory(factory.DjangoModelFactory): <|code_end|> , predict the immediate next line with the help of imports: import factory import factory.fuzzy from .models import BreadLabelValueTestModel, BreadTestModel, BreadTestModel2 and context (classes, functions, sometimes code) from other files: # Path: tests/models.py # class BreadLabelValueTestModel(models.Model): # """Model for testing LabelValueReadView, also for GetVerboseNameTest""" # # name = models.CharField(max_length=10) # banana = models.IntegerField(verbose_name="a yellow fruit", default=0) # # def name_reversed(self): # return self.name[::-1] # # class BreadTestModel(models.Model): # name = models.CharField(max_length=10) # age = models.IntegerField() # other = models.ForeignKey( # BreadTestModel2, # blank=True, # null=True, # on_delete=models.CASCADE, # ) # # class Meta: # ordering = [ # "name", # "-age", # If same name, sort oldest first # ] # permissions = [ # ("browse_breadtestmodel", "can browse BreadTestModel"), # ] # # def __str__(self): # return self.name # # def get_name(self): # return self.name # # def method1(self, arg): # # Method that has a required arg # pass # # def method2(self, arg=None): # # method that has an optional arg # pass # # class BreadTestModel2(models.Model): # text = models.CharField(max_length=20) # label_model = models.OneToOneField( # BreadLabelValueTestModel, # null=True, # related_name="model2", # on_delete=models.CASCADE, # ) # model1 = models.OneToOneField( # "BreadTestModel", # null=True, # related_name="model1", # on_delete=models.CASCADE, # ) # # def get_text(self): # return self.text . Output only the next line.
FACTORY_FOR = BreadTestModel
Given the following code snippet before the placeholder: <|code_start|> logger = logging.getLogger(__name__) register = template.Library() @register.filter(name="getter") def getter(value, arg): """ Given an object `value`, return the value of the attribute named `arg`. `arg` can contain `__` to drill down recursively into the values. If the final result is a callable, it is called and its return value used. """ try: <|code_end|> , predict the next line using imports from the current file: import logging from django import template from django.core.exceptions import ObjectDoesNotExist from bread.utils import get_model_field and context including class names, function names, and sometimes code from other files: # Path: bread/utils.py # def get_model_field(model_instance, spec): # if model_instance is None: # raise ValueError("None passed into get_model_field") # if not isinstance(model_instance, Model): # raise ValueError( # "%r should be an instance of a model but it is a %s" # % (model_instance, type(model_instance)) # ) # # if spec.startswith("__") and spec.endswith("__"): # # It's a dunder method; don't split it. # name_parts = [spec] # else: # name_parts = spec.split("__", 1) # # value = getattr(model_instance, name_parts[0]) # if callable(value): # value = value() # if len(name_parts) > 1 and value is not None: # return get_model_field(value, name_parts[1]) # return value . Output only the next line.
return get_model_field(value, arg)
Given the code snippet: <|code_start|> ) """ template_name_suffix = "_label_value_read" fields = [] def get_context_data(self, **kwargs): context_data = super(LabelValueReadView, self).get_context_data(**kwargs) context_data["read_fields"] = [ self.get_field_label_value(label, value, context_data) for label, value in self.fields ] return context_data def get_field_label_value(self, label, evaluator, context_data): """Given a 2-tuple from fields, return the corresponding (label, value) tuple. Implements the modes described in the class docstring. (q.v.) """ value = "" if isinstance(evaluator, str): if hasattr(self.object, evaluator): # This is an instance attr or method attr = getattr(self.object, evaluator) # Modes #1 and #2. value = attr() if callable(attr) else attr if label is None: # evaluator refers to a model field (we hope). <|code_end|> , generate the next line using the imports in this file: import json from functools import reduce from operator import or_ from urllib.parse import urlencode from django.conf import settings from django.contrib.admin.utils import lookup_needs_distinct from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.models import Permission from django.contrib.auth.views import redirect_to_login from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ( EmptyResultSet, FieldError, ImproperlyConfigured, PermissionDenied, ) from django.db.models import Model, Q from django.forms.models import modelform_factory from django.http.response import HttpResponseBadRequest from django.urls import path, reverse_lazy from vanilla import CreateView, DeleteView, DetailView, ListView, UpdateView from .utils import get_verbose_name, validate_fieldspec and context (functions, classes, or occasionally code) from other files: # Path: bread/utils.py # def get_verbose_name(an_object, field_name, title_cap=True): # """Given a model or model instance, return the verbose_name of the model's field. # # If title_cap is True (the default), the verbose_name will be returned with the first letter # of each word capitalized which makes the verbose_name look nicer in labels. # # If field_name doesn't refer to a model field, raises a FieldDoesNotExist error. # """ # # get_field() can raise FieldDoesNotExist which I simply propogate up to the caller. # try: # field = an_object._meta.get_field(field_name) # except TypeError: # # TypeError happens if the caller is very confused and passes an unhashable type such # # as {} or []. I convert that into a FieldDoesNotExist exception for simplicity. # raise FieldDoesNotExist("No field named {}".format(str(field_name))) # # verbose_name = field.verbose_name # # if title_cap: # # Title cap the label using this stackoverflow-approved technique: # # http://stackoverflow.com/questions/1549641/how-to-capitalize-the-first-letter-of-each-word-in-a-string-python # verbose_name = " ".join(word.capitalize() for word in verbose_name.split()) # # return verbose_name # # def validate_fieldspec(model, spec): # """ # Given a model class and a string that refers to a possibly nested # field on that model (as used in `get_model_field`). # # Raises a ValidationError with a useful error message if the spec # does not appear to be valid. # # Otherwise just returns. # """ # if not issubclass(model, Model): # raise TypeError( # "First argument to validate_fieldspec must be a " # "subclass of Model; it is %r" % model # ) # parts = spec.split("__", 1) # rest_of_spec = parts[1] if len(parts) > 1 else None # # # What are the possibilities for what parts[0] is on our model? # # - It could be a field # # - simple (not a key) # # - key # # - It could be a non-field # # - class variable # # - method # # - It could not exist # # try: # field = model._meta.get_field(parts[0]) # except FieldDoesNotExist: # # Not a field - is there an attribute of some sort? # if not hasattr(model, parts[0]): # raise ValidationError( # "There is no field or attribute named '%s' on model '%s'" # % (parts[0], model) # ) # if rest_of_spec: # raise ValidationError( # "On model '%s', '%s' is not a field, but the spec tries to refer through " # "it to '%s'." % (model, parts[0], rest_of_spec) # ) # attr = getattr(model, parts[0]) # if callable(attr): # if has_required_args(attr): # raise ValidationError( # "On model '%s', '%s' is callable and has required arguments; it is not " # "valid to use in a field spec" % (model, parts[0]) # ) # else: # # It's a field # # Is it a key? # if isinstance(field, RelatedField): # # Yes, refers to another model # if rest_of_spec: # # Recurse! # validate_fieldspec(model=field.related_model, spec=rest_of_spec) # # Well, it's okay if it just returns a reference to another record # else: # # Simple field # # Is there more spec? # if rest_of_spec: # raise ValidationError( # "On model '%s', '%s' is not a key field, but the spec tries to refer through " # "it to '%s'." % (model, parts[0], rest_of_spec) # ) # # Simple field, no more spec, looks good . Output only the next line.
label = get_verbose_name(self.object, evaluator)
Given snippet: <|code_start|> browse_view = BrowseView read_view = ReadView edit_view = EditView add_view = AddView delete_view = DeleteView exclude = [] # Names of fields not to show views = "BREAD" base_template = setting("DEFAULT_BASE_TEMPLATE", "base.html") namespace = "" template_name_pattern = None plural_name = None form_class = None def __init__(self): self.name = self.model._meta.object_name.lower() self.views = self.views.upper() if not self.plural_name: self.plural_name = self.name + "s" if not issubclass(self.model, Model): raise TypeError( "'model' argument for Bread must be a " "subclass of Model; it is %r" % self.model ) if self.browse_view.columns: for colspec in self.browse_view.columns: column = colspec[1] <|code_end|> , continue by predicting the next line. Consider current file imports: import json from functools import reduce from operator import or_ from urllib.parse import urlencode from django.conf import settings from django.contrib.admin.utils import lookup_needs_distinct from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.models import Permission from django.contrib.auth.views import redirect_to_login from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ( EmptyResultSet, FieldError, ImproperlyConfigured, PermissionDenied, ) from django.db.models import Model, Q from django.forms.models import modelform_factory from django.http.response import HttpResponseBadRequest from django.urls import path, reverse_lazy from vanilla import CreateView, DeleteView, DetailView, ListView, UpdateView from .utils import get_verbose_name, validate_fieldspec and context: # Path: bread/utils.py # def get_verbose_name(an_object, field_name, title_cap=True): # """Given a model or model instance, return the verbose_name of the model's field. # # If title_cap is True (the default), the verbose_name will be returned with the first letter # of each word capitalized which makes the verbose_name look nicer in labels. # # If field_name doesn't refer to a model field, raises a FieldDoesNotExist error. # """ # # get_field() can raise FieldDoesNotExist which I simply propogate up to the caller. # try: # field = an_object._meta.get_field(field_name) # except TypeError: # # TypeError happens if the caller is very confused and passes an unhashable type such # # as {} or []. I convert that into a FieldDoesNotExist exception for simplicity. # raise FieldDoesNotExist("No field named {}".format(str(field_name))) # # verbose_name = field.verbose_name # # if title_cap: # # Title cap the label using this stackoverflow-approved technique: # # http://stackoverflow.com/questions/1549641/how-to-capitalize-the-first-letter-of-each-word-in-a-string-python # verbose_name = " ".join(word.capitalize() for word in verbose_name.split()) # # return verbose_name # # def validate_fieldspec(model, spec): # """ # Given a model class and a string that refers to a possibly nested # field on that model (as used in `get_model_field`). # # Raises a ValidationError with a useful error message if the spec # does not appear to be valid. # # Otherwise just returns. # """ # if not issubclass(model, Model): # raise TypeError( # "First argument to validate_fieldspec must be a " # "subclass of Model; it is %r" % model # ) # parts = spec.split("__", 1) # rest_of_spec = parts[1] if len(parts) > 1 else None # # # What are the possibilities for what parts[0] is on our model? # # - It could be a field # # - simple (not a key) # # - key # # - It could be a non-field # # - class variable # # - method # # - It could not exist # # try: # field = model._meta.get_field(parts[0]) # except FieldDoesNotExist: # # Not a field - is there an attribute of some sort? # if not hasattr(model, parts[0]): # raise ValidationError( # "There is no field or attribute named '%s' on model '%s'" # % (parts[0], model) # ) # if rest_of_spec: # raise ValidationError( # "On model '%s', '%s' is not a field, but the spec tries to refer through " # "it to '%s'." % (model, parts[0], rest_of_spec) # ) # attr = getattr(model, parts[0]) # if callable(attr): # if has_required_args(attr): # raise ValidationError( # "On model '%s', '%s' is callable and has required arguments; it is not " # "valid to use in a field spec" % (model, parts[0]) # ) # else: # # It's a field # # Is it a key? # if isinstance(field, RelatedField): # # Yes, refers to another model # if rest_of_spec: # # Recurse! # validate_fieldspec(model=field.related_model, spec=rest_of_spec) # # Well, it's okay if it just returns a reference to another record # else: # # Simple field # # Is there more spec? # if rest_of_spec: # raise ValidationError( # "On model '%s', '%s' is not a key field, but the spec tries to refer through " # "it to '%s'." % (model, parts[0], rest_of_spec) # ) # # Simple field, no more spec, looks good which might include code, classes, or functions. Output only the next line.
validate_fieldspec(self.model, column)
Based on the snippet: <|code_start|> self.request.user = AnonymousUser() rsp = self.view(self.request, pk=self.item.pk) expected_url = "%s?%s=%s" % ( settings.LOGIN_URL, REDIRECT_FIELD_NAME, self.request.path, ) self.assertEqual(expected_url, rsp["Location"]) if self.include_post: self.post_request.user = AnonymousUser() rsp = self.view(self.post_request, pk=self.item.pk) self.assertEqual(302, rsp.status_code) self.assertEqual(expected_url, rsp["Location"]) def test_access_without_permission(self): # Can't do it when logged in but no permission, get 403 with self.assertRaises(PermissionDenied): if self.expects_pk: self.view(self.request, pk=self.item.pk) else: self.view(self.request) if self.include_post: with self.assertRaises(PermissionDenied): if self.expects_pk: self.view(self.post_request, pk=self.item.pk) else: self.view(self.post_request) <|code_end|> , predict the immediate next line with the help of imports: from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.models import AnonymousUser from django.core.exceptions import PermissionDenied from django.test import override_settings from django.urls import reverse from .base import BreadTestCase and context (classes, functions, sometimes code) from other files: # Path: tests/base.py # class BreadTestCase(TestCase): # url_namespace = "" # extra_bread_attributes = {} # # def setUp(self): # self.username = "joe" # self.password = "random" # User = get_user_model() # self.user = User.objects.create_user(username=self.username) # self.user.set_password(self.password) # self.user.save() # assert self.client.login(username=self.username, password=self.password) # self.model = BreadTestModel # self.model_name = self.model._meta.model_name # self.model_factory = BreadTestModelFactory # self.request_factory = RequestFactory() # # class ReadClass(ReadView): # columns = [ # ("Name", "name"), # ("Text", "other__text"), # ( # "Model1", # "model1", # ), # ] # # class BrowseClass(BrowseView): # columns = [ # ("Name", "name"), # ("Text", "other__text"), # ( # "Model1", # "model1", # ), # ] # # class BreadTestClass(Bread): # model = self.model # base_template = "bread/empty.html" # browse_view = BrowseClass # namespace = self.url_namespace # plural_name = "testmodels" # # def get_additional_context_data(self): # context = super(BreadTestClass, self).get_additional_context_data() # context["bread_test_class"] = True # return context # # for k, v in self.extra_bread_attributes.items(): # setattr(BreadTestClass, k, v) # # self.BreadTestClass = BreadTestClass # self.bread = BreadTestClass() # # def tearDown(self): # global urlpatterns # urlpatterns = None # # def set_urls(self, bread): # # Given a bread instance, set its URLs on the test urlconf # global urlpatterns # urlpatterns = bread.get_urls() # # def get_permission(self, short_name): # """Return a Permission object for the test model. # short_name should be browse, read, edit, add, or delete. # """ # return Permission.objects.get_or_create( # content_type=ContentType.objects.get_for_model(self.model), # codename="%s_%s" % (short_name, self.model_name), # )[0] # # def give_permission(self, short_name): # self.user.user_permissions.add(self.get_permission(short_name)) . Output only the next line.
class BreadBrowsePermissionTest(BreadPermissionTestMixin, BreadTestCase):
Given the following code snippet before the placeholder: <|code_start|> class TestForm(forms.ModelForm): # A form we override the bread form with # It only allows names that start with 'Dan' class Meta: model = BreadTestModel fields = ["name", "age"] def clean_name(self): name = self.cleaned_data["name"] if not name.startswith("Dan"): raise ValidationError("All good names start with Dan") return name <|code_end|> , predict the next line using imports from the current file: from django import forms from django.core.exceptions import ValidationError from django.urls import reverse from .base import BreadTestCase from .models import BreadTestModel and context including class names, function names, and sometimes code from other files: # Path: tests/base.py # class BreadTestCase(TestCase): # url_namespace = "" # extra_bread_attributes = {} # # def setUp(self): # self.username = "joe" # self.password = "random" # User = get_user_model() # self.user = User.objects.create_user(username=self.username) # self.user.set_password(self.password) # self.user.save() # assert self.client.login(username=self.username, password=self.password) # self.model = BreadTestModel # self.model_name = self.model._meta.model_name # self.model_factory = BreadTestModelFactory # self.request_factory = RequestFactory() # # class ReadClass(ReadView): # columns = [ # ("Name", "name"), # ("Text", "other__text"), # ( # "Model1", # "model1", # ), # ] # # class BrowseClass(BrowseView): # columns = [ # ("Name", "name"), # ("Text", "other__text"), # ( # "Model1", # "model1", # ), # ] # # class BreadTestClass(Bread): # model = self.model # base_template = "bread/empty.html" # browse_view = BrowseClass # namespace = self.url_namespace # plural_name = "testmodels" # # def get_additional_context_data(self): # context = super(BreadTestClass, self).get_additional_context_data() # context["bread_test_class"] = True # return context # # for k, v in self.extra_bread_attributes.items(): # setattr(BreadTestClass, k, v) # # self.BreadTestClass = BreadTestClass # self.bread = BreadTestClass() # # def tearDown(self): # global urlpatterns # urlpatterns = None # # def set_urls(self, bread): # # Given a bread instance, set its URLs on the test urlconf # global urlpatterns # urlpatterns = bread.get_urls() # # def get_permission(self, short_name): # """Return a Permission object for the test model. # short_name should be browse, read, edit, add, or delete. # """ # return Permission.objects.get_or_create( # content_type=ContentType.objects.get_for_model(self.model), # codename="%s_%s" % (short_name, self.model_name), # )[0] # # def give_permission(self, short_name): # self.user.user_permissions.add(self.get_permission(short_name)) # # Path: tests/models.py # class BreadTestModel(models.Model): # name = models.CharField(max_length=10) # age = models.IntegerField() # other = models.ForeignKey( # BreadTestModel2, # blank=True, # null=True, # on_delete=models.CASCADE, # ) # # class Meta: # ordering = [ # "name", # "-age", # If same name, sort oldest first # ] # permissions = [ # ("browse_breadtestmodel", "can browse BreadTestModel"), # ] # # def __str__(self): # return self.name # # def get_name(self): # return self.name # # def method1(self, arg): # # Method that has a required arg # pass # # def method2(self, arg=None): # # method that has an optional arg # pass . Output only the next line.
class BreadFormAddTest(BreadTestCase):
Continue the code snippet: <|code_start|>''' @Summary: Server for GUI pages and user navigation throughout site @Author: mackhendricks ''' app = Flask(__name__) # Configurations app.config.from_object('config') if ('API_SERVER_URL' in app.config) and len(app.config['API_SERVER_URL']) > 0: API_SERVER = app.config['API_SERVER_URL'] else: #Assume the the server is located on the local server <|code_end|> . Use current file imports: import requests, json from flask import Flask, render_template, request, jsonify, make_response from api.util import dynamic and context (classes, functions, or code) from other files: # Path: api/util/dynamic.py # def getWorkingDirs(): # def setProjectPath(dir=None): # def get_current_ip(): # def get_hostname(): # def script_info(): . Output only the next line.
ip = dynamic.get_current_ip()
Next line prediction: <|code_start|> class MultiLanguageElasticsearchSearchBackend(ElasticsearchSearchBackend): def update(self, index, iterable, commit=True): if not self.setup_complete: try: self.setup() except (requests.RequestException, pyelasticsearch.ElasticHttpError) as e: if not self.silently_fail: raise self.log.error("Failed to add documents to Elasticsearch: %s", e) return prepped_docs = [] <|code_end|> . Use current file imports: (from haystack.backends.elasticsearch_backend import ElasticsearchSearchBackend, ElasticsearchSearchQuery from haystack.backends import BaseEngine from haystack.constants import ID, DJANGO_CT, DJANGO_ID from haystack.utils import get_identifier from simple_cms.contrib.translated_model.models import Language import requests import pyelasticsearch) and context including class names, function names, or small code snippets from other files: # Path: simple_cms/contrib/translated_model/models.py # class Language(CommonAbstractModel): # name = models.CharField(max_length=255, unique=True) # code = models.CharField(max_length=10, unique=True) # display_name = models.CharField(max_length=255, blank=True, default='') # order = PositionField() # # class Meta: # ordering = ['order'] # # @property # def title(self): # if self.display_name: # return self.display_name # return self.name # # def __unicode__(self): # return u'%s' % self.name . Output only the next line.
for language in Language.objects.get_active():
Predict the next line after this snippet: <|code_start|> header['active'] = False pass header['href'] = querystring.urlencode() except KeyError: pass return super(DataGridView, self).get(request, *args, **kwargs) def get_queryset(self): queryset = super(DataGridView, self).get_queryset() return queryset.order_by(self.sort) def get_context_data(self, *args, **kwargs): context = super(DataGridView, self).get_context_data(*args, **kwargs) # operates with use case of a single datagrid per page / view # we could abstract that so we could use the sorting logic to return only queryset and variables # with a namespace context['sort_column'] = self.sort_column context['sort_direction'] = self.sort_direction # try to find a match for header in self.headers: if header.get('column') == self.sort_column: try: context['sort_column_label'] = header['label'] except: context['sort_column_label'] = self.sort_column break context['headers'] = self.headers context['querystring'] = self.querystring.urlencode() if self.digg: <|code_end|> using the current file's imports: from django.views.generic import ListView from simple_cms.contrib.utils import digg_paginator and any relevant context from other files: # Path: simple_cms/contrib/utils.py # def digg_paginator(records, ADJACENT_PAGES=3, BORDER_PAGES=2, BASE_RANGE=10): # pages = [] # leading = [] # trailing = [] # # # only 1 set # if records.paginator.num_pages <= BASE_RANGE: # # be sure to only rock the num of pages # if records.paginator.num_pages > 1: # pages = xrange(1, records.paginator.num_pages+1) # # in the first range, with trailing # elif records.paginator.num_pages > BASE_RANGE and records.number < BASE_RANGE+1: # pages = xrange(1, BASE_RANGE+1) # trailing = xrange(records.paginator.num_pages-BORDER_PAGES+1, records.paginator.num_pages+1) # # within the end range # elif records.paginator.num_pages - records.number <= ADJACENT_PAGES*2 + 1: # leading = xrange(1, BORDER_PAGES+1) # pages = xrange(records.paginator.num_pages-(ADJACENT_PAGES*2+1), records.paginator.num_pages+1) # else: # leading = xrange(1, BORDER_PAGES+1) # pages = xrange(records.number - ADJACENT_PAGES, records.number + ADJACENT_PAGES+1) # trailing = xrange(records.paginator.num_pages-BORDER_PAGES+1, records.paginator.num_pages+1) # # return { # 'pages': pages, # 'leading': leading, # 'trailing': trailing, # } . Output only the next line.
context['digg'] = digg_paginator(context['page_obj'])
Given the code snippet: <|code_start|> class MultiLanguageSolrBackend(SolrSearchBackend): def update(self, index, iterable, commit=True): docs = [] <|code_end|> , generate the next line using the imports in this file: from pysolr import SolrError from haystack.backends.solr_backend import SolrSearchBackend, SolrSearchQuery from haystack.backends import BaseEngine from haystack.utils import get_identifier from simple_cms.contrib.translated_model.models import Language and context (functions, classes, or occasionally code) from other files: # Path: simple_cms/contrib/translated_model/models.py # class Language(CommonAbstractModel): # name = models.CharField(max_length=255, unique=True) # code = models.CharField(max_length=10, unique=True) # display_name = models.CharField(max_length=255, blank=True, default='') # order = PositionField() # # class Meta: # ordering = ['order'] # # @property # def title(self): # if self.display_name: # return self.display_name # return self.name # # def __unicode__(self): # return u'%s' % self.name . Output only the next line.
for language in Language.objects.get_active():
Continue the code snippet: <|code_start|> instance = _translate_instance(instance, code) except KeyError: pass return instance @register.assignment_tag(takes_context=True) def translated_field(context, instance, field): return translate_field(context, instance, field) @register.simple_tag(takes_context=True) def translate_field(context, instance, field): try: code = context['request'].LANGUAGE_CODE if code != get_default_language(): # now try to find a translation try: translations = instance.translations.filter(language__code=code, active=True) if len(translations): p = getattr(translations[0], field) if len(p): return p except AttributeError: pass except KeyError: pass return getattr(instance, field) @register.simple_tag(takes_context=True) def translate_string(context, key, default=''): try: <|code_end|> . Use current file imports: from django.utils.safestring import mark_safe from simple_cms.contrib.translated_model.models import LocalizationTranslation from simple_cms.models import CommonAbstractModel from django import template from django.conf import settings and context (classes, functions, or code) from other files: # Path: simple_cms/contrib/translated_model/models.py # class LocalizationTranslation(models.Model): # language = models.ForeignKey(Language) # localization = models.ForeignKey(Localization) # text = models.TextField() # # class Meta: # unique_together = ('language', 'localization') # # def __unicode__(self): # return u'%s' % self.text # # Path: simple_cms/models.py # class CommonAbstractModel(models.Model): # """ # Common ABC for most models. # Provides created/updated_at, and active/inactive status. # """ # created_at = CreationDateTimeField() # updated_at = ModificationDateTimeField() # active = models.BooleanField(default=True, verbose_name="published") # objects = CommonAbstractManager() # # class Meta: # get_latest_by = 'updated_at' # ordering = ('-updated_at', '-created_at') # abstract = True # # def get_class_name(self): # return self.__class__.__name__ . Output only the next line.
return mark_safe(LocalizationTranslation.objects.get(localization__name=key, language__code=context['request'].LANGUAGE_CODE).text)
Predict the next line for this snippet: <|code_start|> register = template.Library() def get_default_language(): # TODO: check on custom overrides, or future Language based default settings return settings.LANGUAGE_CODE def _translate_instance(instance, code): try: translations = instance.translations.filter(language__code=code, active=True) if len(translations): # map the non empty values on to the original instance translation = translations[0] # TODO: find out how to properly obtain the base classes up to models.Model and exclude all of their fields # TODO: find out how to properly obtain the PK fieldname <|code_end|> with the help of current file imports: from django.utils.safestring import mark_safe from simple_cms.contrib.translated_model.models import LocalizationTranslation from simple_cms.models import CommonAbstractModel from django import template from django.conf import settings and context from other files: # Path: simple_cms/contrib/translated_model/models.py # class LocalizationTranslation(models.Model): # language = models.ForeignKey(Language) # localization = models.ForeignKey(Localization) # text = models.TextField() # # class Meta: # unique_together = ('language', 'localization') # # def __unicode__(self): # return u'%s' % self.text # # Path: simple_cms/models.py # class CommonAbstractModel(models.Model): # """ # Common ABC for most models. # Provides created/updated_at, and active/inactive status. # """ # created_at = CreationDateTimeField() # updated_at = ModificationDateTimeField() # active = models.BooleanField(default=True, verbose_name="published") # objects = CommonAbstractManager() # # class Meta: # get_latest_by = 'updated_at' # ordering = ('-updated_at', '-created_at') # abstract = True # # def get_class_name(self): # return self.__class__.__name__ , which may contain function names, class names, or code. Output only the next line.
excluded = CommonAbstractModel._meta.get_all_field_names() + ['id']
Next line prediction: <|code_start|> self.page = None self.pageA = [] self.nav2 = None self.nav3 = None self.parent = None self.nav2_parent = None self.nav3_parent = None self.exact_match = False try: self.check_domain = settings.SIMPLE_CMS_CHECK_DOMAIN except: self.check_domain = False if self.check_domain: try: self.site = Site.objects.get(domain=RequestSite(request).domain) except: self.site = Site.objects.get(pk=1) else: try: self.site = Site.objects.get_current() except: self.site = Site.objects.get(pk=1) def is_homepage(self): try: if self.urlA[0] == '': try: kwargs = {'active':True, 'homepage':True} if self.check_domain and self.site: kwargs['site'] = self.site <|code_end|> . Use current file imports: (from django.contrib.sites.models import Site, RequestSite from django.conf import settings from simple_cms.models import Navigation) and context including class names, function names, or small code snippets from other files: # Path: simple_cms/models.py # class Navigation(TextMixin, CommonAbstractModel): # """ # Navigation and Page combined model # Customizations on One-To-One in implementing app # """ # title = models.CharField(max_length=255, help_text='Navigation and default page title') # slug = AutoSlugField(editable=True, populate_from='title') # group = models.ForeignKey(NavigationGroup, blank=True, null=True) # parent = models.ForeignKey('self', blank=True, null=True, related_name='children') # order = PositionField(collection=('parent', 'site')) # site = models.ForeignKey(Site, related_name='pages') # homepage = models.BooleanField(default=False) # url = models.CharField(max_length=255, blank=True, default='', help_text='eg. link somewhere else http://awesome.com/ or /awesome/page/') # target = models.CharField(max_length=255, blank=True, default='', help_text='eg. open link in "_blank" window', choices=TARGET_CHOICES) # page_title = models.CharField(max_length=255, blank=True, default='', help_text='Optional html title') # text = models.TextField(blank=True, default='') # format = models.CharField(max_length=255, blank=True, default='', choices=FORMAT_CHOICES) # render_as_template = models.BooleanField(default=False) # template = models.CharField(max_length=255, blank=True, default='', help_text='Eg. common/awesome.html') # view = models.CharField(max_length=255, blank=True, default='', help_text='Eg. common.views.awesome') # redirect_url = models.CharField(max_length=255, blank=True, default='') # redirect_permanent = models.BooleanField(default=False) # inherit_blocks = models.BooleanField(default=True, verbose_name="Inherit Blocks") # inherit_template = models.BooleanField(default=False, verbose_name="Inherit Template") # seo = GenericRelation(Seo) # blocks = GenericRelation(RelatedBlock) # # class Meta: # unique_together = (('site', 'slug', 'parent'),) # ordering = ['title'] # verbose_name_plural = 'Navigation' # # def __unicode__(self): # return u'%s' % self._chain() # # def clean(self): # from django.core.exceptions import ValidationError # if self.parent == self: # raise ValidationError('Can\'t set parent to self.') # # def num_blocks(self): # l = len(self.blocks.all()) # if l: # return l # return '' # # def custom_template(self): # if self.template: # return '<img src="%sadmin/img/icon-yes.gif" alt="yes" title="%s">' % (settings.STATIC_URL, self.template) # return '' # custom_template.allow_tags = True # custom_template.admin_order_field = 'template' # # def custom_view(self): # if self.view: # return '<img src="%sadmin/img/icon-yes.gif" alt="yes" title="%s">' % (settings.STATIC_URL, self.view) # return '' # custom_view.allow_tags = True # custom_view.admin_order_field = 'view' # # def root(self): # item = self # while item.parent: # item = item.parent # return item # # def get_title(self): # if self.page_title: # return self.page_title # return self.title # # def _chain(self, prop='title'): # """ Create slug chain for an object and its parent(s). """ # item = self # tA = [getattr(item, prop)] # while item.parent: # item = item.parent # tA.append(getattr(item, prop)) # else: # pass # tA.reverse() # return '/'.join(['%s' % name for name in tA]) # # def get_absolute_url(self): # if self.url: # return self.url # return mark_safe('/%s/' % self._chain('slug')) # # def get_children(self): # return self.children.all().filter(active=True).order_by('order') # # @property # def href(self): # r = '' # if self.target: # r = r+'target="%s"' % self.target # if self.url: # r = r+'href="%s"' % self.url # return mark_safe(r) # r = r+'href="/%s/"' % self._chain('slug') # return mark_safe(r) # # @property # def link_attributes(self): # return self.href # # @property # def depth(self): # depth = 0 # item = self # while item.parent: # item = item.parent # depth += 1 # else: # pass # return depth # # @property # def search_description(self): # return self.text . Output only the next line.
self.page = Navigation.objects.get(**kwargs)
Predict the next line for this snippet: <|code_start|> @click.group(invoke_without_command=True, help=""" Deploy master to production """) def cli(): <|code_end|> with the help of current file imports: import click from blackbelt.deployment import ( deploy_production ) and context from other files: # Path: blackbelt/deployment.py # def deploy_production(): # post_message("Deploying to production", "#deploy-queue") # # slug_creaction_return_code = run_grunt_in_parallel(( # ['grunt', 'create-slug'], # ['grunt', 'create-slug', '--app=apiary-staging-pre'], # ['grunt', 'create-slug', '--app=apiary-staging-qa'], # )) # # if slug_creaction_return_code != 0: # post_message("Slug creation failed, deploy stopped.", "#deploy-queue") # raise ValueError("One of the slug creations failed. Check output few lines above.") # # check_output(['grunt', 'deploy-slug', '--app=apiary-staging-qa']) # check_output(['grunt', 'deploy-slug', '--app=apiary-staging-pre']) # check_output(['grunt', 'deploy-slug']) , which may contain function names, class names, or code. Output only the next line.
deploy_production()
Given snippet: <|code_start|> class Trello(object): """ I represent a authenticated connection to Trello API. Dispatch all requests to it through my methods. My actions are named from the BlackBelt's POW; I don't aim to be a full, usable client. """ API_KEY = "2e4bb3b8ec5fe2ff6c04bf659ee4553b" APP_NAME = 'black-belt' URL_PREFIX = "https://trello.com/1" def __init__(self, access_token=None): self._access_token = access_token <|code_end|> , continue by predicting the next line. Consider current file imports: import json import re import requests from six.moves.urllib.parse import quote, quote_plus from blackbelt.config import config from blackbelt.errors import ConfigurationError and context: # Path: blackbelt/config.py # # Path: blackbelt/errors.py # class ConfigurationError(BlackBeltError): # """ Catch me to handle bad configuration (missing config, expired tokens etc.) """ which might include code, classes, or functions. Output only the next line.
if not self._access_token and config.get('trello') and config['trello'].get('access_token'):
Based on the snippet: <|code_start|> class Trello(object): """ I represent a authenticated connection to Trello API. Dispatch all requests to it through my methods. My actions are named from the BlackBelt's POW; I don't aim to be a full, usable client. """ API_KEY = "2e4bb3b8ec5fe2ff6c04bf659ee4553b" APP_NAME = 'black-belt' URL_PREFIX = "https://trello.com/1" def __init__(self, access_token=None): self._access_token = access_token if not self._access_token and config.get('trello') and config['trello'].get('access_token'): self._access_token = config['trello']['access_token'] ### Infra def do_request(self, url, method='get', data=None): if not self._access_token: <|code_end|> , predict the immediate next line with the help of imports: import json import re import requests from six.moves.urllib.parse import quote, quote_plus from blackbelt.config import config from blackbelt.errors import ConfigurationError and context (classes, functions, sometimes code) from other files: # Path: blackbelt/config.py # # Path: blackbelt/errors.py # class ConfigurationError(BlackBeltError): # """ Catch me to handle bad configuration (missing config, expired tokens etc.) """ . Output only the next line.
raise ConfigurationError("Trying to talk to Trello without having access token")
Here is a snippet: <|code_start|> class TestGithubRepoGitAddressParsing(object): github_repo = 'git@github.com:apiaryio/apiary-test.git' def setUp(self): <|code_end|> . Write the next line using the current file imports: from nose.tools import assert_equal, assert_raises from mock import patch from sys import version_info from blackbelt.git import get_remote_repo_info, get_current_branch and context from other files: # Path: blackbelt/git.py # def get_remote_repo_info(github_repo_info): # match = re.match(r".*github.com(:|\/)(?P<owner>[a-zA-Z\_\-]+)/{1}(?P<name>[a-zA-Z\-\_]+)\.git$", github_repo_info) # if not match: # raise ValueError("Cannot parse repo info. Bad remote?") # return match.groupdict() # # def get_current_branch(): # return subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip().decode('utf-8') , which may include functions, classes, or code. Output only the next line.
self.parsed = get_remote_repo_info(self.github_repo)
Given the code snippet: <|code_start|> def setUp(self): self.parsed = get_remote_repo_info(self.github_repo) def test_repo_owner(self): assert_equal('apiaryio', self.parsed['owner']) def test_repo_name(self): assert_equal('apiary-test', self.parsed['name']) class TestGithubRepoHttpsAddressParsing(object): github_repo = 'https://github.com/apiaryio/apiary-test.git' def setUp(self): self.parsed = get_remote_repo_info(self.github_repo) def test_repo_owner(self): assert_equal('apiaryio', self.parsed['owner']) def test_repo_name(self): assert_equal('apiary-test', self.parsed['name']) class TestGitBranchOutput(object): @patch('subprocess.check_output') def test_branch_name_parsing(self, check_output_mock): check_output_mock.return_value = b'prefix/branch-name\n' <|code_end|> , generate the next line using the imports in this file: from nose.tools import assert_equal, assert_raises from mock import patch from sys import version_info from blackbelt.git import get_remote_repo_info, get_current_branch and context (functions, classes, or occasionally code) from other files: # Path: blackbelt/git.py # def get_remote_repo_info(github_repo_info): # match = re.match(r".*github.com(:|\/)(?P<owner>[a-zA-Z\_\-]+)/{1}(?P<name>[a-zA-Z\-\_]+)\.git$", github_repo_info) # if not match: # raise ValueError("Cannot parse repo info. Bad remote?") # return match.groupdict() # # def get_current_branch(): # return subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip().decode('utf-8') . Output only the next line.
assert_equal('prefix/branch-name', get_current_branch())
Given the code snippet: <|code_start|> """ Integration exploratory playground for CircleCI. Don't really treat it as a test, but it may still be useful for you. """ class TestBuildInfoRetrieval(object): def setUp(self): try: <|code_end|> , generate the next line using the imports in this file: from nose.plugins.skip import SkipTest from blackbelt.config import config from blackbelt.circle import Client import os and context (functions, classes, or occasionally code) from other files: # Path: blackbelt/config.py # # Path: blackbelt/circle.py # class Client(object): # # def __init__(self, token=None): # if not token: # token = config['circleci']['access_token'] # # if not token: # raise ValueError("Can't do things with CircleCI without access token. Run bb init.") # # self.token = token # # self.default_headers = { # 'Accept': 'application/json', # 'Content-Type': 'application/json' # } # # self.endpoint = 'https://circleci.com/api/v1' # # def get_url(self, url, **kwargs): # kwargs['token'] = self.token # # url = self.endpoint + url + '?circle-token={token}' # return url.format(**kwargs) # # def request(self, method, url, data=None): # res = getattr(requests, method)(url, headers=self.default_headers) # if not res.ok: # raise ValueError("Request to URL %s failed" % url) # # return res.json() # # def get_builds(self, username, project): # url = self.get_url( # '/project/{username}/{project}', # username=username, # project=project # ) # # return self.request('get', url) # # def get_build(self, username, project, number): # url = self.get_url( # '/project/{username}/{project}/{number}', # username=username, # project=project, # number=number # ) # # return self.request('get', url) . Output only the next line.
self.client = Client()
Using the snippet: <|code_start|> class Slack(object): def __init__(self, token=None): if not token: <|code_end|> , determine the next line of code. You have imports: from slacker import Slacker from blackbelt.config import config and context (class names, function names, or code) available: # Path: blackbelt/config.py . Output only the next line.
token = config['slack']['access_token']
Here is a snippet: <|code_start|> class TestDependencyNameParsing(object): def test_no_version(self): assert_equal(parse_dep('react'), ('react', 'latest')) def test_at_separator(self): assert_equal(parse_dep('react@16.2'), ('react', '16.2')) def test_equals_separator(self): assert_equal(parse_dep('react==16.2'), ('react', '16.2')) class TestLicenseTextParsing(object): def test_basic(self): <|code_end|> . Write the next line using the current file imports: from nose.tools import assert_equal from blackbelt.dependencies import ( parse_dep, parse_license_text, ) and context from other files: # Path: blackbelt/dependencies.py # def parse_dep(dep): # split_result = re.split(r'==|@', dep) # if split_result[0] != '': # try: # return (split_result[0], split_result[1]) # except IndexError: # return (split_result[0], 'latest') # else: # try: # return ('@' + split_result[1], split_result[2]) # except IndexError: # return ('@' + split_result[1], 'latest') # # def parse_license_text(text): # license_text = (text or '').strip() # copyright_notice = detect_copyright_notice(license_text, require_year=True) # # # If the license doesn't contain any of the following words, it's suspicius # # and should be classified as "rubbish" (sometimes the license-checker picks # # up a README file without any real license text). # license_text_lc = license_text.lower() # if ( # 'software' not in license_text_lc and # 'copyright' not in license_text_lc and # 'license' not in license_text_lc # ): # return (None, None) # # if 'Apache License' in license_text: # return (copyright_notice, license_text) # # copyright_notice = detect_copyright_notice(license_text) # if copyright_notice: # license_text = text.split(copyright_notice)[1] # license_text = license_text.strip() # license_text = re.sub(r' +', ' ', license_text) # license_text = re.sub(r' ?(\r\n|\n)+ ?', remove_newlines_keep_paragraps, license_text) # return (copyright_notice, license_text) , which may include functions, classes, or code. Output only the next line.
assert_equal(parse_license_text('''
Here is a snippet: <|code_start|> MAX_WAIT_MINUTES = 120 class Client(object): def __init__(self, token=None): if not token: <|code_end|> . Write the next line using the current file imports: from datetime import datetime, timedelta from time import sleep from .config import config import sys import requests and context from other files: # Path: blackbelt/config.py , which may include functions, classes, or code. Output only the next line.
token = config['circleci']['access_token']
Given snippet: <|code_start|> @click.group(invoke_without_command=True, help=""" Deploy current branch to staging """) def cli(): <|code_end|> , continue by predicting the next line. Consider current file imports: import click from blackbelt.deployment import ( deploy_staging ) and context: # Path: blackbelt/deployment.py # def deploy_staging(): # branch_name = get_current_branch() # # post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue") # # check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name]) which might include code, classes, or functions. Output only the next line.
deploy_staging()
Using the snippet: <|code_start|> class TestGithubPullRequestParsing(object): github_pr = 'https://github.com/apiaryio/apiary-test/pull/123' def setUp(self): <|code_end|> , determine the next line of code. You have imports: from nose.tools import assert_equal, assert_raises, assert_not_equal from mock import patch, MagicMock from blackbelt.handle_github import ( get_pr_info, verify_merge, get_pr_ticket_id, verify_pr_state, verify_pr_required_checks, verify_branch_required_checks, run_grunt_in_parallel, get_grunt_application_name, ) import requests import json and context (class names, function names, or code) available: # Path: blackbelt/handle_github.py # def get_pr_info(pr_url): # match = re.match(r".*github.com/(?P<owner>\S+)/{1}(?P<name>\S+)/pull/{1}(?P<number>\d+).*$", pr_url) # if not match: # raise ValueError("Cannot parse pull request URL, bad format") # return match.groupdict() # # def verify_merge(pr_url, headers, max_waiting_time=30, retry_time=0.1): # merge_url = get_pr_api_url(pr_url) + "/merge" # https://api.github.com/repos/apiaryio/apiary/pulls/1234/merge # start_time = datetime.now() # succeeded = False # # def do_request(): # r = requests.get(merge_url, headers=headers) # # if r.status_code == 404: # if datetime.now() < start_time + timedelta(seconds=max_waiting_time): # sleep(retry_time) # return False # else: # raise ValueError("GitHub says PR hasn't been merged yet and I've reached the waiting time of %s seconds" % max_waiting_time) # # elif (r.status_code not in [200, 204]): # raise ValueError("Can't get PR merge info with status code %s" % r.status_code) # # else: # return True # # while not succeeded: # succeeded = do_request() # # def get_pr_ticket_id(description): # match = re.search(PR_PHRASE_PREFIX + ' ' + r"\[.*\]\(https://trello.com/c/(?P<id>\w+)/.*\)", description) # if not match or not 'id' in match.groupdict(): # raise ValueError("Can't find URL in the PR description") # # return match.groupdict()['id'] # # def verify_pr_state(pr_details): # pr_state = pr_details['state'] # message = "PR state: %s" % pr_state # if pr_state != 'open': # raise ValueError(message) # # print(message) # return message # # def verify_pr_required_checks(pr_details): # status_url = "https://api.github.com/repos/%(repo_full_name)s/commits/%(head_sha)s/status" % { # 'repo_full_name': pr_details['base']['repo']['full_name'], # 'head_sha': pr_details['head']['sha']} # # pr_checks_info = get_json_response(status_url) # message = "PR required checks (%(count)g): %(state)s" % { # 'count': len(pr_checks_info['statuses']), # 'state': pr_checks_info['state']} # if pr_checks_info['state'] != 'success': # raise ValueError(message) # # print(message) # return message # # def verify_branch_required_checks(branch_name): # repo = get_github_repo() # repo_info = get_remote_repo_info(repo) # # status_url = "https://api.github.com/repos/%(owner)s/%(name)s/commits/%(branch_name)s/status" % { # 'owner': repo_info['owner'], # 'name': repo_info['name'], # 'branch_name': branch_name} # branch = get_json_response(status_url) # message = "Branch required checks (%(count)g): %(state)s" % { # 'count': len(branch['statuses']), # 'state': branch['state']} # if branch['state'] != 'success': # raise ValueError(message) # # print(message) # return message # # def run_grunt_in_parallel(grunt_commands): # """ Helper function to run grunt commands (e.g. deploy or slug manipulation) for multiple environments in parallel""" # # return_code = 0 # # commands = [] # for command in grunt_commands: # with tempfile.NamedTemporaryFile(delete=False) as f: # app = get_grunt_application_name(' '.join(command)) # commands.append({'app': app, 'process': Popen(command, stdout=f), 'log': f.name}) # print('Running `{}` with PID {}'.format(' '.join(command), commands[-1]['process'].pid)) # # print('\n') # # while len(commands): # sleep(5) # next_round = [] # for command in commands: # rc = command['process'].poll() # if rc == None: # next_round.append(command) # else: # if rc == 0: # print('Grunt task for {} completed successfully.\n'.format(command['app'])) # os.remove(command['log']) # else: # return_code = rc # print('Grunt task for {} failed with exit code {}.'.format(command['app'], rc)) # print('Logfile can be found at {}\n'.format(command['log'])) # # commands = next_round # # # return return_code # # def get_grunt_application_name(command): # app_search = re.search("(--app=|-a=)(\w+)", command, re.IGNORECASE) # app = app_search.group(2) if app_search else "production" # # return app . Output only the next line.
self.parsed = get_pr_info(self.github_pr)
Given snippet: <|code_start|> @click.group(help='Handle Slack-related tasks and integrations.') def cli(): pass @cli.command() @click.argument('message', required=True) def post(message): <|code_end|> , continue by predicting the next line. Consider current file imports: import click from blackbelt.slack import ( post_message ) and context: # Path: blackbelt/slack.py # def post_message(self, message, room): # return self.slack.chat.post_message(room, message, username = "Black Belt", icon_emoji = ":blackbelt:") which might include code, classes, or functions. Output only the next line.
post_message(message)
Continue the code snippet: <|code_start|> def deploy_staging(): branch_name = get_current_branch() post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue") check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name]) def deploy_production(): post_message("Deploying to production", "#deploy-queue") <|code_end|> . Use current file imports: from subprocess import check_call, check_output from blackbelt.handle_github import get_current_branch, run_grunt_in_parallel from blackbelt.messages import post_message and context (classes, functions, or code) from other files: # Path: blackbelt/handle_github.py # GITHUB_CLIENT_ID = "c9f51ce9cb320bf86f16" # UA_STRING = "black-belt/%s" % VERSION # PR_PHRASE_PREFIX = "Pull request for" # def get_pr_info(pr_url): # def get_pr_api_url(pr_url): # def get_pr_details(pr_url): # def get_branch_url(pr_details): # def get_username(): # def get_request_headers(): # def get_json_response(url): # def pull_request(card_url): # def verify_merge(pr_url, headers, max_waiting_time=30, retry_time=0.1): # def do_request(): # def merge(pr_url): # def check_status(pr_url=None, branch_name=None, error_on_failure=False): # def verify_pr_state(pr_details): # def verify_pr_required_checks(pr_details): # def verify_branch_required_checks(branch_name): # def verify_gh_repo(pr_gh_repo): # def get_pr_ticket_id(description): # def deploy(pr_url): # def create_release(ref, payload, description, repo_info): # def run_grunt_in_parallel(grunt_commands): # def get_grunt_application_name(command): # # Path: blackbelt/messages.py # def post_message(message, room): # slack_post_message(message, room) . Output only the next line.
slug_creaction_return_code = run_grunt_in_parallel((
Given the code snippet: <|code_start|> config[group_name][url_key] = value config[group_name][key + '_id'] = value_id def configure_blackbelt(): print("Going to collect all the tokens and store them in ~/.blackbelt") config = { 'trello': { 'access_token': None }, 'github': { 'access_token': None }, 'circleci': { 'access_token': None }, 'slack': { 'access_token': None } } if exists(CONFIG_FILE): with open(CONFIG_FILE) as f: config = json.loads(f.read()) get_token( group_name='trello', config=config, <|code_end|> , generate the next line using the imports in this file: import json import re import webbrowser import click from os.path import expanduser, exists from blackbelt import handle_trello and context (functions, classes, or occasionally code) from other files: # Path: blackbelt/handle_trello.py # STORY_CARD_TODO_LIST_NAMES = [ # "To Do", # "ToDo", # "Engineering ToDo" # ] # TODO_QUEUE_NAME = "To Do Queue" # DEPLOY_QUEUE_NAME = "Ready" # DEPLOYED_PREFIX = "Deployed by" # VERIFIED_PREFIX = "Verified by" # TEA_ORDER_QUEUE_NAME = "Order next" # COLUMN_CACHE = {} # def get_token_url(): # def get_api(): # def get_column(name, board_id=None): # def get_next_todo_card(): # def get_current_working_ticket(card_url=None): # def open_current_working_ticket(): # def get_ticket_ready(ticket): # def comment_ticket(ticket, comment): # def migrate_label(label, board, board_to, column, column_to): # def get_conversion_items(api, card_list, story_card, story_list): # def schedule_list(story_card, story_list=None, owner=None, label=None): # def infer_branch_name(url): # def next_card(): # def move_to_deployed(card_id, comment=None): # def get_next_sunday(): # def next_week(): # def verify(story_card): # def get_tea_from_card(card): # def get_tea_email(teas, sender_name): # def order_tea(): . Output only the next line.
token_url=handle_trello.get_token_url()
Given the code snippet: <|code_start|> datetime_patcher = mock.patch.object( blackbelt.handle_trello.datetime, 'date', mock.Mock(wraps=datetime.datetime) ) class TestInferringBranch(object): def test_simple_url(self): <|code_end|> , generate the next line using the imports in this file: import mock import datetime import blackbelt from mock import patch from nose.tools import assert_equal from blackbelt.handle_trello import infer_branch_name, get_next_sunday and context (functions, classes, or occasionally code) from other files: # Path: blackbelt/handle_trello.py # def infer_branch_name(url): # return '-'.join(url.split('/')[~0].split('-')[1:]) # # def get_next_sunday(): # diff = datetime.date.today().weekday() # # On sunday, add week instead # if diff == 6: # diff = -1 # # return datetime.date.today() + datetime.timedelta( # days=6 - diff # ) . Output only the next line.
assert_equal('bb-t-next', infer_branch_name(
Given the following code snippet before the placeholder: <|code_start|> datetime_patcher = mock.patch.object( blackbelt.handle_trello.datetime, 'date', mock.Mock(wraps=datetime.datetime) ) class TestInferringBranch(object): def test_simple_url(self): assert_equal('bb-t-next', infer_branch_name( 'https://trello.com/c/7b4Z3V8o/1803-bb-t-next' )) class TestNextSunday(object): def setUp(self): self.mocked_datetime = datetime_patcher.start() def tearDown(self): datetime_patcher.stop() def test_middle_week(self): self.mocked_datetime.today.return_value = datetime.datetime(2015, 4, 1) # April's Fools! In fact, Wednesday <|code_end|> , predict the next line using imports from the current file: import mock import datetime import blackbelt from mock import patch from nose.tools import assert_equal from blackbelt.handle_trello import infer_branch_name, get_next_sunday and context including class names, function names, and sometimes code from other files: # Path: blackbelt/handle_trello.py # def infer_branch_name(url): # return '-'.join(url.split('/')[~0].split('-')[1:]) # # def get_next_sunday(): # diff = datetime.date.today().weekday() # # On sunday, add week instead # if diff == 6: # diff = -1 # # return datetime.date.today() + datetime.timedelta( # days=6 - diff # ) . Output only the next line.
sun = get_next_sunday()
Predict the next line after this snippet: <|code_start|> @click.group(invoke_without_command=True, help=""" Rollback latest version from production environments (prod, pre, qa) """) def cli(): <|code_end|> using the current file's imports: import click from blackbelt.deployment import ( rollback_production ) and any relevant context from other files: # Path: blackbelt/deployment.py # def rollback_production(): # # post_message("Rollback production for all environments (prod, qa, pre)", "#deploy-queue") # # check_call(['grunt', 'rollback', '--app=apiary-staging-qa']) # check_call(['grunt', 'rollback', '--app=apiary-staging-pre']) # check_call(['grunt', 'rollback']) . Output only the next line.
rollback_production()
Here is a snippet: <|code_start|> :param model: A MongoEngine Document schema class :param base_class: Base form class to extend from. Must be a ``wtforms.Form`` subclass. :param fields: An optional iterable with the property names that should be included in the form. Only these properties will have fields. It also determines the order of the fields. :param exclude: An optional iterable with the property names that should be excluded from the form. All other properties will have fields. :param field_args: An optional dictionary of field names mapping to keyword arguments used to construct each field object. :param converter: A converter to generate the fields based on the model properties. If not set, ``ModelConverter`` is used. """ field_dict = model_fields(model, fields, readonly_fields, exclude, field_args, converter) field_dict['model_class'] = model def populate_obj(self, obj): return data_to_document(obj, self.data) field_dict['populate_obj'] = populate_obj return type(model.__name__ + 'Form', (base_class,), field_dict) <|code_end|> . Write the next line using the current file imports: import inspect import mongoengine.fields as fields from werkzeug import secure_filename from wtforms import Form, validators, fields as f from fields import ModelSelectField, ModelSelectMultipleField, ListField from mongoengine.fields import ReferenceField, IntField, FloatField from flask_superadmin.model import AdminModelConverter as AdminModelConverter_ from mongoengine.base import BaseDocument from bson.objectid import ObjectId from inspect import isclass and context from other files: # Path: flask_superadmin/model/base.py # class AdminModelConverter(object): # def convert(self, *args, **kwargs): # field = super(AdminModelConverter, self).convert(*args, **kwargs) # if field: # widget = field.kwargs.get('widget', field.field_class.widget) # if isinstance(widget, widgets.Select): # field.kwargs['widget'] = ChosenSelectWidget( # multiple=widget.multiple) # elif issubclass(field.field_class, fields.DateTimeField): # field.kwargs['widget'] = DateTimePickerWidget() # elif issubclass(field.field_class, fields.DateField): # field.kwargs['widget'] = DatePickerWidget() # elif issubclass(field.field_class, fields.FileField): # field.field_class = FileField # return field , which may include functions, classes, or code. Output only the next line.
class AdminModelConverter(AdminModelConverter_, ModelConverter):
Using the snippet: <|code_start|> __all__ = ( 'AdminModelConverter', 'model_fields', 'model_form' ) class ModelConverterBase(object): def __init__(self, converters): self.converters = converters def convert(self, model, field, field_args): kwargs = { 'label': field.verbose_name, 'description': field.help_text, 'validators': [], 'filters': [], 'default': field.default, } if field_args: kwargs.update(field_args) if field.blank: kwargs['validators'].append(validators.Optional()) if field.max_length is not None and field.max_length > 0: kwargs['validators'].append(validators.Length(max=field.max_length)) ftype = type(field).__name__ if field.choices: kwargs['choices'] = field.choices <|code_end|> , determine the next line of code. You have imports: from wtforms import fields as f from wtforms import Form from wtforms import validators from wtforms.ext.django.fields import ModelSelectField from flask_superadmin import form from django.contrib.localflavor.us.us_states import STATE_CHOICES and context (class names, function names, or code) available: # Path: flask_superadmin/form.py # class BaseForm(wtf.Form): # class TimeField(fields.Field): # class ChosenSelectWidget(widgets.Select): # class ChosenSelectField(fields.SelectField): # class FileFieldWidget(object): # class FileField(fields.FileField): # class DatePickerWidget(widgets.TextInput): # class DateTimePickerWidget(widgets.TextInput): # def __init__(self, formdata=None, obj=None, prefix='', **kwargs): # def has_file_field(self): # def __init__(self, label=None, validators=None, formats=None, **kwargs): # def _value(self): # def process_formdata(self, valuelist): # def __call__(self, field, **kwargs): # def __call__(self, field, **kwargs): # def __init__(self,*args,**kwargs): # def process(self, formdata, data=fields._unset_value): # def clear(self): # def data(self): # def data(self, data): # def __call__(self, field, **kwargs): # def __call__(self, field, **kwargs): . Output only the next line.
return f.SelectField(widget=form.ChosenSelectWidget(), **kwargs)
Here is a snippet: <|code_start|> def archive_capsule(docs): links = docs.get('links') if links is None or not links.upload: return None try: return urllib.unquote( re.search( r'C:([^:]*):', urlparse(links.upload).fragment ).group(1) ).decode('utf8') except Exception: <|code_end|> . Write the next line using the current file imports: import urllib import re from lacli.log import getLogger from urlparse import urlparse and context from other files: # Path: lacli/log.py # def getLogger(logger='lacli'): # return lacore.log.getLogger(logger) , which may include functions, classes, or code. Output only the next line.
getLogger().debug("no capsule information found", exc_info=True)
Continue the code snippet: <|code_start|> __metaclass__ = ABCMeta def __init__(self, *args, **kwargs): self.tx = {} self.progress = kwargs.pop('progress', 0) super(BaseProgressHandler, self).__init__(*args, **kwargs) def update_current(self, msg): self.tx[msg['part']] = int(msg['tx']) return sum(self.tx.values()) def save_current(self): self.progress += sum(self.tx.values()) self.tx = {} def handle(self, msg): if 'part' in msg: self.update(self.progress + self.update_current(msg)) elif 'save' in msg: self.keydone(msg) self.save_current() def __enter__(self): q = super(BaseProgressHandler, self).__enter__() progressToQueue(q) self.start(initval=self.progress) return q @abstractmethod def keydone(self, msg): <|code_end|> . Use current file imports: import os import multiprocessing from progressbar import (ProgressBar, Bar, ETA, FileTransferSpeed) from lacli.log import getLogger from abc import ABCMeta, abstractmethod from logutils.queue import QueueListener and context (classes, functions, or code) from other files: # Path: lacli/log.py # def getLogger(logger='lacli'): # return lacore.log.getLogger(logger) . Output only the next line.
getLogger().debug("saved key: {key} ({size})".format(msg))
Given the following code snippet before the placeholder: <|code_start|> }, }, 'loggers': { 'boto': { 'handlers': ['queue'] }, 'lacli': { 'level': 'DEBUG', 'handlers': ['queue'] }, 'lacore': { 'level': 'DEBUG', 'handlers': ['queue'] }, }, 'root': { 'level': 'DEBUG', }, }) def initworker(logq, progq, ctrlq, stdin=None): """initializer that sets up logging and progress from sub procs """ logToQueue(logq) progressToQueue(progq) controlByQueue(ctrlq) setproctitle(current_process().name) signal.signal(signal.SIGINT, signal.SIG_IGN) if hasattr(signal, 'SIGBREAK'): signal.signal(signal.SIGBREAK, signal.SIG_IGN) <|code_end|> , predict the next line using imports from the current file: import logging import sys import os import signal from lacli.log import getLogger from lacli.progress import progressToQueue from lacli.control import controlByQueue from multiprocessing import cpu_count, pool, current_process, Process from setproctitle import setproctitle and context including class names, function names, and sometimes code from other files: # Path: lacli/log.py # def getLogger(logger='lacli'): # return lacore.log.getLogger(logger) # # Path: lacli/progress.py # def progressToQueue(queue): # global progress # progress = queue # # Path: lacli/control.py # def controlByQueue(queue): # global controlq # controlq = queue . Output only the next line.
getLogger().debug("Worker " + current_process().name + " logging started")