addTwoNumbers

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): :param l1: ListNode :param l2: ListNode :return: ListNode
- def addTwoNumbers2(self, l1, l2): :param l1: ListNode :param l2: ListNode :return: ListNode

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): :param l1: ListNode :param l2: ListNode :return: ListNode
- def addTwoNumbers2(self, l1, l2): :param l1: ListNode :param l2: ListNode :return: ListNode

<|skeleton|>
class Solution:

    def addTwoNumbers(self, l1, l2):
        """:param l1: ListNode :param l2: ListNode :return: ListNode"""
        <|body_0|>

    def addTwoNumbers2(self, l1, l2):
        """:param l1: ListNode :param l2: ListNode :return: ListNode"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        l = ListNode(0)
        while l1:
            l.next = ListNode(0)
            if l1.value + l2.value >= 10:
                l.value = l1.value + l2.value - 10
                l.next.value = 1
            else:
                l.value = l.value + l1.value + l2.value
            print('l.value:{0}'.format(l.value))
            l1 = l1.next
            l2 = l2.next
        return l
<|end_body_0|>

<|body_start_1|>
        i, s1, l = (1, 0, l1)
        while l:
            s1 += l.value * i
            i = i * 10
            l = l.next
        i, s2, l = (1, 0, l2)
        while l:
            s2 += l.value * i
            i *= 10
            l = l.next
        s = s1 + s2
        s = str(s)[::-1]
        res = [ListNode(int(ch)) for ch in s]
        for i in range(len(res) - 1):
            res[i].next = res[i + 1]
        return res[0]
<|end_body_1|>

Solution:
class Solution:
    def addTwoNumbers(self, l1, l2):
        """:param l1: ListNode :param l2: ListNode :return: ListNode"""
        l = ListNode(0)
        while l1:
            l.next = ListNode(0)
            if l1.value + l2.value >= 10:
                l.value = l1.value + l2.value - 10
                l.next.value = 1
            else:
                l.value = l.value + l1.value + l2.value
            print('l.value:{0}'.format(l.value))
            l1 = l1.next
            l2 = l2.next
        return l

    def addTwoNumbers2(self, l1, l2):
        """:param l1: ListNode :param l2: ListNode :return: ListNode"""
        i, s1, l = (1, 0, l1)
        while l:
            s1 += l.value * i
            i = i * 10
            l = l.next
        i, s2, l = (1, 0, l2)
        while l:
            s2 += l.value * i
            i *= 10
            l = l.next
        s = s1 + s2
        s = str(s)[::-1]
        res = [ListNode(int(ch)) for ch in s]
        for i in range(len(res) - 1):
            res[i].next = res[i + 1]
        return res[0]


show

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

Class description:
The config plugin.

Method signatures and docstrings:
- def plugins(self, argv): Parse and load the builtin plugins and the ones in the configuration file. If this method is called using 'mesos config plugins', it displays the plugins that can be used.
- def show(self, argv): Show the contents of the configuration file.

Implement the Python class `Config` described below.

Class description:
The config plugin.

Method signatures and docstrings:
- def plugins(self, argv): Parse and load the builtin plugins and the ones in the configuration file. If this method is called using 'mesos config plugins', it displays the plugins that can be used.
- def show(self, argv): Show the contents of the configuration file.

<|skeleton|>
class Config:
    """The config plugin."""

    def plugins(self, argv):
        """Parse and load the builtin plugins and the ones in the configuration file. If this method is called using 'mesos config plugins', it displays the plugins that can be used."""
        <|body_0|>

    def show(self, argv):
        """Show the contents of the configuration file."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        plugins_table = Table(['NAME', 'DESCRIPTION'])
        plugins = cli.util.import_modules(cli.util.join_plugin_paths(self.settings, self.config), 'plugins')
        for plugin in plugins:
            plugins_table.add_row([cli.util.get_module(plugins, plugin).PLUGIN_NAME, cli.util.get_module(plugins, plugin).SHORT_HELP])
        sys.stdout.write('{}\n'.format(plugins_table))
<|end_body_0|>

<|body_start_1|>
        config_file = self.config.path
        if not os.path.isfile(config_file):
            raise CLIException("Unable to show the config file, '{path}' does not exist".format(path=config_file))
        with open(config_file, 'r') as stream:
            try:
                sys.stdout.write('{stream}\n'.format(stream=stream.read().rstrip()))
            except Exception as exception:
                raise CLIException("Unable to read config file '{path}': {error}".format(path=config_file, error=exception))
<|end_body_1|>

Solution:
class Config:
    """The config plugin."""

    def plugins(self, argv):
        """Parse and load the builtin plugins and the ones in the configuration file. If this method is called using 'mesos config plugins', it displays the plugins that can be used."""
        plugins_table = Table(['NAME', 'DESCRIPTION'])
        plugins = cli.util.import_modules(cli.util.join_plugin_paths(self.settings, self.config), 'plugins')
        for plugin in plugins:
            plugins_table.add_row([cli.util.get_module(plugins, plugin).PLUGIN_NAME, cli.util.get_module(plugins, plugin).SHORT_HELP])
        sys.stdout.write('{}\n'.format(plugins_table))

    def show(self, argv):
        """Show the contents of the configuration file."""
        config_file = self.config.path
        if not os.path.isfile(config_file):
            raise CLIException("Unable to show the config file, '{path}' does not exist".format(path=config_file))
        with open(config_file, 'r') as stream:
            try:
                sys.stdout.write('{stream}\n'.format(stream=stream.read().rstrip()))
            except Exception as exception:
                raise CLIException("Unable to read config file '{path}': {error}".format(path=config_file, error=exception))


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

Class description:
Implement the KthLargest class.

Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int

Implement the Python class `KthLargest` described below.

Class description:
Implement the KthLargest class.

Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int

<|skeleton|>
class KthLargest:

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

    def add(self, val):
        """:type val: int :rtype: int"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.k = k
        self.nums = sorted(nums)
        self.length = len(self.nums)
<|end_body_0|>

<|body_start_1|>
        self.nums.append(val)
        self.nums.sort()
        self.length += 1
        return self.nums[-self.k] if 0 < self.k <= self.length else self.nums[-1]
<|end_body_1|>

Solution:
class KthLargest:
    def __init__(self, k, nums):
        """:type k: int :type nums: List[int]"""
        self.k = k
        self.nums = sorted(nums)
        self.length = len(self.nums)

    def add(self, val):
        """:type val: int :rtype: int"""
        self.nums.append(val)
        self.nums.sort()
        self.length += 1
        return self.nums[-self.k] if 0 < self.k <= self.length else self.nums[-1]


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

Class description:
Manages polling for state changes from the device.

Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: Device): Initialize the data update coordinator.
- async def _async_update_data(self): Update the state of the device.
- async def push_state_update(self): Send state updates to the physical device.

Implement the Python class `DeviceDataUpdateCoordinator` described below.

Class description:
Manages polling for state changes from the device.

Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: Device): Initialize the data update coordinator.
- async def _async_update_data(self): Update the state of the device.
- async def push_state_update(self): Send state updates to the physical device.

<|skeleton|>
class DeviceDataUpdateCoordinator:
    """Manages polling for state changes from the device."""

    def __init__(self, hass: HomeAssistant, device: Device):
        """Initialize the data update coordinator."""
        <|body_0|>

    async def _async_update_data(self):
        """Update the state of the device."""
        <|body_1|>

    async def push_state_update(self):
        """Send state updates to the physical device."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        DataUpdateCoordinator.__init__(self, hass, _LOGGER, name=f'{DOMAIN}-{device.device_info.name}', update_interval=timedelta(seconds=60))
        self.device = device
        self._error_count = 0
<|end_body_0|>

<|body_start_1|>
        try:
            await self.device.update_state()
        except DeviceTimeoutError as error:
            self._error_count += 1
            if self.last_update_success and self._error_count >= MAX_ERRORS:
                _LOGGER.warning('Device is unavailable: %s (%s)', self.name, self.device.device_info)
                raise UpdateFailed(error) from error
        else:
            if not self.last_update_success and self._error_count:
                _LOGGER.warning('Device is available: %s (%s)', self.name, str(self.device.device_info))
            self._error_count = 0
<|end_body_1|>

<|body_start_2|>
        try:
            return await self.device.push_state_update()
        except DeviceTimeoutError:
            _LOGGER.warning('Timeout send state update to: %s (%s)', self.name, self.device.device_info)
<|end_body_2|>

Solution:
class DeviceDataUpdateCoordinator:
    """Manages polling for state changes from the device."""

    def __init__(self, hass: HomeAssistant, device: Device):
        """Initialize the data update coordinator."""
        DataUpdateCoordinator.__init__(self, hass, _LOGGER, name=f'{DOMAIN}-{device.device_info.name}', update_interval=timedelta(seconds=60))
        self.device = device
        self._error_count = 0

    async def _async_update_data(self):
        """Update the state of the device."""
        try:
            await self.device.update_state()
        except DeviceTimeoutError as error:
            self._error_count += 1
            if self.last_update_success and self._error_count >= MAX_ERRORS:
                _LOGGER.warning('Device is unavailable: %s (%s)', self.name, self.device.device_info)
                raise UpdateFailed(error) from error
        else:
            if not self.last_update_success and self._error_count:
                _LOGGER.warning('Device is available: %s (%s)', self.name, str(self.device.device_info))
            self._error_count = 0

    async def push_state_update(self):
        """Send state updates to the physical device."""
        try:
            return await self.device.push_state_update()
        except DeviceTimeoutError:
            _LOGGER.warning('Timeout send state update to: %s (%s)', self.name, self.device.device_info)


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

Class description:
Class for loading TTL events. Note that timestamps for events are stored relative to the start of acquisition (play button), not recording. This class can make the right conversion to match spike data from kilosort.

Method signatures and docstrings:
- def __init__(self, processedDataDir, convert=True): Args: processedDataDir (str): path to root of neuropixels raw data for a given session. convert(bool): if True, convert timestamps to seconds.
- def get_onset_times(self, eventChannel=1, channelState=1): Get the onset times for specific events. Args: eventChannel (int): The openEphys DIO channel that recieves the event. channelState (int): 1 for onset, -1 for offset Returns: eventOnsetTimes (array): An array of the timestamps of the event onsets.

Implement the Python class `Events` described below.

Class description:
Class for loading TTL events. Note that timestamps for events are stored relative to the start of acquisition (play button), not recording. This class can make the right conversion to match spike data from kilosort.

