Prompt:
Implement the Python class `LoginSMSForm` described below.

Class description:
添加手机号字段

Method signatures and docstrings:
- def clean_mobile_phone(self): 校验手机号
- def clean_code(self): 校验验证码

Implement the Python class `LoginSMSForm` described below.

Class description:
添加手机号字段

Method signatures and docstrings:
- def clean_mobile_phone(self): 校验手机号
- def clean_code(self): 校验验证码

<|skeleton|>
class LoginSMSForm:
    """添加手机号字段"""

    def clean_mobile_phone(self):
        """校验手机号"""
        <|body_0|>

    def clean_code(self):
        """校验验证码"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        mobile_phone = self.cleaned_data['mobile_phone']
        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if not exists:
            raise ValidationError('手机号未注册,请先注册')
        return mobile_phone
<|end_body_0|>

<|body_start_1|>
        code = self.cleaned_data['code']
        mobile_phone = self.cleaned_data.get('mobile_phone')
        if not mobile_phone:
            return code
        pool = redis.ConnectionPool(host='127.0.0.1', port=6379, encoding='utf-8', max_connections=1000)
        conn = redis.Redis(connection_pool=pool)
        redis_code = conn.get(mobile_phone)
        if not redis_code:
            raise ValidationError('验证码失效或未发送，请重新发送')
        redis_str_code = redis_code.decode('utf-8')
        if code.strip() != redis_str_code:
            raise ValidationError('验证码错误，请重新输入')
        return code
<|end_body_1|>

Solution:
class LoginSMSForm:
    """添加手机号字段"""

    def clean_mobile_phone(self):
        """校验手机号"""
        mobile_phone = self.cleaned_data['mobile_phone']
        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if not exists:
            raise ValidationError('手机号未注册,请先注册')
        return mobile_phone

    def clean_code(self):
        """校验验证码"""
        code = self.cleaned_data['code']
        mobile_phone = self.cleaned_data.get('mobile_phone')
        if not mobile_phone:
            return code
        pool = redis.ConnectionPool(host='127.0.0.1', port=6379, encoding='utf-8', max_connections=1000)
        conn = redis.Redis(connection_pool=pool)
        redis_code = conn.get(mobile_phone)
        if not redis_code:
            raise ValidationError('验证码失效或未发送，请重新发送')
        redis_str_code = redis_code.decode('utf-8')
        if code.strip() != redis_str_code:
            raise ValidationError('验证码错误，请重新输入')
        return code


read

Prompt:
Implement the Python class `IERS_A` described below.

Class description:
IERS Table class targeted to IERS A, provided by USNO. These include rapid turnaround and predicted times. See http://maia.usno.navy.mil/ Notes ----- The IERS A file is not part of astropy. It can be downloaded from `iers.IERS_A_URL`. See `iers.__doc__` for instructions on how to use it in `Time`, etc.

Method signatures and docstrings:
- def __init__(self, table): Initialize an IERS-A table that is already read in. Use read or open class methods to read it from disk. Combines UT1-UTC values, taking UT1_UTC_B if available, else UT1_UTC_A
- def read(cls, file=IERS_A_FILE, readme=None): Read IERS-A table from a finals2000a.* file provided by USNO. Parameters ---------- file : str full path to ascii file holding IERS-A data (default: `iers.IERS_A_FILE`) readme : str full path to ascii file holding CDS-style readme (default: package version, `iers.IERS_A_README`) Returns ------- `IERS_A` class instance
- def ut1_utc_source(self, i): Set UT1-UTC source flag for entries in IERS table
- def pm_source(self, i): Set polar motion source flag for entries in IERS table

Implement the Python class `IERS_A` described below.

Class description:
IERS Table class targeted to IERS A, provided by USNO. These include rapid turnaround and predicted times. See http://maia.usno.navy.mil/ Notes ----- The IERS A file is not part of astropy. It can be downloaded from `iers.IERS_A_URL`. See `iers.__doc__` for instructions on how to use it in `Time`, etc.

Method signatures and docstrings:
- def __init__(self, table): Initialize an IERS-A table that is already read in. Use read or open class methods to read it from disk. Combines UT1-UTC values, taking UT1_UTC_B if available, else UT1_UTC_A
- def read(cls, file=IERS_A_FILE, readme=None): Read IERS-A table from a finals2000a.* file provided by USNO. Parameters ---------- file : str full path to ascii file holding IERS-A data (default: `iers.IERS_A_FILE`) readme : str full path to ascii file holding CDS-style readme (default: package version, `iers.IERS_A_README`) Returns ------- `IERS_A` class instance
- def ut1_utc_source(self, i): Set UT1-UTC source flag for entries in IERS table
- def pm_source(self, i): Set polar motion source flag for entries in IERS table

<|skeleton|>
class IERS_A:
    """IERS Table class targeted to IERS A, provided by USNO. These include rapid turnaround and predicted times. See http://maia.usno.navy.mil/ Notes ----- The IERS A file is not part of astropy. It can be downloaded from `iers.IERS_A_URL`. See `iers.__doc__` for instructions on how to use it in `Time`, etc."""

    def __init__(self, table):
        """Initialize an IERS-A table that is already read in. Use read or open class methods to read it from disk. Combines UT1-UTC values, taking UT1_UTC_B if available, else UT1_UTC_A"""
        <|body_0|>

    def read(cls, file=IERS_A_FILE, readme=None):
        """Read IERS-A table from a finals2000a.* file provided by USNO. Parameters ---------- file : str full path to ascii file holding IERS-A data (default: `iers.IERS_A_FILE`) readme : str full path to ascii file holding CDS-style readme (default: package version, `iers.IERS_A_README`) Returns ------- `IERS_A` class instance"""
        <|body_1|>

    def ut1_utc_source(self, i):
        """Set UT1-UTC source flag for entries in IERS table"""
        <|body_2|>

    def pm_source(self, i):
        """Set polar motion source flag for entries in IERS table"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        table['UT1_UTC'] = np.where(table['UT1_UTC_B'].mask, table['UT1_UTC_A'].data, table['UT1_UTC_B'].data)
        table['UT1_UTC'].unit = table['UT1_UTC_A'].unit
        table['UT1Flag'] = np.where(table['UT1_UTC_B'].mask, table['UT1Flag_A'].data, 'B')
        table['PM_x'] = np.where(table['PM_X_B'].mask, table['PM_x_A'].data, table['PM_X_B'].data)
        table['PM_x'].unit = table['PM_x_A'].unit
        table['PM_y'] = np.where(table['PM_Y_B'].mask, table['PM_y_A'].data, table['PM_Y_B'].data)
        table['PM_y'].unit = table['PM_y_A'].unit
        table['PolPMFlag'] = np.where(table['PM_X_B'].mask, table['PolPMFlag_A'].data, 'B')
        super(IERS_A, self).__init__(table.filled())
<|end_body_0|>

<|body_start_1|>
        if readme is None:
            readme = IERS_A_README
        iers_a = Table.read(file, format='cds', readme=readme)
        return cls(iers_a[~iers_a['UT1_UTC_A'].mask & ~iers_a['PolPMFlag_A'].mask])
<|end_body_1|>

<|body_start_2|>
        ut1flag = self['UT1Flag'][i]
        source = np.ones_like(i) * FROM_IERS_B
        source[ut1flag == 'I'] = FROM_IERS_A
        source[ut1flag == 'P'] = FROM_IERS_A_PREDICTION
        return source
<|end_body_2|>

<|body_start_3|>
        pmflag = self['PolPMFlag'][i]
        source = np.ones_like(i) * FROM_IERS_B
        source[pmflag == 'I'] = FROM_IERS_A
        source[pmflag == 'P'] = FROM_IERS_A_PREDICTION
        return source
<|end_body_3|>

Solution:
class IERS_A:
    """IERS Table class targeted to IERS A, provided by USNO. These include rapid turnaround and predicted times. See http://maia.usno.navy.mil/ Notes ----- The IERS A file is not part of astropy. It can be downloaded from `iers.IERS_A_URL`. See `iers.__doc__` for instructions on how to use it in `Time`, etc."""

    def __init__(self, table):
        """Initialize an IERS-A table that is already read in. Use read or open class methods to read it from disk. Combines UT1-UTC values, taking UT1_UTC_B if available, else UT1_UTC_A"""
        table['UT1_UTC'] = np.where(table['UT1_UTC_B'].mask, table['UT1_UTC_A'].data, table['UT1_UTC_B'].data)
        table['UT1_UTC'].unit = table['UT1_UTC_A'].unit
        table['UT1Flag'] = np.where(table['UT1_UTC_B'].mask, table['UT1Flag_A'].data, 'B')
        table['PM_x'] = np.where(table['PM_X_B'].mask, table['PM_x_A'].data, table['PM_X_B'].data)
        table['PM_x'].unit = table['PM_x_A'].unit
        table['PM_y'] = np.where(table['PM_Y_B'].mask, table['PM_y_A'].data, table['PM_Y_B'].data)
        table['PM_y'].unit = table['PM_y_A'].unit
        table['PolPMFlag'] = np.where(table['PM_X_B'].mask, table['PolPMFlag_A'].data, 'B')
        super(IERS_A, self).__init__(table.filled())

    def read(cls, file=IERS_A_FILE, readme=None):
        """Read IERS-A table from a finals2000a.* file provided by USNO. Parameters ---------- file : str full path to ascii file holding IERS-A data (default: `iers.IERS_A_FILE`) readme : str full path to ascii file holding CDS-style readme (default: package version, `iers.IERS_A_README`) Returns ------- `IERS_A` class instance"""
        if readme is None:
            readme = IERS_A_README
        iers_a = Table.read(file, format='cds', readme=readme)
        return cls(iers_a[~iers_a['UT1_UTC_A'].mask & ~iers_a['PolPMFlag_A'].mask])

    def ut1_utc_source(self, i):
        """Set UT1-UTC source flag for entries in IERS table"""
        ut1flag = self['UT1Flag'][i]
        source = np.ones_like(i) * FROM_IERS_B
        source[ut1flag == 'I'] = FROM_IERS_A
        source[ut1flag == 'P'] = FROM_IERS_A_PREDICTION
        return source

    def pm_source(self, i):
        """Set polar motion source flag for entries in IERS table"""
        pmflag = self['PolPMFlag'][i]
        source = np.ones_like(i) * FROM_IERS_B
        source[pmflag == 'I'] = FROM_IERS_A
        source[pmflag == 'P'] = FROM_IERS_A_PREDICTION
        return source


