text:
<?php

/**
 * Export subscribers.
 * @property string limiter
 * @property bool found
 * @property int customers
 * @property int newsletterSubscribers
 * @property int deleted
 * @property mixed exportPolicy
 * @property Contactlab_Subscribers_Helper_Exporter helper
 * @property Mage_Core_Model_Resource $resource
 * @property string ukQuery
 * @property array customerAttributes
 * @property array addressAttributes
 * @property Mage_Customer_Model_Customer customerModel
 * @property Mage_Customer_Model_Address addressModel
 * @property array statsAttributesMap
 * @property array stores
 * @property array fAttributesMap
 * @property array fAddressAttributes
 * @property array deletedEntities
 */
class Contactlab_Subscribers_Model_Exporter_Subscribers extends Contactlab_Commons_Model_Exporter_Abstract {
    /**
     * Get xml object.
     */
    protected function writeXml() {

        $this->limiter = '###';
        $this->found = false;

        $this->customers = 0;
        $this->newsletterSubscribers = 0;
        $this->deleted = 0;

        $this->exportPolicy = $this->getTask()->getConfig('contactlab_subscribers/global/export_policy');
        $this->helper = Mage::helper("contactlab_subscribers/exporter");
        $this->resource = Mage::getSingleton('core/resource');

        $this->ukQuery = "";

        Mage::helper("contactlab_commons")->enableDbProfiler();

        if ($this->_mustResetExportDates()) {
            $this->_resetExportDates();
        }

        $this->customerAttributes = $this->helper->getAttributesCodesForEntityType('customer');
        $this->addressAttributes = $this->helper->getAttributesCodesForEntityType('customer_address');

        $this->customerModel = Mage::getModel('customer/customer');
        $this->addressModel = Mage::getModel('customer/address');

        $this->statsAttributesMap = $this->helper->getStatsAttributesMap();
        $this->stores = $this->_loadStores();

        // Define customer collection
        $attributesCustomer = $this->helper->getAttributesForEntityType('customer',
            array_keys($this->helper->getAttributesMap($this->getTask())));
        $this->fAttributesMap = array_flip($this->helper->getAttributesMap($this->getTask()));
        $this->fAddressAttributes = array_flip($this->helper->getAddressesAttributesMap());

        $counter = 0;
        $start = microtime(true);
        $max = $this->_createCounterSubscribersInCustomersCollection()->getSize();
        $this->getTask()->setMaxValue($max);
        Mage::helper("contactlab_commons")->logNotice(sprintf("Counting time: %0.4f", microtime(true) - $start));

        $customKeys = array();
        for ($ic = 1; $ic < 8; ++$ic) {
            if ($this->getTask()->getConfigFlag("contactlab_subscribers/custom_fields/enable_field_" . $ic)) {
                $customKeys[] = $this->getTask()->getConfig("contactlab_subscribers/custom_fields/field_" . $ic);
            }
        }

        $start = microtime(true);

        $limit = 50000;
        $page = 1;
        $preFilled = array_fill_keys(array_values($this->fAttributesMap), '');
        $this->_addAddressFields($preFilled);
        while (true) {
            $subscribersInCustomers = $this->_createSubscribersInCustomersCollection($attributesCustomer);
            $subscribersInCustomers->getSelect()->limitPage($page, $limit);

            Mage::helper("contactlab_commons")->logDebug($subscribersInCustomers->getSelect()->assemble());
            $found = false;
            while ($item = $subscribersInCustomers->fetchItem()) {
                $toFill = array();
                $found = true;
                $counter++;
                $toFill['is_customer'] = 1;
                /** Checked also if there is the key uk but if not void */
                if (!$item->hasData('uk') || !$item->getData('uk')) {
                    $msg = sprintf("FATAL ERROR, %s subscriber has no UK record!", $item->getData('email'));
                    $this->getTask()->addEvent($msg, true);
                    throw new Exception($msg);
                }
                $toFill['entity_id'] = $item->getData('uk');

                $toFill = array_merge($toFill, $preFilled);
                $toFill['email'] = $item->getData('email');

                $this->_setAttributeKeys($toFill, $item);
                $this->_setAddressesAttributeKeys($toFill, $item);

                $this->_fillStoreAttributes($toFill, $item);
                foreach ($this->statsAttributesMap as $k => $v) {
                    $toFill[$k] = $item->getData($v);
                }
                $this->_fillCustomerGroupAttributes($toFill, $item);
                $this->_manageCustomerClsFlag($toFill, $item);
                /** Custom rispetto alla versione originale del modulo */
                $this->customizeInfoCustomer($toFill, $item);

                foreach ($customKeys as $icKey) {
                    if (empty($icKey)) {
                        continue;
                    }
                    $icValue = $item->getData($icKey);
                    if (isset($toFill[$icKey]) && empty($toFill[$icKey]) && !empty($icValue)) {
                        $toFill[$icKey] = $icValue;
                    }
                }
                $this->found = true;
                $this->customers++;
                $writer = new XMLWriter();
                $writer->openMemory();
                $writer->setIndent(true);
                $writer->startElement("RECORD");
                $writer->writeAttribute('ACTION', 'U');
                foreach ($toFill as $k => $v) {

                    if (empty($k)) {
                        continue;
                    }
                    if ($k !== $this->getSubscribedFlagName()) {
                        $k = strtoupper($this->getOutputTagName($k));
                    }
                    $writer->writeElement($k, $v);
                }
                $writer->endElement();
                gzwrite($this->gz, $writer->outputMemory());

                if ($counter % 2000 == 0) {
                    Mage::helper("contactlab_commons")->logNotice(sprintf("Exporting %6s / %-6s", $counter, $max));
                    $this->getTask()->setProgressValue($counter);
                }
            }
            $this->_setUkIsExported();
            if (!$found) {
                break;
            }
            $page++;
        }
        Mage::helper("contactlab_commons")->logNotice(sprintf("Loop time: %0.4f", microtime(true) - $start));

        $this->_addNotCustomerRecords();
        $this->_addDeletedRecords();

        $this->_setUkIsExported();

        Mage::helper("contactlab_commons")->flushDbProfiler();
        if (!$this->found) {
            $this->getTask()->addEvent("No record exported or deleted");
        } else {
            if ($this->customers > 0) {
                $this->getTask()->addEvent(sprintf("%d customers exported", $this->customers));
            }
            if ($this->newsletterSubscribers > 0) {
                $this->getTask()->addEvent(sprintf("%d newsletter subscribers exported", $this->newsletterSubscribers));
            }
            if ($this->deleted > 0) {
                $this->getTask()->addEvent(sprintf("%d record deleted", $this->deleted));
            }
        }
    }

    /**
     * Create subscribers in customers collection.
     * @param Mage_Eav_Model_Resource_Entity_Attribute_Collection $attributesCustomer
     * @return Mage_Customer_Model_Resource_Customer_Collection
     */
    private function _createSubscribersInCustomersCollection(
        Mage_Eav_Model_Resource_Entity_Attribute_Collection $attributesCustomer)
    {
        /**
         * @var $subscribersInCustomers Mage_Customer_Model_Resource_Customer_Collection
         */
        $rv = Mage::getModel('customer/customer')->getCollection();
//        $w = 'subscriber_status = ' . Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED;
//        $w = $this->_manageExportPolicySql($w, array(
//            'e#1' => 'updated_at',
//            'e#2' => 'created_at',
//            'newsletter_subscriber' => 'last_updated_at'
//        ));

//        if (!$this->_mustExportNotSubscribed()) {
//            $rv->getSelect()
//                ->where('e.entity_id in (select customer_id from ' . $this->resource->getTableName('newsletter_subscriber')
//                . ' where ' . $w . ')');
//        }

        // Fills array of types with attributes id array
        foreach ($this->helper->fillBackendTypesFromArray($attributesCustomer) as $backendType => $ids) {
            $alias = 'ce' . $backendType;
            $w = 'e.entity_id = ' . $alias . '.entity_id and length(' . $alias . '.value) > 0 and '
                . $alias . '.attribute_id IN (' . implode(',', $ids) . ')';
            $rv->getSelect()->joinLeft(
                array(
                    $alias => $this->resource->getTableName('customer_entity_' . $backendType)),
                $w, array($backendType . '_value' => new Zend_Db_Expr('GROUP_CONCAT(DISTINCT CONCAT('
                . $alias . ".attribute_id, '_', " .$alias. ".value) SEPARATOR '" . $this->limiter . "')")));
        }

        // Stats
        $this->_addStatsToSelect($rv);
        $this->_addAddressesToSelect($rv);
        $this->_addCustomerGroupToSelect($rv);
        $this->_manageExportPolicy($rv,
            array(
                'e' => array('created_at', 'updated_at'),
                'newsletter_subscriber' => 'last_updated_at',
            ));
        $this->_addCustomerExportCollection($rv);
        $this->_addSubscriberFields($rv);

        $rv->getSelect()->group('e.entity_id');
        return $rv;
    }

