text:
import time

from oslo_log import log as logging
from oslo_service import loopingcall

from cinder import coordination
from cinder import exception
from cinder.i18n import _
from cinder.volume.drivers.dell_emc.vmax import utils

LOG = logging.getLogger(__name__)

WRITE_DISABLED = "Write Disabled"
UNLINK_INTERVAL = 15
UNLINK_RETRIES = 30

class VMAXProvision(object):
    """Provisioning Class for Dell EMC VMAX volume drivers.

    It supports VMAX arrays.
    """
    def __init__(self, rest):
        self.utils = utils.VMAXUtils()
        self.rest = rest

    def create_storage_group(
            self, array, storagegroup_name, srp, slo, workload,
            extra_specs, do_disable_compression=False):
        """Create a new storage group.

        :param array: the array serial number
        :param storagegroup_name: the group name (String)
        :param srp: the SRP (String)
        :param slo: the SLO (String)
        :param workload: the workload (String)
        :param extra_specs: additional info
        :param do_disable_compression: disable compression flag
        :returns: storagegroup - storage group object
        """
        start_time = time.time()

        @coordination.synchronized("emc-sg-{storage_group}")
        def do_create_storage_group(storage_group):
            # Check if storage group has been recently created
            storagegroup = self.rest.get_storage_group(
                array, storagegroup_name)
            if storagegroup is None:
                storagegroup = self.rest.create_storage_group(
                    array, storage_group, srp, slo, workload, extra_specs,
                    do_disable_compression)

                LOG.debug("Create storage group took: %(delta)s H:MM:SS.",
                          {'delta': self.utils.get_time_delta(start_time,
                                                              time.time())})
                LOG.info("Storage group %(sg)s created successfully.",
                         {'sg': storagegroup_name})
            else:
                LOG.info("Storage group %(sg)s already exists.",
                         {'sg': storagegroup_name})
            return storagegroup

        return do_create_storage_group(storagegroup_name)

    def create_volume_from_sg(self, array, volume_name, storagegroup_name,
                              volume_size, extra_specs):
        """Create a new volume in the given storage group.

        :param array: the array serial number
        :param volume_name: the volume name (String)
        :param storagegroup_name: the storage group name
        :param volume_size: volume size (String)
        :param extra_specs: the extra specifications
        :returns: dict -- volume_dict - the volume dict
        """
        @coordination.synchronized("emc-sg-{storage_group}")
        def do_create_volume_from_sg(storage_group):
            start_time = time.time()

            volume_dict = self.rest.create_volume_from_sg(
                array, volume_name, storage_group,
                volume_size, extra_specs)

            LOG.debug("Create volume from storage group "
                      "took: %(delta)s H:MM:SS.",
                      {'delta': self.utils.get_time_delta(start_time,
                                                          time.time())})
            return volume_dict
        return do_create_volume_from_sg(storagegroup_name)

    def delete_volume_from_srp(self, array, device_id, volume_name):
        """Delete a volume from the srp.

        :param array: the array serial number
        :param device_id:  the volume device id
        :param volume_name: the volume name
        """
        start_time = time.time()
        LOG.debug("Delete volume %(volume_name)s from srp.",
                  {'volume_name': volume_name})
        self.rest.delete_volume(array, device_id)
        LOG.debug("Delete volume took: %(delta)s H:MM:SS.",
                  {'delta': self.utils.get_time_delta(
                      start_time, time.time())})

    def create_volume_snapvx(self, array, source_device_id,
                             snap_name, extra_specs):
        """Create a snapVx of a volume.

        :param array: the array serial number
        :param source_device_id: source volume device id
        :param snap_name: the snapshot name
        :param extra_specs: the extra specifications
        """
        start_time = time.time()
        LOG.debug("Create Snap Vx snapshot of: %(source)s.",
                  {'source': source_device_id})
        self.rest.create_volume_snap(
            array, snap_name, source_device_id, extra_specs)
        LOG.debug("Create volume snapVx took: %(delta)s H:MM:SS.",
                  {'delta': self.utils.get_time_delta(start_time,
                                                      time.time())})

    def create_volume_replica(
            self, array, source_device_id, target_device_id,
            snap_name, extra_specs, create_snap=False):
        """Create a snap vx of a source and copy to a target.

        :param array: the array serial number
        :param source_device_id: source volume device id
        :param target_device_id: target volume device id
        :param snap_name: the name for the snap shot
        :param extra_specs: extra specifications
        :param create_snap: Flag for create snapvx
        """
        start_time = time.time()
        if create_snap:
            self.create_volume_snapvx(array, source_device_id,
                                      snap_name, extra_specs)
        # Link source to target
        self.rest.modify_volume_snap(
            array, source_device_id, target_device_id, snap_name,
            extra_specs, link=True)

        LOG.debug("Create element replica took: %(delta)s H:MM:SS.",
                  {'delta': self.utils.get_time_delta(start_time,
                                                      time.time())})

    def break_replication_relationship(
            self, array, target_device_id, source_device_id, snap_name,
            extra_specs):
        """Unlink a snapshot from its target volume.

        :param array: the array serial number
        :param source_device_id: source volume device id
        :param target_device_id: target volume device id
        :param snap_name: the name for the snap shot
        :param extra_specs: extra specifications
        """
        LOG.debug("Break snap vx link relationship between: %(src)s "
                  "and: %(tgt)s.",
                  {'src': source_device_id, 'tgt': target_device_id})

        self._unlink_volume(array, source_device_id, target_device_id,
                            snap_name, extra_specs)

    def _unlink_volume(
            self, array, source_device_id, target_device_id, snap_name,
            extra_specs, list_volume_pairs=None):
        """Unlink a target volume from its source volume.

        :param array: the array serial number
        :param source_device_id: the source device id
        :param target_device_id: the target device id
        :param snap_name: the snap name
        :param extra_specs: extra specifications
        :param list_volume_pairs: list of volume pairs, optional
        :return: return code
        """

        def _unlink_vol():
            """Called at an interval until the synchronization is finished.

            :raises: loopingcall.LoopingCallDone
            """
            retries = kwargs['retries']
            try:
                kwargs['retries'] = retries + 1
                if not kwargs['modify_vol_success']:
                    self.rest.modify_volume_snap(
                        array, source_device_id, target_device_id, snap_name,
                        extra_specs, unlink=True,
                        list_volume_pairs=list_volume_pairs)
                    kwargs['modify_vol_success'] = True
            except exception.VolumeBackendAPIException:
                pass

            if kwargs['retries'] > UNLINK_RETRIES:
                LOG.error("_unlink_volume failed after %(retries)d "
                          "tries.", {'retries': retries})
                raise loopingcall.LoopingCallDone(retvalue=30)
            if kwargs['modify_vol_success']:
                raise loopingcall.LoopingCallDone()

        kwargs = {'retries': 0,
                  'modify_vol_success': False}
        timer = loopingcall.FixedIntervalLoopingCall(_unlink_vol)
        rc = timer.start(interval=UNLINK_INTERVAL).wait()
        return rc

    def delete_volume_snap(self, array, snap_name,
                           source_device_id, restored=False):
        """Delete a snapVx snapshot of a volume.

        :param array: the array serial number
        :param snap_name: the snapshot name
        :param source_device_id: the source device id
        :param restored: Flag to indicate if restored session is being deleted
        """
        LOG.debug("Delete SnapVx: %(snap_name)s for volume %(vol)s.",
                  {'vol': source_device_id, 'snap_name': snap_name})
        self.rest.delete_volume_snap(
            array, snap_name, source_device_id, restored)

    def is_restore_complete(self, array, source_device_id,
                            snap_name, extra_specs):
        """Check and wait for a restore to complete

        :param array: the array serial number
        :param source_device_id: source device id
        :param snap_name: snapshot name
        :param extra_specs: extra specification
        :returns: bool
        """

        def _wait_for_restore():
            """Called at an interval until the restore is finished.

            :raises: loopingcall.LoopingCallDone
            :raises: VolumeBackendAPIException
            """
            retries = kwargs['retries']
            try:
                kwargs['retries'] = retries + 1
                if not kwargs['wait_for_restore_called']:
                    if self._is_restore_complete(
                            array, source_device_id, snap_name):
                        kwargs['wait_for_restore_called'] = True
            except Exception:
                exception_message = (_("Issue encountered waiting for "
                                       "restore."))
                LOG.exception(exception_message)
                raise exception.VolumeBackendAPIException(
                    data=exception_message)

            if kwargs['wait_for_restore_called']:
                raise loopingcall.LoopingCallDone()
            if kwargs['retries'] > int(extra_specs[utils.RETRIES]):
                LOG.error("_wait_for_restore failed after %(retries)d "
                          "tries.", {'retries': retries})
                raise loopingcall.LoopingCallDone(
                    retvalue=int(extra_specs[utils.RETRIES]))

        kwargs = {'retries': 0,
                  'wait_for_restore_called': False}
        timer = loopingcall.FixedIntervalLoopingCall(_wait_for_restore)
        rc = timer.start(interval=int(extra_specs[utils.INTERVAL])).wait()
        return rc

    def _is_restore_complete(self, array, source_device_id, snap_name):
        """Helper function to check if restore is complete.

        :param array: the array serial number
        :param source_device_id: source device id
        :param snap_name: the snapshot name
        :returns: restored -- bool
        """
        restored = False
        snap_details = self.rest.get_volume_snap(
            array, source_device_id, snap_name)
        if snap_details:
            linked_devices = snap_details.get("linkedDevices", [])
            for linked_device in linked_devices:
                if ('targetDevice' in linked_device and
                        source_device_id == linked_device['targetDevice']):
                    if ('state' in linked_device and
                            linked_device['state'] == "Restored"):
                        restored = True
        return restored

    def delete_temp_volume_snap(self, array, snap_name, source_device_id):
        """Delete the temporary snapshot created for clone operations.

        There can be instances where the source and target both attempt to
        delete a temp snapshot simultaneously, so we must lock the snap and
        then double check it is on the array.
        :param array: the array serial number
        :param snap_name: the snapshot name
        :param source_device_id: the source device id
        """

        @coordination.synchronized("emc-snapvx-{snapvx_name}")
        def do_delete_temp_snap(snapvx_name):
            # Ensure snap has not been recently deleted
            if self.rest.get_volume_snap(
                    array, source_device_id, snapvx_name):
                self.delete_volume_snap(array, snapvx_name, source_device_id)

        do_delete_temp_snap(snap_name)

    def delete_volume_snap_check_for_links(self, array, snap_name,
                                           source_devices, extra_specs):
        """Check if a snap has any links before deletion.

        If a snapshot has any links, break the replication relationship
        before deletion.
        :param array: the array serial number
        :param snap_name: the snapshot name
        :param source_devices: the source device ids
        :param extra_specs: the extra specifications
        """
        list_device_pairs = []
        if not isinstance(source_devices, list):
            source_devices = [source_devices]
        for source_device in source_devices:
            LOG.debug("Check for linked devices to SnapVx: %(snap_name)s "
                      "for volume %(vol)s.",
                      {'vol': source_device, 'snap_name': snap_name})
            linked_list = self.rest.get_snap_linked_device_list(
                array, source_device, snap_name)
            for link in linked_list:
                target_device = link['targetDevice']
                list_device_pairs.append((source_device, target_device))
        if list_device_pairs:
            self._unlink_volume(array, "", "", snap_name, extra_specs,
                                list_volume_pairs=list_device_pairs)
        self.delete_volume_snap(array, snap_name, source_devices)

    def extend_volume(self, array, device_id, new_size, extra_specs,
                      rdf_group=None):
        """Extend a volume.

        :param array: the array serial number
        :param device_id: the volume device id
        :param new_size: the new size (GB)
        :param extra_specs: the extra specifications
        :param rdf_group: the rdf group number, if required
        :returns: status_code
        """
        start_time = time.time()
        if rdf_group:
            @coordination.synchronized('emc-rg-{rdf_group}')
            def _extend_replicated_volume(rdf_group):
                self.rest.extend_volume(array, device_id,
                                        new_size, extra_specs)
            _extend_replicated_volume(rdf_group)
        else:
            self.rest.extend_volume(array, device_id, new_size, extra_specs)
            LOG.debug("Extend VMAX volume took: %(delta)s H:MM:SS.",
                      {'delta': self.utils.get_time_delta(start_time,
                                                          time.time())})

    def get_srp_pool_stats(self, array, array_info):
        """Get the srp capacity stats.

        :param array: the array serial number
        :param array_info: the array dict
        :returns: total_capacity_gb
        :returns: remaining_capacity_gb
        :returns: subscribed_capacity_gb
        :returns: array_reserve_percent
        """
        total_capacity_gb = 0
        remaining_capacity_gb = 0
        subscribed_capacity_gb = 0
        array_reserve_percent = 0
        srp = array_info['srpName']
        LOG.debug(
            "Retrieving capacity for srp %(srpName)s on array %(array)s.",
            {'srpName': srp, 'array': array})

        srp_details = self.rest.get_srp_by_name(array, srp)
        if not srp_details:
            LOG.error("Unable to retrieve srp instance of %(srpName)s on "
                      "array %(array)s.",
                      {'srpName': srp, 'array': array})
            return 0, 0, 0, 0, False
        try:
            total_capacity_gb = srp_details['total_usable_cap_gb']
            try:
                used_capacity_gb = srp_details['total_used_cap_gb']
                remaining_capacity_gb = float(
                    total_capacity_gb - used_capacity_gb)
            except KeyError:
                remaining_capacity_gb = srp_details['fba_free_capacity']
            subscribed_capacity_gb = srp_details['total_subscribed_cap_gb']
            array_reserve_percent = srp_details['reserved_cap_percent']
        except KeyError:
            pass

        return (total_capacity_gb, remaining_capacity_gb,
                subscribed_capacity_gb, array_reserve_percent)

    def verify_slo_workload(self, array, slo, workload, srp):
        """Check if SLO and workload values are valid.

        :param array: the array serial number
        :param slo: Service Level Object e.g bronze
        :param workload: workload e.g DSS
        :param srp: the storage resource pool name
        :returns: boolean
        """
        is_valid_slo, is_valid_workload = False, False

        if workload and workload.lower() == 'none':
            workload = None

        if not workload:
            is_valid_workload = True

        if slo and slo.lower() == 'none':
            slo = None

        valid_slos = self.rest.get_slo_list(array)
        valid_workloads = self.rest.get_workload_settings(array)
        for valid_slo in valid_slos:
            if slo == valid_slo:
                is_valid_slo = True
                break

        for valid_workload in valid_workloads:
            if workload == valid_workload:
                is_valid_workload = True
                break

        if not slo:
            is_valid_slo = True
            if workload:
                is_valid_workload = False

        if not is_valid_slo:
            LOG.error(
                "SLO: %(slo)s is not valid. Valid values are: "
                "%(valid_slos)s.", {'slo': slo, 'valid_slos': valid_slos})

        if not is_valid_workload:
            LOG.error(
                "Workload: %(workload)s is not valid. Valid values are "
                "%(valid_workloads)s. Note you cannot "
                "set a workload without an SLO.",
                {'workload': workload, 'valid_workloads': valid_workloads})

        return is_valid_slo, is_valid_workload

    def get_slo_workload_settings_from_storage_group(
            self, array, sg_name):
        """Get slo and workload settings from a storage group.

        :param array: the array serial number
        :param sg_name: the storage group name
        :returns: storage group slo settings
        """
        slo = 'NONE'
        workload = 'NONE'
        storage_group = self.rest.get_storage_group(array, sg_name)
        if storage_group:
            try:
                slo = storage_group['slo']
                workload = storage_group['workload']
            except KeyError:
                pass
        else:
            exception_message = (_(
                "Could not retrieve storage group %(sg_name)s. ") %
                {'sg_name': sg_name})
            LOG.error(exception_message)
            raise exception.VolumeBackendAPIException(data=exception_message)
        return '%(slo)s+%(workload)s' % {'slo': slo, 'workload': workload}

    @coordination.synchronized('emc-rg-{rdf_group}')
    def break_rdf_relationship(self, array, device_id, target_device,
                               rdf_group, rep_extra_specs, state):
        """Break the rdf relationship between a pair of devices.

        :param array: the array serial number
        :param device_id: the source device id
        :param target_device: target device id
        :param rdf_group: the rdf group number
        :param rep_extra_specs: replication extra specs
        :param state: the state of the rdf pair
        """
        LOG.info("Suspending rdf pair: source device: %(src)s "
                 "target device: %(tgt)s.",
                 {'src': device_id, 'tgt': target_device})
        if state.lower() == utils.RDF_SYNCINPROG_STATE:
            self.rest.wait_for_rdf_consistent_state(
                array, device_id, target_device,
                rep_extra_specs, state)
        if state.lower() == utils.RDF_SUSPENDED_STATE:
            LOG.info("RDF pair is already suspended")
        else:
            self.rest.modify_rdf_device_pair(
                array, device_id, rdf_group, rep_extra_specs, suspend=True)
        self.delete_rdf_pair(array, device_id, rdf_group,
                             target_device, rep_extra_specs)

    def break_metro_rdf_pair(self, array, device_id, target_device,
                             rdf_group, rep_extra_specs, metro_grp):
        """Delete replication for a Metro device pair.

        Need to suspend the entire group before we can delete a single pair.
        :param array: the array serial number
        :param device_id: the device id
        :param target_device: the target device id
        :param rdf_group: the rdf group number
        :param rep_extra_specs: the replication extra specifications
        :param metro_grp: the metro storage group name
        """
        # Suspend I/O on the RDF links...
        LOG.info("Suspending I/O for all volumes in the RDF group: %(rdfg)s",
                 {'rdfg': rdf_group})
        self.disable_group_replication(
            array, metro_grp, rdf_group, rep_extra_specs)
        self.delete_rdf_pair(array, device_id, rdf_group,
                             target_device, rep_extra_specs)

    def delete_rdf_pair(
            self, array, device_id, rdf_group, target_device, extra_specs):
        """Delete an rdf pairing.

        If the replication mode is synchronous, only one attempt is required
        to delete the pair. Otherwise, we need to wait until all the tracks
        are cleared before the delete will be successful. As there is
        currently no way to track this information, we keep attempting the
        operation until it is successful.

        :param array: the array serial number
        :param device_id: source volume device id
        :param rdf_group: the rdf group number
        :param target_device: the target device
        :param extra_specs: extra specifications
        """
        LOG.info("Deleting rdf pair: source device: %(src)s "
                 "target device: %(tgt)s.",
                 {'src': device_id, 'tgt': target_device})
        if (extra_specs.get(utils.REP_MODE) and
                extra_specs.get(utils.REP_MODE) == utils.REP_SYNC):
            return self.rest.delete_rdf_pair(array, device_id, rdf_group)

        def _delete_pair():
            """Delete a rdf volume pair.

            Called at an interval until all the tracks are cleared
            and the operation is successful.

            :raises: loopingcall.LoopingCallDone
            """
            retries = kwargs['retries']
            try:
                kwargs['retries'] = retries + 1
                if not kwargs['delete_pair_success']:
                    self.rest.delete_rdf_pair(
                        array, device_id, rdf_group)
                    kwargs['delete_pair_success'] = True
            except exception.VolumeBackendAPIException:
                pass

            if kwargs['retries'] > UNLINK_RETRIES:
                LOG.error("Delete volume pair failed after %(retries)d "
                          "tries.", {'retries': retries})
                raise loopingcall.LoopingCallDone(retvalue=30)
            if kwargs['delete_pair_success']:
                raise loopingcall.LoopingCallDone()

        kwargs = {'retries': 0,
                  'delete_pair_success': False}
        timer = loopingcall.FixedIntervalLoopingCall(_delete_pair)
        rc = timer.start(interval=UNLINK_INTERVAL).wait()
        return rc

    def get_or_create_volume_group(self, array, group, extra_specs):
        """Get or create a volume group.

        Sometimes it may be necessary to recreate a volume group on the
        backend - for example, when the last member volume has been removed
        from the group, but the cinder group object has not been deleted.
        :param array: the array serial number
        :param group: the group object
        :param extra_specs: the extra specifications
        :return: group name
        """
        vol_grp_name = self.utils.update_volume_group_name(group)
        return self.get_or_create_group(array, vol_grp_name, extra_specs)

    def get_or_create_group(self, array, group_name, extra_specs):
        """Get or create a generic volume group.

        :param array: the array serial number
        :param group_name: the group name
        :param extra_specs: the extra specifications
        :return: group name
        """
        storage_group = self.rest.get_storage_group(array, group_name)
        if not storage_group:
            self.create_volume_group(array, group_name, extra_specs)
        return group_name

    def create_volume_group(self, array, group_name, extra_specs):
        """Create a generic volume group.

        :param array: the array serial number
        :param group_name: the name of the group
        :param extra_specs: the extra specifications
        :returns: volume_group
        """
        return self.create_storage_group(array, group_name,
                                         None, None, None, extra_specs)

    def create_group_replica(
            self, array, source_group, snap_name, extra_specs):
        """Create a replica (snapVx) of a volume group.

        :param array: the array serial number
        :param source_group: the source group name
        :param snap_name: the name for the snap shot
        :param extra_specs: extra specifications
        """
        LOG.debug("Creating Snap Vx snapshot of storage group: %(srcGroup)s.",
                  {'srcGroup': source_group})

        # Create snapshot
        self.rest.create_storagegroup_snap(
            array, source_group, snap_name, extra_specs)

    def delete_group_replica(self, array, snap_name, source_group_name,
                             src_dev_ids, extra_specs):
        """Delete the snapshot.

        :param array: the array serial number
        :param snap_name: the name for the snap shot
        :param source_group_name: the source group name
        :param src_dev_ids: the list of source device ids
        :param extra_specs: extra specifications
        """
        # Delete snapvx snapshot
        LOG.debug("Deleting Snap Vx snapshot: source group: %(srcGroup)s "
                  "snapshot: %(snap_name)s.",
                  {'srcGroup': source_group_name, 'snap_name': snap_name})
        self.delete_volume_snap_check_for_links(
            array, snap_name, src_dev_ids, extra_specs)

    def link_and_break_replica(self, array, source_group_name,
                               target_group_name, snap_name, extra_specs,
                               list_volume_pairs, delete_snapshot=False):
        """Links a group snap and breaks the relationship.

        :param array: the array serial
        :param source_group_name: the source group name
        :param target_group_name: the target group name
        :param snap_name: the snapshot name
        :param extra_specs: extra specifications
        :param list_volume_pairs: the list of volume pairs
        :param delete_snapshot: delete snapshot flag
        """
        LOG.debug("Linking Snap Vx snapshot: source group: %(srcGroup)s "
                  "targetGroup: %(tgtGroup)s.",
                  {'srcGroup': source_group_name,
                   'tgtGroup': target_group_name})
        # Link the snapshot
        self.rest.modify_volume_snap(
            array, None, None, snap_name, extra_specs, link=True,
            list_volume_pairs=list_volume_pairs)
        # Unlink the snapshot
        LOG.debug("Unlinking Snap Vx snapshot: source group: %(srcGroup)s "
                  "targetGroup: %(tgtGroup)s.",
                  {'srcGroup': source_group_name,
                   'tgtGroup': target_group_name})
        self._unlink_volume(array, None, None, snap_name, extra_specs,
                            list_volume_pairs=list_volume_pairs)
        # Delete the snapshot if necessary
        if delete_snapshot:
            LOG.debug("Deleting Snap Vx snapshot: source group: %(srcGroup)s "
                      "snapshot: %(snap_name)s.",
                      {'srcGroup': source_group_name,
                       'snap_name': snap_name})
            source_devices = [a for a, b in list_volume_pairs]
            self.delete_volume_snap(array, snap_name, source_devices)

    def enable_group_replication(self, array, storagegroup_name,
                                 rdf_group_num, extra_specs, establish=False):
        """Resume rdf replication on a storage group.

        Replication is enabled by default. This allows resuming
        replication on a suspended group.
        :param array: the array serial number
        :param storagegroup_name: the storagegroup name
        :param rdf_group_num: the rdf group number
        :param extra_specs: the extra specifications
        :param establish: flag to indicate 'establish' instead of 'resume'
        """
        action = "Establish" if establish is True else "Resume"
        self.rest.modify_storagegroup_rdf(
            array, storagegroup_name, rdf_group_num, action, extra_specs)

    def disable_group_replication(self, array, storagegroup_name,
                                  rdf_group_num, extra_specs):
        """Suspend rdf replication on a storage group.

        This does not delete the rdf pairs, that can only be done
        by deleting the group. This method suspends all i/o activity
        on the rdf links.
        :param array: the array serial number
        :param storagegroup_name: the storagegroup name
        :param rdf_group_num: the rdf group number
        :param extra_specs: the extra specifications
        """
        action = "Suspend"
        self.rest.modify_storagegroup_rdf(
            array, storagegroup_name, rdf_group_num, action, extra_specs)

    def failover_group(self, array, storagegroup_name,
                       rdf_group_num, extra_specs, failover=True):
        """Failover or failback replication on a storage group.

        :param array: the array serial number
        :param storagegroup_name: the storagegroup name
        :param rdf_group_num: the rdf group number
        :param extra_specs: the extra specifications
        :param failover: flag to indicate failover/ failback
        """
        action = "Failover" if failover else "Failback"
        self.rest.modify_storagegroup_rdf(
            array, storagegroup_name, rdf_group_num, action, extra_specs)

    def delete_group_replication(self, array, storagegroup_name,
                                 rdf_group_num, extra_specs):
        """Split replication for a group and delete the pairs.

        :param array: the array serial number
        :param storagegroup_name: the storage group name
        :param rdf_group_num: the rdf group number
        :param extra_specs: the extra specifications
        """
        group_details = self.rest.get_storage_group_rep(
            array, storagegroup_name)
        if (group_details and group_details.get('rdf')
                and group_details['rdf'] is True):
            action = "Split"
            LOG.debug("Splitting remote replication for group %(sg)s",
                      {'sg': storagegroup_name})
            self.rest.modify_storagegroup_rdf(
                array, storagegroup_name, rdf_group_num, action, extra_specs)
            LOG.debug("Deleting remote replication for group %(sg)s",
                      {'sg': storagegroup_name})
            self.rest.delete_storagegroup_rdf(
                array, storagegroup_name, rdf_group_num)

    def revert_volume_snapshot(self, array, source_device_id,
                               snap_name, extra_specs):
        """Revert a volume snapshot

        :param array: the array serial number
        :param source_device_id: device id of the source
        :param snap_name: snapvx snapshot name
        :param extra_specs: the extra specifications
        """
        start_time = time.time()
        self.rest.modify_volume_snap(
            array, source_device_id, "", snap_name, extra_specs, restore=True)
        LOG.debug("Restore volume snapshot took: %(delta)s H:MM:SS.",
                  {'delta': self.utils.get_time_delta(start_time,
                                                      time.time())})