start

Prompt:
Implement the Python class `QChatCLIRPCClient` described below.

Class description:
Simple RPC client that sends messages to an RPCServer

Method signatures and docstrings:
- def __init__(self, user, destination, server_url): Initializes the RPC client :param user: str The user we wish to send a message as :param destination: str The peer we wish to send a message to :param server_url: str The RPCServer url to connect to, eg. http://127.0.0.1:6666
- def start(self): Starts the RPC client and sends messages based on user input :return: None
- def stop(self): Stops the RPC Client :return: None
- def _read_messages(self): Polls the RPCServer for messages that belong to the user running the RPC client :return: None

Implement the Python class `QChatCLIRPCClient` described below.

Class description:
Simple RPC client that sends messages to an RPCServer

Method signatures and docstrings:
- def __init__(self, user, destination, server_url): Initializes the RPC client :param user: str The user we wish to send a message as :param destination: str The peer we wish to send a message to :param server_url: str The RPCServer url to connect to, eg. http://127.0.0.1:6666
- def start(self): Starts the RPC client and sends messages based on user input :return: None
- def stop(self): Stops the RPC Client :return: None
- def _read_messages(self): Polls the RPCServer for messages that belong to the user running the RPC client :return: None

<|skeleton|>
class QChatCLIRPCClient:
    """Simple RPC client that sends messages to an RPCServer"""

    def __init__(self, user, destination, server_url):
        """Initializes the RPC client :param user: str The user we wish to send a message as :param destination: str The peer we wish to send a message to :param server_url: str The RPCServer url to connect to, eg. http://127.0.0.1:6666"""
        <|body_0|>

    def start(self):
        """Starts the RPC client and sends messages based on user input :return: None"""
        <|body_1|>

    def stop(self):
        """Stops the RPC Client :return: None"""
        <|body_2|>

    def _read_messages(self):
        """Polls the RPCServer for messages that belong to the user running the RPC client :return: None"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        self.client = xmlrpc.client.ServerProxy(server_url)
        self.user = user
        self.destination = destination
        self._running = False
        self._message_reader = threading.Thread(target=self._read_messages)
        self.lock = threading.Lock()
        self.logger = QChatLogger('QChatCLIRPCClient-{}'.format(user))
<|end_body_0|>

<|body_start_1|>
        print('Hello, this is {}'.format(self.user))
        self._running = True
        self._message_reader.start()
        while self._running:
            input_text = input('\n[ {} ]: '.format(self.user))
            the_message = '{} @ {}'.format(input_text, time.time())
            with self.lock:
                self.client.send_message(self.user, self.destination, the_message)
<|end_body_1|>

<|body_start_2|>
        self.logger.info('Stopping the CLI RPC Client')
        self._running = False
        self._message_reader.join()
<|end_body_2|>

<|body_start_3|>
        while self._running:
            try:
                with self.lock:
                    user_messages = self.client.get_messages(self.user)
                if user_messages:
                    print('\n')
                    for sender, messages in user_messages.items():
                        for message in messages:
                            print('[ {} ]: {}\n'.format(sender, message))
                    print('[ {} ]: '.format(self.user), end='')
            except Exception:
                self.logger.exception('Failed getting messages for {}'.format(self.user))
                time.sleep(2)
            time.sleep(1)
<|end_body_3|>

Solution:
class QChatCLIRPCClient:
    """Simple RPC client that sends messages to an RPCServer"""

    def __init__(self, user, destination, server_url):
        """Initializes the RPC client :param user: str The user we wish to send a message as :param destination: str The peer we wish to send a message to :param server_url: str The RPCServer url to connect to, eg. http://127.0.0.1:6666"""
        self.client = xmlrpc.client.ServerProxy(server_url)
        self.user = user
        self.destination = destination
        self._running = False
        self._message_reader = threading.Thread(target=self._read_messages)
        self.lock = threading.Lock()
        self.logger = QChatLogger('QChatCLIRPCClient-{}'.format(user))

    def start(self):
        """Starts the RPC client and sends messages based on user input :return: None"""
        print('Hello, this is {}'.format(self.user))
        self._running = True
        self._message_reader.start()
        while self._running:
            input_text = input('\n[ {} ]: '.format(self.user))
            the_message = '{} @ {}'.format(input_text, time.time())
            with self.lock:
                self.client.send_message(self.user, self.destination, the_message)

    def stop(self):
        """Stops the RPC Client :return: None"""
        self.logger.info('Stopping the CLI RPC Client')
        self._running = False
        self._message_reader.join()

    def _read_messages(self):
        """Polls the RPCServer for messages that belong to the user running the RPC client :return: None"""
        while self._running:
            try:
                with self.lock:
                    user_messages = self.client.get_messages(self.user)
                if user_messages:
                    print('\n')
                    for sender, messages in user_messages.items():
                        for message in messages:
                            print('[ {} ]: {}\n'.format(sender, message))
                    print('[ {} ]: '.format(self.user), end='')
            except Exception:
                self.logger.exception('Failed getting messages for {}'.format(self.user))
                time.sleep(2)
            time.sleep(1)


list

Prompt:
Implement the Python class `IngestsStatusView` described below.

Class description:
This view is the endpoint for retrieving summarized ingest status.

Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def list(self, request): Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def list_impl(self, request): Retrieves the ingest status information and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user

Implement the Python class `IngestsStatusView` described below.

Class description:
This view is the endpoint for retrieving summarized ingest status.

Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def list(self, request): Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
- def list_impl(self, request): Retrieves the ingest status information and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user

<|skeleton|>
class IngestsStatusView:
    """This view is the endpoint for retrieving summarized ingest status."""

    def get_serializer_class(self):
        """Returns the appropriate serializer based off the requests version of the REST API"""
        <|body_0|>

    def list(self, request):
        """Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        <|body_1|>

    def list_impl(self, request):
        """Retrieves the ingest status information and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if self.request.version == 'v6':
            return IngestStatusSerializerV6
        elif self.request.version == 'v7':
            return IngestStatusSerializerV6
<|end_body_0|>

<|body_start_1|>
        if request.version == 'v6' or request.version == 'v7':
            return self.list_impl(request)
        raise Http404()
<|end_body_1|>

<|body_start_2|>
        started = rest_util.parse_timestamp(request, 'started', required=False)
        ended = rest_util.parse_timestamp(request, 'ended', required=False)
        rest_util.check_time_range(started, ended, max_duration=datetime.timedelta(days=31))
        use_ingest_time = rest_util.parse_bool(request, 'use_ingest_time', default_value=False)
        ingests = Ingest.objects.get_status(started, ended, use_ingest_time)
        page = self.paginate_queryset(ingests)
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)
<|end_body_2|>

Solution:
class IngestsStatusView:
    """This view is the endpoint for retrieving summarized ingest status."""

    def get_serializer_class(self):
        """Returns the appropriate serializer based off the requests version of the REST API"""
        if self.request.version == 'v6':
            return IngestStatusSerializerV6
        elif self.request.version == 'v7':
            return IngestStatusSerializerV6

    def list(self, request):
        """Determine api version and call specific method :param request: the HTTP POST request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        if request.version == 'v6' or request.version == 'v7':
            return self.list_impl(request)
        raise Http404()

    def list_impl(self, request):
        """Retrieves the ingest status information and returns it in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user"""
        started = rest_util.parse_timestamp(request, 'started', required=False)
        ended = rest_util.parse_timestamp(request, 'ended', required=False)
        rest_util.check_time_range(started, ended, max_duration=datetime.timedelta(days=31))
        use_ingest_time = rest_util.parse_bool(request, 'use_ingest_time', default_value=False)
        ingests = Ingest.objects.get_status(started, ended, use_ingest_time)
        page = self.paginate_queryset(ingests)
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)


Prompt:
Implement the Python class `Seeing` described below.

Class description:
Measures seeing on reduced images with a catalog.

Method signatures and docstrings:
- def __init__(self, sources: Optional[Union[str, List[str]]]=None, publisher: Optional[Union[Publisher, Dict[str, Any]]]=None, max_ellipticity: float=0.2, correct_for_airmass: bool=True, **kwargs: Any): Creates a new seeing estimator. Args: sources: List of sources (e.g. cameras) to process images from or None for all. publisher: Publisher to publish results to. max_ellipticity: Maximum ellipticity for sources to consider. correct_for_zenith: Whether to correct seeing for airmass.
- async def open(self) -> None: Open module.
- async def process_new_image_event(self, event: Event, sender: str) -> bool: Puts a new images in the DB with the given ID. Args: event: New image event sender: Who sent the event? Returns: Success

Implement the Python class `Seeing` described below.

Class description:
Measures seeing on reduced images with a catalog.

Method signatures and docstrings:
- def __init__(self, sources: Optional[Union[str, List[str]]]=None, publisher: Optional[Union[Publisher, Dict[str, Any]]]=None, max_ellipticity: float=0.2, correct_for_airmass: bool=True, **kwargs: Any): Creates a new seeing estimator. Args: sources: List of sources (e.g. cameras) to process images from or None for all. publisher: Publisher to publish results to. max_ellipticity: Maximum ellipticity for sources to consider. correct_for_zenith: Whether to correct seeing for airmass.
- async def open(self) -> None: Open module.
- async def process_new_image_event(self, event: Event, sender: str) -> bool: Puts a new images in the DB with the given ID. Args: event: New image event sender: Who sent the event? Returns: Success

<|skeleton|>
class Seeing:
    """Measures seeing on reduced images with a catalog."""

    def __init__(self, sources: Optional[Union[str, List[str]]]=None, publisher: Optional[Union[Publisher, Dict[str, Any]]]=None, max_ellipticity: float=0.2, correct_for_airmass: bool=True, **kwargs: Any):
        """Creates a new seeing estimator. Args: sources: List of sources (e.g. cameras) to process images from or None for all. publisher: Publisher to publish results to. max_ellipticity: Maximum ellipticity for sources to consider. correct_for_zenith: Whether to correct seeing for airmass."""
        <|body_0|>

    async def open(self) -> None:
        """Open module."""
        <|body_1|>

    async def process_new_image_event(self, event: Event, sender: str) -> bool:
        """Puts a new images in the DB with the given ID. Args: event: New image event sender: Who sent the event? Returns: Success"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        Module.__init__(self, **kwargs)
        self._sources = [sources] if isinstance(sources, str) else sources
        self._publisher = self.add_child_object(publisher, Publisher)
        self._max_ellipticity = max_ellipticity
        self._correct_for_airmass = correct_for_airmass