    /**
     * Create count subscribers in customers collection.
     * @return Mage_Customer_Model_Resource_Customer_Collection
     */
    private function _createCounterSubscribersInCustomersCollection()
    {
        /**
         * @var $subscribersInCustomers Mage_Customer_Model_Resource_Customer_Collection
         */
        $rv = Mage::getModel('customer/customer')->getCollection();
//        $w = 'subscriber_status = ' . Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED;
//        $w = $this->_manageExportPolicySql($w, array(
//            'e#1' => 'updated_at',
//            'e#2' => 'created_at',
//            'newsletter_subscriber' => 'last_updated_at'
//        ));

//        if (!$this->_mustExportNotSubscribed()) {
//            $rv->getSelect()
//                ->where('e.entity_id in (select customer_id from ' . 'newsletter_subscriber'
//                . ' where ' . $w . ')');
//        }

        $this->_manageExportPolicy($rv,
            array(
                'e' => array('created_at', 'updated_at'),
                'newsletter_subscriber' => 'last_updated_at',
            ));
        $this->_addCustomerExportCollection($rv);
        return $rv;
    }

    /**
     * Called after the export.
     */
    public function afterFileCopy() {
        $this->helper->soapCallAfterExport($this->getTask());
    }

    /** Not customer records. */
    private function _addNotCustomerRecords() {
        Mage::helper("contactlab_commons")->logDebug("_addNotCustomerRecords");
        $preFilled = array_fill_keys(array_values($this->fAttributesMap), '');
        $this->_addAddressFields($preFilled);
        $subscribersNotInCustomers = $this->_createSubscribersNotInCustomers();
        $customKeys = array();
        for ($ic = 1; $ic < 8; ++$ic) {
            if ($this->getTask()->getConfigFlag("contactlab_subscribers/custom_fields/enable_field_" . $ic)) {
                $customKeys[] = $this->getTask()->getConfig("contactlab_subscribers/custom_fields/field_" . $ic);
            }
        }
        $counter = 0;
        $max = $subscribersNotInCustomers->getSize();
        $this->getTask()->setMaxValue($max);

        $limit = 200000;
        $page = 1;
        while (true) {
            $subscribersNotInCustomers = $this->_createSubscribersNotInCustomers();
            $subscribersNotInCustomers->getSelect()->limitPage($page, $limit);
            Mage::helper("contactlab_commons")->logDebug($subscribersNotInCustomers->getSelect()->assemble());
            $found = false;

            while ($item = $subscribersNotInCustomers->fetchItem()) {
                $counter++;
                $found = true;
                $toFill1 = array();

                $toFill1['is_customer'] = 0;
                if (!$item->hasData('uk')) {
                    $msg = sprintf("FATAL ERROR, %s customer has no UK record!", $item->getData('subscriber_email'));
                    $this->getTask()->addEvent($msg, true);
                    throw new Exception($msg);
                }
                $toFill1['entity_id'] = $item->getData('uk');

                $toFill = array_merge($toFill1, $preFilled);
                $toFill['email'] = $item->getData('subscriber_email');
                $this->_manageNewsletterClsFlag($toFill, $item);
                $this->_fillStoreAttributes($toFill, $item);
                $this->_fillNewsletterAttributes($toFill, $item);
                /** Custom rispetto alla versione originale del modulo */
                $this->customizeInfoSubscriber($toFill, $item);

                foreach ($customKeys as $icKey) {
                    if (empty($icKey)) {
                        continue;
                    }
                    $icValue = $item->getData($icKey);
                    if (isset($toFill[$icKey]) && empty($toFill[$icKey]) && !empty($icValue)) {
                        $toFill[$icKey] = $icValue;
                    }
                }

                $this->found = true;
                $this->newsletterSubscribers++;
                $writer = new XMLWriter();
                $writer->openMemory();
                $writer->setIndent(true);
                $writer->startElement("RECORD");
                $writer->writeAttribute('ACTION', 'U');
                foreach ($toFill as $k => $v) {
                    if (empty($k)) {
                        continue;
                    }
                    if ($k !== $this->getSubscribedFlagName()) {
                        $k = strtoupper($this->getOutputTagName($k));
                    }
                    $writer->writeElement($k, $v);
                }
                $writer->endElement();
                gzwrite($this->gz, $writer->outputMemory());
                if ($counter % 2000 == 0) {
                    Mage::helper("contactlab_commons")->logNotice(sprintf("Exporting %6s / %-6s", $counter, $max));
                    $this->getTask()->setProgressValue($counter);
                }
            }
            $this->_setUkIsExported();
            if (!$found) {
                break;
            }
            $page++;
        }
    }

