text:
<?php

/**
 * Catalog rule indexer
 *
 * @category    Mage
 * @package     Mage_CatalogRule
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_CatalogRule_Model_Action_Index_Refresh
{
    /**
     * Connection instance
     *
     * @var Varien_Db_Adapter_Interface
     */
    protected $_connection;

    /**
     * Core factory instance
     *
     * @var Mage_Core_Model_Factory
     */
    protected $_factory;

    /**
     * Resource instance
     *
     * @var Mage_Core_Model_Resource_Db_Abstract
     */
    protected $_resource;

    /**
     * Application instance
     *
     * @var Mage_Core_Model_App
     */
    protected $_app;

    /**
     * Constructor with parameters
     * Array of arguments with keys
     *  - 'connection' Varien_Db_Adapter_Interface
     *  - 'factory' Mage_Core_Model_Factory
     *  - 'resource' Mage_Core_Model_Resource_Db_Abstract
     *  - 'app' Mage_Core_Model_App
     *
     * @param array $args
     */
    public function __construct(array $args)
    {
        $this->_setConnection($args['connection']);
        $this->_setFactory($args['factory']);
        $this->_setResource($args['resource']);
        $this->_app = !empty($args['app']) ? $args['app'] : Mage::app();
    }

    /**
     * Set connection
     *
     * @param Varien_Db_Adapter_Interface $connection
     */
    protected function _setConnection(Varien_Db_Adapter_Interface $connection)
    {
        $this->_connection = $connection;
    }

    /**
     * Set factory
     *
     * @param Mage_Core_Model_Factory $factory
     */
    protected function _setFactory(Mage_Core_Model_Factory $factory)
    {
        $this->_factory = $factory;
    }

    /**
     * Set resource
     *
     * @param Mage_Core_Model_Resource_Db_Abstract $resource
     */
    protected function _setResource(Mage_Core_Model_Resource_Db_Abstract $resource)
    {
        $this->_resource = $resource;
    }

    /**
     * Run reindex
     */
    public function execute()
    {
        $this->_app->dispatchEvent('catalogrule_before_apply', array('resource' => $this->_resource));

        /** @var $coreDate Mage_Core_Model_Date */
        $coreDate  = $this->_factory->getModel('core/date');
        $timestamp = $coreDate->gmtTimestamp('Today');

        foreach ($this->_app->getWebsites(false) as $website) {
            /** @var $website Mage_Core_Model_Website */
            if ($website->getDefaultStore()) {
                $this->_reindex($website, $timestamp);
            }
        }

        $this->_prepareGroupWebsite($timestamp);
        $this->_prepareAffectedProduct();
    }

    /**
     * Return temporary table name
     *
     * @return string
     */
    protected function _getTemporaryTable()
    {
        return $this->_resource->getTable('catalogrule/rule_product_price_tmp');
    }

    /**
     * Create temporary table
     */
    protected function _createTemporaryTable()
    {
        $this->_connection->dropTemporaryTable($this->_getTemporaryTable());
        $table = $this->_connection->newTable($this->_getTemporaryTable())
            ->addColumn(
                'grouped_id',
                Varien_Db_Ddl_Table::TYPE_VARCHAR,
                80,
                array(),
                'Grouped ID'
            )
            ->addColumn(
                'product_id',
                Varien_Db_Ddl_Table::TYPE_INTEGER,
                null,
                array(
                    'unsigned' => true
                ),
                'Product ID'
            )
            ->addColumn(
                'customer_group_id',
                Varien_Db_Ddl_Table::TYPE_SMALLINT,
                5,
                array(
                    'unsigned' => true
                ),
                'Customer Group ID'
            )
            ->addColumn(
                'from_date',
                Varien_Db_Ddl_Table::TYPE_DATE,
                null,
                array(),
                'From Date'
            )
            ->addColumn(
                'to_date',
                Varien_Db_Ddl_Table::TYPE_DATE,
                null,
                array(),
                'To Date'
            )
            ->addColumn(
                'action_amount',
                Varien_Db_Ddl_Table::TYPE_DECIMAL,
                '12,4',
                array(),
                'Action Amount'
            )
            ->addColumn(
                'action_operator',
                Varien_Db_Ddl_Table::TYPE_VARCHAR,
                10,
                array(),
                'Action Operator'
            )
            ->addColumn(
                'action_stop',
                Varien_Db_Ddl_Table::TYPE_SMALLINT,
                6,
                array(),
                'Action Stop'
            )
            ->addColumn(
                'sort_order',
                Varien_Db_Ddl_Table::TYPE_INTEGER,
                10,
                array(
                    'unsigned' => true
                ),
                'Sort Order'
            )
            ->addColumn(
                'price',
                Varien_Db_Ddl_Table::TYPE_DECIMAL,
                '12,4',
                array(),
                'Product Price'
            )
            ->addColumn(
                'rule_product_id',
                Varien_Db_Ddl_Table::TYPE_INTEGER,
                null,
                array(
                    'unsigned' => true
                ),
                'Rule Product ID'
            )
            ->addColumn(
                'from_time',
                Varien_Db_Ddl_Table::TYPE_INTEGER,
                null,
                array(
                    'unsigned' => true,
                    'nullable' => true,
                    'default'  => 0,
                ),
                'From Time'
            )
            ->addColumn(
                'to_time',
                Varien_Db_Ddl_Table::TYPE_INTEGER,
                null,
                array(
                    'unsigned' => true,
                    'nullable' => true,
                    'default'  => 0,
                ),
                'To Time'
            )
            ->addIndex(
                $this->_connection->getIndexName($this->_getTemporaryTable(), 'grouped_id'),
                array('grouped_id')
            )
            ->setComment('CatalogRule Price Temporary Table');
        $this->_connection->createTemporaryTable($table);
    }

    /**
     * Prepare temporary data
     *
     * @param Mage_Core_Model_Website $website
     * @return Varien_Db_Select
     */
    protected function _prepareTemporarySelect(Mage_Core_Model_Website $website)
    {
        /** @var $catalogFlatHelper Mage_Catalog_Helper_Product_Flat */
        $catalogFlatHelper = $this->_factory->getHelper('catalog/product_flat');

        /** @var $eavConfig Mage_Eav_Model_Config */
        $eavConfig = $this->_factory->getSingleton('eav/config');
        $priceAttribute = $eavConfig->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'price');

        $select = $this->_connection->select()
            ->from(
                array('rp' => $this->_resource->getTable('catalogrule/rule_product')),
                array()
            )
            ->joinInner(
                array('r' => $this->_resource->getTable('catalogrule/rule')),
                'r.rule_id = rp.rule_id',
                array()
            )
            ->where('rp.website_id = ?', $website->getId())
            ->order(
                array('rp.product_id', 'rp.customer_group_id', 'rp.sort_order', 'rp.rule_product_id')
            )
            ->joinLeft(
                array(
                    'pg' => $this->_resource->getTable('catalog/product_attribute_group_price')
                ),
                'pg.entity_id = rp.product_id AND pg.customer_group_id = rp.customer_group_id'
                    . ' AND pg.website_id = rp.website_id',
                array()
            )
            ->joinLeft(
                array(
                    'pgd' => $this->_resource->getTable('catalog/product_attribute_group_price')
                ),
                'pgd.entity_id = rp.product_id AND pgd.customer_group_id = rp.customer_group_id'
                    . ' AND pgd.website_id = 0',
                array()
            );

        $storeId = $website->getDefaultStore()->getId();

        if ($catalogFlatHelper->isEnabled() && $storeId && $catalogFlatHelper->isBuilt($storeId)) {
            $select->joinInner(
                array('p' => $this->_resource->getTable('catalog/product_flat') . '_' . $storeId),
                'p.entity_id = rp.product_id',
                array()
            );
            $priceColumn = $this->_connection->getIfNullSql(
                $this->_connection->getIfNullSql(
                    $this->_connection->getCheckSql(
                        'pg.is_percent = 1',
                        'p.price * (100 - pg.value)/100',
                        'pg.value'
                    ),
                    $this->_connection->getCheckSql(
                        'pgd.is_percent = 1',
                        'p.price * (100 - pgd.value)/100',
                        'pgd.value'
                    )
                ),
                'p.price'
            );
        } else {
            $select->joinInner(
                    array(
                        'pd' => $this->_resource->getTable(array('catalog/product', $priceAttribute->getBackendType()))
                    ),
                    'pd.entity_id = rp.product_id AND pd.store_id = 0 AND pd.attribute_id = '
                        . $priceAttribute->getId(),
                    array()
                )
                ->joinLeft(
                    array(
                        'p' => $this->_resource->getTable(array('catalog/product', $priceAttribute->getBackendType()))
                    ),
                    'p.entity_id = rp.product_id AND p.store_id = ' . $storeId
                        . ' AND p.attribute_id = pd.attribute_id',
                    array()
                );
            $priceColumn = $this->_connection->getIfNullSql(
                $this->_connection->getIfNullSql(
                    $this->_connection->getCheckSql(
                        'pg.is_percent = 1',
                        $this->_connection->getIfNullSql(
                            'p.value',
                            'pd.value'
                        ) . ' * (100 - pg.value)/100',
                        'pg.value'
                    ),
                    $this->_connection->getCheckSql(
                        'pgd.is_percent = 1',
                        $this->_connection->getIfNullSql(
                            'p.value',
                            'pd.value'
                        ) . ' * (100 - pgd.value)/100',
                        'pgd.value'
                    )
                ),
                $this->_connection->getIfNullSql(
                    'p.value',
                    'pd.value'
                )
            );
        }

        $select->columns(
            array(
                'grouped_id' => $this->_connection->getConcatSql(
                    array('rp.product_id', 'rp.customer_group_id'),
                    '-'
                ),
                'product_id'        => 'rp.product_id',
                'customer_group_id' => 'rp.customer_group_id',
                'from_date'         => 'r.from_date',
                'to_date'           => 'r.to_date',
                'action_amount'     => 'rp.action_amount',
                'action_operator'   => 'rp.action_operator',
                'action_stop'       => 'rp.action_stop',
                'sort_order'        => 'rp.sort_order',
                'price'             => $priceColumn,
                'rule_product_id'   => 'rp.rule_product_id',
                'from_time'         => 'rp.from_time',
                'to_time'           => 'rp.to_time'
            )
        );

        return $select;
    }

    /**
     * Prepare price column
     *
     * @return Zend_Db_Expr
     */
    protected function _calculatePrice()
    {
        $toPercent = $this->_connection->quote('to_percent');
        $byPercent = $this->_connection->quote('by_percent');
        $toFixed   = $this->_connection->quote('to_fixed');
        $byFixed   = $this->_connection->quote('by_fixed');
        $nA        = $this->_connection->quote('N/A');

        return $this->_connection->getCaseSql(
            '',
            array(
                $this->_connection->getIfNullSql(
                    new Zend_Db_Expr('@group_id'), $nA
                ) . ' != cppt.grouped_id' =>
                '@price := ' . $this->_connection->getCaseSql(
                    $this->_connection->quoteIdentifier('cppt.action_operator'),
                    array(
                        $toPercent => new Zend_Db_Expr('cppt.price * cppt.action_amount/100'),
                        $byPercent => new Zend_Db_Expr('cppt.price * (1 - cppt.action_amount/100)'),
                        $toFixed   => $this->_connection->getCheckSql(
                            new Zend_Db_Expr('cppt.action_amount < cppt.price'),
                            new Zend_Db_Expr('cppt.action_amount'),
                            new Zend_Db_Expr('cppt.price')
                        ),
                        $byFixed   => $this->_connection->getCheckSql(
                            new Zend_Db_Expr('0 > cppt.price - cppt.action_amount'),
                            new Zend_Db_Expr('0'),
                            new Zend_Db_Expr('cppt.price - cppt.action_amount')
                        ),
                    )
                ),
                $this->_connection->getIfNullSql(
                    new Zend_Db_Expr('@group_id'), $nA
                ) . ' = cppt.grouped_id AND '
                . $this->_connection->getIfNullSql(
                    new Zend_Db_Expr('@action_stop'),
                    new Zend_Db_Expr(0)
                ) . ' = 0' => '@price := ' . $this->_connection->getCaseSql(
                    $this->_connection->quoteIdentifier('cppt.action_operator'),
                    array(
                        $toPercent => new Zend_Db_Expr('@price * cppt.action_amount/100'),
                        $byPercent => new Zend_Db_Expr('@price * (1 - cppt.action_amount/100)'),
                        $toFixed   => $this->_connection->getCheckSql(
                            new Zend_Db_Expr('cppt.action_amount < @price'),
                            new Zend_Db_Expr('cppt.action_amount'),
                            new Zend_Db_Expr('@price')
                        ),
                        $byFixed   => $this->_connection->getCheckSql(
                            new Zend_Db_Expr('0 > @price - cppt.action_amount'),
                            new Zend_Db_Expr('0'),
                            new Zend_Db_Expr('@price - cppt.action_amount')
                        ),
                    )
                )
            ),
            '@price := @price'
        );
    }

    /**
     * Prepare index select
     *
     * @param Mage_Core_Model_Website $website
     * @param $time
     * @return Varien_Db_Select
     */
    protected function _prepareIndexSelect(Mage_Core_Model_Website $website, $time)
    {
        $nA = $this->_connection->quote('N/A');
        $this->_connection->query('SET @price := 0');
        $this->_connection->query('SET @group_id := NULL');
        $this->_connection->query('SET @action_stop := NULL');

        $indexSelect = $this->_connection->select()
            ->from(array('cppt' => $this->_getTemporaryTable()), array())
            ->order(array('cppt.grouped_id', 'cppt.sort_order', 'cppt.rule_product_id'))
            ->columns(
                array(
                    'customer_group_id' => 'cppt.customer_group_id',
                    'product_id'        => 'cppt.product_id',
                    'rule_price'        => $this->_calculatePrice(),
                    'latest_start_date' => 'cppt.from_date',
                    'earliest_end_date' => 'cppt.to_date',
                    new Zend_Db_Expr(
                        $this->_connection->getCaseSql(
                            '',
                            array(
                                $this->_connection->getIfNullSql(
                                    new Zend_Db_Expr('@group_id'),
                                    $nA
                                ) . ' != cppt.grouped_id' => new Zend_Db_Expr('@action_stop := cppt.action_stop'),
                                $this->_connection->getIfNullSql(
                                    new Zend_Db_Expr('@group_id'),
                                    $nA
                                ) . ' = cppt.grouped_id' => '@action_stop := '
                                    . $this->_connection->getIfNullSql(
                                        new Zend_Db_Expr('@action_stop'),
                                        new Zend_Db_Expr(0)
                                    ) . ' + cppt.action_stop',
                            )
                        )
                    ),
                    new Zend_Db_Expr('@group_id := cppt.grouped_id'),
                    'from_time'         => 'cppt.from_time',
                    'to_time'           => 'cppt.to_time'
                )
            );

        $select = $this->_connection->select()
            ->from($indexSelect, array())
            ->joinInner(
                array(
                    'dates' => $this->_connection->select()->union(
                        array(
                            new Zend_Db_Expr(
                                'SELECT ' . $this->_connection->getDateAddSql(
                                    $this->_connection->fromUnixtime($time),
                                    -1,
                                    Varien_Db_Adapter_Interface::INTERVAL_DAY
                                ) . ' AS rule_date'
                            ),
                            new Zend_Db_Expr('SELECT ' . $this->_connection->fromUnixtime($time) . ' AS rule_date'),
                            new Zend_Db_Expr(
                                'SELECT ' . $this->_connection->getDateAddSql(
                                    $this->_connection->fromUnixtime($time),
                                    1,
                                    Varien_Db_Adapter_Interface::INTERVAL_DAY
                                ) . ' AS rule_date'
                            ),
                        )
                    )
                ),
                '1=1',
                array()
            )
            ->columns(
                array(
                    'rule_product_price_id' => new Zend_Db_Expr('NULL'),
                    'rule_date'             => 'dates.rule_date',
                    'customer_group_id'     => 'customer_group_id',
                    'product_id'            => 'product_id',
                    'rule_price'            => 'MIN(rule_price)',
                    'website_id'            => new Zend_Db_Expr($website->getId()),
                    'latest_start_date'     => 'latest_start_date',
                    'earliest_end_date'     => 'earliest_end_date',
                )
            )
            ->where(new Zend_Db_Expr($this->_connection->getUnixTimestamp('dates.rule_date') . " >= from_time"))
            ->where(
                $this->_connection->getCheckSql(
                    new Zend_Db_Expr('to_time = 0'),
                    new Zend_Db_Expr(1),
                    new Zend_Db_Expr($this->_connection->getUnixTimestamp('dates.rule_date') . " <= to_time")
                )
            )
            ->group(array('customer_group_id', 'product_id', 'dates.rule_date'));

        return $select;
    }

    /**
     * Remove old index data
     *
     * @param Mage_Core_Model_Website $website
     */
    protected function _removeOldIndexData(Mage_Core_Model_Website $website)
    {
        $this->_connection->delete(
            $this->_resource->getTable('catalogrule/rule_product_price'),
            array('website_id = ?' => $website->getId())
        );
    }

    /**
     * Fill Index Data
     *
     * @param Mage_Core_Model_Website $website
     * @param int $time
     */
    protected function _fillIndexData(Mage_Core_Model_Website $website, $time)
    {
        $this->_connection->query(
            $this->_connection->insertFromSelect(
                $this->_prepareIndexSelect($website, $time),
                $this->_resource->getTable('catalogrule/rule_product_price')
            )
        );
    }

    /**
     * Reindex catalog prices by website for timestamp
     *
     * @param Mage_Core_Model_Website $website
     * @param int $timestamp
     */
    protected function _reindex(Mage_Core_Model_Website $website, $timestamp)
    {
        $this->_createTemporaryTable();
        $this->_connection->query(
            $this->_connection->insertFromSelect(
                $this->_prepareTemporarySelect($website),
                $this->_getTemporaryTable()
            )
        );
        $this->_removeOldIndexData($website);
        $this->_fillIndexData($website, $timestamp);
    }

    /**
     * Prepare data for group website relation
     */
    protected function _prepareGroupWebsite($timestamp)
    {
        $this->_connection->delete($this->_resource->getTable('catalogrule/rule_group_website'), array());
        $select = $this->_connection->select()
            ->distinct(true)
            ->from(
                $this->_resource->getTable('catalogrule/rule_product'),
                array('rule_id', 'customer_group_id', 'website_id')
            )
            ->where(new Zend_Db_Expr("{$timestamp} >= from_time"))
            ->where(
                $this->_connection->getCheckSql(
                    new Zend_Db_Expr('to_time = 0'),
                    new Zend_Db_Expr(1),
                    new Zend_Db_Expr("{$timestamp} <= to_time")
                )
            );
        $query = $select->insertFromSelect($this->_resource->getTable('catalogrule/rule_group_website'));
        $this->_connection->query($query);
    }

    /**
     * Return data for affected product
     *
     * @return null
     */
    protected function _getProduct()
    {
        return null;
    }

    /**
     * Prepare affected product
     */
    protected function _prepareAffectedProduct()
    {
        /** @var $modelCondition Mage_Catalog_Model_Product_Condition */
        $modelCondition = $this->_factory->getModel('catalog/product_condition');

        $productCondition = $modelCondition->setTable($this->_resource->getTable('catalogrule/affected_product'))
            ->setPkFieldName('product_id');

            $this->_app->dispatchEvent(
                'catalogrule_after_apply',
                array(
                    'product' => $this->_getProduct(),
                    'product_condition' => $productCondition
                )
            );

        $this->_connection->delete($this->_resource->getTable('catalogrule/affected_product'));
    }
}