<|end_body_0|>

<|body_start_1|>
        await Module.open(self)
        log.info('Subscribing to new image events...')
        await self.comm.register_event(NewImageEvent, self.process_new_image_event)
<|end_body_1|>

<|body_start_2|>
        if not isinstance(event, NewImageEvent):
            return False
        if self._sources is not None and sender not in self._sources:
            return False
        log.info('Received new image event from %s.', sender)
        try:
            log.info('Downloading file %s...', event.filename)
            image = await self.vfs.read_image(event.filename)
        except FileNotFoundError:
            log.error('Could not download image.')
            return False
        cat = image.catalog
        if cat is None:
            return False
        cat = cat[cat['ellipticity'] < self._max_ellipticity]
        wcs = WCS(image.header)
        pix_size = abs(proj_plane_pixel_scales(wcs)[0] * 3600.0)
        seeing = np.mean(cat['fwhm']) * pix_size
        if self._correct_for_airmass:
            if 'AIRMASS' in image.header:
                seeing /= image.header['AIRMASS'] ** 0.6
            else:
                return False
        if self._publisher is not None:
            await self._publisher(time=Time.now().isot, seeing=seeing)
        return True
<|end_body_2|>

Solution:
class Seeing:
    """Measures seeing on reduced images with a catalog."""

    def __init__(self, sources: Optional[Union[str, List[str]]]=None, publisher: Optional[Union[Publisher, Dict[str, Any]]]=None, max_ellipticity: float=0.2, correct_for_airmass: bool=True, **kwargs: Any):
        """Creates a new seeing estimator. Args: sources: List of sources (e.g. cameras) to process images from or None for all. publisher: Publisher to publish results to. max_ellipticity: Maximum ellipticity for sources to consider. correct_for_zenith: Whether to correct seeing for airmass."""
        Module.__init__(self, **kwargs)
        self._sources = [sources] if isinstance(sources, str) else sources
        self._publisher = self.add_child_object(publisher, Publisher)
        self._max_ellipticity = max_ellipticity
        self._correct_for_airmass = correct_for_airmass

    async def open(self) -> None:
        """Open module."""
        await Module.open(self)
        log.info('Subscribing to new image events...')
        await self.comm.register_event(NewImageEvent, self.process_new_image_event)

    async def process_new_image_event(self, event: Event, sender: str) -> bool:
        """Puts a new images in the DB with the given ID. Args: event: New image event sender: Who sent the event? Returns: Success"""
        if not isinstance(event, NewImageEvent):
            return False
        if self._sources is not None and sender not in self._sources:
            return False
        log.info('Received new image event from %s.', sender)
        try:
            log.info('Downloading file %s...', event.filename)
            image = await self.vfs.read_image(event.filename)
        except FileNotFoundError:
            log.error('Could not download image.')
            return False
        cat = image.catalog
        if cat is None:
            return False
        cat = cat[cat['ellipticity'] < self._max_ellipticity]
        wcs = WCS(image.header)
        pix_size = abs(proj_plane_pixel_scales(wcs)[0] * 3600.0)
        seeing = np.mean(cat['fwhm']) * pix_size
        if self._correct_for_airmass:
            if 'AIRMASS' in image.header:
                seeing /= image.header['AIRMASS'] ** 0.6
            else:
                return False
        if self._publisher is not None:
            await self._publisher(time=Time.now().isot, seeing=seeing)
        return True


Prompt:
Implement the Python class `ServerRecvChannel` described below.

Class description:
Creates a server recv channel for pingpong and gossip

Method signatures and docstrings:
- def __init__(self, uid, callback_obj, callback_obj_gossip, port, ip, chunks_size=1024): Initialize callbacks, parameters and create tcp/udp sockets
- async def tcp_listen(self): Wait for tcp connections to arrive
- async def udp_listen(self): Wait until udp message arrives.
- async def udp_response(self, data, addr): Create udp response and send it.
- async def tcp_response(self, conn): Receive tcp stream, create response and send it
- async def check_msg(self, res): Determine message type and create response message accordingly

Implement the Python class `ServerRecvChannel` described below.

Class description:
Creates a server recv channel for pingpong and gossip

Method signatures and docstrings:
- def __init__(self, uid, callback_obj, callback_obj_gossip, port, ip, chunks_size=1024): Initialize callbacks, parameters and create tcp/udp sockets
- async def tcp_listen(self): Wait for tcp connections to arrive
- async def udp_listen(self): Wait until udp message arrives.
- async def udp_response(self, data, addr): Create udp response and send it.
- async def tcp_response(self, conn): Receive tcp stream, create response and send it
- async def check_msg(self, res): Determine message type and create response message accordingly

<|skeleton|>
class ServerRecvChannel:
    """Creates a server recv channel for pingpong and gossip"""

    def __init__(self, uid, callback_obj, callback_obj_gossip, port, ip, chunks_size=1024):
        """Initialize callbacks, parameters and create tcp/udp sockets"""
        <|body_0|>

    async def tcp_listen(self):
        """Wait for tcp connections to arrive"""
        <|body_1|>

    async def udp_listen(self):
        """Wait until udp message arrives."""
        <|body_2|>

    async def udp_response(self, data, addr):
        """Create udp response and send it."""
        <|body_3|>

    async def tcp_response(self, conn):
        """Receive tcp stream, create response and send it"""
        <|body_4|>

    async def check_msg(self, res):
        """Determine message type and create response message accordingly"""
        <|body_5|>

<|end_skeleton|>

<|body_start_0|>
        self.uid = uid.encode()
        self.cb_obj = callback_obj
        self.cb_obj_gossip = callback_obj_gossip
        self.port = port
        self.chunks_size = chunks_size
        self.loop = asyncio.get_event_loop()
        self.udp_sock = UdpSender(self.loop, ip, int(port))
        self.token_size = 2 * struct.calcsize('i') + struct.calcsize('17s')
        self.tokens = {}
        self.tc_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tc_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.tc_sock.setblocking(False)
        self.tc_sock.bind((ip, int(port)))
        self.tc_sock.listen()
<|end_body_0|>

<|body_start_1|>
        print('Listening for tcp connections')
        while True:
            conn, addr = await self.loop.sock_accept(self.tc_sock)
            if __debug__:
                print('{} got tcp connection from {}'.format(self.port, addr))
            asyncio.ensure_future(self.tcp_response(conn))
<|end_body_1|>

<|body_start_2|>
        print('Listening for udp connections')
        while True:
            data, addr = await self.udp_sock.recvfrom(self.chunks_size)
            if __debug__:
                print('{} got udp request from {}'.format(self.port, addr))
            asyncio.ensure_future(self.udp_response(data, addr))
<|end_body_2|>

<|body_start_3|>
        response = await self.check_msg(data)
        if response:
            await self.udp_sock.sendto(response, addr)
<|end_body_3|>

<|body_start_4|>
        int_size = struct.calcsize('i')
        recv_msg_size = await self.loop.sock_recv(conn, int_size)
        try:
            msg_size = struct.unpack('i', recv_msg_size)[0]
        except Exception as e:
            conn.close()
            return
        res = b''
        while len(res) < msg_size:
            res += await self.loop.sock_recv(conn, self.chunks_size)
            await asyncio.sleep(0)
        response = await self.check_msg(res)
        response_stream = io.BytesIO(response)
        stream = True
        while stream:
            stream = response_stream.read(self.chunks_size)
            try:
                await self.loop.sock_sendall(conn, stream)
            except Exception as e:
                conn.close()
                return
        conn.close()
        if __debug__:
            print('Connection closed')
<|end_body_4|>

<|body_start_5|>
        token = res[:self.token_size]
        payload = res[self.token_size:]
        msg_type, msg_cntr, sender = struct.unpack('ii17s', token)
        if sender not in self.tokens.keys():
            if __debug__:
                print('Add new token')
            self.tokens[sender] = 0
        if self.tokens[sender] != msg_cntr:
            self.tokens[sender] = msg_cntr
            token = struct.pack('ii17s', msg_type, self.tokens[sender], self.uid)
            if msg_type == 0:
                if payload:
                    new_msg = await self.cb_obj.arrival(sender, payload)
                    if new_msg:
                        response = token + new_msg if new_msg else token
                    else:
                        response = token
                else:
                    response = token
            elif msg_type == 1:
                await self.cb_obj_gossip.arrival(sender, payload)
                response = token
        else:
            if __debug__:
                print('NO TOKEN ARRIVAL')
            token = struct.pack('ii17s', msg_type, self.tokens[sender], self.uid)
            response = token
        return response
<|end_body_5|>

Solution:
class ServerRecvChannel:
    """Creates a server recv channel for pingpong and gossip"""

    def __init__(self, uid, callback_obj, callback_obj_gossip, port, ip, chunks_size=1024):
        """Initialize callbacks, parameters and create tcp/udp sockets"""
        self.uid = uid.encode()
        self.cb_obj = callback_obj
        self.cb_obj_gossip = callback_obj_gossip
        self.port = port
        self.chunks_size = chunks_size
        self.loop = asyncio.get_event_loop()
        self.udp_sock = UdpSender(self.loop, ip, int(port))
        self.token_size = 2 * struct.calcsize('i') + struct.calcsize('17s')
        self.tokens = {}
        self.tc_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tc_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.tc_sock.setblocking(False)
        self.tc_sock.bind((ip, int(port)))
        self.tc_sock.listen()

    async def tcp_listen(self):
        """Wait for tcp connections to arrive"""
        print('Listening for tcp connections')
        while True:
            conn, addr = await self.loop.sock_accept(self.tc_sock)
            if __debug__:
                print('{} got tcp connection from {}'.format(self.port, addr))
            asyncio.ensure_future(self.tcp_response(conn))

    async def udp_listen(self):
        """Wait until udp message arrives."""
        print('Listening for udp connections')
        while True:
            data, addr = await self.udp_sock.recvfrom(self.chunks_size)
            if __debug__:
                print('{} got udp request from {}'.format(self.port, addr))
            asyncio.ensure_future(self.udp_response(data, addr))

    async def udp_response(self, data, addr):
        """Create udp response and send it."""
        response = await self.check_msg(data)
        if response:
            await self.udp_sock.sendto(response, addr)

    async def tcp_response(self, conn):
        """Receive tcp stream, create response and send it"""
        int_size = struct.calcsize('i')
        recv_msg_size = await self.loop.sock_recv(conn, int_size)
        try:
            msg_size = struct.unpack('i', recv_msg_size)[0]
        except Exception as e:
            conn.close()
            return
        res = b''
        while len(res) < msg_size:
            res += await self.loop.sock_recv(conn, self.chunks_size)
            await asyncio.sleep(0)
        response = await self.check_msg(res)
        response_stream = io.BytesIO(response)
        stream = True
        while stream:
            stream = response_stream.read(self.chunks_size)
            try:
                await self.loop.sock_sendall(conn, stream)
            except Exception as e:
                conn.close()
                return
        conn.close()
        if __debug__:
            print('Connection closed')

    async def check_msg(self, res):
        """Determine message type and create response message accordingly"""
        token = res[:self.token_size]
        payload = res[self.token_size:]
        msg_type, msg_cntr, sender = struct.unpack('ii17s', token)
        if sender not in self.tokens.keys():
            if __debug__:
                print('Add new token')
            self.tokens[sender] = 0
        if self.tokens[sender] != msg_cntr:
            self.tokens[sender] = msg_cntr
            token = struct.pack('ii17s', msg_type, self.tokens[sender], self.uid)
            if msg_type == 0:
                if payload:
                    new_msg = await self.cb_obj.arrival(sender, payload)
                    if new_msg:
                        response = token + new_msg if new_msg else token
                    else:
                        response = token
                else:
                    response = token
            elif msg_type == 1:
                await self.cb_obj_gossip.arrival(sender, payload)
                response = token
        else:
            if __debug__:
                print('NO TOKEN ARRIVAL')
            token = struct.pack('ii17s', msg_type, self.tokens[sender], self.uid)
            response = token
        return response