    /**
     * Create subscribers not in customers.
     * @return Contactlab_Template_Model_Resource_Newsletter_Subscriber_Collection
     */
    private function _createSubscribersNotInCustomers()
    {
        /** @var $rv Contactlab_Template_Model_Resource_Newsletter_Subscriber_Collection */
        $rv = Mage::getModel('contactlab_subscribers/uk')->getCollection();
        $rv->addFieldToSelect(
            array('uk' => 'entity_id', 'is_exported' => 'is_exported')
        );
        $this->_addSubscriberFields($rv, 'main_table');
        $rv->getSelect()->joinLeft(
            array('native_nl' => $this->resource->getTableName('newsletter/subscriber')),
            'native_nl.subscriber_id = main_table.subscriber_id');
        $this->_manageExportPolicy($rv,
            array('native_nl' => 'last_updated_at'));
        if (!$this->_mustExportNotSubscribed()) {
            $rv->addFieldToFilter('native_nl.subscriber_status', Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
        }
        $rv->getSelect()->where('main_table.customer_id is null or main_table.customer_id = 0');

        return $rv;
    }

    /**
     * Add delete records.
     */
    private function _addDeletedRecords() {
        /** @var $deletedEntities Contactlab_Commons_Model_Resource_Deleted_Collection */
        $deletedEntities = Mage::getModel('contactlab_commons/deleted')
            ->getCollection()
            ->addFieldToFilter('task_id', array('null' => true));

        $counter = 0;
        // FIXME TODO count vs getSize
        $max = $deletedEntities->count();

        Mage::helper("contactlab_commons")->logDebug($deletedEntities->getSelect()->assemble());
        $this->deletedEntities = array();
        $preFilled = array_fill_keys(array_keys($this->fAttributesMap), '');
        $this->_addAddressFields($preFilled);

        /** @var $deletedEntity Contactlab_Commons_Model_Deleted */
        while ($deletedEntity = $deletedEntities->fetchItem()) {
            $counter++;
            $toFill1 = array();

            $this->found = true;
            $this->deleted++;

            $toFill1['is_customer'] = $deletedEntity->getIsCustomer();
            $toFill1['entity_id'] = $deletedEntity->getEntityId();
            $toFill = array_merge($toFill1, $preFilled);
            $toFill['email'] = $deletedEntity->getEmail();
            /** Custom rispetto alla versione originale del modulo */
            $this->customizeInfoDeleted($toFill, $deletedEntity);

            $writer = new XMLWriter();
            $writer->openMemory();
            $writer->setIndent(true);
            $writer->startElement("RECORD");
            $writer->writeAttribute('ACTION', 'D');
            foreach ($toFill as $k => $v) {
                if ($k !== $this->getSubscribedFlagName()) {
                    $k = strtoupper($k);
                }
                $writer->writeElement($k, $v);
            }
            $writer->endElement();
            gzwrite($this->gz, $writer->outputMemory());

            $deletedEntity->setTaskId($this->getTask()->getTaskId())->save();
            if ($counter % 500 == 0) {
                Mage::helper("contactlab_commons")->logNotice(sprintf("Exporting deleted %6s / %-6s", $counter, $max));
            }
        }
    }

    /**
     * Set addresses attribute keys.
     * @param array $toFill
     * @param Varien_Object $data
     */
    private function _setAddressesAttributeKeys(array &$toFill, Varien_Object $data) {
        $this->_setAddressAttributeKeys($toFill, $data, "shipping");
        $this->_setAddressAttributeKeys($toFill, $data, "billing");
    }

    /**
     * Do export address with type.
     * @param string $addressType
     * @return bool
     */
    private function _mustExportAddress($addressType) {
        return $this->getTask()->getConfigFlag("contactlab_subscribers/global/export_" . $addressType . "_address");
    }

    /**
     * Set address attribute keys.
     * @param array $toFill
     * @param Varien_Object $data
     * @param $addressType
     */
    private function _setAddressAttributeKeys(array &$toFill, Varien_Object $data, $addressType) {
        if (!$this->_mustExportAddress($addressType)) {
            return;
        }
        $entityTypes = array('int', 'varchar', 'text', 'decimal', 'datetime');
        foreach ($entityTypes as $type) {
            if (!array_key_exists($addressType . '_' . $type . '_value', $data->getData())) {
                return;
            }
            $values = explode($this->limiter, $data->getData($addressType . '_' . $type . '_value'));
            foreach ($values as $key) {
                $pos = strpos($key, '_');
                if ($pos === false) {
                    continue;
                }
                $k = substr($key, 0, $pos);
                $v = substr($key, $pos + 1);
                if (!array_key_exists($k, $this->addressAttributes)) {
                    continue;
                }
                $toFill[$addressType . '_' . $this->fAddressAttributes[$this->addressAttributes[$k]]] =
                    $this->helper->decode($this->addressModel, 'address', $this->addressAttributes[$k], $v);
            }
        }
    }

    /**
     * Set attribute keys.
     * @param array $toFill
     * @param Varien_Object $data
     */
    private function _setAttributeKeys(array &$toFill, Varien_Object $data) {
        $entityTypes = array('int', 'varchar', 'text', 'decimal', 'datetime');
        foreach ($entityTypes as $type) {
            if (!array_key_exists($type . '_value', $data->getData())) {
                continue;
            }
            $values = explode($this->limiter, $data->getData($type . '_value'));
            foreach ($values as $key) {
                $pos = strpos($key, '_');
                if ($pos === false) {
                    continue;
                }
                $k = substr($key, 0, $pos);
                $v = substr($key, $pos + 1);
                if (!array_key_exists($k, $this->customerAttributes)) {
                    continue;
                }
                // use flipped array for cstm attributes
                //$flip = array_flip($this->fAttributesMap);
                //$toFill[$this->fAttributesMap[$this->customerAttributes[$k]]] =
//                $toFill[$flip[$this->customerAttributes[$k]]] =
                $toFill[$this->customerAttributes[$k]] =
                    $this->helper->decode($this->customerModel, 'customer', $this->customerAttributes[$k], $v);
            }
        }

    }

    /**
     * Add store, group and website attributes.
     * @param array $toFill
     * @param Varien_Object $item
     */
    private function _fillStoreAttributes(array &$toFill, Varien_Object $item) {
        $store = $this->stores[$item->getData('store_id')];
        foreach (array('store_id', 'store_name', 'website_id', 'website_name',
                     'group_id', 'group_name', 'lang') as $k) {
            $toFill[$k] = $store[$k];
        }
    }

    private function _fillCustomerGroupAttributes(array &$toFill, Varien_Object $item)
    {
        $toFill['customer_group_id'] = $item->getData('customer_group_id');
        $toFill['customer_group_name'] = $item->getData('customer_group_name');
    }

    /**
     * Fill Newsletter attributes fields.
     * @param array $toFill
     * @param Varien_Object $item
     */
    private function _fillNewsletterAttributes(array &$toFill, Varien_Object $item)
    {
        foreach ($this->helper->getSubscriberToCustomerAttributeMap() as $k => $v) {
            if (!$this->_doManageAddressAttribute($v)) {
                continue;
            }
            $toFill[$v] = $item->getData($k);
        }
    }

    /**
     * Add stats to collection.
     * @param Varien_Data_Collection_Db $collection
     */
    private function _addStatsToSelect(Varien_Data_Collection_Db $collection) {
        $collection->getSelect()->joinLeft(
            array('stats' => $this->resource->getTableName('contactlab_subscribers/stats')),
            'stats.customer_id = e.entity_id', $this->statsAttributesMap);
    }

    /**
     * Add customer export to collection.
     * @param Varien_Data_Collection_Db $collection
     */
    private function _addCustomerExportCollection(Varien_Data_Collection_Db $collection) {
        if (!$this->_mustExportNotSubscribed()) {
            $w = 'subscriber_status = ' . Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED;
            $w = $this->_manageExportPolicySql($w, array(
                'e#1' => 'updated_at',
                'e#2' => 'created_at',
                'newsletter_subscriber' => 'last_updated_at'
            ));

            $collection->getSelect()->joinInner(
                array('newsletter_subscriber' => $this->resource->getTableName('newsletter/subscriber')),
                'newsletter_subscriber.customer_id = e.entity_id AND ' . $w,
                array('subscriber_status' => 'subscriber_status', 'subscriber_created_at'=>'created_at', 'last_subscribed_at' => 'last_subscribed_at', 'last_updated_at' => 'last_updated_at'));
        }else{
            $collection->getSelect()->joinLeft(
                array('newsletter_subscriber' => $this->resource->getTableName('newsletter/subscriber')),
                'newsletter_subscriber.customer_id = e.entity_id',
                array('subscriber_status' => 'subscriber_status', 'subscriber_created_at'=>'created_at', 'last_subscribed_at' => 'last_subscribed_at', 'last_updated_at' => 'last_updated_at'));
        }

        $collection->getSelect()->joinLeft(
            array('uk' => $this->resource->getTableName('contactlab_subscribers/uk')),
            'uk.customer_id = e.entity_id',
            array('uk' => 'entity_id', 'is_exported' => 'is_exported'));
    }

    /**
     * Add newsletter subscriber export to collection.
     * @param Varien_Data_Collection_Db $collection
     */
    private function _addNewsletterSubscriberExportCollection(Varien_Data_Collection_Db $collection) {
        $collection->getSelect()->joinLeft(
            array('uk' => $this->resource->getTableName('contactlab_subscribers/uk')),
            'uk.subscriber_id = main_table.subscriber_id',
            array('uk' => 'entity_id', 'is_exported' => 'is_exported'));
    }

    /**
     * Add export policy to sql statement.
     * @param Varien_Data_Collection_Db $collection
     * @param array $fields
     */
    private function _manageExportPolicy(Varien_Data_Collection_Db $collection,
                                         array $fields) {
        if ($this->exportPolicy != '2') {
            // Ok, will export everything
            return;
        }
        $lastExport = $this->getTask()->getConfig('contactlab_subscribers/global/last_export');
        if (empty($lastExport)) {
            // Ok, will export everything, no last import saved.
            return;
        }
        $clause = '';
        //$lastExport = Mage::getModel("core/date")->gmtDate(null, $lastExport);

        foreach ($fields as $table => $field) {
            if (!is_array($field)) {
                $field = array($field);
            }
            foreach ($field as $item) {
                if (!empty($clause)) {
                    $clause .= ' or ';
                }
                $clause .= sprintf("%s.%s >= '%s'", $table, $item, $lastExport);
                if (preg_match("/.*newsletter_subscriber.*/", $table)) {
                    $clause .= sprintf(" or (%s.%s is null and %s.subscriber_id is not null)", $table, $item, $table);
                } else {
                    $clause .= sprintf(" or %s.%s is null", $table, $item);
                }
            }
        }
        $collection->getSelect()->where($clause);
    }

    /**
     * Add export policy to sql statement.
     * @param string $w
     * @param array $fields
     * @return string
     */
    private function _manageExportPolicySql($w, array $fields) {
        if ($this->exportPolicy != '2') {
            // Ok, will export everything
            return $w;
        }
        $lastExport = $this->getTask()->getConfig('contactlab_subscribers/global/last_export');
        if (empty($lastExport)) {
            // Ok, will export everything, no last import saved.
            return $w;
        }
        // $lastExport = Mage::getModel("core/date")->gmtDate(null, $lastExport);

        $w .= ' and (';
        $first = true;
        foreach ($fields as $table => $field) {
            $table = preg_replace('|#.*|', '', $table);
            if (!is_array($field)) {
                $field = array($field);
            }
            if (!$first) {
                $w .= ' and ';
            }
            foreach ($field as $item) {
                $w .= sprintf("%s.%s >= '%s'", $table, $item, $lastExport);
                if (preg_match("/.*newsletter_subscriber.*/", $table)) {
                    $w .= sprintf(" or (%s.%s is null and %s.subscriber_id is not null)", $table, $item, $table);
                } else {
                    $w .= sprintf(" or %s.%s is null", $table, $item);
                }
            }
            $first = false;
        }
        $w .= ')';
        return $w;
    }

    /**
     * Add addresses to select
     * @param Varien_Data_Collection_Db $collection
     */
    private function _addAddressesToSelect(Varien_Data_Collection_Db $collection) {
        $this->_addAddressToSelect($collection, "shipping");
        $this->_addAddressToSelect($collection, "billing");
    }

    /**
     * Add address to select.
     * @param Varien_Data_Collection_Db $collection
     * @param string $type
     */
    private function _addAddressToSelect(Varien_Data_Collection_Db $collection, $type) {
        if (!$this->getTask()->getConfigFlag("contactlab_subscribers/global/export_" . $type . "_address")) {
            return;
        }
        $collection->getSelect()->joinLeft(
            array($type . '_addr' => $this->resource->getTableName('customer_entity_int')),
            $type . '_addr.entity_id = e.entity_id and ' . $type . '_addr.attribute_id = '
            . $this->helper->getAttributeId('customer', 'default_' . $type),
            array('default_' . $type => 'value'));

        // Fills array of types with attributes id array
        $attributesAddress = $this->helper->getAttributesForEntityType('customer_address',
            array_values($this->helper->getAddressesAttributesMap()));
        foreach ($this->helper->fillBackendTypesFromArray($attributesAddress) as $backendType => $ids) {
            $alias = 'ce' . $type . $backendType;
            $w = $type . '_addr.value = ' . $alias . '.entity_id and length(' . $alias . '.value) > 0 and '
                . $alias . '.attribute_id IN (' . implode(',', $ids) . ')';
            $collection->getSelect()->joinLeft(
                array(
                    $alias => $this->resource->getTableName('customer_address_entity_' . $backendType)),
                $w, array($type . '_' . $backendType . '_value' => new Zend_Db_Expr('GROUP_CONCAT(DISTINCT CONCAT('
                . $alias . ".attribute_id, '_', " .$alias. ".value) SEPARATOR '" . $this->limiter . "')")));
        }
    }

    /**
     * Remove deleted entity.
     * @throws Exception
     */
    private function _removeDeletedEntity() {
        $toDelete = Mage::getModel('contactlab_commons/deleted')
            ->getCollection()
            ->addFieldToFilter('task_id', $this->getTask()->getTaskId());

        $counter = 0;
        $max = $toDelete->count();

        Mage::helper("contactlab_commons")->logDebug($toDelete->getSelect()->assemble());

        foreach ($toDelete as $item) {
            $counter++;
            $item->delete();
            if ($counter % 500 == 0) {
                Mage::helper("contactlab_commons")->logNotice(sprintf("Deleted %6s / %-6s", $counter, $max));
            }
        }
    }

    /**
     * Load stores.
     * @return array
     */
    private function _loadStores() {
        $rv = array();
        $websiteTable = $this->resource->getTableName('core/website');
        $storeGroupTable = $this->resource->getTableName('core/store_group');

        /** @var Mage_Core_Model_Resource_Store_Collection $stores */
        $stores = Mage::getModel('core/store')
            ->getCollection()->setLoadDefault(true);
        $stores->addFieldToSelect('*')->getSelect()
            ->join(array('core_website' => $websiteTable),
                'main_table.website_id = ' . 'core_website.website_id',
                array('website_name' => 'core_website.name'))
            ->join(array('core_store_group' => $storeGroupTable),
                'main_table.group_id = ' . 'core_store_group.group_id',
                array('group_name' => 'core_store_group.name'));
        /** @var $store Mage_Core_Model_Store */
        foreach ($stores as $store) {
            $storeId = $store->getData('store_id');
            $rv[$storeId] = array(
                'store_id' => $storeId,
                'website_id' => $store->getData('website_id'),
                'group_id' => $store->getData('group_id'),
                'store_name' => $store->getData('mame'),
                'website_name' => $store->getData('website_name'),
                'group_name' => $store->getData('group_name'),
                'lang' => $store->getConfig("general/locale/code"),
            );
        }
        return $rv;
    }

    /**
     * Do I have to export all contacts? Or only subscribed ones?
     * @return bool
     */
    private function _mustExportNotSubscribed() {
        return $this->getTask()->getConfigFlag("contactlab_subscribers/global/export_not_subscribed");
    }

    /**
     * Do I have to reset export dates before export?
     * @return bool
     */
    private function _mustResetExportDates() {
        return $this->getTask()->getConfigFlag("contactlab_subscribers/global/reset_export_dates_before_next_export");
    }

    /**
     * Reset reset export flg.
     */
    private function _resetMustResetExportDatesFlag() {
        Mage::helper("contactlab_commons")->logDebug("Reset reset_export_dates_before_next_export flag");
        Mage::getConfig()
            ->saveConfig('contactlab_subscribers/global/reset_export_dates_before_next_export', '0');
        Mage::getConfig()->reinit();
        Mage::app()->reinitStores();
    }

    private function _resetExportDates() {
        $tableName = $this->resource->getTableName('contactlab_subscribers/uk');
        $this->_query("update $tableName set is_exported = 0;");
    }

    /**
     * Run custom query.
     * @param $sql
     * @return Zend_Db_Statement_Interface
     */
    private function _query($sql) {
        $write = Mage::getSingleton('core/resource')->getConnection('core_write');
        return $write->query($sql);
    }

    /** Get subscription flag name. */
    public function getSubscribedFlagName() {
        return $this->getTask()->getConfig("contactlab_subscribers/global/subscribed_flag_name");
    }

    /**
     * Manage if include CLS tag and his value.
     * Fill the persistence table.
     * @param array $toFill
     * @param Varien_Object $item
     */
    private function _manageCustomerClsFlag(array &$toFill, Varien_Object $item) {
        /*  1 = Subscribed
            0 = Not subscribed
           -1 = Unsubscribed
        */
        if ($this->_manageClsFlag($toFill, $item)) {
            if ($this->ukQuery != '') {
                $this->ukQuery .= ', ';
            }
            $this->ukQuery .= $item->getData('uk');
        }
    }

    /**
     * Manage if include CLS tag and his value.
     * Fill the persistence table.
     * @param array $toFill
     * @param Varien_Object $item
     */
    private function _manageNewsletterClsFlag(array &$toFill, Varien_Object $item) {
        if ($this->_manageClsFlag($toFill, $item, true)) {
            if ($this->ukQuery != '') {
                $this->ukQuery .= ', ';
            }
            $this->ukQuery .= $item->getData('uk');
        }
    }

    /**
     * Manage if include CLS tag and his value.
     * Fill the persistence table.
     * @param array $toFill
     * @param Varien_Object $item
     * @param bool $force
     * @return bool
     */
    private function _manageClsFlag(array &$toFill, Varien_Object $item, $force = false) {
        // If processing record has (first) ExportDate, return.
        if ($item->hasData('is_exported') && $item->getData('is_exported') == 1 && !$force) {
            return false;
        }
        $toFill[$this->getSubscribedFlagName()]
            = $item->getData('subscriber_status') == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED
            ? 1 : 0;
        return true;
    }

    /**
     * Is enabled.
     * @return bool
     */
    protected function isEnabled() {
        return Mage::helper("contactlab_subscribers")->isEnabled($this->getTask());
    }

    /**
     * Get file name.
     * @return string
     */
    protected function getFileName() {
        return $this->getTask()->getConfig("contactlab_subscribers/global/export_filename");
    }

    /**
     * Called after the export.
     */
    public function afterExport() {
        $this->helper->saveLastExportDatetime($this->getTask());
        $this->_removeDeletedEntity();
        if ($this->_mustResetExportDates()) {
            $this->_resetMustResetExportDatesFlag();
        }
    }

    /**
     * Set uk is exported.
     */
    private function _setUkIsExported()
    {
        if ($this->ukQuery != "") {
            $tableName = $this->resource->getTableName('contactlab_subscribers/uk');
            $this->ukQuery = "update $tableName set is_exported = 1 where entity_id in ({$this->ukQuery})";
            $this->_query($this->ukQuery);
            $this->ukQuery = "";
        }
    }

    /**
     * Add subscriber fields.
     * @param Varien_Data_Collection_Db $collection
     * @param string $table Table name for join
     * @return Varien_Db_Select
     */
    private function _addSubscriberFields(Varien_Data_Collection_Db $collection, $table = 'newsletter_subscriber')
    {
        return $collection->getSelect()->joinLeft(
            array('fields' => $this->resource->getTableName('contactlab_subscribers/newsletter_subscriber_fields')),
            "fields.subscriber_id = $table.subscriber_id"
        );
    }

    /**
     * Do include this field into xml element?
     * @param String $attributeCode
     * @return bool
     */
    private function _doManageAddressAttribute($attributeCode)
    {
        if (preg_match('|^billing_|', $attributeCode)) {
            return $this->_mustExportAddress('billing');
        } else if (preg_match('|^shipping|', $attributeCode)) {
            return $this->_mustExportAddress('shipping');
        }
        return true;
    }

    /**
     * Add address fields.
     * @param array $preFilled
     */
    private function _addAddressFields(array &$preFilled)
    {
        foreach (array('billing', 'shipping') as $addressType) {
            if ($this->_mustExportAddress($addressType)) {
                foreach ($this->fAddressAttributes as $k) {
                    $preFilled[$addressType . '_' . $k] = '';
                }
            }
        }
    }

    /**
     * @param Varien_Data_Collection_Db $collection
     * @return Varien_Db_Select
     */
    private function _addCustomerGroupToSelect(Varien_Data_Collection_Db $collection)
    {
        return $collection->getSelect()->joinInner(
            array(
                'customer_group' => $this->resource->getTableName('customer/customer_group')
            ),
            "customer_group.customer_group_id = e.group_id",
            array(
                'customer_group_name' => 'customer_group_code',
                'customer_group_id' => 'customer_group_id'
            )
        );
    }

    /**
     * Use destination field name for cstm fields
     * @param $k
     * @return mixed
     */
    private function getOutputTagName($k) {
        if (isset($this->fAttributesMap[$k]) && strpos($k, 'cstm') === 0) {
            return $this->fAttributesMap[$k];
        }
        return $k;
    }

    /**
     *  Custom rispetto alla versione originale del modulo
     */
    protected function customizeInfoCustomer(array &$toFill, Varien_Object $customer){
        $tCustInfo = Mage::getModel('contactlab_subscribers/exporter_subscribers_infoTransporter_customer');
        $tCustInfo->setInfo($toFill);
        $tCustInfo->setCustomer($customer);
        $tCustInfo->setIsMod(false);

        //FIX
        $toFill['created_at'] = $customer->getData('created_at');
        if($customer->getData('subscriber_created_at'))
        {
            $createdAt = $customer->getData('created_at');
            $subscriberCreatedAt = $customer->getData('subscriber_created_at');
            if(strtotime($subscriberCreatedAt) < strtotime($createdAt))
            {
                $toFill['created_at'] = $customer->getData('subscriber_created_at');
            }
        }
        if($customer->getData('last_subscribed_at'))
        {
            $toFill['last_subscribed_at'] = $customer->getData('last_subscribed_at');
        }
        Mage::dispatchEvent("contactlab_export_subscribers_customer_info",array(
            'customer_info' => $tCustInfo
        ));

        if ($tCustInfo->isMod()){
            $toFill = $tCustInfo->getInfo();
        }
    }

    /**
     *  Custom rispetto alla versione originale del modulo
     */
    protected function customizeInfoDeleted(array &$toFill, Varien_Object $deleted){
        $tDeletedInfo = Mage::getModel('contactlab_subscribers/exporter_subscribers_infoTransporter_deleted');
        $tDeletedInfo->setInfo($toFill);
        $tDeletedInfo->setDeleted($deleted);
        $tDeletedInfo->setIsMod(false);

        Mage::dispatchEvent("contactlab_export_subscribers_deleted_info",array(
            'deleted_info' => $tDeletedInfo
        ));

        if ($tDeletedInfo->isMod()){
            $toFill = $tDeletedInfo->getInfo();
        }
    }

    /**
     *  Custom rispetto alla versione originale del modulo
     */
    protected function customizeInfoSubscriber(array &$toFill, Varien_Object $subscriber){
        $tSubscriberInfo = Mage::getModel('contactlab_subscribers/exporter_subscribers_infoTransporter_subscriber');
        $tSubscriberInfo->setInfo($toFill);
        $tSubscriberInfo->setSubscriber($subscriber);
        $tSubscriberInfo->setIsMod(false);

        //FIX
        $toFill['created_at'] = $subscriber->getData('created_at');

        Mage::dispatchEvent("contactlab_export_subscribers_subscriber_info",array(
            'subscriber_info' => $tSubscriberInfo
        ));

        if ($tSubscriberInfo->isMod()){
            $toFill = $tSubscriberInfo->getInfo();
        }
    }
}


text:
<?php

namespace Aws\DynamoDb\Model\BatchRequest;

use Aws\DynamoDb\Model\Item;
use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Service\Command\AbstractCommand;

/**
 * Represents a batch put request. It is composed of a table name and item
 */
class PutRequest extends AbstractWriteRequest
{
    /**
     * @var Item The item to be inserted into the DynamoDB table
     */
    protected $item;