text:
namespace Microsoft.Azure.Management.ContainerService.Models
{

    /// <summary>
    /// Defines values for OSSKU.
    /// </summary>
    public static class OSSKU
    {
        public const string Ubuntu = "Ubuntu";
        public const string CBLMariner = "CBLMariner";
    }
}

redpajama_set_name: RedPajamaGithub


text:
# YAML support for the Go language

[![PkgGoDev](https://pkg.go.dev/badge/github.com/goccy/go-yaml)](https://pkg.go.dev/github.com/goccy/go-yaml)
![Go](https://github.com/goccy/go-yaml/workflows/Go/badge.svg)
[![codecov](https://codecov.io/gh/goccy/go-yaml/branch/master/graph/badge.svg)](https://codecov.io/gh/goccy/go-yaml)
[![Go Report Card](https://goreportcard.com/badge/github.com/goccy/go-yaml)](https://goreportcard.com/report/github.com/goccy/go-yaml)

# Why a new library?

As of this writing, there already exists a de facto standard library for YAML processing for Go: [https://github.com/go-yaml/yaml](https://github.com/go-yaml/yaml). However we feel that some features are lacking, namely:

- Pretty format for error notifications
- Direct manipulation of YAML abstract syntax tree
- Support for `Anchor` and `Alias` when marshaling
- Allow referencing elements declared in another file via anchors

# Features

- Pretty format for error notifications
- Supports `Scanner` or `Lexer` or `Parser` as public API
- Supports `Anchor` and `Alias` to Marshaler
- Allow referencing elements declared in another file via anchors
- Extract value or AST by YAMLPath ( YAMLPath is like a JSONPath )

# Installation

```sh
go get -u github.com/goccy/go-yaml
```

# Synopsis

## 1. Simple Encode/Decode

Has an interface like `go-yaml/yaml` using `reflect`

```go
var v struct {
	A int
	B string
}
v.A = 1
v.B = "hello"
bytes, err := yaml.Marshal(v)
if err != nil {
	//...
}
fmt.Println(string(bytes)) // "a: 1\nb: hello\n"
```

```go
	yml := `
%YAML 1.2
---
a: 1
b: c
`
var v struct {
	A int
	B string
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
	//...
}
```

To control marshal/unmarshal behavior, you can use the `yaml` tag.

```go
	yml := `---
foo: 1
bar: c
`
var v struct {
	A int    `yaml:"foo"`
	B string `yaml:"bar"`
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
	//...
}
```

For convenience, we also accept the `json` tag. Note that not all options from
the `json` tag will have significance when parsing YAML documents. If both
tags exist, `yaml` tag will take precedence.

```go
	yml := `---
foo: 1
bar: c
`
var v struct {
	A int    `json:"foo"`
	B string `json:"bar"`
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
	//...
}
```

For custom marshal/unmarshaling, implement either `Bytes` or `Interface` variant of marshaler/unmarshaler. The difference is that while `BytesMarshaler`/`BytesUnmarshaler` behaves like [`encoding/json`](https://pkg.go.dev/encoding/json) and `InterfaceMarshaler`/`InterfaceUnmarshaler` behaves like [`gopkg.in/yaml.v2`](https://pkg.go.dev/gopkg.in/yaml.v2).

Semantically both are the same, but they differ in performance. Because indentation matters in YAML, you cannot simply accept a valid YAML fragment from a Marshaler, and expect it to work when it is attached to the parent container's serialized form. Therefore when we receive use the `BytesMarshaler`, which returns `[]byte`, we must decode it once to figure out how to make it work in the given context. If you use the `InterfaceMarshaler`, we can skip the decoding.

If you are repeatedly marshaling complex objects, the latter is always better
performance wise. But if you are, for example, just providing a choice between
a config file format that is read only once, the former is probably easier to
code.

## 2. Reference elements declared in another file

`testdata` directory contains `anchor.yml` file:

```shell
├── testdata
   └── anchor.yml
```

And `anchor.yml` is defined as follows:

```yaml
a: &a
  b: 1
  c: hello
```

Then, if `yaml.ReferenceDirs("testdata")` option is passed to `yaml.Decoder`,
 `Decoder` tries to find the anchor definition from YAML files the under `testdata` directory.

```go
buf := bytes.NewBufferString("a: *a\n")
dec := yaml.NewDecoder(buf, yaml.ReferenceDirs("testdata"))
var v struct {
	A struct {
		B int
		C string
	}
}
if err := dec.Decode(&v); err != nil {
	//...
}
fmt.Printf("%+v\n", v) // {A:{B:1 C:hello}}
```

## 3. Encode with `Anchor` and `Alias`

### 3.1. Explicitly declared `Anchor` name and `Alias` name

If you want to use `anchor` or `alias`, you can define it as a struct tag.

```go
type T struct {
  A int
  B string
}
var v struct {
  C *T `yaml:"c,anchor=x"`
  D *T `yaml:"d,alias=x"`
}
v.C = &T{A: 1, B: "hello"}
v.D = v.C
bytes, err := yaml.Marshal(v)
if err != nil {
  panic(err)
}
fmt.Println(string(bytes))
/*
c: &x
  a: 1
  b: hello
d: *x
*/
```

### 3.2. Implicitly declared `Anchor` and `Alias` names

If you do not explicitly declare the anchor name, the default behavior is to
use the equivalent of `strings.ToLower($FieldName)` as the name of the anchor.

If you do not explicitly declare the alias name AND the value is a pointer
to another element, we look up the anchor name by finding out which anchor
field the value is assigned to by looking up its pointer address.

```go
type T struct {
	I int
	S string
}
var v struct {
	A *T `yaml:"a,anchor"`
	B *T `yaml:"b,anchor"`
	C *T `yaml:"c,alias"`
	D *T `yaml:"d,alias"`
}
v.A = &T{I: 1, S: "hello"}
v.B = &T{I: 2, S: "world"}
v.C = v.A // C has same pointer address to A
v.D = v.B // D has same pointer address to B
bytes, err := yaml.Marshal(v)
if err != nil {
	//...
}
fmt.Println(string(bytes))
/*
a: &a
  i: 1
  s: hello
b: &b
  i: 2
  s: world
c: *a
d: *b
*/
```

### 3.3 MergeKey and Alias

Merge key and alias ( `<<: *alias` ) can be used by embedding a structure with the `inline,alias` tag.

```go
type Person struct {
	*Person `yaml:",omitempty,inline,alias"` // embed Person type for default value
	Name    string `yaml:",omitempty"`
	Age     int    `yaml:",omitempty"`
}
defaultPerson := &Person{
	Name: "John Smith",
	Age:  20,
}
people := []*Person{
	{
		Person: defaultPerson, // assign default value
		Name:   "Ken",         // override Name property
		Age:    10,            // override Age property
	},
	{
		Person: defaultPerson, // assign default value only
	},
}
var doc struct {
	Default *Person   `yaml:"default,anchor"`
	People  []*Person `yaml:"people"`
}
doc.Default = defaultPerson
doc.People = people
bytes, err := yaml.Marshal(doc)
if err != nil {
	//...
}
fmt.Println(string(bytes))
/*
default: &default
  name: John Smith
  age: 20
people:
- <<: *default
  name: Ken
  age: 10
- <<: *default
*/
```

## 4. Pretty Formatted Errors

Error values produced during parsing have two extra features over regular
error values.

First, by default, they contain extra information on the location of the error
from the source YAML document, to make it easier to find the error location.

Second, the error messages can optionally be colorized.

If you would like to control exactly how the output looks like, consider
using  `yaml.FormatError`, which accepts two boolean values to
control turning these features on or off.

## 5. Use YAMLPath

```go
yml := `
store:
  book:
    - author: john
      price: 10
    - author: ken
      price: 12
  bicycle:
    color: red
    price: 19.95
`
path, err := yaml.PathString("$.store.book[*].author")
if err != nil {
  //...
}
var authors []string
if err := path.Read(strings.NewReader(yml), &authors); err != nil {
  //...
}
fmt.Println(authors)
// [john ken]
```

### 5.1 Print customized error with YAML source code

```go
package main

import (
  "fmt"

  "github.com/goccy/go-yaml"
)

func main() {
  yml := `
a: 1
b: "hello"
`
  var v struct {
    A int
    B string
  }
  if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
    panic(err)
  }
  if v.A != 2 {
    // output error with YAML source
    path, err := yaml.PathString("$.a")
    if err != nil {
      panic(err)
    }
    source, err := path.AnnotateSource([]byte(yml), true)
    if err != nil {
      panic(err)
    }
    fmt.Printf("a value expected 2 but actual %d:\n%s\n", v.A, string(source))
  }
}
```

output result is the following:

# Tools

## ycat

print yaml file with color

### Installation

```sh
go install github.com/goccy/go-yaml/cmd/ycat@latest
```

# Looking for Sponsors

I'm looking for sponsors this library. This library is being developed as a personal project in my spare time. If you want a quick response or problem resolution when using this library in your project, please register as a [sponsor](https://github.com/sponsors/goccy). I will cooperate as much as possible. Of course, this library is developed as an MIT license, so you can use it freely for free.

# License

MIT


text:
using AutomaticTypeMapper;

namespace EOLib.Net.Communication
{
    public interface INetworkClientRepository
    {
        INetworkClient NetworkClient { get; set; }
    }

    public interface INetworkClientProvider
    {
        INetworkClient NetworkClient { get; }
    }

    [AutoMappedType(IsSingleton = true)]
    public sealed class NetworkClientRepository : INetworkClientProvider, INetworkClientRepository, INetworkClientDisposer
    {
        public INetworkClient NetworkClient { get; set; }

        public void Dispose()
        {
            if (NetworkClient != null)
                NetworkClient.Dispose();
        }
    }
}


text:
package org.apache.camel.component.activemq;

import javax.jms.Connection;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.test.spring.junit5.CamelSpringTestSupport;
import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.AbstractApplicationContext;

import static org.junit.jupiter.api.Assertions.assertFalse;

public class PoisonJMSPayloadTest extends CamelSpringTestSupport {

    @Test
    public void testCreateBodyThrowException() throws Exception {
        getMockEndpoint("mock:result-activemq").expectedMessageCount(0);
        getMockEndpoint("mock:dead").expectedMessageCount(1);
        getMockEndpoint("mock:dead").message(0).body(String.class)
                .startsWith(
                        "Poison JMS message payload: Failed to extract body due to: javax.jms.JMSException: Failed to build body from content. Serializable class not available to broker.");

        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
        Connection conn = factory.createConnection();
        conn.start();
        Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = sess.createProducer(sess.createTopic("foo"));
        ObjectMessage msg = sess.createObjectMessage();
        ObjectPayload payload = new ObjectPayload();
        payload.payload = "test";
        msg.setObject(payload);
        producer.send(msg);

        Thread.sleep(1000);

        // bean should not be invoked
        boolean invoked = context.getRegistry().lookupByNameAndType("myBean", MyBean.class).isInvoked();
        assertFalse(invoked, "Bean should not be invoked");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected AbstractApplicationContext createApplicationContext() {
        AbstractApplicationContext context
                = new ClassPathXmlApplicationContext("org/apache/camel/component/activemq/jms-createbody.xml");
        return context;
    }
}


text: $(document).ready(function(){globalCharacterInit()});


text:
package com.design.builder;

/**
 * Created by IntelliJ IDEA.
 * User: Sai Anudeep Machavarapu
 * Date: 6/22/14
 * Time: 2:33 AM
 */

/** The director / engineer class creates a Robot using the
 * builder interface that is defined (OldRobotBuilder)
 **/
 public class RobotEngineer {
    private IRobotBuilder robotBuilder;

    // OldRobotBuilder specification is sent to the engineer
    public RobotEngineer(IRobotBuilder robotBuilder) {
        this.robotBuilder = robotBuilder;
    }

    public void makeRobot(){
        this.robotBuilder.buildRobotHead();
        this.robotBuilder.buildRobotArms();
        this.robotBuilder.buildRobotTorso();
        this.robotBuilder.buildRobotLegs();
    }

    public Robot getRobot(){
        return this.robotBuilder.getRobot();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LongPolling
{
    public class TaskResultContextFactory : IResultContextFactory
    {
        public IResultContext<T> CreateContext<T>()
        {
            return new TaskResultContext<T>();
        }

        public void Dispose()
        {

        }
    }
}


text:
package desmoj.extensions.visualization2d.engine.viewer;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

import desmoj.extensions.visualization2d.engine.model.Model;

public class AboutModelDialog extends HelpDialogTemplate{

	private Model 	model 				= null;

	public AboutModelDialog(ViewerPanel viewer) {
		super(viewer);
		model	= this.getViewer().getModel();
	}

	protected void buildDialog() throws MalformedURLException{
		if(model.isValid()){
			String projectName = this.getViewer().getModel().getModelProjectName();
			if(projectName == null) projectName = "Simulation Project";
			String text = this.getLanguage().getString("Help_about")+" "+projectName;
			JDialog dialog	= new JDialog((JFrame)null, text, true);
			dialog.setBounds(100, 100, 600, 400);
			dialog.getContentPane().setLayout(new BorderLayout());
			dialog.getContentPane().add(this.getHeaderBox(), BorderLayout.NORTH);
			JScrollPane scrollpane = new JScrollPane(this.getProjectBox(dialog));
			scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
			scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
			dialog.getContentPane().add(scrollpane, BorderLayout.CENTER);
			dialog.setResizable(false);
			dialog.setVisible(true);
		}
	}

	private Box getHeaderBox() throws MalformedURLException{
		String projectName 		 = this.getViewer().getModel().getModelProjectName();

	    JLabel projectIconLabel = new JLabel(this.getProjectTitleIcon());
		JLabel title 	= new JLabel(projectName);
		title.setFont(ViewerPanel.FONT_BIG);
		title.setAlignmentX(Component.CENTER_ALIGNMENT);

		Box outBox = Box.createHorizontalBox();
		outBox.add(Box.createHorizontalGlue());
		outBox.add(title);
		outBox.add(Box.createHorizontalGlue());
		outBox.add(projectIconLabel);
		outBox.setBackground(ViewerPanel.HEADER_BG_COLOR);
		outBox.setOpaque(true);
		return outBox;
	}

	private Box getProjectBox(JDialog dialog) throws MalformedURLException{
		String projectURLString = this.getViewer().getModel().getModelProjectURL();
		URL	projectURL 			= null;
		try{
			if(projectURLString != null) projectURL = new URL(projectURLString);
		}catch(MalformedURLException e){ projectURL = null;}

		String content	= "";
		content += "";
		content += "
";
		content += "
"+this.getLanguage().getString("Help_Project")+
			" 	"+this.getViewer().getModel().getModelProjectName()+"
";
		content += "
"+this.getLanguage().getString("Help_Model")+
			" 	"+this.getViewer().getModel().getModelName()+"
";
		content += "
"+this.getLanguage().getString("Help_Author")+
			" 	"+this.getViewer().getModel().getModelAuthor()+"
";
		content += "
"+this.getLanguage().getString("Help_CreatedAt")+
			" 	"+this.getViewer().getModel().getModelCreatedAt()+"
";
		content += "
"+this.getLanguage().getString("Help_Description")+
			" 	"+this.getViewer().getModel().getModelDescription()+"
";
		content += "
"+this.getLanguage().getString("Help_Remarks")+
			" 	"+this.getViewer().getModel().getModelRemark()+"
";
		content += "
"+this.getLanguage().getString("Help_LicenseModel")+
			" 	"+this.getViewer().getModel().getModelLicence()+"
";
		content += "
"+this.getLanguage().getString("Help_SimulationFramework")+
			" 	"+this.getLanguage().getString("Help_Version")+" "+
			this.getViewer().getDesmoJ_Info().getDesmoJ_Version()+
			"  "+
			"
";
		content += "
"+this.getLanguage().getString("Help_Visualization2dEngine")+
		" 	"+this.getLanguage().getString("Help_Version")+" "+
		this.getLanguage().getString("VISUALIZATION_VERSION")+
		"  "+
		"
";
		content += "
";

		Box contentBox = Box.createHorizontalBox();
		JLabel contentLabel = new JLabel(content);
		contentLabel.setFont(ViewerPanel.FONT_MIDDLE);
		contentBox.add(contentLabel);
		contentBox.add(Box.createHorizontalGlue());

		Box buttonBox = Box.createHorizontalBox();
		buttonBox.add(Box.createHorizontalGlue());
		if(projectURL != null){
			JButton projectButton = new JButton("more Information");
			projectButton.addActionListener(new Click(projectURL, this.getAppletContext()));
			projectButton.setFont(ViewerPanel.FONT_MIDDLE);
			buttonBox.add(projectButton);
		}

		Box outBox = Box.createVerticalBox();
		outBox.add(contentBox);
		outBox.add(buttonBox);
		return outBox;
	}

	private ImageIcon scale(Image src, int height){
		int w 				= src.getWidth(this.getViewer());
		int h 				= src.getHeight(this.getViewer());
		double scale		= (double)height/(double)h;
		int width			= (int)Math.round(scale * w);
		int type 			= BufferedImage.BITMASK;
		BufferedImage dst 	= new BufferedImage(width, height, type);
		Graphics2D g2 		= dst.createGraphics();
		g2.drawImage(src, 0, 0, width, height, this.getViewer());
		g2.dispose();
		return new ImageIcon(dst);
	}

	private ImageIcon getProjectIcon(int height){
		ImageIcon out = null;
		Model model 			= this.getViewer().getModel();
		String projectIconId 	= model.getModelProjectIconId();
		if(projectIconId != null){
			try{
				Image image 	= model.getImage(projectIconId);
				out = this.scale(image, height);
				//out = new ImageIcon(image);
			}catch(Exception e){
				out = null;
			}
		}
		return out;
	}

	protected ImageIcon getProjectTitleIcon(){
		return this.getProjectIcon(60);
	}

	protected ImageIcon getProjectMenueIcon(){
		// bestimme Referenzhoehe fuer Icon
		int h = new ImageIcon(this.getInternURL("th_wildau_menue_icon")).getIconHeight();
		return this.getProjectIcon(h);
	}

}


text:
package com.alexrnl.subtitlecorrector.io;

import java.nio.file.Path;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.alexrnl.commons.io.IOUtils;
import com.alexrnl.commons.utils.StringUtils;
import com.alexrnl.subtitlecorrector.common.SubtitleFile;

/**
 * Manager to ease the use of the {@link SubtitleFile} reading / writing.

 * @author Alex
 */
public class SubtitleFormatManager {
	/** Logger */
	private static final Logger			LG	= Logger.getLogger(SubtitleFormatManager.class.getName());

	/** The registered format of subtitles */
	private final Set<SubtitleFormat>	formats;

	/**
	 * Constructor #1.

	 * Default constructor.
	 */
	public SubtitleFormatManager () {
		super();
		formats = new HashSet<>();
	}

	/**
	 * Register a new {@link SubtitleFormat}.
	 * @param format
	 *        the format to add.
	 * @return true if a previous same format existed (and is thus override).
	 */
	public boolean registerFormat (final SubtitleFormat format) {
		Objects.requireNonNull(format);
		final boolean removed = formats.remove(format);
		formats.add(format);
		return removed;
	}

	/**
	 * Return the available {@link SubtitleFormat}.

	 * The set returned is not modifiable to avoid side effects.
	 * @return the subtitle format available.
	 */
	public Set<SubtitleFormat> getAvailableFormats () {
		return Collections.unmodifiableSet(formats);
	}

	/**
	 * Find a subtitle format by its name.
	 * @param name
	 *        the name of the format to find.
	 * @return the matching format or null if no matching format were found.
	 */
	public SubtitleFormat getFormatByName (final String name) {
		if (StringUtils.nullOrEmpty(name)) {
			throw new IllegalArgumentException("Cannot search for null or empty name");
		}

		for (final SubtitleFormat format : formats) {
			if (format.getName().equals(name)) {
				return format;
			}
		}

		if (LG.isLoggable(Level.INFO)) {
			LG.info("No matching format found for name " + name);
		}
		return null;
	}

	/**
	 * Find the {@link SubtitleFormat} which support the specified extension.
	 * @param extension
	 *        the extension of the file.
	 * @return the format which support the following extension.
	 */
	public Set<SubtitleFormat> getFormatByExtension (final String extension) {
		if (StringUtils.nullOrEmpty(extension)) {
			throw new IllegalArgumentException("Cannot search for null or empty extension");
		}

		final Set<SubtitleFormat> candidates = new HashSet<>();
		for (final SubtitleFormat format : formats) {
			if (format.getExtensions().contains(extension)) {
				candidates.add(format);
			}
		}

		if (LG.isLoggable(Level.INFO)) {
			LG.info("Subtitle format matching extension " + extension + " are: " + candidates);
		}
		return candidates;
	}

	/**
	 * Find the {@link SubtitleFormat} which support the following {@link Path} according to its
	 * extension.
	 * @param path
	 *        the path of the file.
	 * @return the format(s) which support the following path.
	 */
	public Set<SubtitleFormat> getFormatByPath (final Path path) {
		return getFormatByExtension(IOUtils.getFileExtension(path));
	}
}


text:
package com.facebook.cache.disk;

import java.io.IOException;

import com.facebook.cache.common.CacheEventListener;
import com.facebook.cache.common.CacheKey;

import org.junit.Test;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

public class SettableCacheEventTest {

  @Test
  public void testRecycleClearsAllFields() {
    SettableCacheEvent event = SettableCacheEvent.obtain();
    event.setCacheKey(mock(CacheKey.class));
    event.setCacheLimit(21L);
    event.setCacheSize(12332445L);
    event.setEvictionReason(CacheEventListener.EvictionReason.CACHE_MANAGER_TRIMMED);
    event.setException(mock(IOException.class));
    event.setItemSize(1435L);
    event.setResourceId("sddqrtyjf");

    event.recycle();

    assertThat(event.getCacheKey()).isNull();
    assertThat(event.getCacheLimit()).isZero();
    assertThat(event.getCacheSize()).isZero();
    assertThat(event.getEvictionReason()).isNull();
    assertThat(event.getException()).isNull();
    assertThat(event.getItemSize()).isZero();
    assertThat(event.getResourceId()).isNull();
  }

  @Test
  public void testSecondObtainGetsNewEventIfNoRecycling() {
    SettableCacheEvent firstEvent = SettableCacheEvent.obtain();
    SettableCacheEvent secondEvent = SettableCacheEvent.obtain();

    assertThat(secondEvent).isNotSameAs(firstEvent);
  }

  @Test
  public void testSecondObtainAfterRecyclingGetsRecycledEvent() {
    SettableCacheEvent firstEvent = SettableCacheEvent.obtain();
    firstEvent.recycle();
    SettableCacheEvent secondEvent = SettableCacheEvent.obtain();

    assertThat(secondEvent).isSameAs(firstEvent);
  }
}


text:
package com.vzaar;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.vzaar.client.ResourcePath;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;

@ResourcePath(path = "feeds/playlists")
public class Playlist implements Identifiable {
    private int id;
    private int categoryId;
    private String title;
    private String sortBy;
    private SortDirection sortOrder;
    @JsonProperty(value = "private")
    private boolean isPrivate;
    private String dimensions;
    private int maxVids;
    private ControlsPosition position;
    private boolean autoplay;
    private boolean continuousPlay;
    private String embedCode;
    private List<Video> videos = new ArrayList<>();
    private ZonedDateTime createdAt;
    private ZonedDateTime updatedAt;

    public int getId() {
        return id;
    }

    public int getCategoryId() {
        return categoryId;
    }

    public String getTitle() {
        return title;
    }

    public String getSortBy() {
        return sortBy;
    }

    public SortDirection getSortOrder() {
        return sortOrder;
    }

    public boolean isPrivate() {
        return isPrivate;
    }

    public String getDimensions() {
        return dimensions;
    }

    public int getMaxVids() {
        return maxVids;
    }

    public ControlsPosition getPosition() {
        return position;
    }

    public boolean isAutoplay() {
        return autoplay;
    }

    public boolean isContinuousPlay() {
        return continuousPlay;
    }

    public String getEmbedCode() {
        return embedCode;
    }

    public List<Video> getVideos() {
        return videos;
    }

    public ZonedDateTime getCreatedAt() {
        return createdAt;
    }

    public ZonedDateTime getUpdatedAt() {
        return updatedAt;
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}

module Main where

import qualified Runtime.Run as Runtime (main)

main :: IO ()
main = Runtime.main


text:
module RuboCop
  module Cop
    module Layout
      # Checks that brackets used for array literals have or don't have
      # surrounding space depending on configuration.
      #
      # @example EnforcedStyle: space
      #   # The `space` style enforces that array literals have
      #   # surrounding space.
      #
      #   # bad
      #   array = [a, b, c, d]
      #
      #   # good
      #   array = [ a, b, c, d ]
      #
      # @example EnforcedStyle: no_space (default)
      #   # The `no_space` style enforces that array literals have
      #   # no surrounding space.
      #
      #   # bad
      #   array = [ a, b, c, d ]
      #
      #   # good
      #   array = [a, b, c, d]
      #
      # @example EnforcedStyle: compact
      #   # The `compact` style normally requires a space inside
      #   # array brackets, with the exception that successive left
      #   # or right brackets are collapsed together in nested arrays.
      #
      #   # bad
      #   array = [ a, [ b, c ] ]
      #   array = [
      #     [ a ],
      #     [ b, c ]
      #   ]
      #
      #   # good
      #   array = [ a, [ b, c ]]
      #   array = [[ a ],
      #     [ b, c ]]
      #
      # @example EnforcedStyleForEmptyBrackets: no_space (default)
      #   # The `no_space` EnforcedStyleForEmptyBrackets style enforces that
      #   # empty array brackets do not contain spaces.
      #
      #   # bad
      #   foo = [ ]
      #   bar = [     ]
      #
      #   # good
      #   foo = []
      #   bar = []
      #
      # @example EnforcedStyleForEmptyBrackets: space
      #   # The `space` EnforcedStyleForEmptyBrackets style enforces that
      #   # empty array brackets contain exactly one space.
      #
      #   # bad
      #   foo = []
      #   bar = [    ]
      #
      #   # good
      #   foo = [ ]
      #   bar = [ ]
      #
      class SpaceInsideArrayLiteralBrackets < Cop
        include SurroundingSpace
        include ConfigurableEnforcedStyle

        MSG = '%<command>s space inside array brackets.'
        EMPTY_MSG = '%<command>s space inside empty array brackets.'

        def on_array(node)
          return unless node.square_brackets?

          left, right = array_brackets(node)
          if empty_brackets?(left, right)
            return empty_offenses(node, left, right, EMPTY_MSG)
          end

          start_ok = next_to_newline?(node, left)
          end_ok = node.single_line? ? false : end_has_own_line?(right)

          issue_offenses(node, left, right, start_ok, end_ok)
        end

        def autocorrect(node)
          left, right = array_brackets(node)

          lambda do |corrector|
            if empty_brackets?(left, right)
              SpaceCorrector.empty_corrections(processed_source, corrector,
                                               empty_config, left, right)
            elsif style == :no_space
              SpaceCorrector.remove_space(processed_source, corrector,
                                          left, right)
            elsif style == :space
              SpaceCorrector.add_space(processed_source, corrector, left, right)
            else
              compact_corrections(corrector, node, left, right)
            end
          end
        end

        private

        def array_brackets(node)
          [left_array_bracket(node), right_array_bracket(node)]
        end

        def left_array_bracket(node)
          tokens(node).find(&:left_array_bracket?)
        end

        def right_array_bracket(node)
          tokens(node).reverse.find(&:right_bracket?)
        end

        def empty_config
          cop_config['EnforcedStyleForEmptyBrackets']
        end

        def next_to_newline?(node, token)
          tokens(node)[index_for(node, token) + 1].line != token.line
        end

        def end_has_own_line?(token)
          line, col = line_and_column_for(token)
          return true if col == -1

          processed_source.lines[line][0..col] !~ /\S/
        end

        def index_for(node, token)
          tokens(node).index(token)
        end

        def line_and_column_for(token)
          [token.line - 1, token.column - 1]
        end

        def issue_offenses(node, left, right, start_ok, end_ok)
          if style == :no_space
            start_ok = next_to_comment?(node, left)
            no_space_offenses(node, left, right, MSG, start_ok: start_ok,
                                                      end_ok: end_ok)
          elsif style == :space
            space_offenses(node, left, right, MSG, start_ok: start_ok,
                                                   end_ok: end_ok)
          else
            compact_offenses(node, left, right, start_ok, end_ok)
          end
        end

        def next_to_comment?(node, token)
          tokens(node)[index_for(node, token) + 1].comment?
        end

        def compact_offenses(node, left, right, start_ok, end_ok)
          if qualifies_for_compact?(node, left, side: :left)
            compact_offense(node, left, side: :left)
          elsif !multi_dimensional_array?(node, left, side: :left)
            space_offenses(node, left, nil, MSG, start_ok: start_ok,
                                                 end_ok: true)
          end
          if qualifies_for_compact?(node, right)
            compact_offense(node, right)
          elsif !multi_dimensional_array?(node, right)
            space_offenses(node, nil, right, MSG, start_ok: true,
                                                  end_ok: end_ok)
          end
        end

        def qualifies_for_compact?(node, token, side: :right)
          if side == :right
            multi_dimensional_array?(node, token) &&
              !next_to_bracket?(token)
          else
            multi_dimensional_array?(node, token, side: :left) &&
              !next_to_bracket?(token, side: :left)
          end
        end

        def multi_dimensional_array?(node, token, side: :right)
          i = index_for(node, token)
          if side == :right
            tokens(node)[i - 1].right_bracket?
          else
            tokens(node)[i + 1].left_array_bracket?
          end
        end

        def next_to_bracket?(token, side: :right)
          line_index, col = line_and_column_for(token)
          line = processed_source.lines[line_index]
          side == :right ? line[col] == ']' : line[col + 2] == '['
        end

        def compact_offense(node, token, side: :right)
          if side == :right
            space_offense(node, token, :left, MSG, NO_SPACE_COMMAND)
          else
            space_offense(node, token, :right, MSG, NO_SPACE_COMMAND)
          end
        end

        def compact_corrections(corrector, node, left, right)
          if qualifies_for_compact?(node, left, side: :left)
            compact(corrector, left, :right)
          elsif !left.space_after?
            corrector.insert_after(left.pos, ' ')
          end
          if qualifies_for_compact?(node, right)
            compact(corrector, right, :left)
          elsif !right.space_before?
            corrector.insert_before(right.pos, ' ')
          end
        end

        def compact(corrector, bracket, side)
          range = side_space_range(range: bracket.pos, side: side)
          corrector.remove(range)
        end
      end
    end
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Agrartud. Egyet. Kert- Szologazdasagtud. Karanak Evk. 14:36. 1950

#### Original name
null

### Remarks
null


text:
import { addText } from 'src/application-state/actions'
import Form from 'src/ui/modules/TextFormModule'
import { reduxForm } from 'redux-form'
import store from 'src/application-state/index'
import { Promise } from 'es6-promise';

const fields = [ 'text' ];

export default reduxForm({
    form: 'textForm',
    fields,
    onSubmit: (values) => {
        return new Promise((resolve, reject) => {
            store.dispatch(addText(values, resolve, reject));
        });
    }
})(Form)


text:
package org.apache.sling.hc.samples.impl;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyUnbounded;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.hc.api.HealthCheck;
import org.apache.sling.hc.api.Result;
import org.apache.sling.hc.util.FormattingResultLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Sample that demonstrates how to implement asynchronous health checks
 *  that run in the background at regular intervals.
 *  The execute() method stays fast as it just reads a pre-computed value.
 */
@Component(
        configurationFactory=true,
        policy=ConfigurationPolicy.REQUIRE,
        metatype=true)
@Properties({
    @Property(name=HealthCheck.NAME),
    @Property(name=HealthCheck.TAGS, unbounded=PropertyUnbounded.ARRAY),
    @Property(name=HealthCheck.MBEAN_NAME),

    // Period *must* be a Long
    @Property(name="scheduler.period", longValue=AsyncHealthCheckSample.PERIOD_SECONDS, propertyPrivate=true),
    // Concurrent=false avoids reentrant calls to run()
    @Property(name="scheduler.concurrent", boolValue=false)
})
@Service(value={HealthCheck.class,Runnable.class})
public class AsyncHealthCheckSample implements HealthCheck, Runnable {

    private final Logger log = LoggerFactory.getLogger(getClass());
    private final AtomicInteger counter = new AtomicInteger();

    public static final int PERIOD_SECONDS = 5;

    @Override
    public Result execute() {
        final FormattingResultLog resultLog = new FormattingResultLog();
        final int value = counter.get();
        resultLog.debug("{} - counter value is {}", this, value);
        if(value % 2 != 0) {
            resultLog.warn("Counter value ({}) is not even", value);
        }
        return new Result(resultLog);
    }

    /** Called by the Sling scheduler, every {@link #SCHEDULER_PERIOD} seconds, without
     *  reentrant calls, as configured by our scheduler.* service properties.
     *
     *  Simulates an expensive operation by waiting a random time up to twice that period
     *  before incrementing our counter.
     */
    @Override
    public void run() {
        final long toWait = (long)(Math.random() * 2 * PERIOD_SECONDS);
        log.info("{} - Waiting {} seconds to simulate an expensive operation...", this, toWait);
        try {
            Thread.sleep(toWait * 1000L);
        } catch(InterruptedException iex) {
            log.warn("Sleep interrupted", iex);
        }
        counter.incrementAndGet();
        log.info("{} - counter set to {}", this, counter.get());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="0dp"
              android:layout_height="30dp"
              android:orientation="horizontal"

              android:weightSum="20" >

    <TextView
        android:id="@+id/train_trainNo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="8dp"
        android:text="G122"
        android:textSize="8sp" />
    <!-- 出发站和到达站 -->

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:gravity="left"
        android:orientation="vertical"
        android:padding="5dp" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:background="@mipmap/train9"
                android:id="@+id/train_startPicture"
                />

            <TextView
                android:id="@+id/train_startStation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:gravity="center"
                android:singleLine="true"
                android:text="出发站"
                android:textSize="8sp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:background="@mipmap/train10"
                android:id="@+id/train_endPicture"
                />

            <TextView
                android:id="@+id/train_endStation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:gravity="center"
                android:singleLine="true"
                android:text="出发站"
                android:textSize="8sp" />
        </LinearLayout>
        <!--
             <TextView
	        android:id="@+id/train_endStation"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:gravity="center"
	        android:text="到达站"
	        android:textSize="20sp"
	        android:drawableLeft="@drawable/train10"
	        />
        -->
    </LinearLayout>
    <!--
         <TextView
        android:id="@+id/train_station"
        android:layout_width="0dp"
        android:layout_height="wrap_content"

        android:layout_marginTop="10dp"
        android:layout_weight="2"
        android:gravity="center"
        android:padding="5dp"
        android:text="出发站\n到达站"
        android:textSize="20sp"

         />
    -->

    <TextView
        android:id="@+id/train_time"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:gravity="center"
        android:padding="5dp"
        android:text="出发时间\n到达时间"
        android:textSize="8sp" />

    <TextView
        android:id="@+id/train_time1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="2"
        android:gravity="center"
        android:padding="5dp"
        android:text="历时"
        android:textSize="8sp" />
    <!-- 商务座 -->

    <TextView
        android:id="@+id/train_shangwuzuo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 特等座 -->

    <TextView
        android:id="@+id/train_tedengseat"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 一等座 -->

    <TextView
        android:id="@+id/train_yidengseat"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 二等座 -->

    <TextView
        android:id="@+id/train_erdengseat"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 高级软卧 -->

    <TextView
        android:id="@+id/gaojiruanwo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 软卧 -->

    <TextView
        android:id="@+id/train_ruanwo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 硬卧 -->

    <TextView
        android:id="@+id/train_yingwo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 软座 -->

    <TextView
        android:id="@+id/train_ruanzuo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 硬座 -->

    <TextView
        android:id="@+id/train_yingzuo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 无座 -->

    <TextView
        android:id="@+id/wuzuo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />
    <!-- 其他 -->

    <TextView
        android:id="@+id/train_else"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:gravity="center"
        android:padding="5dp"
        android:text="--"
        android:textSize="8sp" />

    <Button
        android:id="@+id/train_yuding"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp"
        android:layout_weight="2"
        android:background="@drawable/btn_bg"
        android:gravity="center"
        android:padding="5dp"
        android:text="预定"
        android:textColor="#ffffff"
        android:textSize="8sp" />

</LinearLayout>


text:
package br.com.agneresteves.ef.core.transformer;

/**
 * ParseCallback
 * I
 *
 * @author Agner Esteves Ballejo
 * @since 17/11/2017
 */
public interface ParseCallback {

    void onSuccess(ParsedTransformer parsedTransformer);
    void onFail(String message);

}


text:
set -e

source ${3}tensorflow/lite/micro/tools/make/bash_helpers.sh

DOWNLOADS_DIR=${1}
GENERATED_SRCS_DIR=${2}

if [ ! -d ${DOWNLOADS_DIR} ]; then
  echo "The top-level downloads directory: ${DOWNLOADS_DIR} does not exist."
  exit 1
fi

# Optimize downloaded model with Vela for Ethos-U.
# See tensorflow/lite/micro/kernels/ethos_u/README.md for more info.
MODEL_DIR=${GENERATED_SRCS_DIR}tensorflow/lite/micro/models
CONVERTED_PERSON_MODEL_INT8=${MODEL_DIR}/person_detect_model_data_vela.cc

if [ ! -f ${CONVERTED_PERSON_MODEL_INT8} ]; then
  # Compile an optimized .tflite version for Ethos-U.
  TEMPFILE=$(mktemp -d)/
  python3 -m venv $TEMPFILE
  source $TEMPFILE/bin/activate
  python3 -m pip install --upgrade pip >&2
  pip install --upgrade cython >&2
  pip install --prefer-binary ethos-u-vela >&2
  vela --accelerator-config=ethos-u55-256 ${DOWNLOADS_DIR}/../../../models/person_detect.tflite \
       --output-dir ${MODEL_DIR} >&2
  deactivate

  # Convert .tflite back to C array.
  echo "// This file is generated by $0." > ${CONVERTED_PERSON_MODEL_INT8}
  echo '#include "tensorflow/lite/micro/models/person_detect_model_data.h"' >> \
       ${CONVERTED_PERSON_MODEL_INT8}
  echo -n "const " >> ${CONVERTED_PERSON_MODEL_INT8}
  xxd -i ${MODEL_DIR}/person_detect_vela.tflite >> ${CONVERTED_PERSON_MODEL_INT8}
  sed -i 's/gen_cortex_m_corstone_300_cortex_m55_default_genfiles_tensorflow_lite_micro_models_person_detect_vela_tflite/g_person_detect_model_data/' \
      ${CONVERTED_PERSON_MODEL_INT8}
  sed -i 's/^const unsigned char g_person_detect_model_data/alignas\(16\) &/'  ${CONVERTED_PERSON_MODEL_INT8}
  sed -i 's/g_person_detect_model_data_len/g_person_detect_model_data_size/'  ${CONVERTED_PERSON_MODEL_INT8}
  sed -i 's/unsigned int/const unsigned int/' ${CONVERTED_PERSON_MODEL_INT8}
fi

echo "SUCCESS"


text:
package stiface

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"
	"os"
	"testing"

	"cloud.google.com/go/storage"
)

func TestIntegration(t *testing.T) {
	if testing.Short() {
		t.Skip("integration tests skipped in short mode")
	}
	name := os.Getenv("STIFACE_BUCKET")
	if name == "" {
		t.Skip("missing STIFACE_BUCKET environment variable")
	}
	ctx := context.Background()
	c, err := storage.NewClient(ctx)
	if err != nil {
		t.Fatal(err)
	}
	client := AdaptClient(c)
	defer client.Close()
	bkt := client.Bucket(name)
	basicTests(t, name, bkt)
}

func basicTests(t *testing.T, bucketName string, bkt BucketHandle) {
	ctx := context.Background()
	attrs, err := bkt.Attrs(ctx)
	if err != nil {
		t.Fatal(err)
	}
	if got, want := attrs.Name, bucketName; got != want {
		t.Errorf("name: got %v, want %v", got, want)
	}

	const contents = "hello, stiface"
	obj := bkt.Object("stiface-test")
	w := obj.NewWriter(ctx)
	if _, err := fmt.Fprint(w, contents); err != nil {
		t.Fatal(err)
	}
	if err := w.Close(); err != nil {
		t.Fatal(err)
	}
	bytes := readObject(t, obj)
	if got, want := string(bytes), contents; got != want {
		t.Errorf("got %q, want %q", got, want)
	}
	if err := obj.Delete(ctx); err != nil {
		t.Errorf("deleting: %v", err)
	}
}

func readObject(t *testing.T, obj ObjectHandle) []byte {
	r, err := obj.NewReader(context.Background())
	if err != nil {
		t.Fatalf("reading %v: %v", obj, err)
	}
	defer r.Close()
	bytes, err := ioutil.ReadAll(r)
	if err != nil {
		t.Fatalf("reading %v: %v", obj, err)
	}
	return bytes
}

// This test demonstrates how to use this package to create a simple fake for the storage client.
func TestFake(t *testing.T) {
	ctx := context.Background()
	client := newFakeClient()

	bkt := client.Bucket("my-bucket")
	if err := bkt.Create(ctx, "my-project", nil); err != nil {
		t.Fatal(err)
	}
	basicTests(t, "my-bucket", bkt)
}

type fakeClient struct {
	Client
	buckets map[string]*fakeBucket
}

type fakeBucket struct {
	attrs   *storage.BucketAttrs
	objects map[string][]byte
}

func newFakeClient() Client {
	return &fakeClient{buckets: map[string]*fakeBucket{}}
}

func (c *fakeClient) Bucket(name string) BucketHandle {
	return fakeBucketHandle{c: c, name: name}
}

type fakeBucketHandle struct {
	BucketHandle
	c    *fakeClient
	name string
}

func (b fakeBucketHandle) Create(_ context.Context, _ string, attrs *storage.BucketAttrs) error {
	if _, ok := b.c.buckets[b.name]; ok {
		return fmt.Errorf("bucket %q already exists", b.name)
	}
	if attrs == nil {
		attrs = &storage.BucketAttrs{}
	}
	attrs.Name = b.name
	b.c.buckets[b.name] = &fakeBucket{attrs: attrs, objects: map[string][]byte{}}
	return nil
}

func (b fakeBucketHandle) Attrs(context.Context) (*storage.BucketAttrs, error) {
	bkt, ok := b.c.buckets[b.name]
	if !ok {
		return nil, fmt.Errorf("bucket %q does not exist", b.name)
	}
	return bkt.attrs, nil
}

func (b fakeBucketHandle) Object(name string) ObjectHandle {
	return fakeObjectHandle{c: b.c, bucketName: b.name, name: name}
}

type fakeObjectHandle struct {
	ObjectHandle
	c          *fakeClient
	bucketName string
	name       string
}

func (o fakeObjectHandle) NewReader(context.Context) (Reader, error) {
	bkt, ok := o.c.buckets[o.bucketName]
	if !ok {
		return nil, fmt.Errorf("bucket %q not found", o.bucketName)
	}
	contents, ok := bkt.objects[o.name]
	if !ok {
		return nil, fmt.Errorf("object %q not found in bucket %q", o.name, o.bucketName)
	}
	return fakeReader{r: bytes.NewReader(contents)}, nil
}

func (o fakeObjectHandle) Delete(context.Context) error {
	bkt, ok := o.c.buckets[o.bucketName]
	if !ok {
		return fmt.Errorf("bucket %q not found", o.bucketName)
	}
	delete(bkt.objects, o.name)
	return nil
}

type fakeReader struct {
	Reader
	r *bytes.Reader
}

func (r fakeReader) Read(buf []byte) (int, error) {
	return r.r.Read(buf)
}

func (r fakeReader) Close() error {
	return nil
}

func (o fakeObjectHandle) NewWriter(context.Context) Writer {
	return &fakeWriter{obj: o}
}

type fakeWriter struct {
	Writer
	obj fakeObjectHandle
	buf bytes.Buffer
}

func (w *fakeWriter) Write(data []byte) (int, error) {
	return w.buf.Write(data)
}

func (w *fakeWriter) Close() error {
	bkt, ok := w.obj.c.buckets[w.obj.bucketName]
	if !ok {
		return fmt.Errorf("bucket %q not found", w.obj.bucketName)
	}
	bkt.objects[w.obj.name] = w.buf.Bytes()
	return nil
}


text:
package api.database;

import java.sql.Timestamp;

public class Row
{
	private long		id;
	private long		trip_id;
	private long		imei;
	private short		fuel_level;
	private int			analog_inputs1;
	private int			digital_inputs;
	private float		longitude;
	private float		latitude;
	private short		speed;
	private float		odometer;
	private short		prev_digital_inputs;
	private Timestamp	time;

	// Represent Data in Row
	public Row()
	{
	}

	// Getters
	public long getID()
	{
		return id;
	}

	public long getTripID()
	{
		return trip_id;
	}

	public long getImei()
	{
		return imei;
	}

	public short getFuel_level()
	{
		return fuel_level;
	}

	public int getAnalog_inputs1()
	{
		return analog_inputs1;
	}

	public int getDigital_inputs()
	{
		return digital_inputs;
	}

	public float getLongitude()
	{
		return longitude;
	}

	public float getLatitude()
	{
		return latitude;
	}

	public short getSpeed()
	{
		return speed;
	}

	public float getOdometer()
	{
		return odometer;
	}

	public short getPrev_digital_inputs()
	{
		return prev_digital_inputs;
	}

	public Timestamp getTime()
	{
		return time;
	}

	// Setters
	public void setID(long id)
	{
		this.id = id;
	}

	public void setTripID(long trip_id)
	{
		this.trip_id = trip_id;
	}

	public void setImei(long imei)
	{
		this.imei = imei;
	}

	public void setFuel_level(short fuel_level)
	{
		this.fuel_level = fuel_level;
	}

	public void setAnalog_inputs1(int analog_inputs1)
	{
		this.analog_inputs1 = analog_inputs1;
	}

	public void setDigital_inputs(int digital_inputs)
	{
		this.digital_inputs = digital_inputs;
	}

	public void setLongitude(float longitude)
	{
		this.longitude = longitude;
	}

	public void setLatitude(float latitude)
	{
		this.latitude = latitude;
	}

	public void setSpeed(short speed)
	{
		this.speed = speed;
	}

	public void setOdometer(float odometer)
	{
		this.odometer = odometer;
	}

	public void setPrev_digital_inputs(short prev_digital_inputs)
	{
		this.prev_digital_inputs = prev_digital_inputs;
	}

	public void setTime(Timestamp time)
	{
		this.time = time;
	}

	@Override
	public String toString()
	{
		return "Data [id=" + id + ", trip_id=" + trip_id + " , imei=" + imei + ", fuel_level=" + fuel_level + ", analog_inputs1=" + analog_inputs1
				+ ", digital_inputs=" + digital_inputs + ", longitude=" + longitude + ", latitude=" + latitude
				+ ", speed=" + speed + ", odometer=" + odometer + ", prev_digital_inputs=" + prev_digital_inputs
				+ ", time=" + time + "]";
	}
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_64b.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE129.label.xml
Template File: sources-sinks-64b.tmpl.c
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: Larger than zero but less than 10
 * Sinks:
 *    GoodSink: Ensure the array index is valid
 *    BadSink : Improperly check the array index by not checking the upper bound
 * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

#ifndef OMITBAD

void CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_64b_badSink(void * dataVoidPtr)
{
    /* cast void pointer to a pointer of the appropriate type */
    int * dataPtr = (int *)dataVoidPtr;
    /* dereference dataPtr into data */
    int data = (*dataPtr);
    {
        int i;
        int * buffer = (int *)malloc(10 * sizeof(int));
        if (buffer == NULL) {exit(-1);}
        /* initialize buffer */
        for (i = 0; i < 10; i++)
        {
            buffer[i] = 0;
        }
        /* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound
         * This code does check to see if the array index is negative */
        if (data >= 0)
        {
            buffer[data] = 1;
            /* Print the array values */
            for(i = 0; i < 10; i++)
            {
                printIntLine(buffer[i]);
            }
        }
        else
        {
            printLine("ERROR: Array index is negative.");
        }
        free(buffer);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_64b_goodG2BSink(void * dataVoidPtr)
{
    /* cast void pointer to a pointer of the appropriate type */
    int * dataPtr = (int *)dataVoidPtr;
    /* dereference dataPtr into data */
    int data = (*dataPtr);
    {
        int i;
        int * buffer = (int *)malloc(10 * sizeof(int));
        if (buffer == NULL) {exit(-1);}
        /* initialize buffer */
        for (i = 0; i < 10; i++)
        {
            buffer[i] = 0;
        }
        /* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound
         * This code does check to see if the array index is negative */
        if (data >= 0)
        {
            buffer[data] = 1;
            /* Print the array values */
            for(i = 0; i < 10; i++)
            {
                printIntLine(buffer[i]);
            }
        }
        else
        {
            printLine("ERROR: Array index is negative.");
        }
        free(buffer);
    }
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE122_Heap_Based_Buffer_Overflow__c_CWE129_fgets_64b_goodB2GSink(void * dataVoidPtr)
{
    /* cast void pointer to a pointer of the appropriate type */
    int * dataPtr = (int *)dataVoidPtr;
    /* dereference dataPtr into data */
    int data = (*dataPtr);
    {
        int i;
        int * buffer = (int *)malloc(10 * sizeof(int));
        if (buffer == NULL) {exit(-1);}
        /* initialize buffer */
        for (i = 0; i < 10; i++)
        {
            buffer[i] = 0;
        }
        /* FIX: Properly validate the array index and prevent a buffer overflow */
        if (data >= 0 && data < (10))
        {
            buffer[data] = 1;
            /* Print the array values */
            for(i = 0; i < 10; i++)
            {
                printIntLine(buffer[i]);
            }
        }
        else
        {
            printLine("ERROR: Array index is out-of-bounds");
        }
        free(buffer);
    }
}

#endif /* OMITGOOD */