Method signatures and docstrings:
- def __init__(self, processedDataDir, convert=True): Args: processedDataDir (str): path to root of neuropixels raw data for a given session. convert(bool): if True, convert timestamps to seconds.
- def get_onset_times(self, eventChannel=1, channelState=1): Get the onset times for specific events. Args: eventChannel (int): The openEphys DIO channel that recieves the event. channelState (int): 1 for onset, -1 for offset Returns: eventOnsetTimes (array): An array of the timestamps of the event onsets.

<|skeleton|>
class Events:
    """Class for loading TTL events. Note that timestamps for events are stored relative to the start of acquisition (play button), not recording. This class can make the right conversion to match spike data from kilosort."""

    def __init__(self, processedDataDir, convert=True):
        """Args: processedDataDir (str): path to root of neuropixels raw data for a given session. convert(bool): if True, convert timestamps to seconds."""
        <|body_0|>

    def get_onset_times(self, eventChannel=1, channelState=1):
        """Get the onset times for specific events. Args: eventChannel (int): The openEphys DIO channel that recieves the event. channelState (int): 1 for onset, -1 for offset Returns: eventOnsetTimes (array): An array of the timestamps of the event onsets."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.convertUnits = convert
        self.eventsDir = os.path.join(processedDataDir, 'events/Neuropix-PXI-100.0/TTL_1/')
        self.infoDir = os.path.join(processedDataDir, 'info')
        channelsFile = 'channels.npy'
        channelStatesFile = 'channel_states.npy'
        fullWordsFile = 'full_words.npy'
        timestampsFile = 'timestamps.npy'
        self.firstTimestamp, self.samplingRate = read_recording_info(processedDataDir)
        self.channels = np.load(os.path.join(self.eventsDir, channelsFile))
        self.channelStates = np.load(os.path.join(self.eventsDir, channelStatesFile))
        self.fullWords = np.load(os.path.join(self.eventsDir, fullWordsFile))
        self.timestamps = np.load(os.path.join(self.eventsDir, timestampsFile))
        if self.convertUnits:
            self.timestamps = (self.timestamps - self.firstTimestamp) / self.samplingRate
<|end_body_0|>

<|body_start_1|>
        thisStateThisChannel = (self.channelStates == channelState) & (self.channels == eventChannel)
        eventOnsetTimes = self.timestamps[thisStateThisChannel]
        return eventOnsetTimes
<|end_body_1|>

Solution:
class Events:
    """Class for loading TTL events. Note that timestamps for events are stored relative to the start of acquisition (play button), not recording. This class can make the right conversion to match spike data from kilosort."""

    def __init__(self, processedDataDir, convert=True):
        """Args: processedDataDir (str): path to root of neuropixels raw data for a given session. convert(bool): if True, convert timestamps to seconds."""
        self.convertUnits = convert
        self.eventsDir = os.path.join(processedDataDir, 'events/Neuropix-PXI-100.0/TTL_1/')
        self.infoDir = os.path.join(processedDataDir, 'info')
        channelsFile = 'channels.npy'
        channelStatesFile = 'channel_states.npy'
        fullWordsFile = 'full_words.npy'
        timestampsFile = 'timestamps.npy'
        self.firstTimestamp, self.samplingRate = read_recording_info(processedDataDir)
        self.channels = np.load(os.path.join(self.eventsDir, channelsFile))
        self.channelStates = np.load(os.path.join(self.eventsDir, channelStatesFile))
        self.fullWords = np.load(os.path.join(self.eventsDir, fullWordsFile))
        self.timestamps = np.load(os.path.join(self.eventsDir, timestampsFile))
        if self.convertUnits:
            self.timestamps = (self.timestamps - self.firstTimestamp) / self.samplingRate

    def get_onset_times(self, eventChannel=1, channelState=1):
        """Get the onset times for specific events. Args: eventChannel (int): The openEphys DIO channel that recieves the event. channelState (int): 1 for onset, -1 for offset Returns: eventOnsetTimes (array): An array of the timestamps of the event onsets."""
        thisStateThisChannel = (self.channelStates == channelState) & (self.channels == eventChannel)
        eventOnsetTimes = self.timestamps[thisStateThisChannel]
        return eventOnsetTimes


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

Class description:
MakeLayer2

Method signatures and docstrings:
- def __init__(self, block, in_channels, out_channels, stride): init
- def construct(self, x): construct

Implement the Python class `MakeLayer2` described below.

Class description:
MakeLayer2

Method signatures and docstrings:
- def __init__(self, block, in_channels, out_channels, stride): init
- def construct(self, x): construct

<|skeleton|>
class MakeLayer2:
    """MakeLayer2"""

    def __init__(self, block, in_channels, out_channels, stride):
        """init"""
        <|body_0|>

    def construct(self, x):
        """construct"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(MakeLayer2, self).__init__()
        self.a = ResidualBlockWithDown(in_channels, out_channels, stride=stride, down_sample=True)
        self.b = block(out_channels, out_channels, stride=1)
        self.c = block(out_channels, out_channels, stride=1)
        self.d = block(out_channels, out_channels, stride=1)
        self.e = block(out_channels, out_channels, stride=1)
        self.f = block(out_channels, out_channels, stride=1)
<|end_body_0|>

<|body_start_1|>
        x = self.a(x)
        x = self.b(x)
        x = self.c(x)
        x = self.d(x)
        x = self.e(x)
        x = self.f(x)
        return x
<|end_body_1|>

Solution:
class MakeLayer2:
    """MakeLayer2"""

    def __init__(self, block, in_channels, out_channels, stride):
        """init"""
        super(MakeLayer2, self).__init__()
        self.a = ResidualBlockWithDown(in_channels, out_channels, stride=stride, down_sample=True)
        self.b = block(out_channels, out_channels, stride=1)
        self.c = block(out_channels, out_channels, stride=1)
        self.d = block(out_channels, out_channels, stride=1)
        self.e = block(out_channels, out_channels, stride=1)
        self.f = block(out_channels, out_channels, stride=1)

    def construct(self, x):
        """construct"""
        x = self.a(x)
        x = self.b(x)
        x = self.c(x)
        x = self.d(x)
        x = self.e(x)
        x = self.f(x)
        return x


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

Class description:
Implementation of the 'ProtectionSourceSnapshotInformation' model. Specifies details about a Snapshot that backups up a leaf Protection Source Object. Attributes: copy_tasks (list of SnapshotCopyTask): Array of Snapshot Copy Tasks. Specifies a list of copy tasks (such as replication and archival tasks). job_id (long|int): Specifies the id of the Protection Job. job_name (string): Specifies the name of the Protection Job. job_run_id (long|int): Specifies the id of the Job Run. job_run_start_time_usecs (long|int): Specifies the start time of the Job which this object is part of. The time is specified in Unix epoch Timestamp (in microseconds). last_run_end_time_usecs (long|int): Specifies the e

Method signatures and docstrings:
- def __init__(self, copy_tasks=None, job_id=None, job_name=None, job_run_id=None, job_run_start_time_usecs=None, last_run_end_time_usecs=None, last_run_start_time_usecs=None, message=None, num_bytes_read=None, num_logical_bytes_protected=None, pagination_cookie=None, run_status=None, run_type=None): Constructor for the ProtectionSourceSnapshotInformation class
- def from_dictionary(cls, dictionary): Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class.

Implement the Python class `ProtectionSourceSnapshotInformation` described below.

Class description:
Implementation of the 'ProtectionSourceSnapshotInformation' model. Specifies details about a Snapshot that backups up a leaf Protection Source Object. Attributes: copy_tasks (list of SnapshotCopyTask): Array of Snapshot Copy Tasks. Specifies a list of copy tasks (such as replication and archival tasks). job_id (long|int): Specifies the id of the Protection Job. job_name (string): Specifies the name of the Protection Job. job_run_id (long|int): Specifies the id of the Job Run. job_run_start_time_usecs (long|int): Specifies the start time of the Job which this object is part of. The time is specified in Unix epoch Timestamp (in microseconds). last_run_end_time_usecs (long|int): Specifies the e

Method signatures and docstrings:
- def __init__(self, copy_tasks=None, job_id=None, job_name=None, job_run_id=None, job_run_start_time_usecs=None, last_run_end_time_usecs=None, last_run_start_time_usecs=None, message=None, num_bytes_read=None, num_logical_bytes_protected=None, pagination_cookie=None, run_status=None, run_type=None): Constructor for the ProtectionSourceSnapshotInformation class
- def from_dictionary(cls, dictionary): Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class.