    /**
     * Factory that creates a PutRequest from a PutItem command
     *
     * @param AbstractCommand $command The command to create the request from
     *
     * @return PutRequest
     *
     * @throws InvalidArgumentException if the command is not a PutItem command
     */
    public static function fromCommand(AbstractCommand $command)
    {
        if ($command->getName() !== 'PutItem') {
            throw new InvalidArgumentException();
        }

        // Get relevant data for a PutRequest
        $table = $command->get('TableName');
        $item  = $command->get('Item');

        // Create an Item object from the 'item' command data
        if (!($item instanceof Item)) {
            $item = new Item($item, $table);
        }

        // Return an instantiated PutRequest object
        return new PutRequest($item, $table);
    }

    /**
     * Constructs a new put request
     *
     * @param Item   $item      The item to put into DynamoDB
     * @param string $tableName The name of the table which has the item
     *
     * @throw InvalidArgumentException if the table name is not provided
     */
    public function __construct(Item $item, $tableName = null)
    {
        $this->item      = $item;
        $this->tableName = $tableName ?: $item->getTableName();

        if (!$this->tableName) {
            throw new InvalidArgumentException('A table name is required to create a PutRequest.');
        }
    }

    /**
     * The parameter form of the request
     *
     * @return array
     */
    public function toArray()
    {
        return array('PutRequest' => array('Item' => $this->item->toArray()));
    }