Prompt:
Implement the Python class `LineBuilder` described below.

Class description:
Line instance static fabric.

Method signatures and docstrings:
- def from_Flask_req(cls, r, session): Creates class instance from Flask request object. Args: r: Flask request object. session: Flask session object. Returns: Ammo class instance.
- def from_row(cls, **row): Creates class instance from RDBMS returned row. Args: row: dict with table columns as keys. Returns: *Line* class instance.

Implement the Python class `LineBuilder` described below.

Class description:
Line instance static fabric.

Method signatures and docstrings:
- def from_Flask_req(cls, r, session): Creates class instance from Flask request object. Args: r: Flask request object. session: Flask session object. Returns: Ammo class instance.
- def from_row(cls, **row): Creates class instance from RDBMS returned row. Args: row: dict with table columns as keys. Returns: *Line* class instance.

<|skeleton|>
class LineBuilder:
    """Line instance static fabric."""

    def from_Flask_req(cls, r, session):
        """Creates class instance from Flask request object. Args: r: Flask request object. session: Flask session object. Returns: Ammo class instance."""
        <|body_0|>

    def from_row(cls, **row):
        """Creates class instance from RDBMS returned row. Args: row: dict with table columns as keys. Returns: *Line* class instance."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        strip_dc = lambda name: ''.join([el for el in name if el in string.ascii_lowercase])
        msg_rvd = cls.parse_flask_req(r, session)
        msg_rvd.update({'dc': {'name': strip_dc(msg_rvd['name'])}})
        return Line(**msg_rvd)
<|end_body_0|>

<|body_start_1|>
        if row.get('dc_id'):
            row.setdefault('dc', {})
            row['dc']['id'] = row.get('dc_id')
            del row['dc_id']
        if row.get('dc_name'):
            row.setdefault('dc', {})
            row['dc']['name'] = row.get('dc_name')
            del row['dc_name']
        return Line(**row)
<|end_body_1|>

Solution:
class LineBuilder:
    """Line instance static fabric."""

    def from_Flask_req(cls, r, session):
        """Creates class instance from Flask request object. Args: r: Flask request object. session: Flask session object. Returns: Ammo class instance."""
        strip_dc = lambda name: ''.join([el for el in name if el in string.ascii_lowercase])
        msg_rvd = cls.parse_flask_req(r, session)
        msg_rvd.update({'dc': {'name': strip_dc(msg_rvd['name'])}})
        return Line(**msg_rvd)

    def from_row(cls, **row):
        """Creates class instance from RDBMS returned row. Args: row: dict with table columns as keys. Returns: *Line* class instance."""
        if row.get('dc_id'):
            row.setdefault('dc', {})
            row['dc']['id'] = row.get('dc_id')
            del row['dc_id']
        if row.get('dc_name'):
            row.setdefault('dc', {})
            row['dc']['name'] = row.get('dc_name')
            del row['dc_name']
        return Line(**row)


clean

Prompt:
Implement the Python class `CheckoutCouponBillingRecordForm` described below.

Class description:
The billing record form during coupon purchase

Method signatures and docstrings:
- def clean(self): Clean all fields and de-populate default state if no other address info is present.
- def create_or_update(self, business_id, billing_record_id=None): Retrieve billing record from previous payment submit or create new billing record. Return billing record.

Implement the Python class `CheckoutCouponBillingRecordForm` described below.

Class description:
The billing record form during coupon purchase

Method signatures and docstrings:
- def clean(self): Clean all fields and de-populate default state if no other address info is present.
- def create_or_update(self, business_id, billing_record_id=None): Retrieve billing record from previous payment submit or create new billing record. Return billing record.

<|skeleton|>
class CheckoutCouponBillingRecordForm:
    """The billing record form during coupon purchase"""

    def clean(self):
        """Clean all fields and de-populate default state if no other address info is present."""
        <|body_0|>

    def create_or_update(self, business_id, billing_record_id=None):
        """Retrieve billing record from previous payment submit or create new billing record. Return billing record."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.cleaned_data = trim_fields_in_form(self)
        if not self.cleaned_data['billing_zip_postal'] and (not self.cleaned_data['billing_city']) and (not self.cleaned_data['billing_address2']) and (not self.cleaned_data['billing_address1']):
            self.cleaned_data['billing_state_province'] = ''
        return self.cleaned_data
<|end_body_0|>

<|body_start_1|>
        billing_address1 = self.cleaned_data['billing_address1']
        billing_address2 = self.cleaned_data['billing_address2']
        billing_city = self.cleaned_data['billing_city']
        billing_state_province = self.cleaned_data['billing_state_province']
        billing_zip_postal = self.cleaned_data['billing_zip_postal']
        try:
            billing_record = BillingRecord.objects.get(id=billing_record_id, business__id=business_id)
            billing_record.billing_address1 = billing_address1
            billing_record.billing_address2 = billing_address2
            billing_record.billing_city = billing_city
            billing_record.billing_state_province = billing_state_province
            billing_record.billing_zip_postal = billing_zip_postal
        except BillingRecord.DoesNotExist:
            billing_record = BillingRecord(business_id=business_id, billing_address1=billing_address1, billing_address2=billing_address2, billing_city=billing_city, billing_state_province=billing_state_province, billing_zip_postal=billing_zip_postal)
        billing_record.save()
        return billing_record
<|end_body_1|>

Solution:
class CheckoutCouponBillingRecordForm:
    """The billing record form during coupon purchase"""

    def clean(self):
        """Clean all fields and de-populate default state if no other address info is present."""
        self.cleaned_data = trim_fields_in_form(self)
        if not self.cleaned_data['billing_zip_postal'] and (not self.cleaned_data['billing_city']) and (not self.cleaned_data['billing_address2']) and (not self.cleaned_data['billing_address1']):
            self.cleaned_data['billing_state_province'] = ''
        return self.cleaned_data

    def create_or_update(self, business_id, billing_record_id=None):
        """Retrieve billing record from previous payment submit or create new billing record. Return billing record."""
        billing_address1 = self.cleaned_data['billing_address1']
        billing_address2 = self.cleaned_data['billing_address2']
        billing_city = self.cleaned_data['billing_city']
        billing_state_province = self.cleaned_data['billing_state_province']
        billing_zip_postal = self.cleaned_data['billing_zip_postal']
        try:
            billing_record = BillingRecord.objects.get(id=billing_record_id, business__id=business_id)
            billing_record.billing_address1 = billing_address1
            billing_record.billing_address2 = billing_address2
            billing_record.billing_city = billing_city
            billing_record.billing_state_province = billing_state_province
            billing_record.billing_zip_postal = billing_zip_postal
        except BillingRecord.DoesNotExist:
            billing_record = BillingRecord(business_id=business_id, billing_address1=billing_address1, billing_address2=billing_address2, billing_city=billing_city, billing_state_province=billing_state_province, billing_zip_postal=billing_zip_postal)
        billing_record.save()
        return billing_record


Prompt:
Implement the Python class `SessionBoardData` described below.

Class description:
handles all AJAX related session board data

Method signatures and docstrings:
- def get(self, slug=None, eid=None): return rooms and timeslots
- def post(self, slug=None, eid=None): store room and timetable data

Implement the Python class `SessionBoardData` described below.

Class description:
handles all AJAX related session board data

Method signatures and docstrings:
- def get(self, slug=None, eid=None): return rooms and timeslots
- def post(self, slug=None, eid=None): store room and timetable data