<|skeleton|>
class ProtectionSourceSnapshotInformation:
    """Implementation of the 'ProtectionSourceSnapshotInformation' model. Specifies details about a Snapshot that backups up a leaf Protection Source Object. Attributes: copy_tasks (list of SnapshotCopyTask): Array of Snapshot Copy Tasks. Specifies a list of copy tasks (such as replication and archival tasks). job_id (long|int): Specifies the id of the Protection Job. job_name (string): Specifies the name of the Protection Job. job_run_id (long|int): Specifies the id of the Job Run. job_run_start_time_usecs (long|int): Specifies the start time of the Job which this object is part of. The time is specified in Unix epoch Timestamp (in microseconds). last_run_end_time_usecs (long|int): Specifies the e"""

    def __init__(self, copy_tasks=None, job_id=None, job_name=None, job_run_id=None, job_run_start_time_usecs=None, last_run_end_time_usecs=None, last_run_start_time_usecs=None, message=None, num_bytes_read=None, num_logical_bytes_protected=None, pagination_cookie=None, run_status=None, run_type=None):
        """Constructor for the ProtectionSourceSnapshotInformation class"""
        <|body_0|>

    def from_dictionary(cls, dictionary):
        """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.copy_tasks = copy_tasks
        self.job_id = job_id
        self.job_name = job_name
        self.job_run_id = job_run_id
        self.job_run_start_time_usecs = job_run_start_time_usecs
        self.last_run_end_time_usecs = last_run_end_time_usecs
        self.last_run_start_time_usecs = last_run_start_time_usecs
        self.message = message
        self.num_bytes_read = num_bytes_read
        self.num_logical_bytes_protected = num_logical_bytes_protected
        self.pagination_cookie = pagination_cookie
        self.run_status = run_status
        self.run_type = run_type
<|end_body_0|>

<|body_start_1|>
        if dictionary is None:
            return None
        copy_tasks = None
        if dictionary.get('copyTasks') != None:
            copy_tasks = list()
            for structure in dictionary.get('copyTasks'):
                copy_tasks.append(cohesity_management_sdk.models.snapshot_copy_task.SnapshotCopyTask.from_dictionary(structure))
        job_id = dictionary.get('jobId')
        job_name = dictionary.get('jobName')
        job_run_id = dictionary.get('jobRunId')
        job_run_start_time_usecs = dictionary.get('jobRunStartTimeUsecs')
        last_run_end_time_usecs = dictionary.get('lastRunEndTimeUsecs')
        last_run_start_time_usecs = dictionary.get('lastRunStartTimeUsecs')
        message = dictionary.get('message')
        num_bytes_read = dictionary.get('numBytesRead')
        num_logical_bytes_protected = dictionary.get('numLogicalBytesProtected')
        pagination_cookie = dictionary.get('paginationCookie')
        run_status = dictionary.get('runStatus')
        run_type = dictionary.get('runType')
        return cls(copy_tasks, job_id, job_name, job_run_id, job_run_start_time_usecs, last_run_end_time_usecs, last_run_start_time_usecs, message, num_bytes_read, num_logical_bytes_protected, pagination_cookie, run_status, run_type)
<|end_body_1|>

Solution:
class ProtectionSourceSnapshotInformation:
    """Implementation of the 'ProtectionSourceSnapshotInformation' model. Specifies details about a Snapshot that backups up a leaf Protection Source Object. Attributes: copy_tasks (list of SnapshotCopyTask): Array of Snapshot Copy Tasks. Specifies a list of copy tasks (such as replication and archival tasks). job_id (long|int): Specifies the id of the Protection Job. job_name (string): Specifies the name of the Protection Job. job_run_id (long|int): Specifies the id of the Job Run. job_run_start_time_usecs (long|int): Specifies the start time of the Job which this object is part of. The time is specified in Unix epoch Timestamp (in microseconds). last_run_end_time_usecs (long|int): Specifies the e"""

    def __init__(self, copy_tasks=None, job_id=None, job_name=None, job_run_id=None, job_run_start_time_usecs=None, last_run_end_time_usecs=None, last_run_start_time_usecs=None, message=None, num_bytes_read=None, num_logical_bytes_protected=None, pagination_cookie=None, run_status=None, run_type=None):
        """Constructor for the ProtectionSourceSnapshotInformation class"""
        self.copy_tasks = copy_tasks
        self.job_id = job_id
        self.job_name = job_name
        self.job_run_id = job_run_id
        self.job_run_start_time_usecs = job_run_start_time_usecs
        self.last_run_end_time_usecs = last_run_end_time_usecs
        self.last_run_start_time_usecs = last_run_start_time_usecs
        self.message = message
        self.num_bytes_read = num_bytes_read
        self.num_logical_bytes_protected = num_logical_bytes_protected
        self.pagination_cookie = pagination_cookie
        self.run_status = run_status
        self.run_type = run_type

    def from_dictionary(cls, dictionary):
        """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class."""
        if dictionary is None:
            return None
        copy_tasks = None
        if dictionary.get('copyTasks') != None:
            copy_tasks = list()
            for structure in dictionary.get('copyTasks'):
                copy_tasks.append(cohesity_management_sdk.models.snapshot_copy_task.SnapshotCopyTask.from_dictionary(structure))
        job_id = dictionary.get('jobId')
        job_name = dictionary.get('jobName')
        job_run_id = dictionary.get('jobRunId')
        job_run_start_time_usecs = dictionary.get('jobRunStartTimeUsecs')
        last_run_end_time_usecs = dictionary.get('lastRunEndTimeUsecs')
        last_run_start_time_usecs = dictionary.get('lastRunStartTimeUsecs')
        message = dictionary.get('message')
        num_bytes_read = dictionary.get('numBytesRead')
        num_logical_bytes_protected = dictionary.get('numLogicalBytesProtected')
        pagination_cookie = dictionary.get('paginationCookie')
        run_status = dictionary.get('runStatus')
        run_type = dictionary.get('runType')
        return cls(copy_tasks, job_id, job_name, job_run_id, job_run_start_time_usecs, last_run_end_time_usecs, last_run_start_time_usecs, message, num_bytes_read, num_logical_bytes_protected, pagination_cookie, run_status, run_type)


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

Class description:
The Youless low meter value sensor.

Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str, state_class: SensorStateClass) -> None: Instantiate a energy meter sensor.
- def get_sensor(self) -> YoulessSensor | None: Get the sensor for providing the value.

Implement the Python class `EnergyMeterSensor` described below.

Class description:
The Youless low meter value sensor.

Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str, state_class: SensorStateClass) -> None: Instantiate a energy meter sensor.
- def get_sensor(self) -> YoulessSensor | None: Get the sensor for providing the value.

<|skeleton|>
class EnergyMeterSensor:
    """The Youless low meter value sensor."""

    def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str, state_class: SensorStateClass) -> None:
        """Instantiate a energy meter sensor."""
        <|body_0|>

    def get_sensor(self) -> YoulessSensor | None:
        """Get the sensor for providing the value."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(coordinator, device, 'power', 'Energy usage', f'power_{dev_type}')
        self._device = device
        self._type = dev_type
        self._attr_name = f'Energy {dev_type}'
        self._attr_state_class = state_class
<|end_body_0|>

<|body_start_1|>
        if self.coordinator.data.power_meter is None:
            return None
        return getattr(self.coordinator.data.power_meter, f'_{self._type}', None)
<|end_body_1|>

Solution:
class EnergyMeterSensor:
    """The Youless low meter value sensor."""

    def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, dev_type: str, state_class: SensorStateClass) -> None:
        """Instantiate a energy meter sensor."""
        super().__init__(coordinator, device, 'power', 'Energy usage', f'power_{dev_type}')
        self._device = device
        self._type = dev_type
        self._attr_name = f'Energy {dev_type}'
        self._attr_state_class = state_class

    def get_sensor(self) -> YoulessSensor | None:
        """Get the sensor for providing the value."""
        if self.coordinator.data.power_meter is None:
            return None
        return getattr(self.coordinator.data.power_meter, f'_{self._type}', None)


forward

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

Class description:
Implement the CNN class.

Method signatures and docstrings:
- def __init__(self, is_increasing, num_layers, filter_counts, max_len_token=100): params is_increasing: whether the filter size is increasing or decreasing params num_layers: number of layers in the CNN params filter_counts: dictionary of filter index to filter size params max_len_token: maximum number of tokens in sentence
- def forward(self, src_tgt_sim, src_tgt_mask): Run CNN over input. :params src_tgt_sim: tensor representing similarity between source and target :return: scores for similarity

Implement the Python class `CNN` described below.

Class description:
Implement the CNN class.

Method signatures and docstrings:
- def __init__(self, is_increasing, num_layers, filter_counts, max_len_token=100): params is_increasing: whether the filter size is increasing or decreasing params num_layers: number of layers in the CNN params filter_counts: dictionary of filter index to filter size params max_len_token: maximum number of tokens in sentence
- def forward(self, src_tgt_sim, src_tgt_mask): Run CNN over input. :params src_tgt_sim: tensor representing similarity between source and target :return: scores for similarity

