text:
from .constants import DESCRIPTOR_TYPE, DEVICE_CAPABILITY_TYPE, ENDPOINT
from .formatters import UInt8Formatter, UInt16Formatter, BCD16Formatter, BitMapFormatter, StringFormatter, Formatter, CommentFormatter
from .defaults import defaults

class Descriptor(object):
    def __init__(self, descriptor_type, *formatters):
        self._data = []
        self._size = 0
        self.append(UInt8Formatter(descriptor_type, 'Descriptor Type'))

        for formatter in formatters:
            self.append(formatter)

    def append(self, formatter):
        self._data.append(formatter)
        self._size += len(formatter)

    def prepend(self, formatter):
        self._data.prepend(formatter)
        self._size += len(formatter)

    def get_data(self):
        return [UInt8Formatter(len(self), 'Descriptor Size')] + self._data

    def __len__(self):
        return self._size + 1

    def __call__(*args):
        raise Exception(args)

    def __str__(self):
        formatters = self.get_data()
        max_main_length = max(formatter.get_main_length() for formatter in formatters)
        for formatter in formatters:
            formatter.set_max_main_length(max_main_length)
        return '{\n' + ''.join('\t{}\n'.format(formatter) for formatter in formatters) + '}'

class DescriptorWithChildren(Descriptor):
    def __init__(self, descriptor_type, *children):
        super(DescriptorWithChildren, self).__init__(descriptor_type)

        self._children = []
        self._children_size = 0

        self._size_formatter = UInt16Formatter(0, 'Size of descriptor and all its sub descriptors')
        self._number_formatter = UInt8Formatter(0, 'Number of sub descriptors')

        for child in children:
            self.add(child)

    def add(self, child):
        self._children.append(child)
        try:
            self._children_size += child.get_size()
        except AttributeError:
            self._children_size += len(child)

    def get_size(self):
        return len(self) + self._children_size

    def get_number(self):
        return len(self._children)

    def get_data(self):
        self._size_formatter.set(self.get_size())
        self._number_formatter.set(self.get_number())

        data = super(DescriptorWithChildren, self).get_data()
        for child in self._children:
            data += [Formatter(), CommentFormatter(child.__class__.__name__)] + child.get_data()

        return data

class StringDescriptor(Descriptor):
    def __init__(self, *args):
        super(StringDescriptor, self).__init__(DESCRIPTOR_TYPE.STRING)
        if len(args) == 1 and (type(args[0]) == str or type(args[0]) == unicode):
            self.append(StringFormatter(args[0], 'String'))
        else:
            for i, langid in enumerate(args):
                self.append(UInt16Formatter(langid, 'Language Identifier {}'.format(i)))

class DeviceDescriptor(Descriptor):
    def __init__(self, **kwargs):
        super(DeviceDescriptor, self).__init__(DESCRIPTOR_TYPE.DEVICE)

        self.append(BCD16Formatter(defaults.get('usb_version', kwargs, 2.0), "USB Version"))
        self.append(UInt8Formatter(defaults.get('device_class', kwargs, 0), "Device Class"))
        self.append(UInt8Formatter(defaults.get('device_subclass', kwargs, 0), "Device Sub-class"))
        self.append(UInt8Formatter(defaults.get('device_protocol', kwargs, 0), "Device Protocol"))
        self.append(UInt8Formatter(defaults.get('max_packet_size', kwargs, 8), "Max packet size for EP0"))
        self.append(UInt16Formatter(defaults.get('vendor_id', kwargs, 0), "Vendor ID"))
        self.append(UInt16Formatter(defaults.get('product_id', kwargs, 0), "Product ID"))
        self.append(UInt16Formatter(defaults.get('device_release_number', kwargs, 0), "Device release number"))
        self.append(UInt8Formatter(defaults.get('manufacturer_string', kwargs, 0), "Manufacturer string index"))
        self.append(UInt8Formatter(defaults.get('product_string', kwargs, 0), "Product string index"))
        self.append(UInt8Formatter(defaults.get('serial_number_string', kwargs, 0), "Serial string index"))
        self.append(UInt8Formatter(defaults.get('number_of_configurations', kwargs, 1), "Number of configurations"))

class ConfigurationDescriptor(DescriptorWithChildren):
    def __init__(self, *children, **kwargs):
        super(ConfigurationDescriptor, self).__init__(DESCRIPTOR_TYPE.CONFIGURATION, *children)

        self.append(self._size_formatter)
        self.append(self._number_formatter)

        self.append(UInt8Formatter(defaults.get('configuration_number', kwargs, 1), "Configuration Number"))
        self.append(UInt8Formatter(defaults.get('configuration_string', kwargs, 0), "Configuration String"))

        self.append(BitMapFormatter(
            1,
            [
                0, 0, 0, 0, 0,
                kwargs.get('remote_wakeup', 0),
                kwargs.get('self_powered', 0),
            ],
            "Attributes"
        ))

        self.append(UInt8Formatter(defaults.get('max_power', kwargs, 0), "Max power"))

    def get_number(self):
        n = 0
        for child in self._children:
            if type(child) == InterfaceDescriptor:
                n += 1
        return n

class InterfaceDescriptor(Descriptor):
    def __init__(self, **kwargs):
        super(InterfaceDescriptor, self).__init__(DESCRIPTOR_TYPE.INTERFACE)

        self.append(UInt8Formatter(defaults.get('interface_number', kwargs, 0), "Interface number"))
        self.append(UInt8Formatter(defaults.get('alternate_setting', kwargs, 0), "Alternate setting"))
        self.append(UInt8Formatter(defaults.get('endpoint_count', kwargs, 0), "Number of endpoints"))
        self.append(UInt8Formatter(defaults.get('interface_class', kwargs, 0), "Interface Class"))
        self.append(UInt8Formatter(defaults.get('interface_subclass', kwargs, 0), "Interface Sub-class"))
        self.append(UInt8Formatter(defaults.get('interface_protocol', kwargs, 0), "Interface Protocol"))
        self.append(UInt8Formatter(defaults.get('interface_string', kwargs, 0), "Interface String"))

class EndpointDescriptor(Descriptor):
    def __init__(self, **kwargs):
        super(EndpointDescriptor, self).__init__(DESCRIPTOR_TYPE.ENDPOINT)

        endpoint_number = defaults.get('endpoint_number', kwargs, 0)
        endpoint_in = defaults.get('endpoint_in', kwargs, False)
        self.append(BitMapFormatter(
            1,
            BitMapFormatter.uint_parse(4, endpoint_number) +
            [
                0, 0, 0,
                endpoint_in,
            ],
            "Endpoint Address"
        ))

        attributes = None
        transfer_type = defaults.get('transfer_type', kwargs, ENDPOINT.TRANSFER_TYPE_CONTROL)
        if transfer_type == ENDPOINT.TRANSFER_TYPE_CONTROL or transfer_type == ENDPOINT.TRANSFER_TYPE_BULK:
            attributes = BitMapFormatter(
                1,
                BitMapFormatter.uint_parse(2, transfer_type),
                "Attributes"
            )
        elif transfer_type == ENDPOINT.TRANSFER_TYPE_INTERRUPT:
            attributes = BitMapFormatter(
                1,
                BitMapFormatter.uint_parse(2, transfer_type) +
                [0, 0] +
                BitMapFormatter.uint_parse(2, defaults.get('usage_type', kwargs, ENDPOINT.USAGE_TYPE_INTERRUPT_PERIODIC)),
                "Attributes"
            )
        elif transfer_type == ENDPOINT.TRANSFER_TYPE_ISOCHRONOUS:
            attributes = BitMapFormatter(
                1,
                BitMapFormatter.uint_parse(2, transfer_type) +
                BitMapFormatter.uint_parse(2, defaults.get('synchronization_type', kwargs, ENDPOINT.SYNCHRONIZATION_TYPE_NONE)) +
                BitMapFormatter.uint_parse(2, defaults.get('usage_type', kwargs, ENDPOINT.USAGE_TYPE_ISOCHRONOUS_DATA)),
                "Attributes"
            )
        else:
            raise Exception("Invalid transfer type")

        self.append(attributes)

        default_max_packet_size = 512 if transfer_type == ENDPOINT.TRANSFER_TYPE_CONTROL else 1024
        self.append(UInt16Formatter(defaults.get('max_packet_size', kwargs, default_max_packet_size), "Max Packet Size"))
        self.append(UInt8Formatter(defaults.get('interval', kwargs, 0), "Interval"))

class InterfaceAssociationDescriptor(Descriptor):
    def __init__(self, **kwargs):
        super(InterfaceAssociationDescriptor, self).__init__(DESCRIPTOR_TYPE.INTERFACE_ASSOCIATION)

        self.append(UInt8Formatter(defaults.get('first_interface_number', kwargs, 0), "First interface number"))
        self.append(UInt8Formatter(defaults.get('interface_count', kwargs, 0), "Number of interfaces"))
        self.append(UInt8Formatter(defaults.get('interface_class', kwargs, 0), "Interface Class"))
        self.append(UInt8Formatter(defaults.get('interface_subclass', kwargs, 0), "Interface Sub-class"))
        self.append(UInt8Formatter(defaults.get('interface_protocol', kwargs, 0), "Interface Protocol"))
        self.append(UInt8Formatter(defaults.get('interface_association_string', kwargs, 0), "Interface Association String"))

class DeviceQualifierDescriptor(Descriptor):
    def __init__(self, **kwargs):
        super(DeviceQualifierDescriptor, self).__init__(DESCRIPTOR_TYPE.DEVICE_QUALIFIER)

        self.append(BCD16Formatter(defaults.get('usb_version', kwargs, 2.0), "USB Version"))
        self.append(UInt8Formatter(defaults.get('device_class', kwargs, 0), "Device Class"))
        self.append(UInt8Formatter(defaults.get('device_subclass', kwargs, 0), "Device Sub-class"))
        self.append(UInt8Formatter(defaults.get('device_protocol', kwargs, 0), "Device Protocol"))
        self.append(UInt8Formatter(defaults.get('max_packet_size', kwargs, 8), "Max packet size for EP0"))
        self.append(UInt8Formatter(defaults.get('number_of_configurations', kwargs, 1), "Number of configurations"))
        self.append(UInt8Formatter(0, "Reserved"))

class BOSDescriptor(DescriptorWithChildren):
    def __init__(self, *children):
        super(BOSDescriptor, self).__init__(DESCRIPTOR_TYPE.BOS, *children)

        self.append(self._size_formatter)
        self.append(self._number_formatter)

class CapabilityDescriptor(Descriptor):
    def __init__(self, capability_type, *formatters):
        super(CapabilityDescriptor, self).__init__(
            DESCRIPTOR_TYPE.DEVICE_CAPABILITY,
            UInt8Formatter(capability_type, "Device capability type"),
            *formatters
        )

class USB20ExtensionDescriptor(CapabilityDescriptor):
    def __init__(self, lpm=False, besl=False, besl_baseline=None, besl_deep=None):
        super(USB20ExtensionDescriptor, self).__init__(DEVICE_CAPABILITY_TYPE.USB_20_EXTENSION)

        self.append(BitMapFormatter(
            4,
            [
                0,
                lpm,
                besl,
                besl_baseline is not None,
                besl_deep is not None,
                0, 0, 0
            ] +
            (BitMapFormatter.uint_parse(4, besl_baseline) if besl_baseline else []) +
            (BitMapFormatter.uint_parse(4, besl_deep) if besl_deep else []),
            "Attributes"
        ))