<|skeleton|>
class SessionBoardData:
    """handles all AJAX related session board data"""

    def get(self, slug=None, eid=None):
        """return rooms and timeslots"""
        <|body_0|>

    def post(self, slug=None, eid=None):
        """store room and timetable data"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        ub = self.app.module_map.userbase
        event = self.barcamp.get_event(eid)
        rooms = event.timetable.get('rooms', [])
        timeslots = event.timetable.get('timeslots', [])
        sessions = event.timetable.get('sessions', {})
        if self.barcamp.ticketmode_enabled:
            tdb = self.config.dbs.tickets
            tickets = tdb.get_tickets(barcamp_id=self.barcamp._id)
            uids = set([t.user_id for t in tickets])
            participants = list(ub.get_users_by_ids(uids))
        else:
            participants = list(ub.get_users_by_ids(event.participants))
        participants = [{'name': p.fullname, '_id': str(p._id)} for p in participants]
        proposals = []
        for p in self.config.dbs.sessions.find({'barcamp_id': str(self.barcamp_id)}):
            proposals.append({'value': p.title, 'label': '%s (%s)' % (p.title, p.user.fullname), 'description': p.description, 'user_id': p.user_id, 'vote_count': p.vote_count})
        return {'rooms': rooms, 'timeslots': timeslots, 'event': event, 'eid': event._id, 'participants': participants, 'proposals': proposals, 'sessions': sessions}
<|end_body_0|>

<|body_start_1|>
        event = self.barcamp.get_event(eid)
        data = json.loads(self.request.data)
        event.timetable = {'rooms': data.get('rooms', []), 'timeslots': data.get('timeslots', []), 'sessions': data.get('sessions', {})}
        self.barcamp.events[eid] = event
        self.barcamp.save()
        return {'status': 'ok'}
<|end_body_1|>

Solution:
class SessionBoardData:
    """handles all AJAX related session board data"""

    def get(self, slug=None, eid=None):
        """return rooms and timeslots"""
        ub = self.app.module_map.userbase
        event = self.barcamp.get_event(eid)
        rooms = event.timetable.get('rooms', [])
        timeslots = event.timetable.get('timeslots', [])
        sessions = event.timetable.get('sessions', {})
        if self.barcamp.ticketmode_enabled:
            tdb = self.config.dbs.tickets
            tickets = tdb.get_tickets(barcamp_id=self.barcamp._id)
            uids = set([t.user_id for t in tickets])
            participants = list(ub.get_users_by_ids(uids))
        else:
            participants = list(ub.get_users_by_ids(event.participants))
        participants = [{'name': p.fullname, '_id': str(p._id)} for p in participants]
        proposals = []
        for p in self.config.dbs.sessions.find({'barcamp_id': str(self.barcamp_id)}):
            proposals.append({'value': p.title, 'label': '%s (%s)' % (p.title, p.user.fullname), 'description': p.description, 'user_id': p.user_id, 'vote_count': p.vote_count})
        return {'rooms': rooms, 'timeslots': timeslots, 'event': event, 'eid': event._id, 'participants': participants, 'proposals': proposals, 'sessions': sessions}

    def post(self, slug=None, eid=None):
        """store room and timetable data"""
        event = self.barcamp.get_event(eid)
        data = json.loads(self.request.data)
        event.timetable = {'rooms': data.get('rooms', []), 'timeslots': data.get('timeslots', []), 'sessions': data.get('sessions', {})}
        self.barcamp.events[eid] = event
        self.barcamp.save()
        return {'status': 'ok'}


get

Prompt:
Implement the Python class `Player` described below.

Class description:
models a player (user) in the game environment

Method signatures and docstrings:
- def __init__(self): creates a new player
- def has(self, thing_name): checks if this Player has an item with a given name in their inventory :param thing_name: the name to check :return: True if the item is present in the Player's inventory
- def get(self, thing_name): gets a given item from a Player's inventory :param thing_name: the item's name :return: the item from the Player's inventory or None if it was not found
- def remove_from_inventory(self, thing_name): removes the first item with a given name from the Player's inventory :param thing_name: the name of the item to remove :return: None
- def item_that_can(self, action): finds the first item in a Player's inventory that can perform a given action :param action: the action to perform :return: the first item found that can perform the given action or None if not found

Implement the Python class `Player` described below.

Class description:
models a player (user) in the game environment

Method signatures and docstrings:
- def __init__(self): creates a new player
- def has(self, thing_name): checks if this Player has an item with a given name in their inventory :param thing_name: the name to check :return: True if the item is present in the Player's inventory
- def get(self, thing_name): gets a given item from a Player's inventory :param thing_name: the item's name :return: the item from the Player's inventory or None if it was not found
- def remove_from_inventory(self, thing_name): removes the first item with a given name from the Player's inventory :param thing_name: the name of the item to remove :return: None
- def item_that_can(self, action): finds the first item in a Player's inventory that can perform a given action :param action: the action to perform :return: the first item found that can perform the given action or None if not found

<|skeleton|>
class Player:
    """models a player (user) in the game environment"""

    def __init__(self):
        """creates a new player"""
        <|body_0|>

    def has(self, thing_name):
        """checks if this Player has an item with a given name in their inventory :param thing_name: the name to check :return: True if the item is present in the Player's inventory"""
        <|body_1|>

    def get(self, thing_name):
        """gets a given item from a Player's inventory :param thing_name: the item's name :return: the item from the Player's inventory or None if it was not found"""
        <|body_2|>

    def remove_from_inventory(self, thing_name):
        """removes the first item with a given name from the Player's inventory :param thing_name: the name of the item to remove :return: None"""
        <|body_3|>

    def item_that_can(self, action):
        """finds the first item in a Player's inventory that can perform a given action :param action: the action to perform :return: the first item found that can perform the given action or None if not found"""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        self.inventory = []
        self.name = 'Mysterious denizen'
        Log.info('new player created')
<|end_body_0|>

<|body_start_1|>
        result = self.get(thing_name) is not None
        Log.info('thing: %s, result: %s' % (thing_name, result))
        return result
<|end_body_1|>

<|body_start_2|>
        Log.info('thing: %s' % thing_name)
        for thing in self.inventory:
            if thing.name == thing_name:
                return thing
        return None
<|end_body_2|>

<|body_start_3|>
        Log.info('thing: %s' % thing_name)
        for thing in self.inventory:
            if thing.name == thing_name:
                self.inventory.remove(thing)
                return
<|end_body_3|>

<|body_start_4|>
        Log.info('action: %s' % action)
        for item in self.inventory:
            if item.can_be_source_of(action):
                return item
        return None
<|end_body_4|>

Solution:
class Player:
    """models a player (user) in the game environment"""

    def __init__(self):
        """creates a new player"""
        self.inventory = []
        self.name = 'Mysterious denizen'
        Log.info('new player created')

    def has(self, thing_name):
        """checks if this Player has an item with a given name in their inventory :param thing_name: the name to check :return: True if the item is present in the Player's inventory"""
        result = self.get(thing_name) is not None
        Log.info('thing: %s, result: %s' % (thing_name, result))
        return result

    def get(self, thing_name):
        """gets a given item from a Player's inventory :param thing_name: the item's name :return: the item from the Player's inventory or None if it was not found"""
        Log.info('thing: %s' % thing_name)
        for thing in self.inventory:
            if thing.name == thing_name:
                return thing
        return None

    def remove_from_inventory(self, thing_name):
        """removes the first item with a given name from the Player's inventory :param thing_name: the name of the item to remove :return: None"""
        Log.info('thing: %s' % thing_name)
        for thing in self.inventory:
            if thing.name == thing_name:
                self.inventory.remove(thing)
                return

    def item_that_can(self, action):
        """finds the first item in a Player's inventory that can perform a given action :param action: the action to perform :return: the first item found that can perform the given action or None if not found"""
        Log.info('action: %s' % action)
        for item in self.inventory:
            if item.can_be_source_of(action):
                return item
        return None


forward

Prompt:
Implement the Python class `Attention` described below.

Class description:
Implement the Attention class.

Method signatures and docstrings:
- def __init__(self, C_in_q, C_in_kv, C_qk, C_v, w_norm='none', scale=False, n_heads=1, down_kv=False, rel_pos_size=None): Args: C_in_q: query source (encoder feature x) C_in_kv: key/value source (decoder feature y) C_qk: inner query/key dim, which should be same C_v: inner value dim, which same as output dim down_kv: Area attention for lightweight self-attention w/ mean pooling. rel_pos_size: height & width for relative positional embedding. If None or 0 is given, do not use relative positional embedding.
- def forward(self, x, y): Attend from x (decoder) to y (encoder) Args: x: decoder feature y: encoder feature

Implement the Python class `Attention` described below.

Class description:
Implement the Attention class.

Method signatures and docstrings:
- def __init__(self, C_in_q, C_in_kv, C_qk, C_v, w_norm='none', scale=False, n_heads=1, down_kv=False, rel_pos_size=None): Args: C_in_q: query source (encoder feature x) C_in_kv: key/value source (decoder feature y) C_qk: inner query/key dim, which should be same C_v: inner value dim, which same as output dim down_kv: Area attention for lightweight self-attention w/ mean pooling. rel_pos_size: height & width for relative positional embedding. If None or 0 is given, do not use relative positional embedding.
- def forward(self, x, y): Attend from x (decoder) to y (encoder) Args: x: decoder feature y: encoder feature