<|skeleton|>
class CNN:

    def __init__(self, is_increasing, num_layers, filter_counts, max_len_token=100):
        """params is_increasing: whether the filter size is increasing or decreasing params num_layers: number of layers in the CNN params filter_counts: dictionary of filter index to filter size params max_len_token: maximum number of tokens in sentence"""
        <|body_0|>

    def forward(self, src_tgt_sim, src_tgt_mask):
        """Run CNN over input. :params src_tgt_sim: tensor representing similarity between source and target :return: scores for similarity"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(CNN, self).__init__()
        decreasing = 0
        if not is_increasing:
            decreasing = 1
        assert 1 <= num_layers <= 4
        self.num_layers = num_layers
        map_conv_layer_to_filter_size = {4: [[3, 5, 5, 7], [7, 5, 5, 3]], 3: [[5, 5, 7], [7, 5, 5]], 2: [[5, 3], [5, 3]], 1: [[7], [7]]}
        pool_output_height = int(np.floor(max_len_token / 2.0))
        for i in range(1, self.num_layers + 1):
            filter_size = map_conv_layer_to_filter_size[self.num_layers][decreasing][i - 1]
            padding_size = math.floor(filter_size / 2)
            prev_filter_count = 1
            if i > 1:
                prev_filter_count = filter_counts[i - 2]
            convlyr = nn.Conv2d(prev_filter_count, filter_counts[i - 1], filter_size, padding=padding_size, stride=1)
            if i == 1:
                self.add_module('cnn_1', convlyr)
            elif i == 2:
                self.add_module('cnn_2', convlyr)
            elif i == 3:
                self.add_module('cnn_3', convlyr)
            elif i == 4:
                self.add_module('cnn_4', convlyr)
        self.align_weights = nn.Parameter(torch.randn(filter_counts[num_layers - 1], pool_output_height, pool_output_height).cuda(), requires_grad=True)
        self.final_dense = nn.Conv2d(filter_counts[num_layers - 1], 1, 1)
        self.relu = nn.ReLU()
        self.pool = nn.MaxPool2d((2, 2), stride=2)
<|end_body_0|>

<|body_start_1|>
        convd = self.cnn_1(src_tgt_sim.unsqueeze(1))
        if self.num_layers > 1:
            convd = self.relu(convd)
            convd = self.cnn_2(convd)
        if self.num_layers > 2:
            convd = self.relu(convd)
            convd = self.cnn_3(convd)
        if self.num_layers > 3:
            convd = self.relu(convd)
            convd = self.cnn_4(convd)
        convd_after_pooling = self.pool(convd)
        pooled_mask = self.pool(src_tgt_mask)
        output = self.final_dense(convd_after_pooling).squeeze(1)
        return (output * pooled_mask).sum(2).sum(1) / pooled_mask.sum(2).sum(1)
<|end_body_1|>

Solution:
class CNN:
    def __init__(self, is_increasing, num_layers, filter_counts, max_len_token=100):
        """params is_increasing: whether the filter size is increasing or decreasing params num_layers: number of layers in the CNN params filter_counts: dictionary of filter index to filter size params max_len_token: maximum number of tokens in sentence"""
        super(CNN, self).__init__()
        decreasing = 0
        if not is_increasing:
            decreasing = 1
        assert 1 <= num_layers <= 4
        self.num_layers = num_layers
        map_conv_layer_to_filter_size = {4: [[3, 5, 5, 7], [7, 5, 5, 3]], 3: [[5, 5, 7], [7, 5, 5]], 2: [[5, 3], [5, 3]], 1: [[7], [7]]}
        pool_output_height = int(np.floor(max_len_token / 2.0))
        for i in range(1, self.num_layers + 1):
            filter_size = map_conv_layer_to_filter_size[self.num_layers][decreasing][i - 1]
            padding_size = math.floor(filter_size / 2)
            prev_filter_count = 1
            if i > 1:
                prev_filter_count = filter_counts[i - 2]
            convlyr = nn.Conv2d(prev_filter_count, filter_counts[i - 1], filter_size, padding=padding_size, stride=1)
            if i == 1:
                self.add_module('cnn_1', convlyr)
            elif i == 2:
                self.add_module('cnn_2', convlyr)
            elif i == 3:
                self.add_module('cnn_3', convlyr)
            elif i == 4:
                self.add_module('cnn_4', convlyr)
        self.align_weights = nn.Parameter(torch.randn(filter_counts[num_layers - 1], pool_output_height, pool_output_height).cuda(), requires_grad=True)
        self.final_dense = nn.Conv2d(filter_counts[num_layers - 1], 1, 1)
        self.relu = nn.ReLU()
        self.pool = nn.MaxPool2d((2, 2), stride=2)

    def forward(self, src_tgt_sim, src_tgt_mask):
        """Run CNN over input. :params src_tgt_sim: tensor representing similarity between source and target :return: scores for similarity"""
        convd = self.cnn_1(src_tgt_sim.unsqueeze(1))
        if self.num_layers > 1:
            convd = self.relu(convd)
            convd = self.cnn_2(convd)
        if self.num_layers > 2:
            convd = self.relu(convd)
            convd = self.cnn_3(convd)
        if self.num_layers > 3:
            convd = self.relu(convd)
            convd = self.cnn_4(convd)
        convd_after_pooling = self.pool(convd)
        pooled_mask = self.pool(src_tgt_mask)
        output = self.final_dense(convd_after_pooling).squeeze(1)
        return (output * pooled_mask).sum(2).sum(1) / pooled_mask.sum(2).sum(1)


complete

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

Class description:
Utility library that performs auto-completion on the given potentially incomplete query. :py:meth:`complete` is the single entry point of this class which returns Tuple.of(the incomplete prefix, potential completes)

Method signatures and docstrings:
- def complete(data, query): Complete the given query with potential options in the given data. :param data: the data :type data: dict, list, int, float, str, bool, None :param query: the query :type query: str :return: (option_prefix, options)
- def _list_options(data, prefix): List all possible next values with the query result from last valid JSONPath query with given prefix. :param data: the current query result :type data: dict, list, int, float, str, bool, None :return: potential options, return empty if `data` is not a composite JSON node
- def _generate_list_completes(length, prefix): Generates completes for an array, use its length also add `*` to represent everything. :param length: the list length :type length: int :return: completes for current length.

Implement the Python class `JSONPathAutoComplete` described below.

Class description:
Utility library that performs auto-completion on the given potentially incomplete query. :py:meth:`complete` is the single entry point of this class which returns Tuple.of(the incomplete prefix, potential completes)

Method signatures and docstrings:
- def complete(data, query): Complete the given query with potential options in the given data. :param data: the data :type data: dict, list, int, float, str, bool, None :param query: the query :type query: str :return: (option_prefix, options)
- def _list_options(data, prefix): List all possible next values with the query result from last valid JSONPath query with given prefix. :param data: the current query result :type data: dict, list, int, float, str, bool, None :return: potential options, return empty if `data` is not a composite JSON node
- def _generate_list_completes(length, prefix): Generates completes for an array, use its length also add `*` to represent everything. :param length: the list length :type length: int :return: completes for current length.

<|skeleton|>
class JSONPathAutoComplete:
    """Utility library that performs auto-completion on the given potentially incomplete query. :py:meth:`complete` is the single entry point of this class which returns Tuple.of(the incomplete prefix, potential completes)"""

    def complete(data, query):
        """Complete the given query with potential options in the given data. :param data: the data :type data: dict, list, int, float, str, bool, None :param query: the query :type query: str :return: (option_prefix, options)"""
        <|body_0|>

    def _list_options(data, prefix):
        """List all possible next values with the query result from last valid JSONPath query with given prefix. :param data: the current query result :type data: dict, list, int, float, str, bool, None :return: potential options, return empty if `data` is not a composite JSON node"""
        <|body_1|>

    def _generate_list_completes(length, prefix):
        """Generates completes for an array, use its length also add `*` to represent everything. :param length: the list length :type length: int :return: completes for current length."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if len(query) == 0:
            return ('', ['$'])
        prefix, jsonpath_exp = Parser.parse(query)
        if jsonpath_exp is None:
            return ('', [])
        current_data = [match.value for match in jsonpath_exp.find(data)]
        options = JSONPathAutoComplete._list_options(current_data, prefix)
        return (prefix, options)
<|end_body_0|>

<|body_start_1|>
        options = []
        if len(data) > 1:
            options = JSONPathAutoComplete._generate_list_completes(len(data), prefix)
        else:
            cur = data[0]
            if isinstance(cur, list):
                options = JSONPathAutoComplete._generate_list_completes(len(cur), prefix)
            elif isinstance(cur, dict):
                for key in cur.keys():
                    if re.match('.*[\\.\\[\\]].*', key) or prefix.startswith('['):
                        options.append("['" + key + "']")
                    else:
                        options.append(key)
                options = list(filter(lambda k: k.startswith(prefix), options))
        return options
<|end_body_1|>

<|body_start_2|>
        options = ['[*]']
        options.extend(['[' + str(index) + ']' for index in range(length)])
        return list(filter(lambda k: k.startswith(prefix), options))
<|end_body_2|>

Solution:
class JSONPathAutoComplete:
    """Utility library that performs auto-completion on the given potentially incomplete query. :py:meth:`complete` is the single entry point of this class which returns Tuple.of(the incomplete prefix, potential completes)"""

    def complete(data, query):
        """Complete the given query with potential options in the given data. :param data: the data :type data: dict, list, int, float, str, bool, None :param query: the query :type query: str :return: (option_prefix, options)"""
        if len(query) == 0:
            return ('', ['$'])
        prefix, jsonpath_exp = Parser.parse(query)
        if jsonpath_exp is None:
            return ('', [])
        current_data = [match.value for match in jsonpath_exp.find(data)]
        options = JSONPathAutoComplete._list_options(current_data, prefix)
        return (prefix, options)

    def _list_options(data, prefix):
        """List all possible next values with the query result from last valid JSONPath query with given prefix. :param data: the current query result :type data: dict, list, int, float, str, bool, None :return: potential options, return empty if `data` is not a composite JSON node"""
        options = []
        if len(data) > 1:
            options = JSONPathAutoComplete._generate_list_completes(len(data), prefix)
        else:
            cur = data[0]
            if isinstance(cur, list):
                options = JSONPathAutoComplete._generate_list_completes(len(cur), prefix)
            elif isinstance(cur, dict):
                for key in cur.keys():
                    if re.match('.*[\\.\\[\\]].*', key) or prefix.startswith('['):
                        options.append("['" + key + "']")
                    else:
                        options.append(key)
                options = list(filter(lambda k: k.startswith(prefix), options))
        return options

    def _generate_list_completes(length, prefix):
        """Generates completes for an array, use its length also add `*` to represent everything. :param length: the list length :type length: int :return: completes for current length."""
        options = ['[*]']
        options.extend(['[' + str(index) + ']' for index in range(length)])
        return list(filter(lambda k: k.startswith(prefix), options))


dfs

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def exist(self, board, word): :type board: List[List[str]] :type word: str :rtype: bool
- def dfs(self, board, i, j, word): :type board: List[List[str]] :type i: next loc row :type i: next loc col :type word: str :rtype: bool

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def exist(self, board, word): :type board: List[List[str]] :type word: str :rtype: bool
- def dfs(self, board, i, j, word): :type board: List[List[str]] :type i: next loc row :type i: next loc col :type word: str :rtype: bool

<|skeleton|>
class Solution:

    def exist(self, board, word):
        """:type board: List[List[str]] :type word: str :rtype: bool"""
        <|body_0|>

    def dfs(self, board, i, j, word):
        """:type board: List[List[str]] :type i: next loc row :type i: next loc col :type word: str :rtype: bool"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if not board:
            return False
        for i in range(len(board)):
            for j in range(len(board[0])):
                if self.dfs(board, i, j, word):
                    return True
        return False
<|end_body_0|>

<|body_start_1|>
        if len(word) == 0:
            return True
        if i < 0 or i >= len(board) or j < 0 or (j >= len(board[0])) or (board[i][j] != word[0]):
            return False
        tmp = board[i][j]
        board[i][j] = '#'
        res = self.dfs(board, i + 1, j, word[1:]) or self.dfs(board, i - 1, j, word[1:]) or self.dfs(board, i, j + 1, word[1:]) or self.dfs(board, i, j - 1, word[1:])
        board[i][j] = tmp
        return res
<|end_body_1|>

Solution:
class Solution:
    def exist(self, board, word):
        """:type board: List[List[str]] :type word: str :rtype: bool"""
        if not board:
            return False
        for i in range(len(board)):
            for j in range(len(board[0])):
                if self.dfs(board, i, j, word):
                    return True
        return False

    def dfs(self, board, i, j, word):
        """:type board: List[List[str]] :type i: next loc row :type i: next loc col :type word: str :rtype: bool"""
        if len(word) == 0:
            return True
        if i < 0 or i >= len(board) or j < 0 or (j >= len(board[0])) or (board[i][j] != word[0]):
            return False
        tmp = board[i][j]
        board[i][j] = '#'
        res = self.dfs(board, i + 1, j, word[1:]) or self.dfs(board, i - 1, j, word[1:]) or self.dfs(board, i, j + 1, word[1:]) or self.dfs(board, i, j - 1, word[1:])
        board[i][j] = tmp
        return res


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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def coinChange_bfs(self, coins, amount): Breadth first search :type coins: List[int] :type amount: int :rtype: int
- def coinChange_dp(self, coins, amount): Dynamic programming :type coins: List[int] :type amount: int :rtype: int

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def coinChange_bfs(self, coins, amount): Breadth first search :type coins: List[int] :type amount: int :rtype: int
- def coinChange_dp(self, coins, amount): Dynamic programming :type coins: List[int] :type amount: int :rtype: int

<|skeleton|>
class Solution:

    def coinChange_bfs(self, coins, amount):
        """Breadth first search :type coins: List[int] :type amount: int :rtype: int"""
        <|body_0|>

    def coinChange_dp(self, coins, amount):
        """Dynamic programming :type coins: List[int] :type amount: int :rtype: int"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if amount == 0:
            return 0
        visited = [False] * (amount + 1)
        num = 0
        cur_sum = [0]
        next_sum = []
        while cur_sum:
            num += 1
            for val in cur_sum:
                for coin in coins:
                    new_val = val + coin
                    if new_val == amount:
                        return num
                    if new_val < amount and (not visited[new_val]):
                        next_sum.append(new_val)
                        visited[new_val] = True
            cur_sum, next_sum = (next_sum, [])
        return -1