class SuperSpeedDeviceCapabilityDescriptor(CapabilityDescriptor):
    def __init__(self, ltm=False, supported_speed_low=False, supported_speed_full=False, supported_speed_high=False, supported_speed_gen1=False, full_functionality_support_speed=0, u1_device_exit_latency=0, u2_device_exit_latency=0):
        super(SuperSpeedDeviceCapabilityDescriptor, self).__init__(DEVICE_CAPABILITY_TYPE.SUPERSPEED_USB)

        self.append(BitMapFormatter(1, [0, ltm], "Attributes"))
        self.append(BitMapFormatter(2, [
            supported_speed_low,
            supported_speed_full,
            supported_speed_high,
            supported_speed_gen1,
        ], "Supported speeds"))
        self.append(UInt8Formatter(full_functionality_support_speed, "Full functionality support speed"))
        self.append(UInt8Formatter(u1_device_exit_latency, "U1 Device Exit Latency"))
        self.append(UInt16Formatter(u2_device_exit_latency, "U2 Device Exit Latency"))

class SuperSpeedEndpointCompanionDescriptor(Descriptor):
    def __init__(self, **kwargs):
        super(SuperSpeedEndpointCompanionDescriptor, self).__init__(DESCRIPTOR_TYPE.SUPERSPEED_USB_ENDPOINT_COMPANION)

        self.append(UInt8Formatter(defaults.get('max_burst', kwargs, 1)-1, "Max Burst"))

        max_streams = kwargs.get('max_streams')
        mult = kwargs.get('mult')
        if max_streams is not None:
            if max_streams < 16:
                self.append(UInt8Formatter(max_streams, "Max streams"))
            else:
                raise Exception("Max streams out of range")
        elif mult is not None:
            self.append(BitMapFormatter(
                1,
                BitMapFormatter.uint_parse(2, mult),
                [
                    0, 0, 0, 0, 0,
                    kwargs.get('ssp_iso_companion', False)
                ],
                "Attributes",
            ))
        else:
            self.append(UInt8Formatter(0, "Attributes"))

        self.append(UInt16Formatter(defaults.get('bytes_per_interval', kwargs, 0), "Bytes Per Interval"))


text:
<?php

declare(strict_types=1);

namespace Hostnet\Component\CssSniff\Output;

/**
 * Checkstyle xml formatter
 */
final class CheckstyleFormatter implements FormatterInterface
{
    private $pretty_format;

    public function __construct(bool $pretty_format)
    {
        $this->pretty_format = $pretty_format;
    }

    /**
     * {@inheritdoc}
     */
    public function format(array $files): string
    {
        $out  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        $out .= "<checkstyle version=\"1.0.0\">\n";

        foreach ($files as $file) {
            if ($file->isOk()) {
                continue;
            }

            $out .= sprintf("  <file name=\"%s\">\n", $file->getName());

            foreach ($file->getViolations() as $violation) {
                $out .= sprintf(
                    "    <error line=\"%d\" column=\"%d\" severity=\"error\" message=\"%s\" source=\"%s\"/>\n",
                    $violation->getLine(),
                    $violation->getStart(),
                    htmlspecialchars($violation->getMsg()),
                    htmlspecialchars($violation->getSource())
                );
            }

            $out .= "  </file>\n";
        }

        $out .= "</checkstyle>\n";

        return $out;
    }

    /**
     * {@inheritdoc}
     */
    public function formatError(\Exception $error): string
    {
        return $error->getMessage();
    }
}

redpajama_set_name: RedPajamaGithub


text:
class BLEUModelImpl;

class BLEUModel : public FeatureFunction {
 public:
  // param = "filename.lm [-o n]"
  BLEUModel(const std::string& param);
  ~BLEUModel();
  virtual void FinalTraversalFeatures(const void* context,
                                      SparseVector<double>* features) const;
  std::string DebugStateToString(const void* state) const;
  static std::string usage(bool param,bool verbose);
 protected:
  virtual void TraversalFeaturesImpl(const SentenceMetadata& smeta,
                                     const HG::Edge& edge,
                                     const std::vector<const void*>& ant_contexts,
                                     SparseVector<double>* features,
                                     SparseVector<double>* estimated_features,
                                     void* out_context) const;
 private:
  const int fid_;
  mutable BLEUModelImpl* pimpl_;
};
#endif


text:
window.onload = function() {
  console.log("PAGE_ONLOAD_EVENT" + location.hash);
};


text:
Reduce over collections without recomputing everything when new items arrive or
when items in the source change.