    /**
     * Get the item
     *
     * @return Item
     */
    public function getItem()
    {
        return $this->item;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { FunctionInfo } from '../models/functions/function-info';
import { BindingInfo, BindingType } from '../models/functions/function-binding';

export class BindingManager {
  public static getHttpTriggerTypeInfo = (functionInfo: FunctionInfo): BindingInfo | undefined => {
    return functionInfo.config && functionInfo.config.bindings
      ? functionInfo.config.bindings.find(e => e.type === BindingType.httpTrigger)
      : undefined;
  };

  public static getWebHookTypeInfo = (functionInfo: FunctionInfo): BindingInfo | undefined => {
    return functionInfo.config && functionInfo.config.bindings ? functionInfo.config.bindings.find(e => !!e.webHookType) : undefined;
  };

  public static getAuthLevelInfo = (functionInfo: FunctionInfo): BindingInfo | undefined => {
    return functionInfo.config && functionInfo.config.bindings ? functionInfo.config.bindings.find(e => !!e.authLevel) : undefined;
  };

  public static getEventGridTriggerInfo = (functionInfo: FunctionInfo): BindingInfo | undefined => {
    return functionInfo.config && functionInfo.config.bindings
      ? functionInfo.config.bindings.find(e => e.type === BindingType.eventGridTrigger)
      : undefined;
  };
}


text:
package com.intellij.codeInsight.daemon.impl;

import com.intellij.codeHighlighting.Pass;
import com.intellij.codeHighlighting.TextEditorHighlightingPass;
import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory;
import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar;
import com.intellij.openapi.components.AbstractProjectComponent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author cdr
*/
public class LineMarkersPassFactory extends AbstractProjectComponent implements TextEditorHighlightingPassFactory {
  public LineMarkersPassFactory(Project project, TextEditorHighlightingPassRegistrar highlightingPassRegistrar) {
    super(project);
    highlightingPassRegistrar.registerTextEditorHighlightingPass(this, null, new int[]{Pass.UPDATE_ALL}, false, Pass.LINE_MARKERS);
  }

  @NonNls
  @NotNull
  public String getComponentName() {
    return "LineMarkersPassFactory";
  }

  @Nullable
  public TextEditorHighlightingPass createHighlightingPass(@NotNull PsiFile file, @NotNull final Editor editor) {
    TextRange textRange = calculateRangeToProcessForSyntaxPass(editor);
    if (textRange == null) return new ProgressableTextEditorHighlightingPass.EmptyPass(myProject, editor.getDocument(), GeneralHighlightingPass.IN_PROGRESS_ICON,
                                                                             GeneralHighlightingPass.PRESENTABLE_NAME);
    return new LineMarkersPass(myProject, file, editor.getDocument(), textRange.getStartOffset(), textRange.getEndOffset(), true);
  }

  @Nullable
  static TextRange calculateRangeToProcessForSyntaxPass(Editor editor) {
    return FileStatusMap.getDirtyTextRange(editor, Pass.UPDATE_ALL);
  }
}


text:
<?php
if (!empty($_REQUEST['page'])){
    $page = $_REQUEST['page'];
}
  //set up the base url for pagination
  $rcopy = $_REQUEST;
  unset($rcopy['page']);
  $end = '?'.http_build_query($rcopy);
  $session_id = session_id();

?>

<?php
   $class = 'inactive';
   $value = 'Search';
   $selected = '';

?>

<form action="<?=URL?>table" method ="GET">
<input type="hidden" name="table" value="<?=$table?>" />
<input type="text" name="q" id="q" class="<?php echo $class?>" value="<?php echo $value?>" />
<select name="column">
<?foreach ($colnames as $col){?>
<option value="<?=$col?>"<?php if ($selected == $col){ echo ' selected="selected"';}?>><?=$col?></option>
<?}?>
</select>
<input type="reset" name="Reset" title="Reset" />
<input type="submit" name="Search" value="Search" title="Reset" />
</form>
 Select Table Columns

<form action="<?=URL?>table" method="get" id="basic-modal-content" class="displaynone">
<fieldset style="border:none">
   <legend>Table columns</legend>
    <input type="hidden" name="table" value="<?=$table?>" />
    <button type="submit" class="btn">Apply</button>
   <?foreach ($colnames as $col){?>

<label class="checkbox" for="<?=$col?>">
           <input <?if (in_array($col, $cols)) echo 'checked="checked" ';?>type="checkbox" value="<?=$col?>" name="tableColumns[]" id="<?=$col?>"><?=$col?>

   <?}?>

   <button type="submit" class="btn">Apply</button>
</fieldset>
</form>

Caption

<?
//copy of request for ordering
$copy_of_request = $_REQUEST;
unset($copy_of_request['PHPSESSID']);
unset($copy_of_request['orderby']);
$copy_of_request_asc = $copy_of_request;
$copy_of_request_desc = $copy_of_request;
foreach ($cols as $col){
    $ascclass = '';
    $descclass = '';
    if(!empty($_REQUEST['orderby']) &&
        $_REQUEST['orderby']==' Order by `'.$col . '` ASC'){
            $ascclass = ' class="active"';
        }
        if(!empty($_REQUEST['orderby']) &&
        $_REQUEST['orderby']==' Order by `'.$col . '` DESC'){
            $descclass= ' class="active"';
        }
    $copy_of_request_asc['orderby'] = ' Order by `'.$col . '` ASC';
    $copy_of_request_desc['orderby'] = ' Order by `'.$col . '` DESC';

    //Refresh

    $asc = '↻';
    $desc = '';
    if ($col != 'id'){
       $asc = '⇑';
       $desc = '⇓';
    }
?>
<?=$asc?>  <?=$col;?>  <?=$desc?>
<?
}
  $i=0;
  foreach($page_data as $object){
     //odd or even class
     $i++;
     if ($i % 2){
         $class= 'odd';
     }else{
         $class = 'even';
    }

?>
  <tr class="<?=$class?>">
  <?

  foreach ($cols as $col){
    //little work around to get the column name right
    //-for spreadsheets with whitespace in the name

    $cell = $object->$col;
    $cellbr = wordwrap($cell, 45, "
\n",true);

    if (preg_match('/^http:/', $cell) || preg_match('/^https:/', $cell)){
      $cellbr = ''.$cellbr.'';
    }
  ?>

<?=$cellbr?>
  <?}?>

<?}?>

table summary

<?

?>

<?

$copy_of_request = $_REQUEST;
unset($copy_of_request['PHPSESSID']);
unset($copy_of_request['page']);
echo $model->paginate(URL.'table?'.http_build_query($copy_of_request), $page, $pages);
?>


text:
(function(util, events, _, log, eco, cfg){

    _.extend(util,{
        callback: function(){
            var
            args = Array.prototype.slice.call(arguments),
            fn   = args.shift();

            if(_.isFunction(fn)) {
                fn.apply(fn, args);
            }
        },
        formatDuration: function(elapsed){
            return util.format('%d sec',(elapsed / 1000));
        },
        formatBenchmark: function(start,end){
            return this.formatDuration((end||new Date()).getTime() - start.getTime());
        },
        // array manipulation functions
        // @see http://stackoverflow.com/questions/1348178/a-better-way-to-splice-an-array-into-an-array-in-javascript
        insertAt: function(array, index) {
            var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
            return util.insertArrayAt(array, index, arrayToInsert);
        },
        insertArrayAt: function(array, index, arrayToInsert) {
            Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
            return array;
        }
    });

    var
    checklist = [
        { name: 'configuration', root: cfg.global, event: 'ready' }
    ];

    function Core() {
        events.EventEmitter.call(this);
        return this;
    }

    // inherit constructor from event emitter.
    util.inherits(Core, events.EventEmitter);

    var
    instance = module.exports = new Core(),
    config = cfg.global,
    onReady = function(){
        instance.emit('ready', instance);
    },
    onError = function(msg){
        instance.emit('error', instance, msg);
    },
    getComponent = function(name){
        var
        comp = require(eco.getPathComponent(name)),
        bootSig = '$__booted$$';

        if(comp[bootSig] === undefined) {

            // on the fly extension of components
            _.extend(comp,{
                isDebugging: log.isDebugging,
                log: log,
                logDebug: log.debug,
                logInfo: log.info,
                logWarn: log.warn,
                logError: log.error
            });

            if(_.isFunction(comp.configure)) {
                comp.configure(eco, config);
            }

            comp[bootSig] = true;
        }

        return comp;
    },
    runChecklist = function(callback){

        var
        checkCount = 0,
        debugging = log.isDebugging(),
        bootMsg = function(clItem, status) {
            return util.format("checklist item '%s' %s", clItem, status);
        };

        if(checklist.length === 0) { // nothing to wait for
            util.callback(callback);
            return;
        }

        _.each(checklist, function(v, i){
            var
            clName = v.name,
            clRoot = v.root,
            clEvent = v.event||'ready';

            if( debugging ) log.debug(bootMsg(clName,'booting..'));

            clRoot.on(clEvent,function(){
                if( debugging ) log.debug(bootMsg(clName,'ready.'));

                checkCount++;

                if( checkCount === checklist.length) {
                    if( debugging ) log.debug('system ready');
                    util.callback(callback);
                }
            });
        });
    };

    _.extend(Core.prototype, {
        boot: function(callback){
            runChecklist(function(){
                onReady();
                util.callback(callback);
            });
        },
        shutdown: function(callback){
            if( this.isDebugging() ) log.debug("shutting down");
            util.callback(callback);
        },
        get: getComponent,

        isDebugging: log.isDebugging,

        debug: log.createDebugFn(),
        info:  log.createInfoFn(),
        warn:  log.createWarnFn(),
        error: log.createErrorFn(),

        getLog: function() {
            return log;
        },
        getEcoSystem: function() {
            return eco;
        },
        getConfig: function() {
            return config;
        }
    });
})(
require('util'),
require('events'),
require('underscore'),
require('./util/log'),
require('./util/eco'),
require('./util/config')
);


text:
"use strict";

const JSONItemHelper = require("./JSONItemHelper.js");
const JSONItemFS = require("./lib/categoriesFS");
const Q = require("q");
const rest = require("./lib/sitesREST").instance;
const SitesFS = require("./lib/sitesFS");
const fS = SitesFS.instance;
const utils = require("./lib/utils/utils.js");
const options = require("./lib/utils/options.js");
const i18n = utils.getI18N(__dirname, ".json", "en");

const singleton = Symbol();
const singletonEnforcer = Symbol();

class SitesHelper extends JSONItemHelper {
    /**
     * The constructor for an SitesHelper object. This constructor implements a singleton pattern, and will fail if
     * called directly. The static instance property can be used to get the singleton instance.
     *
     * @param {Symbol} enforcer - A Symbol that must match a local Symbol to create the new object.
     */
    constructor (enforcer) {
        if (enforcer !== singletonEnforcer) {
            throw i18n.__("singleton_construct_error", {classname: "SitesHelper"});
        }
        super(rest, fS, "sites");
    }

    /**
     * The instance property can be used to to get the singleton instance for this class.
     */
    static get instance() {
        if (!this[singleton]) {
            this[singleton] = new SitesHelper(singletonEnforcer);
        }
        return this[singleton];
    }

    /**
     * Get the context name to use for the given site.
     *
     * @param {Object} siteItem The site for which to get the context name.
     *
     * @returns {String} The context name to use for the given site.
     */
    getSiteContextName(siteItem) {
        return SitesFS.getSiteContextName(siteItem);
    }

    makeEmittedObject(context, item, opts) {
        const result = super.makeEmittedObject(context, item, opts);

        // Add the site's context root and status to the result.
        result.contextRoot = item.contextRoot || "";
        result.status = this.getStatus(context, item, opts);

        return result;
    }

    _makeListItemResult(context, item, opts) {
        const result = super._makeListItemResult(context, item, opts);

        // Add the site's context root and status to the result.
        result.contextRoot = item.contextRoot || "";
        result.status = this.getStatus(context, item, opts);

        return result;
    }

    /**
     * @param {Object} context The API context to be used for this operation.
     * @param {Object} opts - The options to be used for the push operation.
     *
     * @returns {Q.Promise} - A promise that resolves with an array of the names of
     *                      all items that exist on the file system.
     */
    _listLocalItemNames (context, opts) {
        return super._listLocalItemNames(context, opts)
            .then(function (localSites) {
                if (localSites && context.siteList) {
                    // This method will typically return a list of local sites which is limited to those sites contained
                    // in the context site list. For example, when called during a list, push, or compare of sites, the
                    // result should only include a local site if it is also in the context site list. But when called
                    // during a pull of sites "with deletions", the context site list will only contain those sites that
                    // exist on the server. In that case, the list of local sites returned from this method must include
                    // any local sites that do not exist on the server, so that the local site artifact can be deleted.
                    if (options.getRelevantOption(context, opts, "deletions")) {
                        // This is the deletions case. The list of local sites has already been filtered based on ready
                        // and draft options. But if a site option was specified, local sites must also be filtered by
                        // context root. Note that deletion of local site artifacts is not dependent on the site order.
                        const filterSite = options.getRelevantOption(context, opts, "filterSite");
                        localSites = localSites.filter(function (localSite) {
                            // The default site (and any of its drafts) do not have a context root, so the special value
                            // "default" is used for the site option.
                            if (filterSite && filterSite === "default") {
                                // Only include the site in the result if its id matches one of the default sites.
                                return (localSite.id === "default") || localSite.id.startsWith("default:");
                            } else if (filterSite) {
                                // Only include the site in the result if its context root matches the site option.
                                return (localSite.contextRoot === filterSite);
                            } else {
                                // Not filtering by context root, so include the site in the result.
                                return true;
                            }
                        });
                    } else {
                        // This is the typical case. A local site is only included in the result if it is contained in
                        // the context site list. It's important to preserve the order of the context site list, because
                        // certain operations depend on the order.
                        const sortedLocalSites = [];
                        context.siteList.forEach(function (siteItem) {
                            // For each site in the context site list, find the matching site in the list of local sites.
                            const site = localSites.find(function (localSite) {
                                return (localSite.id === siteItem.id);
                            });

                            // If the matching site was found in the list of local sites, add it to the sorted result.
                            if (site) {
                                sortedLocalSites.push(site);
                            }
                        });

                        return sortedLocalSites;
                    }
                }

                return localSites;
            });
    }

    /**
     * Get an array of names for all items on the file system which have been modified since being pushed/pulled.
     *
     * @param {Object} context The API context to be used for this operation.
     * @param {Array} flags An array of the state (NEW, DELETED, MODIFIED) of the items to be included in the list.
     * @param {Object} opts The options to be used for the push operation.
     *
     * @returns {Q.Promise} A promise that resolves with an array of names for all items on the file system which have
     *                      been modified since being pushed/pulled.
     */
    _listModifiedLocalItemNames (context, flags, opts) {
        return super._listModifiedLocalItemNames(context, flags, opts)
            .then(function (localSites) {
                if (localSites && context.siteList) {
                    // Filter the list of local sites to only include those in the context site list. It is important
                    // to preserve the order of the context site list, because certain operations depend on the order.
                    const sortedLocalSites = [];
                    context.siteList.forEach(function (siteItem) {
                        // For each site in the context site list, find the matching site in the list of local sites.
                        const site = localSites.find(function (localSite) {
                            return (localSite.id === siteItem.id);
                        });

                        // If the matching site was found in the list of local sites, add it to the sorted result.
                        if (site) {
                            sortedLocalSites.push(site);
                        }
                    });

                    return sortedLocalSites;
                }
                return localSites;
            });
    }

    /**
     * Filter the given list of items before completing the delete operation.
     *
     * @param {Object} context The API context to be used for this operation.
     * @param {Array} items The items to be deleted.
     * @param {Object} opts The options to be used for this operation.
     *
     * @returns {Array} The filtered list of items to be deleted.
     *
     * @protected
     */
    _deleteFilter (context, items, opts) {
        // DO NOT filter the item list based on the ready and draft options. The sites to be deleted are based on
        // the siteList (defined in the context), which may not align with the filterDraft and filterReady values.

        // Filter out any items that cannot be deleted.
        const self = this;
        items = items.filter(function (item) {
            return self.canDeleteItem(item, true, opts);
        });

        return items;
    }

    /**
     *  Determine whether the given item can be deleted.
     *
     *  @param {Object} item The item to be deleted.
     *  @param {Object} isDeleteAll Flag that indicates whether the item will be deleted during a delete all operation.
     *  @param {Object} opts - The options to be used for the delete operation.
     *
     *  @returns {Boolean} A return value of true indicates that the item can be deleted. A return value of false
     *                     indicates that the item cannot be deleted.
     */
    canDeleteItem(item, isDeleteAll, opts) {
        // Don't delete the default site.
        return super.canDeleteItem(item, isDeleteAll, opts) && item["id"] !== "default" && item["id"] !== "default:draft";
    }

    /**
     * Get the items on the remote content hub.
     *
     * @param {Object} context The API context to be used by the get operation.
     * @param {Object} opts - The options to be used to get the items.
     *
     * @returns {Q.Promise} A promise to get the items on the remote content hub.
     *
     * @resolves {Array} The items on the remote content hub.
     */
    getRemoteItems (context, opts) {
        return super.getRemoteItems(context, opts)
            .then(function (remoteSites) {
                if (remoteSites && context.siteList) {
                    // Filter the list of remote sites to only include those in the context site list. It is important
                    // to preserve the order of the context site list, because certain operations depend on the order.
                    const sortedRemoteSites = [];
                    context.siteList.forEach(function (siteItem) {
                        // For each site in the context site list, find the matching site in the list of remote sites.
                        const site = remoteSites.find(function (remoteSite) {
                            return (remoteSite.id === siteItem.id);
                        });

                        // If the matching site was found in the list of remote sites, add it to the sorted result.
                        if (site) {
                            sortedRemoteSites.push(site);
                        }
                    });

                    return sortedRemoteSites;
                }

                return remoteSites;
            });
    }

    /**
     * Get a list of the items that have been modified.
     *
     * @param {Object} context The API context to be used for this operation.
     * @param {Array} flags - An array of the state (NEW, DELETED, MODIFIED) of the items to be included in the list.
     * @param {Object} opts - The options to be used for this operation.
     *
     * @returns {Q.Promise} - A promise for an array of all remote items that were modified since being pushed/pulled.
     *
     * @resolves {Array} The items on the remote content hub that have been modified.
     */
    getModifiedRemoteItems (context, flags, opts) {
        return super.getModifiedRemoteItems(context, flags, opts)
            .then(function (remoteSites) {
                if (remoteSites && context.siteList) {
                    // Filter the list of remote sites to only include those in the context site list. It is important
                    // to preserve the order of the context site list, because certain operations depend on the order.
                    const sortedRemoteSites = [];
                    context.siteList.forEach(function (siteItem) {
                        // For each site in the context site list, find the matching site in the list of remote sites.
                        const site = remoteSites.find(function (remoteSite) {
                            return (remoteSite.id === siteItem.id);
                        });

                        // If the matching site was found in the list of remote sites, add it to the sorted result.
                        if (site) {
                            sortedRemoteSites.push(site);
                        }
                    });

                    return sortedRemoteSites;
                }
                return remoteSites;
            });
    }

    /**
     * Pull all items from the remote content hub to the local file system.
     *
     * @param {Object} context The API context to be used for this operation.
     * @param {Object} opts The options to be used for the pull operations.
     *
     * @returns {Q.Promise} A promise to pull the remote items to the local file system.
     *
     * @resolves {Array} The items that were pulled.
     */
    pullAllItems(context, opts) {
        // Create a local file path map to be used for cleaning up old files after the pull.
        const map = this._fsApi.createLocalFilePathMap(context, opts);

        // Use a clone of the opts object to store the local file path map, so that it goes away after the call.
        opts = utils.cloneOpts(opts, {"localFilePathMap": map});

        return super.pullAllItems(context, opts);
    }

    /**
     * Pull any modified items from the remote content hub to the local file system.
     *
     * @param {Object} context The API context to be used for this operation.
     * @param {Object} opts - The options to be used for the pull operations.
     *
     * @returns {Q.Promise} A promise to pull the modified remote items to the local file system.
     *
     * @resolves {Array} The modified items that were pulled.
     */
    pullModifiedItems(context, opts) {
        // Create a local file path map to be used for cleaning up old files after the pull.
        const map = this._fsApi.createLocalFilePathMap(context, opts);

        // Use a clone of the opts object to store the local file path map, so that it goes away after the call.
        opts = utils.cloneOpts(opts, {"localFilePathMap": map});

        return super.pullModifiedItems(context, opts);
    }

    /**
     * Push the items with the given names.
     *
     * @param {Object} context The API context to be used by the push operations.
     * @param {Array} names - The names of the items to be pushed.
     * @param {Object} opts - The options to be used for the push operations.
     *
     * @returns {Q.Promise} A promise for the items that were pushed.
     *
     * @override
     * @protected
     */
    _pushNameList(context, names, opts) {
        const helper = this;

        // Bind the super method so that we can call it later.
        const superMethod = super._pushNameList.bind(this);

        // Enable the local file cache so that the sites being pushed are only read once.
        JSONItemFS.setCacheEnabled(context, true, opts);

        return Q.all(names.map(function (name) {
            return helper.getLocalItem(context, name, opts);
        }))
            .then(function (items) {
                // Sort sites by status -- ready before draft.
                items.sort(function (a, b) {
                    const aStatus = helper.getStatus(context, a, opts);
                    const bStatus = helper.getStatus(context, b, opts);
                    if (aStatus === "ready") {
                        if (bStatus === "ready") {
                            // Ready site a goes after ready site b to maintain original order.
                            return 1;
                        } else {
                            // Ready site goes before draft site.
                            return -1;
                        }
                    } else {
                        // Draft site goes to the end, after ready sites and to maintain original order of draft sites.
                        return 1;
                    }
                });

                // Push the sorted sites one at a time.
                names = items.map(function (item) {
                    return SitesFS.getSiteContextName(item);
                });

                // Call the super class method to do the push.
                return superMethod(context, names, opts);
            })
            .finally(function () {
                // Disable the local file cache once the push operation has completed.
                JSONItemFS.setCacheEnabled(context, false, opts);
            });
    }
}

/**
 * Export the SitesHelper class.
 */
module.exports = SitesHelper;


text:
<?php

namespace app\framework\Component\Image\Bridge\Filter\Basic;

use app\framework\Component\Image\Bridge\Filter\FilterInterface;
use app\framework\Component\Image\Bridge\Image\ImageInterface;

/**
 * A copy filter
 */
class Copy implements FilterInterface
{
    /**
     * {@inheritdoc}
     */
    public function apply(ImageInterface $image)
    {
        return $image->copy();
    }
}


text:
/* $Id$ */

package org.apache.fop.afp.goca;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.fop.afp.util.BinaryUtils;

/**
 * A base class encapsulating the structure of coordinate based GOCA objects
 */
public abstract class AbstractGraphicsCoord extends AbstractGraphicsDrawingOrder {

    /** array of x/y coordinates */
    protected int[] coords;

    /** if true, then uses relative drawing order */
    protected boolean relative;

    /**
     * Constructor
     *
     * @param coords the x/y coordinates for this object
     */
    public AbstractGraphicsCoord(int[] coords) {
        if (coords == null) {
            relative = true;
        } else {
            this.coords = coords;
        }
    }

    /**
     * Constructor
     *
     * @param coords the x/y coordinates for this object
     * @param relative true if relative drawing order
     */
    public AbstractGraphicsCoord(int[] coords, boolean relative) {
        this(coords);
        this.relative = relative;
    }

    /**
     * Constructor
     *
     * @param x the x coordinate for this object
     * @param y the y coordinate for this object
     */
    public AbstractGraphicsCoord(int x, int y) {
        this(new int[] {x, y});
    }

    /**
     * Constructor
     *
     * @param x1 the x1 coordinate for this object
     * @param y1 the y1 coordinate for this object
     * @param x2 the x2 coordinate for this object
     * @param y2 the y2 coordinate for this object
     */
    public AbstractGraphicsCoord(int x1, int y1, int x2, int y2) {
        this(new int[] {x1, y1, x2, y2});
    }

    /** {@inheritDoc} */
    public int getDataLength() {
        return 2 + (coords != null ? coords.length * 2 : 0);
    }

    /**
     * Returns the coordinate data start index
     *
     * @return the coordinate data start index
     */
    int getCoordinateDataStartIndex() {
        return 2;
    }

    /**
     * Returns the coordinate data
     *
     * @return the coordinate data
     */
    byte[] getData() {
        byte[] data = super.getData();
        if (coords != null) {
            addCoords(data, getCoordinateDataStartIndex());
        }
        return data;
    }

    /** {@inheritDoc} */
    public void writeToStream(OutputStream os) throws IOException {
        os.write(getData());
    }

    /**
     * Adds the coordinates to the structured field data
     *
     * @param data the structured field data
     * @param fromIndex the start index
     */
    protected void addCoords(byte[] data, int fromIndex) {
        // X/Y POS
        for (int i = 0; i < coords.length; i++, fromIndex += 2) {
            byte[] coord = BinaryUtils.convert(coords[i], 2);
            data[fromIndex] = coord[0];
            data[fromIndex + 1] = coord[1];
        }
    }

    /** {@inheritDoc} */
    public String toString() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < coords.length; i++) {
            if (sb.length() > 0) {
                sb.append(',');
            }
            sb.append((i % 2 == 0) ? 'x' : 'y');
            sb.append(i / 2);
            sb.append('=');
            sb.append(coords[i]);
        }
        return getName() + "{" + sb + "}";
    }

    /**
     * Returns true if this is a relative drawing order
     *
     * @return true if this is a relative drawing order
     */
    protected boolean isRelative() {
        return this.relative;
    }
}


text:
:: Defect analysis and prediction
:: AJE
java -jar bugc.jar --format=defect:aje.out --bugpattern=.\pat\bugpattern_aje.xml --issues .\input\issues\softco --commits .\input\commits\softco\aje
:: RVS
java -jar bugc.jar --format=defect:rvs.out --bugpattern=.\pat\bugpattern_rvs.xml --issues .\input\issues\hbs --commits .\input\commits\hbs\rvs
:: GIC
java -jar bugc.jar --format=defect:gic.out --bugpattern=.\pat\bugpattern_gic.xml --issues .\input\issues\ecc\gic --commits .\input\commits\ecc\gic
:: OHC
java -jar bugc.jar --format=defect:ohc.out --bugpattern=.\pat\bugpattern_ohc.xml --issues .\input\issues\ecc\ohc --commits .\input\commits\ecc\ohc
:: WHIC
java -jar bugc.jar --format=defect:whic.out --bugpattern=.\pat\bugpattern_whic.xml --issues .\input\issues\ecc\whic --commits .\input\commits\ecc\whic


text:
using Ninject.Extensions.Interception;
using Ninject.Extensions.Interception.Attributes;
using Ninject.Extensions.Interception.Request;

namespace FunWithNinject.Interception
{
    public class SetReturnValueAttribute : InterceptAttribute
    {
        private readonly int _returnValue;

