Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Using the snippet: <|code_start|> logging.basicConfig(level=logging.INFO) class Command(BaseCommand): def handle(self, *args, **options): <|code_end|> , determine the next line of code. You have imports: import logging from django.core.management.base import BaseCommand from auv_control_pi.components.remote_proxy import main and context (class names, function names, or code) available: # Path: auv_control_pi/components/remote_proxy.py # def main(): # RouterProxy(remote_comp, local_comp) # run([local_comp, remote_comp]) . Output only the next line.
main()
Given the code snippet: <|code_start|> logging.basicConfig(level=logging.INFO) class Command(BaseCommand): def handle(self, *args, **options): comp = Component( transports="ws://crossbar:8080/ws", realm="realm1", <|code_end|> , generate the next line using the imports in this file: import logging from autobahn.asyncio.component import Component, run from django.core.management.base import BaseCommand from auv_control_pi.components.camera import Camera and context (functions, classes, or occasionally code) from other files: # Path: auv_control_pi/components/camera.py # class Camera(ApplicationSession): # """Main entry point for controling the Mothership and AUV # """ # name = 'camera' # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # # TODO check if gopro connected # self.gopro = GoProCamera.GoPro() # if not self.gopro._camera: # logger.warning('Failed to connect to GoPro!') # self.gopro = None # else: # logger.info('Connected to GoPro!') # # @rpc('camera.take_snapshot') # def take_snapshot(self): # if self.gopro: # url = self.gopro.take_photo() # img_uri = download_image(url) # print(url) # else: # img_uri = DataURI.from_file('cat.jpg') # return img_uri # # async def update(self): # """Publish current state to anyone listening # """ # while True: # image = self.take_snapshot() # # payload = { # 'img': image, # # 'timestamp': timezone.now().isoformat() # } # self.publish('camera.update', payload) # # await asyncio.sleep(0.1) . Output only the next line.
session_factory=Camera,
Predict the next line after this snippet: <|code_start|> logger = logging.getLogger(__name__) config = Configuration.get_solo() def download_image(url): resp = requests.get(url, stream=True) with open('img.jpg', 'wb') as f: resp.raw.decode_content = True shutil.copyfileobj(resp.raw, f) img_uri = DataURI.from_file('img.jpg') return img_uri <|code_end|> using the current file's imports: import asyncio import logging import shutil import requests from goprocam import GoProCamera from datauri import DataURI from ..models import Configuration from ..wamp import ApplicationSession, rpc and any relevant context from other files: # Path: auv_control_pi/models.py # class Configuration(SingletonModel): # # auv_id = models.UUIDField(blank=True, null=True) # auth_token = models.CharField(max_length=1024, blank=True) # update_frequency = models.DecimalField(blank=True, null=True, # max_digits=5, decimal_places=3) # left_motor_channel = models.IntegerField(default=0) # right_motor_channel = models.IntegerField(default=1) # trim = models.IntegerField(default=0) # name = models.CharField(max_length=255, blank=True) # address = models.CharField(max_length=255, blank=True) # crossbar_url = models.CharField(max_length=255, default='ws://localhost:8000/ws') # crossbar_realm = models.CharField(max_length=255, default='realm1') # # # auto pilot config vars # kP = models.FloatField(blank=True, default=1) # kI = models.FloatField(blank=True, default=0) # kD = models.FloatField(blank=True, default=0) # target_waypoint_distance = models.FloatField(blank=True, default=60) # pid_error_debounce = models.FloatField(blank=True, default=5) # # magbias_x = models.FloatField(blank=True, default=0) # magbias_y = models.FloatField(blank=True, default=0) # magbias_z = models.FloatField(blank=True, default=0) # declination = models.FloatField(blank=True, default=0) # board_offset = models.FloatField(blank=True, default=0) # # def __str__(self): # return 'AUV Configuration' # # class Meta: # verbose_name = "AUV Configuration" # # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer . Output only the next line.
class Camera(ApplicationSession):
Given the code snippet: <|code_start|> logger = logging.getLogger(__name__) config = Configuration.get_solo() def download_image(url): resp = requests.get(url, stream=True) with open('img.jpg', 'wb') as f: resp.raw.decode_content = True shutil.copyfileobj(resp.raw, f) img_uri = DataURI.from_file('img.jpg') return img_uri class Camera(ApplicationSession): """Main entry point for controling the Mothership and AUV """ name = 'camera' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO check if gopro connected self.gopro = GoProCamera.GoPro() if not self.gopro._camera: logger.warning('Failed to connect to GoPro!') self.gopro = None else: logger.info('Connected to GoPro!') <|code_end|> , generate the next line using the imports in this file: import asyncio import logging import shutil import requests from goprocam import GoProCamera from datauri import DataURI from ..models import Configuration from ..wamp import ApplicationSession, rpc and context (functions, classes, or occasionally code) from other files: # Path: auv_control_pi/models.py # class Configuration(SingletonModel): # # auv_id = models.UUIDField(blank=True, null=True) # auth_token = models.CharField(max_length=1024, blank=True) # update_frequency = models.DecimalField(blank=True, null=True, # max_digits=5, decimal_places=3) # left_motor_channel = models.IntegerField(default=0) # right_motor_channel = models.IntegerField(default=1) # trim = models.IntegerField(default=0) # name = models.CharField(max_length=255, blank=True) # address = models.CharField(max_length=255, blank=True) # crossbar_url = models.CharField(max_length=255, default='ws://localhost:8000/ws') # crossbar_realm = models.CharField(max_length=255, default='realm1') # # # auto pilot config vars # kP = models.FloatField(blank=True, default=1) # kI = models.FloatField(blank=True, default=0) # kD = models.FloatField(blank=True, default=0) # target_waypoint_distance = models.FloatField(blank=True, default=60) # pid_error_debounce = models.FloatField(blank=True, default=5) # # magbias_x = models.FloatField(blank=True, default=0) # magbias_y = models.FloatField(blank=True, default=0) # magbias_z = models.FloatField(blank=True, default=0) # declination = models.FloatField(blank=True, default=0) # board_offset = models.FloatField(blank=True, default=0) # # def __str__(self): # return 'AUV Configuration' # # class Meta: # verbose_name = "AUV Configuration" # # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer . Output only the next line.
@rpc('camera.take_snapshot')
Given the code snippet: <|code_start|> SIMULATION = os.getenv('SIMULATION', False) logger = logging.getLogger(__name__) class Navitgator(ApplicationSession): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.enabled = False self.heading = None self.target_heading = None self.current_location = None self.target_waypoint = None self.update_frequency = 10 self.arrived = False self.waypoints = deque() self.completed_waypoints = [] # the pid setpoint is the error setpoint # and thus we always want the error to be 0 regardless of the scale # we use to feed into the pid. <|code_end|> , generate the next line using the imports in this file: import os import asyncio import logging from collections import deque from simple_pid import PID from auv_control_pi.config import config from auv_control_pi.utils import Point, distance_to_point, heading_to_point, get_error_angle from auv_control_pi.wamp import ApplicationSession, rpc, subscribe and context (functions, classes, or occasionally code) from other files: # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): # # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer . Output only the next line.
self.pid = PID(config.kP, config.kI, config.kD, setpoint=0, output_limits=(-100, 100))
Given the code snippet: <|code_start|>SIMULATION = os.getenv('SIMULATION', False) logger = logging.getLogger(__name__) class Navitgator(ApplicationSession): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.enabled = False self.heading = None self.target_heading = None self.current_location = None self.target_waypoint = None self.update_frequency = 10 self.arrived = False self.waypoints = deque() self.completed_waypoints = [] # the pid setpoint is the error setpoint # and thus we always want the error to be 0 regardless of the scale # we use to feed into the pid. self.pid = PID(config.kP, config.kI, config.kD, setpoint=0, output_limits=(-100, 100)) self.pid_output = None self.heading_error = None @subscribe('ahrs.update') def _update_ahrs(self, data): self.heading = data.get('heading', None) @subscribe('gps.update') def _update_gps(self, data): <|code_end|> , generate the next line using the imports in this file: import os import asyncio import logging from collections import deque from simple_pid import PID from auv_control_pi.config import config from auv_control_pi.utils import Point, distance_to_point, heading_to_point, get_error_angle from auv_control_pi.wamp import ApplicationSession, rpc, subscribe and context (functions, classes, or occasionally code) from other files: # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): # # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer . Output only the next line.
self.current_location = Point(lat=data.get('lat'), lng=data.get('lng'))
Here is a snippet: <|code_start|> 'target_heading': self.target_heading, 'kP': self.pid.Kp, 'kI': self.pid.Ki, 'kD': self.pid.Kd, 'heading_error': self.heading_error, 'pid_output': self.pid_output, 'arrived': self.arrived, 'distance_to_target': self.distance_to_target }) await asyncio.sleep(1 / self.update_frequency) def _steer(self): """Calculate heading error to feed into PID """ # TODO think about how often should we update the target heading? # if it's updated too often then it could cause jittery behavior self.target_heading = heading_to_point(self.current_location, self.target_waypoint) self.heading_error = get_error_angle(self.target_heading, self.heading) # update the pid self.pid_output = self.pid(self.heading_error) # only take action if the error is beyond the debounce if abs(self.heading_error) > config.pid_error_debounce: # take action to ajdust the speed of each motor to steer # in the direction to minimize the heading error self.call('auv.set_turn_val', self.pid_output) @property def distance_to_target(self): if self.target_waypoint: <|code_end|> . Write the next line using the current file imports: import os import asyncio import logging from collections import deque from simple_pid import PID from auv_control_pi.config import config from auv_control_pi.utils import Point, distance_to_point, heading_to_point, get_error_angle from auv_control_pi.wamp import ApplicationSession, rpc, subscribe and context from other files: # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): # # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer , which may include functions, classes, or code. Output only the next line.
return distance_to_point(self.current_location, self.target_waypoint)
Given snippet: <|code_start|> @rpc('nav.get_pid_values') def get_pid_values(self): return { 'kP': self.pid.Kp, 'kI': self.pid.Ki, 'kD': self.pid.Kd, 'debounce': config.pid_error_debounce } @rpc('nav.get_target_waypoint_distance') def get_target_waypoint_distance(self): return { 'target_waypoint_distance': config.target_waypoint_distance } @rpc('nav.set_target_waypoint_distance') def set_target_waypoint_distance(self, target_waypoint_distance): config.target_waypoint_distance = int(target_waypoint_distance) config.save() @rpc('nav.move_to_waypoint') def move_to_waypoint(self, waypoint): self.call('auv.forward_throttle', 50) self.pid.auto_mode = True if isinstance(waypoint, dict): waypoint = Point(**waypoint) logger.info('Moving to waypint: {}'.format(waypoint)) self.arrived = False self.target_waypoint = waypoint <|code_end|> , continue by predicting the next line. Consider current file imports: import os import asyncio import logging from collections import deque from simple_pid import PID from auv_control_pi.config import config from auv_control_pi.utils import Point, distance_to_point, heading_to_point, get_error_angle from auv_control_pi.wamp import ApplicationSession, rpc, subscribe and context: # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): # # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer which might include code, classes, or functions. Output only the next line.
self.target_heading = heading_to_point(self.current_location, waypoint)
Using the snippet: <|code_start|> self.stop() logger.info('Arrived at {}'.format(self.target_waypoint)) # otherwise keep steering towards the target waypoint else: self._steer() config.refresh_from_db() self.publish('nav.update', { 'enabled': self.enabled, 'target_waypoint': self.target_waypoint._asdict() if self.target_waypoint else None, 'completed_waypoints': list(self.completed_waypoints), 'waypoints': list(self.waypoints), 'target_heading': self.target_heading, 'kP': self.pid.Kp, 'kI': self.pid.Ki, 'kD': self.pid.Kd, 'heading_error': self.heading_error, 'pid_output': self.pid_output, 'arrived': self.arrived, 'distance_to_target': self.distance_to_target }) await asyncio.sleep(1 / self.update_frequency) def _steer(self): """Calculate heading error to feed into PID """ # TODO think about how often should we update the target heading? # if it's updated too often then it could cause jittery behavior self.target_heading = heading_to_point(self.current_location, self.target_waypoint) <|code_end|> , determine the next line of code. You have imports: import os import asyncio import logging from collections import deque from simple_pid import PID from auv_control_pi.config import config from auv_control_pi.utils import Point, distance_to_point, heading_to_point, get_error_angle from auv_control_pi.wamp import ApplicationSession, rpc, subscribe and context (class names, function names, or code) available: # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): # # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer . Output only the next line.
self.heading_error = get_error_angle(self.target_heading, self.heading)
Predict the next line after this snippet: <|code_start|> class Navitgator(ApplicationSession): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.enabled = False self.heading = None self.target_heading = None self.current_location = None self.target_waypoint = None self.update_frequency = 10 self.arrived = False self.waypoints = deque() self.completed_waypoints = [] # the pid setpoint is the error setpoint # and thus we always want the error to be 0 regardless of the scale # we use to feed into the pid. self.pid = PID(config.kP, config.kI, config.kD, setpoint=0, output_limits=(-100, 100)) self.pid_output = None self.heading_error = None @subscribe('ahrs.update') def _update_ahrs(self, data): self.heading = data.get('heading', None) @subscribe('gps.update') def _update_gps(self, data): self.current_location = Point(lat=data.get('lat'), lng=data.get('lng')) <|code_end|> using the current file's imports: import os import asyncio import logging from collections import deque from simple_pid import PID from auv_control_pi.config import config from auv_control_pi.utils import Point, distance_to_point, heading_to_point, get_error_angle from auv_control_pi.wamp import ApplicationSession, rpc, subscribe and any relevant context from other files: # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): # # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer . Output only the next line.
@rpc('nav.set_pid_values')
Using the snippet: <|code_start|> SIMULATION = os.getenv('SIMULATION', False) logger = logging.getLogger(__name__) class Navitgator(ApplicationSession): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.enabled = False self.heading = None self.target_heading = None self.current_location = None self.target_waypoint = None self.update_frequency = 10 self.arrived = False self.waypoints = deque() self.completed_waypoints = [] # the pid setpoint is the error setpoint # and thus we always want the error to be 0 regardless of the scale # we use to feed into the pid. self.pid = PID(config.kP, config.kI, config.kD, setpoint=0, output_limits=(-100, 100)) self.pid_output = None self.heading_error = None <|code_end|> , determine the next line of code. You have imports: import os import asyncio import logging from collections import deque from simple_pid import PID from auv_control_pi.config import config from auv_control_pi.utils import Point, distance_to_point, heading_to_point, get_error_angle from auv_control_pi.wamp import ApplicationSession, rpc, subscribe and context (class names, function names, or code) available: # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): # # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer . Output only the next line.
@subscribe('ahrs.update')
Given the code snippet: <|code_start|> def test_point(): point = Point(10, 20) assert point.lat == 10 assert point.lng == 20 def test_heading_to_point(): start_point = Point(49, -120) end_point = Point(50, -120) heading = heading_to_point(start_point, end_point) assert heading == 0.0 def test_distance_to_point(): start_point = Point(49, -120) end_point = Point(50, -120) distance = distance_to_point(start_point, end_point) assert isinstance(distance, float) def test_get_error_angle(): <|code_end|> , generate the next line using the imports in this file: from ..utils import get_error_angle, Point, heading_to_point, distance_to_point and context (functions, classes, or occasionally code) from other files: # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): . Output only the next line.
result = get_error_angle(target=10, heading=0)
Given the code snippet: <|code_start|> def test_point(): point = Point(10, 20) assert point.lat == 10 assert point.lng == 20 def test_heading_to_point(): start_point = Point(49, -120) end_point = Point(50, -120) <|code_end|> , generate the next line using the imports in this file: from ..utils import get_error_angle, Point, heading_to_point, distance_to_point and context (functions, classes, or occasionally code) from other files: # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): . Output only the next line.
heading = heading_to_point(start_point, end_point)
Given the following code snippet before the placeholder: <|code_start|> def test_point(): point = Point(10, 20) assert point.lat == 10 assert point.lng == 20 def test_heading_to_point(): start_point = Point(49, -120) end_point = Point(50, -120) heading = heading_to_point(start_point, end_point) assert heading == 0.0 def test_distance_to_point(): start_point = Point(49, -120) end_point = Point(50, -120) <|code_end|> , predict the next line using imports from the current file: from ..utils import get_error_angle, Point, heading_to_point, distance_to_point and context including class names, function names, and sometimes code from other files: # Path: auv_control_pi/utils.py # def elapsed_micros(start_time_us): # def micros(): # def clamp_angle(deg): # def point_at_distance(distance, heading, current_point): # def heading_to_point(point_a, point_b): # def distance_to_point(point_a, point_b): # def get_error_angle(target, heading): . Output only the next line.
distance = distance_to_point(start_point, end_point)
Predict the next line after this snippet: <|code_start|> logging.basicConfig(level=logging.INFO) class Command(BaseCommand): def handle(self, *args, **options): comp = Component( transports="ws://crossbar:8080/ws", realm="realm1", <|code_end|> using the current file's imports: import logging from autobahn.asyncio.component import Component, run from django.core.management.base import BaseCommand from auv_control_pi.components.rc_controller import RCControler and any relevant context from other files: # Path: auv_control_pi/components/rc_controller.py # class RCControler(ApplicationSession): # """Main entry point for controling the Mothership and AUV # """ # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.armed = False # self.rc_input = RCInput() # self.last_throttle_signal = None # self.last_turn_signal = None # self.update_frequency = 10 # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, 'rc_control')) # self.join(realm=self.config.realm) # # def onJoin(self, details): # """Register functions for access via RPC and start update loops # """ # logger.info("Joined Crossbar Session") # # # create subtasks # loop = asyncio.get_event_loop() # loop.create_task(self.run()) # loop.create_task(self.update()) # # async def update(self): # while True: # self.publish( # 'rc_control.update', # { # 'armed': self.armed, # 'throttle': self.last_throttle_signal, # 'turn': self.last_turn_signal, # } # ) # await asyncio.sleep(1 / self.update_frequency) # # async def run(self): # """Main controll loop # """ # while True: # # check if the armed button is on/off # rc_armed = int(self.rc_input.read(ch=RC_ARM_CHANNEL)) # if rc_armed < ARMED_THRESHOLD and self.armed is True: # logger.info('RC Control: Disarmed') # self.call('nav.stop') # self.call('auv.stop') # self.armed = False # # elif rc_armed > ARMED_THRESHOLD and self.armed is False: # logger.info('RC Control: Armed') # self.armed = True # # # TODO when initially armed it would be useful to force the user to zero # # the throttle and turn inputs before any new commands are registered # # This will prevent connecting via the RC controller and having the throttle # # already engaged which could cause unexpected behaviour. # # # only respond to commands when the rc is armed # if self.armed: # rc_throttle = int(self.rc_input.read(ch=RC_THROTTLE_CHANNEL)) # rc_turn = int(self.rc_input.read(ch=RC_TURN_CHANNEL)) # # # only update if the signal has changed # if self.last_throttle_signal is not None and abs(rc_throttle - self.last_throttle_signal) > DEBOUNCE_RANGE: # if rc_throttle < REVERSE_THRESHOLD: # throttle = int(100 * abs(rc_throttle - REVERSE_THRESHOLD) / abs(RC_LOW - REVERSE_THRESHOLD)) # self.call('auv.reverse_throttle', throttle) # elif rc_throttle > FORWARD_THRESHOLD: # throttle = int(100 * abs(rc_throttle - FORWARD_THRESHOLD) / abs(RC_HIGH - FORWARD_THRESHOLD)) # self.call('auv.forward_throttle', throttle) # else: # self.call('auv.stop') # # # store the current reading for use next time around the loop # self.last_throttle_signal = rc_throttle # # if self.last_throttle_signal is None: # self.last_throttle_signal = rc_throttle # # if self.last_turn_signal is not None and abs(rc_turn - self.last_turn_signal) > DEBOUNCE_RANGE: # if rc_turn < LEFT_THRESHOLD: # turn = int(100 * abs(rc_turn - LEFT_THRESHOLD) / abs(RC_LOW - LEFT_THRESHOLD)) # self.call('auv.move_left', turn) # elif rc_turn > RIGHT_THRESHOLD: # turn = int(100 * abs(rc_turn - RIGHT_THRESHOLD) / abs(RC_HIGH - RIGHT_THRESHOLD)) # self.call('auv.move_right', turn) # else: # self.call('auv.move_center') # # # store the current reading for use next time around the loop # self.last_turn_signal = rc_turn # # if self.last_turn_signal is None: # self.last_turn_signal = rc_turn # # # wait a little bit until reading in a new command to prevent twichy controls # await asyncio.sleep(0.05) . Output only the next line.
session_factory=RCControler,
Next line prediction: <|code_start|>This is adapted from https://github.com/micropython-IMU/micropython-fusion Basically things have been renamed to AHRS naming scheme, pep8 improvements and adjusted to work with CPython instead of MicroPython. Supports 6 and 9 degrees of freedom sensors. Tested with InvenSense MPU-9150 9DOF sensor. Source https://github.com/xioTechnologies/Open-Source-AHRS-With-x-IMU.git also https://github.com/kriswiner/MPU-9250.git Ported to Python. Integrator timing adapted for pyboard. User should repeatedly call the appropriate 6 or 9 DOF update method and extract heading pitch and roll angles as required. Calibrate method: The sensor should be slowly rotated around each orthogonal axis while this runs. arguments: getxyz must return current magnetometer (x, y, z) tuple from the sensor stopfunc (responding to time or user input) tells it to stop waitfunc provides an optional delay between readings to accommodate hardware or to avoid hogging the CPU in a threaded environment. It sets magbias to the mean values of x,y,z """ PI = os.getenv('PI', False) if PI: logger = logging.getLogger(__name__) SIMULATION = os.getenv('SIMULATION', False) <|code_end|> . Use current file imports: (import os import asyncio import logging from ..wamp import ApplicationSession, rpc, subscribe from navio.lsm9ds1 import LSM9DS1 from ..config import config from math import sqrt, atan2, asin, degrees, radians from ..utils import micros, elapsed_micros, clamp_angle) and context including class names, function names, or small code snippets from other files: # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer # # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def micros(): # return time.perf_counter() * 1e6 # # def elapsed_micros(start_time_us): # return (time.perf_counter() * 1e6) - start_time_us # # def clamp_angle(deg): # """Rotate angle back to be within [0, 360] # """ # n_rotations = deg // 360 # deg -= 360 * n_rotations # return deg . Output only the next line.
class AHRS(ApplicationSession):
Predict the next line for this snippet: <|code_start|> name = 'ahrs' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not SIMULATION: self.imu = LSM9DS1() self.imu.initialize() self.declination = config.declination self.board_offset = config.board_offset # local magnetic bias factors: set from calibration self.magbias = (config.magbias_x, config.magbias_y, config.magbias_z) self.start_time = None # Time between updates self.q = [1.0, 0.0, 0.0, 0.0] # vector to hold quaternion gyro_meas_error = radians(270) # Original code indicates this leads to a 2 sec response time self.beta = sqrt(3.0 / 4.0) * gyro_meas_error # compute beta (see README) self.update_frequency = 10 self._simulated_heading = 0 def calibrate(self, getxyz, stopfunc, waitfunc=None): magmax = list(getxyz()) # Initialise max and min lists with current values magmin = magmax[:] while not stopfunc(): if waitfunc is not None: waitfunc() magxyz = tuple(getxyz()) for x in range(3): magmax[x] = max(magmax[x], magxyz[x]) magmin[x] = min(magmin[x], magxyz[x]) self.magbias = tuple(map(lambda a, b: (a + b)/2, magmin, magmax)) <|code_end|> with the help of current file imports: import os import asyncio import logging from ..wamp import ApplicationSession, rpc, subscribe from navio.lsm9ds1 import LSM9DS1 from ..config import config from math import sqrt, atan2, asin, degrees, radians from ..utils import micros, elapsed_micros, clamp_angle and context from other files: # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer # # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def micros(): # return time.perf_counter() * 1e6 # # def elapsed_micros(start_time_us): # return (time.perf_counter() * 1e6) - start_time_us # # def clamp_angle(deg): # """Rotate angle back to be within [0, 360] # """ # n_rotations = deg // 360 # deg -= 360 * n_rotations # return deg , which may contain function names, class names, or code. Output only the next line.
@rpc('ahrs.get_heading')
Predict the next line after this snippet: <|code_start|> magxyz = tuple(getxyz()) for x in range(3): magmax[x] = max(magmax[x], magxyz[x]) magmin[x] = min(magmin[x], magxyz[x]) self.magbias = tuple(map(lambda a, b: (a + b)/2, magmin, magmax)) @rpc('ahrs.get_heading') def get_heading(self): return self.heading @rpc('ahrs.get_declination') def get_declination(self): return config.declination @rpc('ahrs.get_board_offset') def get_board_offset(self): return config.board_offset @rpc('ahrs.set_declination') def set_declination(self, val): self.declination = float(val) config.declination = self.declination config.save() @rpc('ahrs.set_board_offset') def set_board_offset(self, val): self.board_offset = float(val) config.board_offset = self.board_offset config.save() <|code_end|> using the current file's imports: import os import asyncio import logging from ..wamp import ApplicationSession, rpc, subscribe from navio.lsm9ds1 import LSM9DS1 from ..config import config from math import sqrt, atan2, asin, degrees, radians from ..utils import micros, elapsed_micros, clamp_angle and any relevant context from other files: # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer # # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def micros(): # return time.perf_counter() * 1e6 # # def elapsed_micros(start_time_us): # return (time.perf_counter() * 1e6) - start_time_us # # def clamp_angle(deg): # """Rotate angle back to be within [0, 360] # """ # n_rotations = deg // 360 # deg -= 360 * n_rotations # return deg . Output only the next line.
@subscribe('auv.update')
Predict the next line for this snippet: <|code_start|>The sensor should be slowly rotated around each orthogonal axis while this runs. arguments: getxyz must return current magnetometer (x, y, z) tuple from the sensor stopfunc (responding to time or user input) tells it to stop waitfunc provides an optional delay between readings to accommodate hardware or to avoid hogging the CPU in a threaded environment. It sets magbias to the mean values of x,y,z """ PI = os.getenv('PI', False) if PI: logger = logging.getLogger(__name__) SIMULATION = os.getenv('SIMULATION', False) class AHRS(ApplicationSession): """Class provides sensor fusion allowing heading, pitch and roll to be extracted. This uses the Madgwick algorithm. The update method must be called peiodically. """ name = 'ahrs' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not SIMULATION: self.imu = LSM9DS1() self.imu.initialize() <|code_end|> with the help of current file imports: import os import asyncio import logging from ..wamp import ApplicationSession, rpc, subscribe from navio.lsm9ds1 import LSM9DS1 from ..config import config from math import sqrt, atan2, asin, degrees, radians from ..utils import micros, elapsed_micros, clamp_angle and context from other files: # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer # # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def micros(): # return time.perf_counter() * 1e6 # # def elapsed_micros(start_time_us): # return (time.perf_counter() * 1e6) - start_time_us # # def clamp_angle(deg): # """Rotate angle back to be within [0, 360] # """ # n_rotations = deg // 360 # deg -= 360 * n_rotations # return deg , which may contain function names, class names, or code. Output only the next line.
self.declination = config.declination
Continue the code snippet: <|code_start|> @property def heading(self): if SIMULATION: heading = self.declination + self.board_offset + self._simulated_heading return clamp_angle(heading) else: offset = self.declination + self.board_offset heading = ( 180 + degrees(radians(offset) + atan2(2.0 * (self.q[1] * self.q[2] + self.q[0] * self.q[3]), self.q[0] * self.q[0] + self.q[1] * self.q[1] - self.q[2] * self.q[2] - self.q[3] * self.q[3])) ) return clamp_angle(heading) @property def pitch(self): if SIMULATION: return 0 return degrees(-asin(2.0 * (self.q[1] * self.q[3] - self.q[0] * self.q[2]))) @property def roll(self): if SIMULATION: return 0 return degrees(atan2(2.0 * (self.q[0] * self.q[1] + self.q[2] * self.q[3]), self.q[0] * self.q[0] - self.q[1] * self.q[1] - self.q[2] * self.q[2] + self.q[3] * self.q[3])) def update_nomag(self, accel, gyro): # 3-tuples (x, y, z) for accel, gyro ax, ay, az = accel # Units G (but later normalised) gx, gy, gz = (radians(x) for x in gyro) # Units deg/s if self.start_time is None: <|code_end|> . Use current file imports: import os import asyncio import logging from ..wamp import ApplicationSession, rpc, subscribe from navio.lsm9ds1 import LSM9DS1 from ..config import config from math import sqrt, atan2, asin, degrees, radians from ..utils import micros, elapsed_micros, clamp_angle and context (classes, functions, or code) from other files: # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer # # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def micros(): # return time.perf_counter() * 1e6 # # def elapsed_micros(start_time_us): # return (time.perf_counter() * 1e6) - start_time_us # # def clamp_angle(deg): # """Rotate angle back to be within [0, 360] # """ # n_rotations = deg // 360 # deg -= 360 * n_rotations # return deg . Output only the next line.
self.start_time = micros() # First run
Next line prediction: <|code_start|> q3q3 = q3 * q3 q4q4 = q4 * q4 # Normalise accelerometer measurement norm = sqrt(ax * ax + ay * ay + az * az) if norm == 0: return # handle NaN norm = 1 / norm # use reciprocal for division ax *= norm ay *= norm az *= norm # Gradient decent algorithm corrective step s1 = _4q1 * q3q3 + _2q3 * ax + _4q1 * q2q2 - _2q2 * ay s2 = _4q2 * q4q4 - _2q4 * ax + 4 * q1q1 * q2 - _2q1 * ay - _4q2 + _8q2 * q2q2 + _8q2 * q3q3 + _4q2 * az s3 = 4 * q1q1 * q3 + _2q1 * ax + _4q3 * q4q4 - _2q4 * ay - _4q3 + _8q3 * q2q2 + _8q3 * q3q3 + _4q3 * az s4 = 4 * q2q2 * q4 - _2q2 * ax + 4 * q3q3 * q4 - _2q3 * ay norm = 1 / sqrt(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4) # normalise step magnitude s1 *= norm s2 *= norm s3 *= norm s4 *= norm # Compute rate of change of quaternion qDot1 = 0.5 * (-q2 * gx - q3 * gy - q4 * gz) - self.beta * s1 qDot2 = 0.5 * (q1 * gx + q3 * gz - q4 * gy) - self.beta * s2 qDot3 = 0.5 * (q1 * gy - q2 * gz + q4 * gx) - self.beta * s3 qDot4 = 0.5 * (q1 * gz + q2 * gy - q3 * gx) - self.beta * s4 # Integrate to yield quaternion <|code_end|> . Use current file imports: (import os import asyncio import logging from ..wamp import ApplicationSession, rpc, subscribe from navio.lsm9ds1 import LSM9DS1 from ..config import config from math import sqrt, atan2, asin, degrees, radians from ..utils import micros, elapsed_micros, clamp_angle) and context including class names, function names, or small code snippets from other files: # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer # # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def micros(): # return time.perf_counter() * 1e6 # # def elapsed_micros(start_time_us): # return (time.perf_counter() * 1e6) - start_time_us # # def clamp_angle(deg): # """Rotate angle back to be within [0, 360] # """ # n_rotations = deg // 360 # deg -= 360 * n_rotations # return deg . Output only the next line.
deltat = elapsed_micros(self.start_time) / 1e6
Next line prediction: <|code_start|> @rpc('ahrs.get_declination') def get_declination(self): return config.declination @rpc('ahrs.get_board_offset') def get_board_offset(self): return config.board_offset @rpc('ahrs.set_declination') def set_declination(self, val): self.declination = float(val) config.declination = self.declination config.save() @rpc('ahrs.set_board_offset') def set_board_offset(self, val): self.board_offset = float(val) config.board_offset = self.board_offset config.save() @subscribe('auv.update') def _simulate_heading(self, data): if SIMULATION: speed = data['turn_speed'] / 10 self._simulated_heading += speed @property def heading(self): if SIMULATION: heading = self.declination + self.board_offset + self._simulated_heading <|code_end|> . Use current file imports: (import os import asyncio import logging from ..wamp import ApplicationSession, rpc, subscribe from navio.lsm9ds1 import LSM9DS1 from ..config import config from math import sqrt, atan2, asin, degrees, radians from ..utils import micros, elapsed_micros, clamp_angle) and context including class names, function names, or small code snippets from other files: # Path: auv_control_pi/wamp.py # class ApplicationSession(AutobahnApplicationSession): # name = '' # # @classmethod # def rpc_methods(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('rpc_methods') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # rpc_methods = [method for method in methods if getattr(method, 'is_rpc', False)] # return {method.rpc_uri: method for method in rpc_methods} # # @classmethod # def rpc_uris(cls, instance=None): # return cls.rpc_methods(instance).keys() # # @classmethod # def subcribtion_handlers(cls, instance=None): # _cls = instance or cls # attrs = dir(_cls) # attrs.remove('subcribtion_handlers') # methods = [getattr(_cls, attr) for attr in attrs if callable(getattr(_cls, attr))] # handlers = [method for method in methods if getattr(method, 'is_subcription', False)] # return {method.topic: method for method in handlers} # # def onConnect(self): # logger.info('Connecting to {} as {}'.format(self.config.realm, self.name)) # self.join(realm=self.config.realm) # # async def onJoin(self, details): # logger.info('Joined realm as {}'.format(self.name)) # for rpc_uri, method in self.rpc_methods(self).items(): # logger.debug('Registering RPC: {}'.format(rpc_uri)) # await self.register(method, rpc_uri) # # for topic, handler in self.subcribtion_handlers(self).items(): # logger.debug('Subscribing To Topic: {}'.format(topic)) # await self.subscribe(handler, topic) # # loop = asyncio.get_event_loop() # loop.create_task(self.update()) # # def rpc(rpc_uri=None): # if rpc_uri is None: # raise ValueError('Must provide rpc_uri') # # def outer(fnc): # @wraps(fnc) # def inner(*args, **kwargs): # return fnc(*args, **kwargs) # inner.is_rpc = True # inner.rpc_uri = rpc_uri # return inner # return outer # # def subscribe(topic): # if topic is None: # raise ValueError('Must provide `topic `to subscribe to') # # def outer(fnc): # @wraps(fnc) # def inner(self, *args, **kwargs): # return fnc(self, *args, **kwargs) # inner.is_subcription = True # inner.topic = topic # return inner # return outer # # Path: auv_control_pi/config.py # # Path: auv_control_pi/utils.py # def micros(): # return time.perf_counter() * 1e6 # # def elapsed_micros(start_time_us): # return (time.perf_counter() * 1e6) - start_time_us # # def clamp_angle(deg): # """Rotate angle back to be within [0, 360] # """ # n_rotations = deg // 360 # deg -= 360 * n_rotations # return deg . Output only the next line.
return clamp_angle(heading)
Given the code snippet: <|code_start|> @pytest.fixture def sim(): starting_point = Point(50, 120) <|code_end|> , generate the next line using the imports in this file: import pytest from pygc import great_circle from ..simulator import Navitgator, GPS, Motor, AHRS from ..components.navigation import Point, distance_to_point and context (functions, classes, or occasionally code) from other files: # Path: auv_control_pi/simulator.py # class Navitgator: # # # target distance is the minimum distance we need to # # arrive at in order to consider ourselves "arrived" # # at the waypoint # TARGET_DISTANCE = 20 # meters # # def __init__(self, gps=None, # left_motor=None, right_motor=None, # update_period=1, current_location=None): # self._gps = GPS() # self._ahrs = AHRS() # self._left_motor = left_motor # self._right_motor = right_motor # self._running = False # self.target_waypoint = None # self._current_location = current_location or Point(lat=49.2827, lng=-123.1207) # # self.update_period = update_period # self.speed = 0 # [m/s] # self.arrived = False # self.waypoints = deque() # # def stop(self): # self._running = False # # def move_to_waypoint(self, waypoint): # self.arrived = False # self.target_waypoint = waypoint # self._ahrs.heading = heading_to_point(self._current_location, waypoint) # self.speed = 50 # # def start_trip(self, waypoints=None): # if waypoints: # self.waypoints = deque(waypoints) # self.move_to_waypoint(self.waypoints.popleft()) # # def pause_trip(self): # # push the current waypoint back on the stack # self.waypoints.appendleft(self.target_waypoint) # self.target_waypoint = None # # def _update(self): # """Update the current position and heading""" # # update current position based on speed # distance = self.speed * self.update_period # result = great_circle(distance=distance, # azimuth=self._ahrs.heading, # latitude=self._current_location.lat, # longitude=self._current_location.lng) # self._current_location = Point(result['latitude'], result['longitude']) # self._gps.lat = self._current_location.lat # self._gps.lng = self._current_location.lng # # if self.target_waypoint and not self.arrived: # # update compass heading if we have a target waypoint # self._ahrs.heading = heading_to_point(self._current_location, # self.target_waypoint) # # check if we have hit our target # if self.distance_to_target <= self.TARGET_DISTANCE: # try: # # if there are waypoints qued up keep going # self.move_to_waypoint(self.waypoints.popleft()) # except IndexError: # # otherwise we have arrived # self.arrived = True # self.speed = 0 # logger.info('Arrived at Waypoint({}, {})'.format(self.target_waypoint.lat, # self.target_waypoint.lng)) # # else: # # update heading and speed based on motor speeds # self.speed = (self._left_motor.speed + self._right_motor.speed) // 2 # self._ahrs.heading += ((self._left_motor.speed - self._right_motor.speed) / 10) # self._ahrs.heading = abs(self._ahrs.heading % 360) # # @property # def distance_to_target(self): # if self.target_waypoint: # return distance_to_point(self._current_location, self.target_waypoint) # else: # return None # # def run(self): # logger.info('Starting simulation') # self._running = True # while self._running: # self._update() # time.sleep(self.update_period) # # class GPS: # # def __init__(self): # self.lat = 49.2827 # self.lng = -123.1207 # # class Motor: # # def __init__(self, name): # self.name = name # self.speed = 0 # # def __repr__(self): # return 'Motor({})'.format(self.name) # # class AHRS: # # def __init__(self): # self.heading = 0 # # Path: auv_control_pi/components/navigation.py # SIMULATION = os.getenv('SIMULATION', False) # class Navitgator(ApplicationSession): # class Trip: # def __init__(self, *args, **kwargs): # def _update_ahrs(self, data): # def _update_gps(self, data): # def set_pid_values(self, kP, kI, kD, debounce=None): # def get_pid_values(self): # def get_target_waypoint_distance(self): # def set_target_waypoint_distance(self, target_waypoint_distance): # def move_to_waypoint(self, waypoint): # def start_trip(self, waypoints=None): # def resume_trip(self): # def stop(self): # async def update(self): # def _steer(self): # def distance_to_target(self): # def __init__(self, pk, waypoints): . Output only the next line.
return Navitgator(gps=GPS(),
Based on the snippet: <|code_start|> @pytest.fixture def sim(): starting_point = Point(50, 120) <|code_end|> , predict the immediate next line with the help of imports: import pytest from pygc import great_circle from ..simulator import Navitgator, GPS, Motor, AHRS from ..components.navigation import Point, distance_to_point and context (classes, functions, sometimes code) from other files: # Path: auv_control_pi/simulator.py # class Navitgator: # # # target distance is the minimum distance we need to # # arrive at in order to consider ourselves "arrived" # # at the waypoint # TARGET_DISTANCE = 20 # meters # # def __init__(self, gps=None, # left_motor=None, right_motor=None, # update_period=1, current_location=None): # self._gps = GPS() # self._ahrs = AHRS() # self._left_motor = left_motor # self._right_motor = right_motor # self._running = False # self.target_waypoint = None # self._current_location = current_location or Point(lat=49.2827, lng=-123.1207) # # self.update_period = update_period # self.speed = 0 # [m/s] # self.arrived = False # self.waypoints = deque() # # def stop(self): # self._running = False # # def move_to_waypoint(self, waypoint): # self.arrived = False # self.target_waypoint = waypoint # self._ahrs.heading = heading_to_point(self._current_location, waypoint) # self.speed = 50 # # def start_trip(self, waypoints=None): # if waypoints: # self.waypoints = deque(waypoints) # self.move_to_waypoint(self.waypoints.popleft()) # # def pause_trip(self): # # push the current waypoint back on the stack # self.waypoints.appendleft(self.target_waypoint) # self.target_waypoint = None # # def _update(self): # """Update the current position and heading""" # # update current position based on speed # distance = self.speed * self.update_period # result = great_circle(distance=distance, # azimuth=self._ahrs.heading, # latitude=self._current_location.lat, # longitude=self._current_location.lng) # self._current_location = Point(result['latitude'], result['longitude']) # self._gps.lat = self._current_location.lat # self._gps.lng = self._current_location.lng # # if self.target_waypoint and not self.arrived: # # update compass heading if we have a target waypoint # self._ahrs.heading = heading_to_point(self._current_location, # self.target_waypoint) # # check if we have hit our target # if self.distance_to_target <= self.TARGET_DISTANCE: # try: # # if there are waypoints qued up keep going # self.move_to_waypoint(self.waypoints.popleft()) # except IndexError: # # otherwise we have arrived # self.arrived = True # self.speed = 0 # logger.info('Arrived at Waypoint({}, {})'.format(self.target_waypoint.lat, # self.target_waypoint.lng)) # # else: # # update heading and speed based on motor speeds # self.speed = (self._left_motor.speed + self._right_motor.speed) // 2 # self._ahrs.heading += ((self._left_motor.speed - self._right_motor.speed) / 10) # self._ahrs.heading = abs(self._ahrs.heading % 360) # # @property # def distance_to_target(self): # if self.target_waypoint: # return distance_to_point(self._current_location, self.target_waypoint) # else: # return None # # def run(self): # logger.info('Starting simulation') # self._running = True # while self._running: # self._update() # time.sleep(self.update_period) # # class GPS: # # def __init__(self): # self.lat = 49.2827 # self.lng = -123.1207 # # class Motor: # # def __init__(self, name): # self.name = name # self.speed = 0 # # def __repr__(self): # return 'Motor({})'.format(self.name) # # class AHRS: # # def __init__(self): # self.heading = 0 # # Path: auv_control_pi/components/navigation.py # SIMULATION = os.getenv('SIMULATION', False) # class Navitgator(ApplicationSession): # class Trip: # def __init__(self, *args, **kwargs): # def _update_ahrs(self, data): # def _update_gps(self, data): # def set_pid_values(self, kP, kI, kD, debounce=None): # def get_pid_values(self): # def get_target_waypoint_distance(self): # def set_target_waypoint_distance(self, target_waypoint_distance): # def move_to_waypoint(self, waypoint): # def start_trip(self, waypoints=None): # def resume_trip(self): # def stop(self): # async def update(self): # def _steer(self): # def distance_to_target(self): # def __init__(self, pk, waypoints): . Output only the next line.
return Navitgator(gps=GPS(),
Continue the code snippet: <|code_start|>def sim(): starting_point = Point(50, 120) return Navitgator(gps=GPS(), current_location=starting_point, update_period=1) def test_simulator_move_to_waypoint(sim): waypoint = Point(49, 120) sim.move_to_waypoint(waypoint) assert sim._compass.heading == 180 def test_simulator_update(sim): # generate a waypoint 100 meters away due South heading = 140.0 distance = 100 result = great_circle(distance=distance, azimuth=heading, latitude=sim._current_location.lat, longitude=sim._current_location.lng) waypoint = Point(result['latitude'], result['longitude']) sim.move_to_waypoint(waypoint) sim.speed = 10 starting_point = sim._current_location # since we have an update period of 1s and speed of 10 m/s # after one update cycle we should have moved 10 meters # from our last point sim._update() <|code_end|> . Use current file imports: import pytest from pygc import great_circle from ..simulator import Navitgator, GPS, Motor, AHRS from ..components.navigation import Point, distance_to_point and context (classes, functions, or code) from other files: # Path: auv_control_pi/simulator.py # class Navitgator: # # # target distance is the minimum distance we need to # # arrive at in order to consider ourselves "arrived" # # at the waypoint # TARGET_DISTANCE = 20 # meters # # def __init__(self, gps=None, # left_motor=None, right_motor=None, # update_period=1, current_location=None): # self._gps = GPS() # self._ahrs = AHRS() # self._left_motor = left_motor # self._right_motor = right_motor # self._running = False # self.target_waypoint = None # self._current_location = current_location or Point(lat=49.2827, lng=-123.1207) # # self.update_period = update_period # self.speed = 0 # [m/s] # self.arrived = False # self.waypoints = deque() # # def stop(self): # self._running = False # # def move_to_waypoint(self, waypoint): # self.arrived = False # self.target_waypoint = waypoint # self._ahrs.heading = heading_to_point(self._current_location, waypoint) # self.speed = 50 # # def start_trip(self, waypoints=None): # if waypoints: # self.waypoints = deque(waypoints) # self.move_to_waypoint(self.waypoints.popleft()) # # def pause_trip(self): # # push the current waypoint back on the stack # self.waypoints.appendleft(self.target_waypoint) # self.target_waypoint = None # # def _update(self): # """Update the current position and heading""" # # update current position based on speed # distance = self.speed * self.update_period # result = great_circle(distance=distance, # azimuth=self._ahrs.heading, # latitude=self._current_location.lat, # longitude=self._current_location.lng) # self._current_location = Point(result['latitude'], result['longitude']) # self._gps.lat = self._current_location.lat # self._gps.lng = self._current_location.lng # # if self.target_waypoint and not self.arrived: # # update compass heading if we have a target waypoint # self._ahrs.heading = heading_to_point(self._current_location, # self.target_waypoint) # # check if we have hit our target # if self.distance_to_target <= self.TARGET_DISTANCE: # try: # # if there are waypoints qued up keep going # self.move_to_waypoint(self.waypoints.popleft()) # except IndexError: # # otherwise we have arrived # self.arrived = True # self.speed = 0 # logger.info('Arrived at Waypoint({}, {})'.format(self.target_waypoint.lat, # self.target_waypoint.lng)) # # else: # # update heading and speed based on motor speeds # self.speed = (self._left_motor.speed + self._right_motor.speed) // 2 # self._ahrs.heading += ((self._left_motor.speed - self._right_motor.speed) / 10) # self._ahrs.heading = abs(self._ahrs.heading % 360) # # @property # def distance_to_target(self): # if self.target_waypoint: # return distance_to_point(self._current_location, self.target_waypoint) # else: # return None # # def run(self): # logger.info('Starting simulation') # self._running = True # while self._running: # self._update() # time.sleep(self.update_period) # # class GPS: # # def __init__(self): # self.lat = 49.2827 # self.lng = -123.1207 # # class Motor: # # def __init__(self, name): # self.name = name # self.speed = 0 # # def __repr__(self): # return 'Motor({})'.format(self.name) # # class AHRS: # # def __init__(self): # self.heading = 0 # # Path: auv_control_pi/components/navigation.py # SIMULATION = os.getenv('SIMULATION', False) # class Navitgator(ApplicationSession): # class Trip: # def __init__(self, *args, **kwargs): # def _update_ahrs(self, data): # def _update_gps(self, data): # def set_pid_values(self, kP, kI, kD, debounce=None): # def get_pid_values(self): # def get_target_waypoint_distance(self): # def set_target_waypoint_distance(self, target_waypoint_distance): # def move_to_waypoint(self, waypoint): # def start_trip(self, waypoints=None): # def resume_trip(self): # def stop(self): # async def update(self): # def _steer(self): # def distance_to_target(self): # def __init__(self, pk, waypoints): . Output only the next line.
distance_moved = distance_to_point(starting_point, sim._current_location)
Predict the next line for this snippet: <|code_start|> logging.basicConfig(level=logging.INFO) class Command(BaseCommand): def handle(self, *args, **options): comp = Component( transports="ws://crossbar:8080/ws", realm="realm1", <|code_end|> with the help of current file imports: import logging from autobahn.asyncio.component import Component, run from django.core.management.base import BaseCommand from auv_control_pi.components.gps import GPSComponent and context from other files: # Path: auv_control_pi/components/gps.py # class GPSComponent(ApplicationSession): # name = 'gps' # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # # # initialize the gps # if PI and not SIMULATION: # self.lat = None # self.lng = None # self.gps = GPS() # elif SIMULATION: # self.gps = None # # Jericho Beach # self.lat = 49.273008 # self.lng = -123.179694 # # self.status = None # self.height_ellipsoid = None # self.height_sea = None # self.horizontal_accruacy = None # self.vertiacl_accruracy = None # self.throttle = 0 # self.heading = 0 # # @subscribe('auv.update') # def _update_auv(self, data): # self.throttle = data['throttle'] # # @subscribe('ahrs.update') # def _update_ahrs(self, data): # self.heading = data['heading'] # # @rpc('gps.get_position') # def get_position(self): # return self.lat, self.lng # # @rpc('gps.get_status') # def get_status(self): # return self.status # # def _parse_msg(self, msg): # """ # Update all local instance variables # """ # if msg.name() == "NAV_POSLLH": # self.lat = msg.Latitude / 10e6 # self.lng = msg.Longitude / 10e6 # self.height_ellipsoid = msg.height # self.height_sea = msg.hMSL # self.horizontal_accruacy = msg.hAcc # self.vertiacl_accruracy = msg.vAcc # # async def update(self): # while True: # if PI: # msg = self.gps.update() # self._parse_msg(msg) # elif SIMULATION: # if self.throttle > 0: # distance = self.throttle / 10 # new_point = point_at_distance(distance, self.heading, Point(self.lat, self.lng)) # self.lat = new_point.lat # self.lng = new_point.lng # # payload = { # 'lat': self.lat, # 'lng': self.lng, # 'height_sea': self.height_sea, # 'height_ellipsoid': self.height_ellipsoid, # 'horizontal_accruacy': self.horizontal_accruacy, # 'vertiacl_accruracy': self.vertiacl_accruracy, # } # # self.publish('gps.update', payload) # # if PI and self.lat is not None: # payload['lon'] = payload.pop('lng') # # GPSLog.objects.create(**payload) # # await asyncio.sleep(0.1) , which may contain function names, class names, or code. Output only the next line.
session_factory=GPSComponent,
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class TestIPDevice(base.TestCase): def setUp(self): super(TestIPDevice, self).setUp() self.device_name = 'test_device' <|code_end|> using the current file's imports: from unittest import mock from os_vif.internal.ip.windows import impl_netifaces as ip_lib from os_vif.tests.unit import base import netifaces and any relevant context from other files: # Path: os_vif/internal/ip/windows/impl_netifaces.py # LOG = logging.getLogger(__name__) # class Netifaces(ip_command.IpCommand): # def exists(self, device): # def set(self, device, check_exit_code=None, state=None, mtu=None, # address=None, promisc=None, master=None): # def add(self, device, dev_type, check_exit_code=None, peer=None, link=None, # vlan_id=None): # def delete(self, device, check_exit_code=None): # # Path: os_vif/tests/unit/base.py # class TestCase(testtools.TestCase): . Output only the next line.
self.mock_log = mock.patch.object(ip_lib, "LOG").start()
Predict the next line for this snippet: <|code_start|> address=None, promisc=None, master=None): check_exit_code = check_exit_code or [] with iproute.IPRoute() as ip: idx = self.lookup_interface(ip, device) args = {'index': idx} if state: args['state'] = state if mtu: args['mtu'] = mtu if address: args['address'] = address if promisc is not None: flags = ip.link('get', index=idx)[0]['flags'] args['flags'] = (utils.set_mask(flags, ifinfmsg.IFF_PROMISC) if promisc is True else utils.unset_mask(flags, ifinfmsg.IFF_PROMISC)) if master: args['master'] = self.lookup_interface(ip, master) if isinstance(check_exit_code, int): check_exit_code = [check_exit_code] return self._ip_link(ip, 'set', check_exit_code, **args) def lookup_interface(self, ip, link): # TODO(sean-k-mooney): remove try block after we raise # the min pyroute2 version above 0.5.12 try: idx = ip.link_lookup(ifname=link) except ipexc.NetlinkError: <|code_end|> with the help of current file imports: from oslo_log import log as logging from oslo_utils import excutils from pyroute2 import iproute from pyroute2.netlink import exceptions as ipexc from pyroute2.netlink.rtnl import ifinfmsg from os_vif import exception from os_vif.internal.ip import ip_command from os_vif import utils and context from other files: # Path: os_vif/exception.py # class ExceptionBase(Exception): # class LibraryNotInitialized(ExceptionBase): # class NoMatchingPlugin(ExceptionBase): # class NoMatchingPortProfileClass(ExceptionBase): # class NoSupportedPortProfileVersion(ExceptionBase): # class NoMatchingVIFClass(ExceptionBase): # class NoSupportedVIFVersion(ExceptionBase): # class PlugException(ExceptionBase): # class UnplugException(ExceptionBase): # class NetworkMissingPhysicalNetwork(ExceptionBase): # class NetworkInterfaceNotFound(ExceptionBase): # class NetworkInterfaceTypeNotDefined(ExceptionBase): # class ExternalImport(ExceptionBase): # class NotImplementedForOS(ExceptionBase): # def __init__(self, message=None, **kwargs): # def format_message(self): # # Path: os_vif/internal/ip/ip_command.py # class IpCommand(metaclass=abc.ABCMeta): # TYPE_VETH = 'veth' # TYPE_VLAN = 'vlan' # TYPE_BRIDGE = 'bridge' # def set(self, device, check_exit_code=None, state=None, mtu=None, # address=None, promisc=None, master=None): # def add(self, device, dev_type, check_exit_code=None, peer=None, link=None, # vlan_id=None, ageing=None): # def delete(self, device, check_exit_code=None): # def exists(self, device): # # Path: os_vif/utils.py # def set_mask(data, mask): # def unset_mask(data, mask, bit_size=32): , which may contain function names, class names, or code. Output only the next line.
raise exception.NetworkInterfaceNotFound(interface=link)
Given the following code snippet before the placeholder: <|code_start|> class PyRoute2(ip_command.IpCommand): def _ip_link(self, ip, command, check_exit_code, **kwargs): try: LOG.debug('pyroute2 command %(command)s, arguments %(args)s' % {'command': command, 'args': kwargs}) return ip.link(command, **kwargs) except ipexc.NetlinkError as e: with excutils.save_and_reraise_exception() as ctx: if e.code in check_exit_code: LOG.error('NetlinkError was raised, code %s, message: %s' % (e.code, str(e))) ctx.reraise = False def set(self, device, check_exit_code=None, state=None, mtu=None, address=None, promisc=None, master=None): check_exit_code = check_exit_code or [] with iproute.IPRoute() as ip: idx = self.lookup_interface(ip, device) args = {'index': idx} if state: args['state'] = state if mtu: args['mtu'] = mtu if address: args['address'] = address if promisc is not None: flags = ip.link('get', index=idx)[0]['flags'] <|code_end|> , predict the next line using imports from the current file: from oslo_log import log as logging from oslo_utils import excutils from pyroute2 import iproute from pyroute2.netlink import exceptions as ipexc from pyroute2.netlink.rtnl import ifinfmsg from os_vif import exception from os_vif.internal.ip import ip_command from os_vif import utils and context including class names, function names, and sometimes code from other files: # Path: os_vif/exception.py # class ExceptionBase(Exception): # class LibraryNotInitialized(ExceptionBase): # class NoMatchingPlugin(ExceptionBase): # class NoMatchingPortProfileClass(ExceptionBase): # class NoSupportedPortProfileVersion(ExceptionBase): # class NoMatchingVIFClass(ExceptionBase): # class NoSupportedVIFVersion(ExceptionBase): # class PlugException(ExceptionBase): # class UnplugException(ExceptionBase): # class NetworkMissingPhysicalNetwork(ExceptionBase): # class NetworkInterfaceNotFound(ExceptionBase): # class NetworkInterfaceTypeNotDefined(ExceptionBase): # class ExternalImport(ExceptionBase): # class NotImplementedForOS(ExceptionBase): # def __init__(self, message=None, **kwargs): # def format_message(self): # # Path: os_vif/internal/ip/ip_command.py # class IpCommand(metaclass=abc.ABCMeta): # TYPE_VETH = 'veth' # TYPE_VLAN = 'vlan' # TYPE_BRIDGE = 'bridge' # def set(self, device, check_exit_code=None, state=None, mtu=None, # address=None, promisc=None, master=None): # def add(self, device, dev_type, check_exit_code=None, peer=None, link=None, # vlan_id=None, ageing=None): # def delete(self, device, check_exit_code=None): # def exists(self, device): # # Path: os_vif/utils.py # def set_mask(data, mask): # def unset_mask(data, mask, bit_size=32): . Output only the next line.
args['flags'] = (utils.set_mask(flags, ifinfmsg.IFF_PROMISC)
Predict the next line after this snippet: <|code_start|> max_version=max_version) @base.VersionedObjectRegistry.register class HostPortProfileInfo(osv_base.VersionedObject, base.ComparableVersionedObject, osv_base.VersionedObjectPrintableMixin): """ Class describing a PortProfile class and its supported versions """ # Version 1.0: Initial version VERSION = "1.0" fields = { # object name of the subclass of os_vif.objects.vif.VIFPortProfileBase "profile_object_name": fields.StringField(), # String representing the earliest version of @name # that the plugin understands "min_version": fields.StringField(), # String representing the latest version of @name # that the plugin understands "max_version": fields.StringField(), } def get_common_version(self): return _get_common_version(self.profile_object_name, self.max_version, self.min_version, <|code_end|> using the current file's imports: from oslo_utils import versionutils from oslo_versionedobjects import base from oslo_versionedobjects import fields from os_vif import exception from os_vif.objects import base as osv_base and any relevant context from other files: # Path: os_vif/exception.py # class ExceptionBase(Exception): # class LibraryNotInitialized(ExceptionBase): # class NoMatchingPlugin(ExceptionBase): # class NoMatchingPortProfileClass(ExceptionBase): # class NoSupportedPortProfileVersion(ExceptionBase): # class NoMatchingVIFClass(ExceptionBase): # class NoSupportedVIFVersion(ExceptionBase): # class PlugException(ExceptionBase): # class UnplugException(ExceptionBase): # class NetworkMissingPhysicalNetwork(ExceptionBase): # class NetworkInterfaceNotFound(ExceptionBase): # class NetworkInterfaceTypeNotDefined(ExceptionBase): # class ExternalImport(ExceptionBase): # class NotImplementedForOS(ExceptionBase): # def __init__(self, message=None, **kwargs): # def format_message(self): # # Path: os_vif/objects/base.py # class VersionedObject(ovo_base.VersionedObject): # class VersionedObjectPrintableMixin(object): # OBJ_PROJECT_NAMESPACE = 'os_vif' # def __str__(self): . Output only the next line.
exception.NoMatchingPortProfileClass,
Continue the code snippet: <|code_start|># under the License. def _get_common_version(object_name, max_version, min_version, exc_notmatch, exc_notsupported): """Returns the accepted version from the loaded OVO registry""" reg = base.VersionedObjectRegistry.obj_classes() if object_name not in reg: raise exc_notmatch(name=object_name) gotvers = [] for regobj in reg[object_name]: gotvers.append(regobj.VERSION) got = versionutils.convert_version_to_tuple(regobj.VERSION) minwant = versionutils.convert_version_to_tuple(min_version) maxwant = versionutils.convert_version_to_tuple(max_version) if minwant <= got <= maxwant: return regobj.VERSION raise exc_notsupported(name=object_name, got_versions=",".join(gotvers), min_version=min_version, max_version=max_version) @base.VersionedObjectRegistry.register <|code_end|> . Use current file imports: from oslo_utils import versionutils from oslo_versionedobjects import base from oslo_versionedobjects import fields from os_vif import exception from os_vif.objects import base as osv_base and context (classes, functions, or code) from other files: # Path: os_vif/exception.py # class ExceptionBase(Exception): # class LibraryNotInitialized(ExceptionBase): # class NoMatchingPlugin(ExceptionBase): # class NoMatchingPortProfileClass(ExceptionBase): # class NoSupportedPortProfileVersion(ExceptionBase): # class NoMatchingVIFClass(ExceptionBase): # class NoSupportedVIFVersion(ExceptionBase): # class PlugException(ExceptionBase): # class UnplugException(ExceptionBase): # class NetworkMissingPhysicalNetwork(ExceptionBase): # class NetworkInterfaceNotFound(ExceptionBase): # class NetworkInterfaceTypeNotDefined(ExceptionBase): # class ExternalImport(ExceptionBase): # class NotImplementedForOS(ExceptionBase): # def __init__(self, message=None, **kwargs): # def format_message(self): # # Path: os_vif/objects/base.py # class VersionedObject(ovo_base.VersionedObject): # class VersionedObjectPrintableMixin(object): # OBJ_PROJECT_NAMESPACE = 'os_vif' # def __str__(self): . Output only the next line.
class HostPortProfileInfo(osv_base.VersionedObject,
Predict the next line for this snippet: <|code_start|> return False return True class _CatchTimeoutMetaclass(abc.ABCMeta): def __init__(cls, name, bases, dct): super(_CatchTimeoutMetaclass, cls).__init__(name, bases, dct) for name, method in inspect.getmembers( # NOTE(ihrachys): we should use isroutine because it will catch # both unbound methods (python2) and functions (python3) cls, predicate=inspect.isroutine): if name.startswith('test_'): setattr(cls, name, cls._catch_timeout(method)) @staticmethod def _catch_timeout(f): @functools.wraps(f) def func(self, *args, **kwargs): try: return f(self, *args, **kwargs) except eventlet.Timeout as e: self.fail('Execution of this test timed out: %s' % e) return func def setup_logging(component_name): """Sets up the logging options for a log with supplied name.""" logging.setup(cfg.CONF, component_name) LOG.info("Logging enabled!") LOG.info("%(prog)s version %(version)s", <|code_end|> with the help of current file imports: import abc import functools import inspect import os import sys import eventlet.timeout from os_vif import version as osvif_version from oslo_config import cfg from oslo_log import log as logging from oslo_utils import fileutils from oslotest import base and context from other files: # Path: os_vif/version.py , which may contain function names, class names, or code. Output only the next line.
{'prog': sys.argv[0], 'version': osvif_version.__version__})
Next line prediction: <|code_start|> class BaseOVS(object): def __init__(self, config): self.timeout = config.ovs_vsctl_timeout self.connection = config.ovsdb_connection self.interface = config.ovsdb_interface self._ovsdb = None # NOTE(sean-k-mooney): when using the native ovsdb bindings # creating an instance of the ovsdb api connects to the ovsdb # to initialize the library based on the schema version # of the ovsdb. To avoid that we lazy load the ovsdb # instance the first time we need it via a property. @property def ovsdb(self): if not self._ovsdb: self._ovsdb = ovsdb_api.get_instance(self) return self._ovsdb def _ovs_supports_mtu_requests(self): return self.ovsdb.has_table_column('Interface', 'mtu_request') def _set_mtu_request(self, dev, mtu): self.ovsdb.db_set('Interface', dev, ('mtu_request', mtu)).execute() def update_device_mtu(self, dev, mtu, interface_type=None): if not mtu: return if interface_type not in [ <|code_end|> . Use current file imports: (import sys from oslo_log import log as logging from vif_plug_ovs import constants from vif_plug_ovs import linux_net from vif_plug_ovs.ovsdb import api as ovsdb_api) and context including class names, function names, or small code snippets from other files: # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/ovsdb/api.py # def get_instance(context, iface_name=None): # def has_table_column(self, table, column): # class ImplAPI(metaclass=abc.ABCMeta): . Output only the next line.
constants.OVS_VHOSTUSER_INTERFACE_TYPE,
Using the snippet: <|code_start|> self._ovsdb = None # NOTE(sean-k-mooney): when using the native ovsdb bindings # creating an instance of the ovsdb api connects to the ovsdb # to initialize the library based on the schema version # of the ovsdb. To avoid that we lazy load the ovsdb # instance the first time we need it via a property. @property def ovsdb(self): if not self._ovsdb: self._ovsdb = ovsdb_api.get_instance(self) return self._ovsdb def _ovs_supports_mtu_requests(self): return self.ovsdb.has_table_column('Interface', 'mtu_request') def _set_mtu_request(self, dev, mtu): self.ovsdb.db_set('Interface', dev, ('mtu_request', mtu)).execute() def update_device_mtu(self, dev, mtu, interface_type=None): if not mtu: return if interface_type not in [ constants.OVS_VHOSTUSER_INTERFACE_TYPE, constants.OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE]: if sys.platform != constants.PLATFORM_WIN32: # Hyper-V with OVS does not support external programming of # virtual interface MTUs via netsh or other Windows tools. # When plugging an interface on Windows, we therefore skip # programming the MTU and fallback to DHCP advertisement. <|code_end|> , determine the next line of code. You have imports: import sys from oslo_log import log as logging from vif_plug_ovs import constants from vif_plug_ovs import linux_net from vif_plug_ovs.ovsdb import api as ovsdb_api and context (class names, function names, or code) available: # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/ovsdb/api.py # def get_instance(context, iface_name=None): # def has_table_column(self, table, column): # class ImplAPI(metaclass=abc.ABCMeta): . Output only the next line.
linux_net.set_device_mtu(dev, mtu)
Predict the next line after this snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. LOG = logging.getLogger(__name__) class BaseOVS(object): def __init__(self, config): self.timeout = config.ovs_vsctl_timeout self.connection = config.ovsdb_connection self.interface = config.ovsdb_interface self._ovsdb = None # NOTE(sean-k-mooney): when using the native ovsdb bindings # creating an instance of the ovsdb api connects to the ovsdb # to initialize the library based on the schema version # of the ovsdb. To avoid that we lazy load the ovsdb # instance the first time we need it via a property. @property def ovsdb(self): if not self._ovsdb: <|code_end|> using the current file's imports: import sys from oslo_log import log as logging from vif_plug_ovs import constants from vif_plug_ovs import linux_net from vif_plug_ovs.ovsdb import api as ovsdb_api and any relevant context from other files: # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/ovsdb/api.py # def get_instance(context, iface_name=None): # def has_table_column(self, table, column): # class ImplAPI(metaclass=abc.ABCMeta): . Output only the next line.
self._ovsdb = ovsdb_api.get_instance(self)
Given snippet: <|code_start|># Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Implements vlans, bridges, and iptables rules using linux utilities.""" LOG = logging.getLogger(__name__) _IPTABLES_MANAGER = None def _set_device_mtu(dev, mtu): """Set the device MTU.""" if mtu: <|code_end|> , continue by predicting the next line. Consider current file imports: import os from os_vif.internal.ip.api import ip as ip_lib from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_log import log as logging from vif_plug_linux_bridge import privsep and context: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_linux_bridge/privsep.py which might include code, classes, or functions. Output only the next line.
ip_lib.set(dev, mtu=mtu, check_exit_code=[0, 2, 254])
Based on the snippet: <|code_start|># License for the specific language governing permissions and limitations # under the License. """Implements vlans, bridges, and iptables rules using linux utilities.""" LOG = logging.getLogger(__name__) _IPTABLES_MANAGER = None def _set_device_mtu(dev, mtu): """Set the device MTU.""" if mtu: ip_lib.set(dev, mtu=mtu, check_exit_code=[0, 2, 254]) else: LOG.debug("MTU not set on %(interface_name)s interface", {'interface_name': dev}) def _ip_bridge_cmd(action, params, device): """Build commands to add/del ips to bridges/devices.""" cmd = ['ip', 'addr', action] cmd.extend(params) cmd.extend(['dev', device]) return cmd <|code_end|> , predict the immediate next line with the help of imports: import os from os_vif.internal.ip.api import ip as ip_lib from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_log import log as logging from vif_plug_linux_bridge import privsep and context (classes, functions, sometimes code) from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_linux_bridge/privsep.py . Output only the next line.
@privsep.vif_plug.entrypoint
Given the code snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. CONF = cfg.CONF class LinuxNetTest(testtools.TestCase): def setUp(self): super(LinuxNetTest, self).setUp() privsep.vif_plug.set_client_mode(False) lock_path = self.useFixture(fixtures.TempDir()).path self.fixture = self.useFixture( config_fixture.Config(lockutils.CONF)) self.fixture.config(lock_path=lock_path, group='oslo_concurrency') self.useFixture(log_fixture.get_logging_handle_error_fixture()) <|code_end|> , generate the next line using the imports in this file: from unittest import mock from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_config import cfg from oslo_config import fixture as config_fixture from oslo_log.fixture import logging_error as log_fixture from os_vif.internal.ip.api import ip as ip_lib from vif_plug_linux_bridge import linux_net from vif_plug_linux_bridge import privsep import fixtures import testtools and context (functions, classes, or occasionally code) from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_linux_bridge/linux_net.py # LOG = logging.getLogger(__name__) # _IPTABLES_MANAGER = None # _IPTABLES_MANAGER = iptables_mgr # def _set_device_mtu(dev, mtu): # def _ip_bridge_cmd(action, params, device): # def ensure_vlan_bridge(vlan_num, bridge, bridge_interface, # net_attrs=None, mac_address=None, # mtu=None): # def _ensure_vlan_privileged(vlan_num, bridge_interface, mac_address, mtu): # def ensure_bridge(bridge, interface, net_attrs=None, gateway=True, # filtering=True, mtu=None): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def _update_bridge_routes(interface, bridge): # def _ensure_bridge_privileged(bridge, interface, net_attrs, gateway, # filtering=True, mtu=None): # def _ensure_bridge_filtering(bridge, gateway): # def configure(iptables_mgr): # # Path: vif_plug_linux_bridge/privsep.py . Output only the next line.
@mock.patch.object(ip_lib, "set")
Given the code snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. CONF = cfg.CONF class LinuxNetTest(testtools.TestCase): def setUp(self): super(LinuxNetTest, self).setUp() privsep.vif_plug.set_client_mode(False) lock_path = self.useFixture(fixtures.TempDir()).path self.fixture = self.useFixture( config_fixture.Config(lockutils.CONF)) self.fixture.config(lock_path=lock_path, group='oslo_concurrency') self.useFixture(log_fixture.get_logging_handle_error_fixture()) @mock.patch.object(ip_lib, "set") def test_set_device_mtu(self, mock_ip_set): <|code_end|> , generate the next line using the imports in this file: from unittest import mock from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_config import cfg from oslo_config import fixture as config_fixture from oslo_log.fixture import logging_error as log_fixture from os_vif.internal.ip.api import ip as ip_lib from vif_plug_linux_bridge import linux_net from vif_plug_linux_bridge import privsep import fixtures import testtools and context (functions, classes, or occasionally code) from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_linux_bridge/linux_net.py # LOG = logging.getLogger(__name__) # _IPTABLES_MANAGER = None # _IPTABLES_MANAGER = iptables_mgr # def _set_device_mtu(dev, mtu): # def _ip_bridge_cmd(action, params, device): # def ensure_vlan_bridge(vlan_num, bridge, bridge_interface, # net_attrs=None, mac_address=None, # mtu=None): # def _ensure_vlan_privileged(vlan_num, bridge_interface, mac_address, mtu): # def ensure_bridge(bridge, interface, net_attrs=None, gateway=True, # filtering=True, mtu=None): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def _update_bridge_routes(interface, bridge): # def _ensure_bridge_privileged(bridge, interface, net_attrs, gateway, # filtering=True, mtu=None): # def _ensure_bridge_filtering(bridge, gateway): # def configure(iptables_mgr): # # Path: vif_plug_linux_bridge/privsep.py . Output only the next line.
linux_net._set_device_mtu(dev='fakedev', mtu=1500)
Given the following code snippet before the placeholder: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. CONF = cfg.CONF class LinuxNetTest(testtools.TestCase): def setUp(self): super(LinuxNetTest, self).setUp() <|code_end|> , predict the next line using imports from the current file: from unittest import mock from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_config import cfg from oslo_config import fixture as config_fixture from oslo_log.fixture import logging_error as log_fixture from os_vif.internal.ip.api import ip as ip_lib from vif_plug_linux_bridge import linux_net from vif_plug_linux_bridge import privsep import fixtures import testtools and context including class names, function names, and sometimes code from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_linux_bridge/linux_net.py # LOG = logging.getLogger(__name__) # _IPTABLES_MANAGER = None # _IPTABLES_MANAGER = iptables_mgr # def _set_device_mtu(dev, mtu): # def _ip_bridge_cmd(action, params, device): # def ensure_vlan_bridge(vlan_num, bridge, bridge_interface, # net_attrs=None, mac_address=None, # mtu=None): # def _ensure_vlan_privileged(vlan_num, bridge_interface, mac_address, mtu): # def ensure_bridge(bridge, interface, net_attrs=None, gateway=True, # filtering=True, mtu=None): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def _update_bridge_routes(interface, bridge): # def _ensure_bridge_privileged(bridge, interface, net_attrs, gateway, # filtering=True, mtu=None): # def _ensure_bridge_filtering(bridge, gateway): # def configure(iptables_mgr): # # Path: vif_plug_linux_bridge/privsep.py . Output only the next line.
privsep.vif_plug.set_client_mode(False)
Here is a snippet: <|code_start|> Despite the confusing name, direct-style VIFs utilize macvtap which is a device driver that inserts a software layer between a guest and an SR-IOV Virtual Function (VF). Contrast this with :class:`~os_vif.objects.vif.VIFHostDevice`, which allows the guest to directly connect to the VF. The connection to the device may operate in one of a number of different modes, :term:`VEPA` (either :term:`802.1Qbg` or :term:`802.1Qbh`), passthrough (exclusive assignment of the host NIC) or bridge (ethernet layer bridging of traffic). The passthrough mode would be used when there is a network device which needs to have a MAC address or VLAN configuration. For passthrough of network devices without MAC/VLAN configuration, :class:`~os_vif.objects.vif.VIFHostDevice` should be used instead. For libvirt drivers, this maps to type='direct' """ # Version 1.0: Initial release VERSION = '1.0' fields = { #: Name of the device to create. 'vif_name': fields.StringField(), #: The PCI address of the host device. 'dev_address': fields.PCIAddressField(), #: Port connection mode. <|code_end|> . Write the next line using the current file imports: from debtcollector import removals from oslo_utils import versionutils from oslo_versionedobjects import base from oslo_versionedobjects import fields from os_vif.objects import base as osv_base from os_vif.objects import fields as osv_fields and context from other files: # Path: os_vif/objects/base.py # class VersionedObject(ovo_base.VersionedObject): # class VersionedObjectPrintableMixin(object): # OBJ_PROJECT_NAMESPACE = 'os_vif' # def __str__(self): # # Path: os_vif/objects/fields.py # class VIFDirectMode(fields.Enum): # class VIFDirectModeField(fields.BaseEnumField): # class VIFVHostUserMode(fields.Enum): # class VIFVHostUserModeField(fields.BaseEnumField): # class ListOfIPAddressField(fields.AutoTypedField): # class VIFHostDeviceDevType(fields.Enum): # class VIFHostDeviceDevTypeField(fields.BaseEnumField): # VEPA = 'vepa' # PASSTHROUGH = 'passthrough' # BRIDGE = 'bridge' # ALL = (VEPA, PASSTHROUGH, BRIDGE) # AUTO_TYPE = VIFDirectMode() # CLIENT = "client" # SERVER = "server" # ALL = (CLIENT, SERVER) # AUTO_TYPE = VIFVHostUserMode() # AUTO_TYPE = fields.List(fields.IPAddress()) # ETHERNET = 'ethernet' # GENERIC = 'generic' # ALL = (ETHERNET, GENERIC) # AUTO_TYPE = VIFHostDeviceDevType() # def __init__(self): # def __init__(self): # def __init__(self): , which may include functions, classes, or code. Output only the next line.
'mode': osv_fields.VIFDirectModeField(),
Here is a snippet: <|code_start|>CONF = cfg.CONF class BaseOVSTest(testtools.TestCase): def setUp(self): super(BaseOVSTest, self).setUp() test_vif_plug_ovs_group = cfg.OptGroup('test_vif_plug_ovs') CONF.register_group(test_vif_plug_ovs_group) CONF.register_opt(cfg.IntOpt('ovs_vsctl_timeout', default=1500), test_vif_plug_ovs_group) CONF.register_opt(cfg.StrOpt('ovsdb_interface', default='vsctl'), test_vif_plug_ovs_group) CONF.register_opt(cfg.StrOpt('ovsdb_connection', default=None), test_vif_plug_ovs_group) self.br = ovsdb_lib.BaseOVS(cfg.CONF.test_vif_plug_ovs) self.mock_db_set = mock.patch.object(self.br.ovsdb, 'db_set').start() self.mock_del_port = mock.patch.object(self.br.ovsdb, 'del_port').start() self.mock_add_port = mock.patch.object(self.br.ovsdb, 'add_port').start() self.mock_add_br = mock.patch.object(self.br.ovsdb, 'add_br').start() self.mock_transaction = mock.patch.object(self.br.ovsdb, 'transaction').start() def test__set_mtu_request(self): self.br._set_mtu_request('device', 1500) calls = [mock.call('Interface', 'device', ('mtu_request', 1500))] self.mock_db_set.assert_has_calls(calls) <|code_end|> . Write the next line using the current file imports: from unittest import mock from oslo_concurrency import processutils from oslo_config import cfg from oslo_utils import uuidutils from vif_plug_ovs import constants from vif_plug_ovs import linux_net from vif_plug_ovs.ovsdb import ovsdb_lib import testtools and context from other files: # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/ovsdb/ovsdb_lib.py # LOG = logging.getLogger(__name__) # class BaseOVS(object): # def __init__(self, config): # def ovsdb(self): # def _ovs_supports_mtu_requests(self): # def _set_mtu_request(self, dev, mtu): # def update_device_mtu(self, dev, mtu, interface_type=None): # def ensure_ovs_bridge(self, bridge, datapath_type): # def delete_ovs_bridge(self, bridge): # def create_patch_port_pair( # self, port_bridge, port_bridge_port, int_bridge, int_bridge_port, # iface_id, mac, instance_id, tag=None # ): # def create_ovs_vif_port( # self, bridge, dev, iface_id, mac, instance_id, # mtu=None, interface_type=None, vhost_server_path=None, # tag=None, pf_pci=None, vf_num=None, set_ids=True # ): # def update_ovs_vif_port(self, dev, mtu=None, interface_type=None): # def delete_ovs_vif_port(self, bridge, dev, delete_netdev=True): , which may include functions, classes, or code. Output only the next line.
@mock.patch('sys.platform', constants.PLATFORM_LINUX)
Predict the next line for this snippet: <|code_start|> class BaseOVSTest(testtools.TestCase): def setUp(self): super(BaseOVSTest, self).setUp() test_vif_plug_ovs_group = cfg.OptGroup('test_vif_plug_ovs') CONF.register_group(test_vif_plug_ovs_group) CONF.register_opt(cfg.IntOpt('ovs_vsctl_timeout', default=1500), test_vif_plug_ovs_group) CONF.register_opt(cfg.StrOpt('ovsdb_interface', default='vsctl'), test_vif_plug_ovs_group) CONF.register_opt(cfg.StrOpt('ovsdb_connection', default=None), test_vif_plug_ovs_group) self.br = ovsdb_lib.BaseOVS(cfg.CONF.test_vif_plug_ovs) self.mock_db_set = mock.patch.object(self.br.ovsdb, 'db_set').start() self.mock_del_port = mock.patch.object(self.br.ovsdb, 'del_port').start() self.mock_add_port = mock.patch.object(self.br.ovsdb, 'add_port').start() self.mock_add_br = mock.patch.object(self.br.ovsdb, 'add_br').start() self.mock_transaction = mock.patch.object(self.br.ovsdb, 'transaction').start() def test__set_mtu_request(self): self.br._set_mtu_request('device', 1500) calls = [mock.call('Interface', 'device', ('mtu_request', 1500))] self.mock_db_set.assert_has_calls(calls) @mock.patch('sys.platform', constants.PLATFORM_LINUX) <|code_end|> with the help of current file imports: from unittest import mock from oslo_concurrency import processutils from oslo_config import cfg from oslo_utils import uuidutils from vif_plug_ovs import constants from vif_plug_ovs import linux_net from vif_plug_ovs.ovsdb import ovsdb_lib import testtools and context from other files: # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/ovsdb/ovsdb_lib.py # LOG = logging.getLogger(__name__) # class BaseOVS(object): # def __init__(self, config): # def ovsdb(self): # def _ovs_supports_mtu_requests(self): # def _set_mtu_request(self, dev, mtu): # def update_device_mtu(self, dev, mtu, interface_type=None): # def ensure_ovs_bridge(self, bridge, datapath_type): # def delete_ovs_bridge(self, bridge): # def create_patch_port_pair( # self, port_bridge, port_bridge_port, int_bridge, int_bridge_port, # iface_id, mac, instance_id, tag=None # ): # def create_ovs_vif_port( # self, bridge, dev, iface_id, mac, instance_id, # mtu=None, interface_type=None, vhost_server_path=None, # tag=None, pf_pci=None, vf_num=None, set_ids=True # ): # def update_ovs_vif_port(self, dev, mtu=None, interface_type=None): # def delete_ovs_vif_port(self, bridge, dev, delete_netdev=True): , which may contain function names, class names, or code. Output only the next line.
@mock.patch.object(linux_net, 'set_device_mtu')
Given the code snippet: <|code_start|># a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. CONF = cfg.CONF class BaseOVSTest(testtools.TestCase): def setUp(self): super(BaseOVSTest, self).setUp() test_vif_plug_ovs_group = cfg.OptGroup('test_vif_plug_ovs') CONF.register_group(test_vif_plug_ovs_group) CONF.register_opt(cfg.IntOpt('ovs_vsctl_timeout', default=1500), test_vif_plug_ovs_group) CONF.register_opt(cfg.StrOpt('ovsdb_interface', default='vsctl'), test_vif_plug_ovs_group) CONF.register_opt(cfg.StrOpt('ovsdb_connection', default=None), test_vif_plug_ovs_group) <|code_end|> , generate the next line using the imports in this file: from unittest import mock from oslo_concurrency import processutils from oslo_config import cfg from oslo_utils import uuidutils from vif_plug_ovs import constants from vif_plug_ovs import linux_net from vif_plug_ovs.ovsdb import ovsdb_lib import testtools and context (functions, classes, or occasionally code) from other files: # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/ovsdb/ovsdb_lib.py # LOG = logging.getLogger(__name__) # class BaseOVS(object): # def __init__(self, config): # def ovsdb(self): # def _ovs_supports_mtu_requests(self): # def _set_mtu_request(self, dev, mtu): # def update_device_mtu(self, dev, mtu, interface_type=None): # def ensure_ovs_bridge(self, bridge, datapath_type): # def delete_ovs_bridge(self, bridge): # def create_patch_port_pair( # self, port_bridge, port_bridge_port, int_bridge, int_bridge_port, # iface_id, mac, instance_id, tag=None # ): # def create_ovs_vif_port( # self, bridge, dev, iface_id, mac, instance_id, # mtu=None, interface_type=None, vhost_server_path=None, # tag=None, pf_pci=None, vf_num=None, set_ids=True # ): # def update_ovs_vif_port(self, dev, mtu=None, interface_type=None): # def delete_ovs_vif_port(self, bridge, dev, delete_netdev=True): . Output only the next line.
self.br = ovsdb_lib.BaseOVS(cfg.CONF.test_vif_plug_ovs)
Based on the snippet: <|code_start|> def show_state(self, device): regex = re.compile(r".*state (?P<state>\w+)") match = regex.match(self.show_device(device)[0]) if match is None: return return match.group('state') def show_promisc(self, device): regex = re.compile(r".*(PROMISC)") match = regex.match(self.show_device(device)[0]) return True if match else False def show_mac(self, device): exp = r".*link/ether (?P<mac>([0-9A-Fa-f]{2}[:]){5}[0-9A-Fa-f]{2})" regex = re.compile(exp) match = regex.match(self.show_device(device)[1]) if match is None: return return match.group('mac') def show_mtu(self, device): regex = re.compile(r".*mtu (?P<mtu>\d+)") match = regex.match(self.show_device(device)[0]) if match is None: return return int(match.group('mtu')) @privsep.os_vif_pctxt.entrypoint def _ip_cmd_set(*args, **kwargs): <|code_end|> , predict the immediate next line with the help of imports: import os import re from oslo_concurrency import processutils from oslo_utils import excutils from os_vif.internal.ip.api import ip as ip_lib from os_vif.tests.functional import base from os_vif.tests.functional import privsep and context (classes, functions, sometimes code) from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: os_vif/tests/functional/base.py # CONF = cfg.CONF # LOG = logging.getLogger(__name__) # DEFAULT_LOG_DIR = os.path.join(_get_test_log_path(), 'osvif-functional-logs') # COMPONENT_NAME = 'os_vif' # PRIVILEGED_GROUP = 'os_vif_privileged' # def _get_test_log_path(): # def wait_until_true(predicate, timeout=15, sleep=1): # def __init__(cls, name, bases, dct): # def _catch_timeout(f): # def func(self, *args, **kwargs): # def setup_logging(component_name): # def sanitize_log_path(path): # def setUp(self): # def flags(self, **kw): # class _CatchTimeoutMetaclass(abc.ABCMeta): # class BaseFunctionalTestCase(base.BaseTestCase, # metaclass=_CatchTimeoutMetaclass): # # Path: os_vif/tests/functional/privsep.py . Output only the next line.
ip_lib.set(*args, **kwargs)
Here is a snippet: <|code_start|> return match.group('mac') def show_mtu(self, device): regex = re.compile(r".*mtu (?P<mtu>\d+)") match = regex.match(self.show_device(device)[0]) if match is None: return return int(match.group('mtu')) @privsep.os_vif_pctxt.entrypoint def _ip_cmd_set(*args, **kwargs): ip_lib.set(*args, **kwargs) @privsep.os_vif_pctxt.entrypoint def _ip_cmd_add(*args, **kwargs): ip_lib.add(*args, **kwargs) @privsep.os_vif_pctxt.entrypoint def _ip_cmd_delete(*args, **kwargs): ip_lib.delete(*args, **kwargs) @privsep.os_vif_pctxt.entrypoint def _ip_cmd_exists(*args, **kwargs): return ip_lib.exists(*args, **kwargs) <|code_end|> . Write the next line using the current file imports: import os import re from oslo_concurrency import processutils from oslo_utils import excutils from os_vif.internal.ip.api import ip as ip_lib from os_vif.tests.functional import base from os_vif.tests.functional import privsep and context from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: os_vif/tests/functional/base.py # CONF = cfg.CONF # LOG = logging.getLogger(__name__) # DEFAULT_LOG_DIR = os.path.join(_get_test_log_path(), 'osvif-functional-logs') # COMPONENT_NAME = 'os_vif' # PRIVILEGED_GROUP = 'os_vif_privileged' # def _get_test_log_path(): # def wait_until_true(predicate, timeout=15, sleep=1): # def __init__(cls, name, bases, dct): # def _catch_timeout(f): # def func(self, *args, **kwargs): # def setup_logging(component_name): # def sanitize_log_path(path): # def setUp(self): # def flags(self, **kw): # class _CatchTimeoutMetaclass(abc.ABCMeta): # class BaseFunctionalTestCase(base.BaseTestCase, # metaclass=_CatchTimeoutMetaclass): # # Path: os_vif/tests/functional/privsep.py , which may include functions, classes, or code. Output only the next line.
class TestIpCommand(ShellIpCommands, base.BaseFunctionalTestCase):
Predict the next line for this snippet: <|code_start|> # phys_port_name only contains the VF number INT_RE = re.compile(r"^(\d+)$") # phys_port_name contains VF## or vf## VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # phys_port_name contains PF## or pf## PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # bus_info (bdf) contains <bus>:<dev>.<func> PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # phys_port_name contains p## UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) _SRIOV_TOTALVFS = "sriov_totalvfs" NIC_NAME_LEN = 14 def _update_device_mtu(dev, mtu): if not mtu: return if sys.platform != constants.PLATFORM_WIN32: # Hyper-V with OVS does not support external programming of # virtual interface MTUs via netsh or other Windows tools. # When plugging an interface on Windows, we therefore skip # programming the MTU and fallback to DHCP advertisement. set_device_mtu(dev, mtu) @privsep.vif_plug.entrypoint def delete_net_dev(dev): """Delete a network device only if it exists.""" <|code_end|> with the help of current file imports: import glob import os import re import sys from os_vif.internal.ip.api import ip as ip_lib from oslo_concurrency import processutils from oslo_log import log as logging from oslo_utils import excutils from vif_plug_ovs import constants from vif_plug_ovs import exception from vif_plug_ovs import privsep and context from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/exception.py # class AgentError(osv_exception.ExceptionBase): # class MissingPortProfile(osv_exception.ExceptionBase): # class WrongPortProfile(osv_exception.ExceptionBase): # class RepresentorNotFound(osv_exception.ExceptionBase): # class PciDeviceNotFoundById(osv_exception.ExceptionBase): # # Path: vif_plug_ovs/privsep.py , which may contain function names, class names, or code. Output only the next line.
if ip_lib.exists(dev):
Here is a snippet: <|code_start|># License for the specific language governing permissions and limitations # under the License. """Implements vlans, bridges using linux utilities.""" LOG = logging.getLogger(__name__) VIRTFN_RE = re.compile(r"virtfn(\d+)") # phys_port_name only contains the VF number INT_RE = re.compile(r"^(\d+)$") # phys_port_name contains VF## or vf## VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # phys_port_name contains PF## or pf## PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # bus_info (bdf) contains <bus>:<dev>.<func> PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # phys_port_name contains p## UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) _SRIOV_TOTALVFS = "sriov_totalvfs" NIC_NAME_LEN = 14 def _update_device_mtu(dev, mtu): if not mtu: return <|code_end|> . Write the next line using the current file imports: import glob import os import re import sys from os_vif.internal.ip.api import ip as ip_lib from oslo_concurrency import processutils from oslo_log import log as logging from oslo_utils import excutils from vif_plug_ovs import constants from vif_plug_ovs import exception from vif_plug_ovs import privsep and context from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/exception.py # class AgentError(osv_exception.ExceptionBase): # class MissingPortProfile(osv_exception.ExceptionBase): # class WrongPortProfile(osv_exception.ExceptionBase): # class RepresentorNotFound(osv_exception.ExceptionBase): # class PciDeviceNotFoundById(osv_exception.ExceptionBase): # # Path: vif_plug_ovs/privsep.py , which may include functions, classes, or code. Output only the next line.
if sys.platform != constants.PLATFORM_WIN32:
Given snippet: <|code_start|> return None, False def _get_pf_func(pf_ifname): """Gets PF function number using pf_ifname and returns function number or None. """ address_str, pf = get_function_by_ifname(pf_ifname) if not address_str: return None match = PF_FUNC_RE.search(address_str) if match: return match.group(1) return None def get_representor_port(pf_ifname, vf_num): """Get the representor netdevice which is corresponding to the VF. This method gets PF interface name and number of VF. It iterates over all the interfaces under the PF location and looks for interface that has the VF number in the phys_port_name. That interface is the representor for the requested VF. """ pf_sw_id = None try: pf_sw_id = _get_phys_switch_id(pf_ifname) except (OSError, IOError): <|code_end|> , continue by predicting the next line. Consider current file imports: import glob import os import re import sys from os_vif.internal.ip.api import ip as ip_lib from oslo_concurrency import processutils from oslo_log import log as logging from oslo_utils import excutils from vif_plug_ovs import constants from vif_plug_ovs import exception from vif_plug_ovs import privsep and context: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/exception.py # class AgentError(osv_exception.ExceptionBase): # class MissingPortProfile(osv_exception.ExceptionBase): # class WrongPortProfile(osv_exception.ExceptionBase): # class RepresentorNotFound(osv_exception.ExceptionBase): # class PciDeviceNotFoundById(osv_exception.ExceptionBase): # # Path: vif_plug_ovs/privsep.py which might include code, classes, or functions. Output only the next line.
raise exception.RepresentorNotFound(ifname=pf_ifname, vf_num=vf_num)
Given the following code snippet before the placeholder: <|code_start|>LOG = logging.getLogger(__name__) VIRTFN_RE = re.compile(r"virtfn(\d+)") # phys_port_name only contains the VF number INT_RE = re.compile(r"^(\d+)$") # phys_port_name contains VF## or vf## VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # phys_port_name contains PF## or pf## PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # bus_info (bdf) contains <bus>:<dev>.<func> PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # phys_port_name contains p## UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) _SRIOV_TOTALVFS = "sriov_totalvfs" NIC_NAME_LEN = 14 def _update_device_mtu(dev, mtu): if not mtu: return if sys.platform != constants.PLATFORM_WIN32: # Hyper-V with OVS does not support external programming of # virtual interface MTUs via netsh or other Windows tools. # When plugging an interface on Windows, we therefore skip # programming the MTU and fallback to DHCP advertisement. set_device_mtu(dev, mtu) <|code_end|> , predict the next line using imports from the current file: import glob import os import re import sys from os_vif.internal.ip.api import ip as ip_lib from oslo_concurrency import processutils from oslo_log import log as logging from oslo_utils import excutils from vif_plug_ovs import constants from vif_plug_ovs import exception from vif_plug_ovs import privsep and context including class names, function names, and sometimes code from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_ovs/constants.py # PLUGIN_NAME = 'ovs' # OVS_VHOSTUSER_INTERFACE_TYPE = 'dpdkvhostuser' # OVS_VHOSTUSER_CLIENT_INTERFACE_TYPE = 'dpdkvhostuserclient' # OVS_VHOSTUSER_PREFIX = 'vhu' # OVS_DATAPATH_SYSTEM = 'system' # OVS_DATAPATH_NETDEV = 'netdev' # PLATFORM_LINUX = 'linux2' # PLATFORM_WIN32 = 'win32' # OVS_DPDK_INTERFACE_TYPE = 'dpdk' # DEAD_VLAN = 4095 # # Path: vif_plug_ovs/exception.py # class AgentError(osv_exception.ExceptionBase): # class MissingPortProfile(osv_exception.ExceptionBase): # class WrongPortProfile(osv_exception.ExceptionBase): # class RepresentorNotFound(osv_exception.ExceptionBase): # class PciDeviceNotFoundById(osv_exception.ExceptionBase): # # Path: vif_plug_ovs/privsep.py . Output only the next line.
@privsep.vif_plug.entrypoint
Using the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class ExceptionBase(Exception): """Base Exception To correctly use this class, inherit from it and define a 'msg_fmt' property. That msg_fmt will get printf'd with the keyword arguments provided to the constructor. """ <|code_end|> , determine the next line of code. You have imports: from os_vif.i18n import _ and context (class names, function names, or code) available: # Path: os_vif/i18n.py # DOMAIN = 'os_vif' # def translate(value, user_locale): # def get_available_languages(): . Output only the next line.
msg_fmt = _("An unknown exception occurred.")
Based on the snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. REQUIRED_TABLES = ('Interface', 'Port', 'Bridge', 'Open_vSwitch') def idl_factory(config): conn = config.connection schema_name = 'Open_vSwitch' helper = idlutils.get_schema_helper(conn, schema_name) for table in REQUIRED_TABLES: helper.register_table(table) return idl.Idl(conn, helper) def api_factory(config): conn = connection.Connection( idl=idl_factory(config), timeout=config.timeout) return NeutronOvsdbIdl(conn) <|code_end|> , predict the immediate next line with the help of imports: import functools import socket from ovs.db import idl from ovs import socket_util from ovs import stream from ovsdbapp.backend.ovs_idl import connection from ovsdbapp.backend.ovs_idl import idlutils from ovsdbapp.backend.ovs_idl import vlog from ovsdbapp.schema.open_vswitch import impl_idl from vif_plug_ovs.ovsdb import api and context (classes, functions, sometimes code) from other files: # Path: vif_plug_ovs/ovsdb/api.py # def get_instance(context, iface_name=None): # def has_table_column(self, table, column): # class ImplAPI(metaclass=abc.ABCMeta): . Output only the next line.
class NeutronOvsdbIdl(impl_idl.OvsdbIdl, api.ImplAPI):
Given snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. @base.VersionedObjectRegistry.register class FixedIP(osv_base.VersionedObject): """Represents a fixed IP.""" # Version 1.0: Initial version VERSION = '1.0' fields = { 'address': fields.IPAddressField(), <|code_end|> , continue by predicting the next line. Consider current file imports: from oslo_versionedobjects import base from oslo_versionedobjects import fields from os_vif.objects import base as osv_base from os_vif.objects import fields as osv_fields and context: # Path: os_vif/objects/base.py # class VersionedObject(ovo_base.VersionedObject): # class VersionedObjectPrintableMixin(object): # OBJ_PROJECT_NAMESPACE = 'os_vif' # def __str__(self): # # Path: os_vif/objects/fields.py # class VIFDirectMode(fields.Enum): # class VIFDirectModeField(fields.BaseEnumField): # class VIFVHostUserMode(fields.Enum): # class VIFVHostUserModeField(fields.BaseEnumField): # class ListOfIPAddressField(fields.AutoTypedField): # class VIFHostDeviceDevType(fields.Enum): # class VIFHostDeviceDevTypeField(fields.BaseEnumField): # VEPA = 'vepa' # PASSTHROUGH = 'passthrough' # BRIDGE = 'bridge' # ALL = (VEPA, PASSTHROUGH, BRIDGE) # AUTO_TYPE = VIFDirectMode() # CLIENT = "client" # SERVER = "server" # ALL = (CLIENT, SERVER) # AUTO_TYPE = VIFVHostUserMode() # AUTO_TYPE = fields.List(fields.IPAddress()) # ETHERNET = 'ethernet' # GENERIC = 'generic' # ALL = (ETHERNET, GENERIC) # AUTO_TYPE = VIFHostDeviceDevType() # def __init__(self): # def __init__(self): # def __init__(self): which might include code, classes, or functions. Output only the next line.
'floating_ips': osv_fields.ListOfIPAddressField(),
Predict the next line for this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class LinuxNetTest(testtools.TestCase): def setUp(self): super(LinuxNetTest, self).setUp() privsep.vif_plug.set_client_mode(False) @mock.patch.object(linux_net, "_arp_filtering") @mock.patch.object(linux_net, "set_interface_state") @mock.patch.object(linux_net, "_disable_ipv6") <|code_end|> with the help of current file imports: import glob import os.path import testtools from unittest import mock from os_vif.internal.ip.api import ip as ip_lib from vif_plug_ovs import exception from vif_plug_ovs import linux_net from vif_plug_ovs import privsep and context from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_ovs/exception.py # class AgentError(osv_exception.ExceptionBase): # class MissingPortProfile(osv_exception.ExceptionBase): # class WrongPortProfile(osv_exception.ExceptionBase): # class RepresentorNotFound(osv_exception.ExceptionBase): # class PciDeviceNotFoundById(osv_exception.ExceptionBase): # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/privsep.py , which may contain function names, class names, or code. Output only the next line.
@mock.patch.object(ip_lib, "add")
Based on the snippet: <|code_start|> @mock.patch.object(linux_net, "_get_phys_switch_id") def test_get_representor_port_2_pfs( self, mock__get_phys_switch_id, mock__get_phys_port_name, mock__get_pf_func, mock_listdir): mock_listdir.return_value = [ 'pf_ifname1', 'pf_ifname2', 'rep_pf1_vf_1', 'rep_pf1_vf_2', 'rep_pf2_vf_1', 'rep_pf2_vf_2', ] mock__get_phys_switch_id.return_value = 'pf_sw_id' mock__get_pf_func.return_value = "2" mock__get_phys_port_name.side_effect = ( ["p1", "p2", "VF1@PF1", "pf2vf1", "vf2@pf1", "pf2vf2"]) ifname = linux_net.get_representor_port('pf_ifname2', '2') self.assertEqual('rep_pf2_vf_2', ifname) @mock.patch.object(os, 'listdir') @mock.patch.object(linux_net, "_get_pf_func") @mock.patch.object(linux_net, "_get_phys_switch_id") @mock.patch.object(linux_net, "_get_phys_port_name") def test_get_representor_port_not_found( self, mock__get_phys_port_name, mock__get_phys_switch_id, mock__get_pf_func, mock_listdir): mock_listdir.return_value = [ 'pf_ifname', 'rep_vf_1', 'rep_vf_2' ] mock__get_phys_switch_id.return_value = 'pf_sw_id' mock__get_pf_func.return_value = "0" mock__get_phys_port_name.side_effect = ( ["p0", "1", "2"]) self.assertRaises( <|code_end|> , predict the immediate next line with the help of imports: import glob import os.path import testtools from unittest import mock from os_vif.internal.ip.api import ip as ip_lib from vif_plug_ovs import exception from vif_plug_ovs import linux_net from vif_plug_ovs import privsep and context (classes, functions, sometimes code) from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_ovs/exception.py # class AgentError(osv_exception.ExceptionBase): # class MissingPortProfile(osv_exception.ExceptionBase): # class WrongPortProfile(osv_exception.ExceptionBase): # class RepresentorNotFound(osv_exception.ExceptionBase): # class PciDeviceNotFoundById(osv_exception.ExceptionBase): # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/privsep.py . Output only the next line.
exception.RepresentorNotFound,
Next line prediction: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class LinuxNetTest(testtools.TestCase): def setUp(self): super(LinuxNetTest, self).setUp() privsep.vif_plug.set_client_mode(False) <|code_end|> . Use current file imports: (import glob import os.path import testtools from unittest import mock from os_vif.internal.ip.api import ip as ip_lib from vif_plug_ovs import exception from vif_plug_ovs import linux_net from vif_plug_ovs import privsep) and context including class names, function names, or small code snippets from other files: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_ovs/exception.py # class AgentError(osv_exception.ExceptionBase): # class MissingPortProfile(osv_exception.ExceptionBase): # class WrongPortProfile(osv_exception.ExceptionBase): # class RepresentorNotFound(osv_exception.ExceptionBase): # class PciDeviceNotFoundById(osv_exception.ExceptionBase): # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/privsep.py . Output only the next line.
@mock.patch.object(linux_net, "_arp_filtering")
Using the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class LinuxNetTest(testtools.TestCase): def setUp(self): super(LinuxNetTest, self).setUp() <|code_end|> , determine the next line of code. You have imports: import glob import os.path import testtools from unittest import mock from os_vif.internal.ip.api import ip as ip_lib from vif_plug_ovs import exception from vif_plug_ovs import linux_net from vif_plug_ovs import privsep and context (class names, function names, or code) available: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: vif_plug_ovs/exception.py # class AgentError(osv_exception.ExceptionBase): # class MissingPortProfile(osv_exception.ExceptionBase): # class WrongPortProfile(osv_exception.ExceptionBase): # class RepresentorNotFound(osv_exception.ExceptionBase): # class PciDeviceNotFoundById(osv_exception.ExceptionBase): # # Path: vif_plug_ovs/linux_net.py # LOG = logging.getLogger(__name__) # VIRTFN_RE = re.compile(r"virtfn(\d+)") # INT_RE = re.compile(r"^(\d+)$") # VF_RE = re.compile(r"vf(\d+)", re.IGNORECASE) # PF_RE = re.compile(r"pf(\d+)", re.IGNORECASE) # PF_FUNC_RE = re.compile(r"\.(\d+)", 0) # UPLINK_PORT_RE = re.compile(r"p(\d+)", re.IGNORECASE) # _SRIOV_TOTALVFS = "sriov_totalvfs" # NIC_NAME_LEN = 14 # def _update_device_mtu(dev, mtu): # def delete_net_dev(dev): # def create_veth_pair(dev1_name, dev2_name, mtu): # def update_veth_pair(dev1_name, dev2_name, mtu): # def _disable_ipv6(bridge): # def _arp_filtering(bridge): # def ensure_bridge(bridge): # def delete_bridge(bridge, dev): # def add_bridge_port(bridge, dev): # def set_device_mtu(dev, mtu): # def set_interface_state(interface_name, port_state): # def _parse_vf_number(phys_port_name): # def _parse_pf_number(phys_port_name): # def get_function_by_ifname(ifname): # def _get_pf_func(pf_ifname): # def get_representor_port(pf_ifname, vf_num): # def _get_sysfs_netdev_path(pci_addr, pf_interface): # def _is_switchdev(netdev): # def get_ifname_by_pci_address(pci_addr, pf_interface=False, switchdev=False): # def get_vf_num_by_pci_address(pci_addr): # def get_dpdk_representor_port_name(port_id): # def get_pf_pci_from_vf(vf_pci): # def _get_phys_port_name(ifname): # def _get_phys_switch_id(ifname): # # Path: vif_plug_ovs/privsep.py . Output only the next line.
privsep.vif_plug.set_client_mode(False)
Given snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class TestIpApi(base.TestCase): @staticmethod def _reload_original_os_module(): <|code_end|> , continue by predicting the next line. Consider current file imports: import importlib from unittest import mock from os_vif.internal.ip import api from os_vif.tests.unit import base from os_vif.internal.ip.windows import impl_netifaces from os_vif.internal.ip.linux import impl_pyroute2 and context: # Path: os_vif/internal/ip/api.py # LOG = logging.getLogger(__name__) # # Path: os_vif/tests/unit/base.py # class TestCase(testtools.TestCase): which might include code, classes, or functions. Output only the next line.
importlib.reload(api)
Predict the next line after this snippet: <|code_start|> with mock.patch.object(iproute.IPRoute, 'link_lookup', return_value=[1]) as mock_link_lookup: self.ip_link.return_value = [{'flags': 0x4000}] self.ip.set(self.DEVICE, state=self.UP, mtu=self.MTU, address=self.MAC, promisc=True) mock_link_lookup.assert_called_once_with(ifname=self.DEVICE) args = {'state': self.UP, 'mtu': self.MTU, 'address': self.MAC, 'flags': 0x4000 | ifinfmsg.IFF_PROMISC} calls = [mock.call('get', index=1), mock.call('set', index=1, **args)] self.ip_link.assert_has_calls(calls) def test_set_exit_code(self): with mock.patch.object(iproute.IPRoute, 'link_lookup', return_value=[1]) as mock_link_lookup: self.ip_link.side_effect = ipexc.NetlinkError(self.ERROR_CODE, msg="Error message") self.ip.set(self.DEVICE, check_exit_code=[self.ERROR_CODE]) mock_link_lookup.assert_called_once_with(ifname=self.DEVICE) self.ip_link.assert_called_once_with('set', index=1) self.assertRaises(ipexc.NetlinkError, self.ip.set, self.DEVICE, check_exit_code=[self.OTHER_ERROR_CODE]) def test_set_no_interface_found(self): with mock.patch.object(iproute.IPRoute, 'link_lookup', return_value=[]) as mock_link_lookup: <|code_end|> using the current file's imports: from unittest import mock from pyroute2 import iproute from pyroute2.netlink import exceptions as ipexc from pyroute2.netlink.rtnl import ifinfmsg from os_vif import exception from os_vif.internal.ip.linux import impl_pyroute2 from os_vif.tests.unit import base and any relevant context from other files: # Path: os_vif/exception.py # class ExceptionBase(Exception): # class LibraryNotInitialized(ExceptionBase): # class NoMatchingPlugin(ExceptionBase): # class NoMatchingPortProfileClass(ExceptionBase): # class NoSupportedPortProfileVersion(ExceptionBase): # class NoMatchingVIFClass(ExceptionBase): # class NoSupportedVIFVersion(ExceptionBase): # class PlugException(ExceptionBase): # class UnplugException(ExceptionBase): # class NetworkMissingPhysicalNetwork(ExceptionBase): # class NetworkInterfaceNotFound(ExceptionBase): # class NetworkInterfaceTypeNotDefined(ExceptionBase): # class ExternalImport(ExceptionBase): # class NotImplementedForOS(ExceptionBase): # def __init__(self, message=None, **kwargs): # def format_message(self): # # Path: os_vif/internal/ip/linux/impl_pyroute2.py # LOG = logging.getLogger(__name__) # class PyRoute2(ip_command.IpCommand): # def _ip_link(self, ip, command, check_exit_code, **kwargs): # def set(self, device, check_exit_code=None, state=None, mtu=None, # address=None, promisc=None, master=None): # def lookup_interface(self, ip, link): # def add(self, device, dev_type, check_exit_code=None, peer=None, link=None, # vlan_id=None, ageing=None): # def delete(self, device, check_exit_code=None): # def exists(self, device): # # Path: os_vif/tests/unit/base.py # class TestCase(testtools.TestCase): . Output only the next line.
self.assertRaises(exception.NetworkInterfaceNotFound, self.ip.set,
Predict the next line for this snippet: <|code_start|># a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class TestIpCommand(base.TestCase): ERROR_CODE = 40 OTHER_ERROR_CODE = 50 DEVICE = 'device' MTU = 1500 MAC = 'ca:fe:ca:fe:ca:fe' UP = 'up' TYPE_VETH = 'veth' TYPE_VLAN = 'vlan' TYPE_BRIDGE = 'bridge' LINK = 'device2' VLAN_ID = 14 def setUp(self): super(TestIpCommand, self).setUp() <|code_end|> with the help of current file imports: from unittest import mock from pyroute2 import iproute from pyroute2.netlink import exceptions as ipexc from pyroute2.netlink.rtnl import ifinfmsg from os_vif import exception from os_vif.internal.ip.linux import impl_pyroute2 from os_vif.tests.unit import base and context from other files: # Path: os_vif/exception.py # class ExceptionBase(Exception): # class LibraryNotInitialized(ExceptionBase): # class NoMatchingPlugin(ExceptionBase): # class NoMatchingPortProfileClass(ExceptionBase): # class NoSupportedPortProfileVersion(ExceptionBase): # class NoMatchingVIFClass(ExceptionBase): # class NoSupportedVIFVersion(ExceptionBase): # class PlugException(ExceptionBase): # class UnplugException(ExceptionBase): # class NetworkMissingPhysicalNetwork(ExceptionBase): # class NetworkInterfaceNotFound(ExceptionBase): # class NetworkInterfaceTypeNotDefined(ExceptionBase): # class ExternalImport(ExceptionBase): # class NotImplementedForOS(ExceptionBase): # def __init__(self, message=None, **kwargs): # def format_message(self): # # Path: os_vif/internal/ip/linux/impl_pyroute2.py # LOG = logging.getLogger(__name__) # class PyRoute2(ip_command.IpCommand): # def _ip_link(self, ip, command, check_exit_code, **kwargs): # def set(self, device, check_exit_code=None, state=None, mtu=None, # address=None, promisc=None, master=None): # def lookup_interface(self, ip, link): # def add(self, device, dev_type, check_exit_code=None, peer=None, link=None, # vlan_id=None, ageing=None): # def delete(self, device, check_exit_code=None): # def exists(self, device): # # Path: os_vif/tests/unit/base.py # class TestCase(testtools.TestCase): , which may contain function names, class names, or code. Output only the next line.
self.ip = impl_pyroute2.PyRoute2()
Predict the next line for this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # TODO(jaypipes): Replace this entire module with use of the python-iptables # library: https://github.com/ldx/python-iptables # NOTE(vish): Iptables supports chain names of up to 28 characters, and we # add up to 12 characters to binary_name which is used as a prefix, # so we limit it to 16 characters. # (max_chain_name_length - len('-POSTROUTING') == 16) def get_binary_name(): """Grab the name of the binary we're running in.""" return os.path.basename(inspect.stack()[-1][1])[:16] binary_name = get_binary_name() <|code_end|> with the help of current file imports: import inspect import os import re from oslo_concurrency import lockutils from oslo_concurrency import processutils from vif_plug_linux_bridge import privsep and context from other files: # Path: vif_plug_linux_bridge/privsep.py , which may contain function names, class names, or code. Output only the next line.
@privsep.vif_plug.entrypoint
Continue the code snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. LOG = logging.getLogger(__name__) class Netifaces(ip_command.IpCommand): def exists(self, device): """Return True if the device exists in the namespace.""" try: return bool(netifaces.ifaddresses(device)) except ValueError: LOG.warning("The device does not exist on the system: %s", device) return False except OSError: LOG.error("Failed to get interface addresses: %s", device) return False def set(self, device, check_exit_code=None, state=None, mtu=None, address=None, promisc=None, master=None): <|code_end|> . Use current file imports: import netifaces from oslo_log import log as logging from os_vif import exception from os_vif.internal.ip import ip_command and context (classes, functions, or code) from other files: # Path: os_vif/exception.py # class ExceptionBase(Exception): # class LibraryNotInitialized(ExceptionBase): # class NoMatchingPlugin(ExceptionBase): # class NoMatchingPortProfileClass(ExceptionBase): # class NoSupportedPortProfileVersion(ExceptionBase): # class NoMatchingVIFClass(ExceptionBase): # class NoSupportedVIFVersion(ExceptionBase): # class PlugException(ExceptionBase): # class UnplugException(ExceptionBase): # class NetworkMissingPhysicalNetwork(ExceptionBase): # class NetworkInterfaceNotFound(ExceptionBase): # class NetworkInterfaceTypeNotDefined(ExceptionBase): # class ExternalImport(ExceptionBase): # class NotImplementedForOS(ExceptionBase): # def __init__(self, message=None, **kwargs): # def format_message(self): # # Path: os_vif/internal/ip/ip_command.py # class IpCommand(metaclass=abc.ABCMeta): # TYPE_VETH = 'veth' # TYPE_VLAN = 'vlan' # TYPE_BRIDGE = 'bridge' # def set(self, device, check_exit_code=None, state=None, mtu=None, # address=None, promisc=None, master=None): # def add(self, device, dev_type, check_exit_code=None, peer=None, link=None, # vlan_id=None, ageing=None): # def delete(self, device, check_exit_code=None): # def exists(self, device): . Output only the next line.
exception.NotImplementedForOS(function='ip.set', os='Windows')
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. @base.VersionedObjectRegistry.register class Subnet(osv_base.VersionedObject): """Represents a subnet.""" # Version 1.0: Initial version VERSION = '1.0' fields = { 'cidr': fields.IPNetworkField(), <|code_end|> using the current file's imports: from oslo_versionedobjects import base from oslo_versionedobjects import fields from os_vif.objects import base as osv_base from os_vif.objects import fields as osv_fields and any relevant context from other files: # Path: os_vif/objects/base.py # class VersionedObject(ovo_base.VersionedObject): # class VersionedObjectPrintableMixin(object): # OBJ_PROJECT_NAMESPACE = 'os_vif' # def __str__(self): # # Path: os_vif/objects/fields.py # class VIFDirectMode(fields.Enum): # class VIFDirectModeField(fields.BaseEnumField): # class VIFVHostUserMode(fields.Enum): # class VIFVHostUserModeField(fields.BaseEnumField): # class ListOfIPAddressField(fields.AutoTypedField): # class VIFHostDeviceDevType(fields.Enum): # class VIFHostDeviceDevTypeField(fields.BaseEnumField): # VEPA = 'vepa' # PASSTHROUGH = 'passthrough' # BRIDGE = 'bridge' # ALL = (VEPA, PASSTHROUGH, BRIDGE) # AUTO_TYPE = VIFDirectMode() # CLIENT = "client" # SERVER = "server" # ALL = (CLIENT, SERVER) # AUTO_TYPE = VIFVHostUserMode() # AUTO_TYPE = fields.List(fields.IPAddress()) # ETHERNET = 'ethernet' # GENERIC = 'generic' # ALL = (ETHERNET, GENERIC) # AUTO_TYPE = VIFHostDeviceDevType() # def __init__(self): # def __init__(self): # def __init__(self): . Output only the next line.
'dns': osv_fields.ListOfIPAddressField(),
Using the snippet: <|code_start|> if self._result: self._result = list(self._result[0].values())[0] class DbCreateCommand(BaseCommand): def __init__(self, context, opts=None, args=None): super(DbCreateCommand, self).__init__(context, "create", opts, args) # NOTE(twilson) pre-commit result used for intra-transaction reference self.record_id = "@%s" % uuidutils.generate_uuid() self.opts.append("--id=%s" % self.record_id) @property def result(self): return self._result @result.setter def result(self, val): self._result = uuid.UUID(val) if val else val class BrExistsCommand(DbCommand): @DbCommand.result.setter def result(self, val): self._result = val is not None def execute(self): return super(BrExistsCommand, self).execute(check_error=False, log_errors=False) <|code_end|> , determine the next line of code. You have imports: import collections.abc import itertools import uuid from oslo_concurrency import processutils from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import excutils from oslo_utils import uuidutils from ovsdbapp import api as ovsdb_api from vif_plug_ovs.ovsdb import api from vif_plug_ovs import privsep and context (class names, function names, or code) available: # Path: vif_plug_ovs/ovsdb/api.py # def get_instance(context, iface_name=None): # def has_table_column(self, table, column): # class ImplAPI(metaclass=abc.ABCMeta): # # Path: vif_plug_ovs/privsep.py . Output only the next line.
class OvsdbVsctl(ovsdb_api.API, api.ImplAPI):
Using the snippet: <|code_start|>LOG = logging.getLogger(__name__) def _val_to_py(val): """Convert a json ovsdb return value to native python object""" if isinstance(val, collections.abc.Sequence) and len(val) == 2: if val[0] == "uuid": return uuid.UUID(val[1]) elif val[0] == "set": return [_val_to_py(x) for x in val[1]] elif val[0] == "map": return {_val_to_py(x): _val_to_py(y) for x, y in val[1]} return val def _py_to_val(pyval): """Convert python value to ovs-vsctl value argument""" if isinstance(pyval, bool): return 'true' if pyval is True else 'false' elif pyval == '': return '""' else: # NOTE(twilson) If a Command object, return its record_id as a value return getattr(pyval, "record_id", pyval) def api_factory(context): return OvsdbVsctl(context) <|code_end|> , determine the next line of code. You have imports: import collections.abc import itertools import uuid from oslo_concurrency import processutils from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import excutils from oslo_utils import uuidutils from ovsdbapp import api as ovsdb_api from vif_plug_ovs.ovsdb import api from vif_plug_ovs import privsep and context (class names, function names, or code) available: # Path: vif_plug_ovs/ovsdb/api.py # def get_instance(context, iface_name=None): # def has_table_column(self, table, column): # class ImplAPI(metaclass=abc.ABCMeta): # # Path: vif_plug_ovs/privsep.py . Output only the next line.
@privsep.vif_plug.entrypoint
Next line prediction: <|code_start|> SEASON_NUMBER = 32002 SPECIALS = 20381 UNKNOWN_SOURCE = 32000 CHOOSE_TYPE_HEADER = 32050 CHOOSE_ART_HEADER = 32051 REFRESH_ITEM = 32409 AVAILABLE_COUNT = 32006 def prompt_for_artwork(mediatype, medialabel, availableart, monitor): if not availableart: return None, None arttypes = [] for arttype, artlist in availableart.iteritems(): if arttype.startswith('season.-1.'): # Ignore 'all' seasons artwork, as I can't set artwork for it with JSON continue label = arttype if not arttype.startswith('season.') else get_seasonlabel(arttype) for image in artlist: if image.get('existing'): arttypes.append({'arttype': arttype, 'label': label, 'count': len(artlist), 'url': image['url']}) break if arttype not in (at['arttype'] for at in arttypes): arttypes.append({'arttype': arttype, 'label': label, 'count': len(artlist)}) arttypes.sort(key=lambda art: sort_arttype(art['arttype'])) typeselectwindow = ArtworkTypeSelector('DialogSelect.xml', settings.addon_path, arttypes=arttypes, <|code_end|> . Use current file imports: (import re import xbmc import xbmcgui from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import localize as L) and context including class names, function names, or small code snippets from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result . Output only the next line.
medialabel=medialabel, show_refresh=mediatype in mediatypes.require_manualid)
Given snippet: <|code_start|> SEASON_NUMBER = 32002 SPECIALS = 20381 UNKNOWN_SOURCE = 32000 CHOOSE_TYPE_HEADER = 32050 CHOOSE_ART_HEADER = 32051 REFRESH_ITEM = 32409 AVAILABLE_COUNT = 32006 def prompt_for_artwork(mediatype, medialabel, availableart, monitor): if not availableart: return None, None arttypes = [] for arttype, artlist in availableart.iteritems(): if arttype.startswith('season.-1.'): # Ignore 'all' seasons artwork, as I can't set artwork for it with JSON continue label = arttype if not arttype.startswith('season.') else get_seasonlabel(arttype) for image in artlist: if image.get('existing'): arttypes.append({'arttype': arttype, 'label': label, 'count': len(artlist), 'url': image['url']}) break if arttype not in (at['arttype'] for at in arttypes): arttypes.append({'arttype': arttype, 'label': label, 'count': len(artlist)}) arttypes.sort(key=lambda art: sort_arttype(art['arttype'])) <|code_end|> , continue by predicting the next line. Consider current file imports: import re import xbmc import xbmcgui from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import localize as L and context: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result which might include code, classes, or functions. Output only the next line.
typeselectwindow = ArtworkTypeSelector('DialogSelect.xml', settings.addon_path, arttypes=arttypes,
Given snippet: <|code_start|> typelist = [at['arttype'] for at in arttypes] while selectedart is None and not monitor.abortRequested(): # The loop shows the first window if viewer backs out of the second selectedarttype = typeselectwindow.prompt() if selectedarttype not in typelist: return selectedarttype, None if not selectedarttype: break multi = mediatypes.get_artinfo(mediatype, selectedarttype)['multiselect'] artselectwindow = ArtworkSelector('DialogSelect.xml', settings.addon_path, artlist=availableart[selectedarttype], arttype=selectedarttype, medialabel=medialabel, multi=multi) selectedart = artselectwindow.prompt() return selectedarttype, selectedart class ArtworkTypeSelector(xbmcgui.WindowXMLDialog): def __init__(self, *args, **kwargs): super(ArtworkTypeSelector, self).__init__() self.arttypes = kwargs.get('arttypes') self.medialabel = kwargs.get('medialabel') self.show_refresh = kwargs.get('show_refresh') self.guilist = None self.selected = None def prompt(self): self.doModal() return self.selected def onInit(self): # This is called every time the window is shown if not self.selected: <|code_end|> , continue by predicting the next line. Consider current file imports: import re import xbmc import xbmcgui from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import localize as L and context: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result which might include code, classes, or functions. Output only the next line.
self.getControl(1).setLabel("Artwork Beef: " + L(CHOOSE_TYPE_HEADER).format(self.medialabel))
Next line prediction: <|code_start|> TVSHOW = 'tvshow' MOVIE = 'movie' EPISODE = 'episode' SEASON = 'season' MOVIESET = 'set' MUSICVIDEO = 'musicvideo' ARTIST = 'artist' ALBUM = 'album' SONG = 'song' audiotypes = (ARTIST, ALBUM, SONG) require_manualid = (MOVIESET, MUSICVIDEO) PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), 'music': ('theaudiodb.com', audiotypes), 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} <|code_end|> . Use current file imports: (from lib.libs import pykodi) and context including class names, function names, or small code snippets from other files: # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): . Output only the next line.
addon = pykodi.get_main_addon()
Continue the code snippet: <|code_start|> try: except ImportError: projectkeys = None <|code_end|> . Use current file imports: import xbmc import projectkeys from lib.libs import pykodi from lib.libs import quickjson and context (classes, functions, or code) from other files: # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): . Output only the next line.
addon = pykodi.get_main_addon()
Predict the next line after this snippet: <|code_start|> CANT_CONTACT_PROVIDER = 32034 HTTP_ERROR = 32035 urllib3.disable_warnings() languages = () cache = StorageServer.StorageServer('script.artwork.beef', 72) monitor = xbmc.Monitor() # Result of `get_images` is dict of lists, keyed on art type # {'url': URL, 'language': ISO alpha-2 code, 'rating': SortedDisplay, 'size': SortedDisplay, 'provider': self.name, 'preview': preview URL} # 'title': optional image title # 'subtype': optional image subtype, like disc dvd/bluray/3d, SortedDisplay # language should be None if there is no title on the image class AbstractProvider(object): __metaclass__ = ABCMeta name = SortedDisplay(0, '') mediatype = None contenttype = None def __init__(self): self.getter = Getter(self.contenttype, self.login) <|code_end|> using the current file's imports: import StorageServer import xbmc from abc import ABCMeta, abstractmethod from requests.packages import urllib3 from lib.libs.addonsettings import settings from lib.libs.pykodi import log, localize as L from lib.libs.utils import SortedDisplay from lib.libs.webhelper import Getter, GetterError and any relevant context from other files: # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def log(message, level=xbmc.LOGDEBUG, tag=None): # if is_addon_watched() and level < xbmc.LOGNOTICE: # # Messages from this add-on are being watched, elevate to NOTICE so Kodi logs it # level_tag = _log_level_tag_lookup[level] + ': ' if level in _log_level_tag_lookup else '' # level = xbmc.LOGNOTICE # else: # level_tag = '' # # if isinstance(message, (dict, list)) and len(message) > 300: # message = str(message) # elif isinstance(message, unicode): # message = message.encode('utf-8') # elif not isinstance(message, str): # message = json.dumps(message, cls=UTF8PrettyJSONEncoder) # # addontag = ADDONID if not tag else ADDONID + ':' + tag # file_message = '%s[%s] %s' % (level_tag, addontag, scrub_message(message)) # xbmc.log(file_message, level) # # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): # # Path: lib/libs/webhelper.py # class Getter(object): # def __init__(self, contenttype=None, login=lambda: False, session=None): # self.session = session or retryable_session() # self.login = login # if contenttype: # self.session.headers['Accept'] = contenttype # # def __call__(self, url, **kwargs): # try: # return self._inner_call(url, **kwargs) # except (Timeout, ConnectionError, RequestException) as ex: # message = ex.response.reason if getattr(ex, 'response', None) is not None else type(ex).__name__ # raise GetterError(message, ex, not isinstance(ex, RequestException)) # # def _inner_call(self, url, **kwargs): # if 'timeout' not in kwargs: # kwargs['timeout'] = 20 # result = self.session.get(url, **kwargs) # if result is None: # return # if result.status_code == 401: # if self.login(): # result = self.session.get(url, **kwargs) # if result is None: # return # # if result.status_code == 404: # return # result.raise_for_status() # return result # # class GetterError(Exception): # def __init__(self, message, cause, connection_error): # super(GetterError, self).__init__() # self.message = message # self.cause = cause # self.connection_error = connection_error # self.request = getattr(cause, 'request', None) # self.response = getattr(cause, 'response', None) . Output only the next line.
self.getter.session.headers['User-Agent'] = settings.useragent
Here is a snippet: <|code_start|>HTTP_ERROR = 32035 urllib3.disable_warnings() languages = () cache = StorageServer.StorageServer('script.artwork.beef', 72) monitor = xbmc.Monitor() # Result of `get_images` is dict of lists, keyed on art type # {'url': URL, 'language': ISO alpha-2 code, 'rating': SortedDisplay, 'size': SortedDisplay, 'provider': self.name, 'preview': preview URL} # 'title': optional image title # 'subtype': optional image subtype, like disc dvd/bluray/3d, SortedDisplay # language should be None if there is no title on the image class AbstractProvider(object): __metaclass__ = ABCMeta name = SortedDisplay(0, '') mediatype = None contenttype = None def __init__(self): self.getter = Getter(self.contenttype, self.login) self.getter.session.headers['User-Agent'] = settings.useragent def doget(self, url, **kwargs): try: return self.getter(url, **kwargs) except GetterError as ex: <|code_end|> . Write the next line using the current file imports: import StorageServer import xbmc from abc import ABCMeta, abstractmethod from requests.packages import urllib3 from lib.libs.addonsettings import settings from lib.libs.pykodi import log, localize as L from lib.libs.utils import SortedDisplay from lib.libs.webhelper import Getter, GetterError and context from other files: # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def log(message, level=xbmc.LOGDEBUG, tag=None): # if is_addon_watched() and level < xbmc.LOGNOTICE: # # Messages from this add-on are being watched, elevate to NOTICE so Kodi logs it # level_tag = _log_level_tag_lookup[level] + ': ' if level in _log_level_tag_lookup else '' # level = xbmc.LOGNOTICE # else: # level_tag = '' # # if isinstance(message, (dict, list)) and len(message) > 300: # message = str(message) # elif isinstance(message, unicode): # message = message.encode('utf-8') # elif not isinstance(message, str): # message = json.dumps(message, cls=UTF8PrettyJSONEncoder) # # addontag = ADDONID if not tag else ADDONID + ':' + tag # file_message = '%s[%s] %s' % (level_tag, addontag, scrub_message(message)) # xbmc.log(file_message, level) # # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): # # Path: lib/libs/webhelper.py # class Getter(object): # def __init__(self, contenttype=None, login=lambda: False, session=None): # self.session = session or retryable_session() # self.login = login # if contenttype: # self.session.headers['Accept'] = contenttype # # def __call__(self, url, **kwargs): # try: # return self._inner_call(url, **kwargs) # except (Timeout, ConnectionError, RequestException) as ex: # message = ex.response.reason if getattr(ex, 'response', None) is not None else type(ex).__name__ # raise GetterError(message, ex, not isinstance(ex, RequestException)) # # def _inner_call(self, url, **kwargs): # if 'timeout' not in kwargs: # kwargs['timeout'] = 20 # result = self.session.get(url, **kwargs) # if result is None: # return # if result.status_code == 401: # if self.login(): # result = self.session.get(url, **kwargs) # if result is None: # return # # if result.status_code == 404: # return # result.raise_for_status() # return result # # class GetterError(Exception): # def __init__(self, message, cause, connection_error): # super(GetterError, self).__init__() # self.message = message # self.cause = cause # self.connection_error = connection_error # self.request = getattr(cause, 'request', None) # self.response = getattr(cause, 'response', None) , which may include functions, classes, or code. Output only the next line.
message = L(CANT_CONTACT_PROVIDER) if ex.connection_error else L(HTTP_ERROR).format(ex.message)
Based on the snippet: <|code_start|> CANT_CONTACT_PROVIDER = 32034 HTTP_ERROR = 32035 urllib3.disable_warnings() languages = () cache = StorageServer.StorageServer('script.artwork.beef', 72) monitor = xbmc.Monitor() # Result of `get_images` is dict of lists, keyed on art type # {'url': URL, 'language': ISO alpha-2 code, 'rating': SortedDisplay, 'size': SortedDisplay, 'provider': self.name, 'preview': preview URL} # 'title': optional image title # 'subtype': optional image subtype, like disc dvd/bluray/3d, SortedDisplay # language should be None if there is no title on the image class AbstractProvider(object): __metaclass__ = ABCMeta <|code_end|> , predict the immediate next line with the help of imports: import StorageServer import xbmc from abc import ABCMeta, abstractmethod from requests.packages import urllib3 from lib.libs.addonsettings import settings from lib.libs.pykodi import log, localize as L from lib.libs.utils import SortedDisplay from lib.libs.webhelper import Getter, GetterError and context (classes, functions, sometimes code) from other files: # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def log(message, level=xbmc.LOGDEBUG, tag=None): # if is_addon_watched() and level < xbmc.LOGNOTICE: # # Messages from this add-on are being watched, elevate to NOTICE so Kodi logs it # level_tag = _log_level_tag_lookup[level] + ': ' if level in _log_level_tag_lookup else '' # level = xbmc.LOGNOTICE # else: # level_tag = '' # # if isinstance(message, (dict, list)) and len(message) > 300: # message = str(message) # elif isinstance(message, unicode): # message = message.encode('utf-8') # elif not isinstance(message, str): # message = json.dumps(message, cls=UTF8PrettyJSONEncoder) # # addontag = ADDONID if not tag else ADDONID + ':' + tag # file_message = '%s[%s] %s' % (level_tag, addontag, scrub_message(message)) # xbmc.log(file_message, level) # # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): # # Path: lib/libs/webhelper.py # class Getter(object): # def __init__(self, contenttype=None, login=lambda: False, session=None): # self.session = session or retryable_session() # self.login = login # if contenttype: # self.session.headers['Accept'] = contenttype # # def __call__(self, url, **kwargs): # try: # return self._inner_call(url, **kwargs) # except (Timeout, ConnectionError, RequestException) as ex: # message = ex.response.reason if getattr(ex, 'response', None) is not None else type(ex).__name__ # raise GetterError(message, ex, not isinstance(ex, RequestException)) # # def _inner_call(self, url, **kwargs): # if 'timeout' not in kwargs: # kwargs['timeout'] = 20 # result = self.session.get(url, **kwargs) # if result is None: # return # if result.status_code == 401: # if self.login(): # result = self.session.get(url, **kwargs) # if result is None: # return # # if result.status_code == 404: # return # result.raise_for_status() # return result # # class GetterError(Exception): # def __init__(self, message, cause, connection_error): # super(GetterError, self).__init__() # self.message = message # self.cause = cause # self.connection_error = connection_error # self.request = getattr(cause, 'request', None) # self.response = getattr(cause, 'response', None) . Output only the next line.
name = SortedDisplay(0, '')
Given the code snippet: <|code_start|> CANT_CONTACT_PROVIDER = 32034 HTTP_ERROR = 32035 urllib3.disable_warnings() languages = () cache = StorageServer.StorageServer('script.artwork.beef', 72) monitor = xbmc.Monitor() # Result of `get_images` is dict of lists, keyed on art type # {'url': URL, 'language': ISO alpha-2 code, 'rating': SortedDisplay, 'size': SortedDisplay, 'provider': self.name, 'preview': preview URL} # 'title': optional image title # 'subtype': optional image subtype, like disc dvd/bluray/3d, SortedDisplay # language should be None if there is no title on the image class AbstractProvider(object): __metaclass__ = ABCMeta name = SortedDisplay(0, '') mediatype = None contenttype = None def __init__(self): <|code_end|> , generate the next line using the imports in this file: import StorageServer import xbmc from abc import ABCMeta, abstractmethod from requests.packages import urllib3 from lib.libs.addonsettings import settings from lib.libs.pykodi import log, localize as L from lib.libs.utils import SortedDisplay from lib.libs.webhelper import Getter, GetterError and context (functions, classes, or occasionally code) from other files: # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def log(message, level=xbmc.LOGDEBUG, tag=None): # if is_addon_watched() and level < xbmc.LOGNOTICE: # # Messages from this add-on are being watched, elevate to NOTICE so Kodi logs it # level_tag = _log_level_tag_lookup[level] + ': ' if level in _log_level_tag_lookup else '' # level = xbmc.LOGNOTICE # else: # level_tag = '' # # if isinstance(message, (dict, list)) and len(message) > 300: # message = str(message) # elif isinstance(message, unicode): # message = message.encode('utf-8') # elif not isinstance(message, str): # message = json.dumps(message, cls=UTF8PrettyJSONEncoder) # # addontag = ADDONID if not tag else ADDONID + ':' + tag # file_message = '%s[%s] %s' % (level_tag, addontag, scrub_message(message)) # xbmc.log(file_message, level) # # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): # # Path: lib/libs/webhelper.py # class Getter(object): # def __init__(self, contenttype=None, login=lambda: False, session=None): # self.session = session or retryable_session() # self.login = login # if contenttype: # self.session.headers['Accept'] = contenttype # # def __call__(self, url, **kwargs): # try: # return self._inner_call(url, **kwargs) # except (Timeout, ConnectionError, RequestException) as ex: # message = ex.response.reason if getattr(ex, 'response', None) is not None else type(ex).__name__ # raise GetterError(message, ex, not isinstance(ex, RequestException)) # # def _inner_call(self, url, **kwargs): # if 'timeout' not in kwargs: # kwargs['timeout'] = 20 # result = self.session.get(url, **kwargs) # if result is None: # return # if result.status_code == 401: # if self.login(): # result = self.session.get(url, **kwargs) # if result is None: # return # # if result.status_code == 404: # return # result.raise_for_status() # return result # # class GetterError(Exception): # def __init__(self, message, cause, connection_error): # super(GetterError, self).__init__() # self.message = message # self.cause = cause # self.connection_error = connection_error # self.request = getattr(cause, 'request', None) # self.response = getattr(cause, 'response', None) . Output only the next line.
self.getter = Getter(self.contenttype, self.login)
Continue the code snippet: <|code_start|>CANT_CONTACT_PROVIDER = 32034 HTTP_ERROR = 32035 urllib3.disable_warnings() languages = () cache = StorageServer.StorageServer('script.artwork.beef', 72) monitor = xbmc.Monitor() # Result of `get_images` is dict of lists, keyed on art type # {'url': URL, 'language': ISO alpha-2 code, 'rating': SortedDisplay, 'size': SortedDisplay, 'provider': self.name, 'preview': preview URL} # 'title': optional image title # 'subtype': optional image subtype, like disc dvd/bluray/3d, SortedDisplay # language should be None if there is no title on the image class AbstractProvider(object): __metaclass__ = ABCMeta name = SortedDisplay(0, '') mediatype = None contenttype = None def __init__(self): self.getter = Getter(self.contenttype, self.login) self.getter.session.headers['User-Agent'] = settings.useragent def doget(self, url, **kwargs): try: return self.getter(url, **kwargs) <|code_end|> . Use current file imports: import StorageServer import xbmc from abc import ABCMeta, abstractmethod from requests.packages import urllib3 from lib.libs.addonsettings import settings from lib.libs.pykodi import log, localize as L from lib.libs.utils import SortedDisplay from lib.libs.webhelper import Getter, GetterError and context (classes, functions, or code) from other files: # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def log(message, level=xbmc.LOGDEBUG, tag=None): # if is_addon_watched() and level < xbmc.LOGNOTICE: # # Messages from this add-on are being watched, elevate to NOTICE so Kodi logs it # level_tag = _log_level_tag_lookup[level] + ': ' if level in _log_level_tag_lookup else '' # level = xbmc.LOGNOTICE # else: # level_tag = '' # # if isinstance(message, (dict, list)) and len(message) > 300: # message = str(message) # elif isinstance(message, unicode): # message = message.encode('utf-8') # elif not isinstance(message, str): # message = json.dumps(message, cls=UTF8PrettyJSONEncoder) # # addontag = ADDONID if not tag else ADDONID + ':' + tag # file_message = '%s[%s] %s' % (level_tag, addontag, scrub_message(message)) # xbmc.log(file_message, level) # # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): # # Path: lib/libs/webhelper.py # class Getter(object): # def __init__(self, contenttype=None, login=lambda: False, session=None): # self.session = session or retryable_session() # self.login = login # if contenttype: # self.session.headers['Accept'] = contenttype # # def __call__(self, url, **kwargs): # try: # return self._inner_call(url, **kwargs) # except (Timeout, ConnectionError, RequestException) as ex: # message = ex.response.reason if getattr(ex, 'response', None) is not None else type(ex).__name__ # raise GetterError(message, ex, not isinstance(ex, RequestException)) # # def _inner_call(self, url, **kwargs): # if 'timeout' not in kwargs: # kwargs['timeout'] = 20 # result = self.session.get(url, **kwargs) # if result is None: # return # if result.status_code == 401: # if self.login(): # result = self.session.get(url, **kwargs) # if result is None: # return # # if result.status_code == 404: # return # result.raise_for_status() # return result # # class GetterError(Exception): # def __init__(self, message, cause, connection_error): # super(GetterError, self).__init__() # self.message = message # self.cause = cause # self.connection_error = connection_error # self.request = getattr(cause, 'request', None) # self.response = getattr(cause, 'response', None) . Output only the next line.
except GetterError as ex:
Based on the snippet: <|code_start|> if sys.version_info < (2, 7): else: NFO_FILE = 32003 class NFOFileAbstractProvider(object): __metaclass__ = ABCMeta name = SortedDisplay('file:nfo', NFO_FILE) def build_resultimage(self, url, title): if isinstance(url, unicode): url = url.encode('utf-8') if url.startswith('http'): url = urllib.quote(url, safe="%/:=&?~#+!$,;'@()*[]") resultimage = {'url': url, 'provider': self.name, 'preview': url} resultimage['title'] = '<{0}>'.format(title) resultimage['rating'] = SortedDisplay(0, '') resultimage['size'] = SortedDisplay(0, '') resultimage['language'] = 'xx' return resultimage class NFOFileSeriesProvider(NFOFileAbstractProvider): <|code_end|> , predict the immediate next line with the help of imports: import os import sys import urllib import xbmcvfs import xml.etree.ElementTree as ET from abc import ABCMeta from contextlib import closing from xml.parsers.expat import ExpatError as ParseError from xml.etree.ElementTree import ParseError from lib.libs import mediatypes from lib.libs.utils import SortedDisplay, get_movie_path_list and context (classes, functions, sometimes code) from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): . Output only the next line.
mediatype = mediatypes.TVSHOW
Based on the snippet: <|code_start|> if sys.version_info < (2, 7): else: NFO_FILE = 32003 class NFOFileAbstractProvider(object): __metaclass__ = ABCMeta <|code_end|> , predict the immediate next line with the help of imports: import os import sys import urllib import xbmcvfs import xml.etree.ElementTree as ET from abc import ABCMeta from contextlib import closing from xml.parsers.expat import ExpatError as ParseError from xml.etree.ElementTree import ParseError from lib.libs import mediatypes from lib.libs.utils import SortedDisplay, get_movie_path_list and context (classes, functions, sometimes code) from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): . Output only the next line.
name = SortedDisplay('file:nfo', NFO_FILE)
Next line prediction: <|code_start|> if root is None or root.find('art') is None: return {} artlistelement = root.find('art') result = {} for artelement in artlistelement: arttype = artelement.tag.lower() if arttype == 'season': num = artelement.get('num') if num is None: continue try: num = int(num) except ValueError: continue if num < -1: continue for seasonartelement in artelement: url = seasonartelement.text.strip() if seasonartelement.tag.isalnum() and url: seasonarttype = 'season.{0}.{1}'.format(num, seasonartelement.tag.lower()) result[seasonarttype] = self.build_resultimage(url, seasonarttype) elif arttype.isalnum() and artelement.text.strip(): result[arttype] = self.build_resultimage(artelement.text.strip(), arttype) return result class NFOFileMovieProvider(NFOFileAbstractProvider): mediatype = mediatypes.MOVIE def get_exact_images(self, mediaitem): <|code_end|> . Use current file imports: (import os import sys import urllib import xbmcvfs import xml.etree.ElementTree as ET from abc import ABCMeta from contextlib import closing from xml.parsers.expat import ExpatError as ParseError from xml.etree.ElementTree import ParseError from lib.libs import mediatypes from lib.libs.utils import SortedDisplay, get_movie_path_list) and context including class names, function names, or small code snippets from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): . Output only the next line.
paths = get_movie_path_list(mediaitem.file)
Given the following code snippet before the placeholder: <|code_start|> def does_not_exist(self, mediaid, mediatype, medialabel): return not self.exists(mediaid, mediatype, medialabel) def _key_exists(self, mediaid, mediatype): return bool(self.db.fetchone("SELECT * FROM processeditems WHERE mediaid=? AND mediatype=?", (mediaid, mediatype))) def upgrade_processeditems(db, fromversion): if fromversion == VERSION: return VERSION if fromversion == -1: # new install, build the database fresh db.execute("""CREATE TABLE processeditems (mediaid INTEGER NOT NULL, mediatype TEXT NOT NULL, medialabel TEXT, nextdate DATETIME, data TEXT, PRIMARY KEY (mediaid, mediatype))""") return VERSION workingversion = fromversion if workingversion == 0: db.execute("""ALTER TABLE processeditems ADD COLUMN medialabel TEXT""") workingversion = 1 return workingversion SETTINGS_TABLE_VALUE = 'database-settings' # must be quoted to use as identifier SETTINGS_TABLE = '"{0}"'.format(SETTINGS_TABLE_VALUE) class Database(object): def __init__(self, databasename, upgrade_fn): <|code_end|> , predict the next line using imports from the current file: import sqlite3 import xbmc import xbmcvfs from lib.libs.addonsettings import settings and context including class names, function names, and sometimes code from other files: # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): . Output only the next line.
dbpath = settings.datapath
Next line prediction: <|code_start|> if not stackedpath.startswith('stack://'): result = [stackedpath] else: firstpath, path2 = stackedpath[8:].split(' , ')[0:2] path, filename = split(firstpath) if filename: filename2 = basename(path2) for regex in moviestacking: offset = 0 while True: match = regex.match(filename, offset) match2 = regex.match(filename2, offset) if match is not None and match2 is not None and match.group(1).lower() == match2.group(1).lower(): if match.group(2).lower() == match2.group(2).lower(): offset = match.start(3) continue # DEPRECATED: Returning the path to part1 doesn't seem to work in Kodi. # Not sure where I got that idea, but it shouldn't be used. # Also, AB created the ones missing `group(3)` for awhile, but it is wrong. # Adding both here so that file scanning still finds them. pathbase = path + get_pathsep(path) + filename[:offset] + match.group(1) result = [ pathbase + match.group(3) + match.group(4), pathbase + match.group(4), firstpath] break else: # folder stacking pass # I can't even get Kodi to add stacked VIDEO_TS rips period if not result: <|code_end|> . Use current file imports: (import re import xbmc from collections import namedtuple from os.path import split, basename, dirname from lib.libs.pykodi import log) and context including class names, function names, or small code snippets from other files: # Path: lib/libs/pykodi.py # def log(message, level=xbmc.LOGDEBUG, tag=None): # if is_addon_watched() and level < xbmc.LOGNOTICE: # # Messages from this add-on are being watched, elevate to NOTICE so Kodi logs it # level_tag = _log_level_tag_lookup[level] + ': ' if level in _log_level_tag_lookup else '' # level = xbmc.LOGNOTICE # else: # level_tag = '' # # if isinstance(message, (dict, list)) and len(message) > 300: # message = str(message) # elif isinstance(message, unicode): # message = message.encode('utf-8') # elif not isinstance(message, str): # message = json.dumps(message, cls=UTF8PrettyJSONEncoder) # # addontag = ADDONID if not tag else ADDONID + ':' + tag # file_message = '%s[%s] %s' % (level_tag, addontag, scrub_message(message)) # xbmc.log(file_message, level) . Output only the next line.
log("Couldn't get an unstacked path from \"{0}\"".format(stackedpath), xbmc.LOGWARNING)
Given snippet: <|code_start|> FILENAME = 'special://userdata/advancedsettings.xml' FILENAME_BAK = FILENAME + '.beef.bak' ROOT_TAG = 'advancedsettings' VIDEO_TAG = 'videolibrary' MUSIC_TAG = 'musiclibrary' ARTTYPE_TAG = 'arttype' # 0: mediatype tag name, 1: library tag name, 2: Kodi's hardcoded art types to exclude from AS.xml mediatype_map = {'tvshow': ('tvshowextraart', VIDEO_TAG, ('poster', 'banner', 'fanart')), 'season': ('tvshowseasonextraart', VIDEO_TAG, ('poster', 'banner', 'fanart')), 'episode': ('episodeextraart', VIDEO_TAG, ('thumb',)), 'movie': ('movieextraart', VIDEO_TAG, ('poster', 'fanart')), 'set': ('moviesetextraart', VIDEO_TAG, ('poster', 'fanart')), 'musicvideo': ('musicvideoextraart', VIDEO_TAG, ('poster', 'fanart')), 'artist': ('artistextraart', MUSIC_TAG, ('thumb', 'fanart')), 'album': ('albumextraart', MUSIC_TAG, ('thumb',))} unsupported_types = ('song',) MALFORMED = 32654 BACKUP_SUCCESSFUL = 32655 BACKUP_UNSUCCESSFUL = 32656 RESTORE_SUCCESSFUL = 32657 RESTORE_UNSUCCESSFUL = 32658 RESTART_KODI = 32659 def save_arttypes(arttype_map): root = read_xml() if root is None: <|code_end|> , continue by predicting the next line. Consider current file imports: import xbmc import xbmcgui import xbmcvfs import xml.etree.ElementTree as ET from contextlib import closing from lib.libs.pykodi import log, localize as L and context: # Path: lib/libs/pykodi.py # def log(message, level=xbmc.LOGDEBUG, tag=None): # if is_addon_watched() and level < xbmc.LOGNOTICE: # # Messages from this add-on are being watched, elevate to NOTICE so Kodi logs it # level_tag = _log_level_tag_lookup[level] + ': ' if level in _log_level_tag_lookup else '' # level = xbmc.LOGNOTICE # else: # level_tag = '' # # if isinstance(message, (dict, list)) and len(message) > 300: # message = str(message) # elif isinstance(message, unicode): # message = message.encode('utf-8') # elif not isinstance(message, str): # message = json.dumps(message, cls=UTF8PrettyJSONEncoder) # # addontag = ADDONID if not tag else ADDONID + ':' + tag # file_message = '%s[%s] %s' % (level_tag, addontag, scrub_message(message)) # xbmc.log(file_message, level) # # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result which might include code, classes, or functions. Output only the next line.
xbmcgui.Dialog().notification("Artwork Beef", L(MALFORMED), xbmcgui.NOTIFICATION_WARNING)
Predict the next line after this snippet: <|code_start|> cfgurl = 'https://api.themoviedb.org/3/configuration' class TheMovieDBAbstractProvider(AbstractImageProvider): __metaclass__ = ABCMeta contenttype = 'application/json' name = SortedDisplay('themoviedb.org', 'The Movie Database') _baseurl = None artmap = {} @property def baseurl(self): if not self._baseurl: <|code_end|> using the current file's imports: import xbmc from abc import ABCMeta from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import json, UTF8JSONDecoder from lib.libs.utils import SortedDisplay from lib.providers.base import AbstractProvider, AbstractImageProvider, cache, build_key_error and any relevant context from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): # # Path: lib/providers/base.py # CANT_CONTACT_PROVIDER = 32034 # HTTP_ERROR = 32035 # class AbstractProvider(object): # class AbstractImageProvider(AbstractProvider): # class ProviderError(Exception): # def __init__(self): # def doget(self, url, **kwargs): # def log(self, message, level=xbmc.LOGDEBUG): # def login(self): # def build_key_error(provider): # def get_images(self, uniqueids, types=None): # def __init__(self, message, cause=None): . Output only the next line.
apikey = settings.get_apikey('tmdb')
Here is a snippet: <|code_start|> cfgurl = 'https://api.themoviedb.org/3/configuration' class TheMovieDBAbstractProvider(AbstractImageProvider): __metaclass__ = ABCMeta contenttype = 'application/json' name = SortedDisplay('themoviedb.org', 'The Movie Database') _baseurl = None artmap = {} @property def baseurl(self): if not self._baseurl: apikey = settings.get_apikey('tmdb') if not apikey: raise build_key_error('tmdb') response = self.doget(cfgurl, params={'api_key': apikey}) if response is None: return <|code_end|> . Write the next line using the current file imports: import xbmc from abc import ABCMeta from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import json, UTF8JSONDecoder from lib.libs.utils import SortedDisplay from lib.providers.base import AbstractProvider, AbstractImageProvider, cache, build_key_error and context from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): # # Path: lib/providers/base.py # CANT_CONTACT_PROVIDER = 32034 # HTTP_ERROR = 32035 # class AbstractProvider(object): # class AbstractImageProvider(AbstractProvider): # class ProviderError(Exception): # def __init__(self): # def doget(self, url, **kwargs): # def log(self, message, level=xbmc.LOGDEBUG): # def login(self): # def build_key_error(provider): # def get_images(self, uniqueids, types=None): # def __init__(self, message, cause=None): , which may include functions, classes, or code. Output only the next line.
self._baseurl = response.json()['images']['secure_base_url']
Next line prediction: <|code_start|> cfgurl = 'https://api.themoviedb.org/3/configuration' class TheMovieDBAbstractProvider(AbstractImageProvider): __metaclass__ = ABCMeta contenttype = 'application/json' <|code_end|> . Use current file imports: (import xbmc from abc import ABCMeta from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import json, UTF8JSONDecoder from lib.libs.utils import SortedDisplay from lib.providers.base import AbstractProvider, AbstractImageProvider, cache, build_key_error) and context including class names, function names, or small code snippets from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): # # Path: lib/providers/base.py # CANT_CONTACT_PROVIDER = 32034 # HTTP_ERROR = 32035 # class AbstractProvider(object): # class AbstractImageProvider(AbstractProvider): # class ProviderError(Exception): # def __init__(self): # def doget(self, url, **kwargs): # def log(self, message, level=xbmc.LOGDEBUG): # def login(self): # def build_key_error(provider): # def get_images(self, uniqueids, types=None): # def __init__(self, message, cause=None): . Output only the next line.
name = SortedDisplay('themoviedb.org', 'The Movie Database')
Using the snippet: <|code_start|> cfgurl = 'https://api.themoviedb.org/3/configuration' class TheMovieDBAbstractProvider(AbstractImageProvider): __metaclass__ = ABCMeta contenttype = 'application/json' name = SortedDisplay('themoviedb.org', 'The Movie Database') _baseurl = None artmap = {} @property def baseurl(self): if not self._baseurl: apikey = settings.get_apikey('tmdb') if not apikey: <|code_end|> , determine the next line of code. You have imports: import xbmc from abc import ABCMeta from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import json, UTF8JSONDecoder from lib.libs.utils import SortedDisplay from lib.providers.base import AbstractProvider, AbstractImageProvider, cache, build_key_error and context (class names, function names, or code) available: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): # # Path: lib/providers/base.py # CANT_CONTACT_PROVIDER = 32034 # HTTP_ERROR = 32035 # class AbstractProvider(object): # class AbstractImageProvider(AbstractProvider): # class ProviderError(Exception): # def __init__(self): # def doget(self, url, **kwargs): # def log(self, message, level=xbmc.LOGDEBUG): # def login(self): # def build_key_error(provider): # def get_images(self, uniqueids, types=None): # def __init__(self, message, cause=None): . Output only the next line.
raise build_key_error('tmdb')
Predict the next line for this snippet: <|code_start|> class FanartTVAbstractProvider(AbstractImageProvider): __metaclass__ = ABCMeta api_section = None mediatype = None contenttype = 'application/json' name = SortedDisplay('fanart.tv', 'fanart.tv') apiurl = 'https://webservice.fanart.tv/v3/%s/%s' def get_images(self, uniqueids, types=None): if not settings.get_apienabled('fanarttv'): return {} if types is not None and not self.provides(types): return {} mediaid = get_mediaid(uniqueids, self.mediatype) if not mediaid or isinstance(mediaid, tuple) and not mediaid[0]: return {} data = self.get_data(mediaid[0] if isinstance(mediaid, tuple) else mediaid) if not data: return {} <|code_end|> with the help of current file imports: import re import urllib import xbmc from abc import ABCMeta, abstractmethod from lib.providers.base import AbstractImageProvider, cache, build_key_error from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import json, UTF8JSONDecoder from lib.libs.utils import SortedDisplay and context from other files: # Path: lib/providers/base.py # CANT_CONTACT_PROVIDER = 32034 # HTTP_ERROR = 32035 # class AbstractProvider(object): # class AbstractImageProvider(AbstractProvider): # class ProviderError(Exception): # def __init__(self): # def doget(self, url, **kwargs): # def log(self, message, level=xbmc.LOGDEBUG): # def login(self): # def build_key_error(provider): # def get_images(self, uniqueids, types=None): # def __init__(self, message, cause=None): # # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): , which may contain function names, class names, or code. Output only the next line.
if self.mediatype == mediatypes.MUSICVIDEO:
Next line prediction: <|code_start|> class FanartTVAbstractProvider(AbstractImageProvider): __metaclass__ = ABCMeta api_section = None mediatype = None contenttype = 'application/json' name = SortedDisplay('fanart.tv', 'fanart.tv') apiurl = 'https://webservice.fanart.tv/v3/%s/%s' def get_images(self, uniqueids, types=None): <|code_end|> . Use current file imports: (import re import urllib import xbmc from abc import ABCMeta, abstractmethod from lib.providers.base import AbstractImageProvider, cache, build_key_error from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import json, UTF8JSONDecoder from lib.libs.utils import SortedDisplay) and context including class names, function names, or small code snippets from other files: # Path: lib/providers/base.py # CANT_CONTACT_PROVIDER = 32034 # HTTP_ERROR = 32035 # class AbstractProvider(object): # class AbstractImageProvider(AbstractProvider): # class ProviderError(Exception): # def __init__(self): # def doget(self, url, **kwargs): # def log(self, message, level=xbmc.LOGDEBUG): # def login(self): # def build_key_error(provider): # def get_images(self, uniqueids, types=None): # def __init__(self, message, cause=None): # # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): . Output only the next line.
if not settings.get_apienabled('fanarttv'):
Next line prediction: <|code_start|> class FanartTVAbstractProvider(AbstractImageProvider): __metaclass__ = ABCMeta api_section = None mediatype = None contenttype = 'application/json' <|code_end|> . Use current file imports: (import re import urllib import xbmc from abc import ABCMeta, abstractmethod from lib.providers.base import AbstractImageProvider, cache, build_key_error from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import json, UTF8JSONDecoder from lib.libs.utils import SortedDisplay) and context including class names, function names, or small code snippets from other files: # Path: lib/providers/base.py # CANT_CONTACT_PROVIDER = 32034 # HTTP_ERROR = 32035 # class AbstractProvider(object): # class AbstractImageProvider(AbstractProvider): # class ProviderError(Exception): # def __init__(self): # def doget(self, url, **kwargs): # def log(self, message, level=xbmc.LOGDEBUG): # def login(self): # def build_key_error(provider): # def get_images(self, uniqueids, types=None): # def __init__(self, message, cause=None): # # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): . Output only the next line.
name = SortedDisplay('fanart.tv', 'fanart.tv')
Using the snippet: <|code_start|> VIDEO_FILE = 32004 VIDEO_FILE_THUMB = 32005 class VideoFileAbstractProvider(object): __metaclass__ = ABCMeta name = SortedDisplay('video:thumb', VIDEO_FILE) def build_video_thumbnail(self, path): url = build_video_thumbnail_path(path) return {'url': url, 'rating': SortedDisplay(0, ''), 'language': 'xx', 'title': L(VIDEO_FILE_THUMB), 'provider': self.name, 'size': SortedDisplay(0, ''), 'preview': url} def build_video_thumbnail_path(videofile): if videofile.startswith('image://'): return videofile # Kodi goes lowercase and doesn't encode some chars result = 'image://video@{0}/'.format(urllib.quote(videofile, '()!')) result = re.sub(r'%[0-9A-F]{2}', lambda mo: mo.group().lower(), result) return result class VideoFileMovieProvider(VideoFileAbstractProvider): <|code_end|> , determine the next line of code. You have imports: import re import urllib from abc import ABCMeta from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import localize as L from lib.libs.utils import SortedDisplay, get_movie_path_list and context (class names, function names, or code) available: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): . Output only the next line.
mediatype = mediatypes.MOVIE
Next line prediction: <|code_start|> VIDEO_FILE = 32004 VIDEO_FILE_THUMB = 32005 class VideoFileAbstractProvider(object): __metaclass__ = ABCMeta name = SortedDisplay('video:thumb', VIDEO_FILE) def build_video_thumbnail(self, path): url = build_video_thumbnail_path(path) <|code_end|> . Use current file imports: (import re import urllib from abc import ABCMeta from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import localize as L from lib.libs.utils import SortedDisplay, get_movie_path_list) and context including class names, function names, or small code snippets from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): . Output only the next line.
return {'url': url, 'rating': SortedDisplay(0, ''), 'language': 'xx', 'title': L(VIDEO_FILE_THUMB),
Based on the snippet: <|code_start|> VIDEO_FILE = 32004 VIDEO_FILE_THUMB = 32005 class VideoFileAbstractProvider(object): __metaclass__ = ABCMeta <|code_end|> , predict the immediate next line with the help of imports: import re import urllib from abc import ABCMeta from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import localize as L from lib.libs.utils import SortedDisplay, get_movie_path_list and context (classes, functions, sometimes code) from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): . Output only the next line.
name = SortedDisplay('video:thumb', VIDEO_FILE)
Given snippet: <|code_start|> VIDEO_FILE = 32004 VIDEO_FILE_THUMB = 32005 class VideoFileAbstractProvider(object): __metaclass__ = ABCMeta name = SortedDisplay('video:thumb', VIDEO_FILE) def build_video_thumbnail(self, path): url = build_video_thumbnail_path(path) return {'url': url, 'rating': SortedDisplay(0, ''), 'language': 'xx', 'title': L(VIDEO_FILE_THUMB), 'provider': self.name, 'size': SortedDisplay(0, ''), 'preview': url} def build_video_thumbnail_path(videofile): if videofile.startswith('image://'): return videofile # Kodi goes lowercase and doesn't encode some chars result = 'image://video@{0}/'.format(urllib.quote(videofile, '()!')) result = re.sub(r'%[0-9A-F]{2}', lambda mo: mo.group().lower(), result) return result class VideoFileMovieProvider(VideoFileAbstractProvider): mediatype = mediatypes.MOVIE def get_exact_images(self, mediaitem): if not mediatypes.generatethumb(mediaitem.mediatype): return {} <|code_end|> , continue by predicting the next line. Consider current file imports: import re import urllib from abc import ABCMeta from lib.libs import mediatypes from lib.libs.addonsettings import settings from lib.libs.pykodi import localize as L from lib.libs.utils import SortedDisplay, get_movie_path_list and context: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/addonsettings.py # DEFAULT_IMAGESIZE = '1' # AVAILABLE_IMAGESIZES = {'0': (10000, 10000, 600), '1': (1920, 1080, 600), '2': (1280, 720, 480)} # PROGRESS_DISPLAY_FULLPROGRESS = '0' # PROGRESS_DISPLAY_WARNINGSERRORS = '1' # PROGRESS_DISPLAY_NONE = '2' # Only add-on crashes # EXCLUSION_PATH_TYPE_FOLDER = '0' # EXCLUSION_PATH_TYPE_PREFIX = '1' # EXCLUSION_PATH_TYPE_REGEX = '2' # class Settings(object): # def __init__(self): # def update_useragent(self): # def update_settings(self): # def get_apikey(self, provider): # def get_apienabled(self, provider): # def get_api_config(self, provider): # def autoadd_episodes(self): # def autoadd_episodes(self, value): # def get_projectkey(provider): # # Path: lib/libs/pykodi.py # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result # # Path: lib/libs/utils.py # def natural_sort(string, split_regex=re.compile(r'([0-9]+)')): # def get_pathsep(path): # def parent_dir(path): # def get_simpledict_updates(original, newdict): # def get_movie_path_list(stackedpath): # def path_component(string): # def iter_possible_cleannames(originalname, uniqueslug=None): # def build_cleanest_name(originalname, uniqueslug=None): which might include code, classes, or functions. Output only the next line.
path = get_movie_path_list(mediaitem.file)[0]
Continue the code snippet: <|code_start|> ACTION_SELECTSERIES = 32400 # TODO: Don't use 'imdbnumber' class SeriesSelector(xbmcgui.WindowXMLDialog): def __init__(self, *args, **kwargs): super(SeriesSelector, self).__init__(args, kwargs) self.serieslist = kwargs.get('serieslist') self.originalselected = kwargs.get('selected', []) self.selected = [] self.guilist = None def prompt(self): self.doModal() return self.selected def onInit(self): <|code_end|> . Use current file imports: import xbmcgui from lib.libs.pykodi import localize as L and context (classes, functions, or code) from other files: # Path: lib/libs/pykodi.py # def localize(messageid): # if isinstance(messageid, basestring): # result = messageid # elif messageid >= 32000 and messageid < 33000: # result = get_main_addon().getLocalizedString(messageid) # else: # result = xbmc.getLocalizedString(messageid) # return result.encode('utf-8') if isinstance(result, unicode) else result . Output only the next line.
self.getControl(1).setLabel(L(ACTION_SELECTSERIES))
Here is a snippet: <|code_start|> # [0] method part, [1] list: properties, [2] dict: extra params typemap = {mediatypes.MOVIE: ('Movie', ['art', 'imdbnumber', 'file', 'premiered', 'uniqueid', 'setid'], None), mediatypes.MOVIESET: ('MovieSet', ['art'], {'movies': {'properties': ['art', 'file']}}), mediatypes.TVSHOW: ('TVShow', ['art', 'imdbnumber', 'season', 'file', 'premiered', 'uniqueid'], None), mediatypes.EPISODE: ('Episode', ['art', 'uniqueid', 'tvshowid', 'season', 'episode', 'file', 'showtitle'], None), mediatypes.SEASON: ('Season', ['season', 'art', 'tvshowid', 'showtitle'], None), mediatypes.MUSICVIDEO: ('MusicVideo', ['art', 'file', 'title', 'artist'], None), mediatypes.ARTIST: ('Artist', ['art', 'musicbrainzartistid'], None), mediatypes.ALBUM: ('Album', ['art', 'musicbrainzalbumid', 'musicbrainzreleasegroupid', 'musicbrainzalbumartistid', 'artist', 'artistid', 'title'], None), mediatypes.SONG: ('Song', ['art', 'musicbrainztrackid', 'musicbrainzalbumartistid', 'album', 'albumartist', 'albumartistid', 'albumid', 'file', 'disc', 'artist', 'title'], None)} def _needupgrade(mediatype): <|code_end|> . Write the next line using the current file imports: from itertools import chain from lib.libs import mediatypes, pykodi from lib.libs.pykodi import get_kodi_version, json, log and context from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): , which may include functions, classes, or code. Output only the next line.
return mediatype in (mediatypes.MOVIE, mediatypes.TVSHOW) and get_kodi_version() < 17
Here is a snippet: <|code_start|> def get_base_json_request(method): return {'jsonrpc': '2.0', 'method': method, 'params': {}, 'id': 1} def get_application_properties(properties): json_request = get_base_json_request('Application.GetProperties') json_request['params']['properties'] = properties json_result = pykodi.execute_jsonrpc(json_request) if check_json_result(json_result, None, json_request): return json_result['result'] def get_settingvalue(setting): json_request = get_base_json_request('Settings.GetSettingValue') json_request['params']['setting'] = setting json_result = pykodi.execute_jsonrpc(json_request) if check_json_result(json_result, None, json_request): return json_result['result']['value'] def check_json_result(json_result, result_key, json_request): if 'error' in json_result: raise JSONException(json_request, json_result) return 'result' in json_result and (not result_key or result_key in json_result['result']) class JSONException(Exception): def __init__(self, json_request, json_result): self.json_request = json_request self.json_result = json_result message = "There was an error with a JSON-RPC request.\nRequest: " <|code_end|> . Write the next line using the current file imports: from itertools import chain from lib.libs import mediatypes, pykodi from lib.libs.pykodi import get_kodi_version, json, log and context from other files: # Path: lib/libs/mediatypes.py # TVSHOW = 'tvshow' # MOVIE = 'movie' # EPISODE = 'episode' # SEASON = 'season' # MOVIESET = 'set' # MUSICVIDEO = 'musicvideo' # ARTIST = 'artist' # ALBUM = 'album' # SONG = 'song' # PREFERRED_SOURCE_SHARED = {'0': None, '1': 'fanart.tv'} # PREFERRED_SOURCE_MEDIA = {'tvshows': ('thetvdb.com', (TVSHOW, SEASON, EPISODE)), # 'movies': ('themoviedb.org', (MOVIE, MOVIESET)), # 'music': ('theaudiodb.com', audiotypes), # 'musicvideos': ('theaudiodb.com', (MUSICVIDEO,))} # def get_artinfo(mediatype, arttype): # def hack_mediaarttype(mediatype, arttype): # def disabled(mediatype): # def iter_every_arttype(mediatype): # def downloadartwork(mediatype, arttype): # def downloadanyartwork(mediatype): # def _split_arttype(arttype): # def generatethumb(mediatype): # def haspreferred_source(mediatype): # def ispreferred_source(mediatype, provider): # def only_filesystem(mediatype): # def update_settings(): # def _get_autolimit_from_setting(settingid): # def _set_allmulti(always_multi): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): # # Path: lib/libs/pykodi.py # ADDONID = 'script.artwork.beef' # def get_main_addon(): # def is_addon_watched(): # def get_kodi_version(): # def localize(messageid): # def get_conditional(conditional): # def get_infolabel(infolabel): # def execute_builtin(builtin_command): # def datetime_now(): # def datetime_strptime(date_string, format_string): # def execute_jsonrpc(jsonrpc_command): # def log(message, level=xbmc.LOGDEBUG, tag=None): # def scrub_message(message): # def set_log_scrubstring(key, string): # def get_language(language_format=xbmc.ENGLISH_NAME, region=False): # def unquoteimage(imagestring): # def quoteimage(imagestring): # def unquotearchive(filepath): # def get_command(*first_arg_keys): # def get_busydialog(): # def __init__(self, *args, **kwargs): # def get_setting(self, settingid): # def set_setting(self, settingid, value): # def __init__(self, *args, **kwargs): # def default(self, obj): # def __init__(self, *args, **kwargs): # def iterencode(self, obj, _one_shot=False): # def raw_decode(self, s, idx=0): # def _json_unicode_to_str(self, jsoninput): # def __init__(self): # def create(self): # def close(self): # def __del__(self): # class Addon(xbmcaddon.Addon): # class ObjectJSONEncoder(json.JSONEncoder): # class UTF8PrettyJSONEncoder(ObjectJSONEncoder): # class UTF8JSONDecoder(json.JSONDecoder): # class DialogBusy(object): , which may include functions, classes, or code. Output only the next line.
message += json.dumps(json_request, cls=pykodi.UTF8PrettyJSONEncoder)
Given the code snippet: <|code_start|> # Scrapy settings for crawler project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'crawler' SPIDER_MODULES = ['crawler.spiders'] NEWSPIDER_MODULE = 'crawler.spiders' RETRY_ENABLED = True RETRY_TIMES = 3 # Crawl responsibly by identifying yourself (and your website) on the user-agent # USER_AGENT = 'crawler (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) # CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs <|code_end|> , generate the next line using the imports in this file: from config import base_settings as bs and context (functions, classes, or occasionally code) from other files: # Path: config/base_settings.py # BASE_PATH = os.path.split(os.path.split(__file__)[0])[0] # OUTPUT_PATH = os.path.join(BASE_PATH, 'output') # OUTPUT_GROUP_PATH = os.path.join(OUTPUT_PATH, TimeUtil.getFormatTime('%Y%m%d_%H%M%S')) # DATABASE_NAME = os.path.join(OUTPUT_GROUP_PATH, 'Patent.db') # EXCEL_NAME = os.path.join(OUTPUT_GROUP_PATH, '专利.xlsx') # CHARTS_NAME = os.path.join(OUTPUT_GROUP_PATH, 'charts.html') # LOG_FILENAME = os.path.join(OUTPUT_GROUP_PATH, "PatentCrawler.log") # CAPTCHA_MODEL_NAME = os.path.join(BASE_PATH, 'res', 'captcha', 'sipo3.job') # AD_PATH = os.path.join(BASE_PATH, 'res', 'advertisement', 'ad.html') # USE_PROXY = False # PROXY_URL = 'http://127.0.0.1:5010/get' # TIMEOUT = 10 # DOWNLOAD_DELAY = 1 # OUTPUT_ITEMS = ['data', 'log', 'chart'] # USE_PROXY = use_proxy # PROXY_URL = proxy_url # TIMEOUT = timeout # DOWNLOAD_DELAY = delay # OUTPUT_ITEMS = output_items # def check_proxy(cfg): # def check_request(cfg: configparser.ConfigParser): # def check_output(cfg): . Output only the next line.
DOWNLOAD_DELAY = bs.DOWNLOAD_DELAY
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """ Created on 2018/3/14 @author: will4906 采集的内容、方式定义 """ class PatentId(BaseItem): is_required = True <|code_end|> using the current file's imports: from bs4 import BeautifulSoup from controller.url_config import url_search, url_detail, url_related_info, url_full_text from crawler.items import DataItem from entity.crawler_item import BaseItem, ResultItem and any relevant context from other files: # Path: controller/url_config.py # # Path: crawler/items.py # class DataItem: # # def __repr__(self): # return str(self.__dict__) # # Path: entity/crawler_item.py # class BaseItem: # # 是否必须参数,即无论用户在config.ini如何配置都会进行采集记录 # is_required = False # # 在url_config.py对应的url标志 # crawler_id = -1 # # 采集结果对应的中文名称 # chinese = None # # 采集结果对应的英文名称 # english = None # # 字段标题 # title = None # # 隶属表名称 # table_name = 'main' # # 字段名称 # field_names = None # # @classmethod # def set_title(cls, title): # if cls.title is None: # cls.title = title # # @classmethod # def get_chinese(cls): # """ # 如果中文为字符串,则直接返回,若为list则返回第一个元素 # :return: # """ # if isinstance(cls.chinese, str): # return cls.chinese # elif isinstance(cls.chinese, list): # return str(cls.chinese[0]) # # @classmethod # def check_chinese(cls, chinese): # if isinstance(cls.chinese, str): # if chinese == cls.chinese: # return True # else: # return False # elif isinstance(cls.chinese, list): # if chinese in cls.chinese: # cls.chinese = chinese # return True # else: # return False # # @classmethod # def check_english(cls, english): # if isinstance(cls.english, str): # if english == cls.english: # return True # else: # return False # elif isinstance(cls.english, list): # if english in cls.english: # cls.english = english # return True # else: # return False # # @classmethod # def get_english(cls): # """ # 如果英文为字符串,则直接返回,若为list则返回第一个元素 # :return: # """ # if isinstance(cls.english, str): # return cls.english # elif isinstance(cls.english, list): # return str(cls.english[0]) # # @classmethod # def parse(cls, raw, item, process=None): # """ # 数据解析函数 # :param raw: 原生内容 # :param item: scarpy采集的item # :param process: 如果非json则传递BeautifulSoup对象 # :return: # """ # pass # # class ResultItem: # """ # 储存采集结果的对象 # """ # def __init__(self, table='main', title=None, value=None): # self.table = table # self.title = title # self.value = value # # def __repr__(self): # return str(self.__dict__) . Output only the next line.
crawler_id = url_search.get('crawler_id')
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """ Created on 2018/3/14 @author: will4906 采集的内容、方式定义 """ class PatentId(BaseItem): is_required = True crawler_id = url_search.get('crawler_id') english = 'patent_id' chinese = ['专利标志', '专利id', '专利ID', '专利Id'] @classmethod def parse(cls, raw, item, process=None): if process is not None: patent_id = process.find(attrs={'name': 'idHidden'}).get('value') item.patent_id = ResultItem(title=cls.title, value=str(patent_id)) return item class PatentName(BaseItem): is_required = True <|code_end|> , predict the immediate next line with the help of imports: from bs4 import BeautifulSoup from controller.url_config import url_search, url_detail, url_related_info, url_full_text from crawler.items import DataItem from entity.crawler_item import BaseItem, ResultItem and context (classes, functions, sometimes code) from other files: # Path: controller/url_config.py # # Path: crawler/items.py # class DataItem: # # def __repr__(self): # return str(self.__dict__) # # Path: entity/crawler_item.py # class BaseItem: # # 是否必须参数,即无论用户在config.ini如何配置都会进行采集记录 # is_required = False # # 在url_config.py对应的url标志 # crawler_id = -1 # # 采集结果对应的中文名称 # chinese = None # # 采集结果对应的英文名称 # english = None # # 字段标题 # title = None # # 隶属表名称 # table_name = 'main' # # 字段名称 # field_names = None # # @classmethod # def set_title(cls, title): # if cls.title is None: # cls.title = title # # @classmethod # def get_chinese(cls): # """ # 如果中文为字符串,则直接返回,若为list则返回第一个元素 # :return: # """ # if isinstance(cls.chinese, str): # return cls.chinese # elif isinstance(cls.chinese, list): # return str(cls.chinese[0]) # # @classmethod # def check_chinese(cls, chinese): # if isinstance(cls.chinese, str): # if chinese == cls.chinese: # return True # else: # return False # elif isinstance(cls.chinese, list): # if chinese in cls.chinese: # cls.chinese = chinese # return True # else: # return False # # @classmethod # def check_english(cls, english): # if isinstance(cls.english, str): # if english == cls.english: # return True # else: # return False # elif isinstance(cls.english, list): # if english in cls.english: # cls.english = english # return True # else: # return False # # @classmethod # def get_english(cls): # """ # 如果英文为字符串,则直接返回,若为list则返回第一个元素 # :return: # """ # if isinstance(cls.english, str): # return cls.english # elif isinstance(cls.english, list): # return str(cls.english[0]) # # @classmethod # def parse(cls, raw, item, process=None): # """ # 数据解析函数 # :param raw: 原生内容 # :param item: scarpy采集的item # :param process: 如果非json则传递BeautifulSoup对象 # :return: # """ # pass # # class ResultItem: # """ # 储存采集结果的对象 # """ # def __init__(self, table='main', title=None, value=None): # self.table = table # self.title = title # self.value = value # # def __repr__(self): # return str(self.__dict__) . Output only the next line.
crawler_id = url_detail.get('crawler_id')
Predict the next line for this snippet: <|code_start|> crawler_id = url_detail.get('crawler_id') english = ['proposer_post_code', 'zip_code_of_the_applicant', 'proposer_zip_code'] chinese = '申请人邮编' @classmethod def parse(cls, raw, item, process=None): return push_item(process, item, 'proposer_zip_code', '申请人邮编') class CountryOfTheApplicant(BaseItem): crawler_id = url_detail.get('crawler_id') english = ['proposer_location', 'country_of_the_applicant', 'country_of_the_assignee'] chinese = ['申请人所在国(省)', '申请人所在地'] @classmethod def parse(cls, raw, item, process=None): return push_item(process, item, 'proposer_location', '申请人所在国(省)') class CpcClassificationNumber(BaseItem): crawler_id = url_detail.get('crawler_id') english = ['cpc_class_number', 'cpc', 'CPC', 'Cpc'] chinese = 'CPC分类号' @classmethod def parse(cls, raw, item, process=None): return push_item(process, item, 'cpc_class_number', 'CPC分类号') class Cognation(BaseItem): <|code_end|> with the help of current file imports: from bs4 import BeautifulSoup from controller.url_config import url_search, url_detail, url_related_info, url_full_text from crawler.items import DataItem from entity.crawler_item import BaseItem, ResultItem and context from other files: # Path: controller/url_config.py # # Path: crawler/items.py # class DataItem: # # def __repr__(self): # return str(self.__dict__) # # Path: entity/crawler_item.py # class BaseItem: # # 是否必须参数,即无论用户在config.ini如何配置都会进行采集记录 # is_required = False # # 在url_config.py对应的url标志 # crawler_id = -1 # # 采集结果对应的中文名称 # chinese = None # # 采集结果对应的英文名称 # english = None # # 字段标题 # title = None # # 隶属表名称 # table_name = 'main' # # 字段名称 # field_names = None # # @classmethod # def set_title(cls, title): # if cls.title is None: # cls.title = title # # @classmethod # def get_chinese(cls): # """ # 如果中文为字符串,则直接返回,若为list则返回第一个元素 # :return: # """ # if isinstance(cls.chinese, str): # return cls.chinese # elif isinstance(cls.chinese, list): # return str(cls.chinese[0]) # # @classmethod # def check_chinese(cls, chinese): # if isinstance(cls.chinese, str): # if chinese == cls.chinese: # return True # else: # return False # elif isinstance(cls.chinese, list): # if chinese in cls.chinese: # cls.chinese = chinese # return True # else: # return False # # @classmethod # def check_english(cls, english): # if isinstance(cls.english, str): # if english == cls.english: # return True # else: # return False # elif isinstance(cls.english, list): # if english in cls.english: # cls.english = english # return True # else: # return False # # @classmethod # def get_english(cls): # """ # 如果英文为字符串,则直接返回,若为list则返回第一个元素 # :return: # """ # if isinstance(cls.english, str): # return cls.english # elif isinstance(cls.english, list): # return str(cls.english[0]) # # @classmethod # def parse(cls, raw, item, process=None): # """ # 数据解析函数 # :param raw: 原生内容 # :param item: scarpy采集的item # :param process: 如果非json则传递BeautifulSoup对象 # :return: # """ # pass # # class ResultItem: # """ # 储存采集结果的对象 # """ # def __init__(self, table='main', title=None, value=None): # self.table = table # self.title = title # self.value = value # # def __repr__(self): # return str(self.__dict__) , which may contain function names, class names, or code. Output only the next line.
crawler_id = url_related_info.get('crawler_id')
Predict the next line for this snippet: <|code_start|> crawler_id = url_related_info.get('crawler_id') table_name = 'law_state' english = 'law_state_list' chinese = '法律状态表' title = ['法律状态', '法律状态时间'] @classmethod def set_title(cls, title): if title == cls.english: cls.title = ['law_status', 'law_status_date'] elif title == cls.chinese: cls.title = ['法律状态', '法律状态时间'] @classmethod def parse(cls, raw, item, process=None): if process is not None: law_state_list = process.get('lawStateList') if law_state_list is not None: tmp_list = [] for law in law_state_list: mean = law.get('lawStateCNMeaning') law_date = law.get('prsDate') part = (ResultItem(table=cls.table_name, title=cls.title[0], value=mean), ResultItem(table=cls.table_name, title=cls.title[1], value=law_date)) tmp_list.append(part) item.law_state_list = tmp_list return item class FullText(BaseItem): <|code_end|> with the help of current file imports: from bs4 import BeautifulSoup from controller.url_config import url_search, url_detail, url_related_info, url_full_text from crawler.items import DataItem from entity.crawler_item import BaseItem, ResultItem and context from other files: # Path: controller/url_config.py # # Path: crawler/items.py # class DataItem: # # def __repr__(self): # return str(self.__dict__) # # Path: entity/crawler_item.py # class BaseItem: # # 是否必须参数,即无论用户在config.ini如何配置都会进行采集记录 # is_required = False # # 在url_config.py对应的url标志 # crawler_id = -1 # # 采集结果对应的中文名称 # chinese = None # # 采集结果对应的英文名称 # english = None # # 字段标题 # title = None # # 隶属表名称 # table_name = 'main' # # 字段名称 # field_names = None # # @classmethod # def set_title(cls, title): # if cls.title is None: # cls.title = title # # @classmethod # def get_chinese(cls): # """ # 如果中文为字符串,则直接返回,若为list则返回第一个元素 # :return: # """ # if isinstance(cls.chinese, str): # return cls.chinese # elif isinstance(cls.chinese, list): # return str(cls.chinese[0]) # # @classmethod # def check_chinese(cls, chinese): # if isinstance(cls.chinese, str): # if chinese == cls.chinese: # return True # else: # return False # elif isinstance(cls.chinese, list): # if chinese in cls.chinese: # cls.chinese = chinese # return True # else: # return False # # @classmethod # def check_english(cls, english): # if isinstance(cls.english, str): # if english == cls.english: # return True # else: # return False # elif isinstance(cls.english, list): # if english in cls.english: # cls.english = english # return True # else: # return False # # @classmethod # def get_english(cls): # """ # 如果英文为字符串,则直接返回,若为list则返回第一个元素 # :return: # """ # if isinstance(cls.english, str): # return cls.english # elif isinstance(cls.english, list): # return str(cls.english[0]) # # @classmethod # def parse(cls, raw, item, process=None): # """ # 数据解析函数 # :param raw: 原生内容 # :param item: scarpy采集的item # :param process: 如果非json则传递BeautifulSoup对象 # :return: # """ # pass # # class ResultItem: # """ # 储存采集结果的对象 # """ # def __init__(self, table='main', title=None, value=None): # self.table = table # self.title = title # self.value = value # # def __repr__(self): # return str(self.__dict__) , which may contain function names, class names, or code. Output only the next line.
crawler_id = url_full_text.get('crawler_id')