[![browser support](http://ci.testling.com/substack/rolling-reduce.png)](http://ci.testling.com/substack/rolling-reduce)

[![build status](https://secure.travis-ci.org/substack/rolling-reduce.png)](http://travis-ci.org/substack/rolling-reduce)

# example

## sum

``` js
var reduce = require('rolling-reduce');
var summer = reduce(0);

summer.on('insert', function (sum, x) {
    return sum + x;
});

summer.on('update', function (sum, xPrev, x) {
    return sum - xPrev + x;
});

summer.on('remove', function (sum, x) {
    return sum - x;
});

summer.on('result', function (sum) {
    console.log('sum=' + sum);
});

[ 7, 8, 9 ].forEach(function (x) {
    summer.insert(x);
}); // 7 + 8 + 9 = 24

summer.remove(7); // 24 - 7 = 17

summer.update(9, 10); // 17 - 9 + 10 = 18

summer.insert(11); // 18 + 11 = 29
```

```
$ node example/sum.js
sum=7
sum=15
sum=24
sum=17
sum=18
sum=29
```

## pairs

``` js
var reduce = require('rolling-reduce');
var pairs = reduce([]);

function indexOf (xs, x) {
    for (var i = 0; i < xs.length; i++) {
        if (xs[i][0] === x.id) return i;
    }
    return -1;
}

pairs.on('insert', function (xs, x) {
    xs.push([ x.id, x.value ]);
    return xs;
});

pairs.on('update', function (xs, xPrev, x) {
    var ix = indexOf(xs, xPrev);
    xs[ix][1] = x.value;
    return xs;
});

pairs.on('remove', function (xs, x) {
    var ix = indexOf(xs, x);
    if (ix >= 0) xs.splice(ix, 1);
    return xs;
});

pairs.on('result', function (res) {
    console.log('pairs=' + JSON.stringify(res));
});

var abc = { id : 'abc', value : 7 };
pairs.insert(abc);

var def = { id : 'def', value : 8 };
pairs.insert(def);

var ghi = { id : 'ghi', value : 9 };
pairs.insert(ghi);

pairs.remove(abc);

pairs.update(def, { id : 'def', value : 555 });

var xyz = { id : 'xyz', value : 5 };
pairs.insert(xyz);
```

```
$ node example/pairs.js
pairs=[["abc",7]]
pairs=[["abc",7],["def",8]]
pairs=[["abc",7],["def",8],["ghi",9]]
pairs=[["def",8],["ghi",9]]
pairs=[["def",555],["ghi",9]]
pairs=[["def",555],["ghi",9],["xyz",5]]
```

# methods

``` js
var reduce = require('rolling-reduce')
```

## var r = reduce(init)

Create a reduce object `r` from an initial accumulator value `init`.

The event handlers `'insert'`, `'update'`, and `'remove'` are responible for
computing the reduction on the accumulator.

## r.insert(x)

Insert a new object `x` into the source.

## r.update(xPrev, x)

Update over the previous item `xPrev` with a new source item `x`.

## r.remove(x)

Remove the item `x` from the source.

# events

## r.on('insert', cb)

The callback `cb(acc,x)` fires when `r.insert(x)` is called.

`cb(acc,x)` should return the new value for the accumulator `acc`.

## r.on('update', cb)

The callback `cb(acc,xPrev,x)` fires when `r.update(xPrev,x)` is called.

Note that `xPrev` and `x` are merely a convention and the values from
`r.update()` are passed directly through.

`cb(acc,xPrev,x)` should return the new value for the accumulator `acc`.

## r.on('remove', cb)

The callback `cb(acc,x)` fires when `r.remove(x)` is called.

Note that `x` is merely a convention and you can choose to signify elements in
any scheme that you like.

`cb(acc,x)` should return the new value for the accumulator `acc`.

# install

With [npm](https://npmjs.org) do:

```
npm install rolling-reduce
```

# license

MIT


text:
package softlayer_scale_asset_hardware

// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED


text:
@aQute.bnd.annotation.Version("1.1.0")
package com.adobe.acs.commons.fam.actions;


text:
/*
** Gmail Backup Database Definition
*/

PRAGMA auto_vacuum        = none;
PRAGMA encoding           = "UTF-8";
PRAGMA legacy_file_format = 0;
PRAGMA page_size          = 4096;
PRAGMA user_version       = {uv};

BEGIN;

-- TABLE: conf -----------------------------------------------------------------
-- Persistent storage for database settings.

CREATE TABLE conf (
	key    TEXT PRIMARY KEY NOT NULL,
	value  TEXT
);

-- Full account name; set by the first backup (e.g. someone@example.com)
INSERT INTO conf VALUES ('account', NULL);

-- File digest algorithm (any algorithm in hashlib.algorithms_guaranteed)
INSERT INTO conf VALUES ('digest', 'sha1');

-- Directory hierarchy levels (reduces the number of files in each directory)
INSERT INTO conf VALUES ('dir_levels',  3);

-- File compression method (none or gzip)
INSERT INTO conf VALUES ('comp_method', 'gzip');

-- File compression level when comp_method is gzip
INSERT INTO conf VALUES ('comp_level', 6);

-- How long to keep deleted messages (in seconds, default = 365 days)
INSERT INTO conf VALUES ('retention', 31536000);

-- ID of the last message successfully uploaded during a restore operation
INSERT INTO conf VALUES ('resume', NULL);

-- Indexing status, set to 1 when the most recent backup is already indexed
INSERT INTO conf VALUES ('indexed', 0);

-- TABLE: op -------------------------------------------------------------------
-- Master table that contains one row for each operation (command) performed.

CREATE TABLE op (
	op_id   INTEGER PRIMARY KEY AUTOINCREMENT,  -- Internal operation ID
	name    TEXT    NOT NULL,  -- Operation name ('backup', 'restore')
	start   INTEGER NOT NULL,  -- Start time (Unix timestamp)
	stop    INTEGER,           -- Stop time
	filter  TEXT,              -- Search string used to filter messages
	result  TEXT,              -- Result ('ok', 'abort', or 'error')
	info    TEXT               -- Additional result information
);

CREATE INDEX op_start ON op (start);

-- TABLE: file -----------------------------------------------------------------
-- Index of messages downloaded to disk.

CREATE TABLE file (
	file_id  INTEGER PRIMARY KEY,      -- Internal file ID
	op_id    INTEGER,                  -- Operation that downloaded this file
	digest   TEXT    NOT NULL UNIQUE,  -- Uncompressed file digest
	size     INTEGER NOT NULL,         -- Uncompressed file size in bytes

	FOREIGN KEY (op_id) REFERENCES op ON DELETE SET NULL
);

CREATE INDEX file_op_id ON file (op_id);

-- TABLE: flag -----------------------------------------------------------------
-- List of message flags returned by the IMAP server.

CREATE TABLE flag (
	flag_id  INTEGER PRIMARY KEY,     -- Internal flag list ID
	flags    TEXT    NOT NULL UNIQUE  -- Sorted flag list (separated by spaces)
);

-- TABLE: lbl ------------------------------------------------------------------
-- List of message labels.

CREATE TABLE lbl (
	lbl_id  INTEGER PRIMARY KEY,     -- Internal label list ID
	labels  TEXT    NOT NULL UNIQUE  -- Sorted label list (quoted strings)
);

-- TABLE: msg ------------------------------------------------------------------
-- Message index that ties all message components together.
-- The msg_id and thr_id columns contain signed 64-bit equivalents of the
-- unsigned 64-bit X-GM-MSGID and X-GM-THRID values.

CREATE TABLE msg (
	msg_id   INTEGER PRIMARY KEY,  -- External message ID (X-GM-MSGID)
	op_id    INTEGER NOT NULL,     -- The last backup to see this message
	file_id  INTEGER NOT NULL,     -- File contents
	flag_id  INTEGER,              -- Message flags  (NULL = no flags)
	lbl_id   INTEGER,              -- Message labels (NULL = no labels)
	thr_id   INTEGER NOT NULL,     -- Thread ID (X-GM-THRID)
	idate    INTEGER NOT NULL,     -- Internal date and time (Unix timestamp)

	FOREIGN KEY (op_id)   REFERENCES op   ON DELETE CASCADE,
	FOREIGN KEY (file_id) REFERENCES file ON DELETE CASCADE,
	FOREIGN KEY (flag_id) REFERENCES flag,
	FOREIGN KEY (lbl_id)  REFERENCES lbl
);

CREATE INDEX msg_op_id   ON msg (op_id);
CREATE INDEX msg_file_id ON msg (file_id);
CREATE INDEX msg_flag_id ON msg (flag_id);
CREATE INDEX msg_lbl_id  ON msg (lbl_id);
CREATE INDEX msg_thr_id  ON msg (thr_id);

-- VIEW: msg_view --------------------------------------------------------------
-- A complete overview of stored messages.

CREATE VIEW msg_view AS
	SELECT msg_id, msg.op_id, digest, size, flags, labels, thr_id, idate
	FROM msg, file USING (file_id)
	LEFT JOIN flag USING (flag_id)
	LEFT JOIN lbl  USING (lbl_id);

COMMIT;


text:
package p;
public class P {
  public P() {
  }
  public void foo() {}
}


text:
<?php

/**
 * This component is used for minor utility functions that we might need.
 */
class Utilities extends CComponent
{
    /**
     * Returns an array of random integers of a specified min, max, and size.
     * NOTE: This might generate numbers for which there are no database
     * entries in the relevant DB table (if using this to help query the DB).
     * This can happen in the case of an auto incrementing primary key that has
     * deleted entries.
     * @param int $min The smallest desired integer.
     * @param int $max The largest desired integer.
     * @param int $size The size of the array to be returned (the # of #'s).
     * @return Array An array of integers.
     */
    public function getRandomArray($min = 1, $max = 5, $size = 5)
    {
        $randomArray = array();
        while (count($randomArray) < $size ) {
            $randomNumber = mt_rand($min, $max);
            if ( !in_array($randomNumber,$randomArray) ) {
                $randomArray[] = $randomNumber;
            }
        }

        return $randomArray;
    }

    public function query($sql, $paramArray = array(), $queryType = 'execute')
    {
        $connection = Yii::app()->db;
        $command = $connection->createCommand($sql);
        $command->bindValues($paramArray);

        $queryType = strtolower($queryType);
        if ($queryType == 'column')
            return $command->queryColumn();
        elseif ($queryType == 'row')
            return $command->queryRow();
        elseif ($queryType == 'scalar')
            return $command->queryScalar();
        elseif ($queryType == 'execute')
            return $command->execute();
        elseif ($queryType == 'all')
            return $command->queryAll();
        else
            return 'Unknown query type!';
    }

    /**
     * Return the total number of non-limited, non-offset rows from the
     * latest executed query.
     * @return int A count of rows.
     */
    public function getTotalEntries()
    {
        $sql = "SELECT FOUND_ROWS()";

        return Utilities::query($sql, array(), 'scalar');
    }

    public function filterList($list, $filterText)
    {
//        var_dump($list); exit;
        $stringLength = strlen($filterText);
        foreach ($list as $key=>$element) {
            if ($filterText != substr($element, 0, $stringLength))
                unset($list[$key]);
        }
        return $list; exit;
    }

    /**
     * A simple function to get a success return given a success variable,
     * possible error text, and possible data to return.
     * @param boolean $success Represents the success of the task.
     * @param string $errorText Error text to return, if any.
     * @param mixed $data The data that succeeded or failed.
     * @return array An array describing task success or failure.
     */
    public function getSuccessReturn($success, $errorText = '', $data = '') {
        $returnArray = array("success"=>$success);
        // add error text if failure
        if ($success == false && !empty($errorText))
            $returnArray['error'] = $errorText;
        // add return data if success
//        if ($success == true && !empty($data))
        if ($success == true)
            $returnArray['returnData'] = $data;
        return $returnArray;
    }

    /**
     * Simply a JSON wrapper for getSuccessReturn
     * For params, see self::getSuccessReturn().
     * @return JSON A JSON encoded array describing task success or failure.
     */
    public function getFullSuccessReturn($success, $errorText = '', $data = '') {
        $returnArray = self::getSuccessReturn($success, $errorText, $data);
        return json_encode($returnArray);
    }

    public function getUrlStart() {
        if (isset($_SERVER['HTTPS']))
            return 'https://';
        else
            return 'http://';
    }

    /**
     * Gets an HTML/JavaScript safe version of the inputText. Prevents
     * frint-end injection, eg. javascript injection.
     * @param string $inputHtml The HTML/JavaScript to be converted.
     * @return string The converted (safe) output string.
     */
    public function cleanHtml($inputHtml) {
        return htmlentities($inputHtml);
    }
}

?>


text:
layout: default
---
### About Us

Our focus is to improve the current state of food chain and related commodities market through our SaaS platform.

In current reports, a world-wide finding by [Food and Agriculture Organization](http://www.fao.org/) (a UN Organization), [about a third of the food never reaches our plates](http://www.fao.org/save-food/en/), world-wide.

The wastage of food contributes to increased CO2 emission from the food wastage itself and also transportation. Other impact includes, increase in food prices (resulting in reduction of spending in other markets), impact on low-income families and securities, and others.

With the exponential increase in world-wide population, as well as food and energy demands, we are  motivated to design and develop software, hardware and consult in designing company policies that can help food producers, distributors, processors and retailers in the food supply chain.


text:
var assert = require('assert')

module.exports = function (_, dir, finish, gm) {
  var filename = dir + '/autoOrient.jpg';

  gm(dir + '/originalSideways.jpg').orientation(function (err, o) {
    if (err) return finish(err);

    assert.equal('RightTop', o);
    assert.ok(!! this.data['Profile-EXIF'], 'No Profile-EXIF data found');
    assert.equal('155x460', this.data.Geometry);

    // this image is sideways, but may be auto-oriented by modern OS's
    // try opening it in a browser to see its true orientation
    gm(dir + '/originalSideways.jpg')
    .autoOrient()
    .write(filename, function autoOrient (err) {
      if (err) return finish(err);

      // fs race condition
      setTimeout(function () {
        gm(filename).identify(function (err) {
          if (err) return finish(err);

          assert.equal('Unknown', this.data.Orientation);
          assert.ok(! this.data['Profile-EXIF'], 'Profile-EXIF still exists');
          assert.equal('460x155', this.data.Geometry);

          finish(err);
        });
      }, 200);
    });
  });

}


text:
import mongoose, { Schema } from 'mongoose'
import mongoosastic from '../lib/index'
import { MongoosasticDocument, MongoosasticModel } from '../lib/types'
import { config } from './config'

interface IRepo extends MongoosasticDocument {
  name: string,
  settingLicense: string,
  detectedLicense: string,
}

// -- Only index specific field
const RepoSchema = new Schema({
  name: {
    type: String,
    es_indexed: true
  },
  settingLicense: {
    type: String
  },
  detectedLicense: {
    type: String
  }
})

RepoSchema.plugin(mongoosastic, {
  transform: function (data: Record<string, unknown>, repo: IRepo) {
    data.license = repo.settingLicense || repo.detectedLicense
    return data
  }
})

const Repo = mongoose.model<IRepo, MongoosasticModel<IRepo>>('Repo', RepoSchema)

// -- Index with async transform function
const PodcastSchema = new Schema({name: {type: String, es_indexed: true}})

PodcastSchema.plugin(mongoosastic, {
  transform: async function (data: Record<string, unknown>) {
    data.name = await new Promise(
      resolve => setTimeout(
        () => resolve('Qwerpline'),
        50
      )
    )
    return data
  }
})

const Podcast = mongoose.model<IRepo, MongoosasticModel<IRepo>>('Podcast', PodcastSchema)

describe('Transform mode', function () {

  beforeAll(async function () {
    await config.deleteIndexIfExists(['repos', 'podcasts'])
    await mongoose.connect(config.mongoUrl, config.mongoOpts)
    await Repo.deleteMany()
    await Podcast.deleteMany()
  })

  afterAll(async function () {
    await Repo.deleteMany()
    await Podcast.deleteMany()
    await config.deleteIndexIfExists(['repos', 'podcasts'])
    await mongoose.disconnect()
  })

  it('should index with field "fullTitle"', async function () {

    await config.createModelAndEnsureIndex(Repo, {
      name: 'LOTR',
      settingLicense: '',
      detectedLicense: 'Apache'
    })

    const results = await Repo.search({
      query_string: {
        query: 'Apache'
      }
    })

    expect(results?.body.hits.total).toEqual(1)
  })

  it('should wait for promise if transform is async', async function () {

    await config.createModelAndEnsureIndex(Podcast, {
      name: 'The Fitzroy Diaries'
    })

    const results = await Podcast.search({
      query_string: {
        query: 'Qwerpline'
      }
    })

    expect(results?.body.hits.total).toEqual(1)
  })
})


text:
Mesos == an application-aligned SSI ...

modern applications are highly dependent on data. when planning modern infrastructure for storing and processing the data, we can no longer hope to simply buy hardware with more capacity to solve the problem. the size and variety of big data means traditional scale-up strategies are no longer adequate for modern workloads. thus, large organizations have moved to *scale-out distributed processing*, where a large number of computers act as a single giant computer.

Mesos allows you to treat your cluster as a single, large group of resources (a single logical datacenter). the design philosophy behind Mesos is to define a *minimal interface* to enable *efficient resource sharing* across frameworks and defer the task scheduling and execution to the frameworks.

Mesos provides functionality that crosses between *Infrastructure as a Service (IaaS)* and *Platform as a Service (PaaS)*. on the one hand, Mesos is infrastructure. on the other hand, Mesos becomes the platform that we are building on.

## Mesos as a Deployment System

typical deployment systems today, like Ansible or Chef, are fundamentally designed to make a fleet of machines conform to a static configuration. this is intentional: once you've run your Ansible or Puppet configuration, you want the cluster to be in the same, known consistent state. if, however, you want your cluster to *dynamically reallocate resources* or *shift configurations* depending on various external factors, these tools can't help you.

distributed applications can be made into Mesos frameworks for use on a Mesos cluster. since the framework is a live, running program, it can *make decisions on the fly*, *reacting to changing workloads and cluster conditions*. Mesos frameworks are strictly more powerful than static descriptions used by more traditional deployment systems. you'll still need a traditional configuration manager to bootstrap the Mesos cluster.

## Mesos as an Execution Platform

with Mesos cluster as the foundation, you can easily launch whatever frameworks you require. in essence, Mesos is an operating system: it manages your computers and harnesses them together into a single, logical unit.

## Differences with other Cluster Manager

vs. traditional HPC cluster manager

> But the interface that cluster managers gave you was, "Hey, here's a specification that describes how to run my job" and then the cluster manager goes and runs the job. We recognized what we really want was an API, an interface, that was not, "Here go and run the job" but, "Can I get some resources to run the job? OK, run this job for me, tell me when the job finished, tell me when the job failed", so that you could programmatically build something against your cluster."

vs. YARN (and Kubernetes)

> Mesos itself is focused on not just running data analytics but also on running long-lived services, web apps -- things that we considered at Twitter to be tier-zero services. It's really important that those things don't go down.

> So YARN and Mesos are similar but Mesos has been going after a more general, "We want to run everything, not just your analytics but also your web services". In fact, a big amount of the work in Mesos right now is running your stateful services as well -- so your database, your key-value store and ultimately your distributed file systems as well.

vs. Puppet, Chef and Ansible

> It's still a very node-specific perspective. The Mesos abstraction is not. It's top down, application-specific where resources are just an abstraction -- not machines but resources that you might be able to use.

> So it's an inverse of the abstractions of things like Puppet and Chef and the real reason you end up doing something like that is it's far easier to get things like multi-tenancy done because we can control it and therefore we can increase the utilization much more easily.

so ...

* finer-grained resource management and task scheduling: CPU cores, memory, GPUs, etc. not just a job batching system?

* a general architecture/two-level scheduling: master/slave, framework, scheduler/executor, task, resource offer, etc.

* leverage of containers: lightweight isolation and agile distribution.

* high-availability/fault-tolerance: based on Zookeeper.

* ecosystem: DC/OS, marathon, chronos, aurora, etc. -> more suitable for a datacenter scenario.

# Key Concepts

## Masters and Slaves

*master*s are the software that coordinates the cluster; *slave*s are what execute code in containers.

* Mesos masters are the brain of the cluster, they are primarily responsible for allocating resources to different frameworks and managing the task life cycle for them. Mesos masters implement fine-grained resource sharing using resource offers. Mesos master acts as a resource broker for frameworks using pluggable policies.

* Mesos slaves are responsible for executing tasks from frameworks using the resource they have and providing proper isolation while running multiple tasks. resources can be described using slave resources and slave attributes. slave resources can be consumed by a task and attributes are used to tag slaves with some information. Mesos doesn't understand slave attribute, and interpretation of the attributes is left to the frameworks.

  when Mesos reaches the 1.0 release, the nomenclature will change -- the Mesos slave will be called the Mesos *agent*, and all occurences of "slave" will be changed to "agent".

## Frameworks

applications that run on Mesos are called *framework*s. a framework has two parts: the controller portion, which is called the *scheduler*, and the worker portion, which are called the *executor*s.

a scheduler is simply a process that can speak the Mesos protocol. when a scheduler first starts up, it connects to the Mesos cluster so that it can use the cluster's resources. as scheduler runs, it makes requests to Mesos to launch executors as it sees fit. schedulers can launch tasks based on resource availability, changing workloads, or external triggers.

when a scheduler wants to do some work, it launches an executor. the executor is simply the scheduler's worker: the scheduler then decides to send one or more *task*s to the executor, which will work on those tasks independently, sending status updates to the scheduler until the tasks are completed.

## Resources and Offers

there are 4 different types describing *attribute*s and *resources*: *scalar*, *range*, *set*, and *text*.

Mesos has a few pre-defined types of resources: `cpus`, `mem`, `disk`, and `ports`, resources are specified as key-value pairs. attributes are also key-value pairs that Mesos passes along when it sends offers to frameworks.

here are some examples for configuring Mesos slaves

    --resources='cpu:32;mem:131072;disk:400000;ports:[21000-24000,30000-34000];bugs(debug_role):{a,b,c}'
    --attributes='rack:abc;zone:west;os:centos7;level:10;keys:[1000-1500]'

or

    [
      {
        "name": "cpus",
        "type": "SCALAR",
        "scalar": {
          "value": 32
        }
      },
      {
        "name": "mem",
        "type": "SCALAR",
        "scalar": {
          "value": 131072
        }
      },
      {
        "name": "disk",
        "type": "SCALAR",
        "scalar": {
          "value": 400000
        }
      },
      {
        "name": "ports",
        "type": "RANGES",
        "ranges": {
          "range": [
            {
              "begin": 21000,
              "end": 24000
            },
            {
              "begin": 30000,
              "end": 34000
            }
          ]
        }
      },
      {
        "name": "bugs",
        "type": "SET",
        "set": {
          "item": [
            "a",
            "b",
            "c"
          ]
        },
        "role": "debug_role"
      }
    ]

Mesos enables fine-grained sharing of resources across frameworks by making them *offers*. Mesos master decides how many resources to offer to each framework according to a given organizational policy. frameworks have the ability to *reject* offers that do not satisfy its constraints and accept the ones that do.

to support a diverse set of policies, Mesos master employs a modular architecture that makes it easy to add new allocation modules via a plugin mechanism. the logic that the Mesos master uses to determine which framework to make resource offers to is encapsulated in the master's *allocation module*.

## Containerizer

*containerizer*s are intended to run tasks in "containers" which in turn are used to

* isolate a task from other running tasks,

* "contain" tasks to run in limited resource runtime environment,

* control task's individual resources (e.g., CPU, memory) programatically,

* run software in a pre-packaged file system image, allowing it to run in different environments.

containerizers own the containers launched for the tasks/executors, and are responsible for their isolation, resource management, and events (e.g., statistics).

Mesos provides its own container technology and also plays well with existing container technologies (e.g., Docker).

* Mesos containerizer uses Linux-specific functionality such as cgroup and namespace. it is composable so operators can selectively enable different isolators.

  *launcher* is responsible for forking/destroying containers. launcher forks a new process in the containerized context. the child will exec the binary at the given path with the given argv, flags, and environment. the I/O of the child will be redirected according to the specified I/O descriptors.

  *isolator* is responsible for creating an environment for the containers where resources like cpu, network, storage and memory can be isolated from other containers.

  *fetcher* is a mechanism to download resources into the sandbox directory of a task in preparation of running the task. fetcher can copy files from a local filesystem and it also natively supports the HTTP, HTTPS, FTP and FTPS protocols.

* Mesos 0.20.0 adds the support for launching tasks that contains Docker images. users can either launch a Docker image as a Task, or as an Executor.

`MESOS-2840`, a.k.a. the Unified Containerizer, was an effort to unify containerizers in Mesos, and the *image provisioner* was added. image provisioner is responsible for pulling, caching and preparing container root filesystems. it also extracts runtime configurations from container images which will then be passed to the corresponding isolators.

a *provisioner backend* takes a set of filesystem layers and stacks them into a root filesystem.

* *copy*: simply copies all the layers into a target root directory to create a root filesystem.

* *bind*: may be useful for deployments using large (multi-GB) single-layer images and where more recent kernel features such as overlayfs are not available. for small images (10's to 100's of MB) the copy backend may be sufficient. bind backend is faster than copy as it requires nearly zero IO.

  bind backend supports only a single layer, and the filesystem is read-only because all containers using this image share the source.

* *overlay*: the reason overlay backend was introduced is because the copy backend will waste IO and space while the bind backend can only deal with one layer. the overlay backend allows containerizer to utilize the filesystem to merge multiple filesystems into one efficiently.

## Roles and Weights

*role*s can be used to specify that certain resources are reserved for the use of one or more frameworks. roles can be used to enable a variety of restrictions on how resources are offered to frameworks.

*weight*s can be used to control the relative share of cluster resources that is offered to different roles.


text:
name: Bug report
about: Create a report to help us improve

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Actual behavior**
A clear and concise description of what is the actual outcome.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Versions (please complete the following information):**
 - NodeJS:
 - TypeScript:
 - npm/yarn:
 - feed:

**Additional context**
Add any other context about the problem here.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dataset SYSTEM "yearAsInteger.dtd">
<!--

  Copyright 2010, 2011 Christopher Pheby

  Licensed 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.

 -->
<dataset>
  <YEARASINTEGER ID="0" NAME="test_0" YEAR="1"/>
  <YEARASINTEGER ID="1" NAME="test_1" YEAR="2010"/>
  <YEARASINTEGER ID="2" NAME="test_2" YEAR="1999"/>
</dataset>


text:
.. _quick_start:

===========
Quick start
===========

Installation
------------

Install openpyxl-templates using pypi::

    pip install openpyxl-templates

Creating your template
----------------------
The first we create our TemplatedWorkbook, which describes the structure of our file using TemplatedWorksheets. This template can then be used for both creating new files or reading existing ones. Below is an example using the TableSheet (a TemplatedWorksheet) to describe a excel file of people and their favorite fruits.

.. literalinclude:: examples/simple_usage.py
    :lines: 1-26

Writing
-------
To write create an instance of your templated workbook, supply data to the sheets and save to a file.

.. literalinclude:: examples/simple_usage.py
    :lines: 31-38

The TableSheet in this case will handle all formatting and produce the following sheet.

.. image:: examples/fruit_lovers.png

Reading
-------
To utilize the openpyxl-templates to read from an existing excel file, initialize your TemplatedWorkbook with a file (or a path to a file). Using the read method or simply itterating over a sheet will give you access to the data as namedtupels.

.. literalinclude:: examples/simple_usage.py
    :lines: 44-47


text:
"use strict";

var _ = require('underscorem')

exports.type = function(paramTypes){
	if(paramTypes.length === 0){
		return 'list:empty'
	}

	if(paramTypes[0].primitive){
		return 'list:'+paramTypes[0].primitive;//TODO merge primitive types (int+real->real, etc.)
	}else if(paramTypes[0].type === 'object'){
		return 'list:'+paramTypes[0].object;//TODO merge primitive types (int+real->real, etc.)
	}else{
		_.errout('TODO: ' + JSON.stringify(paramTypes))
	}
}
exports.minParams = 0
exports.maxParams = -1
exports.syntax = 'list(value,value,...)'

exports.compute0 = function(){
	return []
}

exports.compute1 = function(a){
	if(a !== undefined) return [a]
	return []
}

exports.compute = function(paramValues){

	var arr = []//.concat(paramValues)
	/*paramValues.forEach(function(v){
		if(v !== undefined) arr.push(v)
	})*/
	for(var i=0;i<paramValues.length;++i){
		var v = paramValues[i]
		if(v !== undefined) arr.push(v)
	}
	return arr
}

exports.computeSync = function(z){
	//console.log(arguments.length)
	var args = Array.prototype.slice.call(arguments, 1)
	return exports.compute(args)
}


text:
package com.huffingtonpost.chronos.spring;

import org.apache.commons.dbcp2.BasicDataSource;

public class Utils {

  public static BasicDataSource getPooledDataSource(String connectUrl,
                                               int maxTotal,
                                               int maxWaitTimeMillis) {
    BasicDataSource bds = new BasicDataSource();
    bds.setUrl(connectUrl);
    bds.setMaxTotal(maxTotal);
    bds.setMaxWaitMillis(maxWaitTimeMillis);
    return bds;
  }

}


text:
package nl.rivm.cib.episim.model.disease.infection;

import io.coala.enterprise.Actor;
import io.coala.enterprise.Fact;
import io.coala.enterprise.FactKind;
import nl.rivm.cib.episim.model.disease.Afflicted;

/**
 * {@link Contagion} is self-initiated by a {@link Contagium} (space, route,
 * locus, vector, ...) triggered by environment changes (occupancy, weather,
 * ...) to attempt {@link Transmission} of its {@link Pathogen}(s) on to some
 * potential {@link Afflicted} host
 *
 * @version $Id$
 * @author Rick van Krevelen
 */
public interface Contagion extends Fact
{
	Actor.ID getSusceptibleRef();

	void setSusceptibleRef( Actor.ID ref );

	default Contagion withSusceptibleRef( final Actor.ID ref )
	{
		setSusceptibleRef( ref );
		return this;
	}

	interface Contagium extends Actor<Contagion>
	{
		@Override
		default void onInit()
		{
			emit( Contagion.class, FactKind.REQUESTED )
					.subscribe( this::onContact, this::onError );
		}

		default void onContact( final Contagion rq )
		{
			initiate( Transmission.class, rq.getSusceptibleRef() );
		}
	}
}


text:
/*
    This file is part of the WebKit open source project.
    This file has been generated by generate-bindings.pl. DO NOT MODIFY!

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "config.h"

#if ENABLE(SVG)

#include "JSSVGPaint.h"

#include "ExceptionCode.h"
#include "JSDOMBinding.h"
#include "KURL.h"
#include "SVGPaint.h"
#include <runtime/Error.h>
#include <runtime/JSString.h>
#include <wtf/GetPtr.h>

using namespace JSC;

namespace WebCore {

ASSERT_CLASS_FITS_IN_CELL(JSSVGPaint);

/* Hash table */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif

static const HashTableValue JSSVGPaintTableValues[4] =
{
    { "paintType", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintPaintType), (intptr_t)0 THUNK_GENERATOR(0) },
    { "uri", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintUri), (intptr_t)0 THUNK_GENERATOR(0) },
    { "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintConstructor), (intptr_t)0 THUNK_GENERATOR(0) },
    { 0, 0, 0, 0 THUNK_GENERATOR(0) }
};

#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSSVGPaintTable = { 9, 7, JSSVGPaintTableValues, 0 };
/* Hash table for constructor */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif

static const HashTableValue JSSVGPaintConstructorTableValues[11] =
{
    { "SVG_PAINTTYPE_UNKNOWN", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_UNKNOWN), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_RGBCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_RGBCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_RGBCOLOR_ICCCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_NONE", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_NONE), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_CURRENTCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_CURRENTCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI_NONE", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI_NONE), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI_CURRENTCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI_CURRENTCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI_RGBCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI_RGBCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI), (intptr_t)0 THUNK_GENERATOR(0) },
    { 0, 0, 0, 0 THUNK_GENERATOR(0) }
};

#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSSVGPaintConstructorTable = { 35, 31, JSSVGPaintConstructorTableValues, 0 };

COMPILE_ASSERT(0 == SVGPaint::SVG_PAINTTYPE_UNKNOWN, SVGPaintEnumSVG_PAINTTYPE_UNKNOWNIsWrongUseDontCheckEnums);
COMPILE_ASSERT(1 == SVGPaint::SVG_PAINTTYPE_RGBCOLOR, SVGPaintEnumSVG_PAINTTYPE_RGBCOLORIsWrongUseDontCheckEnums);
COMPILE_ASSERT(2 == SVGPaint::SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR, SVGPaintEnumSVG_PAINTTYPE_RGBCOLOR_ICCCOLORIsWrongUseDontCheckEnums);
COMPILE_ASSERT(101 == SVGPaint::SVG_PAINTTYPE_NONE, SVGPaintEnumSVG_PAINTTYPE_NONEIsWrongUseDontCheckEnums);
COMPILE_ASSERT(102 == SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR, SVGPaintEnumSVG_PAINTTYPE_CURRENTCOLORIsWrongUseDontCheckEnums);
COMPILE_ASSERT(103 == SVGPaint::SVG_PAINTTYPE_URI_NONE, SVGPaintEnumSVG_PAINTTYPE_URI_NONEIsWrongUseDontCheckEnums);
COMPILE_ASSERT(104 == SVGPaint::SVG_PAINTTYPE_URI_CURRENTCOLOR, SVGPaintEnumSVG_PAINTTYPE_URI_CURRENTCOLORIsWrongUseDontCheckEnums);
COMPILE_ASSERT(105 == SVGPaint::SVG_PAINTTYPE_URI_RGBCOLOR, SVGPaintEnumSVG_PAINTTYPE_URI_RGBCOLORIsWrongUseDontCheckEnums);
COMPILE_ASSERT(106 == SVGPaint::SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR, SVGPaintEnumSVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLORIsWrongUseDontCheckEnums);
COMPILE_ASSERT(107 == SVGPaint::SVG_PAINTTYPE_URI, SVGPaintEnumSVG_PAINTTYPE_URIIsWrongUseDontCheckEnums);

class JSSVGPaintConstructor : public DOMConstructorObject {
public:
    JSSVGPaintConstructor(JSC::ExecState*, JSC::Structure*, JSDOMGlobalObject*);

    virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);
    virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);
    static const JSC::ClassInfo s_info;
    static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)
    {
        return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);
    }