        public SetReturnValueAttribute(int returnValue)
        {
            _returnValue = returnValue;
        }

        public override IInterceptor CreateInterceptor(IProxyRequest request)
        {
            return new OverrideReturnInterceptor<int>(_returnValue);
        }
    }
}


text:
@interface MainPageViewController () <UIPageViewControllerDelegate, UIPageViewControllerDataSource>
@property (nonatomic, strong) UIImageView *blurredImageView;
@end

@implementation MainPageViewController

@synthesize modelArray;
@synthesize pageViewController;

#pragma mark - UIPageViewControllerDataSource Methods

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSUInteger currentIndex = [self.modelArray indexOfObject:[(WXWeatherViewController *)viewController label]];

    if(currentIndex == 0)
    {
        [self.segmentControl setSelectedSegmentIndex:0];
        return nil;
    } else {
        [self.segmentControl setSelectedSegmentIndex:currentIndex];
    }
    WXWeatherViewController *weatherViewController = [[WXWeatherViewController alloc] init];
    weatherViewController.label = [self.modelArray objectAtIndex:currentIndex - 1];

    return weatherViewController;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
       viewControllerAfterViewController:(UIViewController *)viewController
{
    NSUInteger currentIndex = [self.modelArray indexOfObject:[(WXWeatherViewController *)viewController label]];
    if(currentIndex == self.modelArray.count-1)
    {
        return nil;
    }
    WXWeatherViewController *weatherViewController = [[WXWeatherViewController alloc] init];
    weatherViewController.label = [self.modelArray objectAtIndex:currentIndex+1];

    return weatherViewController;
}

#pragma mark - UIPageViewControllerDelegate Methods

- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController
                   spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    if(UIInterfaceOrientationIsPortrait(orientation))
    {
        //Set the array with only 1 view controller
        UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
        NSArray *viewControllers = [NSArray arrayWithObject:currentViewController];
        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

        //Important- Set the doubleSided property to NO.
        self.pageViewController.doubleSided = NO;
        //Return the spine location
        return UIPageViewControllerSpineLocationMin;
    }
    else
    {
        NSArray *viewControllers = nil;
        WXWeatherViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];