text:
from django.conf.urls import url
from . import views

urlpatterns = [
	url(r'^new-marker/$', views.new_marker, name='new_marker'),
	url(r'^get-markers/$', views.get_all_markers, name='get_all_markers'),
]

redpajama_set_name: RedPajamaGithub


text:
package MongoDB::Collection;

# ABSTRACT: A MongoDB Collection

use version;
our $VERSION = 'v0.703.5'; # TRIAL

use Tie::IxHash;
use Carp 'carp';
use boolean;
use Try::Tiny;
use Moose;
use namespace::clean -except => 'meta';

has _database => (
    is       => 'ro',
    isa      => 'MongoDB::Database',
    required => 1,
);

has name => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,
);

has full_name => (
    is      => 'ro',
    isa     => 'Str',
    lazy    => 1,
    builder => '_build_full_name',
);

sub _build_full_name {
    my ($self) = @_;
    my $name    = $self->name;
    my $db_name = $self->_database->name;
    return "${db_name}.${name}";
}

sub get_collection {
    my $self = shift @_;
    my $coll = shift @_;

    return $self->_database->get_collection($self->name.'.'.$coll);
}

sub to_index_string {
    my $keys = shift;

    my @name;
    if (ref $keys eq 'ARRAY') {
        @name = @$keys;
    }
    elsif (ref $keys eq 'HASH' ) {
        @name = %$keys
    }
    elsif (ref $keys eq 'Tie::IxHash') {
        my @ks = $keys->Keys;
        my @vs = $keys->Values;

        for (my $i=0; $i<$keys->Length; $i++) {
            push @name, $ks[$i];
            push @name, $vs[$i];
        }
    }
    else {
        confess 'expected Tie::IxHash, hash, or array reference for keys';
    }

    return join("_", @name);
}

sub _select_cursor_client {
    my ($conn, $ns, $query) = @_;

    return $conn if !$conn->_readpref_pinned || !$conn->find_master;
    return $conn->_master if _cmd_primary_only($ns, $query);
    return $conn->_readpref_pinned;
}

sub _cmd_primary_only {
    my ($ns, $query) = @_;

    # these commands allow read preferences
    my %readpref_commands = (
        'group' => 1,
        'aggregate' => 1,
        'mapreduce' => 1,
        'collstats' => 1,
        'dbstats' => 1,
        'count' => 1,
        'distinct' => 1,
        'geonear' => 1,
        'geosearch' => 1,
        'geowalk' => 1,
        'text' => 1
    );

    if ($ns =~ /\$cmd/) {
        foreach (keys %{$query}) {
            return 0 if $readpref_commands{lc($_)};
        }
        return 1;
    }
    else {
        return 0;
    }
}