protected:
    static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags;
};

const ClassInfo JSSVGPaintConstructor::s_info = { "SVGPaintConstructor", &DOMConstructorObject::s_info, &JSSVGPaintConstructorTable, 0 };

JSSVGPaintConstructor::JSSVGPaintConstructor(ExecState* exec, Structure* structure, JSDOMGlobalObject* globalObject)
    : DOMConstructorObject(structure, globalObject)
{
    ASSERT(inherits(&s_info));
    putDirect(exec->globalData(), exec->propertyNames().prototype, JSSVGPaintPrototype::self(exec, globalObject), DontDelete | ReadOnly);
}

bool JSSVGPaintConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
    return getStaticValueSlot<JSSVGPaintConstructor, JSDOMWrapper>(exec, &JSSVGPaintConstructorTable, this, propertyName, slot);
}

bool JSSVGPaintConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
    return getStaticValueDescriptor<JSSVGPaintConstructor, JSDOMWrapper>(exec, &JSSVGPaintConstructorTable, this, propertyName, descriptor);
}

/* Hash table for prototype */
#if ENABLE(JIT)
#define THUNK_GENERATOR(generator) , generator
#else
#define THUNK_GENERATOR(generator)
#endif

static const HashTableValue JSSVGPaintPrototypeTableValues[13] =
{
    { "SVG_PAINTTYPE_UNKNOWN", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_UNKNOWN), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_RGBCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_RGBCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_RGBCOLOR_ICCCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_NONE", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_NONE), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_CURRENTCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_CURRENTCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI_NONE", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI_NONE), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI_CURRENTCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI_CURRENTCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI_RGBCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI_RGBCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR), (intptr_t)0 THUNK_GENERATOR(0) },
    { "SVG_PAINTTYPE_URI", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGPaintSVG_PAINTTYPE_URI), (intptr_t)0 THUNK_GENERATOR(0) },
    { "setUri", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGPaintPrototypeFunctionSetUri), (intptr_t)1 THUNK_GENERATOR(0) },
    { "setPaint", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGPaintPrototypeFunctionSetPaint), (intptr_t)4 THUNK_GENERATOR(0) },
    { 0, 0, 0, 0 THUNK_GENERATOR(0) }
};