<|skeleton|>
class Attention:

    def __init__(self, C_in_q, C_in_kv, C_qk, C_v, w_norm='none', scale=False, n_heads=1, down_kv=False, rel_pos_size=None):
        """Args: C_in_q: query source (encoder feature x) C_in_kv: key/value source (decoder feature y) C_qk: inner query/key dim, which should be same C_v: inner value dim, which same as output dim down_kv: Area attention for lightweight self-attention w/ mean pooling. rel_pos_size: height & width for relative positional embedding. If None or 0 is given, do not use relative positional embedding."""
        <|body_0|>

    def forward(self, x, y):
        """Attend from x (decoder) to y (encoder) Args: x: decoder feature y: encoder feature"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__()
        self.n_heads = n_heads
        self.down_kv = down_kv
        w_norm = w_norm_dispatch(w_norm)
        self.q_proj = w_norm(nn.Conv1d(C_in_q, C_qk, 1))
        self.k_proj = w_norm(nn.Conv1d(C_in_kv, C_qk, 1))
        self.v_proj = w_norm(nn.Conv1d(C_in_kv, C_v, 1))
        self.out = w_norm(nn.Conv2d(C_v, C_v, 1))
        if scale:
            self.scale = 1.0 / C_qk ** 0.5
        if rel_pos_size:
            C_h_qk = C_qk // n_heads
            self.rel_pos = RelativePositionalEmbedding2d(C_h_qk, rel_pos_size, rel_pos_size, down_kv=down_kv)
<|end_body_0|>

<|body_start_1|>
        B, C, H, W = x.shape
        flat_x = x.flatten(start_dim=2)
        if not self.down_kv:
            flat_y = y.flatten(start_dim=2)
        else:
            y_down = F.avg_pool2d(y, 2)
            flat_y = y_down.flatten(2)
        query = self.q_proj(flat_x)
        key = self.k_proj(flat_y)
        value = self.v_proj(flat_y)
        query = split_dim(query, 1, self.n_heads)
        key = split_dim(key, 1, self.n_heads)
        value = split_dim(value, 1, self.n_heads)
        attn_score = torch.einsum('bhcq,bhck->bhqk', query, key)
        if hasattr(self, 'rel_pos'):
            attn_score += self.rel_pos(query)
        if hasattr(self, 'scale'):
            attn_score *= self.scale
        attn_w = F.softmax(attn_score, dim=-1)
        attn_out = torch.einsum('bhqk,bhck->bhcq', attn_w, value).reshape(B, C, H, W)
        out = self.out(attn_out)
        return out
<|end_body_1|>

Solution:
class Attention:
    def __init__(self, C_in_q, C_in_kv, C_qk, C_v, w_norm='none', scale=False, n_heads=1, down_kv=False, rel_pos_size=None):
        """Args: C_in_q: query source (encoder feature x) C_in_kv: key/value source (decoder feature y) C_qk: inner query/key dim, which should be same C_v: inner value dim, which same as output dim down_kv: Area attention for lightweight self-attention w/ mean pooling. rel_pos_size: height & width for relative positional embedding. If None or 0 is given, do not use relative positional embedding."""
        super().__init__()
        self.n_heads = n_heads
        self.down_kv = down_kv
        w_norm = w_norm_dispatch(w_norm)
        self.q_proj = w_norm(nn.Conv1d(C_in_q, C_qk, 1))
        self.k_proj = w_norm(nn.Conv1d(C_in_kv, C_qk, 1))
        self.v_proj = w_norm(nn.Conv1d(C_in_kv, C_v, 1))
        self.out = w_norm(nn.Conv2d(C_v, C_v, 1))
        if scale:
            self.scale = 1.0 / C_qk ** 0.5
        if rel_pos_size:
            C_h_qk = C_qk // n_heads
            self.rel_pos = RelativePositionalEmbedding2d(C_h_qk, rel_pos_size, rel_pos_size, down_kv=down_kv)

    def forward(self, x, y):
        """Attend from x (decoder) to y (encoder) Args: x: decoder feature y: encoder feature"""
        B, C, H, W = x.shape
        flat_x = x.flatten(start_dim=2)
        if not self.down_kv:
            flat_y = y.flatten(start_dim=2)
        else:
            y_down = F.avg_pool2d(y, 2)
            flat_y = y_down.flatten(2)
        query = self.q_proj(flat_x)
        key = self.k_proj(flat_y)
        value = self.v_proj(flat_y)
        query = split_dim(query, 1, self.n_heads)
        key = split_dim(key, 1, self.n_heads)
        value = split_dim(value, 1, self.n_heads)
        attn_score = torch.einsum('bhcq,bhck->bhqk', query, key)
        if hasattr(self, 'rel_pos'):
            attn_score += self.rel_pos(query)
        if hasattr(self, 'scale'):
            attn_score *= self.scale
        attn_w = F.softmax(attn_score, dim=-1)
        attn_out = torch.einsum('bhqk,bhck->bhcq', attn_w, value).reshape(B, C, H, W)
        out = self.out(attn_out)
        return out


Prompt:
Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def countSmaller_1(self, nums): :type nums: List[int] :rtype: List[int]
- def countSmaller_2(self, nums): :type nums: List[int] :rtype: List[int]

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def countSmaller_1(self, nums): :type nums: List[int] :rtype: List[int]
- def countSmaller_2(self, nums): :type nums: List[int] :rtype: List[int]

<|skeleton|>
class Solution:

    def countSmaller_1(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        <|body_0|>

    def countSmaller_2(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        counts = [0] * len(nums)

        def mergesort(pairs):
            if len(pairs) < 2:
                return pairs
            mid = len(pairs) // 2
            left = mergesort(pairs[:mid])
            right = mergesort(pairs[mid:])
            i = j = 0
            results = []
            while i < len(left) or j < len(right):
                if i >= len(left) or (j < len(right) and right[j][1] < left[i][1]):
                    results.append(right[j])
                    j += 1
                else:
                    results.append(left[i])
                    counts[left[i][0]] += j
                    i += 1
            return results
        mergesort(list(enumerate(nums)))
        return counts
<|end_body_0|>

<|body_start_1|>
        def mergeSort(enum):
            half = len(enum) / 2
            if half:
                left, right = (mergeSort(enum[:half]), mergeSort(enum[half:]))
                for i in range(len(enum))[::-1]:
                    if not right or (left and left[-1][1] > right[-1][1]):
                        smaller[left[-1][0]] += len(right)
                        enum[i] = left.pop()
                    else:
                        enum[i] = right.pop()
            return enum
        smaller = [0] * len(nums)
        mergeSort(list(enumerate(nums)))
        return smaller
<|end_body_1|>

Solution:
class Solution:
    def countSmaller_1(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        counts = [0] * len(nums)

        def mergesort(pairs):
            if len(pairs) < 2:
                return pairs
            mid = len(pairs) // 2
            left = mergesort(pairs[:mid])
            right = mergesort(pairs[mid:])
            i = j = 0
            results = []
            while i < len(left) or j < len(right):
                if i >= len(left) or (j < len(right) and right[j][1] < left[i][1]):
                    results.append(right[j])
                    j += 1
                else:
                    results.append(left[i])
                    counts[left[i][0]] += j
                    i += 1
            return results
        mergesort(list(enumerate(nums)))
        return counts

    def countSmaller_2(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        def mergeSort(enum):
            half = len(enum) / 2
            if half:
                left, right = (mergeSort(enum[:half]), mergeSort(enum[half:]))
                for i in range(len(enum))[::-1]:
                    if not right or (left and left[-1][1] > right[-1][1]):
                        smaller[left[-1][0]] += len(right)
                        enum[i] = left.pop()
                    else:
                        enum[i] = right.pop()
            return enum
        smaller = [0] * len(nums)
        mergeSort(list(enumerate(nums)))
        return smaller


Prompt:
Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def productExceptSelf_0(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf_1(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf_2(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def productExceptSelf_0(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf_1(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf_2(self, nums): :type nums: List[int] :rtype: List[int]
- def productExceptSelf(self, nums): :type nums: List[int] :rtype: List[int]

<|skeleton|>
class Solution:

    def productExceptSelf_0(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        <|body_0|>

    def productExceptSelf_1(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        <|body_1|>

    def productExceptSelf_2(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        <|body_2|>

    def productExceptSelf(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        output = [0] * len(nums)
        for i in range(len(nums)):
            j = 1
            news = nums[:i] + nums[i + 1:]
            for k in news:
                j *= k
            output[i] = j
        return output
<|end_body_0|>

<|body_start_1|>
        length = len(nums)
        L, R, answer = ([0] * length, [0] * length, [0] * length)
        L[0] = 1
        for i in range(1, length):
            L[i] = nums[i - 1] * L[i - 1]
        R[length - 1] = 1
        for i in reversed(range(length - 1)):
            R[i] = nums[i + 1] * R[i + 1]
        for i in range(length):
            answer[i] = L[i] * R[i]
        return answer
<|end_body_1|>

<|body_start_2|>
        length = len(nums)
        answer = [0] * length
        answer[0] = 1
        for i in range(1, length):
            answer[i] = nums[i - 1] * answer[i - 1]
        R = 1
        for i in reversed(range(length)):
            answer[i] = answer[i] * R
            R *= nums[i]
        return answer
<|end_body_2|>

<|body_start_3|>
        left = 1
        right = 1
        result = [1] * len(nums)
        for i in range(len(nums)):
            result[i] *= left
            left *= nums[i]
        for i in range(len(nums) - 1, -1, -1):
            result[i] *= right
            right *= nums[i]
        return result
<|end_body_3|>

Solution:
class Solution:
    def productExceptSelf_0(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        output = [0] * len(nums)
        for i in range(len(nums)):
            j = 1
            news = nums[:i] + nums[i + 1:]
            for k in news:
                j *= k
            output[i] = j
        return output

    def productExceptSelf_1(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        length = len(nums)
        L, R, answer = ([0] * length, [0] * length, [0] * length)
        L[0] = 1
        for i in range(1, length):
            L[i] = nums[i - 1] * L[i - 1]
        R[length - 1] = 1
        for i in reversed(range(length - 1)):
            R[i] = nums[i + 1] * R[i + 1]
        for i in range(length):
            answer[i] = L[i] * R[i]
        return answer

    def productExceptSelf_2(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        length = len(nums)
        answer = [0] * length
        answer[0] = 1
        for i in range(1, length):
            answer[i] = nums[i - 1] * answer[i - 1]
        R = 1
        for i in reversed(range(length)):
            answer[i] = answer[i] * R
            R *= nums[i]
        return answer

    def productExceptSelf(self, nums):
        """:type nums: List[int] :rtype: List[int]"""
        left = 1
        right = 1
        result = [1] * len(nums)
        for i in range(len(nums)):
            result[i] *= left
            left *= nums[i]
        for i in range(len(nums) - 1, -1, -1):
            result[i] *= right
            right *= nums[i]
        return result

238. 除自身以外数组的乘积.py


Prompt:
Implement the Python class `Level1Creator` described below.

Class description:
Level creator for level 1

Method signatures and docstrings:
- def create_obstacles(self) -> list: Create all obstacles for level 1 :return: list of obstacles
- def create_enemies(self) -> list: Create all enemies for level 1 :return: list of enemies
- def music(self) -> None: Linux music for level 1

Implement the Python class `Level1Creator` described below.

Class description:
Level creator for level 1

Method signatures and docstrings:
- def create_obstacles(self) -> list: Create all obstacles for level 1 :return: list of obstacles
- def create_enemies(self) -> list: Create all enemies for level 1 :return: list of enemies
- def music(self) -> None: Linux music for level 1

<|skeleton|>
class Level1Creator:
    """Level creator for level 1"""

    def create_obstacles(self) -> list:
        """Create all obstacles for level 1 :return: list of obstacles"""
        <|body_0|>

    def create_enemies(self) -> list:
        """Create all enemies for level 1 :return: list of enemies"""
        <|body_1|>

    def music(self) -> None:
        """Linux music for level 1"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        obstacles = []
        obstacles.append(Obstacle(Position(400, 400)))
        obstacles.append(Obstacle(Position(690, 380)))
        obstacles.append(Obstacle(Position(490, 500)))
        obstacles.append(Obstacle(Position(300, 200)))
        return obstacles
<|end_body_0|>

<|body_start_1|>
        enemies = []
        enemies.append(CreationFactory().create_dummy_enemy(Position(420, 400)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(700, 380)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(320, 750)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(560, 150)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(750, 220)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(750, 700)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(500, 500)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(820, 300)))
        return enemies
<|end_body_1|>

<|body_start_2|>
        root_dir = Config()['root_dir']
        file = os.path.join(root_dir, 'resources', 'sounds', 'song1.mp3')
        pygame.mixer.music.load(file)
        pygame.mixer.music.play()
<|end_body_2|>