<|end_body_0|>

<|body_start_1|>
        coin_count = [0] + [float('inf')] * amount
        for coin in coins:
            for idx, val in enumerate(coin_count):
                if coin <= idx:
                    coin_count[idx] = min(val, 1 + coin_count[idx - coin])
        if coin_count[-1] == float('inf'):
            return -1
        else:
            return coin_count[-1]
<|end_body_1|>

Solution:
class Solution:
    def coinChange_bfs(self, coins, amount):
        """Breadth first search :type coins: List[int] :type amount: int :rtype: int"""
        if amount == 0:
            return 0
        visited = [False] * (amount + 1)
        num = 0
        cur_sum = [0]
        next_sum = []
        while cur_sum:
            num += 1
            for val in cur_sum:
                for coin in coins:
                    new_val = val + coin
                    if new_val == amount:
                        return num
                    if new_val < amount and (not visited[new_val]):
                        next_sum.append(new_val)
                        visited[new_val] = True
            cur_sum, next_sum = (next_sum, [])
        return -1

    def coinChange_dp(self, coins, amount):
        """Dynamic programming :type coins: List[int] :type amount: int :rtype: int"""
        coin_count = [0] + [float('inf')] * amount
        for coin in coins:
            for idx, val in enumerate(coin_count):
                if coin <= idx:
                    coin_count[idx] = min(val, 1 + coin_count[idx - coin])
        if coin_count[-1] == float('inf'):
            return -1
        else:
            return coin_count[-1]


update

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

Class description:
Join trip serializer.

Method signatures and docstrings:
- def validate_passenger(self, data): Verify passenger exists and is a pool member.
- def validate(self, data): Verify trips allow new passengers.
- def update(self, instance, data): Add passenger to trip, and update stats.

Implement the Python class `JoinTripSerializer` described below.

Class description:
Join trip serializer.

Method signatures and docstrings:
- def validate_passenger(self, data): Verify passenger exists and is a pool member.
- def validate(self, data): Verify trips allow new passengers.
- def update(self, instance, data): Add passenger to trip, and update stats.

<|skeleton|>
class JoinTripSerializer:
    """Join trip serializer."""

    def validate_passenger(self, data):
        """Verify passenger exists and is a pool member."""
        <|body_0|>

    def validate(self, data):
        """Verify trips allow new passengers."""
        <|body_1|>

    def update(self, instance, data):
        """Add passenger to trip, and update stats."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        try:
            user = User.objects.get(pk=data)
        except User.DoesNotExist:
            raise serializers.ValidationError('Invalid passenger.')
        pool = self.context['pool']
        try:
            membership = Membership.objects.get(user=user, pool=pool, is_active=True)
        except Membership.DoesNotExist:
            raise serializers.ValidationError('User is not an active member of the poo.')
        self.context['user'] = user
        self.context['member'] = membership
        return data
<|end_body_0|>

<|body_start_1|>
        trip = self.context['trip']
        if trip.departure_date <= timezone.now():
            raise serializers.ValidationError("You can't join this trip now")
        if trip.available_seats < 1:
            raise serializers.ValidationError('Trip is already full!')
        if trip.passengers.filter(pk=self.context['user'].pk).exists():
            raise serializers.ValidationError('Passenger is already in this trip')
        return data
<|end_body_1|>

<|body_start_2|>
        trip = self.context['trip']
        user = self.context['user']
        trip.passengers.add(user)
        trip.available_seats -= 1
        profile = user.profile
        profile.trips_taken += 1
        profile.save()
        member = self.context['member']
        member.trips_taken += 1
        member.save()
        pool = self.context['pool']
        pool.trips_taken += 1
        pool.save()
        return trip
<|end_body_2|>

Solution:
class JoinTripSerializer:
    """Join trip serializer."""

    def validate_passenger(self, data):
        """Verify passenger exists and is a pool member."""
        try:
            user = User.objects.get(pk=data)
        except User.DoesNotExist:
            raise serializers.ValidationError('Invalid passenger.')
        pool = self.context['pool']
        try:
            membership = Membership.objects.get(user=user, pool=pool, is_active=True)
        except Membership.DoesNotExist:
            raise serializers.ValidationError('User is not an active member of the poo.')
        self.context['user'] = user
        self.context['member'] = membership
        return data

    def validate(self, data):
        """Verify trips allow new passengers."""
        trip = self.context['trip']
        if trip.departure_date <= timezone.now():
            raise serializers.ValidationError("You can't join this trip now")
        if trip.available_seats < 1:
            raise serializers.ValidationError('Trip is already full!')
        if trip.passengers.filter(pk=self.context['user'].pk).exists():
            raise serializers.ValidationError('Passenger is already in this trip')
        return data

    def update(self, instance, data):
        """Add passenger to trip, and update stats."""
        trip = self.context['trip']
        user = self.context['user']
        trip.passengers.add(user)
        trip.available_seats -= 1
        profile = user.profile
        profile.trips_taken += 1
        profile.save()
        member = self.context['member']
        member.trips_taken += 1
        member.save()
        pool = self.context['pool']
        pool.trips_taken += 1
        pool.save()
        return trip


forward

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

Class description:
Implement the DeepGP class.

Method signatures and docstrings:
- def __init__(self): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x_train, y_train=None, m=None, x_test=None): In the forward function we accept a Tensor of input data and we must return a Tensor of output data. We can use Modules defined in the constructor as well as arbitrary operators on Tensors.

Implement the Python class `DeepGP` described below.

Class description:
Implement the DeepGP class.

Method signatures and docstrings:
- def __init__(self): In the constructor we instantiate two nn.Linear modules and assign them as member variables.
- def forward(self, x_train, y_train=None, m=None, x_test=None): In the forward function we accept a Tensor of input data and we must return a Tensor of output data. We can use Modules defined in the constructor as well as arbitrary operators on Tensors.

<|skeleton|>
class DeepGP:

    def __init__(self):
        """In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
        <|body_0|>

    def forward(self, x_train, y_train=None, m=None, x_test=None):
        """In the forward function we accept a Tensor of input data and we must return a Tensor of output data. We can use Modules defined in the constructor as well as arbitrary operators on Tensors."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super(DeepGP, self).__init__()
        self.linear1 = torch.nn.Linear(1, 30)
        self.tanh1 = torch.nn.Tanh()
        self.linear2 = torch.nn.Linear(30, 30)
        self.tanh2 = torch.nn.Tanh()
        self.linear3 = torch.nn.Linear(30, 6)
        self.tanh3 = torch.nn.Tanh()
        self.linear4 = torch.nn.Linear(6, 1)
        self.tanh4 = torch.nn.Sigmoid()
        self.scale = 10.0
        self.scale = torch.nn.Parameter(torch.Tensor([1.0]))
        self.gp = gprh.GP_1D(sigma_f=1.0, lengthscale=1, sigma_n=2 * noise_std)
<|end_body_0|>

<|body_start_1|>
        h = x_train.clone()
        h = self.linear1(h)
        h = self.tanh1(h)
        h = self.linear2(h)
        h = self.tanh2(h)
        h = self.linear3(h)
        h = self.tanh3(h)
        h = self.linear4(h)
        h = self.tanh4(h)
        h = self.scale * h
        if x_test is not None:
            h2 = x_test.clone()
            h2 = self.linear1(h2)
            h2 = self.tanh1(h2)
            h2 = self.linear2(h2)
            h2 = self.tanh2(h2)
            h2 = self.linear3(h2)
            h2 = self.tanh3(h2)
            h2 = self.linear4(h2)
            h2 = self.tanh4(h2)
            h2 = self.scale * h2
        else:
            h2 = None
        if y_train is not None:
            out = self.gp(h, y_train, m, h2)
        else:
            out = h
        return out
<|end_body_1|>

Solution:
class DeepGP:
    def __init__(self):
        """In the constructor we instantiate two nn.Linear modules and assign them as member variables."""
        super(DeepGP, self).__init__()
        self.linear1 = torch.nn.Linear(1, 30)
        self.tanh1 = torch.nn.Tanh()
        self.linear2 = torch.nn.Linear(30, 30)
        self.tanh2 = torch.nn.Tanh()
        self.linear3 = torch.nn.Linear(30, 6)
        self.tanh3 = torch.nn.Tanh()
        self.linear4 = torch.nn.Linear(6, 1)
        self.tanh4 = torch.nn.Sigmoid()
        self.scale = 10.0
        self.scale = torch.nn.Parameter(torch.Tensor([1.0]))
        self.gp = gprh.GP_1D(sigma_f=1.0, lengthscale=1, sigma_n=2 * noise_std)

    def forward(self, x_train, y_train=None, m=None, x_test=None):
        """In the forward function we accept a Tensor of input data and we must return a Tensor of output data. We can use Modules defined in the constructor as well as arbitrary operators on Tensors."""
        h = x_train.clone()
        h = self.linear1(h)
        h = self.tanh1(h)
        h = self.linear2(h)
        h = self.tanh2(h)
        h = self.linear3(h)
        h = self.tanh3(h)
        h = self.linear4(h)
        h = self.tanh4(h)
        h = self.scale * h
        if x_test is not None:
            h2 = x_test.clone()
            h2 = self.linear1(h2)
            h2 = self.tanh1(h2)
            h2 = self.linear2(h2)
            h2 = self.tanh2(h2)
            h2 = self.linear3(h2)
            h2 = self.tanh3(h2)
            h2 = self.linear4(h2)
            h2 = self.tanh4(h2)
            h2 = self.scale * h2
        else:
            h2 = None
        if y_train is not None:
            out = self.gp(h, y_train, m, h2)
        else:
            out = h
        return out


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

Class description:
Class for potency analysis

Method signatures and docstrings:
- def get_ic50(df=None, x_label=None, y_label=None): Get ic50 for x depending on y
- def plot_ic50(ax=None, df=None, x_label=None, y_label=None, legend_label=None, fitted=True, xypos_ic50_f=None, log_scale=True, color=None, ic50_unit='µM', size_label=20, size_legend=16, size_info=18): Plot lineplot for concentration with fitted curve used to determine IC50

Implement the Python class `PotencyAnalysis` described below.

Class description:
Class for potency analysis

Method signatures and docstrings:
- def get_ic50(df=None, x_label=None, y_label=None): Get ic50 for x depending on y
- def plot_ic50(ax=None, df=None, x_label=None, y_label=None, legend_label=None, fitted=True, xypos_ic50_f=None, log_scale=True, color=None, ic50_unit='µM', size_label=20, size_legend=16, size_info=18): Plot lineplot for concentration with fitted curve used to determine IC50

<|skeleton|>
class PotencyAnalysis:
    """Class for potency analysis"""

    def get_ic50(df=None, x_label=None, y_label=None):
        """Get ic50 for x depending on y"""
        <|body_0|>

    def plot_ic50(ax=None, df=None, x_label=None, y_label=None, legend_label=None, fitted=True, xypos_ic50_f=None, log_scale=True, color=None, ic50_unit='µM', size_label=20, size_legend=16, size_info=18):
        """Plot lineplot for concentration with fitted curve used to determine IC50"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        df = df[[x_label, y_label]].dropna()
        x = np.array(df[x_label])
        y = np.array(df[y_label])
        xdata, ydata, str_formula = _get_fitted_curve(f=_exp_reg, x=x, y=y)
        x50, y50 = _get_x50_y50(xdata=xdata, ydata=ydata)
        return (x50, y50)