sub find {
    my ($self, $query, $attrs) = @_;
    # old school options - these should be set with MongoDB::Cursor methods
    my ($limit, $skip, $sort_by) = @{ $attrs || {} }{qw/limit skip sort_by/};

    $limit   ||= 0;
    $skip    ||= 0;

    my $conn = $self->_database->_client;
    my $q = $query || {};
    my $ns = $self->full_name;

    my $slave_ok = ($conn->_readpref_mode == MongoDB::MongoClient->PRIMARY) ||
                   _cmd_primary_only($ns, $q)
                   ? 0 : 1;

    my $cursor = MongoDB::Cursor->new(
        _master    => $conn,
        _client    => _select_cursor_client($conn, $ns, $q),
        _ns        => $ns,
        _query     => $q,
        _limit     => $limit,
        _skip      => $skip,
        slave_okay => $slave_ok
    );

    # add readpref info if connected to mongos
    if ($conn->_readpref_pinned && $conn->_is_mongos && !_cmd_primary_only($ns, $q)) {
        my $modeName = MongoDB::MongoClient->_READPREF_MODENAMES->[$conn->_readpref_mode];
        $cursor->_add_readpref({mode => $modeName, tags => $conn->_readpref_tagsets});
    }

    $cursor->_init;
    if ($sort_by) {
        $cursor->sort($sort_by);
    }
    return $cursor;
}

sub query {
    my ($self, $query, $attrs) = @_;

    return $self->find($query, $attrs);
}

sub find_one {
    my ($self, $query, $fields) = @_;
    $query ||= {};
    $fields ||= {};

    return $self->find($query)->limit(-1)->fields($fields)->next;
}

sub insert {
    my $self = shift;
    my ( $object, $options ) = @_;
    $self->legacy_insert( @_ );
}

sub legacy_insert {
    my ($self, $object, $options) = @_;

    my ($id) = $self->batch_insert( [ $object ], $options);

    return $id;
}

sub batch_insert {
    my ($self, $object, $options) = @_;

    confess 'not an array reference' unless ref $object eq 'ARRAY';

    my $add_ids = 1;
    if ($options->{'no_ids'}) {
        $add_ids = 0;
    }

    my $conn = $self->_database->_client;
    my $ns = $self->full_name;

    my ($insert, $ids) = MongoDB::write_insert($ns, $object, $add_ids);
    if (length($insert) > $conn->max_bson_size) {
        Carp::croak("insert is too large: ".length($insert)." max: ".$conn->max_bson_size);
        return 0;
    }

    if ( ( defined($options) && $options->{safe} ) or $conn->_w_want_safe ) {
        my $ok = $self->_make_safe($insert);

        if (!$ok) {
            return 0;
        }
    }
    else {
        $conn->send($insert);
    }

    return $ids ? @$ids : $ids;
}

sub update {
    my $self = shift;
    my ( $query, $object, $opts ) = @_;

    return $self->legacy_update( @_ );
}

sub legacy_update {
    my ($self, $query, $object, $opts) = @_;
    #$self->update_cmd( $query, $object, $opts ) if $self->_database->_client->_use_write_cmd;

    # there used to be one option: upsert=0/1
    # now there are two, there will probably be
    # more in the future.  So, to support old code,
    # passing "1" will still be supported, but not
    # documented, so we can phase that out eventually.
    #
    # The preferred way of passing options will be a
    # hash of {optname=>value, ...}
    my $flags = 0;
    if ($opts && ref $opts eq 'HASH') {
        $flags |= $opts->{'upsert'} << 0
            if exists $opts->{'upsert'};
        $flags |= $opts->{'multiple'} << 1
            if exists $opts->{'multiple'};
    }
    else {
        $flags = !(!$opts);
    }

    my $conn = $self->_database->_client;
    my $ns = $self->full_name;

    my $update = MongoDB::write_update($ns, $query, $object, $flags);
    if ($opts->{safe} or $conn->_w_want_safe ) {
        return $self->_make_safe($update);
    }

    if ($conn->send($update) == -1) {
        $conn->connect;
        die("can't get db response, not connected");
    }

    return 1;
}

sub find_and_modify {
    my ( $self, $opts ) = @_;

    my $conn = $self->_database->_client;
    my $db   = $self->_database;

    my $result;
    try {
        $result = $db->_try_run_command( [ findAndModify => $self->name, %$opts ] )
    }
    catch {
        die $_ unless $_ eq 'No matching object found';
    };

    return $result->{value} if $result;
    return;
}

sub aggregate {
    my ( $self, $pipeline, $opts ) = @_;
    $opts = ref $opts eq 'HASH' ? $opts : { };

    my $db   = $self->_database;

    if ( exists $opts->{cursor} ) {
        $opts->{cursor} = { } unless ref $opts->{cursor} eq 'HASH';
    }

    # explain requires a boolean
    if ( exists $opts->{explain} ) {
        $opts->{explain} = $opts->{explain} ? true : false;
    }

    my @command = ( aggregate => $self->name, pipeline => $pipeline, %$opts );
    my $result = $db->_try_run_command( \@command );

    # if we got a cursor option then we need to construct a wonky cursor
    # object on our end and populate it with the first batch, since
    # commands can't actually return cursors.
    if ( exists $opts->{cursor} ) {
        unless ( exists $result->{cursor} ) {
            die "no cursor returned from aggregation";
        }

        my $cursor = MongoDB::Cursor->new(
            started_iterating      => 1,              # we have the first batch
            _client                => $db->_client,
            _master                => $db->_client,   # fake this because we're already iterating
            _ns                    => $result->{cursor}{ns},
            _agg_first_batch       => $result->{cursor}{firstBatch},
            _agg_batch_size        => scalar @{ $result->{cursor}{firstBatch} },  # for has_next
            _query                 => \@command,
        );

        $cursor->_init( $result->{cursor}{id} );
        return $cursor;
    }

    # return the whole result document if they want an explain
    if ( $opts->{explain} ) {
        return $result;
    }

    # TODO: handle errors?

    return $result->{result};
}

sub parallel_scan {
    my ( $self, $num_cursors, $opts ) = @_;
    unless (defined $num_cursors && $num_cursors == int($num_cursors)
        && $num_cursors > 0 && $num_cursors <= 10000
    ) {
        Carp::croak( "first argument to parallel_scan must be a positive integer between 1 and 10000" )
    }
    $opts = ref $opts eq 'HASH' ? $opts : { };

    my $db   = $self->_database;

    my @command = ( parallelCollectionScan => $self->name, numCursors => $num_cursors );
    my $result = $db->_try_run_command( \@command );

    Carp::croak("No cursors returned")
        unless $result->{cursors} && ref $result->{cursors} eq 'ARRAY';

    my @cursors;
    for my $c ( map { $_->{cursor} } @{$result->{cursors}} ) {
        # fake up a post-query cursor
        my $cursor = MongoDB::Cursor->new(
            started_iterating      => 1,              # we have the first batch
            _client                => $db->_client,
            _master                => $db->_client,   # fake this because we're already iterating
            _ns                    => $c->{ns},
            _query                 => \@command,
            _is_parallel           => 1,
        );

        $cursor->_init( $c->{id} );
        push @cursors, $cursor;
    }

    return @cursors;
}

sub rename {
    my ($self, $collectionname) = @_;

    my $conn = $self->_database->_client;
    my $database = $conn->get_database( 'admin' );
    my $fullname = $self->full_name;

    my ($db, @collection_bits) = split(/\./, $fullname);
    my $collection = join('.', @collection_bits);
    my $obj = $database->_try_run_command([ 'renameCollection' => "$db.$collection", 'to' => "$db.$collectionname" ]);

    return $conn->get_database( $db )->get_collection( $collectionname );
}

sub remove {
    my $self = shift;
    my ( $query, $options ) = @_;
    $self->legacy_remove( @_ );
}

sub legacy_remove {
    my ($self, $query, $options) = @_;
    #$self->delete_cmd( $query, $options ) if $self->_database->_client->_use_write_cmd;

    my $conn = $self->_database->_client;

    my ($just_one, $safe);
    if (defined $options && ref $options eq 'HASH') {
        $just_one = exists $options->{just_one} ? $options->{just_one} : 0;
        $safe = $options->{safe} or $conn->_w_want_safe;
    }
    else {
        $just_one = $options || 0;
    }

    my $ns = $self->full_name;
    $query ||= {};

    my $remove = MongoDB::write_remove($ns, $query, $just_one);
    if ($safe) {
        return $self->_make_safe($remove);
    }

    if ($conn->send($remove) == -1) {
        $conn->connect;
        die("can't get db response, not connected");
    }

    return 1;
}