Solution:
class Level1Creator:
    """Level creator for level 1"""

    def create_obstacles(self) -> list:
        """Create all obstacles for level 1 :return: list of obstacles"""
        obstacles = []
        obstacles.append(Obstacle(Position(400, 400)))
        obstacles.append(Obstacle(Position(690, 380)))
        obstacles.append(Obstacle(Position(490, 500)))
        obstacles.append(Obstacle(Position(300, 200)))
        return obstacles

    def create_enemies(self) -> list:
        """Create all enemies for level 1 :return: list of enemies"""
        enemies = []
        enemies.append(CreationFactory().create_dummy_enemy(Position(420, 400)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(700, 380)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(320, 750)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(560, 150)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(750, 220)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(750, 700)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(500, 500)))
        enemies.append(CreationFactory().create_dummy_enemy(Position(820, 300)))
        return enemies

    def music(self) -> None:
        """Linux music for level 1"""
        root_dir = Config()['root_dir']
        file = os.path.join(root_dir, 'resources', 'sounds', 'song1.mp3')
        pygame.mixer.music.load(file)
        pygame.mixer.music.play()


pagination

Prompt:
Implement the Python class `ProvenWinnersPlants` described below.

Class description:
Implement the ProvenWinnersPlants class.

Method signatures and docstrings:
- def start_requests(self): Determine which category starting url to run.
- def parse_grid(self, response): Parse cols and rows for grid of results.
- def parse_plant_details(self, response): Parse cols and rows for grid of results.
- def pagination(self, response): Extract the pagination range for a given category.
- def parse(self, response): Parse the response.

Implement the Python class `ProvenWinnersPlants` described below.

Class description:
Implement the ProvenWinnersPlants class.

Method signatures and docstrings:
- def start_requests(self): Determine which category starting url to run.
- def parse_grid(self, response): Parse cols and rows for grid of results.
- def parse_plant_details(self, response): Parse cols and rows for grid of results.
- def pagination(self, response): Extract the pagination range for a given category.
- def parse(self, response): Parse the response.

<|skeleton|>
class ProvenWinnersPlants:

    def start_requests(self):
        """Determine which category starting url to run."""
        <|body_0|>

    def parse_grid(self, response):
        """Parse cols and rows for grid of results."""
        <|body_1|>

    def parse_plant_details(self, response):
        """Parse cols and rows for grid of results."""
        <|body_2|>

    def pagination(self, response):
        """Extract the pagination range for a given category."""
        <|body_3|>

    def parse(self, response):
        """Parse the response."""
        <|body_4|>

<|end_skeleton|>

<|body_start_0|>
        cats = ['annuals', 'perennials', 'grasses', 'shrubs']
        if not hasattr(self, 'category'):
            self.category = 'perennials'
        if self.category not in cats:
            raise ValueError('Invalid category! Choose from: {}'.format(', '.join(cats)))
        url = '{}/plants/search/{}'.format(self.ROOT_URL, self.category)
        yield scrapy.Request(url)
<|end_body_0|>

<|body_start_1|>
        for plant in response.css('.view-content .item-list li'):
            top = plant.css('.info-grid-title')
            if not top:
                continue
            url = top.css('a::attr(href)').extract_first()
            yield response.follow(url, callback=self.parse_plant_details)
<|end_body_1|>

<|body_start_2|>
        title = response.css('.page-title h1 .plant-name')
        features = response.css('.fieldgroup.group-features .content .field')
        chars_groups = response.css('.fieldgroup.group-characteristics .content .field')
        needs_group = response.css('.fieldgroup.group-needs .content .field')

        def extract_group(container):
            vals = {}
            for field in container:
                item = ' '.join(field.css('.field-item::text').extract())
                label = field.css('.field-label-inline-first::text').extract_first()
                if item is None or label is None:
                    continue
                item, label = (item.strip(), label.strip())
                item = item.replace('\n', '').replace('  ', ' ')
                label = labelize(label)
                if label == 'light_requirement':
                    item = item.split(' to ')
                if label in ['soil_fertility_requirement', 'soil_ph_category', 'bloom_time']:
                    item = item.split('  ')
                if label in ['foliage_colors', 'hardiness_zones', 'uses']:
                    item = [x.lower() for x in item.split(' ')]
                if isinstance(item, list):
                    item = [token.strip() for token in item if token.strip()]
                vals[label] = item
            return vals
        yield {'url': response.url, 'genus': maybe_lower(title.css('.genus-species .genus em::text').extract_first()), 'species': maybe_lower(title.css('.genus-species .species em::text').extract_first()), 'variety': ' '.join(title.css('.series-variety span strong::text').extract() + title.css('.series-variety .variety::text').extract()), 'common_name': title.css('.common-name::text').extract_first(), 'features': extract_group(features), 'characteristics': extract_group(chars_groups), 'needs': extract_group(needs_group)}
<|end_body_2|>

<|body_start_3|>
        last_page = response.css('.item-list ul li.pager-item a::text').extract()
        last_page = last_page[-1]
        last_page = int(last_page.strip())
        return (0, last_page)
<|end_body_3|>

<|body_start_4|>
        pages = response.css('.paging .item-list ul.pages')
        rel_url = pages.css('li a::attr(href)').extract_first().split('?')[0:-1]
        rel_url = ''.join(rel_url)
        first, last = self.pagination(response)
        for page_num in range(first, last):
            yield response.follow('{}?page={}'.format(rel_url, page_num), callback=self.parse_grid)
<|end_body_4|>

Solution:
class ProvenWinnersPlants:
    def start_requests(self):
        """Determine which category starting url to run."""
        cats = ['annuals', 'perennials', 'grasses', 'shrubs']
        if not hasattr(self, 'category'):
            self.category = 'perennials'
        if self.category not in cats:
            raise ValueError('Invalid category! Choose from: {}'.format(', '.join(cats)))
        url = '{}/plants/search/{}'.format(self.ROOT_URL, self.category)
        yield scrapy.Request(url)

    def parse_grid(self, response):
        """Parse cols and rows for grid of results."""
        for plant in response.css('.view-content .item-list li'):
            top = plant.css('.info-grid-title')
            if not top:
                continue
            url = top.css('a::attr(href)').extract_first()
            yield response.follow(url, callback=self.parse_plant_details)

    def parse_plant_details(self, response):
        """Parse cols and rows for grid of results."""
        title = response.css('.page-title h1 .plant-name')
        features = response.css('.fieldgroup.group-features .content .field')
        chars_groups = response.css('.fieldgroup.group-characteristics .content .field')
        needs_group = response.css('.fieldgroup.group-needs .content .field')

        def extract_group(container):
            vals = {}
            for field in container:
                item = ' '.join(field.css('.field-item::text').extract())
                label = field.css('.field-label-inline-first::text').extract_first()
                if item is None or label is None:
                    continue
                item, label = (item.strip(), label.strip())
                item = item.replace('\n', '').replace('  ', ' ')
                label = labelize(label)
                if label == 'light_requirement':
                    item = item.split(' to ')
                if label in ['soil_fertility_requirement', 'soil_ph_category', 'bloom_time']:
                    item = item.split('  ')
                if label in ['foliage_colors', 'hardiness_zones', 'uses']:
                    item = [x.lower() for x in item.split(' ')]
                if isinstance(item, list):
                    item = [token.strip() for token in item if token.strip()]
                vals[label] = item
            return vals
        yield {'url': response.url, 'genus': maybe_lower(title.css('.genus-species .genus em::text').extract_first()), 'species': maybe_lower(title.css('.genus-species .species em::text').extract_first()), 'variety': ' '.join(title.css('.series-variety span strong::text').extract() + title.css('.series-variety .variety::text').extract()), 'common_name': title.css('.common-name::text').extract_first(), 'features': extract_group(features), 'characteristics': extract_group(chars_groups), 'needs': extract_group(needs_group)}

    def pagination(self, response):
        """Extract the pagination range for a given category."""
        last_page = response.css('.item-list ul li.pager-item a::text').extract()
        last_page = last_page[-1]
        last_page = int(last_page.strip())
        return (0, last_page)

    def parse(self, response):
        """Parse the response."""
        pages = response.css('.paging .item-list ul.pages')
        rel_url = pages.css('li a::attr(href)').extract_first().split('?')[0:-1]
        rel_url = ''.join(rel_url)
        first, last = self.pagination(response)
        for page_num in range(first, last):
            yield response.follow('{}?page={}'.format(rel_url, page_num), callback=self.parse_grid)


moderate

Prompt:
Implement the Python class `PostCommentModerator` described below.

Class description:
In addition to what we do in Post.comments_allowed, this should also ensure that: * We could enable email_notifications * If something automatedly submits a Comment on a Post that's older than COMMENTS_CLOSE_AFTER_DAYS, it will just be discarded. https://django-contrib-comments.readthedocs.io/en/latest/moderation.html

Method signatures and docstrings:
- def allow(self, comment, content_object, request): While this slightly duplicates Post.comments_allowed() it ensures that our custom things (settings.HINES_COMMENTS_ALLOWED and Blog.allow_comments) are taken into account in this moderator. If this returns False, then a submitted comment is just disappeared.
- def moderate(self, comment, content_object, request): All we do here is: * Get the result from the parent moderate() method. * If the message is to be moderated, add a flash message explaining this. * Return the result.

Implement the Python class `PostCommentModerator` described below.

Class description:
In addition to what we do in Post.comments_allowed, this should also ensure that: * We could enable email_notifications * If something automatedly submits a Comment on a Post that's older than COMMENTS_CLOSE_AFTER_DAYS, it will just be discarded. https://django-contrib-comments.readthedocs.io/en/latest/moderation.html

Method signatures and docstrings:
- def allow(self, comment, content_object, request): While this slightly duplicates Post.comments_allowed() it ensures that our custom things (settings.HINES_COMMENTS_ALLOWED and Blog.allow_comments) are taken into account in this moderator. If this returns False, then a submitted comment is just disappeared.
- def moderate(self, comment, content_object, request): All we do here is: * Get the result from the parent moderate() method. * If the message is to be moderated, add a flash message explaining this. * Return the result.