<|end_body_0|>

<|body_start_1|>
        if xypos_ic50_f is None:
            xypos_ic50_f = [1, 1.4, 0.5, 0.5]
        xpos_ic50, ypos_ic50, xpos_f, ypos_f = xypos_ic50_f
        df = df[[x_label, y_label]].dropna()
        x_array = np.array(df[x_label])
        y_array = np.array(df[y_label])
        xdata, ydata, str_formula = _get_fitted_curve(f=_exp_reg, x=x_array, y=y_array)
        x50, y50 = _get_x50_y50(xdata=xdata, ydata=ydata)
        if legend_label is None:
            legend_label = 'data'
        ax = sns.lineplot(ax=ax, data=df, x=x_label, y=y_array, color=color, legend=True, linewidth=3, linestyle='-', label=legend_label, err_style='bars')
        if fitted:
            ax = sns.lineplot(ax=ax, x=xdata, y=ydata, linestyle='--', linewidth=3, color='black', label='fitted')
            if log_scale:
                ax.set(xscale='log')
            arrow_properties = dict(facecolor='black', width=0.5, headwidth=4, shrink=0.1)
            plt.annotate(f'IC50 = {round(x50, 1)} {ic50_unit}', (x50, y50), (x50 * xpos_ic50, y50 * ypos_ic50), horizontalalignment='center', arrowprops=arrow_properties, fontsize=size_info)
            plt.legend(fontsize=size_legend)
            plt.text(x50 * xpos_f, y50 * ypos_f, str_formula, fontsize=size_info)
        else:
            ax = plt.gca()
            ax.get_legend().remove()
        plt.ylabel(y_label, size=size_label, weight='bold')
        plt.xlabel(x_label, size=size_label, weight='bold')
        sns.despine()
        return ax
<|end_body_1|>

Solution:
class PotencyAnalysis:
    """Class for potency analysis"""

    def get_ic50(df=None, x_label=None, y_label=None):
        """Get ic50 for x depending on y"""
        df = df[[x_label, y_label]].dropna()
        x = np.array(df[x_label])
        y = np.array(df[y_label])
        xdata, ydata, str_formula = _get_fitted_curve(f=_exp_reg, x=x, y=y)
        x50, y50 = _get_x50_y50(xdata=xdata, ydata=ydata)
        return (x50, y50)

    def plot_ic50(ax=None, df=None, x_label=None, y_label=None, legend_label=None, fitted=True, xypos_ic50_f=None, log_scale=True, color=None, ic50_unit='µM', size_label=20, size_legend=16, size_info=18):
        """Plot lineplot for concentration with fitted curve used to determine IC50"""
        if xypos_ic50_f is None:
            xypos_ic50_f = [1, 1.4, 0.5, 0.5]
        xpos_ic50, ypos_ic50, xpos_f, ypos_f = xypos_ic50_f
        df = df[[x_label, y_label]].dropna()
        x_array = np.array(df[x_label])
        y_array = np.array(df[y_label])
        xdata, ydata, str_formula = _get_fitted_curve(f=_exp_reg, x=x_array, y=y_array)
        x50, y50 = _get_x50_y50(xdata=xdata, ydata=ydata)
        if legend_label is None:
            legend_label = 'data'
        ax = sns.lineplot(ax=ax, data=df, x=x_label, y=y_array, color=color, legend=True, linewidth=3, linestyle='-', label=legend_label, err_style='bars')
        if fitted:
            ax = sns.lineplot(ax=ax, x=xdata, y=ydata, linestyle='--', linewidth=3, color='black', label='fitted')
            if log_scale:
                ax.set(xscale='log')
            arrow_properties = dict(facecolor='black', width=0.5, headwidth=4, shrink=0.1)
            plt.annotate(f'IC50 = {round(x50, 1)} {ic50_unit}', (x50, y50), (x50 * xpos_ic50, y50 * ypos_ic50), horizontalalignment='center', arrowprops=arrow_properties, fontsize=size_info)
            plt.legend(fontsize=size_legend)
            plt.text(x50 * xpos_f, y50 * ypos_f, str_formula, fontsize=size_info)
        else:
            ax = plt.gca()
            ax.get_legend().remove()
        plt.ylabel(y_label, size=size_label, weight='bold')
        plt.xlabel(x_label, size=size_label, weight='bold')
        sns.despine()
        return ax


serialize

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

Class description:
Implement the ConditionalAccessRoot class.

Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessRoot: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ConditionalAccessRoot
- def get_field_deserializers(self) -> Dict[str, Callable[[ParseNode], None]]: The deserialization information for the current model Returns: Dict[str, Callable[[ParseNode], None]]
- def serialize(self, writer: SerializationWriter) -> None: Serializes information the current object Args: writer: Serialization writer to use to serialize this model

Implement the Python class `ConditionalAccessRoot` described below.

Class description:
Implement the ConditionalAccessRoot class.

Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessRoot: Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ConditionalAccessRoot
- def get_field_deserializers(self) -> Dict[str, Callable[[ParseNode], None]]: The deserialization information for the current model Returns: Dict[str, Callable[[ParseNode], None]]
- def serialize(self, writer: SerializationWriter) -> None: Serializes information the current object Args: writer: Serialization writer to use to serialize this model

<|skeleton|>
class ConditionalAccessRoot:

    def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessRoot:
        """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ConditionalAccessRoot"""
        <|body_0|>

    def get_field_deserializers(self) -> Dict[str, Callable[[ParseNode], None]]:
        """The deserialization information for the current model Returns: Dict[str, Callable[[ParseNode], None]]"""
        <|body_1|>

    def serialize(self, writer: SerializationWriter) -> None:
        """Serializes information the current object Args: writer: Serialization writer to use to serialize this model"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        if not parse_node:
            raise TypeError('parse_node cannot be null.')
        return ConditionalAccessRoot()
<|end_body_0|>

<|body_start_1|>
        from .authentication_context_class_reference import AuthenticationContextClassReference
        from .authentication_strength_root import AuthenticationStrengthRoot
        from .conditional_access_policy import ConditionalAccessPolicy
        from .conditional_access_template import ConditionalAccessTemplate
        from .entity import Entity
        from .named_location import NamedLocation
        from .authentication_context_class_reference import AuthenticationContextClassReference
        from .authentication_strength_root import AuthenticationStrengthRoot
        from .conditional_access_policy import ConditionalAccessPolicy
        from .conditional_access_template import ConditionalAccessTemplate
        from .entity import Entity
        from .named_location import NamedLocation
        fields: Dict[str, Callable[[Any], None]] = {'authenticationContextClassReferences': lambda n: setattr(self, 'authentication_context_class_references', n.get_collection_of_object_values(AuthenticationContextClassReference)), 'authenticationStrength': lambda n: setattr(self, 'authentication_strength', n.get_object_value(AuthenticationStrengthRoot)), 'namedLocations': lambda n: setattr(self, 'named_locations', n.get_collection_of_object_values(NamedLocation)), 'policies': lambda n: setattr(self, 'policies', n.get_collection_of_object_values(ConditionalAccessPolicy)), 'templates': lambda n: setattr(self, 'templates', n.get_collection_of_object_values(ConditionalAccessTemplate))}
        super_fields = super().get_field_deserializers()
        fields.update(super_fields)
        return fields
<|end_body_1|>

<|body_start_2|>
        if not writer:
            raise TypeError('writer cannot be null.')
        super().serialize(writer)
        writer.write_collection_of_object_values('authenticationContextClassReferences', self.authentication_context_class_references)
        writer.write_object_value('authenticationStrength', self.authentication_strength)
        writer.write_collection_of_object_values('namedLocations', self.named_locations)
        writer.write_collection_of_object_values('policies', self.policies)
        writer.write_collection_of_object_values('templates', self.templates)
<|end_body_2|>

Solution:
class ConditionalAccessRoot:
    def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConditionalAccessRoot:
        """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ConditionalAccessRoot"""
        if not parse_node:
            raise TypeError('parse_node cannot be null.')
        return ConditionalAccessRoot()

    def get_field_deserializers(self) -> Dict[str, Callable[[ParseNode], None]]:
        """The deserialization information for the current model Returns: Dict[str, Callable[[ParseNode], None]]"""
        from .authentication_context_class_reference import AuthenticationContextClassReference
        from .authentication_strength_root import AuthenticationStrengthRoot
        from .conditional_access_policy import ConditionalAccessPolicy
        from .conditional_access_template import ConditionalAccessTemplate
        from .entity import Entity
        from .named_location import NamedLocation
        from .authentication_context_class_reference import AuthenticationContextClassReference
        from .authentication_strength_root import AuthenticationStrengthRoot
        from .conditional_access_policy import ConditionalAccessPolicy
        from .conditional_access_template import ConditionalAccessTemplate
        from .entity import Entity
        from .named_location import NamedLocation
        fields: Dict[str, Callable[[Any], None]] = {'authenticationContextClassReferences': lambda n: setattr(self, 'authentication_context_class_references', n.get_collection_of_object_values(AuthenticationContextClassReference)), 'authenticationStrength': lambda n: setattr(self, 'authentication_strength', n.get_object_value(AuthenticationStrengthRoot)), 'namedLocations': lambda n: setattr(self, 'named_locations', n.get_collection_of_object_values(NamedLocation)), 'policies': lambda n: setattr(self, 'policies', n.get_collection_of_object_values(ConditionalAccessPolicy)), 'templates': lambda n: setattr(self, 'templates', n.get_collection_of_object_values(ConditionalAccessTemplate))}
        super_fields = super().get_field_deserializers()
        fields.update(super_fields)
        return fields

    def serialize(self, writer: SerializationWriter) -> None:
        """Serializes information the current object Args: writer: Serialization writer to use to serialize this model"""
        if not writer:
            raise TypeError('writer cannot be null.')
        super().serialize(writer)
        writer.write_collection_of_object_values('authenticationContextClassReferences', self.authentication_context_class_references)
        writer.write_object_value('authenticationStrength', self.authentication_strength)
        writer.write_collection_of_object_values('namedLocations', self.named_locations)
        writer.write_collection_of_object_values('policies', self.policies)
        writer.write_collection_of_object_values('templates', self.templates)


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

Class description:
Implement the SerieResource class.

Method signatures and docstrings:
- def get(self): Get list of the most popular Series
- def post(self): Add additional Serie for validation

Implement the Python class `SerieResource` described below.

Class description:
Implement the SerieResource class.

Method signatures and docstrings:
- def get(self): Get list of the most popular Series
- def post(self): Add additional Serie for validation

<|skeleton|>
class SerieResource:

    def get(self):
        """Get list of the most popular Series"""
        <|body_0|>

    def post(self):
        """Add additional Serie for validation"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        user_uuid = get_jwt_identity()
        try:
            page = int(request.args.get('page'))
        except (ValueError, TypeError):
            page = 1
        return SerieService.get_popular_series(page, user_uuid)