#undef THUNK_GENERATOR
static JSC_CONST_HASHTABLE HashTable JSSVGPaintPrototypeTable = { 35, 31, JSSVGPaintPrototypeTableValues, 0 };
const ClassInfo JSSVGPaintPrototype::s_info = { "SVGPaintPrototype", &JSC::JSObjectWithGlobalObject::s_info, &JSSVGPaintPrototypeTable, 0 };

JSObject* JSSVGPaintPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
    return getDOMPrototype<JSSVGPaint>(exec, globalObject);
}

bool JSSVGPaintPrototype::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
    return getStaticPropertySlot<JSSVGPaintPrototype, JSObject>(exec, &JSSVGPaintPrototypeTable, this, propertyName, slot);
}

bool JSSVGPaintPrototype::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
    return getStaticPropertyDescriptor<JSSVGPaintPrototype, JSObject>(exec, &JSSVGPaintPrototypeTable, this, propertyName, descriptor);
}

const ClassInfo JSSVGPaint::s_info = { "SVGPaint", &JSSVGColor::s_info, &JSSVGPaintTable, 0 };

JSSVGPaint::JSSVGPaint(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<SVGPaint> impl)
    : JSSVGColor(structure, globalObject, impl)
{
    ASSERT(inherits(&s_info));
}

JSObject* JSSVGPaint::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
    return new (exec) JSSVGPaintPrototype(exec->globalData(), globalObject, JSSVGPaintPrototype::createStructure(exec->globalData(), JSSVGColorPrototype::self(exec, globalObject)));
}

bool JSSVGPaint::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
    return getStaticValueSlot<JSSVGPaint, Base>(exec, &JSSVGPaintTable, this, propertyName, slot);
}

bool JSSVGPaint::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
    return getStaticValueDescriptor<JSSVGPaint, Base>(exec, &JSSVGPaintTable, this, propertyName, descriptor);
}

JSValue jsSVGPaintPaintType(ExecState* exec, JSValue slotBase, const Identifier&)
{
    JSSVGPaint* castedThis = static_cast<JSSVGPaint*>(asObject(slotBase));
    UNUSED_PARAM(exec);
    SVGPaint* imp = static_cast<SVGPaint*>(castedThis->impl());
    JSValue result = jsNumber(imp->paintType());
    return result;
}

JSValue jsSVGPaintUri(ExecState* exec, JSValue slotBase, const Identifier&)
{
    JSSVGPaint* castedThis = static_cast<JSSVGPaint*>(asObject(slotBase));
    UNUSED_PARAM(exec);
    SVGPaint* imp = static_cast<SVGPaint*>(castedThis->impl());
    JSValue result = jsString(exec, imp->uri());
    return result;
}

JSValue jsSVGPaintConstructor(ExecState* exec, JSValue slotBase, const Identifier&)
{
    JSSVGPaint* domObject = static_cast<JSSVGPaint*>(asObject(slotBase));
    return JSSVGPaint::getConstructor(exec, domObject->globalObject());
}

JSValue JSSVGPaint::getConstructor(ExecState* exec, JSGlobalObject* globalObject)
{
    return getDOMConstructor<JSSVGPaintConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));
}

EncodedJSValue JSC_HOST_CALL jsSVGPaintPrototypeFunctionSetUri(ExecState* exec)
{
    JSValue thisValue = exec->hostThisValue();
    if (!thisValue.inherits(&JSSVGPaint::s_info))
        return throwVMTypeError(exec);
    JSSVGPaint* castedThis = static_cast<JSSVGPaint*>(asObject(thisValue));
    SVGPaint* imp = static_cast<SVGPaint*>(castedThis->impl());
    if (exec->argumentCount() < 1)
        return throwVMError(exec, createSyntaxError(exec, "Not enough arguments"));
    const String& uri(ustringToString(exec->argument(0).toString(exec)));
    if (exec->hadException())
        return JSValue::encode(jsUndefined());

    imp->setUri(uri);
    return JSValue::encode(jsUndefined());
}