sub ensure_index {
    my ($self, $keys, $options, $garbage) = @_;
    my $ns = $self->full_name;

    # we need to use the crappy old api if...
    #  - $options isn't a hash, it's a string like "ascending"
    #  - $keys is a one-element array: [foo]
    #  - $keys is an array with more than one element and the second
    #    element isn't a direction (or at least a good one)
    #  - Tie::IxHash has values like "ascending"
    if (($options && ref $options ne 'HASH') ||
        (ref $keys eq 'ARRAY' &&
         ($#$keys == 0 || $#$keys >= 1 && !($keys->[1] =~ /-?1/))) ||
        (ref $keys eq 'Tie::IxHash' && (my $copy = $keys->[2][0]) =~ /(de|a)scending/)) {
        Carp::croak("you're using the old ensure_index format, please upgrade");
    }

    $keys = Tie::IxHash->new(@$keys) if ref $keys eq 'ARRAY';
    my $obj = Tie::IxHash->new("ns" => $ns, "key" => $keys);

    if (exists $options->{name}) {
        $obj->Push("name" => $options->{name});
    }
    else {
        $obj->Push("name" => MongoDB::Collection::to_index_string($keys));
    }

    foreach ("unique", "background", "sparse") {
        if (exists $options->{$_}) {
            $obj->Push("$_" => ($options->{$_} ? boolean::true : boolean::false));
        }
    }
    if (exists $options->{drop_dups}) {
        $obj->Push("dropDups" => ($options->{drop_dups} ? boolean::true : boolean::false));
    }
    $options->{'no_ids'} = 1;

    foreach ("weights", "default_language", "language_override") {
        if (exists $options->{$_}) {
            $obj->Push("$_" => $options->{$_});
        }
    }

    if (exists $options->{expire_after_seconds}) {
        $obj->Push("expireAfterSeconds" => int($options->{expire_after_seconds}));
    }

    my ($db, $coll) = $ns =~ m/^([^\.]+)\.(.*)/;

    # try the new createIndexes command (mongodb 2.6), falling back to the old insert
    # method if createIndexes is not available.
    my $tmp_ns = $obj->DELETE( 'ns' );     # ci command takes ns outside of index spec

    my $res = $self->_database->get_collection( '$cmd' )->find_one( Tie::IxHash->new( createIndexes => $self->name, indexes => [ $obj ] ) );

    return $res if $res->{ok};

    if ( ( not $res->{ok} )  &&
         ( not exists $res->{code} or $res->{code} == 59 or $res->{code} == 13390) ) {
        $obj->Unshift( ns => $tmp_ns );     # restore ns to spec
        my $indexes = $self->_database->get_collection("system.indexes");
        return $indexes->insert($obj, $options);
    } else {
        die "error creating index: " . $res->{errmsg};
    }
}

sub _make_safe {
    my ($self, $req) = @_;
    my $conn = $self->_database->_client;
    my $db = $self->_database->name;

    my $last_error = Tie::IxHash->new(getlasterror => 1, w => $conn->w, wtimeout => $conn->wtimeout, j => $conn->j);
    my ($query, $info) = MongoDB::write_query($db.'.$cmd', 0, 0, -1, $last_error);

    $conn->send("$req$query");

    my $cursor = MongoDB::Cursor->new(_ns => $info->{ns},
                                      _master => $conn,
                                      _client => $conn,
                                      _query => {});
    $cursor->_init;
    $cursor->_request_id($info->{'request_id'});

    $conn->recv($cursor);
    $cursor->started_iterating(1);

    my $ok = $cursor->next();

    # $ok->{ok} is 1 if err is set
    Carp::croak $ok->{err} if $ok->{err};
    # $ok->{ok} == 0 is still an error
    if (!$ok->{ok}) {
        Carp::croak $ok->{errmsg};
    }

    return $ok;
}

sub save {
    my ($self, $doc, $options) = @_;

    if (exists $doc->{"_id"}) {

        if (!$options || !ref $options eq 'HASH') {
            $options = {"upsert" => boolean::true};
        }
        else {
            $options->{'upsert'} = boolean::true;
        }

        return $self->update({"_id" => $doc->{"_id"}}, $doc, $options);
    }
    else {
        return $self->insert($doc, $options);
    }
}

sub count {
    my ($self, $query) = @_;
    $query ||= {};

    my $obj;
    try {
        $obj = $self->_database->_try_run_command([
            count => $self->name,
            query => $query,
        ]);
    }
    catch {
        # if there was an error, check if it was the "ns missing" one that means the
        # collection hasn't been created or a real error.
        die $_ unless /^ns missing/;
    };

    return $obj ? $obj->{n} : 0;
}

sub validate {
    my ($self, $scan_data) = @_;
    $scan_data = 0 unless defined $scan_data;
    my $obj = $self->_database->run_command({ validate => $self->name });
}

sub drop_indexes {
    my ($self) = @_;
    return $self->drop_index('*');
}

sub drop_index {
    my ($self, $index_name) = @_;
    return $self->_database->run_command([
        dropIndexes => $self->name,
        index => $index_name,
    ]);
}

sub get_indexes {
    my ($self) = @_;
    return $self->_database->get_collection('system.indexes')->query({
        ns => $self->full_name,
    })->all;
}

sub drop {
    my ($self) = @_;
    $self->_database->run_command({ drop => $self->name });
    return;
}

sub bulk {
    my ( $self, %args ) = @_;

    return MongoDB::Bulk->new( %args, collection => $self );
}

__PACKAGE__->meta->make_immutable;

1;

__END__

=pod

=head1 SYNOPSIS

An instance of a MongoDB collection.

    # gets the foo collection
    my $collection = $db->get_collection( 'foo' );

Collection names can be chained together to access subcollections.  For
instance, the collection C<foo.bar> can be accessed with either:

    my $collection = $db->get_collection( 'foo' )->get_collection( 'bar' );

or

    my $collection = $db->get_collection( 'foo.bar' );

=attr name

The name of the collection.

=attr full_name

The full_name of the collection, including the namespace of the database it's
in.

=method get_collection ($name)

    my $collection = $database->get_collection('foo');

Returns a L<MongoDB::Collection> for the collection called C<$name> within this
collection.

=method find($query)

    my $cursor = $collection->find({ i => { '$gt' => 42 } });

Executes the given C<$query> and returns a C<MongoDB::Cursor> with the results.
C<$query> can be a hash reference, L<Tie::IxHash>, or array reference (with an
even number of elements).

The set of fields returned can be limited through the use of the
C<MongoDB::Cursor::fields> method on the resulting L<MongoDB::Cursor> object.
Other commonly used cursor methods are C<MongoDB::Cursor::limit>,
C<MongoDB::Cursor::skip>, and C<MongoDB::Cursor::sort>.

See also core documentation on querying:
L<http://docs.mongodb.org/manual/core/read/>.

=method query($query, $attrs?)

Identical to C<MongoDB::Collection::find>, described above.

    my $cursor = $collection->query->limit(10)->skip(10);

    my $cursor = $collection->query({ location => "Vancouver" })->sort({ age => 1 });

Valid query attributes are:

=over 4

=item limit

Limit the number of results.

=item skip

Skip a number of results.

=item sort_by

Order results.

=back

=method find_one($query, $fields?)

    my $object = $collection->find_one({ name => 'Resi' });
    my $object = $collection->find_one({ name => 'Resi' }, { name => 1, age => 1});

Executes the given C<$query> and returns the first object matching it.
C<$query> can be a hash reference, L<Tie::IxHash>, or array reference (with an
even number of elements).  If C<$fields> is specified, the resulting document
will only include the fields given (and the C<_id> field) which can cut down on
wire traffic.

=method insert ($object, $options?)

    my $id1 = $coll->insert({ name => 'mongo', type => 'database' });
    my $id2 = $coll->insert({ name => 'mongo', type => 'database' }, {safe => 1});

Inserts the given C<$object> into the database and returns it's id
value. C<$object> can be a hash reference, a reference to an array with an
even number of elements, or a L<Tie::IxHash>.  The id is the C<_id> value
specified in the data or a L<MongoDB::OID>.

The optional C<$options> parameter can be used to specify if this is a safe
insert.  A safe insert will check with the database if the insert succeeded and
croak if it did not.  You can also check if the insert succeeded by doing an
unsafe insert, then calling L<MongoDB::Database/"last_error($options?)">.

See also core documentation on insert: L<http://docs.mongodb.org/manual/core/create/>.

=method batch_insert (\@array, $options)

    my @ids = $collection->batch_insert([{name => "Joe"}, {name => "Fred"}, {name => "Sam"}]);

Inserts each of the documents in the array into the database and returns an
array of their _id fields.

The optional C<$options> parameter can be used to specify if this is a safe
insert.  A safe insert will check with the database if the insert succeeded and
croak if it did not. You can also check if the inserts succeeded by doing an
unsafe batch insert, then calling L<MongoDB::Database/"last_error($options?)">.

=method update (\%criteria, \%object, \%options?)

    $collection->update({'x' => 3}, {'$inc' => {'count' => -1} }, {"upsert" => 1, "multiple" => 1});

Updates an existing C<$object> matching C<$criteria> in the database.

Returns 1 unless the C<safe> option is set. If C<safe> is set, this will return
a hash of information about the update, including number of documents updated
(C<n>).  If C<safe> is set and the update fails, C<update> will croak. You can
also check if the update succeeded by doing an unsafe update, then calling
L<MongoDB::Database/"last_error($options?)">.

C<update> can take a hash reference of options.  The options currently supported
are:

=over

=item C<upsert>
If no object matching C<$criteria> is found, C<$object> will be inserted.

=item C<multiple>
All of the documents that match C<$criteria> will be updated, not just
the first document found. (Only available with database version 1.1.3 and
newer.)

=item C<safe>
If the update fails and safe is set, the update will croak.

=back

See also core documentation on update: L<http://docs.mongodb.org/manual/core/update/>.

=method find_and_modify

    my $result = $collection->find_and_modify( { query => { ... }, update => { ... } } );

Perform an atomic update. C<find_and_modify> guarantees that nothing else will come along
and change the queried documents before the update is performed.

Returns the old version of the document, unless C<new => 1> is specified. If no documents
match the query, it returns nothing.

=method aggregate

    my $result = $collection->aggregate( [ ... ] );

Run a query using the MongoDB 2.2+ aggregation framework. The first argument is an array-ref of
aggregation pipeline operators.

The type of return value from C<aggregate> depends on how you use it.

=over 4

=item * By default, the aggregation framework returns a document with an embedded array of results, and
the C<aggregate> method returns a reference to that array.

=item * MongoDB 2.6+ supports returning cursors from aggregation queries, allowing you to bypass
the 16MB size limit of documents. If you specifiy a C<cursor> option, the C<aggregate> method
will return a L<MongoDB::Cursor> object which can be iterated in the normal fashion.

    my $cursor = $collection->aggregate( [ ... ], { cursor => 1 } );

Specifying a C<cursor> option will cause an error on versions of MongoDB below 2.6.

The C<cursor> option may also have some useful options of its own. Currently, the only one
is C<batchSize>, which allows you to control how frequently the cursor must go back to the
database for more documents.

    my $cursor = $collection->aggregate( [ ... ], { cursor => { batchSize => 10 } } );

=item * MongoDB 2.6+ supports an C<explain> option to aggregation queries to retrieve data
about how the server will process a query pipeline.

    my $result = $collection->aggregate( [ ... ], { explain => 1 } );

In this case, C<aggregate> will return a document (not an array) containing the explanation
structure.

=item * Finally, MongoDB 2.6+ will return an empty results array if the C<$out> pipeline operator is used to
write aggregation results directly to a collection. Create a new C<Collection> object to
query the result collection.

=back

See L<Aggregation|http://docs.mongodb.org/manual/aggregation/> in the MongoDB manual
for more information on how to construct aggregation queries.

=method parallel_scan($max_cursors)

    my @cursors = $collection->parallel_scan(10);

Scan the collection in parallel. The argument is the maximum number of
L<MongoDB::Cursor> objects to return and must be a positive integer between 1
and 10,000.

As long as the collection is not modified during scanning, each document will
appear only once in one of the cursors' result sets.

Only iteration methods may be called on parallel scan cursors.

If an error occurs, an exception will be thrown.

=method rename ("newcollectionname")

    my $newcollection = $collection->rename("mynewcollection");

Renames the collection.  It expects that the new name is currently not in use.

Returns the new collection.  If a collection already exists with that new collection name this will
die.

=method save($doc, $options)

    $collection->save({"author" => "joe"});
    my $post = $collection->find_one;

    $post->{author} = {"name" => "joe", "id" => 123, "phone" => "555-5555"};

    $collection->save( $post );
    $collection->save( $post, { safe => 1 } )

Inserts a document into the database if it does not have an _id field, upserts
it if it does have an _id field.

The return types for this function are a bit of a mess, as it will return the
_id if a new document was inserted, 1 if an upsert occurred, and croak if the
safe option was set and an error occurred.  You can also check if the save
succeeded by doing an unsafe save, then calling
L<MongoDB::Database/"last_error($options?)">.

=method remove ($query?, $options?)

    $collection->remove({ answer => { '$ne' => 42 } });

Removes all objects matching the given C<$query> from the database. If no
parameters are given, removes all objects from the collection (but does not
delete indexes, as C<MongoDB::Collection::drop> does).

Returns 1 unless the C<safe> option is set.  If C<safe> is set and the remove
succeeds, C<remove> will return a hash of information about the remove,
including how many documents were removed (C<n>).  If the remove fails and
C<safe> is set, C<remove> will croak.  You can also check if the remove
succeeded by doing an unsafe remove, then calling
L<MongoDB::Database/"last_error($options?)">.

C<remove> can take a hash reference of options.  The options currently supported
are

=over

=item C<just_one>
Only one matching document to be removed.

=item C<safe>
If the update fails and safe is set, this function will croak.

=back

See also core documentation on remove: L<http://docs.mongodb.org/manual/core/delete/>.

=method ensure_index ($keys, $options?)

    use boolean;
    $collection->ensure_index({"foo" => 1, "bar" => -1}, { unique => true });

Makes sure the given C<$keys> of this collection are indexed. C<$keys> can be an
array reference, hash reference, or C<Tie::IxHash>.  C<Tie::IxHash> is preferred
for multi-key indexes, so that the keys are in the correct order.  1 creates an
ascending index, -1 creates a descending index.

If the C<safe> option is not set, C<ensure_index> will not return anything
unless there is a socket error (in which case it will croak).  If the C<safe>
option is set and the index creation fails, it will also croak. You can also
check if the indexing succeeded by doing an unsafe index creation, then calling
L<MongoDB::Database/"last_error($options?)">.

See the L<MongoDB::Indexing> pod for more information on indexing.

=method count($query?)

    my $n_objects = $collection->count({ name => 'Bob' });

Counts the number of objects in this collection that match the given C<$query>.
If no query is given, the total number of objects in the collection is returned.

=method validate

    $collection->validate;

Asks the server to validate this collection.
Returns a hash of the form:

    {
        'ok' => '1',
        'ns' => 'foo.bar',
        'result' => info
    }

where C<info> is a string of information
about the collection.

=method drop_indexes

    $collection->drop_indexes;

Removes all indexes from this collection.

=method drop_index ($index_name)

    $collection->drop_index('foo_1');

Removes an index called C<$index_name> from this collection.
Use C<MongoDB::Collection::get_indexes> to find the index name.

=method get_indexes

    my @indexes = $collection->get_indexes;

Returns a list of all indexes of this collection.
Each index contains C<ns>, C<name>, and C<key>
fields of the form:

    {
        'ns' => 'db_name.collection_name',
        'name' => 'index_name',
        'key' => {
            'key1' => dir1,
            'key2' => dir2,
            ...
            'keyN' => dirN
        }
    }

where C<dirX> is 1 or -1, depending on if the
index is ascending or descending on that key.

=method drop

    $collection->drop;

Deletes a collection as well as all of its indexes.


text:
package jenkins.plugins.fauxpasapp.commands;

import hudson.FilePath;
import hudson.util.ArgumentListBuilder;
import jenkins.plugins.fauxpasapp.CommandExecutor;

import java.io.OutputStream;

public class FauxPasCheckCommand implements Command
{
    private String fauxPasCommandPath;
    public String getFauxPasCommandPath() { return fauxPasCommandPath; }
    public void setFauxPasCommandPath(String fauxPasCommandPath) { this.fauxPasCommandPath = fauxPasCommandPath; }

    private String xcodeprojPath;
    public String getXcodeprojPath() { return xcodeprojPath; }
    public void setXcodeprojPath(String xcodeprojPath) { this.xcodeprojPath = xcodeprojPath; }

    private String fauxPasConfigFilePath;
    public String getFauxPasConfigFilePath() { return fauxPasConfigFilePath; }
    public void setFauxPasConfigFilePath(String fauxPasConfigFilePath) { this.fauxPasConfigFilePath = fauxPasConfigFilePath; }

    private FilePath fauxPasOutputFilePath;
    public FilePath getFauxPasOutputFilePath() { return fauxPasOutputFilePath; }
    public void setFauxPasOutputFilePath(FilePath fauxPasOutputFilePath) { this.fauxPasOutputFilePath = fauxPasOutputFilePath; }

    private ArgumentListBuilder getArgumentList()
    {
        ArgumentListBuilder args = new ArgumentListBuilder();
        args.add(getFauxPasCommandPath());
        args.add("--configFile", getFauxPasConfigFilePath());
        args.add("--outputFormat", "json");
        args.add("check", getXcodeprojPath());
        return args;
    }

    @Override
    public int execute(BuildContext context) throws Exception
    {
        context.log("Output file path: " + getFauxPasOutputFilePath());

        OutputStream outputFileStream = getFauxPasOutputFilePath().write();
        int rc = context.waitForProcess(context.getWorkspace(), getArgumentList(), outputFileStream);
        outputFileStream.flush();
        outputFileStream.close();

        if (rc == CommandExecutor.SUCCESS)
            context.log("Faux Pas exit status: success");
        else
            context.log("Faux Pas exit status: error");

        return rc;
    }

    @Override
    public String toString()
    {
        return getArgumentList().toString();
    }
}


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Security\Exception;

/**
 * Rule specific exception.
 */
class RuleException extends GuardException
{
}


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType PackLevelCodeType
 * @xmlName PackLevelCode
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\PackLevelCode
 */
class PackLevelCode extends PackLevelCodeType
{
} // end class PackLevelCode


text:
//
//  JumaInternalDevice.h
//  JumaBluetoothSDK
//
//  Created by 汪安军 on 15/7/22.
//  Copyright (c) 2015年 JUMA. All rights reserved.
//

#import "JumaDevice.h"
@class JumaManager;
@class CBPeripheral;

@interface JumaInternalDevice : JumaDevice

/** 改变 CBPeripheral 的名称之后, 再次扫描时 CBPeripheral.name 属性的值不正确, 但是 advertisementData 中的 local name 是正确的, 为了取得正确的名称, 记下了这个数据 */
@property (nonatomic, strong) NSDictionary *advertisementData;

/** 能否和这个设备建立连接 */
@property (nonatomic, readonly) BOOL canEstablishConnection;
/** 不能和这个设备建立连接的原因 */
@property (nonatomic, strong, readonly) NSError *canNotEstablishConnectionError;

@property (nonatomic, strong, readonly) CBPeripheral *peripheral;

- (instancetype)initWithPeripheral:(CBPeripheral *)peripheral manager:(JumaManager *)manager;
+ (instancetype)deviceWithPeripheral:(CBPeripheral *)peripheral manager:(JumaManager *)manager;

- (void)connectedByManager;
- (void)didConnectedByManager;

- (void)disconnectedByManager;
- (void)didDisconnectedByManager;

/*!
 *  @method disconnectFromManager
 *
 *  @discussion Convince method for the JumaManager to disconnect a JumaDevice.
 */
- (void)disconnectFromManager;

@end


text:
package Google::Ads::GoogleAds::V11::Common::TargetImpressionShareSimulationPoint;

use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);

use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;

sub new {
  my ($class, $args) = @_;
  my $self = {
    absoluteTopImpressions      => $args->{absoluteTopImpressions},
    biddableConversions         => $args->{biddableConversions},
    biddableConversionsValue    => $args->{biddableConversionsValue},
    clicks                      => $args->{clicks},
    costMicros                  => $args->{costMicros},
    impressions                 => $args->{impressions},
    requiredBudgetAmountMicros  => $args->{requiredBudgetAmountMicros},
    requiredCpcBidCeilingMicros => $args->{requiredCpcBidCeilingMicros},
    targetImpressionShareMicros => $args->{targetImpressionShareMicros},
    topSlotImpressions          => $args->{topSlotImpressions}};

  # Delete the unassigned fields in this object for a more concise JSON payload
  remove_unassigned_fields($self, $args);

  bless $self, $class;
  return $self;
}

1;


text:
package com.jdon.annotation.model;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

/**
 *
 * Domain Model should normal live in memory not in database. so cache in memory
 * is very important for domain model life cycle.
 *
 * Example producer: com.jdon.sample.test.domain.onecase.DomainEvent
 * Consumer:com.jdon.sample.test.domain.onecase.DomainListener
 *
 * Domain Model producer /Consumer:
 *
 * 1. annotate the producer class with @Model and @Introduce("message")
 *
 *
 @Model
 *
 @Introduce("message") public class DomainEvent {}
 *
 *                       the value "message" of @@Introduce("message") is the
 *                       om.jdon.domain.message.MessageInterceptor configured in
 *                       aspect.xml
 *
 *                       2. annotate the method with @Send("mytopic") of the
 *                       producer class; * @Send("mytopic") public DomainMessage
 *                       myMethod() { DomainMessage em = new
 *                       DomainMessage(this.name); return em; }
 *
 *                       3. the "mytopic" value in @Send("mytopic") is equals to
 *                       the "mytopic" value in @Consumer("mytopic");
 *
 *                       4. annotate the consumer class with
 *
@Consumer("mytopic");
 *
 *                       5.there are two kind of consumer
 *
 *                       (1)the consumer class must implements
 *                       com.jdon.domain.message.DomainEventHandler
 *
 *
@Consumer("mytopic") public class MyDomainEventHandler implements
 *                      DomainEventHandler {
 *
 *                      public void onEvent(EventDisruptor event, boolean
 *                      endOfBatch) throws Exception{..}
 *
 *                      }
 *
 *
 *                      (2)or the consumer class's method annotated with
 *
@onEvent("mytopic")
 *
 *
 *
 *
 *                      Topic/queue(1:N or 1:1):
 *
 *
@Send(topicName) ==> @Consumer(topicName);
 *
 *
 *
 *                  under version 6.3 there is event Older queue(1:1):
 *
 *
@Send(topicName) ==> @Component(topicName);
 *
 *                  The message accepter class annotated with
 *
@Component(topicName) must implements com.jdon.domain.message.MessageListener
 *
 *
 * @see com.jdon.controller.model.ModelIF
 * @author banQ
 *
 */
@Target(METHOD)
@Retention(RUNTIME)
@Documented
public @interface Send {
	/**
	 * topic/queue name
	 *
	 *
 @Send(topicName) ==> @Consumer(topicName);
	 *
	 * @return topic/queue name
	 */
	String value();

	boolean asyn() default true;
}


text:
For Swift TraceLog comes with the following basic Logging functions (Note: hidden
parameters and defaults were omitted for simplicity).

```swift
    logError  (tag: String?, message: @escaping () -> String)
    logWarning(tag: String?, message: @escaping () -> String)
    logInfo   (tag: String?, message: @escaping () -> String)
    logTrace  (tag: String?, level: UInt, message: @escaping () -> String)
    logTrace  (level: UInt, @escaping message: () -> String)
```

Using it is as simple as calling one of the methods depending on the current type of message you want to log, for instance, to log a simple informational message.

```swift
    logInfo { "A simple informational message" }
```

Since the message parameter is a closure that evaluates to a String, any expression that results in a string message can be used.

```swift
   logInfo {
        "A simple informational message: " +
        " Another expression or constant that evaluates to a string"
   }
```

We used closures for several reasons; one is that the closure will not be evaluated (and you won't incur the overhead) if logging is disabled or if the log level for this call is higher than the current log level set. And two, more complex expressions can be put into the closure to make decisions on the message to be printed based on the current context of the call.  Again, these complex closures will not get executed in the cases mentioned above.  For instance:

```swift
    logInfo {
         if let unwrappedOptionalString = optionalString {
            return "Executing with \(unwrappedOptionalString)..."
         } else {
            return "Executing..."
         }
    }
```

Log methods take an optional tag that you can use to group related messages and also be used to determine whether this statement gets logged based on the current environment configuration.  It no tag is set, the file name of the calling method is used as the tag.

```swift
   logInfo("MyCustomTag") {
        "A simple informational message"
   }
```

There are several trace levels for `logTrace` that can be used.  If you don't pass a level, you get level 3, otherwise, specify a level when making the `logTrace` call.   For example, here is a trace level 1 and a level 3 call.

```swift
   logTrace {
        "A simple trace level 1 message"
   }

   logTrace(3) {
        "A simple trace level 3 message"
   }
```

You can of course also pass a tag like the rest of the log calls.

```swift
    logTrace("MyCustomTag", level: 3) {
         "A simple trace level message"
    }
```

That is all there is to adding logging to your **Swift** application!


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:Android="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_xiu_gai_jian_jie"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ededed"
    tools:context="com.example.ssnn.xiugaiziliao.XiuGaiJianJieActivity">
    <RelativeLayout
        android:id="@+id/rl_xiugaijianjie_toubu"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#fff">

        <TextView

            android:text="简介"
            android:textColor="#000"
            android:textSize="18dp"
            android:gravity="center"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

        <ImageView
            android:id="@+id/iv_xiugaijianjie_fanhui"
            android:layout_marginLeft="-30dp"
            android:src="@drawable/fanhui"
            android:layout_width="wrap_content"
            android:layout_centerVertical="true"
            android:layout_height="35dp" />
        <TextView
            android:id="@+id/tv_jianjie_baocun"
            android:text="保存"
            android:textSize="18sp"
            android:gravity="center"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dp"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
    </RelativeLayout>
    <EditText
        android:id="@+id/et_jianjie"
        android:gravity="top"
        android:textCursorDrawable="@drawable/color_cursor"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:layout_marginRight="15dp"
        android:padding="10dp"
        android:background="@drawable/corners_bg"
        android:layout_below="@id/rl_xiugaijianjie_toubu"
        android:layout_width="match_parent"
        android:layout_height="200dp" />

</RelativeLayout>


text:
..
.. Licensed to the Apache Software Foundation (ASF) under one
.. or more contributor license agreements.  See the NOTICE file
.. distributed with this work for additional information
.. regarding copyright ownership.  The ASF licenses this file
.. to you under the Apache License, Version 2.0 (the
.. "License"); you may not use this file except in compliance
.. with the License.  You may obtain a copy of the License at
..
..   http://www.apache.org/licenses/LICENSE-2.0
..
.. Unless required by applicable law or agreed to in writing,
.. software distributed under the License is distributed on an
.. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
.. KIND, either express or implied.  See the License for the
.. specific language governing permissions and limitations
.. under the License.
..

.. warning::  The documentation is not up-to-date and has moved to `Apache Pinot Docs <https://docs.pinot.apache.org/>`_.

Running Pinot in Production
===========================

Requirements
~~~~~~~~~~~~

You will need the following in order to run pinot in production:

* Hardware for controller/broker/servers as per your load
* Working installation of Zookeeper that Pinot can use. We recommend setting aside a path within zookpeer and including that path in pinot.controller.zkStr. Pinot will create its own cluster under this path (cluster name decided by pinot.controller.helixClusterName)
* Shared storage mounted on controllers (if you plan to have multiple controllers for the same cluster). Alternatively, an implementation of PinotFS that the Pinot hosts have access to.
* HTTP load balancers for spraying queries across brokers (or other mechanism to balance queries)
* HTTP load balancers for spraying controller requests (e.g. segment push, or other controller APIs) or other mechanisms for distribution of these requests.

Deploying Pinot
~~~~~~~~~~~~~~~

In general, when deploying Pinot services, it is best to adhere to a specific ordering in which the various components should be deployed. This deployment order is recommended in case of the scenario that there might be protocol or other significant differences, the deployments go out in a predictable order in which failure  due to these changes can be avoided.

The ordering is as follows:

#. pinot-controller
#. pinot-broker
#. pinot-server
#. pinot-minion

Managing Pinot
~~~~~~~~~~~~~~

Pinot provides a web-based management console and a command-line utility (``pinot-admin.sh``) in order to help provision and manage pinot clusters.

Pinot Management Console
------------------------

The web based management console allows operations on tables, tenants, segments and schemas.
You can access the console via ``http://controller-host:port/help``.
The console also allows you to enter queries for interactive debugging.
Here are some screen-shots from the console.

  .. figure:: img/pinot-console.png

Listing all the schemas in the Pinot cluster:

  .. figure:: img/list-schemas.png

Rebalancing segments of a table:

  .. figure:: img/rebalance-table.png

Command line utility (pinot-admin.sh)
-------------------------------------

The command line utility (``pinot-admin.sh``) can be generated by running
``mvn install package -DskipTests -Pbin-dist`` in the directory in which you checked out Pinot.

Here is an example of invoking the command to create a pinot segment:

.. code-block:: none

  $ ./pinot-distribution/target/apache-pinot-incubating-0.1.0-SNAPSHOT-bin/apache-pinot-incubating-0.1.0-SNAPSHOT-bin/bin/pinot-admin.sh CreateSegment -dataDir /Users/host1/Desktop/test/ -format CSV -outDir /Users/host1/Desktop/test2/ -tableName baseballStats -segmentName baseballStats_data -overwrite -schemaFile ./pinot-distribution/target/apache-pinot-incubating-0.1.0-SNAPSHOT-bin/apache-pinot-incubating-0.1.0-SNAPSHOT-bin/examples/batch/baseballStats/baseballStats_schema.json
  Executing command: CreateSegment  -generatorConfigFile null -dataDir /Users/host1/Desktop/test/ -format CSV -outDir /Users/host1/Desktop/test2/ -overwrite true -tableName baseballStats -segmentName baseballStats_data -timeColumnName null -schemaFile ./pinot-distribution/target/apache-pinot-incubating-0.1.0-SNAPSHOT-bin/apache-pinot-incubating-0.1.0-SNAPSHOT-bin/examples/batch/baseballStats/baseballStats_schema.json -readerConfigFile null -enableStarTreeIndex false -starTreeIndexSpecFile null -hllSize 9 -hllColumns null -hllSuffix _hll -numThreads 1
  Accepted files: [/Users/host1/Desktop/test/baseballStats_data.csv]
  Finished building StatsCollector!
  Collected stats for 97889 documents
  Created dictionary for INT column: homeRuns with cardinality: 67, range: 0 to 73
  Created dictionary for INT column: playerStint with cardinality: 5, range: 1 to 5
  Created dictionary for INT column: groundedIntoDoublePlays with cardinality: 35, range: 0 to 36
  Created dictionary for INT column: numberOfGames with cardinality: 165, range: 1 to 165
  Created dictionary for INT column: AtBatting with cardinality: 699, range: 0 to 716
  Created dictionary for INT column: stolenBases with cardinality: 114, range: 0 to 138
  Created dictionary for INT column: tripples with cardinality: 32, range: 0 to 36
  Created dictionary for INT column: hitsByPitch with cardinality: 41, range: 0 to 51
  Created dictionary for STRING column: teamID with cardinality: 149, max length in bytes: 3, range: ALT to WSU
  Created dictionary for INT column: numberOfGamesAsBatter with cardinality: 166, range: 0 to 165
  Created dictionary for INT column: strikeouts with cardinality: 199, range: 0 to 223
  Created dictionary for INT column: sacrificeFlies with cardinality: 20, range: 0 to 19
  Created dictionary for INT column: caughtStealing with cardinality: 36, range: 0 to 42
  Created dictionary for INT column: baseOnBalls with cardinality: 154, range: 0 to 232
  Created dictionary for STRING column: playerName with cardinality: 11976, max length in bytes: 43, range:  to Zoilo Casanova
  Created dictionary for INT column: doules with cardinality: 64, range: 0 to 67
  Created dictionary for STRING column: league with cardinality: 7, max length in bytes: 2, range: AA to UA
  Created dictionary for INT column: yearID with cardinality: 143, range: 1871 to 2013
  Created dictionary for INT column: hits with cardinality: 250, range: 0 to 262
  Created dictionary for INT column: runsBattedIn with cardinality: 175, range: 0 to 191
  Created dictionary for INT column: G_old with cardinality: 166, range: 0 to 165
  Created dictionary for INT column: sacrificeHits with cardinality: 54, range: 0 to 67
  Created dictionary for INT column: intentionalWalks with cardinality: 45, range: 0 to 120
  Created dictionary for INT column: runs with cardinality: 167, range: 0 to 192
  Created dictionary for STRING column: playerID with cardinality: 18107, max length in bytes: 9, range: aardsda01 to zwilldu01
  Start building IndexCreator!
  Finished records indexing in IndexCreator!
  Finished segment seal!
  Converting segment: /Users/host1/Desktop/test2/baseballStats_data_0 to v3 format
  v3 segment location for segment: baseballStats_data_0 is /Users/host1/Desktop/test2/baseballStats_data_0/v3
  Deleting files in v1 segment directory: /Users/host1/Desktop/test2/baseballStats_data_0
  Driver, record read time : 369
  Driver, stats collector time : 0
  Driver, indexing time : 373

Here is an example of executing a query on a Pinot table:

.. code-block:: none

  $ ./pinot-distribution/target/apache-pinot-incubating-0.1.0-SNAPSHOT-bin/apache-pinot-incubating-0.1.0-SNAPSHOT-bin/bin/pinot-admin.sh PostQuery -query "select count(*) from baseballStats" ./pinot-distribution/target/apache-pinot-incubaExecuting command: PostQuery -brokerHost [broker_host] -brokerPort [broker_port] -query select count(*) from baseballStats
  Result: {"aggregationResults":[{"function":"count_star","value":"97889"}],"exceptions":[],"numServersQueried":1,"numServersResponded":1,"numSegmentsQueried":1,"numSegmentsProcessed":1,"numSegmentsMatched":1,"numDocsScanned":97889,"numEntriesScannedInFilter":0,"numEntriesScannedPostFilter":0,"numGroupsLimitReached":false,"totalDocs":97889,"timeUsedMs":107,"segmentStatistics":[],"traceInfo":{}}

Monitoring Pinot
~~~~~~~~~~~~~~~~

Pinot exposes several metrics to monitor the service and ensure that pinot users are not experiencing issues. In this section we discuss some of the key metrics that are useful to monitor. A full list of metrics is available in the `Metrics <customizations.html#metrics>`_ section.

Pinot Server
------------

* Missing Segments - `NUM_MISSING_SEGMENTS <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java>`_

  * Number of missing segments that the broker queried for (expected to be on the server) but the server didn't have. This can be due to retention or stale routing table.

* Query latency - `TOTAL_QUERY_TIME <https://github.com/apache/incubator-pinot/blob/ce2d9ee9dc73b2d7273a63a4eede774eb024ea8f/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerQueryPhase.java>`_

  * Total time to take from receiving to finishing executing the query.

* Query Execution Exceptions - `QUERY_EXECUTION_EXCEPTIONS <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerMeter.java>`_

  * The number of exception which might have occurred during query execution.

* Realtime Consumption Status - `LLC_PARTITION_CONSUMING <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerGauge.java>`_

  * This gives a binary value based on whether low-level consumption is healthy (1) or unhealthy (0). It's important to ensure at least a single replica of each partition is consuming.

* Realtime Highest Offset Consumed - `HIGHEST_STREAM_OFFSET_CONSUMED <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/ServerGauge.java>`_

  * The highest offset which has been consumed so far.

Pinot Broker
------------

* Incoming QPS (per broker) - `QUERIES <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java>`_

  * The rate which an individual broker is receiving queries. Units are in QPS.

* Dropped Requests - `REQUEST_DROPPED_DUE_TO_SEND_ERROR <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java>`_, `REQUEST_DROPPED_DUE_TO_CONNECTION_ERROR <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java>`_, `REQUEST_DROPPED_DUE_TO_ACCESS_ERROR <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java>`_

  * These multiple metrics will indicate if a query is dropped, ie the processing of that query has been forfeited for some reason.

* Partial Responses - `BROKER_RESPONSES_WITH_PARTIAL_SERVERS_RESPONDED <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java>`_

  * Indicates a count of partial responses. A partial response is when at least 1 of the requested servers fails to respond to the query.

* Table QPS quota exceeded - `QUERY_QUOTA_EXCEEDED <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java>`_

  * Binary metric which will indicate when the configured QPS quota for a table is exceeded (1) or if there is capacity remaining (0).

* Table QPS quota usage percent - `QUERY_QUOTA_CAPACITY_UTILIZATION_RATE <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerGauge.java>`_

  * Percentage of the configured QPS quota being utilized.

Pinot Controller
----------------

Many of the controller metrics include a table name and thus are dynamically generated in the code. The metrics below point to the classes which generate the corresponding metrics.

To get the real metric name, the easiest route is to spin up a controller instance, create a table with the desired name and look through the generated metrics.

.. todo::

  Give a more detailed explanation of how metrics are generated, how to identify real metrics names and where to find them in the code.

* Percent Segments Available - `PERCENT_SEGMENTS_AVAILABLE <https://github.com/apache/incubator-pinot/blob/ce2d9ee9dc73b2d7273a63a4eede774eb024ea8f/pinot-common/src/main/java/org/apache/pinot/common/metrics/ControllerGauge.java>`_

  * Percentage of complete online replicas in external view as compared to replicas in ideal state.

* Segments in Error State - `SEGMENTS_IN_ERROR_STATE <https://github.com/apache/incubator-pinot/blob/ce2d9ee9dc73b2d7273a63a4eede774eb024ea8f/pinot-common/src/main/java/org/apache/pinot/common/metrics/ControllerGauge.java>`_

  * Number of segments in an ``ERROR`` state for a given table.

* Last push delay - Generated in the `ValidationMetrics <https://github.com/apache/incubator-pinot/blob/ce2d9ee9dc73b2d7273a63a4eede774eb024ea8f/pinot-common/src/main/java/org/apache/pinot/common/metrics/ValidationMetrics.java>`_ class.

  * The time in hours since the last time an offline segment has been pushed to the controller.

* Percent of replicas up - `PERCENT_OF_REPLICAS <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/ControllerGauge.java>`_

  * Percentage of complete online replicas in external view as compared to replicas in ideal state.

* Table storage quota usage percent - `TABLE_STORAGE_QUOTA_UTILIZATION <https://github.com/apache/incubator-pinot/blob/master/pinot-common/src/main/java/org/apache/pinot/common/metrics/ControllerGauge.java>`_

  * Shows how much of the table's storage quota is currently being used, metric will a percentage of a the entire quota.


text:
@interface GQViewCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic,copy) NSString *image;

@end


text:
namespace fs = std::experimental::filesystem;
#else
#include <filesystem>
namespace fs = std::filesystem;
#endif

using namespace EPL_DataCollect;
using namespace EPL_DataCollect::constants;
using namespace EPL_Viz;
using namespace EPL_Viz::constants;
using namespace std;
using namespace std::chrono;
using namespace tracer;

void handler(Tracer *t, AbstractPrinter *p, void *ctx);
void handler(Tracer *t, AbstractPrinter *p, void *ctx) {
  (void)t;
  (void)ctx;
  string      outStr = p->generateString();
  CrashDialog diag(QString::fromStdString(outStr));
  diag.exec();
}

int main(int argc, char *argv[]) {
  std::string installPrefix = EPL_DC_INSTALL_PREFIX;

  srand(static_cast<unsigned int>(system_clock::to_time_t(system_clock::now())));

#if !defined(WIN32) && !defined(_WIN32) && !defined(__WIN32)
  char *appImageDir = getenv("APPDIR");
  if (appImageDir) {
    installPrefix = appImageDir;
    installPrefix += "/usr";
  }
#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32)
  fs::path rootDir(argv[0]);
  installPrefix = rootDir.remove_filename().remove_filename().string();
#endif

  Init                init;
  plugins::PythonInit pyInit(argc, argv);

  if (init.getIsOK() != Init::OK) {
    QApplication a(argc, argv);
    QMessageBox::critical(nullptr,
                          "Failed to initialize",
                          QString("Failed to initialize the EPL DataCollect backend\n  -- Error Code: ") +
                                EPLEnum2Str::toStr(init.getIsOK()).c_str());
    return 1;
  }
  pyInit.addPath(installPrefix + "/lib/eplViz");

  QApplication a(argc, argv);

  auto *th              = TracerHandler::getTracer();
  auto  cfg             = th->getConfig();
  cfg.callback          = handler;
  cfg.autoPrintToStdErr = true;
  th->setConfig(cfg);

  auto          pc    = PrinterContainer::fancy();
  FancyPrinter *fP    = dynamic_cast<FancyPrinter *>(pc());
  auto          Pcfg  = fP->getConfig();
  Pcfg.shortenFiles   = true;
  Pcfg.shortenModules = true;
  fP->setConfig(Pcfg);
  fP->addSystemEntry({"Qt", qVersion()});
  fP->addSystemEntry({"EPL-Viz",
                      string("v") + to_string(EPL_VIZ_VERSION_MAJOR) + "." + to_string(EPL_VIZ_VERSION_MINOR) + "." +
                            to_string(EPL_VIZ_VERSION_SUBMINOR) + " +" + to_string(EPL_VIZ_GIT_LAST_TAG_DIFF) + " -- " +
                            EPL_VIZ_VERSION_GIT});
  fP->addSystemEntry({"EPL_DataCollect",
                      string("v") + to_string(EPL_DC_VERSION_MAJOR) + "." + to_string(EPL_DC_VERSION_MINOR) + "." +
                            to_string(EPL_DC_VERSION_SUBMINOR) + " +" + to_string(EPL_DC_GIT_LAST_TAG_DIFF) + " -- " +
                            EPL_DC_VERSION_GIT});
  th->setup(move(pc));

  if (QIcon::fromTheme("application-exit").isNull()) {
    QWidget temp;
    qDebug() << "[THEME] Using integrated theme icons";
    if (temp.palette().window().color().lightness() >= 125) {
      qDebug() << "[THEME] Using LIGHT theme icons";
      QIcon::setThemeName("Breeze_icons_Normal");
    } else {
      qDebug() << "[THEME] Using DARK theme icons";
      QIcon::setThemeName("Breeze_icons_Dark");
    };
  } else {
    qDebug() << "[THEME] Using system theme";
  }

  MainWindow w;
  w.show();

  return a.exec();
}


text:
#ifndef TGBOT_MENUBUTTONWEBAPP_H
#define TGBOT_MENUBUTTONWEBAPP_H

#include "tgbot/types/MenuButton.h"
#include "tgbot/types/WebAppInfo.h"

#include <memory>
#include <string>

namespace TgBot {

/**
 * @brief Represents a menu button, which launches a Web App.
 *
 * @ingroup types
 */
class MenuButtonWebApp : public MenuButton {
public:
    static const std::string TYPE;

    typedef std::shared_ptr<MenuButtonWebApp> Ptr;

    MenuButtonWebApp() {
        this->type = TYPE;
    }

    /**
     * @brief Text on the button
     */
    std::string text;

    /**
     * @brief Description of the Web App that will be launched when the user presses the button.
     * The Web App will be able to send an arbitrary message on behalf of the user using the method Api::answerWebAppQuery.
     */
    WebAppInfo::Ptr webApp;
};
}

#endif //TGBOT_MENUBUTTONWEBAPP_H


text:
using System;
using System.Globalization;

namespace SharpYaml.Events
{
	/// <summary>
	/// Represents an alias event.
	/// </summary>
	public class AnchorAlias : ParsingEvent
	{
		/// <summary>
		/// Gets a value indicating the variation of depth caused by this event.
		/// The value can be either -1, 0 or 1. For start events, it will be 1,
		/// for end events, it will be -1, and for the remaining events, it will be 0.
		/// </summary>
		public override int NestingIncrease {
			get {
				return 0;
			}
		}

		/// <summary>
		/// Gets the event type, which allows for simpler type comparisons.
		/// </summary>
		internal override EventType Type {
			get {
				return EventType.YAML_ALIAS_EVENT;
			}
		}

		private readonly string value;

		/// <summary>
		/// Gets the value of the alias.
		/// </summary>
		public string Value
		{
			get
			{
				return value;
			}
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="AnchorAlias"/> class.
		/// </summary>
		/// <param name="value">The value of the alias.</param>
		/// <param name="start">The start position of the event.</param>
		/// <param name="end">The end position of the event.</param>
		public AnchorAlias(string value, Mark start, Mark end)
			: base(start, end)
		{
			if(string.IsNullOrEmpty(value)) {
				throw new YamlException(start, end, "Anchor value must not be empty.");
			}

			if(!NodeEvent.anchorValidator.IsMatch(value)) {
				throw new YamlException(start, end, "Anchor value must contain alphanumerical characters only.");
			}

			this.value = value;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="AnchorAlias"/> class.
		/// </summary>
		/// <param name="value">The value of the alias.</param>
		public AnchorAlias(string value)
			: this(value, Mark.Empty, Mark.Empty)
		{
		}

		/// <summary>
		/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
		/// </returns>
		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "Alias [value = {0}]", value);
		}
	}
}


text:
'use strict';
const common = require('../common');
const { MessageChannel } = require('worker_threads');

// Make sure that .start() and .stop() do not throw on closing/closed
// MessagePorts.
// Refs: https://github.com/nodejs/node/issues/26463

function dummy() {}

{
  const { port1, port2 } = new MessageChannel();
  port1.close(common.mustCall(() => {
    port1.on('message', dummy);
    port1.off('message', dummy);
    port2.on('message', dummy);
    port2.off('message', dummy);
  }));
  port1.on('message', dummy);
  port1.off('message', dummy);
  port2.on('message', dummy);
  port2.off('message', dummy);
}

{
  const { port1 } = new MessageChannel();
  port1.on('message', dummy);
  port1.close(common.mustCall(() => {
    port1.off('message', dummy);
  }));
}


text:
package com.livescribe.aws.heartbeat.orm.dao.impl;
// Generated Nov 9, 2011 5:40:48 PM by Hibernate Tools 3.2.2.GA

import static org.hibernate.criterion.Example.create;

import java.util.List;

import org.hibernate.LockMode;
import org.springframework.transaction.annotation.Transactional;

import com.livescribe.aws.heartbeat.orm.PenOn;
import com.livescribe.aws.heartbeat.orm.dao.AbstractDao;
import com.livescribe.aws.heartbeat.orm.dao.GenericDao;

/**
 * Home object for domain model class PenOn.
 * @see com.livescribe.aws.heartbeat.orm.PenOn
 * @author Hibernate Tools
 */
public class PenOnDaoImpl extends AbstractDao implements GenericDao<PenOn> {

    @Transactional
    public void persist(PenOn transientInstance) {
        logger.debug("persisting PenOn instance");
        try {
            sessionFactory.getCurrentSession().persist(transientInstance);
            logger.debug("persist successful");
        }
        catch (RuntimeException re) {
            logger.error("persist failed", re);
            throw re;
        }
    }

    public void attachDirty(PenOn instance) {
        logger.debug("attaching dirty PenOn instance");
        try {
            sessionFactory.getCurrentSession().saveOrUpdate(instance);
            logger.debug("attach successful");
        }
        catch (RuntimeException re) {
            logger.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(PenOn instance) {
        logger.debug("attaching clean PenOn instance");
        try {
            sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
            logger.debug("attach successful");
        }
        catch (RuntimeException re) {
            logger.error("attach failed", re);
            throw re;
        }
    }

    public void delete(PenOn persistentInstance) {
        logger.debug("deleting PenOn instance");
        try {
            sessionFactory.getCurrentSession().delete(persistentInstance);
            logger.debug("delete successful");
        }
        catch (RuntimeException re) {
            logger.error("delete failed", re);
            throw re;
        }
    }

    public PenOn merge(PenOn detachedInstance) {
//        logger.debug("merging PenOn instance");
        try {
            PenOn result = (PenOn) sessionFactory.getCurrentSession()
                    .merge(detachedInstance);
//            logger.debug("merge successful");
            return result;
        }
        catch (RuntimeException re) {
            logger.error("merge failed", re);
            throw re;
        }
    }

    public PenOn findById( java.lang.Long id) {
        logger.debug("getting PenOn instance with id: " + id);
        try {
            PenOn instance = (PenOn) sessionFactory.getCurrentSession()
                    .get("com.livescribe.aws.heartbeat.orm.PenOn", id);
            if (instance==null) {
                logger.debug("get successful, no instance found");
            }
            else {
                logger.debug("get successful, instance found");
            }
            return instance;
        }
        catch (RuntimeException re) {
            logger.error("get failed", re);
            throw re;
        }
    }

    public List<PenOn> findByExample(PenOn instance) {
        logger.debug("finding PenOn instance by example");
        try {
            List<PenOn> results = (List<PenOn>) sessionFactory.getCurrentSession()
                    .createCriteria("com.livescribe.aws.heartbeat.orm.PenOn")
                    .add( create(instance) )
            .list();
            logger.debug("find by example successful, result size: " + results.size());
            return results;
        }
        catch (RuntimeException re) {
            logger.error("find by example failed", re);
            throw re;
        }
    }

}


text:
__author__    = 'Bojan Delic <bojan@delic.in.rs>'
__date__      = '02 January 2013'
__copyright__ = 'Copyright (c) 2013 Bojan Delic'

from samovar.commander import BaseCommand
from ._parsing import HgStyle, HgLexer, PARSERS

class Command(BaseCommand):
    '''Performs hg diff command on repositories.

    Note that using --rev or --change options does not make sense without --repo option,
    because every repository has different changesets.
    But these options can be useful if used with tag that are present in every repository.
    '''

    option_list = BaseCommand.option_list + (
        ('r, rev',                 {'action': 'store', 'dest': 'revision', 'help': 'Revision.'}),
        ('c, change',              {'action': 'store',      'help': 'Change made by revision.'}),
        ('a, text',                {'action': 'store_true', 'help': 'Treat all files as text.'}),
        ('g, git',                 {'action': 'store_true', 'help': 'Use git extended diff format.'}),
        ('p, show-function',       {'action': 'store_true', 'help': 'Show which function each change is in.'}),
        ('reverse',                {'action': 'store_true', 'help': 'Produce diff that undoes the changes.'}),
        ('w, ignore-all-space',    {'action': 'store_true', 'help': 'Ignore white space when comparing lines'}),
        ('b, ignore-space-change', {'action': 'store_true', 'help': 'Ignore changes in amount of white space.'}),
        ('B, ignore-blank-lines',  {'action': 'store_true', 'help': 'Ignore changes whose lines are all blank.'}),
        ('stat',                   {'action': 'store_true', 'help': 'Output diffstat-style summary of changes.'}),
        ('U, unified', {
            'action'  : 'store',
            'type'    : int,
            'dest'    : 'unified',
            'default' : -1,
            'help'    : 'Number of lines of context to show.'
        }),
    )

    Style = HgStyle
    Lexer = HgLexer
    LexerConfig = {
        'parse'  : True,
        'parser' : PARSERS['diff'],
        'indent' : 0,
    }

    def handle(self, *args, **kwargs):
        for repo in self.config.repositories:
            status, output, error = repo.diff(**kwargs)
            self.ui.report(repo, status, {'output': output, 'error': error})


text:
<?php
class language extends model {

	function __construct($registry, $id) {

		$this->_registry = $registry;
		$this->_tbl_data = TBL_LNG;
		parent::__construct($this->initP($id));

	}

	private function initP($id) {

		return $this->initDbProp($id);

	}

	public static function get($registry, $opts=null) {

		$objs = array();
		$where = gOpt($opts, "where", '');
		$rows = $registry->db->autoSelect("id", TBL_LNG, $where, 'language');
		foreach($rows as $row) $objs[] = new language($registry, $row['id']);

		return $objs;

	}

	public static function getFromLabel($registry, $label) {

		$rows = $registry->db->autoSelect("id", TBL_LNG, "label='$label'", 'language');
		if(count($rows)) return new language($registry, $rows[0]['id']);

		return null;

	}

	public static function setLanguage($registry) {

		$language = null;
		if($code = cleanInput('get', 'lng', 'string')) {
			// charge language and put it in session
			$rows = $registry->db->autoSelect(array("id", "language"), TBL_LNG, "code='$code'", 'language');
			$language = $rows[0]['language'];
			$_SESSION['lng'] = $language;
			header("Location: ".preg_replace("#\?.*$#", "", $_SERVER['REQUEST_URI']));
		}
		elseif(isset($_SESSION['lng'])) {
			// use session language
			$language = $_SESSION['lng'];
		}

		if(!$language) {
			// default language
			$rows = $registry->db->autoSelect(array("id", "language"), TBL_LNG, "main='1'", 'language');
			$language = $rows[0]['language'];
			$_SESSION['lng'] = $language;
		}

		return $language;
	}

}

?>


text:
/**
	I am not satisfied with how this camera is working, but I got stuck in my approach and
	could not come up with a better solution.

	The solution is based on looking at a specific point on a wall. This
	makes it necessary to keep track of which wall the player is looking at
	(for example the Left, Right, Front, or Back) to be able to retrieve
	the corresponding camera vector.
*/

#define RESOLUTION 512
#define RESTRICTION 0.6f

class Camera
{
public:
	Camera()
	{
		e = glm::vec3(0,0,0);
		eyeWall = 'a';
		myX = 0.0f;
		myY = 0.0f;
	}

	~RenderEngine()
	{
	}

	// Move the camera, returning the new vector
	// e (eye position).
	// Takes the camera vector c (reference point)
	// to move closer to that point
	glm::vec3 move(glm::vec3 c) {
		glm::vec3 tmp = c*0.01f;
		e += tmp;
		checkBorders();
		return e;
	}

	// Check to see if the eye is trying to
	// move to a non wishful position
	void checkBorders() {
		for (int i=0; i<3; i++) {
			if (e[i] >= RESTRICTION)
				e[i] = RESTRICTION;
			else if (e[i] <= -RESTRICTION)
				e[i] = -RESTRICTION;
		}
	}

	// Get the corresponding camera vector when looking at Back wall
	glm::vec3 getBack() {
		return glm::vec3(myX, 1, myY);
	}

	// Get the corresponding camera vector when looking at Front wall
	glm::vec3 getFront() {
		return glm::vec3(-myX, -1, myY);
	}

	// Get the corresponding camera vector when looking at Left wall
	glm::vec3 getLeft() {
		return glm::vec3(-1, myX, myY);
	}

	// Get the corresponding camera vector when looking at Right wall
	glm::vec3 getRight() {
		return glm::vec3(1, -myX, myY);
	}

	glm::vec3 getCameraVector() {
		switch(eyeWall) {
			case 'a':
				return getBack();
			case 'f':
				return getFront();
			case 'l':
				return getLeft();
			case 'r':
				return getRight();
		}
	}

	// Input is x = Event.MouseMove.X
	// and 		y = Event.MouseMove.Y
	//
	// and output is a camera vector c (reference point)
	glm::vec3 updateAndGetCameraVec3(int x, int y) {
		float changeX = (float)(RESOLUTION/2-x)/-300.0;
		float changeY = (float)(RESOLUTION/2-y)/300.0;
		updateCoordinates(changeX, changeY);
		return getCameraVector();
	}

	// Trim to prevent looking around "to fast"
	float trim(float val) {
		if(val >= 2.0)
			val = 1.99;
		else if(val <= -2.0)
			val = -1.99;
		return val;
	}

	void updateCoordinates(float x, float y) {
		x = trim(x);
		y = trim(y);
		myX += x;
		myY += y;
		if(myX <= -1.0f) {
			myX+=1.999;
			updateDirections('l');
		}
		else if(myX >= 1.0f) {
			myX-=1.999;
			updateDirections('r');
		}
		if(myY <= -1.0f) {
			myY = -1.0f;
		}
		else if(myY >= 1.0f) {
			myY = 1.0f;
		}
	}

	void updateDirections(char direction) {
		switch (eyeWall) {
			case 'a':
				return updateBack(direction);
			case 'f':
				return updateFront(direction);
			case 'l':
				return updateLeft(direction);
			case 'r':
				return updateRight(direction);
		}
	}

	void updateBack(char direction) {
		switch (direction) {
			case 'u':
					eyeWall = 't';
					break;
			case 'd':
					eyeWall = 'b';
					break;
			case 'l':
					eyeWall = 'l';
					break;
			case 'r':
					eyeWall = 'r';
					break;
		}
	}

	void updateFront(char direction) {
		switch (direction) {
			case 'u':
					eyeWall = 't';
					break;
			case 'd':
					eyeWall = 'b';
					break;
			case 'l':
					eyeWall = 'r';
					break;
			case 'r':
					eyeWall = 'l';
					break;
		}
	}

	void updateLeft(char direction) {
		switch (direction) {
			case 'u':
					eyeWall = 't';
					break;
			case 'd':
					eyeWall = 'b';
					break;
			case 'l':
					eyeWall = 'f';
					break;
			case 'r':
					eyeWall = 'a';
					break;
		}
	}

	void updateRight(char direction) {
		switch (direction) {
			case 'u':
					eyeWall = 't';
					break;
			case 'd':
					eyeWall = 'b';
					break;
			case 'l':
					eyeWall = 'a';
					break;
			case 'r':
					eyeWall = 'f';
					break;
		}
	}

private:
	float myX, myY;
	char eyeWall;
	glm::vec3 e;
};

/** Snippet

class Program4
{
public:
	int WIDTH;
	int HEIGHT;
	Program4()
	{
		int WIDTH = 960;
		int HEIGHT = 960;
		App = new sf::Window(sf::VideoMode(WIDTH, HEIGHT, 32), "program4");

		App->SetPosition(800,0);					//Set window position
		App->SetCursorPosition(WIDTH/2, HEIGHT/2);	//Set cursor position
		App->ShowMouseCursor(false);				//Hide cursor

		while (App->IsOpened())
		{
			App->SetActive();
			render.display();
			App->Display();
			handleEvents();
			App->SetCursorPosition(RESOLUTION/2, RESOLUTION/2);		// Center cursor position
		}
	}

private:
	sf::Window *App;
	RenderEngine render;

	void handleEvents()
	{
		const sf::Input& Input = App->GetInput();
		sf::Event Event;
		while (App->GetEvent(Event))
		{
			if (Event.Type == sf::Event::MouseMoved)
				render.updateCamera(Event.MouseMove.X, Event.MouseMove.Y);

			if (Event.Type == sf::Event::Closed)
				App->Close();

			if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
				App->Close();

			if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Space))
				render.move();
		}
	}
};

*/


text:
from django.conf.urls import url
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import gettext_lazy as _

urlpatterns = i18n_patterns(
    url(_('translated/'), lambda x: x, name='i18n_prefixed'),
)