<|end_body_0|>

<|body_start_1|>
        user_uuid = get_jwt_identity()
        data = request.get_json()
        return SerieService.add_additional_serie(user_uuid, data)
<|end_body_1|>

Solution:
class SerieResource:
    def get(self):
        """Get list of the most popular Series"""
        user_uuid = get_jwt_identity()
        try:
            page = int(request.args.get('page'))
        except (ValueError, TypeError):
            page = 1
        return SerieService.get_popular_series(page, user_uuid)

    def post(self):
        """Add additional Serie for validation"""
        user_uuid = get_jwt_identity()
        data = request.get_json()
        return SerieService.add_additional_serie(user_uuid, data)


get

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

Class description:
Implement the IndexView class.

Method signatures and docstrings:
- def get_recent_playlist(): Obtenemos las últimas 5 publicaciones :return:
- def get(self, request): Devolvemos consulta de publicaciones al usuario

Implement the Python class `IndexView` described below.

Class description:
Implement the IndexView class.

Method signatures and docstrings:
- def get_recent_playlist(): Obtenemos las últimas 5 publicaciones :return:
- def get(self, request): Devolvemos consulta de publicaciones al usuario

<|skeleton|>
class IndexView:

    def get_recent_playlist():
        """Obtenemos las últimas 5 publicaciones :return:"""
        <|body_0|>

    def get(self, request):
        """Devolvemos consulta de publicaciones al usuario"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        cache_blog_recent_post = cache.get('pythonizame_recent_playlist')
        if cache_blog_recent_post:
            queryset = cache_blog_recent_post
        else:
            queryset = PlayList.objects.filter(status=1).order_by('-timestamp')[:5]
            cache.set('pythonizame_recent_playlist', queryset, 60 * 5)
        return queryset
<|end_body_0|>

<|body_start_1|>
        if 'q' in request.GET and request.GET['q']:
            search_words = request.GET['q']
            queryset = video_search(search_words)
        else:
            search_words = ''
            queryset = PlayList.objects.filter(status=1).order_by('-timestamp')
        paginator = Paginator(queryset, 18)
        if 'page' in request.GET and request.GET['page']:
            my_page = int(request.GET['page'])
        else:
            my_page = 1
        try:
            object_list = paginator.page(my_page)
        except PageNotAnInteger:
            object_list = paginator.page(1)
        except EmptyPage:
            object_list = paginator.page(paginator.num_pages)
        categories = VideoCategory.objects.all()
        ctx = {'object_list': object_list, 'categories': categories, 'page_obj': object_list, 'recent_playlist': self.get_recent_playlist(), 'queryset': search_words}
        return render(request, self.template_name, ctx)
<|end_body_1|>

Solution:
class IndexView:
    def get_recent_playlist():
        """Obtenemos las últimas 5 publicaciones :return:"""
        cache_blog_recent_post = cache.get('pythonizame_recent_playlist')
        if cache_blog_recent_post:
            queryset = cache_blog_recent_post
        else:
            queryset = PlayList.objects.filter(status=1).order_by('-timestamp')[:5]
            cache.set('pythonizame_recent_playlist', queryset, 60 * 5)
        return queryset

    def get(self, request):
        """Devolvemos consulta de publicaciones al usuario"""
        if 'q' in request.GET and request.GET['q']:
            search_words = request.GET['q']
            queryset = video_search(search_words)
        else:
            search_words = ''
            queryset = PlayList.objects.filter(status=1).order_by('-timestamp')
        paginator = Paginator(queryset, 18)
        if 'page' in request.GET and request.GET['page']:
            my_page = int(request.GET['page'])
        else:
            my_page = 1
        try:
            object_list = paginator.page(my_page)
        except PageNotAnInteger:
            object_list = paginator.page(1)
        except EmptyPage:
            object_list = paginator.page(paginator.num_pages)
        categories = VideoCategory.objects.all()
        ctx = {'object_list': object_list, 'categories': categories, 'page_obj': object_list, 'recent_playlist': self.get_recent_playlist(), 'queryset': search_words}
        return render(request, self.template_name, ctx)


maximumUniqueSubarray

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def maximumUniqueSubarray(self, nums: List[int]) -> int: 直接暴力法硬怼 毫无疑问超时了 因为题目给出了数据规模在 10^5 :param nums: :return:
- def maximumUniqueSubarray2(self, nums: List[int]) -> int: 滑动窗口模板 直接套就行了 :param nums: :return:

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def maximumUniqueSubarray(self, nums: List[int]) -> int: 直接暴力法硬怼 毫无疑问超时了 因为题目给出了数据规模在 10^5 :param nums: :return:
- def maximumUniqueSubarray2(self, nums: List[int]) -> int: 滑动窗口模板 直接套就行了 :param nums: :return:

<|skeleton|>
class Solution:

    def maximumUniqueSubarray(self, nums: List[int]) -> int:
        """直接暴力法硬怼 毫无疑问超时了 因为题目给出了数据规模在 10^5 :param nums: :return:"""
        <|body_0|>

    def maximumUniqueSubarray2(self, nums: List[int]) -> int:
        """滑动窗口模板 直接套就行了 :param nums: :return:"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            return nums[0]
        visited = set()
        max_res = 0
        res = 0
        for i in range(n):
            for j in range(i, n):
                if nums[j] not in visited:
                    max_res += nums[j]
                    visited.add(nums[j])
                else:
                    res = max(max_res, res)
                    max_res = 0
                    visited.clear()
                    break
        return res
<|end_body_0|>

<|body_start_1|>
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            return nums[0]
        counters = [0] * 10001
        cur = 0
        res = 0
        l, r = (0, 0)
        while r < n:
            cur += nums[r]
            counters[nums[r]] += 1
            while l < r and counters[nums[r]] > 1:
                cur -= nums[l]
                counters[nums[l]] -= 1
                l += 1
            res = max(res, cur)
            r += 1
        return res
<|end_body_1|>

Solution:
class Solution:
    def maximumUniqueSubarray(self, nums: List[int]) -> int:
        """直接暴力法硬怼 毫无疑问超时了 因为题目给出了数据规模在 10^5 :param nums: :return:"""
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            return nums[0]
        visited = set()
        max_res = 0
        res = 0
        for i in range(n):
            for j in range(i, n):
                if nums[j] not in visited:
                    max_res += nums[j]
                    visited.add(nums[j])
                else:
                    res = max(max_res, res)
                    max_res = 0
                    visited.clear()
                    break
        return res

    def maximumUniqueSubarray2(self, nums: List[int]) -> int:
        """滑动窗口模板 直接套就行了 :param nums: :return:"""
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            return nums[0]
        counters = [0] * 10001
        cur = 0
        res = 0
        l, r = (0, 0)
        while r < n:
            cur += nums[r]
            counters[nums[r]] += 1
            while l < r and counters[nums[r]] > 1:
                cur -= nums[l]
                counters[nums[l]] -= 1
                l += 1
            res = max(res, cur)
            r += 1
        return res

LeetCode周赛/2020-12-20第220场周赛/删除子数组的最大得分.py


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

Class description:
Implement the QueryUniprotOrg class.

Method signatures and docstrings:
- def __init__(self, query, api='https://www.uniprot.org/uniprot/?', include='yes', compress='no', limit=1, offset=0): Init Args: query (:obj:`str`): query message. url (:obj:`int`, optional): API url. include (:obj:`str`, optional): See description in link. Defaults to 'yes'. compress (:obj:`str`, optional): Return results gzipped. Defaults to 'no'. limit (:obj:`int`, optional): Max number of results to return. Defaults to 1. offset (:obj:`int`, optional): Offset of the first result. Defaults to 0.
- def get_kegg_ortholog(self): Get kegg ortholog information using query message. Return: (:obj:`str`): kegg ortholog number
- def get_uniprot_id(self): Get uniprot id. Return: (:obj:`str`): uniprot id
- def get_protein_name(self): Get protein name. Return: (:obj:`list` of :obj:`str`): list of protein names.

