delete

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

Class description:
Study API

Method signatures and docstrings:
- def get(self, kf_id): Get a study by id --- template: path: get_by_id.yml properties: resource: Study
- def patch(self, kf_id): Update an existing study. Allows partial update of resource --- template: path: update_by_id.yml properties: resource: Study
- def delete(self, kf_id): Delete study by id --- template: path: delete_by_id.yml properties: resource: Study

Implement the Python class `StudyAPI` described below.

Class description:
Study API

Method signatures and docstrings:
- def get(self, kf_id): Get a study by id --- template: path: get_by_id.yml properties: resource: Study
- def patch(self, kf_id): Update an existing study. Allows partial update of resource --- template: path: update_by_id.yml properties: resource: Study
- def delete(self, kf_id): Delete study by id --- template: path: delete_by_id.yml properties: resource: Study

<|skeleton|>
class StudyAPI:
    """Study API"""

    def get(self, kf_id):
        """Get a study by id --- template: path: get_by_id.yml properties: resource: Study"""
        <|body_0|>

    def patch(self, kf_id):
        """Update an existing study. Allows partial update of resource --- template: path: update_by_id.yml properties: resource: Study"""
        <|body_1|>

    def delete(self, kf_id):
        """Delete study by id --- template: path: delete_by_id.yml properties: resource: Study"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        st = Study.query.get(kf_id)
        if st is None:
            abort(404, 'could not find {} `{}`'.format('study', kf_id))
        return StudySchema().jsonify(st)
<|end_body_0|>

<|body_start_1|>
        body = request.get_json(force=True)
        st = Study.query.get(kf_id)
        if st is None:
            abort(404, 'could not find {} `{}`'.format('study', kf_id))
        try:
            st = StudySchema(strict=True).load(body, instance=st, partial=True).data
        except ValidationError as err:
            abort(400, 'could not update study: {}'.format(err.messages))
        db.session.add(st)
        db.session.commit()
        return (StudySchema(200, 'study {} updated'.format(st.kf_id)).jsonify(st), 200)
<|end_body_1|>

<|body_start_2|>
        st = Study.query.get(kf_id)
        if st is None:
            abort(404, 'could not find {} `{}`'.format('study', kf_id))
        db.session.delete(st)
        db.session.commit()
        return (StudySchema(200, 'study {} deleted'.format(st.kf_id)).jsonify(st), 200)
<|end_body_2|>

Solution:
class StudyAPI:
    """Study API"""

    def get(self, kf_id):
        """Get a study by id --- template: path: get_by_id.yml properties: resource: Study"""
        st = Study.query.get(kf_id)
        if st is None:
            abort(404, 'could not find {} `{}`'.format('study', kf_id))
        return StudySchema().jsonify(st)

    def patch(self, kf_id):
        """Update an existing study. Allows partial update of resource --- template: path: update_by_id.yml properties: resource: Study"""
        body = request.get_json(force=True)
        st = Study.query.get(kf_id)
        if st is None:
            abort(404, 'could not find {} `{}`'.format('study', kf_id))
        try:
            st = StudySchema(strict=True).load(body, instance=st, partial=True).data
        except ValidationError as err:
            abort(400, 'could not update study: {}'.format(err.messages))
        db.session.add(st)
        db.session.commit()
        return (StudySchema(200, 'study {} updated'.format(st.kf_id)).jsonify(st), 200)

    def delete(self, kf_id):
        """Delete study by id --- template: path: delete_by_id.yml properties: resource: Study"""
        st = Study.query.get(kf_id)
        if st is None:
            abort(404, 'could not find {} `{}`'.format('study', kf_id))
        db.session.delete(st)
        db.session.commit()
        return (StudySchema(200, 'study {} deleted'.format(st.kf_id)).jsonify(st), 200)


绑定（改绑）用户邮箱或者手机号 需发送验证码验证

factory

简单工厂管理手机号和邮箱的改绑

put

改绑OR绑定用户的手机或者邮箱

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

Class description:
绑定（改绑）用户邮箱或者手机号 需发送验证码验证

Method signatures and docstrings:
- def bind_phone(cache, instance, validated_data): 改绑手机号
- def bind_email(cache, instance, validated_data): 改绑邮箱
- def factory(self, way, validated_data, instance): 简单工厂管理手机号和邮箱的改绑
- def put(self, request): 改绑OR绑定用户的手机或者邮箱

Implement the Python class `BindEmailOrPhone` described below.

Class description:
绑定（改绑）用户邮箱或者手机号 需发送验证码验证

Method signatures and docstrings:
- def bind_phone(cache, instance, validated_data): 改绑手机号
- def bind_email(cache, instance, validated_data): 改绑邮箱
- def factory(self, way, validated_data, instance): 简单工厂管理手机号和邮箱的改绑
- def put(self, request): 改绑OR绑定用户的手机或者邮箱

<|skeleton|>
class BindEmailOrPhone:
    """绑定（改绑）用户邮箱或者手机号 需发送验证码验证"""

    def bind_phone(cache, instance, validated_data):
        """改绑手机号"""
        <|body_0|>

    def bind_email(cache, instance, validated_data):
        """改绑邮箱"""
        <|body_1|>

    def factory(self, way, validated_data, instance):
        """简单工厂管理手机号和邮箱的改绑"""
        <|body_2|>

    def put(self, request):
        """改绑OR绑定用户的手机或者邮箱"""
        <|body_3|>

<|end_skeleton|>

<|body_start_0|>
        is_existed = validated_data['is_existed']
        code = validated_data['code']
        new_phone = validated_data['phone']
        if is_existed:
            old_phone = validated_data['old_phone']
            is_success = cache.check_code(old_phone, code)
        else:
            is_success = cache.check_code(new_phone, code)
        if is_success:
            instance.phone = new_phone
            try:
                instance.save()
            except Exception as e:
                consumer_logger.error(e)
                return False
            else:
                return True
        return False
<|end_body_0|>

<|body_start_1|>
        is_existed = validated_data['is_existed']
        code = validated_data['code']
        new_email = validated_data['email']
        if is_existed:
            old_email = validated_data['old_email']
            is_success = cache.check_code(old_email, code)
        else:
            is_success = cache.check_code(new_email, code)
        if is_success:
            instance.email = new_email
            try:
                instance.save()
            except Exception as e:
                consumer_logger.error(e)
                return False
            else:
                return True
        return False
<|end_body_1|>

<|body_start_2|>
        func_list = {'email': 'bind_email', 'phone': 'bind_phone'}
        func = func_list.get(way)
        bind = getattr(self, func)
        return bind(self.redis, instance, validated_data)
<|end_body_2|>

<|body_start_3|>
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        way = serializer.validated_data.get('way')
        bind_success = self.factory(way, serializer.validated_data, request.user)
        if bind_success:
            return Response(response_code.bind_success, status=status.HTTP_200_OK)
        return Response(response_code.bind_error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
<|end_body_3|>

Solution:
class BindEmailOrPhone:
    """绑定（改绑）用户邮箱或者手机号 需发送验证码验证"""

    def bind_phone(cache, instance, validated_data):
        """改绑手机号"""
        is_existed = validated_data['is_existed']
        code = validated_data['code']
        new_phone = validated_data['phone']
        if is_existed:
            old_phone = validated_data['old_phone']
            is_success = cache.check_code(old_phone, code)
        else:
            is_success = cache.check_code(new_phone, code)
        if is_success:
            instance.phone = new_phone
            try:
                instance.save()
            except Exception as e:
                consumer_logger.error(e)
                return False
            else:
                return True
        return False

    def bind_email(cache, instance, validated_data):
        """改绑邮箱"""
        is_existed = validated_data['is_existed']
        code = validated_data['code']
        new_email = validated_data['email']
        if is_existed:
            old_email = validated_data['old_email']
            is_success = cache.check_code(old_email, code)
        else:
            is_success = cache.check_code(new_email, code)
        if is_success:
            instance.email = new_email
            try:
                instance.save()
            except Exception as e:
                consumer_logger.error(e)
                return False
            else:
                return True
        return False

    def factory(self, way, validated_data, instance):
        """简单工厂管理手机号和邮箱的改绑"""
        func_list = {'email': 'bind_email', 'phone': 'bind_phone'}
        func = func_list.get(way)
        bind = getattr(self, func)
        return bind(self.redis, instance, validated_data)

    def put(self, request):
        """改绑OR绑定用户的手机或者邮箱"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        way = serializer.validated_data.get('way')
        bind_success = self.factory(way, serializer.validated_data, request.user)
        if bind_success:
            return Response(response_code.bind_success, status=status.HTTP_200_OK)
        return Response(response_code.bind_error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


SubnetsByCIDR

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

Class description:
Implement the SubnetsFacade class.

Method signatures and docstrings:
- async def AllZones(self): AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Returns -> ZoneResults
- async def ListSubnets(self, space_tag=None, zone=None): ListSubnets returns the matching subnets after applying optional filters. space_tag : str zone : str Returns -> ListSubnetsResults
- async def SubnetsByCIDR(self, cidrs=None): SubnetsByCIDR returns the collection of subnets matching each CIDR in the input. cidrs : typing.Sequence[str] Returns -> SubnetsResults

Implement the Python class `SubnetsFacade` described below.

Class description:
Implement the SubnetsFacade class.

Method signatures and docstrings:
- async def AllZones(self): AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Returns -> ZoneResults
- async def ListSubnets(self, space_tag=None, zone=None): ListSubnets returns the matching subnets after applying optional filters. space_tag : str zone : str Returns -> ListSubnetsResults
- async def SubnetsByCIDR(self, cidrs=None): SubnetsByCIDR returns the collection of subnets matching each CIDR in the input. cidrs : typing.Sequence[str] Returns -> SubnetsResults

<|skeleton|>
class SubnetsFacade:

    async def AllZones(self):
        """AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Returns -> ZoneResults"""
        <|body_0|>

    async def ListSubnets(self, space_tag=None, zone=None):
        """ListSubnets returns the matching subnets after applying optional filters. space_tag : str zone : str Returns -> ListSubnetsResults"""
        <|body_1|>

    async def SubnetsByCIDR(self, cidrs=None):
        """SubnetsByCIDR returns the collection of subnets matching each CIDR in the input. cidrs : typing.Sequence[str] Returns -> SubnetsResults"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        _params = dict()
        msg = dict(type='Subnets', request='AllZones', version=5, params=_params)
        reply = await self.rpc(msg)
        return reply
<|end_body_0|>

<|body_start_1|>
        if space_tag is not None and (not isinstance(space_tag, (bytes, str))):
            raise Exception('Expected space_tag to be a str, received: {}'.format(type(space_tag)))
        if zone is not None and (not isinstance(zone, (bytes, str))):
            raise Exception('Expected zone to be a str, received: {}'.format(type(zone)))
        _params = dict()
        msg = dict(type='Subnets', request='ListSubnets', version=5, params=_params)
        _params['space-tag'] = space_tag
        _params['zone'] = zone
        reply = await self.rpc(msg)
        return reply
<|end_body_1|>

<|body_start_2|>
        if cidrs is not None and (not isinstance(cidrs, (bytes, str, list))):
            raise Exception('Expected cidrs to be a Sequence, received: {}'.format(type(cidrs)))
        _params = dict()
        msg = dict(type='Subnets', request='SubnetsByCIDR', version=5, params=_params)
        _params['cidrs'] = cidrs
        reply = await self.rpc(msg)
        return reply
<|end_body_2|>

Solution:
class SubnetsFacade:
    async def AllZones(self):
        """AllZones returns all availability zones known to Juju. If a zone is unusable, unavailable, or deprecated the Available field will be false. Returns -> ZoneResults"""
        _params = dict()
        msg = dict(type='Subnets', request='AllZones', version=5, params=_params)
        reply = await self.rpc(msg)
        return reply

    async def ListSubnets(self, space_tag=None, zone=None):
        """ListSubnets returns the matching subnets after applying optional filters. space_tag : str zone : str Returns -> ListSubnetsResults"""
        if space_tag is not None and (not isinstance(space_tag, (bytes, str))):
            raise Exception('Expected space_tag to be a str, received: {}'.format(type(space_tag)))
        if zone is not None and (not isinstance(zone, (bytes, str))):
            raise Exception('Expected zone to be a str, received: {}'.format(type(zone)))
        _params = dict()
        msg = dict(type='Subnets', request='ListSubnets', version=5, params=_params)
        _params['space-tag'] = space_tag
        _params['zone'] = zone
        reply = await self.rpc(msg)
        return reply

    async def SubnetsByCIDR(self, cidrs=None):
        """SubnetsByCIDR returns the collection of subnets matching each CIDR in the input. cidrs : typing.Sequence[str] Returns -> SubnetsResults"""
        if cidrs is not None and (not isinstance(cidrs, (bytes, str, list))):
            raise Exception('Expected cidrs to be a Sequence, received: {}'.format(type(cidrs)))
        _params = dict()
        msg = dict(type='Subnets', request='SubnetsByCIDR', version=5, params=_params)
        _params['cidrs'] = cidrs
        reply = await self.rpc(msg)
        return reply


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

Class description:
Implement the Sequence class.

Method signatures and docstrings:
- def find_longest_consecutive(self, nums: List[int]) -> int: Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :return:
- def find_longest_consecutive_(self, nums: List[int]) -> int: Approach: Sorting Time Complexity: O(n log n) Space Complexity: O(1) :param nums: :return:
- def find_longest_consecutive__(self, nums: List[int]) -> int: Approach: Brute Force Time Complexity: O(n^3) Space Complexity: O(1) :param nums: :return:

Implement the Python class `Sequence` described below.

Class description:
Implement the Sequence class.

Method signatures and docstrings:
- def find_longest_consecutive(self, nums: List[int]) -> int: Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :return:
- def find_longest_consecutive_(self, nums: List[int]) -> int: Approach: Sorting Time Complexity: O(n log n) Space Complexity: O(1) :param nums: :return:
- def find_longest_consecutive__(self, nums: List[int]) -> int: Approach: Brute Force Time Complexity: O(n^3) Space Complexity: O(1) :param nums: :return:

<|skeleton|>
class Sequence:

    def find_longest_consecutive(self, nums: List[int]) -> int:
        """Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :return:"""
        <|body_0|>

    def find_longest_consecutive_(self, nums: List[int]) -> int:
        """Approach: Sorting Time Complexity: O(n log n) Space Complexity: O(1) :param nums: :return:"""
        <|body_1|>

    def find_longest_consecutive__(self, nums: List[int]) -> int:
        """Approach: Brute Force Time Complexity: O(n^3) Space Complexity: O(1) :param nums: :return:"""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        longest_streak = 0
        num_set = set(nums)
        for num in num_set:
            if num - 1 not in num_set:
                current_num = num
                current_streak = 1
                while current_num + 1 in num_set:
                    current_num += 1
                    current_streak += 1
                longest_streak = max(longest_streak, current_streak)
        return longest_streak
<|end_body_0|>

<|body_start_1|>
        if not nums:
            return 0
        longest_streak = current_streak = 1
        nums.sort()
        for i in range(1, len(nums)):
            if nums[i] != nums[i - 1]:
                if nums[i] == nums[i - 1] + 1:
                    current_streak += 1
                else:
                    longest_streak = max(longest_streak, current_streak)
                    current_streak = 1
        return max(longest_streak, current_streak)
<|end_body_1|>

<|body_start_2|>
        longest_streak = 0
        for num in nums:
            current_num = num
            current_streak = 1
            while current_num + 1 in nums:
                current_num += 1
                current_streak += 1
            longest_streak = max(longest_streak, current_streak)
        return longest_streak
<|end_body_2|>

Solution:
class Sequence:
    def find_longest_consecutive(self, nums: List[int]) -> int:
        """Approach: Hash Set and Intelligence Sequence Building Time Complexity: O(n) Space Complexity: O(n) :param nums: :return:"""
        longest_streak = 0
        num_set = set(nums)
        for num in num_set:
            if num - 1 not in num_set:
                current_num = num
                current_streak = 1
                while current_num + 1 in num_set:
                    current_num += 1
                    current_streak += 1
                longest_streak = max(longest_streak, current_streak)
        return longest_streak

    def find_longest_consecutive_(self, nums: List[int]) -> int:
        """Approach: Sorting Time Complexity: O(n log n) Space Complexity: O(1) :param nums: :return:"""
        if not nums:
            return 0
        longest_streak = current_streak = 1
        nums.sort()
        for i in range(1, len(nums)):
            if nums[i] != nums[i - 1]:
                if nums[i] == nums[i - 1] + 1:
                    current_streak += 1
                else:
                    longest_streak = max(longest_streak, current_streak)
                    current_streak = 1
        return max(longest_streak, current_streak)

    def find_longest_consecutive__(self, nums: List[int]) -> int:
        """Approach: Brute Force Time Complexity: O(n^3) Space Complexity: O(1) :param nums: :return:"""
        longest_streak = 0
        for num in nums:
            current_num = num
            current_streak = 1
            while current_num + 1 in nums:
                current_num += 1
                current_streak += 1
            longest_streak = max(longest_streak, current_streak)
        return longest_streak


GetPopulationDensity

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

Class description:
USGS Population Raster driver. This class manages the reading of population raster data provided by USGS at: https://www.sciencebase.gov/catalog/item/57753ebee4b07dd077c70868

Method signatures and docstrings:
- def __init__(self, pop_directory=None, lazy_load=False): Initializes the driver. Args: pop_directory: The directory holding the USGS population raster. If None, use the default location. lazy_load: If True, then lazy population loading done (as needed).
- def LoadRaster(self, box=None): Load raster in memory. Args: box: A (lat_min, lon_min, lat_max, lon_max) bounding box. If None, the full raster is loaded in memory.
- def GetPopulationDensity(self, latitudes, longitudes): Retrieves the population density on locations. Args: latitudes: A sequence of points latitudes. longitudes: A sequence of points longitudes. Returns: The population density (pop/km2) as a ndarray (dtype=int16).

Implement the Python class `UsgsPopDriver` described below.

Class description:
USGS Population Raster driver. This class manages the reading of population raster data provided by USGS at: https://www.sciencebase.gov/catalog/item/57753ebee4b07dd077c70868

Method signatures and docstrings:
- def __init__(self, pop_directory=None, lazy_load=False): Initializes the driver. Args: pop_directory: The directory holding the USGS population raster. If None, use the default location. lazy_load: If True, then lazy population loading done (as needed).
- def LoadRaster(self, box=None): Load raster in memory. Args: box: A (lat_min, lon_min, lat_max, lon_max) bounding box. If None, the full raster is loaded in memory.
- def GetPopulationDensity(self, latitudes, longitudes): Retrieves the population density on locations. Args: latitudes: A sequence of points latitudes. longitudes: A sequence of points longitudes. Returns: The population density (pop/km2) as a ndarray (dtype=int16).

<|skeleton|>
class UsgsPopDriver:
    """USGS Population Raster driver. This class manages the reading of population raster data provided by USGS at: https://www.sciencebase.gov/catalog/item/57753ebee4b07dd077c70868"""

    def __init__(self, pop_directory=None, lazy_load=False):
        """Initializes the driver. Args: pop_directory: The directory holding the USGS population raster. If None, use the default location. lazy_load: If True, then lazy population loading done (as needed)."""
        <|body_0|>

    def LoadRaster(self, box=None):
        """Load raster in memory. Args: box: A (lat_min, lon_min, lat_max, lon_max) bounding box. If None, the full raster is loaded in memory."""
        <|body_1|>

    def GetPopulationDensity(self, latitudes, longitudes):
        """Retrieves the population density on locations. Args: latitudes: A sequence of points latitudes. longitudes: A sequence of points longitudes. Returns: The population density (pop/km2) as a ndarray (dtype=int16)."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.lazy_load = lazy_load
        self.fully_loaded = False
        if not pop_directory:
            pop_directory = DEFAULT_POP_DIR
        tiff_path = glob.glob(os.path.join(pop_directory, '*.tif'))
        if not tiff_path:
            raise ValueError('No TIFF file name in directory: %s' % pop_directory)
        self._tiff_path = tiff_path[0]
        self._raster_info = _RasterInfo(self._tiff_path)
        self._raster = np.zeros((self._raster_info.height, self._raster_info.width), dtype=np.uint16)
        dataset = gdal.Open(self._tiff_path)
        raster_band = dataset.GetRasterBand(1)
        self._block_xsize, self._block_ysize = raster_band.GetBlockSize()
        dataset = None
        self._raster_mask = np.zeros((self._raster_info.height // self._block_ysize + 1, self._raster_info.width // self._block_xsize + 1), dtype=np.bool)
<|end_body_0|>

<|body_start_1|>
        dataset = gdal.Open(self._tiff_path)
        raster_band = dataset.GetRasterBand(1)
        row_min, row_max = (0, dataset.RasterYSize - 1)
        col_min, col_max = (0, dataset.RasterXSize - 1)
        if box:
            row_se, col_se = self._raster_info.Indexes(box[0], box[1])
            row_ne, col_ne = self._raster_info.Indexes(box[2], box[1])
            row_sw, col_sw = self._raster_info.Indexes(box[0], box[3])
            row_nw, col_nw = self._raster_info.Indexes(box[2], box[3])
            row_min = max(min(row_ne, row_nw), 0)
            row_max = min(max(row_se, row_sw), dataset.RasterYSize - 1)
            col_min = max(min(col_se, col_ne), 0)
            col_max = min(max(col_sw, col_nw), dataset.RasterXSize - 1)
        b_y_min = int(row_min // self._block_ysize)
        b_y_max = int(row_max // self._block_ysize)
        b_x_min = int(col_min // self._block_xsize)
        b_x_max = int(col_max // self._block_xsize)
        for b_y in range(b_y_min, b_y_max + 1):
            for b_x in range(b_x_min, b_x_max + 1):
                if self._raster_mask[b_y, b_x]:
                    continue
                yoff, xoff = (b_y * self._block_ysize, b_x * self._block_xsize)
                win_xsize, win_ysize = raster_band.GetActualBlockSize(b_x, b_y)
                block = raster_band.ReadAsArray(xoff=xoff, yoff=yoff, win_xsize=win_xsize, win_ysize=win_ysize)
                self._raster[yoff:yoff + win_ysize, xoff:xoff + win_xsize] = np.minimum(block, 65500)
                self._raster_mask[b_y, b_x] = True
        if box is None:
            self.all_loaded = True
        dataset = None
<|end_body_1|>

<|body_start_2|>
        if len(latitudes) == 0:
            return 0
        latitudes = np.asarray(latitudes)
        longitudes = np.asarray(longitudes)
        densities = np.zeros(len(latitudes), dtype=np.int16)
        rows, cols = self._raster_info.Indexes(latitudes, longitudes)
        idx_inside = np.where((rows >= 0) & (cols >= 0) & (rows < self._raster.shape[0]) & (cols < self._raster.shape[1]))[0]
        if self.lazy_load and (not self.fully_loaded):
            lat_min, lat_max = (np.min(latitudes), np.max(latitudes))
            lon_min, lon_max = (np.min(longitudes), np.max(longitudes))
            self.LoadRaster((lat_min, lon_min, lat_max, lon_max))
        densities[idx_inside] = self._raster[rows[idx_inside], cols[idx_inside]]
        return densities
<|end_body_2|>

Solution:
class UsgsPopDriver:
    """USGS Population Raster driver. This class manages the reading of population raster data provided by USGS at: https://www.sciencebase.gov/catalog/item/57753ebee4b07dd077c70868"""

    def __init__(self, pop_directory=None, lazy_load=False):
        """Initializes the driver. Args: pop_directory: The directory holding the USGS population raster. If None, use the default location. lazy_load: If True, then lazy population loading done (as needed)."""
        self.lazy_load = lazy_load
        self.fully_loaded = False
        if not pop_directory:
            pop_directory = DEFAULT_POP_DIR
        tiff_path = glob.glob(os.path.join(pop_directory, '*.tif'))
        if not tiff_path:
            raise ValueError('No TIFF file name in directory: %s' % pop_directory)
        self._tiff_path = tiff_path[0]
        self._raster_info = _RasterInfo(self._tiff_path)
        self._raster = np.zeros((self._raster_info.height, self._raster_info.width), dtype=np.uint16)
        dataset = gdal.Open(self._tiff_path)
        raster_band = dataset.GetRasterBand(1)
        self._block_xsize, self._block_ysize = raster_band.GetBlockSize()
        dataset = None
        self._raster_mask = np.zeros((self._raster_info.height // self._block_ysize + 1, self._raster_info.width // self._block_xsize + 1), dtype=np.bool)

    def LoadRaster(self, box=None):
        """Load raster in memory. Args: box: A (lat_min, lon_min, lat_max, lon_max) bounding box. If None, the full raster is loaded in memory."""
        dataset = gdal.Open(self._tiff_path)
        raster_band = dataset.GetRasterBand(1)
        row_min, row_max = (0, dataset.RasterYSize - 1)
        col_min, col_max = (0, dataset.RasterXSize - 1)
        if box:
            row_se, col_se = self._raster_info.Indexes(box[0], box[1])
            row_ne, col_ne = self._raster_info.Indexes(box[2], box[1])
            row_sw, col_sw = self._raster_info.Indexes(box[0], box[3])
            row_nw, col_nw = self._raster_info.Indexes(box[2], box[3])
            row_min = max(min(row_ne, row_nw), 0)
            row_max = min(max(row_se, row_sw), dataset.RasterYSize - 1)
            col_min = max(min(col_se, col_ne), 0)
            col_max = min(max(col_sw, col_nw), dataset.RasterXSize - 1)
        b_y_min = int(row_min // self._block_ysize)
        b_y_max = int(row_max // self._block_ysize)
        b_x_min = int(col_min // self._block_xsize)
        b_x_max = int(col_max // self._block_xsize)
        for b_y in range(b_y_min, b_y_max + 1):
            for b_x in range(b_x_min, b_x_max + 1):
                if self._raster_mask[b_y, b_x]:
                    continue
                yoff, xoff = (b_y * self._block_ysize, b_x * self._block_xsize)
                win_xsize, win_ysize = raster_band.GetActualBlockSize(b_x, b_y)
                block = raster_band.ReadAsArray(xoff=xoff, yoff=yoff, win_xsize=win_xsize, win_ysize=win_ysize)
                self._raster[yoff:yoff + win_ysize, xoff:xoff + win_xsize] = np.minimum(block, 65500)
                self._raster_mask[b_y, b_x] = True
        if box is None:
            self.all_loaded = True
        dataset = None

    def GetPopulationDensity(self, latitudes, longitudes):
        """Retrieves the population density on locations. Args: latitudes: A sequence of points latitudes. longitudes: A sequence of points longitudes. Returns: The population density (pop/km2) as a ndarray (dtype=int16)."""
        if len(latitudes) == 0:
            return 0
        latitudes = np.asarray(latitudes)
        longitudes = np.asarray(longitudes)
        densities = np.zeros(len(latitudes), dtype=np.int16)
        rows, cols = self._raster_info.Indexes(latitudes, longitudes)
        idx_inside = np.where((rows >= 0) & (cols >= 0) & (rows < self._raster.shape[0]) & (cols < self._raster.shape[1]))[0]
        if self.lazy_load and (not self.fully_loaded):
            lat_min, lat_max = (np.min(latitudes), np.max(latitudes))
            lon_min, lon_max = (np.min(longitudes), np.max(longitudes))
            self.LoadRaster((lat_min, lon_min, lat_max, lon_max))
        densities[idx_inside] = self._raster[rows[idx_inside], cols[idx_inside]]
        return densities


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

Class description:
This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user.

Method signatures and docstrings:
- def __init__(self, matcher, tokens, alphabet, discard, t_regexp=None, s_regexp=None, source=None): matcher is the head of the original matcher graph, which will be called with a tokenised stream. tokens is the set of `Token` instances that define the lexer. alphabet is the alphabet for which the regexps are defined. discard is the regular expression for spaces (which are silently dropped if not token can be matcher). t_regexp and s_regexp are internally compiled state, use in cloning, and should not be provided by non-cloning callers. source is the source used to generate the final stream.
- def token_for_id(self, id_): A utility that checks the known tokens for a given ID. The ID is used internally, but is (by default) an unfriendly integer value. Note that a lexed stream associates a chunk of input with a list of IDs - more than one regexp may be a maximal match (and this is a feature, not a bug).
- def _match(self, stream): Implement matching - pass token stream to tokens.

Implement the Python class `Lexer` described below.

Class description:
This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user.

Method signatures and docstrings:
- def __init__(self, matcher, tokens, alphabet, discard, t_regexp=None, s_regexp=None, source=None): matcher is the head of the original matcher graph, which will be called with a tokenised stream. tokens is the set of `Token` instances that define the lexer. alphabet is the alphabet for which the regexps are defined. discard is the regular expression for spaces (which are silently dropped if not token can be matcher). t_regexp and s_regexp are internally compiled state, use in cloning, and should not be provided by non-cloning callers. source is the source used to generate the final stream.
- def token_for_id(self, id_): A utility that checks the known tokens for a given ID. The ID is used internally, but is (by default) an unfriendly integer value. Note that a lexed stream associates a chunk of input with a list of IDs - more than one regexp may be a maximal match (and this is a feature, not a bug).
- def _match(self, stream): Implement matching - pass token stream to tokens.

<|skeleton|>
class Lexer:
    """This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user."""

    def __init__(self, matcher, tokens, alphabet, discard, t_regexp=None, s_regexp=None, source=None):
        """matcher is the head of the original matcher graph, which will be called with a tokenised stream. tokens is the set of `Token` instances that define the lexer. alphabet is the alphabet for which the regexps are defined. discard is the regular expression for spaces (which are silently dropped if not token can be matcher). t_regexp and s_regexp are internally compiled state, use in cloning, and should not be provided by non-cloning callers. source is the source used to generate the final stream."""
        <|body_0|>

    def token_for_id(self, id_):
        """A utility that checks the known tokens for a given ID. The ID is used internally, but is (by default) an unfriendly integer value. Note that a lexed stream associates a chunk of input with a list of IDs - more than one regexp may be a maximal match (and this is a feature, not a bug)."""
        <|body_1|>

    def _match(self, stream):
        """Implement matching - pass token stream to tokens."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        super(Lexer, self).__init__(TOKENS, TokenNamespace)
        if t_regexp is None:
            unique = {}
            for token in tokens:
                token.compile(alphabet)
                self._debug(format('Token: {0}', token))
                unique[token.id_] = token
            t_regexp = Compiler.multiple(alphabet, [(t.id_, t.regexp) for t in unique.values()]).dfa()
        if s_regexp is None and discard is not None:
            s_regexp = Compiler.single(alphabet, discard).dfa()
        self._arg(matcher=matcher)
        self._arg(tokens=tokens)
        self._arg(alphabet=alphabet)
        self._arg(discard=discard)
        self._karg(t_regexp=t_regexp)
        self._karg(s_regexp=s_regexp)
        self._karg(source=source)
<|end_body_0|>

<|body_start_1|>
        for token in self.tokens:
            if token.id_ == id_:
                return token
<|end_body_1|>

<|body_start_2|>
        if isinstance(stream, LocationStream):
            tokens = lexed_location_stream(self.t_regexp, self.s_regexp, stream, self.source)
        else:
            if self.source:
                raise RuntimeLexerError('Source specified for simple stream')
            tokens = lexed_simple_stream(self.t_regexp, self.s_regexp, stream)
        generator = self.matcher._match(tokens)
        while True:
            result, stream_out = (yield generator)
            yield (result, stream_out)
<|end_body_2|>

Solution:
class Lexer:
    """This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user."""

    def __init__(self, matcher, tokens, alphabet, discard, t_regexp=None, s_regexp=None, source=None):
        """matcher is the head of the original matcher graph, which will be called with a tokenised stream. tokens is the set of `Token` instances that define the lexer. alphabet is the alphabet for which the regexps are defined. discard is the regular expression for spaces (which are silently dropped if not token can be matcher). t_regexp and s_regexp are internally compiled state, use in cloning, and should not be provided by non-cloning callers. source is the source used to generate the final stream."""
        super(Lexer, self).__init__(TOKENS, TokenNamespace)
        if t_regexp is None:
            unique = {}
            for token in tokens:
                token.compile(alphabet)
                self._debug(format('Token: {0}', token))
                unique[token.id_] = token
            t_regexp = Compiler.multiple(alphabet, [(t.id_, t.regexp) for t in unique.values()]).dfa()
        if s_regexp is None and discard is not None:
            s_regexp = Compiler.single(alphabet, discard).dfa()
        self._arg(matcher=matcher)
        self._arg(tokens=tokens)
        self._arg(alphabet=alphabet)
        self._arg(discard=discard)
        self._karg(t_regexp=t_regexp)
        self._karg(s_regexp=s_regexp)
        self._karg(source=source)

    def token_for_id(self, id_):
        """A utility that checks the known tokens for a given ID. The ID is used internally, but is (by default) an unfriendly integer value. Note that a lexed stream associates a chunk of input with a list of IDs - more than one regexp may be a maximal match (and this is a feature, not a bug)."""
        for token in self.tokens:
            if token.id_ == id_:
                return token

    def _match(self, stream):
        """Implement matching - pass token stream to tokens."""
        if isinstance(stream, LocationStream):
            tokens = lexed_location_stream(self.t_regexp, self.s_regexp, stream, self.source)
        else:
            if self.source:
                raise RuntimeLexerError('Source specified for simple stream')
            tokens = lexed_simple_stream(self.t_regexp, self.s_regexp, stream)
        generator = self.matcher._match(tokens)
        while True:
            result, stream_out = (yield generator)
            yield (result, stream_out)


post

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

Class description:
FetchResultListResource

Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:
- def post(self): Example: curl http://0.0.0.0:5000/news/fetch_results -H "Content-Type: application/json" -X POST -d ' { "fetch_result": { "task_id": 14, "platform_id": 3, "platform_name": "头条_post", "channel_id": 0, "channel_name": "", "article_id": "6527896212211761677", "article_url": "https://www.toutiao.com/i6527896212211761677/", "article_title": "【交易机会】澳美短线或继续回调，中长线仍旧看多", "article_author_id": "69781315016", "article_author_name": "恒信贵金属", "article_tags": "外汇,经济,贵金属,斐波那契,投资", "article_abstract": "本周，在新任美联储主席鲍威尔国会首秀发表鹰派言论之后，近期在90下方苦苦挣扎的美元指数迅速上涨并且一举突破90阻力。", "article_content": "

本周，在新任美联储主席鲍威尔国会首秀发表鹰派言论之后，近期在90下方苦苦挣扎的美元指数迅速上涨并且一举突破90阻力。但是需要注意的是，美元靓丽的表现可能只是短期的超跌反弹而已，中长线美元依旧缺乏上涨的动力。因为此前市场普遍预期美联储在201

Implement the Python class `FetchResultListResource` described below.

Class description:
FetchResultListResource

Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:
- def post(self): Example: curl http://0.0.0.0:5000/news/fetch_results -H "Content-Type: application/json" -X POST -d ' { "fetch_result": { "task_id": 14, "platform_id": 3, "platform_name": "头条_post", "channel_id": 0, "channel_name": "", "article_id": "6527896212211761677", "article_url": "https://www.toutiao.com/i6527896212211761677/", "article_title": "【交易机会】澳美短线或继续回调，中长线仍旧看多", "article_author_id": "69781315016", "article_author_name": "恒信贵金属", "article_tags": "外汇,经济,贵金属,斐波那契,投资", "article_abstract": "本周，在新任美联储主席鲍威尔国会首秀发表鹰派言论之后，近期在90下方苦苦挣扎的美元指数迅速上涨并且一举突破90阻力。", "article_content": "

本周，在新任美联储主席鲍威尔国会首秀发表鹰派言论之后，近期在90下方苦苦挣扎的美元指数迅速上涨并且一举突破90阻力。但是需要注意的是，美元靓丽的表现可能只是短期的超跌反弹而已，中长线美元依旧缺乏上涨的动力。因为此前市场普遍预期美联储在201

<|skeleton|>
class FetchResultListResource:
    """FetchResultListResource"""

    def get(self):
        """Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:"""
        <|body_0|>

    def post(self):
        """Example: curl http://0.0.0.0:5000/news/fetch_results -H "Content-Type: application/json" -X POST -d ' { "fetch_result": { "task_id": 14, "platform_id": 3, "platform_name": "头条_post", "channel_id": 0, "channel_name": "", "article_id": "6527896212211761677", "article_url": "https://www.toutiao.com/i6527896212211761677/", "article_title": "【交易机会】澳美短线或继续回调，中长线仍旧看多", "article_author_id": "69781315016", "article_author_name": "恒信贵金属", "article_tags": "外汇,经济,贵金属,斐波那契,投资", "article_abstract": "本周，在新任美联储主席鲍威尔国会首秀发表鹰派言论之后，近期在90下方苦苦挣扎的美元指数迅速上涨并且一举突破90阻力。", "article_content": "

本周，在新任美联储主席鲍威尔国会首秀发表鹰派言论之后，近期在90下方苦苦挣扎的美元指数迅速上涨并且一举突破90阻力。但是需要注意的是，美元靓丽的表现可能只是短期的超跌反弹而已，中长线美元依旧缺乏上涨的动力。因为此前市场普遍预期美联储在201"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        filter_parser = reqparse.RequestParser(bundle_errors=True)
        filter_parser.add_argument('last_pk', type=int, default=0, location='args')
        filter_parser.add_argument('limit_num', type=int, default=20, location='args')
        filter_parser_args = filter_parser.parse_args()
        data = get_fetch_result_limit_rows_by_last_id(**filter_parser_args)
        result = marshal(data, fields_item_fetch_result, envelope=structure_key_items)
        return jsonify(result)
<|end_body_0|>

<|body_start_1|>
        request_args = request_parser.parse_args()
        request_item_args = request_parser_item_post.parse_args(req=request_args)
        if not request_item_args:
            raise BadRequest('Bad request.')
        request_data = request_item_args
        result = add_fetch_result(request_data)
        if result:
            success_msg = SUCCESS_MSG.copy()
            success_msg['id'] = result
            return make_response(jsonify(success_msg), 201)
        else:
            failure_msg = FAILURE_MSG.copy()
            return make_response(jsonify(failure_msg), 400)
<|end_body_1|>

Solution:
class FetchResultListResource:
    """FetchResultListResource"""

    def get(self):
        """Example: curl http://0.0.0.0:5000/news/fetch_results curl http://0.0.0.0:5000/news/fetch_results?last_pk=1000&limit_num=2 :return:"""
        filter_parser = reqparse.RequestParser(bundle_errors=True)
        filter_parser.add_argument('last_pk', type=int, default=0, location='args')
        filter_parser.add_argument('limit_num', type=int, default=20, location='args')
        filter_parser_args = filter_parser.parse_args()
        data = get_fetch_result_limit_rows_by_last_id(**filter_parser_args)
        result = marshal(data, fields_item_fetch_result, envelope=structure_key_items)
        return jsonify(result)

    def post(self):
        """Example: curl http://0.0.0.0:5000/news/fetch_results -H "Content-Type: application/json" -X POST -d ' { "fetch_result": { "task_id": 14, "platform_id": 3, "platform_name": "头条_post", "channel_id": 0, "channel_name": "", "article_id": "6527896212211761677", "article_url": "https://www.toutiao.com/i6527896212211761677/", "article_title": "【交易机会】澳美短线或继续回调，中长线仍旧看多", "article_author_id": "69781315016", "article_author_name": "恒信贵金属", "article_tags": "外汇,经济,贵金属,斐波那契,投资", "article_abstract": "本周，在新任美联储主席鲍威尔国会首秀发表鹰派言论之后，近期在90下方苦苦挣扎的美元指数迅速上涨并且一举突破90阻力。", "article_content": "

本周，在新任美联储主席鲍威尔国会首秀发表鹰派言论之后，近期在90下方苦苦挣扎的美元指数迅速上涨并且一举突破90阻力。但是需要注意的是，美元靓丽的表现可能只是短期的超跌反弹而已，中长线美元依旧缺乏上涨的动力。因为此前市场普遍预期美联储在201"""
        request_args = request_parser.parse_args()
        request_item_args = request_parser_item_post.parse_args(req=request_args)
        if not request_item_args:
            raise BadRequest('Bad request.')
        request_data = request_item_args
        result = add_fetch_result(request_data)
        if result:
            success_msg = SUCCESS_MSG.copy()
            success_msg['id'] = result
            return make_response(jsonify(success_msg), 201)
        else:
            failure_msg = FAILURE_MSG.copy()
            return make_response(jsonify(failure_msg), 400)


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

Class description:
Implement the SelectionSort class.

Method signatures and docstrings:
- def selection_sort_min_version(arr): Selection sort in selecting-min-element style. Note that selection is the slowest of all the common sorting algorithms. It requires quadratic time even in the best case (i.e., when the array is already sorted). :param arr: List[int], list to be sorted :return: List[int], sorted list
- def selection_sort_max_version(arr): Selection sort in selecting-max-element style. Note that selection is the slowest of all the common sorting algorithms. It requires quadratic time even in the best case (i.e., when the array is already sorted). :param arr: List[int], list to be sorted :return: List[int], sorted list

Implement the Python class `SelectionSort` described below.

Class description:
Implement the SelectionSort class.

Method signatures and docstrings:
- def selection_sort_min_version(arr): Selection sort in selecting-min-element style. Note that selection is the slowest of all the common sorting algorithms. It requires quadratic time even in the best case (i.e., when the array is already sorted). :param arr: List[int], list to be sorted :return: List[int], sorted list
- def selection_sort_max_version(arr): Selection sort in selecting-max-element style. Note that selection is the slowest of all the common sorting algorithms. It requires quadratic time even in the best case (i.e., when the array is already sorted). :param arr: List[int], list to be sorted :return: List[int], sorted list

<|skeleton|>
class SelectionSort:

    def selection_sort_min_version(arr):
        """Selection sort in selecting-min-element style. Note that selection is the slowest of all the common sorting algorithms. It requires quadratic time even in the best case (i.e., when the array is already sorted). :param arr: List[int], list to be sorted :return: List[int], sorted list"""
        <|body_0|>

    def selection_sort_max_version(arr):
        """Selection sort in selecting-max-element style. Note that selection is the slowest of all the common sorting algorithms. It requires quadratic time even in the best case (i.e., when the array is already sorted). :param arr: List[int], list to be sorted :return: List[int], sorted list"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if arr is None:
            return arr
        n = len(arr)
        if n <= 1:
            return arr
        for i in range(0, n):
            min_index = i
            j = i + 1
            while j < n:
                if arr[j] < arr[min_index]:
                    min_index = j
                j += 1
            arr[i], arr[min_index] = (arr[min_index], arr[i])
        return arr
<|end_body_0|>

<|body_start_1|>
        if arr is None:
            return arr
        n = len(arr)
        if n <= 1:
            return arr
        for i in range(n - 1, 0, -1):
            max_index = i
            j = i - 1
            while j >= 0:
                if arr[j] > arr[max_index]:
                    max_index = j
                j -= 1
            arr[i], arr[max_index] = (arr[max_index], arr[i])
        return arr
<|end_body_1|>

Solution:
class SelectionSort:
    def selection_sort_min_version(arr):
        """Selection sort in selecting-min-element style. Note that selection is the slowest of all the common sorting algorithms. It requires quadratic time even in the best case (i.e., when the array is already sorted). :param arr: List[int], list to be sorted :return: List[int], sorted list"""
        if arr is None:
            return arr
        n = len(arr)
        if n <= 1:
            return arr
        for i in range(0, n):
            min_index = i
            j = i + 1
            while j < n:
                if arr[j] < arr[min_index]:
                    min_index = j
                j += 1
            arr[i], arr[min_index] = (arr[min_index], arr[i])
        return arr

    def selection_sort_max_version(arr):
        """Selection sort in selecting-max-element style. Note that selection is the slowest of all the common sorting algorithms. It requires quadratic time even in the best case (i.e., when the array is already sorted). :param arr: List[int], list to be sorted :return: List[int], sorted list"""
        if arr is None:
            return arr
        n = len(arr)
        if n <= 1:
            return arr
        for i in range(n - 1, 0, -1):
            max_index = i
            j = i - 1
            while j >= 0:
                if arr[j] > arr[max_index]:
                    max_index = j
                j -= 1
            arr[i], arr[max_index] = (arr[max_index], arr[i])
        return arr


get

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

Class description:
get:

Method signatures and docstrings:
- def get(self, request): Retrieve all notifications from the database for a specific user. :returns notifications: a json data for the notifications
- def put(self, request): Mark all notifications as read.

Implement the Python class `NotificationAPIView` described below.

Class description:
get:

Method signatures and docstrings:
- def get(self, request): Retrieve all notifications from the database for a specific user. :returns notifications: a json data for the notifications
- def put(self, request): Mark all notifications as read.

<|skeleton|>
class NotificationAPIView:
    """get:"""

    def get(self, request):
        """Retrieve all notifications from the database for a specific user. :returns notifications: a json data for the notifications"""
        <|body_0|>

    def put(self, request):
        """Mark all notifications as read."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        user = request.user
        notifications = Notification.objects.all()
        data = {}
        for notification in notifications:
            if user in notification.notified.all():
                serializer = self.serializer_class(notification, context={'request': request})
                data[notification.id] = serializer.data
        return Response(data, status=status.HTTP_200_OK)
<|end_body_0|>

<|body_start_1|>
        notifications = Notification.objects.all()
        user = request.user
        for notification in notifications:
            if user in notification.notified.all():
                notification.read.add(user.id)
                notification.save()
                message = 'You successfully marked all notifications as read'
                response = {'message': message}
        return Response(response, status=status.HTTP_200_OK)
<|end_body_1|>

Solution:
class NotificationAPIView:
    """get:"""

    def get(self, request):
        """Retrieve all notifications from the database for a specific user. :returns notifications: a json data for the notifications"""
        user = request.user
        notifications = Notification.objects.all()
        data = {}
        for notification in notifications:
            if user in notification.notified.all():
                serializer = self.serializer_class(notification, context={'request': request})
                data[notification.id] = serializer.data
        return Response(data, status=status.HTTP_200_OK)

    def put(self, request):
        """Mark all notifications as read."""
        notifications = Notification.objects.all()
        user = request.user
        for notification in notifications:
            if user in notification.notified.all():
                notification.read.add(user.id)
                notification.save()
                message = 'You successfully marked all notifications as read'
                response = {'message': message}
        return Response(response, status=status.HTTP_200_OK)


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

Class description:
Implementation of the main sensor, conducting the actual polling.

Method signatures and docstrings:
- def __init__(self, syncthru, name): Initialize the sensor.
- async def async_update(self): Get the latest data from SyncThru and update the state.

Implement the Python class `SyncThruMainSensor` described below.

Class description:
Implementation of the main sensor, conducting the actual polling.

Method signatures and docstrings:
- def __init__(self, syncthru, name): Initialize the sensor.
- async def async_update(self): Get the latest data from SyncThru and update the state.

<|skeleton|>
class SyncThruMainSensor:
    """Implementation of the main sensor, conducting the actual polling."""

    def __init__(self, syncthru, name):
        """Initialize the sensor."""
        <|body_0|>

    async def async_update(self):
        """Get the latest data from SyncThru and update the state."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        super().__init__(syncthru, name)
        self._id_suffix = '_main'
        self._active = True
<|end_body_0|>

<|body_start_1|>
        if not self._active:
            return
        try:
            await self.syncthru.update()
        except ValueError:
            _LOGGER.warning('Configured printer at %s does not support SyncThru. Consider changing your configuration', self.syncthru.url)
            self._active = False
        self._state = SYNCTHRU_STATE_HUMAN[self.syncthru.device_status()]
        self._attributes = {'display_text': self.syncthru.device_status_details()}
<|end_body_1|>

Solution:
class SyncThruMainSensor:
    """Implementation of the main sensor, conducting the actual polling."""

    def __init__(self, syncthru, name):
        """Initialize the sensor."""
        super().__init__(syncthru, name)
        self._id_suffix = '_main'
        self._active = True

    async def async_update(self):
        """Get the latest data from SyncThru and update the state."""
        if not self._active:
            return
        try:
            await self.syncthru.update()
        except ValueError:
            _LOGGER.warning('Configured printer at %s does not support SyncThru. Consider changing your configuration', self.syncthru.url)
            self._active = False
        self._state = SYNCTHRU_STATE_HUMAN[self.syncthru.device_status()]
        self._attributes = {'display_text': self.syncthru.device_status_details()}


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

Class description:
Class MainFrame.

Method signatures and docstrings:
- def __init__(self, parent, id): Create the MainFrame.
- def OnStart(self, event): Start Computation.
- def OnStop(self, event): Stop Computation.

Implement the Python class `MainFrame` described below.

Class description:
Class MainFrame.

Method signatures and docstrings:
- def __init__(self, parent, id): Create the MainFrame.
- def OnStart(self, event): Start Computation.
- def OnStop(self, event): Stop Computation.

<|skeleton|>
class MainFrame:
    """Class MainFrame."""

    def __init__(self, parent, id):
        """Create the MainFrame."""
        <|body_0|>

    def OnStart(self, event):
        """Start Computation."""
        <|body_1|>

    def OnStop(self, event):
        """Stop Computation."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        wx.Frame.__init__(self, parent, id, 'wxYield Test')
        wx.Button(self, ID_START, 'Start', pos=(0, 0))
        wx.Button(self, ID_STOP, 'Stop', pos=(0, 50))
        self.status = wx.StaticText(self, -1, '', pos=(0, 100))
        self.Bind(wx.EVT_BUTTON, self.OnStart, id=ID_START)
        self.Bind(wx.EVT_BUTTON, self.OnStop, id=ID_STOP)
        self.working = 0
<|end_body_0|>

<|body_start_1|>
        if not self.working:
            self.status.SetLabel('Starting Computation')
            self.working = 1
            self.need_abort = 0
            for i in range(10):
                time.sleep(1)
                wx.Yield()
                if self.need_abort:
                    self.status.SetLabel('Computation aborted')
                    break
            else:
                self.status.SetLabel('Computation Completed')
            self.working = 0
<|end_body_1|>

<|body_start_2|>
        if self.working:
            self.status.SetLabel('Trying to abort computation')
            self.need_abort = 1
<|end_body_2|>

Solution:
class MainFrame:
    """Class MainFrame."""

    def __init__(self, parent, id):
        """Create the MainFrame."""
        wx.Frame.__init__(self, parent, id, 'wxYield Test')
        wx.Button(self, ID_START, 'Start', pos=(0, 0))
        wx.Button(self, ID_STOP, 'Stop', pos=(0, 50))
        self.status = wx.StaticText(self, -1, '', pos=(0, 100))
        self.Bind(wx.EVT_BUTTON, self.OnStart, id=ID_START)
        self.Bind(wx.EVT_BUTTON, self.OnStop, id=ID_STOP)
        self.working = 0

    def OnStart(self, event):
        """Start Computation."""
        if not self.working:
            self.status.SetLabel('Starting Computation')
            self.working = 1
            self.need_abort = 0
            for i in range(10):
                time.sleep(1)
                wx.Yield()
                if self.need_abort:
                    self.status.SetLabel('Computation aborted')
                    break
            else:
                self.status.SetLabel('Computation Completed')
            self.working = 0

    def OnStop(self, event):
        """Stop Computation."""
        if self.working:
            self.status.SetLabel('Trying to abort computation')
            self.need_abort = 1


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

Class description:
Implement the Game class.

Method signatures and docstrings:
- def __init__(self, guesser='human', digits=3): Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be the guesser and it will change how the game is played.
- def create_num(self, digits): This method generates a random number of a specified number of digits (3 to start). No digits can repeat, and the number cannot start with 0. The digits are stored as a list so it's easier to iterate through them and compare them to human guesses.
- def compare_guess(self, human_guess): This method takes the human player's guess and compares the digits and indices to those in the random number the computer chose. It returns the code words "Bagel," "Pico," and/or "Fermi" based on whether any digits are right or in the right place.

Implement the Python class `Game` described below.

Class description:
Implement the Game class.

Method signatures and docstrings:
- def __init__(self, guesser='human', digits=3): Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be the guesser and it will change how the game is played.
- def create_num(self, digits): This method generates a random number of a specified number of digits (3 to start). No digits can repeat, and the number cannot start with 0. The digits are stored as a list so it's easier to iterate through them and compare them to human guesses.
- def compare_guess(self, human_guess): This method takes the human player's guess and compares the digits and indices to those in the random number the computer chose. It returns the code words "Bagel," "Pico," and/or "Fermi" based on whether any digits are right or in the right place.

<|skeleton|>
class Game:

    def __init__(self, guesser='human', digits=3):
        """Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be the guesser and it will change how the game is played."""
        <|body_0|>

    def create_num(self, digits):
        """This method generates a random number of a specified number of digits (3 to start). No digits can repeat, and the number cannot start with 0. The digits are stored as a list so it's easier to iterate through them and compare them to human guesses."""
        <|body_1|>

    def compare_guess(self, human_guess):
        """This method takes the human player's guess and compares the digits and indices to those in the random number the computer chose. It returns the code words "Bagel," "Pico," and/or "Fermi" based on whether any digits are right or in the right place."""
        <|body_2|>

<|end_skeleton|>

<|body_start_0|>
        self.digits = digits
        self.number_of_guesses = 0
        if guesser == 'human':
            self.chosen_number = self.create_num(digits)
<|end_body_0|>

<|body_start_1|>
        final_number = []
        first_digit = randrange(1, 10)
        final_number.append(first_digit)
        infinite_loop_prevention = 0
        while len(final_number) < digits:
            infinite_loop_prevention += 1
            if infinite_loop_prevention > 10:
                raise Exception('Infinite loop detected!')
            new_digit = randrange(0, 10)
            if new_digit not in final_number:
                final_number.append(new_digit)
        return final_number
<|end_body_1|>

<|body_start_2|>
        self.number_of_guesses += 1
        codewords = []
        digits_place = 0
        while digits_place < self.digits:
            if human_guess[digits_place] == self.chosen_number[digits_place]:
                codewords.insert(0, 'Fermi')
            elif human_guess[digits_place] in self.chosen_number:
                codewords.insert(0, 'Pico')
            digits_place += 1
        if len(codewords) == 0:
            codewords.insert(0, 'Bagels')
        return codewords
<|end_body_2|>

Solution:
class Game:
    def __init__(self, guesser='human', digits=3):
        """Each game stores the number of guesses as an attribute. You will be able to choose whether the human player or the computer player will be the guesser and it will change how the game is played."""
        self.digits = digits
        self.number_of_guesses = 0
        if guesser == 'human':
            self.chosen_number = self.create_num(digits)

    def create_num(self, digits):
        """This method generates a random number of a specified number of digits (3 to start). No digits can repeat, and the number cannot start with 0. The digits are stored as a list so it's easier to iterate through them and compare them to human guesses."""
        final_number = []
        first_digit = randrange(1, 10)
        final_number.append(first_digit)
        infinite_loop_prevention = 0
        while len(final_number) < digits:
            infinite_loop_prevention += 1
            if infinite_loop_prevention > 10:
                raise Exception('Infinite loop detected!')
            new_digit = randrange(0, 10)
            if new_digit not in final_number:
                final_number.append(new_digit)
        return final_number

    def compare_guess(self, human_guess):
        """This method takes the human player's guess and compares the digits and indices to those in the random number the computer chose. It returns the code words "Bagel," "Pico," and/or "Fermi" based on whether any digits are right or in the right place."""
        self.number_of_guesses += 1
        codewords = []
        digits_place = 0
        while digits_place < self.digits:
            if human_guess[digits_place] == self.chosen_number[digits_place]:
                codewords.insert(0, 'Fermi')
            elif human_guess[digits_place] in self.chosen_number:
                codewords.insert(0, 'Pico')
            digits_place += 1
        if len(codewords) == 0:
            codewords.insert(0, 'Bagels')
        return codewords


思路：通过flag来标记是否已找到

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def findTarget1(self, root: TreeNode, k: int) -> bool: 思路：回溯+剪枝
- def findTarget2(self, root: TreeNode, k: int) -> bool: 思路：通过flag来标记是否已找到

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def findTarget1(self, root: TreeNode, k: int) -> bool: 思路：回溯+剪枝
- def findTarget2(self, root: TreeNode, k: int) -> bool: 思路：通过flag来标记是否已找到

<|skeleton|>
class Solution:

    def findTarget1(self, root: TreeNode, k: int) -> bool:
        """思路：回溯+剪枝"""
        <|body_0|>

    def findTarget2(self, root: TreeNode, k: int) -> bool:
        """思路：通过flag来标记是否已找到"""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        def recur(root, k, hashset):
            if not root:
                return False
            target = k - root.val
            if target in hashset:
                return True
            else:
                hashset.add(root.val)
            return recur(root.left, k, hashset) or recur(root.right, k, hashset)
        hashset = set()
        return recur(root, k, hashset)
<|end_body_0|>

<|body_start_1|>
        if not root:
            return []
        dic = set()
        flag = False

        def inorder(root):
            if root:
                inorder(root.left)
                if k - root.val in dic:
                    nonlocal flag
                    flag = True
                    return
                dic.add(root.val)
                inorder(root.right)
        inorder(root)
        return flag
<|end_body_1|>

Solution:
class Solution:
    def findTarget1(self, root: TreeNode, k: int) -> bool:
        """思路：回溯+剪枝"""
        def recur(root, k, hashset):
            if not root:
                return False
            target = k - root.val
            if target in hashset:
                return True
            else:
                hashset.add(root.val)
            return recur(root.left, k, hashset) or recur(root.right, k, hashset)
        hashset = set()
        return recur(root, k, hashset)

    def findTarget2(self, root: TreeNode, k: int) -> bool:
        """思路：通过flag来标记是否已找到"""
        if not root:
            return []
        dic = set()
        flag = False

        def inorder(root):
            if root:
                inorder(root.left)
                if k - root.val in dic:
                    nonlocal flag
                    flag = True
                    return
                dic.add(root.val)
                inorder(root.right)
        inorder(root)
        return flag

LeetCode/树(Binary Tree)/653. 两数之和 IV - 输入 BST.py


nextPermutation

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

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def nextPermutation(self, nums: List[int]): 方法一：两遍扫描【官方解】 目标：一个大于当前序列的新序列，且变大的幅度尽可能小 解析：
- def nextPermutation1(self, nums: List[int]): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.

Implement the Python class `Solution` described below.

Class description:
Implement the Solution class.

Method signatures and docstrings:
- def nextPermutation(self, nums: List[int]): 方法一：两遍扫描【官方解】 目标：一个大于当前序列的新序列，且变大的幅度尽可能小 解析：
- def nextPermutation1(self, nums: List[int]): :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.

<|skeleton|>
class Solution:

    def nextPermutation(self, nums: List[int]):
        """方法一：两遍扫描【官方解】 目标：一个大于当前序列的新序列，且变大的幅度尽可能小 解析："""
        <|body_0|>

    def nextPermutation1(self, nums: List[int]):
        """:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        i = len(nums) - 2
        while i >= 0 and nums[i] >= nums[i + 1]:
            i -= 1
        if i >= 0:
            j = len(nums) - 1
            while j >= 0 and nums[i] >= nums[j]:
                j -= 1
            nums[i], nums[j] = (nums[j], nums[i])
        left, right = (i + 1, len(nums) - 1)
        while left < right:
            nums[left], nums[right] = (nums[right], nums[left])
            left += 1
            right -= 1
<|end_body_0|>

<|body_start_1|>
        print('origin nums:{0}'.format(nums))
        n = len(nums)
        max_num = nums[-1]
        sign = True
        for i in range(2, n + 1):
            if nums[-i] < nums[-i + 1]:
                sign = False
                j = -i + 1
                while j < 0:
                    if nums[j] <= nums[-i]:
                        break
                    j += 1
                break
        if sign:
            nums.reverse()
            print('nums1:{0}'.format(nums))
        else:
            nums[-i], nums[j - 1] = (nums[j - 1], nums[-i])
            nums[-i + 1:] = nums[-i + 1:][::-1]
            print('nums2:{0}'.format(nums))
<|end_body_1|>

Solution:
class Solution:
    def nextPermutation(self, nums: List[int]):
        """方法一：两遍扫描【官方解】 目标：一个大于当前序列的新序列，且变大的幅度尽可能小 解析："""
        i = len(nums) - 2
        while i >= 0 and nums[i] >= nums[i + 1]:
            i -= 1
        if i >= 0:
            j = len(nums) - 1
            while j >= 0 and nums[i] >= nums[j]:
                j -= 1
            nums[i], nums[j] = (nums[j], nums[i])
        left, right = (i + 1, len(nums) - 1)
        while left < right:
            nums[left], nums[right] = (nums[right], nums[left])
            left += 1
            right -= 1

    def nextPermutation1(self, nums: List[int]):
        """:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
        print('origin nums:{0}'.format(nums))
        n = len(nums)
        max_num = nums[-1]
        sign = True
        for i in range(2, n + 1):
            if nums[-i] < nums[-i + 1]:
                sign = False
                j = -i + 1
                while j < 0:
                    if nums[j] <= nums[-i]:
                        break
                    j += 1
                break
        if sign:
            nums.reverse()
            print('nums1:{0}'.format(nums))
        else:
            nums[-i], nums[j - 1] = (nums[j - 1], nums[-i])
            nums[-i + 1:] = nums[-i + 1:][::-1]
            print('nums2:{0}'.format(nums))


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

Class description:
A wrapper around a session maker to provide the types of logging and rollbacks that we desire. It is callable and works as a context handler to manage sessions when doing so. Attributes ---------- logger : logging.Logger The logger object. maker : sqlalchemy.orm.session.Session A session maker.

Method signatures and docstrings:
- def __init__(self, session_maker): Create a new Session object. Parameter --------- session_maker : Session or sqlalchemy.orm.session.Session The session wrapper to use.
- def __call__(self): Context handler for the session. This creates a new session and yields it. It will catch, log, and re raise any exceptions that occur. It will also commit and close all sessions. In the case of an error it will rollback the session. Yields ------ session : Session A session that will be closed outside of the context.

Implement the Python class `Session` described below.

Class description:
A wrapper around a session maker to provide the types of logging and rollbacks that we desire. It is callable and works as a context handler to manage sessions when doing so. Attributes ---------- logger : logging.Logger The logger object. maker : sqlalchemy.orm.session.Session A session maker.

Method signatures and docstrings:
- def __init__(self, session_maker): Create a new Session object. Parameter --------- session_maker : Session or sqlalchemy.orm.session.Session The session wrapper to use.
- def __call__(self): Context handler for the session. This creates a new session and yields it. It will catch, log, and re raise any exceptions that occur. It will also commit and close all sessions. In the case of an error it will rollback the session. Yields ------ session : Session A session that will be closed outside of the context.

<|skeleton|>
class Session:
    """A wrapper around a session maker to provide the types of logging and rollbacks that we desire. It is callable and works as a context handler to manage sessions when doing so. Attributes ---------- logger : logging.Logger The logger object. maker : sqlalchemy.orm.session.Session A session maker."""

    def __init__(self, session_maker):
        """Create a new Session object. Parameter --------- session_maker : Session or sqlalchemy.orm.session.Session The session wrapper to use."""
        <|body_0|>

    def __call__(self):
        """Context handler for the session. This creates a new session and yields it. It will catch, log, and re raise any exceptions that occur. It will also commit and close all sessions. In the case of an error it will rollback the session. Yields ------ session : Session A session that will be closed outside of the context."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.logger = logging.getLogger('core.Session')
        self.maker = session_maker
        if isinstance(session_maker, Session):
            self.maker = session_maker.maker
<|end_body_0|>

<|body_start_1|>
        session = self.maker()
        try:
            yield session
            session.commit()
        except Skip:
            session.rollback()
            raise
        except Exception:
            self.logger.error('Transaction failed. Rolling back.')
            session.rollback()
            raise
        finally:
            session.close()
<|end_body_1|>

Solution:
class Session:
    """A wrapper around a session maker to provide the types of logging and rollbacks that we desire. It is callable and works as a context handler to manage sessions when doing so. Attributes ---------- logger : logging.Logger The logger object. maker : sqlalchemy.orm.session.Session A session maker."""

    def __init__(self, session_maker):
        """Create a new Session object. Parameter --------- session_maker : Session or sqlalchemy.orm.session.Session The session wrapper to use."""
        self.logger = logging.getLogger('core.Session')
        self.maker = session_maker
        if isinstance(session_maker, Session):
            self.maker = session_maker.maker

    def __call__(self):
        """Context handler for the session. This creates a new session and yields it. It will catch, log, and re raise any exceptions that occur. It will also commit and close all sessions. In the case of an error it will rollback the session. Yields ------ session : Session A session that will be closed outside of the context."""
        session = self.maker()
        try:
            yield session
            session.commit()
        except Skip:
            session.rollback()
            raise
        except Exception:
            self.logger.error('Transaction failed. Rolling back.')
            session.rollback()
            raise
        finally:
            session.close()


autobump

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

Class description:
Implement the BranchAutoBumper class.

Method signatures and docstrings:
- def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_autobump: List[PackAutoBumper], run_id: str): Args: pr: Pull Request related to the branch. git_repo: Git API object packs_to_autobump: Pack that was changed in this PR and need to autobump its versions. run_id: GitHub action run id.
- def autobump(self): AutoBumps version for all relevant packs in the pr: 1. Checkouts the branch and saves pr changed related data. 2. Merges from BASE and accept `theirs` changes. 3. AutoBumps version for each relevant packs. 4. Commit changes for each pack. 5. Comment on the PR. 6. Pushes the changes.

Implement the Python class `BranchAutoBumper` described below.

Class description:
Implement the BranchAutoBumper class.

Method signatures and docstrings:
- def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_autobump: List[PackAutoBumper], run_id: str): Args: pr: Pull Request related to the branch. git_repo: Git API object packs_to_autobump: Pack that was changed in this PR and need to autobump its versions. run_id: GitHub action run id.
- def autobump(self): AutoBumps version for all relevant packs in the pr: 1. Checkouts the branch and saves pr changed related data. 2. Merges from BASE and accept `theirs` changes. 3. AutoBumps version for each relevant packs. 4. Commit changes for each pack. 5. Comment on the PR. 6. Pushes the changes.

<|skeleton|>
class BranchAutoBumper:

    def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_autobump: List[PackAutoBumper], run_id: str):
        """Args: pr: Pull Request related to the branch. git_repo: Git API object packs_to_autobump: Pack that was changed in this PR and need to autobump its versions. run_id: GitHub action run id."""
        <|body_0|>

    def autobump(self):
        """AutoBumps version for all relevant packs in the pr: 1. Checkouts the branch and saves pr changed related data. 2. Merges from BASE and accept `theirs` changes. 3. AutoBumps version for each relevant packs. 4. Commit changes for each pack. 5. Comment on the PR. 6. Pushes the changes."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        assert packs_to_autobump, f'packs_to_autobump in the pr: {pr.number}, cant be empty.'
        self.pr = pr
        self.branch = pr.head.ref
        self.git_repo = git_repo
        self.packs_to_autobump = packs_to_autobump
        self.github_run_id = run_id
<|end_body_0|>

<|body_start_1|>
        body = PR_COMMENT_TITLE.format(self.github_run_id)
        with Checkout(self.git_repo, self.branch):
            for pack_auto_bumper in self.packs_to_autobump:
                pack_auto_bumper.set_pr_changed_rn_related_data()
            self.git_repo.git.merge(f'origin/{BASE}', '-Xtheirs', '-m', MERGE_FROM_MASTER_COMMIT_MESSAGE)
            for pack_auto_bumper in self.packs_to_autobump:
                new_version = pack_auto_bumper.autobump()
                print(f'Pack {pack_auto_bumper.pack_id} new version: {new_version}.')
                self.git_repo.git.add(f'{PACKS_DIR}/{pack_auto_bumper.pack_id}')
                self.git_repo.git.commit('-m', COMMIT_MESSAGE.format(pack_auto_bumper.pack_id, new_version))
                body += PR_COMMENT.format(pack_auto_bumper.pack_id, new_version)
            print(f'[{self.pr.number}] Committed the changes. Commenting on the pr: \n{body}.\n')
            body += PR_COMMENT_STOP_AUTOMATION
            self.git_repo.git.push()
            self.pr.create_issue_comment(body)
        return body
<|end_body_1|>

Solution:
class BranchAutoBumper:
    def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_autobump: List[PackAutoBumper], run_id: str):
        """Args: pr: Pull Request related to the branch. git_repo: Git API object packs_to_autobump: Pack that was changed in this PR and need to autobump its versions. run_id: GitHub action run id."""
        assert packs_to_autobump, f'packs_to_autobump in the pr: {pr.number}, cant be empty.'
        self.pr = pr
        self.branch = pr.head.ref
        self.git_repo = git_repo
        self.packs_to_autobump = packs_to_autobump
        self.github_run_id = run_id

    def autobump(self):
        """AutoBumps version for all relevant packs in the pr: 1. Checkouts the branch and saves pr changed related data. 2. Merges from BASE and accept `theirs` changes. 3. AutoBumps version for each relevant packs. 4. Commit changes for each pack. 5. Comment on the PR. 6. Pushes the changes."""
        body = PR_COMMENT_TITLE.format(self.github_run_id)
        with Checkout(self.git_repo, self.branch):
            for pack_auto_bumper in self.packs_to_autobump:
                pack_auto_bumper.set_pr_changed_rn_related_data()
            self.git_repo.git.merge(f'origin/{BASE}', '-Xtheirs', '-m', MERGE_FROM_MASTER_COMMIT_MESSAGE)
            for pack_auto_bumper in self.packs_to_autobump:
                new_version = pack_auto_bumper.autobump()
                print(f'Pack {pack_auto_bumper.pack_id} new version: {new_version}.')
                self.git_repo.git.add(f'{PACKS_DIR}/{pack_auto_bumper.pack_id}')
                self.git_repo.git.commit('-m', COMMIT_MESSAGE.format(pack_auto_bumper.pack_id, new_version))
                body += PR_COMMENT.format(pack_auto_bumper.pack_id, new_version)
            print(f'[{self.pr.number}] Committed the changes. Commenting on the pr: \n{body}.\n')
            body += PR_COMMENT_STOP_AUTOMATION
            self.git_repo.git.push()
            self.pr.create_issue_comment(body)
        return body


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

Class description:
A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3.

Method signatures and docstrings:
- def __init__(self, python_path='', dataflow_hook=None, **kwargs): Constructor. Args: python_path: Set PYTHONPATH to include this path before calling DataFlow. dataflow_hook: The DataFlow hook to use. If none, will automatically create. **kwargs: Additional args for super class.
- def execute(self, context): Execute the python dataflow job.

Implement the Python class `DataFlowPythonOperator` described below.

Class description:
A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3.

Method signatures and docstrings:
- def __init__(self, python_path='', dataflow_hook=None, **kwargs): Constructor. Args: python_path: Set PYTHONPATH to include this path before calling DataFlow. dataflow_hook: The DataFlow hook to use. If none, will automatically create. **kwargs: Additional args for super class.
- def execute(self, context): Execute the python dataflow job.

<|skeleton|>
class DataFlowPythonOperator:
    """A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3."""

    def __init__(self, python_path='', dataflow_hook=None, **kwargs):
        """Constructor. Args: python_path: Set PYTHONPATH to include this path before calling DataFlow. dataflow_hook: The DataFlow hook to use. If none, will automatically create. **kwargs: Additional args for super class."""
        <|body_0|>

    def execute(self, context):
        """Execute the python dataflow job."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        old_pypath = os.environ.get('PYTHONPATH', '')
        if not old_pypath:
            pypath = python_path
        elif python_path in old_pypath:
            pypath = old_pypath
        else:
            pypath = old_pypath + ':' + python_path
        os.environ['PYTHONPATH'] = pypath
        self.dataflow_hook = dataflow_hook
        super().__init__(**kwargs)
<|end_body_0|>

<|body_start_1|>
        bucket_helper = dataflow_operator.GoogleCloudBucketHelper(self.gcp_conn_id, self.delegate_to)
        self.py_file = bucket_helper.google_cloud_to_local(self.py_file)
        if self.dataflow_hook is None:
            self.dataflow_hook = dataflow_py3_hook.DataFlowHook(gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, poll_sleep=self.poll_sleep)
        dataflow_options = self.dataflow_default_options.copy()
        dataflow_options.update(self.options)
        formatted_options = {_camel_to_snake(key): dataflow_options[key] for key in dataflow_options}
        self.dataflow_hook.start_python_dataflow(self.task_id, formatted_options, self.py_file, self.py_options)
<|end_body_1|>

Solution:
class DataFlowPythonOperator:
    """A Dataflow Operator to run py3 jobs. This operator patches `dataflow_operator.DataFlowPythonOperator` and call `dataflow_py3_hook.DataFlowHook` to start DataFlow jobs in python 3."""

    def __init__(self, python_path='', dataflow_hook=None, **kwargs):
        """Constructor. Args: python_path: Set PYTHONPATH to include this path before calling DataFlow. dataflow_hook: The DataFlow hook to use. If none, will automatically create. **kwargs: Additional args for super class."""
        old_pypath = os.environ.get('PYTHONPATH', '')
        if not old_pypath:
            pypath = python_path
        elif python_path in old_pypath:
            pypath = old_pypath
        else:
            pypath = old_pypath + ':' + python_path
        os.environ['PYTHONPATH'] = pypath
        self.dataflow_hook = dataflow_hook
        super().__init__(**kwargs)

    def execute(self, context):
        """Execute the python dataflow job."""
        bucket_helper = dataflow_operator.GoogleCloudBucketHelper(self.gcp_conn_id, self.delegate_to)
        self.py_file = bucket_helper.google_cloud_to_local(self.py_file)
        if self.dataflow_hook is None:
            self.dataflow_hook = dataflow_py3_hook.DataFlowHook(gcp_conn_id=self.gcp_conn_id, delegate_to=self.delegate_to, poll_sleep=self.poll_sleep)
        dataflow_options = self.dataflow_default_options.copy()
        dataflow_options.update(self.options)
        formatted_options = {_camel_to_snake(key): dataflow_options[key] for key in dataflow_options}
        self.dataflow_hook.start_python_dataflow(self.task_id, formatted_options, self.py_file, self.py_options)


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

Class description:
Implement the _VisWorker class.

Method signatures and docstrings:
- def __init__(self, video_vis, task_queue, result_queue): Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. task_queue (mp.Queue): a shared queue for incoming task for visualization. result_queue (mp.Queue): a shared queue for visualized results.
- def run(self): Run visualization asynchronously.

Implement the Python class `_VisWorker` described below.

Class description:
Implement the _VisWorker class.

Method signatures and docstrings:
- def __init__(self, video_vis, task_queue, result_queue): Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. task_queue (mp.Queue): a shared queue for incoming task for visualization. result_queue (mp.Queue): a shared queue for visualized results.
- def run(self): Run visualization asynchronously.

<|skeleton|>
class _VisWorker:

    def __init__(self, video_vis, task_queue, result_queue):
        """Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. task_queue (mp.Queue): a shared queue for incoming task for visualization. result_queue (mp.Queue): a shared queue for visualized results."""
        <|body_0|>

    def run(self):
        """Run visualization asynchronously."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.video_vis = video_vis
        self.task_queue = task_queue
        self.result_queue = result_queue
        super().__init__()
<|end_body_0|>

<|body_start_1|>
        while True:
            task = self.task_queue.get()
            if isinstance(task, _StopToken):
                break
            frames = draw_predictions(task, self.video_vis)
            task.frames = np.array(frames)
            self.result_queue.put(task)
<|end_body_1|>

Solution:
class _VisWorker:
    def __init__(self, video_vis, task_queue, result_queue):
        """Visualization Worker for AsyncVis. Args: video_vis (VideoVisualizer object): object with tools for visualization. task_queue (mp.Queue): a shared queue for incoming task for visualization. result_queue (mp.Queue): a shared queue for visualized results."""
        self.video_vis = video_vis
        self.task_queue = task_queue
        self.result_queue = result_queue
        super().__init__()

    def run(self):
        """Run visualization asynchronously."""
        while True:
            task = self.task_queue.get()
            if isinstance(task, _StopToken):
                break
            frames = draw_predictions(task, self.video_vis)
            task.frames = np.array(frames)
            self.result_queue.put(task)


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

Class description:
Utility to get the relevant registrar info for a filing.

Method signatures and docstrings:
- def get_registrar_info(filing_effective_date) -> dict: Return the registrar for a filing.
- def encode_registrar_signature(signature_image) -> str: Return the encoded registrar signature.

Implement the Python class `RegistrarInfo` described below.

Class description:
Utility to get the relevant registrar info for a filing.

Method signatures and docstrings:
- def get_registrar_info(filing_effective_date) -> dict: Return the registrar for a filing.
- def encode_registrar_signature(signature_image) -> str: Return the encoded registrar signature.

<|skeleton|>
class RegistrarInfo:
    """Utility to get the relevant registrar info for a filing."""

    def get_registrar_info(filing_effective_date) -> dict:
        """Return the registrar for a filing."""
        <|body_0|>

    def encode_registrar_signature(signature_image) -> str:
        """Return the encoded registrar signature."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        filing_effective_date = filing_effective_date.replace(tzinfo=None)
        registrar = [x for x in RegistrarInfo.registrar_info if filing_effective_date >= datetime.datetime.strptime(x['startDate'], '%Y-%m-%dT%H:%M:%S') and (x['endDate'] is None or filing_effective_date <= datetime.datetime.strptime(x['endDate'], '%Y-%m-%dT%H:%M:%S'))][0]
        signature = RegistrarInfo.encode_registrar_signature(registrar['signatureImage'])
        registrar['signature'] = f'data:image/png;base64,{signature}'
        if registrar['signatureImageAndText']:
            signature_and_text = RegistrarInfo.encode_registrar_signature(registrar['signatureImageAndText'])
            registrar['signatureAndText'] = f'data:image/png;base64,{signature_and_text}'
        return registrar
<|end_body_0|>

<|body_start_1|>
        template_path = current_app.config.get('REPORT_TEMPLATE_PATH')
        image_path = f'{template_path}/registrar_signatures/{signature_image}'
        with open(image_path, 'rb') as image_file:
            encoded_string = base64.b64encode(image_file.read())
            return encoded_string.decode('utf-8')
<|end_body_1|>

Solution:
class RegistrarInfo:
    """Utility to get the relevant registrar info for a filing."""

    def get_registrar_info(filing_effective_date) -> dict:
        """Return the registrar for a filing."""
        filing_effective_date = filing_effective_date.replace(tzinfo=None)
        registrar = [x for x in RegistrarInfo.registrar_info if filing_effective_date >= datetime.datetime.strptime(x['startDate'], '%Y-%m-%dT%H:%M:%S') and (x['endDate'] is None or filing_effective_date <= datetime.datetime.strptime(x['endDate'], '%Y-%m-%dT%H:%M:%S'))][0]
        signature = RegistrarInfo.encode_registrar_signature(registrar['signatureImage'])
        registrar['signature'] = f'data:image/png;base64,{signature}'
        if registrar['signatureImageAndText']:
            signature_and_text = RegistrarInfo.encode_registrar_signature(registrar['signatureImageAndText'])
            registrar['signatureAndText'] = f'data:image/png;base64,{signature_and_text}'
        return registrar

    def encode_registrar_signature(signature_image) -> str:
        """Return the encoded registrar signature."""
        template_path = current_app.config.get('REPORT_TEMPLATE_PATH')
        image_path = f'{template_path}/registrar_signatures/{signature_image}'
        with open(image_path, 'rb') as image_file:
            encoded_string = base64.b64encode(image_file.read())
            return encoded_string.decode('utf-8')


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

Class description:
Implement the Prime class.

Method signatures and docstrings:
- def is_prime(self, number): Return True if *number* is prime.
- def print_next_prime(self, number): Print the closest prime number larger than *number*.

Implement the Python class `Prime` described below.

Class description:
Implement the Prime class.

Method signatures and docstrings:
- def is_prime(self, number): Return True if *number* is prime.
- def print_next_prime(self, number): Print the closest prime number larger than *number*.

<|skeleton|>
class Prime:

    def is_prime(self, number):
        """Return True if *number* is prime."""
        <|body_0|>

    def print_next_prime(self, number):
        """Print the closest prime number larger than *number*."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        if number in (0, 1):
            return False
        if number < 0:
            return False
        for element in range(2, number):
            if number % element == 0:
                return False
        return True
<|end_body_0|>

<|body_start_1|>
        index = number
        while True:
            index += 1
            if self.is_prime(index):
                print('The next prime after {0} is {1}'.format(number, index))
                return index
<|end_body_1|>

Solution:
class Prime:
    def is_prime(self, number):
        """Return True if *number* is prime."""
        if number in (0, 1):
            return False
        if number < 0:
            return False
        for element in range(2, number):
            if number % element == 0:
                return False
        return True

    def print_next_prime(self, number):
        """Print the closest prime number larger than *number*."""
        index = number
        while True:
            index += 1
            if self.is_prime(index):
                print('The next prime after {0} is {1}'.format(number, index))
                return index


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

Class description:
A class for retrieving and executing metadata scripts.

Method signatures and docstrings:
- def __init__(self, script_type, default_shell=None, run_dir=None, debug=False): Constructor. Args: script_type: string, the metadata script type to run. default_shell: string, the default shell to execute the script. run_dir: string, the base directory location of the temporary directory. debug: bool, True if debug output should write to the console.
- def _RunScripts(self, run_dir=None): Retrieve metadata scripts and execute them. Args: run_dir: string, the base directory location of the temporary directory.

Implement the Python class `ScriptManager` described below.

Class description:
A class for retrieving and executing metadata scripts.

Method signatures and docstrings:
- def __init__(self, script_type, default_shell=None, run_dir=None, debug=False): Constructor. Args: script_type: string, the metadata script type to run. default_shell: string, the default shell to execute the script. run_dir: string, the base directory location of the temporary directory. debug: bool, True if debug output should write to the console.
- def _RunScripts(self, run_dir=None): Retrieve metadata scripts and execute them. Args: run_dir: string, the base directory location of the temporary directory.

<|skeleton|>
class ScriptManager:
    """A class for retrieving and executing metadata scripts."""

    def __init__(self, script_type, default_shell=None, run_dir=None, debug=False):
        """Constructor. Args: script_type: string, the metadata script type to run. default_shell: string, the default shell to execute the script. run_dir: string, the base directory location of the temporary directory. debug: bool, True if debug output should write to the console."""
        <|body_0|>

    def _RunScripts(self, run_dir=None):
        """Retrieve metadata scripts and execute them. Args: run_dir: string, the base directory location of the temporary directory."""
        <|body_1|>

<|end_skeleton|>

<|body_start_0|>
        self.script_type = script_type
        self.default_shell = default_shell
        name = '%s-script' % self.script_type
        facility = logging.handlers.SysLogHandler.LOG_DAEMON
        self.logger = logger.Logger(name=name, debug=debug, facility=facility)
        self.retriever = script_retriever.ScriptRetriever(self.logger, script_type)
        self.executor = script_executor.ScriptExecutor(self.logger, script_type, default_shell=default_shell)
        self._RunScripts(run_dir=run_dir)
<|end_body_0|>

<|body_start_1|>
        with _CreateTempDir(self.script_type, run_dir=run_dir) as dest_dir:
            try:
                self.logger.info('Starting %s scripts.', self.script_type)
                script_dict = self.retriever.GetScripts(dest_dir)
                self.executor.RunScripts(script_dict)
            finally:
                self.logger.info('Finished running %s scripts.', self.script_type)
<|end_body_1|>

Solution:
class ScriptManager:
    """A class for retrieving and executing metadata scripts."""

    def __init__(self, script_type, default_shell=None, run_dir=None, debug=False):
        """Constructor. Args: script_type: string, the metadata script type to run. default_shell: string, the default shell to execute the script. run_dir: string, the base directory location of the temporary directory. debug: bool, True if debug output should write to the console."""
        self.script_type = script_type
        self.default_shell = default_shell
        name = '%s-script' % self.script_type
        facility = logging.handlers.SysLogHandler.LOG_DAEMON
        self.logger = logger.Logger(name=name, debug=debug, facility=facility)
        self.retriever = script_retriever.ScriptRetriever(self.logger, script_type)
        self.executor = script_executor.ScriptExecutor(self.logger, script_type, default_shell=default_shell)
        self._RunScripts(run_dir=run_dir)

    def _RunScripts(self, run_dir=None):
        """Retrieve metadata scripts and execute them. Args: run_dir: string, the base directory location of the temporary directory."""
        with _CreateTempDir(self.script_type, run_dir=run_dir) as dest_dir:
            try:
                self.logger.info('Starting %s scripts.', self.script_type)
                script_dict = self.retriever.GetScripts(dest_dir)
                self.executor.RunScripts(script_dict)
            finally:
                self.logger.info('Finished running %s scripts.', self.script_type)