EncodedJSValue JSC_HOST_CALL jsSVGPaintPrototypeFunctionSetPaint(ExecState* exec)
{
    JSValue thisValue = exec->hostThisValue();
    if (!thisValue.inherits(&JSSVGPaint::s_info))
        return throwVMTypeError(exec);
    JSSVGPaint* castedThis = static_cast<JSSVGPaint*>(asObject(thisValue));
    SVGPaint* imp = static_cast<SVGPaint*>(castedThis->impl());
    if (exec->argumentCount() < 4)
        return throwVMError(exec, createSyntaxError(exec, "Not enough arguments"));
    ExceptionCode ec = 0;
    unsigned short paintType(exec->argument(0).toUInt32(exec));
    if (exec->hadException())
        return JSValue::encode(jsUndefined());
    const String& uri(ustringToString(exec->argument(1).toString(exec)));
    if (exec->hadException())
        return JSValue::encode(jsUndefined());
    const String& rgbColor(ustringToString(exec->argument(2).toString(exec)));
    if (exec->hadException())
        return JSValue::encode(jsUndefined());
    const String& iccColor(ustringToString(exec->argument(3).toString(exec)));
    if (exec->hadException())
        return JSValue::encode(jsUndefined());

    imp->setPaint(paintType, uri, rgbColor, iccColor, ec);
    setDOMException(exec, ec);
    return JSValue::encode(jsUndefined());
}

// Constant getters

JSValue jsSVGPaintSVG_PAINTTYPE_UNKNOWN(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(0));
}

JSValue jsSVGPaintSVG_PAINTTYPE_RGBCOLOR(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(1));
}

JSValue jsSVGPaintSVG_PAINTTYPE_RGBCOLOR_ICCCOLOR(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(2));
}

JSValue jsSVGPaintSVG_PAINTTYPE_NONE(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(101));
}

JSValue jsSVGPaintSVG_PAINTTYPE_CURRENTCOLOR(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(102));
}

JSValue jsSVGPaintSVG_PAINTTYPE_URI_NONE(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(103));
}

JSValue jsSVGPaintSVG_PAINTTYPE_URI_CURRENTCOLOR(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(104));
}

JSValue jsSVGPaintSVG_PAINTTYPE_URI_RGBCOLOR(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(105));
}

JSValue jsSVGPaintSVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(106));
}

JSValue jsSVGPaintSVG_PAINTTYPE_URI(ExecState* exec, JSValue, const Identifier&)
{
    UNUSED_PARAM(exec);
    return jsNumber(static_cast<int>(107));
}

}

#endif // ENABLE(SVG)


text:
pub mod screen;
pub mod serial;
pub mod io;


text:
package com.google.code.ssm.config;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * Provides addresses of cache servers.
 *
 * @author Jakub Białek
 * @since 2.0.0
 *
 */
public interface AddressProvider {

    List<InetSocketAddress> getAddresses();

}


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require 'eventmachine'
require 'fiber'

describe "in fiber" do

  def wrap_fiber
    EM.run do
      Net::SNMP::Dispatcher.fiber_loop
      Fiber.new { yield; EM.stop }.resume(nil)
    end
  end

  it "get should work in a fiber with synchronous calling style" do
    wrap_fiber do
        session = Net::SNMP::Session.open(:peername => 'localhost', :community => 'public')
        result = session.get("sysDescr.0")
        expect(result.varbinds[0].value).to eq $test_mib["sysDescr.0"]
    end
  end

  it "getnext" do
    wrap_fiber do
      Net::SNMP::Session.open(:peername => "localhost", :community => "public" ) do |sess|
        result = sess.get_next(["sysUpTimeInstance.0"])
        expect(result.varbinds.first.oid.oid).to eq Net::SNMP::MIB.translate('sysContact.0')
        expect(result.varbinds.first.value).to eq $test_mib['sysContact.0']
      end
    end
  end

  it "should get using snmpv3" do
    pending
    wrap_fiber do
      Net::SNMP::Session.open(:peername => 'localhost', :version => 3, :username => 'MD5User', :security_level => Net::SNMP::Constants::SNMP_SEC_LEVEL_AUTHNOPRIV, :auth_protocol => :md5, :password => 'The Net-SNMP Demo Password') do |sess|
        result = sess.get(["sysDescr.0"])
        expect(result.varbinds.first.value).to eq $test_mib["sysDescr.0"]
      end
    end
  end

end


text:
#ifndef MAESTRO_DFA_CLUSTER_UNIT_HPP_
#define MAESTRO_DFA_CLUSTER_UNIT_HPP_

//#define DEBUG_CLUSTER_UNIT

#include <memory>
#include <vector>
#include <list>
#include <map>
#include <string>

#include "BASE_maestro-class.hpp"
#include "TL_error-handler.hpp"

#include "AHW_noc-model.hpp"
#include "DFA_dimension-table.hpp"
#include "DFA_directives.hpp"
#include "DFA_directive-table.hpp"

#include "DFA_tensor.hpp"
#include "DFA_tensor-table.hpp"

namespace maestro {
	namespace DFA {

		const int invalid_map_pos = -1;

		class ClusterUnit : public MAESTROClass {
			public:
				ClusterUnit(int cluster_level, int cluster_size,
				            std::shared_ptr<DFA::DirectiveTable> dataflow,
                    std::shared_ptr<DFA::DimensionTable> dimensions,
                    std::shared_ptr<DFA::TensorTable> tensors,
				            std::shared_ptr<AHW::NetworkOnChipModel> noc) :
				      cluster_level_(cluster_level),
				      cluster_size_(cluster_size),
				      noc_(noc),
				      dimensions_(dimensions),
				      dataflow_(dataflow),
				      tensors_(tensors),
		          MAESTROClass("ClusterUnitAnalysis_Lv"+ std::to_string(cluster_level))
			  {

				  num_mapped_elements_ = std::make_unique<std::map<std::string, int>>();
				  sp_mapped_unique_elements_ = std::make_unique<std::map<std::string, int>>();
				  tp_mapped_unique_elements_ = std::make_unique<std::map<std::string, int>>();
				  sp_mapped_reused_elements_ = std::make_unique<std::map<std::string, int>>();
				  tp_mapped_reused_elements_ = std::make_unique<std::map<std::string, int>>();
				  dataflow->ConvertToInputCentric();
				  Preprocess();
				}

				int GetClusterLevel() {
				  return cluster_level_;
				}

				std::shared_ptr<AHW::NetworkOnChipModel> GetNoCModel() {
				  return noc_;
				}

				std::shared_ptr<DFA::DimensionTable> GetDimensions() {
				  return dimensions_;
				}

				std::shared_ptr<DFA::DirectiveTable> GetDataflow() {
				  return dataflow_;
				}

				bool IsUnrolled(std::string dim) {
				  bool ret = false;
				  auto directive = dataflow_->FindDirective(dim);
				  int dim_size =  dimensions_->GetSize(dim);
				  int map_size = directive->GetSize();
				  int ofs_size = directive->GetOfs();

				  if(directive != nullptr) {
				    if(directive->GetClass() == DFA::directive::DirectiveClass::TemporalMap) {
				      ret = (map_size >= dim_size);
				    }
				    else { // Spatial Map case
				      //Spatial unroll: If one spatial iteration covers entire dimension, it is the spatial unroll
				      int sp_covered_size = (cluster_size_-1) * ofs_size + map_size; //TODO: double-check this
				      ret = (sp_covered_size >= dim_size);
				    }
				  }
				  else {
				    this->error_handler_->PrintErrorMsg(TL::ErrorCode::InvalidDirective, dim, this->GetName());
				    this->error_handler_->TerminateProgram();
				  }

				  return ret;
				}

				bool IsInitEdge(std::string var) {
          bool ret = false;
          auto directive = dataflow_->FindDirective(var);
          if(directive != nullptr) {
            auto directive_class = directive->GetClass();
            if(directive_class == DFA::directive::DirectiveClass::TemporalMap) {
              ret = (directive->GetSize() > dimensions_->GetSize(var));
            }
            else {
              ret = ( (directive->GetOfs() * cluster_size_) > dimensions_->GetSize(var));
            }
          }
          return ret;
				}

				bool IsInitUnroll(std::string var) {
          bool ret = false;
          auto directive = dataflow_->FindDirective(var);

          if(directive != nullptr) {
            auto directive_class = directive->GetClass();
            if(directive_class == DFA::directive::DirectiveClass::TemporalMap) {
              ret = (directive->GetSize() >= dimensions_->GetSize(var)); // Updated from ==  to >=
            }
            else {
              ret = ( (directive->GetOfs() * cluster_size_) >= dimensions_->GetSize(var)); // Updated from ==  to >=
            }
          }

          return ret;
				}

				bool HasSpatialEdgeCase() {
				  return (num_edge_spatial_iterations_ != 0);
				}

				bool HasTemporalEdgeCase(std::string var) {
          auto directive = dataflow_->FindDirective(var);
          if(directive == nullptr) {
            this->error_handler_->PrintErrorMsg(TL::ErrorCode::InvalidDimension, var);
          }

          if(directive->GetClass() ==  directive::DirectiveClass::SpatialMap) {
            return false; // Treats entire spatial iterations as one temporal iteration
          }

          int dim_size = 0;
          int offset = directive->GetOfs();
          bool is_overlapping = dimensions_->IsOverlapped(var);

          if(is_overlapping) {
            auto overlapping_var = dimensions_->GetOverlappingDim(var);
            bool is_sliding_dim = dimensions_->IsSlidingDim(var);

            if(is_sliding_dim) {
              int sliding_dim_size = dimensions_->GetSize(var);
              dim_size = sliding_dim_size;
            }
            else {
              int reference_dim_size = dimensions_->GetSize(var);
              int sliding_dim_size = dimensions_->GetSize(overlapping_var);

              dim_size = reference_dim_size - sliding_dim_size + 1;
            }
          }
          else {
            dim_size = dimensions_->GetSize(var);
          }

          return (dim_size % offset != 0);
				}

        long GetNumTemporalIterations(std::string var) {
          long ret = 0;

          auto directive = dataflow_->FindDirective(var);
          if(directive == nullptr) {
            this->error_handler_->PrintErrorMsg(TL::ErrorCode::InvalidDimension, var);
          }

          if(directive->GetClass() ==  directive::DirectiveClass::SpatialMap) {
            return 1; // Treats entire spatial iterations as one temporal iteration
          }

          int dim_size = 0;
          int offset = directive->GetOfs();
          bool is_overlapping = dimensions_->IsOverlapped(var);

          if(is_overlapping) {
            auto overlapping_var = dimensions_->GetOverlappingDim(var);
            bool is_sliding_dim = dimensions_->IsSlidingDim(var);

            if(is_sliding_dim) {
              int sliding_dim_size = dimensions_->GetSize(var);
              dim_size = sliding_dim_size;
            }
            else {
              int reference_dim_size = dimensions_->GetSize(var);
              int sliding_dim_size = dimensions_->GetSize(overlapping_var);

              dim_size = reference_dim_size - sliding_dim_size + 1;
            }
          }
          else {
            dim_size = dimensions_->GetSize(var);
          }

          ret = dim_size / offset;
          if(dim_size % offset != 0) {
            ret++;
          }

          return ret;
        }

        long GetNumSpatialIterations(std::string dim) {
          long ret = 0;

          auto directive = dataflow_->FindDirective(dim);
          if(directive == nullptr) {
            this->error_handler_->PrintErrorMsg(TL::ErrorCode::InvalidDimension, dim);
          }

          if(directive->GetClass() ==  directive::DirectiveClass::TemporalMap) {
            return 1; // Treats entire spatial iterations as one temporal iteration
          }

          int dim_size = 0;
          int offset = directive->GetOfs();
          bool is_overlapping = dimensions_->IsOverlapped(dim);

          if(is_overlapping) {
            auto overlapping_var = dimensions_->GetOverlappingDim(dim);
            bool is_sliding_dim = dimensions_->IsSlidingDim(dim);

            if(is_sliding_dim) {
              int sliding_dim_size = dimensions_->GetSize(dim);
              dim_size = sliding_dim_size;
            }
            else {
              int reference_dim_size = dimensions_->GetSize(dim);
              int sliding_dim_size = dimensions_->GetSize(overlapping_var);

              dim_size = reference_dim_size - sliding_dim_size + 1;
            }
          }
          else {
            dim_size = dimensions_->GetSize(dim);
          }

          int full_spatial_coverage = offset * cluster_size_;

          ret = dim_size / full_spatial_coverage;
          if(dim_size % full_spatial_coverage != 0) {
            ret++;
          }

          return ret;
        }