Implement the Python class `QueryUniprotOrg` described below.

Class description:
Implement the QueryUniprotOrg class.

Method signatures and docstrings:
- def __init__(self, query, api='https://www.uniprot.org/uniprot/?', include='yes', compress='no', limit=1, offset=0): Init Args: query (:obj:`str`): query message. url (:obj:`int`, optional): API url. include (:obj:`str`, optional): See description in link. Defaults to 'yes'. compress (:obj:`str`, optional): Return results gzipped. Defaults to 'no'. limit (:obj:`int`, optional): Max number of results to return. Defaults to 1. offset (:obj:`int`, optional): Offset of the first result. Defaults to 0.
- def get_kegg_ortholog(self): Get kegg ortholog information using query message. Return: (:obj:`str`): kegg ortholog number
- def get_uniprot_id(self): Get uniprot id. Return: (:obj:`str`): uniprot id
- def get_protein_name(self): Get protein name. Return: (:obj:`list` of :obj:`str`): list of protein names.

<|skeleton|>
class QueryUniprotOrg:

    def __init__(self, query, api='https://www.uniprot.org/uniprot/?', include='yes', compress='no', limit=1, offset=0):
        """Init Args: query (:obj:`str`): query message. url (:obj:`int`, optional): API url. include (:obj:`str`, optional): See description in link. Defaults to 'yes'. compress (:obj:`str`, optional): Return results gzipped. Defaults to 'no'. limit (:obj:`int`, optional): Max number of results to return. Defaults to 1. offset (:obj:`int`, optional): Offset of the first result. Defaults to 0."""
        <|body_0|>

    def get_kegg_ortholog(self):
        """Get kegg ortholog information using query message. Return: (:obj:`str`): kegg ortholog number"""
        <|body_1|>

    def get_uniprot_id(self):
        """Get uniprot id. Return: (:obj:`str`): uniprot id"""
        <|body_2|>

    def get_protein_name(self):
        """Get protein name. Return: (:obj:`list` of :obj:`str`): list of protein names."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        columns = 'id,entry name,genes(PREFERRED),protein names,sequence,length,mass,ec,database(GeneID),reviewed,organism-id,database(KO),genes(ALTERNATIVE),genes(ORF),genes(OLN),database(EMBL),database(RefSeq),database(KEGG)'
        suffix = 'query={}&sort=score&columns={}format={}&include={}&compress={}&limit={}&offset={}'.format(query, columns, 'html', include, compress, limit, offset)
        url = api + suffix
        response = requests.get(url)
        self.soup = BeautifulSoup(response.content, 'html.parser')
<|end_body_0|>

<|body_start_1|>
        rx = re.compile('.*dbget-bin.*')
        result = self.soup.find_all(href=rx)
        if result != []:
            return result[0].get_text()
        else:
            return None
<|end_body_1|>

<|body_start_2|>
        result = self.soup.find_all(class_='basket-item namespace-uniprot')
        if result != []:
            return result[0]['id'].split('_')[1]
        else:
            return None
<|end_body_2|>

<|body_start_3|>
        result = []
        tmp = self.soup.find_all(class_='protein_names')
        if tmp != []:
            result.append(tmp[0].div['title'])
            alt_names = tmp[0].div.next_sibling.get_text()
            atl_name_split = alt_names.strip().split(')  (')
            for x in atl_name_split:
                for y in x.split(','):
                    result.append(y.strip())
            return result
        else:
            return None
<|end_body_3|>

Solution:
class QueryUniprotOrg:
    def __init__(self, query, api='https://www.uniprot.org/uniprot/?', include='yes', compress='no', limit=1, offset=0):
        """Init Args: query (:obj:`str`): query message. url (:obj:`int`, optional): API url. include (:obj:`str`, optional): See description in link. Defaults to 'yes'. compress (:obj:`str`, optional): Return results gzipped. Defaults to 'no'. limit (:obj:`int`, optional): Max number of results to return. Defaults to 1. offset (:obj:`int`, optional): Offset of the first result. Defaults to 0."""
        columns = 'id,entry name,genes(PREFERRED),protein names,sequence,length,mass,ec,database(GeneID),reviewed,organism-id,database(KO),genes(ALTERNATIVE),genes(ORF),genes(OLN),database(EMBL),database(RefSeq),database(KEGG)'
        suffix = 'query={}&sort=score&columns={}format={}&include={}&compress={}&limit={}&offset={}'.format(query, columns, 'html', include, compress, limit, offset)
        url = api + suffix
        response = requests.get(url)
        self.soup = BeautifulSoup(response.content, 'html.parser')

    def get_kegg_ortholog(self):
        """Get kegg ortholog information using query message. Return: (:obj:`str`): kegg ortholog number"""
        rx = re.compile('.*dbget-bin.*')
        result = self.soup.find_all(href=rx)
        if result != []:
            return result[0].get_text()
        else:
            return None

    def get_uniprot_id(self):
        """Get uniprot id. Return: (:obj:`str`): uniprot id"""
        result = self.soup.find_all(class_='basket-item namespace-uniprot')
        if result != []:
            return result[0]['id'].split('_')[1]
        else:
            return None

    def get_protein_name(self):
        """Get protein name. Return: (:obj:`list` of :obj:`str`): list of protein names."""
        result = []
        tmp = self.soup.find_all(class_='protein_names')
        if tmp != []:
            result.append(tmp[0].div['title'])
            alt_names = tmp[0].div.next_sibling.get_text()
            atl_name_split = alt_names.strip().split(')  (')
            for x in atl_name_split:
                for y in x.split(','):
                    result.append(y.strip())
            return result
        else:
            return None


complete

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

Class description:
Implement the Completer class.

Method signatures and docstrings:
- def __init__(self, namespace=None, global_namespace=None): Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. An optional second namespace can be given. This allows the completer to handle cases where both the local and global scopes need to be distinguished. Completer instances should be used as the completion mechanism of readline via the set_completer() call: readline.set_completer(Completer(my_namespace).complete)
- def complete(self, text): Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'.
- def global_matches(self, text): Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match.
- def attr_matches(self, text): Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated.

Implement the Python class `Completer` described below.

Class description:
Implement the Completer class.

Method signatures and docstrings:
- def __init__(self, namespace=None, global_namespace=None): Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. An optional second namespace can be given. This allows the completer to handle cases where both the local and global scopes need to be distinguished. Completer instances should be used as the completion mechanism of readline via the set_completer() call: readline.set_completer(Completer(my_namespace).complete)
- def complete(self, text): Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'.
- def global_matches(self, text): Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match.
- def attr_matches(self, text): Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated.

<|skeleton|>
class Completer:

    def __init__(self, namespace=None, global_namespace=None):
        """Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. An optional second namespace can be given. This allows the completer to handle cases where both the local and global scopes need to be distinguished. Completer instances should be used as the completion mechanism of readline via the set_completer() call: readline.set_completer(Completer(my_namespace).complete)"""
        <|body_0|>

    def complete(self, text):
        """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'."""
        <|body_1|>

    def global_matches(self, text):
        """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match."""
        <|body_2|>

    def attr_matches(self, text):
        """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated."""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        if namespace is None:
            self.use_main_ns = 1
        else:
            self.use_main_ns = 0
            self.namespace = namespace
        if global_namespace is None:
            self.global_namespace = {}
        else:
            self.global_namespace = global_namespace
<|end_body_0|>

<|body_start_1|>
        if self.use_main_ns:
            raise RuntimeError('Namespace must be provided!')
        if '.' in text:
            return self.attr_matches(text)
        else:
            return self.global_matches(text)
<|end_body_1|>

<|body_start_2|>
        def get_item(obj, attr):
            return obj[attr]
        a = {}
        filtered_builtin = {}
        for key, val in dict_iter_items(__builtin__.__dict__):
            if not (val is True or val is False or val is None):
                filtered_builtin[key] = val
        for dict_with_comps in [filtered_builtin, self.namespace, self.global_namespace]:
            a.update(dict_with_comps)
        filter = _StartsWithFilter(text)
        return dir2(a, a.keys(), get_item, filter)
<|end_body_2|>

<|body_start_3|>
        import re
        m = re.match('(\\S+(\\.\\w+)*)\\.(\\w*)$', text)
        if not m:
            return []
        expr, attr = m.group(1, 3)
        try:
            obj = eval(expr, self.namespace)
        except:
            try:
                obj = eval(expr, self.global_namespace)
            except:
                return []
        filter = _StartsWithFilter(attr)
        words = dir2(obj, filter=filter)
        return words
<|end_body_3|>

Solution:
class Completer:
    def __init__(self, namespace=None, global_namespace=None):
        """Create a new completer for the command line. Completer([namespace,global_namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. An optional second namespace can be given. This allows the completer to handle cases where both the local and global scopes need to be distinguished. Completer instances should be used as the completion mechanism of readline via the set_completer() call: readline.set_completer(Completer(my_namespace).complete)"""
        if namespace is None:
            self.use_main_ns = 1
        else:
            self.use_main_ns = 0
            self.namespace = namespace
        if global_namespace is None:
            self.global_namespace = {}
        else:
            self.global_namespace = global_namespace

    def complete(self, text):
        """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'."""
        if self.use_main_ns:
            raise RuntimeError('Namespace must be provided!')
        if '.' in text:
            return self.attr_matches(text)
        else:
            return self.global_matches(text)

    def global_matches(self, text):
        """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match."""
        def get_item(obj, attr):
            return obj[attr]
        a = {}
        filtered_builtin = {}
        for key, val in dict_iter_items(__builtin__.__dict__):
            if not (val is True or val is False or val is None):
                filtered_builtin[key] = val
        for dict_with_comps in [filtered_builtin, self.namespace, self.global_namespace]:
            a.update(dict_with_comps)
        filter = _StartsWithFilter(text)
        return dir2(a, a.keys(), get_item, filter)

    def attr_matches(self, text):
        """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated."""
        import re
        m = re.match('(\\S+(\\.\\w+)*)\\.(\\w*)$', text)
        if not m:
            return []
        expr, attr = m.group(1, 3)
        try:
            obj = eval(expr, self.namespace)
        except:
            try:
                obj = eval(expr, self.global_namespace)
            except:
                return []
        filter = _StartsWithFilter(attr)
        words = dir2(obj, filter=filter)
        return words