<|skeleton|>
class PostCommentModerator:
    """In addition to what we do in Post.comments_allowed, this should also ensure that: * We could enable email_notifications * If something automatedly submits a Comment on a Post that's older than COMMENTS_CLOSE_AFTER_DAYS, it will just be discarded. https://django-contrib-comments.readthedocs.io/en/latest/moderation.html"""

    def allow(self, comment, content_object, request):
        """While this slightly duplicates Post.comments_allowed() it ensures that our custom things (settings.HINES_COMMENTS_ALLOWED and Blog.allow_comments) are taken into account in this moderator. If this returns False, then a submitted comment is just disappeared."""
        <|body_0|>

    def moderate(self, comment, content_object, request):
        """All we do here is: * Get the result from the parent moderate() method. * If the message is to be moderated, add a flash message explaining this. * Return the result."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        result = super().allow(comment, content_object, request)
        if not result:
            return False
        elif content_object.comments_allowed:
            return True
        else:
            return False
<|end_body_0|>

<|body_start_1|>
        result = super().moderate(comment, content_object, request)
        if result is True:
            message_content = 'Thanks for your comment. All comments must be checked before publishing, so it should appear soon.'
            add_comment_message(request, messages.SUCCESS, message_content)
        return result
<|end_body_1|>

Solution:
class PostCommentModerator:
    """In addition to what we do in Post.comments_allowed, this should also ensure that: * We could enable email_notifications * If something automatedly submits a Comment on a Post that's older than COMMENTS_CLOSE_AFTER_DAYS, it will just be discarded. https://django-contrib-comments.readthedocs.io/en/latest/moderation.html"""

    def allow(self, comment, content_object, request):
        """While this slightly duplicates Post.comments_allowed() it ensures that our custom things (settings.HINES_COMMENTS_ALLOWED and Blog.allow_comments) are taken into account in this moderator. If this returns False, then a submitted comment is just disappeared."""
        result = super().allow(comment, content_object, request)
        if not result:
            return False
        elif content_object.comments_allowed:
            return True
        else:
            return False

    def moderate(self, comment, content_object, request):
        """All we do here is: * Get the result from the parent moderate() method. * If the message is to be moderated, add a flash message explaining this. * Return the result."""
        result = super().moderate(comment, content_object, request)
        if result is True:
            message_content = 'Thanks for your comment. All comments must be checked before publishing, so it should appear soon.'
            add_comment_message(request, messages.SUCCESS, message_content)
        return result


Prompt:
Implement the Python class `Solution` described below.

Class description:
5 / 4 8 / / 11 13 4 / \\ / 7 2 5 1 sum = 22 [ [5,4,11,2], [5,8,4,5] ] Summary: 这类题考得就是二叉树的遍历，只不过在遍历的同时需要保存每个节点的和，可以用，因此自然而然的可以想用用dfs来做 需要注意的是： 遍历的时候使用 ``` while root: stack.append(...) root = root.left ``` 这种遍历方法并不太好，因为无法获得上一次压栈的值，也就无法很好的保存已访问过的节点以及目前节点的和

Method signatures and docstrings:
- def pathSum1(self, root: TreeNode, Sum: int) -> List[List[int]]: dfs-recursive :param root: :param Sum: :return:
- def pathSum2(self, root: TreeNode, Sum: int) -> List[List[int]]: dfs+stack iterative 迭代版本其实就是自己用一个`stack`实现递归中的栈帧 :param root: :param Sum: :return:
- def pathSum3(self, root: TreeNode, Sum: int) -> List[List[int]]: dfs+stack iterative :param root: :param Sum: :return:
- def pathSum4(self, root: TreeNode, Sum: int) -> List[List[int]]: bfs+queue iterative :param root: :param Sum: :return:

Implement the Python class `Solution` described below.

Class description:
5 / 4 8 / / 11 13 4 / \\ / 7 2 5 1 sum = 22 [ [5,4,11,2], [5,8,4,5] ] Summary: 这类题考得就是二叉树的遍历，只不过在遍历的同时需要保存每个节点的和，可以用，因此自然而然的可以想用用dfs来做 需要注意的是： 遍历的时候使用 ``` while root: stack.append(...) root = root.left ``` 这种遍历方法并不太好，因为无法获得上一次压栈的值，也就无法很好的保存已访问过的节点以及目前节点的和

Method signatures and docstrings:
- def pathSum1(self, root: TreeNode, Sum: int) -> List[List[int]]: dfs-recursive :param root: :param Sum: :return:
- def pathSum2(self, root: TreeNode, Sum: int) -> List[List[int]]: dfs+stack iterative 迭代版本其实就是自己用一个`stack`实现递归中的栈帧 :param root: :param Sum: :return:
- def pathSum3(self, root: TreeNode, Sum: int) -> List[List[int]]: dfs+stack iterative :param root: :param Sum: :return:
- def pathSum4(self, root: TreeNode, Sum: int) -> List[List[int]]: bfs+queue iterative :param root: :param Sum: :return:

<|skeleton|>
class Solution:
    """5 / 4 8 / / 11 13 4 / \\ / 7 2 5 1 sum = 22 [ [5,4,11,2], [5,8,4,5] ] Summary: 这类题考得就是二叉树的遍历，只不过在遍历的同时需要保存每个节点的和，可以用，因此自然而然的可以想用用dfs来做 需要注意的是： 遍历的时候使用 ``` while root: stack.append(...) root = root.left ``` 这种遍历方法并不太好，因为无法获得上一次压栈的值，也就无法很好的保存已访问过的节点以及目前节点的和"""

    def pathSum1(self, root: TreeNode, Sum: int) -> List[List[int]]:
        """dfs-recursive :param root: :param Sum: :return:"""
        <|body_0|>

    def pathSum2(self, root: TreeNode, Sum: int) -> List[List[int]]:
        """dfs+stack iterative 迭代版本其实就是自己用一个`stack`实现递归中的栈帧 :param root: :param Sum: :return:"""
        <|body_1|>

    def pathSum3(self, root: TreeNode, Sum: int) -> List[List[int]]:
        """dfs+stack iterative :param root: :param Sum: :return:"""
        <|body_2|>

    def pathSum4(self, root: TreeNode, Sum: int) -> List[List[int]]:
        """bfs+queue iterative :param root: :param Sum: :return:"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        def dfs(root, Sum, path, ans):
            if not root.left and (not root.right) and (Sum == root.val):
                path.append(root.val)
                ans.append(path)
            if root.left:
                dfs(root.left, Sum - root.val, path + [root.val], ans)
            if root.right:
                dfs(root.right, Sum - root.val, path + [root.val], ans)
        if not root:
            return []
        ans = []
        dfs(root, Sum, [], ans)
        return ans
<|end_body_0|>

<|body_start_1|>
        if not root:
            return []
        res = []
        stack = [(root, Sum - root.val, [root.val])]
        while stack:
            curr, val, ls = stack.pop()
            if not curr.left and (not curr.right) and (val == 0):
                res.append(ls)
            if curr.right:
                stack.append((curr.right, val - curr.right.val, ls + [curr.right.val]))
            if curr.left:
                stack.append((curr.left, val - curr.left.val, ls + [curr.left.val]))
        return res
<|end_body_1|>

<|body_start_2|>
        if not root:
            return []
        ans = []
        stack = [(root, [root.val])]
        while stack:
            curr, path = stack.pop()
            if not curr.left and (not curr.right) and (sum(path) == Sum):
                ans.append(path)
            if curr.right:
                stack.append((curr.right, path + [curr.right.val]))
            if curr.left:
                stack.append((curr.left, path + [curr.left.val]))
        return ans
<|end_body_2|>

<|body_start_3|>
        if not root:
            return []
        queue = [(root, Sum - root.val, [root.val])]
        ans = []
        while queue:
            curr, val, path = queue.pop(0)
            if not curr.left and (not curr.right) and (val == 0):
                ans.append(path)
            if curr.left:
                queue.append((curr.left, val - curr.left.val, path + [curr.left.val]))
            if curr.right:
                queue.append((curr.right, val - curr.right.val, path + [curr.right.val]))
        return ans
<|end_body_3|>

Solution:
class Solution:
    """5 / 4 8 / / 11 13 4 / \\ / 7 2 5 1 sum = 22 [ [5,4,11,2], [5,8,4,5] ] Summary: 这类题考得就是二叉树的遍历，只不过在遍历的同时需要保存每个节点的和，可以用，因此自然而然的可以想用用dfs来做 需要注意的是： 遍历的时候使用 ``` while root: stack.append(...) root = root.left ``` 这种遍历方法并不太好，因为无法获得上一次压栈的值，也就无法很好的保存已访问过的节点以及目前节点的和"""

    def pathSum1(self, root: TreeNode, Sum: int) -> List[List[int]]:
        """dfs-recursive :param root: :param Sum: :return:"""
        def dfs(root, Sum, path, ans):
            if not root.left and (not root.right) and (Sum == root.val):
                path.append(root.val)
                ans.append(path)
            if root.left:
                dfs(root.left, Sum - root.val, path + [root.val], ans)
            if root.right:
                dfs(root.right, Sum - root.val, path + [root.val], ans)
        if not root:
            return []
        ans = []
        dfs(root, Sum, [], ans)
        return ans

    def pathSum2(self, root: TreeNode, Sum: int) -> List[List[int]]:
        """dfs+stack iterative 迭代版本其实就是自己用一个`stack`实现递归中的栈帧 :param root: :param Sum: :return:"""
        if not root:
            return []
        res = []
        stack = [(root, Sum - root.val, [root.val])]
        while stack:
            curr, val, ls = stack.pop()
            if not curr.left and (not curr.right) and (val == 0):
                res.append(ls)
            if curr.right:
                stack.append((curr.right, val - curr.right.val, ls + [curr.right.val]))
            if curr.left:
                stack.append((curr.left, val - curr.left.val, ls + [curr.left.val]))
        return res

    def pathSum3(self, root: TreeNode, Sum: int) -> List[List[int]]:
        """dfs+stack iterative :param root: :param Sum: :return:"""
        if not root:
            return []
        ans = []
        stack = [(root, [root.val])]
        while stack:
            curr, path = stack.pop()
            if not curr.left and (not curr.right) and (sum(path) == Sum):
                ans.append(path)
            if curr.right:
                stack.append((curr.right, path + [curr.right.val]))
            if curr.left:
                stack.append((curr.left, path + [curr.left.val]))
        return ans

    def pathSum4(self, root: TreeNode, Sum: int) -> List[List[int]]:
        """bfs+queue iterative :param root: :param Sum: :return:"""
        if not root:
            return []
        queue = [(root, Sum - root.val, [root.val])]
        ans = []
        while queue:
            curr, val, path = queue.pop(0)
            if not curr.left and (not curr.right) and (val == 0):
                ans.append(path)
            if curr.left:
                queue.append((curr.left, val - curr.left.val, path + [curr.left.val]))
            if curr.right:
                queue.append((curr.right, val - curr.right.val, path + [curr.right.val]))
        return ans