				std::vector<std::string> GetOuterTemporalIterationVars () {
				  std::vector<std::string> ret;

				  for(int idx = 0; idx < upper_spatial_map_idx_; idx++) {
				    if(dataflow_->at(idx)->GetClass() == directive::DirectiveClass::TemporalMap) {
				      ret.push_back(dataflow_->at(idx)->GetVariable());
				    }
				  }

				  return ret;
				}

        std::vector<std::string> GetInnerTemporalIterationVars () {
          std::vector<std::string> ret;

          for(int idx = upper_spatial_map_idx_; idx < dataflow_->size(); idx++) {
            if(dataflow_->at(idx)->GetClass() == directive::DirectiveClass::TemporalMap) {
              ret.push_back(dataflow_->at(idx)->GetVariable());
            }
          }

          return ret;
        }

        std::shared_ptr<std::vector<std::string>> GetAllVarsInDirectiveClass (DFA::directive::DirectiveClass target_class) {
          std::shared_ptr<std::vector<std::string>> ret = std::make_shared<std::vector<std::string>>();

          for(auto directive : *dataflow_) {
            if(target_class == DFA::directive::DirectiveClass::Invalid
                               || directive->GetClass() == target_class) {
              ret->push_back(directive->GetVariable());
            }
          }

          return ret;
        }

        std::shared_ptr<std::vector<std::string>> GetAllDimensionVars () {
          std::shared_ptr<std::vector<std::string>> ret = std::make_shared<std::vector<std::string>>();

          for(auto directive : *dataflow_) {
            ret->push_back(directive->GetVariable());
          }

          return ret;
        }

        long GetNumTemporalIterations_SingleDim(std::string var, bool edge_case) {
          long ret = 0;

          auto dim_size = dimensions_->GetSize(var);
          auto directive = dataflow_->FindDirective(var);

          /*
          bool is_full_tp_unrolled = (dim_size == directive->GetSize());

          if(is_full_tp_unrolled) {
            ret = 0;
          }
          */

          //TODO: Fix this hard-coded part
          if(var == "X") {
        	  dim_size = dim_size - dimensions_->GetSize("S") +1;
          }
          else if(var == "Y") {
        	  dim_size = dim_size - dimensions_->GetSize("R") +1;
          }

          if(directive->GetClass() ==  directive::DirectiveClass::TemporalMap) {
            if(!edge_case) {
              ret = dim_size / directive->GetOfs();
            }
            else {
              ret = dim_size % directive->GetOfs(); //TODO: Fix this
            }
          }

          return ret;
        }

        long GetNumSpatialSparseIterations(int blk_sparsity_size, int num_sparse_blks) {
          long ret;

          auto spatial_map_directive = dataflow_->at(upper_spatial_map_idx_);
          auto spatially_mapped_dimension = spatial_map_directive->GetVariable();

          auto sp_dim_size = dimensions_->GetSize(spatially_mapped_dimension);
          auto sp_map_ofs = spatial_map_directive->GetOfs();

          sp_dim_size = sp_dim_size - blk_sparsity_size * num_sparse_blks;

          ret = sp_dim_size / (sp_map_ofs * cluster_size_);

          if(sp_dim_size % (sp_map_ofs * cluster_size_) != 0) {
            ret++;
          }

          return ret;
        }

        long GetNumTotalIterations() {
          long ret = 1;

          for(int idx = 0; idx < dataflow_->size();idx ++) {

            auto directive = dataflow_->at(idx);
            auto directive_dim = directive->GetVariable();
            auto dim_size = dimensions_->GetSize(directive_dim);
            int num_iter_this_dim = 1;

            if(dimensions_->IsOverlapped(directive_dim)) {
              if(!dimensions_->IsSlidingDim(directive_dim)) {
                auto sliding_dim = dimensions_->GetOverlappingDim(directive_dim);
                auto sliding_dim_directive = dataflow_->FindDirective(directive_dim);
                assert(sliding_dim_directive != nullptr);
                auto sliding_dim_map_size = sliding_dim_directive->GetSize();
                auto sliding_dim_size = dimensions_->GetSize(sliding_dim);

                if(sliding_dim_map_size == sliding_dim_size) {
                  dim_size = dim_size - sliding_dim_size + 1;
                }
              }
            }

/*
            //TODO: Fix this hard-coded part
            if(mapped_dim == "X") {
              dim_size = dim_size - dimensions_->GetSize("S") +1;
            }
            else if(mapped_dim == "Y") {
              dim_size = dim_size - dimensions_->GetSize("R") +1;
            }
*/

            if (directive->GetClass() == directive::DirectiveClass::TemporalMap) {
              num_iter_this_dim = dim_size/directive->GetOfs();
              if(dim_size % directive->GetOfs() != 0) {
                num_iter_this_dim++;
              }
            }
            else if(directive->GetClass() == directive::DirectiveClass::SpatialMap) {
              num_iter_this_dim = dim_size/(directive->GetOfs() * cluster_size_);
              if(dim_size % (directive->GetOfs() * cluster_size_) != 0) {
                num_iter_this_dim++;
              }
            }
            else {
              //TODO: Handle this error
            }

            ret *= num_iter_this_dim;
          } //End of for(idx)
          return ret;
        }

        bool isInnerTemporalMapped(std::string var) {
          auto directive = dataflow_->FindDirective(var);
          auto inner_temporal_map_directive = dataflow_->at(inner_temporal_map_idx_);

          return (directive == inner_temporal_map_directive);
        }

        long GetNumClusters(bool is_spatial_edge = false) {
          if(!is_spatial_edge) {
            return cluster_size_;
          }
          else {
            return num_spatial_edge_clusters_;
          }
        }

        long GetNumPartialOutputs() {
          return num_pouts_;
        }

        void SetDataflow(std::shared_ptr<DFA::DirectiveTable> new_dataflow) {
          dataflow_ = new_dataflow;
        }

				void Reset() {
				  num_mapped_elements_->clear();
				  sp_mapped_unique_elements_->clear();
          tp_mapped_unique_elements_->clear();
          sp_mapped_reused_elements_->clear();
          tp_mapped_reused_elements_->clear();

          cluster_size_ = 1;

          upper_spatial_map_idx_ = invalid_map_pos;
          lower_spatial_map_idx_ = invalid_map_pos;

          outer_temporal_map_idx_ = invalid_map_pos;
          inner_temporal_map_idx_ = invalid_map_pos;

          num_spatial_iterations_ = 1;
          num_spatial_edge_clusters_ = 1;

          num_pouts_ = 0;
				}

				void Reanalyze() {
				  Preprocess();
				}

			protected:
//        directive::ClusterType type_;

				int cluster_level_ = -1;
				int cluster_size_ = 1;

				int upper_spatial_map_idx_ = invalid_map_pos;
				int lower_spatial_map_idx_ = invalid_map_pos;
        int outer_temporal_map_idx_ = invalid_map_pos;
				int inner_temporal_map_idx_ = invalid_map_pos;

        int num_spatial_iterations_ = 1;

				int num_spatial_edge_clusters_ = 1;
				int num_steady_spatial_iterations_ = 1;
				int num_edge_spatial_iterations_ = 0;

				long num_pouts_ = 0;

				std::shared_ptr<DFA::DimensionTable> dimensions_;
        std::shared_ptr<DFA::DirectiveTable> dataflow_;
				std::shared_ptr<AHW::NetworkOnChipModel> noc_;

	      std::unique_ptr<std::map<std::string, int>> num_mapped_elements_; //TSz

	      std::unique_ptr<std::map<std::string, int>> sp_mapped_unique_elements_; //TUSz
	      std::unique_ptr<std::map<std::string, int>> tp_mapped_unique_elements_; //TUSz

	      std::unique_ptr<std::map<std::string, int>> sp_mapped_reused_elements_; //
	      std::unique_ptr<std::map<std::string, int>> tp_mapped_reused_elements_; //

	      std::shared_ptr<DFA::TensorTable> tensors_;

			private:
				//Get the index of the inner-most spatial map
				void AnalyzeSpatialMapIdx() {
				  int idx = 0;

				  for(auto& it : *dataflow_) {
				    if(it->GetClass() == directive::DirectiveClass::SpatialMap) {
				      if(upper_spatial_map_idx_ == invalid_map_pos) { // First spatial map
				        upper_spatial_map_idx_ = idx;
				      }
				      else if(lower_spatial_map_idx_ == invalid_map_pos) { // Second spatial map
				        lower_spatial_map_idx_ = idx;
				      }
				      else { // Third spatial map == Error!
				        this->error_handler_->PrintErrorMsg(TL::ErrorCode::MultiParallelismInSingleCluster, std::to_string(cluster_level_), this->GetName());
                this->error_handler_->TerminateProgram();
				      }
				    } // End of if(this directive == SpatialMap)
				    idx++;
				  }

				  if(upper_spatial_map_idx_ == invalid_map_pos) { // Error: No spatial map!
            this->error_handler_->PrintErrorMsg(TL::ErrorCode::NoSpatialMap, std::to_string(cluster_level_), this->GetName());
            this->error_handler_->TerminateProgram();
				  }

				  //TODO: Add another error check for invalid double spatial map

				}

        //Get the index of the inner-most temporal map under the inner-most spatial map.
        // If no temporal map is under the inner-most spatial map, it returns the index to the inner-most spatial map
				// TODO: FLAG! Needs to check the correctness
        void AnalyzeInnerTemporalMapIdx() {
          int inner_temporal_map_index = -1;
          int idx = 0;

          inner_temporal_map_index = upper_spatial_map_idx_;

          for(int idx = upper_spatial_map_idx_; idx < dataflow_->size() ; idx++) {
            if(dataflow_->at(idx)->GetClass() == directive::DirectiveClass::TemporalMap) {
              bool isUnrolled = dataflow_->at(idx)->GetSize() >= dimensions_->GetSize(dataflow_->at(idx)->GetVariable());
              if(!isUnrolled) {
                inner_temporal_map_index = idx;
              }
            }
          }

          inner_temporal_map_idx_ = inner_temporal_map_index;
        }

        void AnalyzeNumSpatialIterations() {
          auto upper_spatial_map_directive = dataflow_->at(upper_spatial_map_idx_);
          auto spatially_mapped_dimension = upper_spatial_map_directive->GetVariable();

          auto sp_dim_size = dimensions_->GetSize(spatially_mapped_dimension);
          auto sp_map_ofs = upper_spatial_map_directive->GetOfs();

          num_spatial_iterations_ = sp_dim_size / (sp_map_ofs * cluster_size_); // TODO: Double-check this

          //This covers edges (either init-edge or normal spatial edge)
          if(sp_dim_size % (sp_map_ofs * cluster_size_) != 0) {
            num_spatial_iterations_++;
          }
        }