        NSUInteger currentIndex = [self.modelArray indexOfObject:[(WXWeatherViewController *)currentViewController label]];
        if(currentIndex == 0 || currentIndex %2 == 0)
        {
            UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController];
            viewControllers = [NSArray arrayWithObjects:currentViewController, nextViewController, nil];
        }
        else
        {
            UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController];
            viewControllers = [NSArray arrayWithObjects:previousViewController, currentViewController, nil];
        }
        //Now, set the viewControllers property of UIPageViewController
        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

        return UIPageViewControllerSpineLocationMid;
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *background = [UIImage imageNamed: @"outfit-1_Fotor"];

    //3
    self.blurredImageView = [[UIImageView alloc] init];
    self.blurredImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.blurredImageView.alpha = 1.0;
    [self.blurredImageView setImageToBlur:background blurRadius:10 completionBlock:nil];
    [self.view addSubview:self.blurredImageView];

    //Instantiate the model array
    NSMutableArray *array = [[NSMutableArray alloc] init];

    for (int index = 1; index <= 2 ; index++)
    {
        [array addObject:[NSString stringWithFormat:@"Page %d",index]];
    }

    self.modelArray = [NSArray arrayWithArray:array];

    //Step 1
    //Instantiate the UIPageViewController.
    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                                              navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];

    //Step 2:
    //Assign the delegate and datasource as self.
    self.pageViewController.delegate = self;
    self.pageViewController.dataSource = self;

    //Step 3:
    //Set the initial view controllers.
    WXWeatherViewController *weatherViewController = [[WXWeatherViewController alloc] init];
    weatherViewController.label = @"Page 1";
    weatherViewController.isHourly = [NSNumber numberWithBool:YES];

    NSArray *viewControllers = [NSArray arrayWithObject:weatherViewController];
    [self.pageViewController setViewControllers:viewControllers
                                      direction:UIPageViewControllerNavigationDirectionForward
                                       animated:NO
                                     completion:nil];

    //Step 4:
    //ViewController containment steps
    //Add the pageViewController as the childViewController
    [self addChildViewController:self.pageViewController];

    //Add the view of the pageViewController to the current view
    [self.view addSubview:self.pageViewController.view];

    //Call didMoveToParentViewController: of the childViewController, the UIPageViewController instance in our case.
    [self.pageViewController didMoveToParentViewController:self];

    //Step 5:
    // set the pageViewController's frame as an inset rect.