        void AnalyzeMappingSizes() {
          int idx = 0;

          for(auto& directive : *dataflow_) {
            auto loop_var = directive->GetVariable();

            (*num_mapped_elements_)[loop_var] = directive->GetSize();

            if(directive->GetClass() == directive::DirectiveClass::SpatialMap) {
              (*sp_mapped_unique_elements_)[loop_var] = directive->GetOfs();
              (*tp_mapped_unique_elements_)[loop_var] = directive->GetSize();
            }
            else { // if the directive is TemporalMap
              (*sp_mapped_unique_elements_)[loop_var] = 0;
              (*tp_mapped_unique_elements_)[loop_var] = (idx == inner_temporal_map_idx_)? directive->GetOfs() : directive->GetSize();
            }

            (*sp_mapped_reused_elements_)[loop_var] = (*num_mapped_elements_)[loop_var] - (*sp_mapped_unique_elements_)[loop_var];
            (*tp_mapped_reused_elements_)[loop_var] = (*num_mapped_elements_)[loop_var] - (*tp_mapped_unique_elements_)[loop_var];

            idx++;
          } // End of for_each (directive)
        }

        void AnalyzeSpatialEdgeCase() {
          auto sp_map_directive = dataflow_->at(upper_spatial_map_idx_);
          auto sp_var = sp_map_directive->GetVariable();
          auto sp_dim_sz = dimensions_->GetSize(sp_var);

          // Handle sliding window overlaps
          /*
          if(dimensions_->IsOverlapped(sp_var) && !dimensions_->IsSlidingDim(sp_var)) {
            auto overlap_dim = dimensions_->GetOverlappingDim(sp_var);
            sp_dim_sz = sp_dim_sz - dimensions_->GetSize(overlap_dim) + 1;
          }
           */
          int map_size = sp_map_directive->GetSize();
          int map_ofs = sp_map_directive->GetOfs();

          // TODO: Double check this; Currently it ignores out-of-bound caused by mapping size
          // Note: It should be fine with overlapped dimensions (input column/row in conv) if the given dataflow is legal
          // Note: This is now handled below (beta version)
          int each_sp_iter_base_coverage = (sp_map_directive->GetOfs() * cluster_size_);
          int each_sp_iter_full_coverage = (sp_map_directive->GetOfs() * (cluster_size_-1)) + sp_map_directive->GetSize();

          if(sp_dim_sz > each_sp_iter_full_coverage) {
            auto sp_dim_to_cover_after_first_sp_iter = (sp_dim_sz-each_sp_iter_base_coverage);

            num_steady_spatial_iterations_ = ((sp_dim_sz - map_size) / map_ofs + 1) / cluster_size_ -1;
            num_edge_spatial_iterations_ = ((num_steady_spatial_iterations_ + 1) * (map_ofs * cluster_size_) + each_sp_iter_full_coverage > sp_dim_sz )? 1 : 0;

            int remaining_items = sp_dim_sz - (num_steady_spatial_iterations_ + 1) * map_ofs * cluster_size_;

            if(remaining_items < map_size) {
              num_spatial_edge_clusters_ = 1;
            }
            else {
              num_spatial_edge_clusters_ = (remaining_items - map_size) / map_ofs + 1; // TODO: Fix
            }
          }
          else {
            num_steady_spatial_iterations_ = 0;
            num_edge_spatial_iterations_ = 1;
            if(sp_dim_sz > sp_map_directive->GetSize()) {
              num_spatial_edge_clusters_ = (sp_dim_sz -  map_size) / map_ofs + 1; // TODO: Fix
              int sp_edge_clsuter_coverage = (sp_map_directive->GetOfs() * (num_spatial_edge_clusters_-1)) + sp_map_directive->GetSize();
              if(sp_edge_clsuter_coverage < sp_dim_sz) num_spatial_edge_clusters_++;
            }
            else {
              num_spatial_edge_clusters_ = 1;
            }
          }

//          num_steady_spatial_iterations_ = sp_dim_sz / each_sp_iter_base_coverage;

/*
 *  New version that deals with out-of-bound
 *  Currently buggy; rolled back to the original version
 *
          //If final steady iteration involves out-of-bound, treat the last iteration as an sp-edge iteration
          if(num_steady_spatial_iterations_ * each_sp_iter_base_coverage + sp_map_directive->GetSize() > sp_dim_sz) {
            num_edge_spatial_iterations_ = 1;
          }
          else { // If the steady iteration doesn't violate bounds, check if entire sp_dim is covered
            num_edge_spatial_iterations_ = (sp_dim_sz % each_sp_iter_base_coverage == 0)? 0 : 1;
          }

          num_steady_spatial_iterations_ -= num_edge_spatial_iterations_;

          int final_iter_base_idx = num_steady_spatial_iterations_ * each_sp_iter_base_coverage;

          //Based on this inequality (bound check): base_idx + sp_map_directive->GetOfs() * x + sp_map_directive->GetSize() < sp_dim_sz
          num_spatial_edge_clusters_ = std::ceil(static_cast<double>(sp_dim_sz - final_iter_base_idx + 1 - sp_map_directive->GetSize()) / sp_map_directive->GetOfs()); // TODO: Dobule-check this
*/
          // Rolled back to the original version
//          num_edge_spatial_iterations_ = (sp_dim_sz % each_sp_iter_base_coverage == 0)? 0 : 1;
//          num_spatial_edge_clusters_ = (sp_dim_sz % each_sp_iter_base_coverage) / sp_map_directive->GetOfs();

          if(sp_dim_sz <= sp_map_directive->GetSize()) {
            num_spatial_edge_clusters_ = 1;
          }
          // End of original version

#ifdef DEBUG_CLUSTER_UNIT
          std::cout << "Cluster lv: " << cluster_level_ << std::endl;
          std::cout << "Cluster size: " << cluster_size_ << std::endl;
          std::cout << "num_steady_spatial_iterations_ size: " << num_steady_spatial_iterations_ << std::endl;
          std::cout << "Cluster num_edge_spatial_iterations_: " << num_edge_spatial_iterations_ << std::endl;
#endif
        }

        void AnalyzeNumPartialOutputs() {
          long num_pouts = 1;

          for(auto& dim : *dimensions_) {
            auto dim_name = dim->GetName();

            if(dim_name == DFSL::layer_dim_output_width_ || dim_name == DFSL::layer_dim_output_height_) {
              continue;
            }

            if(dimensions_->IsOverlapped(dim_name)) {
              if(dimensions_->IsSlidingDim(dim_name)) {
                num_pouts *= dim->GetSize();
              }
              else {
                auto sliding_dim_name = dimensions_->GetOverlappingDim(dim_name);
                int sliding_dim_size = dimensions_->GetSize(sliding_dim_name);
                int adjusted_size =  dim->GetSize() - sliding_dim_size + 1;
                num_pouts *= (adjusted_size > 0)? dim->GetSize() - sliding_dim_size + 1 : dim->GetSize();
              }
            }
            else {
              num_pouts *= dim->GetSize();
            }

          }
        } // End of void AnalyzeNumPartialOutputs()

        void Preprocess() {
          //Functions regarding spatial mapping always need to be called first
          AnalyzeSpatialMapIdx();
          AnalyzeInnerTemporalMapIdx();

          AnalyzeNumSpatialIterations();

          AnalyzeSpatialEdgeCase();

          AnalyzeMappingSizes();

          AnalyzeNumPartialOutputs();

        }

		}; // End of class ClusterUnit
	}; // End of namespace DFA
}; // End of namespace maestro

#endif


text:
<?php

namespace Cocorico\CoreBundle\Admin;

use A2lix\TranslationFormBundle\Form\Type\TranslationsType;
use Cocorico\CoreBundle\Entity\ListingCharacteristic;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Symfony\Component\Validator\Constraints\NotBlank;

class ListingCharacteristicAdmin extends AbstractAdmin
{
    protected $translationDomain = 'SonataAdminBundle';
    protected $baseRoutePattern = 'listing-characteristic';
    protected $locales;

    // setup the default sort column and order
    protected $datagridValues = array(
        '_sort_order' => 'ASC',
        '_sort_by' => 'position'
    );

    public function setLocales($locales)
    {
        $this->locales = $locales;
    }

    /** @inheritdoc */
    protected function configureFormFields(FormMapper $formMapper)
    {
        /** @var ListingCharacteristic $subject */
//        $subject = $this->getSubject();

        //Translations fields
        $titles = $descriptions = array();
        foreach ($this->locales as $i => $locale) {
            $titles[$locale] = array(
                'label' => 'Name',
                'constraints' => array(new NotBlank())
            );
            $descriptions[$locale] = array(
                'label' => 'Description',
                'constraints' => array(new NotBlank())
            );
        }

        $formMapper
            ->with('admin.listing_characteristic.title')
            ->add(
                'translations',
                TranslationsType::class,
                array(
                    'locales' => $this->locales,
                    'required_locales' => $this->locales,
                    'fields' => array(
                        'name' => array(
                            'field_type' => 'text',
                            'locale_options' => $titles,
                        ),
                        'description' => array(
                            'field_type' => 'textarea',
                            'locale_options' => $descriptions,
                        )
                    ),
                    /** @Ignore */
                    'label' => 'Descriptions'
                )
            )
            ->add(
                'position',
                null,
                array(
                    'label' => 'admin.listing_characteristic.position.label'
                )
            )
            ->add(
                'listingCharacteristicType',
                'sonata_type_model_list',
                array(
                    'label' => 'admin.listing_characteristic.type.label',
                    'constraints' => array(new NotBlank())
                )
            )
            ->add(
                'listingCharacteristicGroup',
                'sonata_type_model_list',
                array(
                    'label' => 'admin.listing_characteristic.group.label',
                    'constraints' => array(new NotBlank())
                )
            )
            ->end();
    }

    /** @inheritdoc */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add(
                'translations.name',
                null,
                array('label' => 'admin.listing_characteristic.name.label')
            )
            ->add(
                'listingCharacteristicType',
                null,
                array('label' => 'admin.listing_characteristic.type.label')
            )
            ->add(
                'listingCharacteristicGroup',
                null,
                array('label' => 'admin.listing_characteristic.group.label')
            );
    }

    /** @inheritdoc */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('id')
            ->add(
                'name',
                null,
                array(
                    'label' => 'admin.listing_characteristic.name.label',
                )
            )
            ->addIdentifier(
                'listingCharacteristicType',
                null,
                array('label' => 'admin.listing_characteristic.type.label')
            )
            ->addIdentifier(
                'listingCharacteristicGroup',
                null,
                array('label' => 'admin.listing_characteristic.group.label')
            )
            ->add(
                'position',
                null,
                array('label' => 'admin.listing_characteristic.position.label')
            );

        $listMapper->add(
            '_action',
            'actions',
            array(
                'actions' => array(
                    //'show' => array(),
                    'edit' => array(),
                )
            )
        );
    }

    public function getExportFields()
    {
        return array(
            'Id' => 'id',
            'Name' => 'name',
            'Type of Characteristic' => 'listingCharacteristicType',
            'Group' => 'listingCharacteristicGroup',
            'Position' => 'position'
        );
    }

    public function getDataSourceIterator()
    {
        $datagrid = $this->getDatagrid();
        $datagrid->buildPager();

        $dataSourceIt = $this->getModelManager()->getDataSourceIterator($datagrid, $this->getExportFields());
        $dataSourceIt->setDateTimeFormat('d M Y'); //change this to suit your needs

        return $dataSourceIt;
    }

    public function getBatchActions()
    {
        $actions = parent::getBatchActions();
        unset($actions["delete"]);

        return $actions;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        //$collection->remove('create');
        //$collection->remove('delete');
    }
}