//    CGRect pageViewRect = self.view.bounds;
//    pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0);
//    self.pageViewController.view.frame = pageViewRect;

    //Step 6:
    //Assign the gestureRecognizers property of our pageViewController to our view's gestureRecognizers property.
    self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;

}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

-(void) viewWillLayoutSubviews{
    [super viewDidLayoutSubviews];

    CGRect bounds = self.view.bounds;
    self.blurredImageView.frame = bounds;
}

@end


text:
export CFLAGS_BASE =
export LDFLAGS_BASE =

ifdef TRAVIS
CFLAGS_BASE += -coverage -fprofile-arcs -ftest-coverage
LDFLAGS_BASE += -fprofile-arcs
endif

build:
	mkdir libs header -p
	$(MAKE) -C logkit
	$(MAKE) -C configkit
	$(MAKE) -C commandkit
	$(MAKE) -C processkit

install:
	sudo mkdir -p /usr/include/jetspace/
	sudo cp header/* /usr/include/jetspace/
	sudo cp libs/* /usr/lib/

test:
	make runtests -C tests


text:
package org.opensaml.xml.encryption.impl;

import org.opensaml.xml.XMLObject;
import org.opensaml.xml.encryption.ReferenceType;
import org.opensaml.xml.io.UnmarshallingException;
import org.w3c.dom.Attr;

/**
 * A thread-safe Unmarshaller for {@link org.opensaml.xml.encryption.ReferenceType} objects.
 */
public class ReferenceTypeUnmarshaller extends AbstractXMLEncryptionUnmarshaller {

    /** {@inheritDoc} */
    protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException {
        ReferenceType rt = (ReferenceType) xmlObject;

        if (attribute.getLocalName().equals(ReferenceType.URI_ATTRIB_NAME)) {
            rt.setURI(attribute.getValue());
        } else {
            super.processAttribute(xmlObject, attribute);
        }
    }

    /** {@inheritDoc} */
    protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject)
            throws UnmarshallingException {
        ReferenceType rt = (ReferenceType) parentXMLObject;

        rt.getUnknownXMLObjects().add(childXMLObject);
    }

}