text:
#region copyright

#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Apaf.NFSdb.Core.Queries;
using Apaf.NFSdb.Core.Storage;
using Apaf.NFSdb.Core.Tx;
using Apaf.NFSdb.Core.Writes;
using Apaf.NFSdb.Tests.Tx;
using Moq;
using NUnit.Framework;

namespace Apaf.NFSdb.Tests.Query
{
    [TestFixture]
    public class PartitionIntervalIteratorTests
    {
        private TransactionContext _tx;

        [TestCase(null, null, ExpectedResult = "1,2,3,4,5")]
        [TestCase(null, "2014-05-01", ExpectedResult = "1,2,3,4,5")]
        [TestCase(null, "2014-04-03", ExpectedResult = "1,2")]
        [TestCase("2014-04-03", "2014-04-03", ExpectedResult = "")]
        [TestCase("2014-04-03", null, ExpectedResult = "3,4,5")]
        [TestCase("2014-04-01", "2014-04-06", ExpectedResult = "1,2,3,4,5")]
        public string Should_find_paritions_by_interval(string startStr, string endStr)
        {
            var iter = CreateIterator();
            var partitions = CreatePartitions(new DateTime(2014, 04, 01),
                new DateTime(2014, 04, 06), 5, TimeSpan.FromHours(1));

            var start = ToDateTime(startStr);
            var end = ToDateTime(endStr);
            DateInterval di = DateInterval.Any;
            if (start != null && end != null)
            {
                di = new DateInterval(start.Value, end.Value);
            }
            else if (start != null)
            {
                di = DateInterval.From(start.Value);
            }
            else if (end != null)
            {
                di = DateInterval.To(end.Value);
            }

            var resultIter =
                iter.IteratePartitions(partitions, di, _tx);

            return string.Join(",",
                resultIter.Select(p => string.Format("{0}", p.PartitionID)));
        }

        [TestCase(null, null, ExpectedResult = "0-23")]
        [TestCase("2014-04-01 00:00:01", null, ExpectedResult = "1-23")]
        [TestCase("2014-04-01 05:00:01", null, ExpectedResult = "6-23")]
        [TestCase("2014-04-01 05:00:00", null, ExpectedResult = "5-23")]
        [TestCase("2014-04-01 05:00:00", "2014-04-01 06:00:00", ExpectedResult = "5-5")]
        public string Should_find_parition_hi_lo(string startStr, string endStr)
        {
            var iter = CreateIterator();
            var partitions = CreatePartitions(new DateTime(2014, 04, 01),
                new DateTime(2014, 04, 02), 1, TimeSpan.FromHours(1));

            var start = ToDateTime(startStr);
            var end = ToDateTime(endStr);
            DateInterval di = DateInterval.Any;
            if (start != null && end != null)
            {
                di = new DateInterval(start.Value, end.Value);
            }
            else if (start != null)
            {
                di = DateInterval.From(start.Value);
            }
            else if (end != null)
            {
                di = DateInterval.To(end.Value);
            }

            var resultIter =
                iter.IteratePartitions(partitions, di, _tx);

            return string.Join(",",
                resultIter.Select(p => string.Format("{0}-{1}", p.Low, p.High)));
        }

        private DateTime? ToDateTime(string startStr)
        {
            if (startStr == null) return null;
            return DateTime.Parse(startStr, CultureInfo.InvariantCulture);
        }

        private PartitionIntervalIterator CreateIterator()
        {
            return new PartitionIntervalIterator();
        }

        private IPartition[] CreatePartitions(DateTime from, DateTime to, int count, TimeSpan recordsDelay)
        {
            var res = new List<IPartition>();
            var tsmp = DateUtils.DateTimeToUnixTimeStamp(from);
            var end = DateUtils.DateTimeToUnixTimeStamp(to);
            var partStart = tsmp;
            var partIncr = (long)(to - from).TotalMilliseconds/count;
            var recIncr = (long)recordsDelay.TotalMilliseconds;
            var partId = 1;
            var partTxs = new List<PartitionTxData>();
            partTxs.Add(new PartitionTxData(100, 0, DateTime.MinValue, DateTime.MaxValue, new ReadContext()));

            while (tsmp < end)
            {
                var partTsmps = new List<long>();
                while (tsmp < partStart + partIncr)
                {
                    partTsmps.Add(tsmp);
                    tsmp += recIncr;
                }
                partTxs.Add(new PartitionTxData(100, partId,
                    DateUtils.UnixTimestampToDateTime(partStart),
                    DateUtils.UnixTimestampToDateTime(partStart + partIncr), new ReadContext()));

                partTxs[partId].NextRowID = partTsmps.Count;
                res.Add(MockPartition(partTsmps, partStart, partStart + partIncr, partId++));
                partStart += partIncr;
            }
            _tx = new TransactionContext(100, partTxs.ToArray(), res.ToArray(), new Mock<ITxPartitionLock>().Object);

            return res.ToArray();
        }

        private IPartition MockPartition(List<long> partTsmps, long start, long end, int id)
        {
            var part = new Mock<IPartition>();
            part.Setup(p => p.StartDate).Returns(DateUtils.UnixTimestampToDateTime(start));
            part.Setup(p => p.EndDate).Returns(DateUtils.UnixTimestampToDateTime(end));
            part.Setup(p => p.PartitionID).Returns(id);
            part.Setup(p => p.BinarySearchTimestamp(It.IsAny<DateTime>(), It.IsAny<IReadTransactionContext>()))
                .Returns((DateTime dt, IReadTransactionContext tx) =>
                    partTsmps.BinarySearch(DateUtils.DateTimeToUnixTimeStamp(dt)));
            return part.Object;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>Hello React!</title>
	<meta charset="utf-8" />


text:
START_ATF_NAMESPACE
    namespace Detail
    {
        extern ::std::array<hook_record, 2> _store_dummy_functions;
    }; // end namespace Detail
END_ATF_NAMESPACE


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

namespace AntShell.Helpers
{
    public class SequenceValidator
    {
        private Dictionary<char, Tuple<SequenceValidator, ControlSequenceGenerator>> seqs = new Dictionary<char, Tuple<SequenceValidator, ControlSequenceGenerator>>();

        public SequenceValidationResult Check(IReadOnlyList<char> input, out ControlSequence seq)
        {
            Tuple<ControlSequenceGenerator, int> result;
            var seqFound = TryCheck(input, 0, out result);
            if(seqFound)
            {
                if(result != null)
                {
                    var length = result.Item2 + 1;
                    seq = result.Item1(input, length);
                    return SequenceValidationResult.SequenceFound;
                }
                else
                {
                    seq = null;
                    return SequenceValidationResult.PrefixFound;
                }
            }
            else
            {
                seq = null;
                return SequenceValidationResult.SequenceNotFound;
            }

        }

        private bool TryCheck(IReadOnlyList<char> input, int offset, out Tuple<ControlSequenceGenerator, int> seq)
        {
            if(offset == input.Count)
            {
                seq = null;
                return true;
            }

            if(seqs.ContainsKey((char)255))
            {
                var loffset = offset;

                if(char.IsDigit((char)input[loffset]))
                {
                    while(loffset < input.Count && char.IsDigit((char)input[loffset]))
                    {
                        if(loffset < input.Count)
                        {
                            loffset++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    var result = seqs[(char)255].Item1.TryCheck(input, loffset, out seq); // might not work when '255' byte is the last one in a sequence
                    if(result)
                    {
                        return result;
                    }
                }
            }

            if(seqs.ContainsKey(input[offset]))
            {
                if(input.Count - offset == 1)
                {
                    if(seqs[input[offset]].Item2 != null)
                    {
                        seq = Tuple.Create(seqs[input[offset]].Item2, offset);
                        return true;
                    }
                    else
                    {
                        seq = null;
                        return true;
                    }
                }

                return seqs[input[offset]].Item1.TryCheck(input, offset + 1, out seq);
            }
            else
            {
                seq = null;
                return false;
            }
        }

        public void Add(ControlSequenceGenerator seq, params char[] input)
        {
            Add(input, 0, seq);
        }

        public void Add(ControlSequence seq, params char[] input)
        {
            Add(input, 0, (a, b) => seq);
        }

        public void Add(ControlSequenceType seqT, params char[] input)
        {
            Add(input, 0, (a, b) => new ControlSequence(seqT));
        }

        private void Add(char[] input, int offset, ControlSequenceGenerator seq)
        {
            if(input.Length - offset == 0)
            {
                return;
            }

            if(!seqs.ContainsKey(input[offset]))
            {
                seqs.Add(input[offset], new Tuple<SequenceValidator, ControlSequenceGenerator>(new SequenceValidator(), input.Length - offset == 1 ? seq : null));
            }

            if(input.Length - offset == 1)
            {
                return;
            }
            else
            {
                seqs[input[offset]].Item1.Add(input, offset + 1, seq);
            }
        }
    }

    public enum SequenceValidationResult
    {
        SequenceNotFound,
        SequenceFound,
        PrefixFound
    }

    public delegate ControlSequence ControlSequenceGenerator(IReadOnlyList<char> seq,int length);
}


text:
<?php

namespace RolesCapabilities\Access;

use Cake\Core\App;
use Cake\Core\Configure;
use Cake\Datasource\EntityInterface;
use Cake\Datasource\Exception\InvalidPrimaryKeyException;
use Cake\Datasource\Exception\RecordNotFoundException;
use Cake\Log\Log;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
use Cake\Utility\Inflector;
use Groups\Model\Table\GroupsTable;
use Qobo\Utils\ModuleConfig\ConfigType;
use Qobo\Utils\ModuleConfig\ModuleConfig;
use Qobo\Utils\Utility;
use RolesCapabilities\Capability as Cap;
use RolesCapabilities\Model\Table\CapabilitiesTable;
use Webmozart\Assert\Assert;

/**
 *  Utils class with common methos for Capabilities
 *
 *
 */
class Utils
{
    /**
     * Full type capability identifier
     */
    const CAP_TYPE_FULL = 'full';

    /**
     * Owner type capability identifier
     */
    const CAP_TYPE_OWNER = 'owner';

    /**
     * Parent type capability identifier
     */
    const CAP_TYPE_PARENT = 'parent';

    /**
     * Belongs to capability identifier
     */
    const CAP_TYPE_BELONGS = 'belongs';

    /**
     * Non-assigned actions
     *
     * @var array
     */
    protected static $nonAssignedActions = [
        'add',
    ];

    protected static $capabilitiesTable = null;

    /**
     * Cached user capabilities by user id.
     *
     * @var array
     */
    protected static $userCapabilities = [];

    /**
     * Returns Controller's class name namespaced.
     *
     * @param mixed[] $url array of URL parameters.
     * @return string|null
     */
    public static function getControllerFullName(array $url): ?string
    {
        $result = null;

        if (empty($url['controller'])) {
            return $result;
        }

        $class = $url['controller'];
        if (!empty($url['plugin'])) {
            $class = $url['plugin'] . '.' . $class;
        }
        $result = App::className($class . 'Controller', 'Controller');
        if (empty($result)) {
            return null;
        }

        return $result;
    }

    /**
     * Get full type capability identifier.
     *
     * @return string
     */
    public static function getTypeFull(): string
    {
        return static::CAP_TYPE_FULL;
    }

    /**
     * Get owner type capability identifier.
     *
     * @return string
     */
    public static function getTypeOwner(): string
    {
        return static::CAP_TYPE_OWNER;
    }

    /**
     * Get parent type capability identifier.
     *
     * @return string
     */
    public static function getTypeParent(): string
    {
        return static::CAP_TYPE_PARENT;
    }

    /**
     * Get belongsTo capability identifier
     *
     * @return string
     */
    public static function getTypeBelongs(): string
    {
        return static::CAP_TYPE_BELONGS;
    }

    /**
     * Method that retrieves and returns Controller public methods.
     *
     * @param  string $controllerName Controller name
     * @return mixed[]
     */
    public static function getControllerPublicMethods(string $controllerName): array
    {
        $actions = [];

        if (!class_exists($controllerName)) {
            return $actions;
        }

        $refClass = new \ReflectionClass($controllerName);
        foreach ($refClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
            $actions[] = $method->name;
        }

        return $actions;
    }

    /**
     * Get list of Cake's Controller class methods.
     *
     * @return mixed[]
     */
    public static function getCakeControllerActions(): array
    {
        $result = get_class_methods('Cake\Controller\Controller');

        return $result;
    }

    /**
     * Method that filter's out skipped actions from Controller's actions list.
     *
     * @param  string $controllerName Controller name
     * @param  mixed[]  $actions        Controller actions
     * @return mixed[]
     */
    public static function filterSkippedActions(string $controllerName, array $actions): array
    {
        $skipActions = [];
        if (is_callable([$controllerName, 'getSkipActions'])) {
            $skipActions = $controllerName::getSkipActions($controllerName);
        }

        // skip actions for all controllers, if defined in the plugin's configuration.
        $allSkipActions = Configure::read('RolesCapabilities.accessCheck.skipActions.*');
        if (!empty($allSkipActions)) {
            $skipActions = array_merge($skipActions, $allSkipActions);
        }

        // skip actions for specified controller, if defined in the plugin's configuration.
        $controllerSkipActions = Configure::read('RolesCapabilities.accessCheck.skipActions.' . $controllerName);
        if (!empty($controllerSkipActions)) {
            $skipActions = array_merge($skipActions, $controllerSkipActions);
        }

        $skipActions = array_merge(
            $skipActions,
            static::getCakeControllerActions()
        );

        foreach ($actions as $k => $action) {
            if (in_array($action, $skipActions)) {
                unset($actions[$k]);
            }
        }

        return $actions;
    }

    /**
     * Method that filters and returns Controller action(s) that can be used for generating access capabilities.
     *
     * @param  string $controllerName Controller name
     * @param  mixed[]  $actions        Action(s) to filter. If not specified all controller's public methods will be used.
     * @return mixed[]
     */
    public static function getActions(string $controllerName, array $actions = []): array
    {
        $publicMethods = static::getControllerPublicMethods($controllerName);
        // return if controller has no public methods
        if (empty($publicMethods)) {
            return [];
        }

        // if no actions defined, use controller's public methods
        if (!empty($actions)) {
            $actions = array_intersect($actions, $publicMethods);
        } else { // else use controller's public methods
            $actions = $publicMethods;
        }

        if (empty($actions)) {
            return $actions;
        }

        // filter out skipped actions
        $actions = static::filterSkippedActions($controllerName, $actions);

        return $actions;
    }

    /**
     * Method that returns Table instance of specified controller.
     *
     * @param  string          $controllerName Controller name
     * @return \Cake\ORM\Table
     */
    public static function getControllerTableInstance(string $controllerName): \Cake\ORM\Table
    {
        $tableName = App::shortName($controllerName, 'Controller', 'Controller');

        // remove vendor prefix
        if (false !== strpos($tableName, '/')) {
            $tableName = substr($tableName, strpos($tableName, '/') + 1);
        }

        return TableRegistry::get($tableName);
    }

    /**
     * Generate capability's controller name.
     *
     * @param  string $controllerName Controller name
     * @return string
     */
    public static function generateCapabilityControllerName(string $controllerName): string
    {
        $result = str_replace('\\', '_', $controllerName);

        return $result;
    }

    /**
     * Generate capability name.
     *
     * @param  string $controllerName Controller name
     * @param  string $action         Action name
     * @return string
     */
    public static function generateCapabilityName(string $controllerName, string $action): string
    {
        $result = 'cap__' . $controllerName . '__' . $action;

        return $result;
    }

    /**
     * Generate capability label.
     *
     * @param  string $controllerName Controller name
     * @param  string $action         Action name
     * @return string
     */
    public static function generateCapabilityLabel(string $controllerName, string $action): string
    {
        $result = 'Cap ' . $controllerName . ' ' . $action;

        return $result;
    }

    /**
     * Generate capability description.
     *
     * @param  string $controllerName Controller name
     * @param  string $action         Action name
     * @return string
     */
    public static function generateCapabilityDescription(string $controllerName, string $action): string
    {
        $result = 'Allow ' . $action;

        return $result;
    }

    /**
     * Convert action/method name to human-friendly description
     *
     * Action/method names mostly follow CakePHP naming conventions
     * and are not very human-friendly.  For example, 'list' is much
     * less confusing than 'index'.
     *
     * When used in the capability description, an additional layer of
     * confusion is introduced.  For example, 'Allow info' or 'Allow
     * changelog'.  Adjusting these to 'Allow view info' and 'Allo
     * view changelog' help a great deal.
     *
     * @todo Allow controllers to take control over these
     *
     * @param string $action Action/method name to humanize
     * @return string
     */
    public static function humanizeActionName(string $action): string
    {
        // cameCaseMethod -> under_score -> Human Form -> lowercase
        $result = strtolower(Inflector::humanize(Inflector::underscore($action)));

        switch ($action) {
            case 'index':
                $result = 'list';
                break;
            case 'info':
            case 'changelog':
                $result = 'view ' . $action;
                break;
        }

        return $result;
    }

    /**
     * Method that generates capabilities for specified controller's actions.
     * Capabilities included are full or owner access types.
     *
     * @param \Cake\ORM\Table $table Table instance
     * @param string $contrName Controller name
     * @param mixed[] $actions Controller actions
     * @return mixed[]
     */
    public static function getCapabilitiesForAction(Table $table, string $contrName, array $actions): array
    {
        $result = [];

        if (empty($contrName) || empty($actions)) {
            return $result;
        }

        $contrName = static::generateCapabilityControllerName($contrName);

        $fullCapabilities = static::generateFullCapabilities($contrName, $actions);
        if (!empty($fullCapabilities)) {
            $result[static::CAP_TYPE_FULL] = $fullCapabilities;
        }

        $ownerCapabilities = static::generateOwnerCapabilities($table, $contrName, $actions);
        if (!empty($ownerCapabilities)) {
            $result[static::CAP_TYPE_OWNER] = $ownerCapabilities;
        }

        $parentCapabilities = static::generateParentCapabilities($table, $contrName, $actions);
        if (!empty($parentCapabilities)) {
            $result[static::CAP_TYPE_PARENT] = $parentCapabilities;
        }

        $belongsToCaps = static::generateBelongsToCapabilities($table, $contrName, $actions);
        if (!empty($belongsToCaps)) {
            $result[static::CAP_TYPE_BELONGS] = $belongsToCaps;
        }

        return $result;
    }

    /**
     * Generate controller full capabilities.
     *
     * @param string $contrName Controller name
     * @param mixed[] $actions Controller actions
     * @return mixed[]
     */
    protected static function generateFullCapabilities(string $contrName, array $actions): array
    {
        $result = [];

        if (empty($contrName) || empty($actions)) {
            return $result;
        }

        // generate action's full (all) type capabilities
        foreach ($actions as $action) {
            $name = static::generateCapabilityName($contrName, $action);
            $options = [
                'label' => static::generateCapabilityLabel($contrName, $action . '_all'),
                'description' => static::generateCapabilityDescription($contrName, static::humanizeActionName($action)),
            ];

            $result[] = new Cap($name, $options);
        }

        return $result;
    }

    /**
     * Generate controller owner capabilities.
     *
     * @param \Cake\ORM\Table $table Table instance
     * @param string $contrName Controller name
     * @param mixed[] $actions Controller actions
     * @return mixed[]
     */
    protected static function generateOwnerCapabilities(Table $table, string $contrName, array $actions): array
    {
        $assignationFields = static::getTableAssignationFields($table);

        return static::generateCapabilities($contrName, $actions, $assignationFields);
    }

    /**
     * generateBelongsToCapabilities method to generate controller belongs to capabilities
     *
     * @param \Cake\ORM\Table $table Table instance
     * @param string $contrName Controller name
     * @param mixed[] $actions Controller actions
     * @return mixed[]
     */
    protected static function generateBelongsToCapabilities(Table $table, string $contrName, array $actions): array
    {
        $assignationFields = static::getTableBelongsToFields($table);

        return static::generateCapabilities($contrName, $actions, $assignationFields);
    }

    /**
     * generateCapabilities method to generate controller belongs to capabilities
     *
     * @param string $contrName Controller name
     * @param mixed[] $actions Controller actions
     * @param mixed[] $assignationFields list of assignation fields
     * @param string $assignationType Type of association
     * @return mixed[]
     */
    protected static function generateCapabilities(string $contrName, array $actions, array $assignationFields, string $assignationType = ''): array
    {
        $result = [];

        if (empty($contrName) || empty($actions)) {
            return $result;
        }

        if (empty($assignationFields)) {
            return $result;
        }

        foreach ($actions as $action) {
            // skip rest of the logic if assignment fields are not found
            // or if current action does not support assignment (Example: add / create)
            if (in_array($action, static::$nonAssignedActions)) {
                continue;
            }

            // generate action's owner (assignment field) type capabilities
            foreach ($assignationFields as $assignationField) {
                $label = static::generateCapabilityLabel($contrName, $action . '_' . $assignationField);
                $suffix = ' if ' . (!empty($assignationType) ? $assignationType : 'owner') . ' (' . Inflector::humanize($assignationField) . ')';
                $description = static::generateCapabilityDescription(
                    $contrName,
                    static::humanizeActionName($action) . $suffix
                );
                $field = $assignationField;

                $name = static::generateCapabilityName($contrName, $action . '_' . $assignationField);
                $options = [
                    'label' => $label,
                    'description' => $description,
                    'field' => $field,
                ];

                if (!empty($assignationType)) {
                    $result[$assignationType . '_(_' . $assignationField . '_)'][] = new Cap($name, $options);
                } else {
                    $result[] = new Cap($name, $options);
                }
            }
        }

        return $result;
    }

    /**
     * Generate controller parent capabilities.
     *
     * @param \Cake\ORM\Table $table Table instance
     * @param string $contrName Controller name
     * @param mixed[] $actions Controller actions
     * @return mixed[]
     */
    protected static function generateParentCapabilities(Table $table, string $contrName, array $actions): array
    {
        $result = [];

        if (empty($contrName) || empty($actions)) {
            return $result;
        }

        $parentModules = static::getTableParentModules($table);
        if (empty($parentModules)) {
            return $result;
        }

        $name = static::generateCapabilityName($contrName, 'fetch_parent');
        $options = [
            'label' => static::generateCapabilityLabel($contrName, 'fetch_parent'),
            'description' => static::generateCapabilityDescription(
                $contrName,
                'fetch if owner on parent module (' . implode(', ', $parentModules) . ')'
            ),
            'parent_modules' => $parentModules,
        ];

        $result[] = new Cap($name, $options);

        return $result;
    }

    /**
     * Method that retrieves all capabilities.
     *
     * @return mixed[] capabilities
     */
    public static function getAllCapabilities(): array
    {
        $result = [];
        foreach (Utility::getControllers() as $controller) {
            if (!is_callable([$controller, 'getCapabilities'])) {
                continue;
            }

            $result[$controller] = $controller::getCapabilities($controller);
        }

        return $result;
    }

    /**
     *  fetchUserCapabilities() fetches user capabilities list
     *
     * @param string $userId    ID of user
     * @return mixed[]          list of user's capabilities or empty array
     */
    public static function fetchUserCapabilities(string $userId): array
    {
        $entities = [];

        if (array_key_exists($userId, static::$userCapabilities)) {
            return static::$userCapabilities[$userId];
        }

        $table = TableRegistry::get('RolesCapabilities.Capabilities');
        Assert::isInstanceOf($table, CapabilitiesTable::class);

        $userGroups = $table->getUserGroups($userId);
        if (empty($userGroups)) {
            return $entities;
        }

        $userRoles = $table->getGroupsRoles($userGroups);
        if (empty($userRoles)) {
            return $entities;
        }

        static::$userCapabilities[$userId] = $table->getUserRolesEntities($userRoles);

        return static::$userCapabilities[$userId];
    }

    /**
     * Returns Controller permission capabilities.
     *
     * @param  string $controllerName Controller name
     * @param  mixed[]  $actions        Controller actions
     * @return mixed[]
     */
    public static function getCapabilities(string $controllerName = null, array $actions = []): array
    {
        $result = [];

        if (empty($controllerName)) {
            return $result;
        }

        $skipControllers = Configure::read('RolesCapabilities.accessCheck.skipControllers');
        if (is_callable([$controllerName, 'getSkipControllers'])) {
            $skipControllers = array_merge($skipControllers, $controllerName::getSkipControllers());
        }

        if (in_array($controllerName, $skipControllers)) {
            return $result;
        }

        $actions = static::getActions($controllerName, $actions);

        if (empty($actions)) {
            return $result;
        }

        // get controller table instance
        $table = static::getControllerTableInstance($controllerName);

        $result = static::getCapabilitiesForAction($table, $controllerName, $actions);

        return $result;
    }

    /**
     * Method that checks if user has full access on Controller's action.
     *
     * @param  string $type               Capability type
     * @param  mixed[]  $actionCapabilities Action capabilities
     * @param  mixed[]  $user               User info
     * @param  mixed[]  $url                Controller url
     * @return bool
     */
    public static function hasTypeAccess(string $type, array $actionCapabilities, array $user, array $url): bool
    {
        // skip if action has no access capabilities for specified type
        if (!isset($actionCapabilities[$type])) {
            return false;
        }

        $methodName = 'hasTypeAccess' . Inflector::camelize($type);

        if (! method_exists(get_called_class(), $methodName)) {
            Log::warning(sprintf(
                'Trying to check type access on non-existing method %s::%s',
                get_called_class(),
                $methodName
            ));

            return false;
        }

        $result = static::$methodName($actionCapabilities[$type], $user, $url);

        return $result;
    }

    /**
     * Method that checks if user has full access on Controller's action.
     *
     * @param  mixed[]  $capabilities Action capabilities
     * @param  mixed[]  $user               User info
     * @param  mixed[]  $url                Controller url
     * @return bool
     */
    protected static function hasTypeAccessFull(array $capabilities, array $user, array $url): bool
    {
        foreach ($capabilities as $capability) {
            if (static::hasAccessInCapabilities($capability->getName(), $user['id'])) {
                return true;
            }
        }

        return false;
    }

    /**
     * Method that checks if user has full access on Controller's action.
     *
     * @param  mixed[]  $capabilities Action capabilities
     * @param  mixed[]  $user               User info
     * @param  mixed[]  $url                Controller url
     * @return bool
     */
    protected static function hasTypeAccessOwner(array $capabilities, array $user, array $url): bool
    {
        $entity = static::getEntityFromUrl($url);

        foreach ($capabilities as $capability) {
            if (!static::hasAccessInCapabilities($capability->getName(), $user['id'])) {
                continue;
            }

            // if url does not include an id and user has owner capability
            // access, to current module action, allow him access. (index action)
            if (empty($entity)) {
                return true;
            }

            // if url includes an id, check capability's field value from the entity
            // against current user id and if they match allow him access. (view, edit actions etc)
            $field = $capability->getField();

            if ($entity->get($field) === $user['id']) {
                return true;
            }
        }

        return false;
    }

    /**
     * getUserGroups method
     *
     * @param mixed[] $user to get groups
     * @return mixed[] with group ID and name
     */
    protected static function getUserGroups(array $user): array
    {
        $table = TableRegistry::get('Groups.Groups');
        Assert::isInstanceOf($table, GroupsTable::class);

        return $table->getUserGroups($user['id'], [
            'fields' => ['id'],
            'contain' => [],
        ]);
    }

    /**
     * Method that checks if user has belongs to access on Controller's action.
     *
     * @param  mixed[]  $capabilities Action capabilities
     * @param  mixed[]  $user               User info
     * @param  mixed[]  $url                Controller url
     * @return bool
     */
    protected static function hasTypeAccessBelongs(array $capabilities, array $user, array $url): bool
    {
        $entity = static::getEntityFromUrl($url);

        $userGroups = static::getUserGroups($user);

        foreach ($capabilities as $capability) {
            if (!static::hasAccessInCapabilities($capability->getName(), $user['id'])) {
                continue;
            }

            // if url does not include an id and user has belongs to capability
            // access, to current module action, allow him access. (index action)
            if (empty($entity)) {
                return true;
            }

            // if url includes an id, check capability's field value from the entity
            // against current user id and if they match allow him access. (view, edit actions etc)
            $field = $capability->getField();

            foreach (array_keys($userGroups) as $id) {
                if ($entity->get($field) === $id) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * getEntityFromUrl method gets entity ID from given URL if so
     *
     * @param mixed[] $url to get ID
     * @return \Cake\Datasource\EntityInterface|null
     */
    protected static function getEntityFromUrl(array $url): ?EntityInterface
    {
        $entity = null;

        $id = null;
        if (!empty($url['pass'][0])) {
            $id = $url['pass'][0];
        }

        if (empty($id) && !empty($url['0'])) {
            $id = $url['0'];
        }

        // if url includes an id, fetch relevant record
        if (!empty($id)) {
            try {
                $tableName = $url['controller'];
                if (!empty($url['plugin'])) {
                    $tableName = $url['plugin'] . '.' . $tableName;
                }
                $table = TableRegistry::get($tableName);
                $entity = $table->get($id);
            } catch (InvalidPrimaryKeyException $e) {
                Log::warning(sprintf('Failed to fetch record with id [%s] from table [%s]', $id, $url['controller']));
            } catch (RecordNotFoundException $e) {
                Log::warning(sprintf('Failed to fetch record with id [%s] from table [%s]', $id, $url['controller']));
            }
        }

        return $entity;
    }

    /**
     * Method that checks if current user is allowed access.
     *
     * Returns true if current user has access, false otherwise.
     *
     * @param  string $capability capability name
     * @param  string $userId     user id
     * @return bool
     */
    public static function hasAccessInCapabilities(string $capability, string $userId): bool
    {
        $userCaps = static::fetchUserCapabilities($userId);
        if (in_array($capability, $userCaps)) {
            return true;
        }

        return false;
    }

    /**
     * Method that retrieves and returns Table's assignation fields.
     *
     * These are fields that dictate assigment, usually foreign key
     * associated with Users tables. (example: assigned_to)
     *
     * @param  \Cake\ORM\Table $table Table instance
     * @return mixed[]
     */
    public static function getTableAssignationFields(Table $table): array
    {
        $fields = [];
        $assignationModels = Configure::read('RolesCapabilities.accessCheck.assignationModels');

        foreach ($table->associations() as $association) {
            // skip non-assignation models
            if (!in_array($association->getClassName(), $assignationModels)) {
                continue;
            }

            $fields[] = $association->getForeignKey();
        }

        return $fields;
    }

    /**
     * Method that retrieves and returns Table's belongs to fields.
     *
     * These are fields that dictate assigment, usually foreign key
     * associated with Groups tables. (example: belongs_to)
     *
     * @param  \Cake\ORM\Table $table Table instance
     * @return mixed[]
     */
    public static function getTableBelongsToFields(Table $table): array
    {
        $fields = [];
        $belongsToModels = Configure::read('RolesCapabilities.accessCheck.belongsToModels');

        foreach ($table->associations() as $association) {
            // skip non-assignation models
            if (!in_array($association->className(), $belongsToModels)) {
                continue;
            }

            $fields[] = $association->foreignKey();
        }

        return $fields;
    }

    /**
     * Get table parent modules from module configuration.
     *
     * @param \Cake\ORM\Table $table Table instance
     * @return mixed[]
     */
    public static function getTableParentModules(Table $table): array
    {
        $result = [];

        list(, $moduleName) = pluginSplit($table->getRegistryAlias());

        try {
            $config = new ModuleConfig(ConfigType::MODULE(), $moduleName);
            $moduleConfig = $config->parseToArray();
            $result = Hash::get($moduleConfig, 'table.permissions_parent_modules', []);
        } catch (\InvalidArgumentException $e) {
            return $result;
        }

        return $result;
    }

    /**
     * normalizeControllerName method
     *
     * @param mixed[] $url including plugin if so, controller and action
     * @return string full controller name including App or Plugin
     */
    public static function normalizeControllerName(array $url): string
    {
        $plugin = !empty($url['plugin']) ? $url['plugin'] : 'App';
        /**
         * @var string $plugin
         */
        $plugin = preg_replace('/\//', '\\', $plugin);
        if (empty($plugin)) {
            $plugin = '';
        }
        $controllerName = $plugin . '\\Controller\\' . $url['controller'] . 'Controller';

        return $controllerName;
    }

    /**
     * getReportToUsers method
     *
     * @param string $userId to find reported to users
     * @return mixed[]
     */
    public static function getReportToUsers(string $userId): array
    {
        $table = TableRegistry::get(Configure::read('Users.table'));
        $users = $table->find()
            ->where([
                'reports_to' => $userId,
                ])
            ->all()
            ->toArray();

        if (empty($users)) {
            return $users;
        }

        $userMap = [];
        $filteredUsers = [];

        foreach ($users as $user) {
            if ($user->get('id') === $userId || isset($userMap[$user->get('id')])) {
                continue;
            }

            $userMap[$user->get('id')] = $user;
            $filteredUsers[] = $user;
        }

        return $filteredUsers;
    }
}


text:
docker build -t fabbit-iot .
docker run -p 5000:5000 --name iotapp fabbit-iot

# to login to the docker iotapp's terminal run
# docker exec -it iotapp bash

# to stop the docker iotapp run
# docker stop iotapp && docker rm $(docker ps -aq)'


text:
{% extends "base.html" %}

{% load staticfiles %}
{% load django_bootstrap_breadcrumbs %}

{% block breadcrumbs %}
    {{ block.super }}
    {% breadcrumb "Internal Error" "dashboard" %}
{% endblock %}

{% block title %}Internal Error{% endblock %}

{% block content_header %}
    Internal Error
{% endblock %}

{% block content_subheader %}{% endblock %}

{% block content %}

 500

 Oops! Something went wrong.

                Please, contact an administrator.

            {% if message %}

{{ message }}

            {% endif %}

{% endblock %}


text:
layout: page
title: University of Utah
subtitle: College of Health
hero: /assets/images/hero-coh.jpg
classes: t-work--uucoh
tags:
  - design
  - front-end development
  - back-end development
---

{% include lead.html content="University of Utah had recently rolled out a redesign of their website. The College of Health needed a design update that aligned closer to main campus." %}

			<button class="c-button  c-button--large  c-button--primary  c-button--expand" disabled>
				Site Offline
			</button>

I acted as full-stack developer on this project and worked closely with a content specialist to roll out websites for the college's seven departments in a short time.

{% include zoom.html src="/assets/images/work__coh--pt.jpg" alt="Department of Physical Therapy website" %}

Skills

Prototyping

Design

Typography

UX/UI

User Testing

Tools

Photoshop

Git

Bootstrap/Less

jQuery

Gulp

PHP

Conclusion

This project taught me the importance of documenting your work, even when you're the sole developer. In addition, I learned that there is no such thing as too much communication with a client.

The site was in use for two years until it was redesigned in order to unify all of University of Utah Health's academic sites. I played a key role in the redesign. You can read more about that project here.


text:
package be.bagofwords.db.data;

import be.bagofwords.util.ByteArraySerializable;
import be.bagofwords.util.HashUtils;
import be.bagofwords.util.Pair;
import be.bagofwords.util.SerializationUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CountsList extends ArrayList<Pair<Long, Long>> implements ByteArraySerializable {

    public CountsList() {
        super();
    }

    public CountsList(CountsList list) {
        super(list);
    }

    public CountsList(long key, int count) {
        this();
        addCount(key, count);
    }

    public CountsList(int initialSize) {
        super(initialSize);
    }

    public CountsList(byte[] serialized) {
        int longWidth = SerializationUtils.getWidth(Long.class);
        int size = serialized.length / (longWidth * 2);
        int offset = 0;
        for (int i = 0; i < size; i++) {
            long key = SerializationUtils.bytesToLong(serialized, offset);
            long value = SerializationUtils.bytesToLong(serialized, serialized.length / 2 + offset);
            offset += longWidth;
            add(new Pair<>(key, value));
        }
    }

    public synchronized long getCount(long key) {
        int ind = Collections.binarySearch((List) this, key);
        if (ind >= 0) {
            return get(ind).getSecond();
        } else {
            return 0;
        }
    }

    public synchronized void addCount(long key, long count) {
        add(new Pair<>(key, count));
    }

    @JsonIgnore
    public synchronized long getTotal() {
        long total = 0;
        for (Pair<Long, Long> value : this) {
            total += value.getSecond();
        }
        return total;
    }

    public synchronized CountsList clone() {
        return new CountsList(this);
    }

    public void compact() {
        if (!isCompacted()) {
            synchronized (this) {
                if (!isCompacted()) {
                    List<Pair<Long, Long>> oldCounts = new ArrayList<>(this);
                    clear();
                    Collections.sort(oldCounts);
                    for (int i = 0; i < oldCounts.size(); ) {
                        Pair<Long, Long> curr = oldCounts.get(i);
                        long combinedCount = curr.getSecond();
                        i++;
                        while (i < oldCounts.size() && oldCounts.get(i).getFirst().equals(curr.getFirst())) {
                            combinedCount += oldCounts.get(i++).getSecond();
                        }
                        add(new Pair<>(curr.getFirst(), combinedCount));
                    }
                }
            }
        }
    }

    private boolean isCompacted() {
        for (int i = 1; i < size(); i++) {
            if (get(i - 1).getFirst() >= get(i).getFirst()) {
                return false;
            }
        }
        return true;
    }

    public synchronized int hashCode() {
        int result = HashUtils.startHash;
        for (Pair<Long, Long> value : this) {
            result = result * HashUtils.addHash + value.getFirst().intValue();
            result = result * HashUtils.addHash + value.getSecond().hashCode();
        }
        return result;
    }

    public String toString() {
        String result = "{ ";
        int i;
        for (i = 0; i < size() && i < 10; i++) {
            result += get(i).getFirst() + ":" + get(i).getSecond();
            if (i < size() - 1) {
                result += ", ";
            }
        }
        if (i < size()) {
            result += " ...";
        }
        result += "}";
        return result;
    }

    public List<Long> getSortedKeys() {
        List<Pair<Long, Long>> sortedValues = new ArrayList<>(this);
        Collections.sort(sortedValues, (val1, val2) -> {
            if (val1.getSecond().equals(val2.getSecond())) {
                return Long.compare(val1.getFirst(), val2.getFirst());
            } else {
                return -Long.compare(val1.getSecond(), val2.getSecond()); //largest first
            }
        });
        List<Long> result = new ArrayList<>();
        for (Pair<Long, Long> value : sortedValues) {
            result.add(value.getFirst());
        }
        return result;
    }

    @Override
    public byte[] toByteArray() {
        int longWidth = SerializationUtils.getWidth(Long.class);
        int size = size() * longWidth * 2;
        byte[] result = new byte[size];
        int offset = 0;
        for (Pair<Long, Long> value : this) {
            SerializationUtils.longToBytes(value.getFirst(), result, offset);
            offset += longWidth;
        }
        for (Pair<Long, Long> value : this) {
            SerializationUtils.longToBytes(value.getSecond(), result, offset);
            offset += longWidth;
        }
        if (offset != result.length) {
            throw new RuntimeException("Something went wrong!");
        }
        return result;
    }
}


text:
@implementation dbHandler

static sqlite3 *_sharedDatabase = nil;

+ (sqlite3 *)sharedDatabase
{

    if (_sharedDatabase != nil) {
        return _sharedDatabase;
    }
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSInteger eventid = [[NSUserDefaults standardUserDefaults] integerForKey:@"eventid"];
    NSString *filename = @"";

    NSString *documentsDirectory = [paths objectAtIndex:0];
    documentsDirectory = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", eventid]];

    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *dirContents = [fm contentsOfDirectoryAtPath:documentsDirectory error:nil];

    for (int i = 0; i < dirContents.count; i++) {
        NSString *name  = [dirContents objectAtIndex:i];
        if (![name isEqualToString:@".DS_Store"]) {
            filename = name;
            break;
        }

    }

    NSString *_writableDBPath = [documentsDirectory stringByAppendingPathComponent:filename];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager fileExistsAtPath:_writableDBPath];

    if(!success)
    {
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:filename];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:_writableDBPath error:nil];
    }

    int ret = sqlite3_open([_writableDBPath UTF8String], &_sharedDatabase);
    NSAssert1(ret == SQLITE_OK, @"Could not open database. '%s'", sqlite3_errmsg(_sharedDatabase));
    return _sharedDatabase;
}

+ (void) deleteEditableCopy:(NSString*)filepath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager fileExistsAtPath:filepath];
    NSError *error;
    if(success)
    {
        [fileManager removeItemAtPath:filepath error:&error];
    }
}

+ (void) copyplist
{
    NSLog(@"Entered dbhandler copyplist: To check events plist is available or not");
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filename = @"events.plist";
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *_writableDBPath = [documentsDirectory stringByAppendingPathComponent:filename];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager fileExistsAtPath:_writableDBPath];
    if(!success)
    {
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:filename];

        success = [fileManager copyItemAtPath:defaultDBPath toPath:_writableDBPath error:nil];
        NSMutableArray *plist = [[NSMutableArray alloc] init];
        [NSKeyedArchiver archiveRootObject:plist toFile:_writableDBPath];
            NSLog(@"Entered dbhandler copyplist: copied events plist");
    }
        NSLog(@"Ended dbhandler copyplist: To check events plist is available or not");
}

+ (void)setDataBaseToNil
{
    _sharedDatabase = nil;
}

@end


text:
angular.module('dashboard')

  .directive('jvmMetricsView', function () {
    'use strict';

    return {
      restrict: 'E',
      templateUrl: 'views/jvm/jvm_metrics_view.html',
      scope: {
        samplingConfig: '=',
        queryMetricsFnRef: '&'
      },
      controller: ['$scope', '$filter', '$propertyTableBuilder', 'helper',
        function ($scope, $filter, $ptb, helper) {
          'use strict';

          var sc = $scope.samplingConfig;
          var recentChartPoints = sc.retainRecentDataSeconds * 1000 / sc.retainRecentDataIntervalMs;
          var histChartPoints = sc.retainHistoryDataHours * 3600 * 1000 / sc.retainHistoryDataIntervalMs;

          // property table part
          var converter = {
            bytes: function (value) {
              return {raw: value, unit: 'B', readable: true};
            },
            direct: function (value) {
              return value;
            }
          };
          var metricsClassProps = {
            'memory.total.max': ['Memory Total', converter.bytes],
            'memory.total.committed': ['Memory Committed', converter.bytes],
            'memory.total.used': ['Memory Used', converter.bytes],
            'thread.count': ['Total Thread Count', converter.direct],
            'thread.daemon.count': ['Daemon Thread Count', converter.direct]
          };

          $scope.jvmMetricsTable = _.map(metricsClassProps, function (prop) {
            var text = prop[0];
            var convertFn = prop[1];
            return $ptb.number(text).value(convertFn(0)).done();
          });

          function updateMetricsTable(metrics) {
            var updates = {};
            var i = 0;
            angular.forEach(metricsClassProps, function (prop, name) {
              if (metrics.hasOwnProperty(name)) {
                var convertFn = prop[1];
                updates[i] = convertFn(metrics[name].value);
              }
              i++;
            });
            $ptb.$update($scope.jvmMetricsTable, updates);
          }

          // metrics charts part
          $scope.isShowingCurrentMetrics = true;

          function rebuildChartsOnPeriodChanged() {
            var all = !$scope.isShowingCurrentMetrics;
            queryMetricsFn(all).then(function (metrics) {
              var dataPoints = makeMemoryUsageChartData(metrics);
              var visibleDataPointsNum = all ?
                Math.max(dataPoints.length, histChartPoints) : recentChartPoints;
              if (all && dataPoints.length < 2) {
                // Hide chart data, if there is only one data point there, which looks very ugly.
                visibleDataPointsNum = 0;
                dataPoints = [];
              }
              // Rebuild the chart
              $scope.memoryUsageChart = createMemoryUsageChart(visibleDataPointsNum, dataPoints);
            });
          }

          var queryMetricsFn = $scope.queryMetricsFnRef();
          queryMetricsFn(/*all=*/false).then(function (metrics0) {
            $scope.metrics = metrics0.$data();
            $scope.$watch('isShowingCurrentMetrics', function (newVal, oldVal) {
              if (angular.equals(newVal, oldVal)) {
                return; // ignore initial notification
              }
              rebuildChartsOnPeriodChanged();
            });
            metrics0.$subscribe($scope, function (metrics) {
              $scope.metrics = metrics;
            });
          });

          $scope.$watch('metrics', function (metrics) {
            if (angular.isObject(metrics)) {
              updateMetricsTable(_.mapValues(metrics, _.last));
              if ($scope.isShowingCurrentMetrics) {
                updateRecentMetricsCharts(metrics);
              }
            }
          });

          function updateRecentMetricsCharts(metrics) {
            $scope.memoryUsageChart.data = makeMemoryUsageChartData(metrics);
          }

          function makeMemoryUsageChartData(metrics) {
            return _.map(metrics['memory.total.used'], function (metric) {
              return {
                x: helper.timeToChartTimeLabel(metric.time, /*shortForm=*/$scope.isShowingCurrentMetrics),
                y: [metric.value]
              };
            });
          }

          function createLineChartOptions(seriesNames, visibleDataPointsNum, dataPoints) {
            return {
              height: '168px',
              margin: {right: 15},
              seriesNames: seriesNames,
              visibleDataPointsNum: visibleDataPointsNum,
              data: dataPoints,
              yAxisLabelFormatter: helper.yAxisLabelFormatterWithoutValue0('B'), // MB, GB, TB, etc.
              valueFormatter: function (value) {
                return $filter('number')(Math.floor(value / (1024 * 1024)), 0) + ' MB';
              }
            };
          }

          function createMemoryUsageChart(visibleDataPointsNum, dataPoints) {
            return {
              options: createLineChartOptions(['Memory Used'], visibleDataPointsNum, dataPoints),
              data: null
            };
          }

          $scope.memoryUsageChart = createMemoryUsageChart(recentChartPoints);
        }]
    }
  })
;


text:
using System;
using NUnit.Framework;
using OpenQA.Selenium;

namespace first_project
{
   /* [TestFixture]
    public class WhenSelectItemRightPageIsOpenedTest : TestBase
    {
        [Test]
        public void IpemsPageOpensCorrectlyTest()
        {
            OpenHomePage();
            IWebElement itemLink = Driver.FindElement(By.CssSelector("div#box-campaigns div.content ul li:first-child a:not([class^=fancybox])"));

            string itemName = itemLink.FindElement(By.CssSelector("div.name")).Text;

            IWebElement regularPrice = itemLink.FindElement(By.CssSelector("s.regular-price"));
            IWebElement campaignPrice = itemLink.FindElement(By.CssSelector("strong.campaign-price"));

            CheckPricesStyles(regularPrice, campaignPrice, "rgba(119, 119, 119, 1)");

            string regularPriceText = regularPrice.Text;
            string campaignPriceText = campaignPrice.Text;

            itemLink.Click();

            IWebElement regularPriceItem =
                Driver.FindElement(By.CssSelector("div.content div.information div.price-wrapper s.regular-price"));
            IWebElement campaignPriceItem =
                Driver.FindElement(By.CssSelector("div.content div.information div.price-wrapper strong.campaign-price"));

            CheckPricesStyles(regularPriceItem, campaignPriceItem, "rgba(102, 102, 102, 1)");

            Assert.AreEqual(itemName, Driver.FindElement(By.CssSelector("div#box-product h1.title")).Text, "Name doesn't match");
            Assert.AreEqual(regularPriceText, regularPriceItem.Text, "Regular price doesn't match");
            Assert.AreEqual(campaignPriceText, campaignPriceItem.Text, "Campaign price doesn't match");
        }

        private void CheckPricesStyles(IWebElement regPrice, IWebElement campPrice, string color)
        {
            Assert.AreEqual(color, regPrice.GetCssValue("color"), "Color doesn't match");
            Assert.AreEqual("line-through", regPrice.GetCssValue("text-decoration"), "Text-decoration doesn't match");
            Assert.AreEqual("rgba(204, 0, 0, 1)", campPrice.GetCssValue("color"), "Color doesn't match");
            Assert.AreEqual("bold", campPrice.GetCssValue("font-weight"), "Font-weight doesn't match");

            String regFontSize = regPrice.GetCssValue("font-size");
            regFontSize = regFontSize.Remove(regFontSize.IndexOf('p')).Replace(".", ",");

            String campFontSize = campPrice.GetCssValue("font-size");
            campFontSize = campFontSize.Remove(campFontSize.IndexOf('p')).Replace(".", ",");

            Assert.IsTrue(Convert.ToDouble(regFontSize)< Convert.ToDouble(campFontSize), "Font sizes are wrong");
        }
    }*/
}


text:
package org.apache.eagle.alert.coordinator.impl;

import org.apache.eagle.alert.coordination.model.*;
import org.apache.eagle.alert.coordination.model.internal.MonitoredStream;
import org.apache.eagle.alert.coordination.model.internal.PolicyAssignment;
import org.apache.eagle.alert.coordination.model.internal.StreamWorkSlotQueue;
import org.apache.eagle.alert.coordination.model.internal.Topology;
import org.apache.eagle.alert.coordinator.IScheduleContext;
import org.apache.eagle.alert.coordinator.model.AlertBoltUsage;
import org.apache.eagle.alert.coordinator.model.TopologyUsage;
import org.apache.eagle.alert.engine.coordinator.PolicyDefinition;
import org.apache.eagle.alert.engine.coordinator.Publishment;
import org.apache.eagle.alert.engine.coordinator.StreamDefinition;
import org.apache.eagle.alert.engine.coordinator.StreamPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Given current policy placement, figure out monitor metadata
 *
TODO: refactor to eliminate the duplicate of stupid if-notInMap-then-create....
 * FIXME: too many duplicated code logic : check null; add list to map; add to list..

 *
 * @since Apr 26, 2016
 */
public class MonitorMetadataGenerator {

    private static final Logger LOG = LoggerFactory.getLogger(MonitorMetadataGenerator.class);

    private IScheduleContext context;

    public MonitorMetadataGenerator(IScheduleContext context) {
        this.context = context;
    }

    public ScheduleState generate(List<WorkItem> expandworkSets) {
        // topologyId -> SpoutSpec
        Map<String, SpoutSpec> topoSpoutSpecsMap = generateSpoutMonitorMetadata();

        // grp-by meta spec(sort & grp)
        Map<String, RouterSpec> groupSpecsMap = generateGroupbyMonitorMetadata();

        // alert bolt spec
        Map<String, AlertBoltSpec> alertSpecsMap = generateAlertMonitorMetadata();

        Map<String, PublishSpec> publishSpecsMap = generatePublishMetadata();

        String uniqueVersion = generateVersion();
        ScheduleState status = new ScheduleState(uniqueVersion,
            topoSpoutSpecsMap,
            groupSpecsMap,
            alertSpecsMap,
            publishSpecsMap,
            context.getPolicyAssignments().values(),
            context.getMonitoredStreams().values(),
            context.getPolicies().values(),
            context.getStreamSchemas().values());
        return status;
    }

    private Map<String, PublishSpec> generatePublishMetadata() {
        Map<String, PublishSpec> pubSpecs = new HashMap<String, PublishSpec>();
        // prebuild policy to publishment map
        Map<String, List<Publishment>> policyToPub = new HashMap<String, List<Publishment>>();
        for (Publishment pub : context.getPublishments().values()) {
            for (String policyId : pub.getPolicyIds()) {
                List<Publishment> policyPubs = policyToPub.get(policyId);
                if (policyPubs == null) {
                    policyPubs = new ArrayList<>();
                    policyToPub.put(policyId, policyPubs);
                }
                policyPubs.add(pub);
            }
        }

        // build per topology
        for (TopologyUsage u : context.getTopologyUsages().values()) {
            PublishSpec pubSpec = pubSpecs.get(u.getTopoName());
            if (pubSpec == null) {
                pubSpec = new PublishSpec(u.getTopoName(), context.getTopologies().get(u.getTopoName()).getPubBoltId());
                pubSpecs.put(u.getTopoName(), pubSpec);
            }

            for (String p : u.getPolicies()) {
                PolicyDefinition definition = context.getPolicies().get(p);
                if (definition == null) {
                    continue;
                }
                if (policyToPub.containsKey(p)) {
                    for (Publishment pub : policyToPub.get(p)) {
                        pubSpec.addPublishment(pub);
                    }
                }
            }
        }
        return pubSpecs;
    }

    /**
     * FIXME: add auto-increment version number?.
     */
    private String generateVersion() {
        return "spec_version_" + System.currentTimeMillis();
    }

    private Map<String, AlertBoltSpec> generateAlertMonitorMetadata() {
        Map<String, AlertBoltSpec> alertSpecs = new HashMap<String, AlertBoltSpec>();
        for (TopologyUsage u : context.getTopologyUsages().values()) {
            AlertBoltSpec alertSpec = alertSpecs.get(u.getTopoName());
            if (alertSpec == null) {
                alertSpec = new AlertBoltSpec(u.getTopoName());
                alertSpecs.put(u.getTopoName(), alertSpec);
            }
            for (AlertBoltUsage boltUsage : u.getAlertUsages().values()) {
                for (String policyName : boltUsage.getPolicies()) {
                    PolicyDefinition definition = context.getPolicies().get(policyName);
                    alertSpec.addBoltPolicy(boltUsage.getBoltId(), definition.getName());

                    for (Publishment publish : context.getPublishments().values()) {
                        if (!publish.getPolicyIds().contains(definition.getName())) {
                            continue;
                        }

                        List<String> streamIds = new ArrayList<>();
                        // add the publish to the bolt
                        if (publish.getStreamIds() == null || publish.getStreamIds().size() <= 0) {
                            streamIds.add(Publishment.STREAM_NAME_DEFAULT);
                        } else {
                            streamIds.addAll(publish.getStreamIds());
                        }
                        for (String streamId : streamIds) {
                            alertSpec.addPublishPartition(streamId, policyName, publish.getName(), publish.getPartitionColumns());
                        }
                    }
                }
            }
        }
        return alertSpecs;
    }

    private Map<String, RouterSpec> generateGroupbyMonitorMetadata() {
        Map<String, RouterSpec> groupSpecsMap = new HashMap<String, RouterSpec>();
        for (TopologyUsage u : context.getTopologyUsages().values()) {
            RouterSpec spec = groupSpecsMap.get(u.getTopoName());
            if (spec == null) {
                spec = new RouterSpec(u.getTopoName());
                groupSpecsMap.put(u.getTopoName(), spec);
            }

            for (MonitoredStream ms : u.getMonitoredStream()) {
                // mutiple stream on the same policy group : for correlation group case:
                for (StreamPartition partiton : ms.getStreamGroup().getStreamPartitions()) {
                    StreamRouterSpec routeSpec = new StreamRouterSpec();
                    routeSpec.setPartition(partiton);
                    routeSpec.setStreamId(partiton.getStreamId());

                    for (StreamWorkSlotQueue sq : ms.getQueues()) {
                        if (sq.getTopoGroupStartIndex().containsKey(u.getTopoName())) {
                            PolicyWorkerQueue queue = new PolicyWorkerQueue();
                            queue.setWorkers(sq.getWorkingSlots());
                            queue.setPartition(partiton);
                            routeSpec.addQueue(queue);
                        }
                    }

                    spec.addRouterSpec(routeSpec);
                }
            }
        }

        return groupSpecsMap;
    }

    private Map<String, SpoutSpec> generateSpoutMonitorMetadata() {
        Map<String, StreamWorkSlotQueue> queueMap = buildQueueMap();

        Map<String, SpoutSpec> topoSpoutSpecsMap = new HashMap<String, SpoutSpec>();
        // streamName -> StreamDefinition
        Map<String, StreamDefinition> streamSchemaMap = context.getStreamSchemas();
        Map<String, Kafka2TupleMetadata> datasourcesMap = context.getDataSourceMetadata();
        for (TopologyUsage usage : context.getTopologyUsages().values()) {
            Topology topo = context.getTopologies().get(usage.getTopoName());

            // based on data source schemas
            // generate topic -> Kafka2TupleMetadata
            // generate topic -> Tuple2StreamMetadata (actually the schema selector)
            Map<String, Kafka2TupleMetadata> dss = new HashMap<String, Kafka2TupleMetadata>();
            Map<String, Tuple2StreamMetadata> tss = new HashMap<String, Tuple2StreamMetadata>();
            for (String dataSourceId : usage.getDataSources()) {
                Kafka2TupleMetadata ds = datasourcesMap.get(dataSourceId);
                dss.put(ds.getTopic(), ds);
                tss.put(ds.getTopic(), ds.getCodec());
            }

            // generate topicId -> StreamRepartitionMetadata
            Map<String, List<StreamRepartitionMetadata>> streamsMap = new HashMap<String, List<StreamRepartitionMetadata>>();
            for (String policyName : usage.getPolicies()) {
                PolicyDefinition def = context.getPolicies().get(policyName);

                PolicyAssignment assignment = context.getPolicyAssignments().get(policyName);
                if (assignment == null) {
                    LOG.error(" can not find assignment for policy {} ! ", policyName);
                    continue;
                }

                for (StreamPartition policyStreamPartition : def.getPartitionSpec()) {
                    String stream = policyStreamPartition.getStreamId();
                    StreamDefinition schema = streamSchemaMap.get(stream);
                    String topic = datasourcesMap.get(schema.getDataSource()).getTopic();

                    // add stream name to tuple metadata
                    if (tss.containsKey(topic)) {
                        Tuple2StreamMetadata tupleMetadata = tss.get(topic);
                        tupleMetadata.getActiveStreamNames().add(stream);
                    }

                    // grouping strategy
                    StreamRepartitionStrategy gs = new StreamRepartitionStrategy();
                    gs.partition = policyStreamPartition;
                    gs.numTotalParticipatingRouterBolts = queueMap.get(assignment.getQueueId()).getNumberOfGroupBolts();
                    gs.startSequence = queueMap.get(assignment.getQueueId()).getTopologyGroupStartIndex(topo.getName());
                    gs.totalTargetBoltIds = new ArrayList<String>(topo.getGroupNodeIds());

                    // add to map
                    addGroupingStrategy(streamsMap, stream, schema, topic, schema.getDataSource(), gs);
                }
            }

            SpoutSpec spoutSpec = new SpoutSpec(topo.getName(), streamsMap, tss, dss);
            topoSpoutSpecsMap.put(topo.getName(), spoutSpec);
        }
        return topoSpoutSpecsMap;
    }

    /**
     * Work queue not a root level object, thus we need to build a map from
     * MonitoredStream for later quick lookup.
     */
    private Map<String, StreamWorkSlotQueue> buildQueueMap() {
        Map<String, StreamWorkSlotQueue> queueMap = new HashMap<String, StreamWorkSlotQueue>();
        for (MonitoredStream ms : context.getMonitoredStreams().values()) {
            for (StreamWorkSlotQueue queue : ms.getQueues()) {
                queueMap.put(queue.getQueueId(), queue);
            }
        }
        return queueMap;
    }

    private void addGroupingStrategy(Map<String, List<StreamRepartitionMetadata>> streamsMap, String stream,
                                     StreamDefinition schema, String topicName, String datasourceName, StreamRepartitionStrategy gs) {
        List<StreamRepartitionMetadata> dsStreamMeta;
        if (streamsMap.containsKey(topicName)) {
            dsStreamMeta = streamsMap.get(topicName);
        } else {
            dsStreamMeta = new ArrayList<StreamRepartitionMetadata>();
            streamsMap.put(topicName, dsStreamMeta);
        }
        StreamRepartitionMetadata targetSm = null;
        for (StreamRepartitionMetadata sm : dsStreamMeta) {
            if (stream.equalsIgnoreCase(sm.getStreamId())) {
                targetSm = sm;
                break;
            }
        }
        if (targetSm == null) {
            targetSm = new StreamRepartitionMetadata(topicName, schema.getStreamId());
            dsStreamMeta.add(targetSm);
        }
        if (!targetSm.groupingStrategies.contains(gs)) {
            targetSm.addGroupStrategy(gs);
        }
    }

}


text:
//-CRE-

using Glass.Mapper.Sc.IoC;
using IDependencyResolver = Glass.Mapper.IoC.IDependencyResolver;

namespace Glass.Mapper.Sc.FakeDb
{
    public static class Utilities
    {
        public static IDependencyResolver CreateStandardResolver(Config config =null)
        {
            if (config == null)
                config = new Config();

            var resolver = new DependencyResolver(config);
            return resolver;
        }
    }
}


text:
// Copyright 2018 Matthias Schwarz
// License: MIT

/*
    Functions to open output streams, initialize and clear
    the linked list and add items to the linked list.
*/

#include "amp.h"

/*
    Adds an item to the linked list, or creates the list, if it doesn't exist.
*/
int list_add(FILE *file, int index)
{
    struct stream *item = (struct stream*)malloc(sizeof(struct stream));

    if (item == NULL)
    {
        log_error("Failed to allocate memory for stream.\n");

        return 1;
    }

    item->file = file;
    item->next = NULL;
    item->index = index;
    item->state = 0;

    if (head == NULL)
    {
        // Initialize linked list
        head = item;
        tail = item;
    }
    else
    {
        // Add item to linked list
        tail->next = item;
        tail = item;
    }

    return 0;
}

/*
    Clears the linked list and frees all allocated memory.
*/
void list_clear()
{
    struct stream *item = head;

    while (item != NULL)
    {
        if (item->file != NULL)
        {
            fclose(item->file);
            item->file = NULL;
        }

        free(item);

        item = item->next;
    }
}

/*
    Tries to open all streams up to last_fd for writing and adds them to the list.
*/
int open_streams()
{
    FILE *file = NULL;
    int fd = 0;
    int added = 0;
    int streams = 0;

    // First, add stdout, if desired
    if (args.ign_stdout == 0)
    {
        added = list_add(stdout, 1);

        if (added != 0)
        {
            log_error("Failed to add stdout to list.\n");
        }

        streams++;
    }

    // Cycle through file descriptors upto last_fd
    for (fd = MIN_FD; fd <= args.last_fd; fd++)
    {
        // Try to open the file descriptor
        file = fdopen(fd, "wb");

        if (file == NULL)
        {
            // Failed to open stream. Try next...
            continue;
        }

        added = list_add(file, fd);

        if (added != 0)
        {
            log_error("Failed to add stream %d to list.\n", fd);

            continue;
        }

        streams++;
    }

    return streams;
}


text:
package org.unidal.cat.spi.report;

import java.util.List;

import junit.framework.Assert;

import org.junit.Test;
import org.unidal.cat.spi.Report;
import org.unidal.cat.spi.ReportPeriod;
import org.unidal.lookup.ComponentTestCase;
import org.unidal.lookup.LookupException;

public class ReportReducerManagerTest extends ComponentTestCase {
	@Test(expected = LookupException.class)
	public void testMissing() throws Exception {
		ReportReducerManager manager = lookup(ReportReducerManager.class);

		manager.getReducer("mock", "mock");
	}

	@Test
	public void testNormal() throws Exception {
		defineComponent(ReportReducer.class, "mock:mock", MockReportReducer.class);

		ReportReducerManager manager = lookup(ReportReducerManager.class);
		ReportReducer<Report> reducer = manager.getReducer("mock", "mock");
		ReportReducer<Report> reducer2 = manager.getReducer("mock", "mock");

		Assert.assertEquals("mock", reducer.getReportName());
		Assert.assertEquals("mock", reducer.getId());
		Assert.assertSame(reducer, reducer2);
	}

	public static class MockReportReducer implements ReportReducer<Report> {
		@Override
		public String getId() {
			return "mock";
		}

		@Override
		public String getReportName() {
			return "mock";
		}

		@Override
		public ReportPeriod getPeriod() {
			throw new UnsupportedOperationException();
		}

		@Override
		public Report reduce(List<Report> reports) {
			throw new UnsupportedOperationException();
		}
	}
}


text:
extern crate bootstrap;

use std::env;

use bootstrap::{Config, Build};

fn main() {
    let args = env::args().skip(1).collect::<Vec<_>>();
    let config = Config::parse(&args);
    Build::new(config).build();
}


text:
package org.apache.ode.axis2.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.activation.DataHandler;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.receivers.AbstractMessageReceiver;
import org.apache.axis2.util.Utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.axis2.OdeFault;
import org.apache.ode.axis2.deploy.DeploymentPoller;
import org.apache.ode.axis2.hooks.ODEAxisService;
import org.apache.ode.bpel.iapi.BpelServer;
import org.apache.ode.bpel.iapi.ProcessConf;
import org.apache.ode.bpel.iapi.ProcessStore;
import org.apache.ode.il.OMUtils;
import org.apache.ode.utils.fs.FileUtils;

/**
 * Axis wrapper for process deployment.
 */
public class DeploymentWebService {

    private static final Log __log = LogFactory.getLog(DeploymentWebService.class);

    private final OMNamespace _pmapi;

    private File _deployPath;
    private DeploymentPoller _poller;
    private ProcessStore _store;

    public DeploymentWebService() {
        _pmapi = OMAbstractFactory.getOMFactory().createOMNamespace("http://www.apache.org/ode/pmapi","pmapi");
    }

    public void enableService(AxisConfiguration axisConfig, BpelServer server, ProcessStore store,
                              DeploymentPoller poller, String rootpath, String workPath) {
        _deployPath = new File(workPath, "processes");
        _store = store;

        Definition def;
        try {
            WSDLReader wsdlReader = WSDLFactory.newInstance().newWSDLReader();
            wsdlReader.setFeature("javax.wsdl.verbose", false);

            File wsdlFile = new File(rootpath + "/deploy.wsdl");
            def = wsdlReader.readWSDL(wsdlFile.toURI().toString());
            AxisService deployService = ODEAxisService.createService(
                    axisConfig, new QName("http://www.apache.org/ode/deployapi", "DeploymentService"),
                    "DeploymentPort", "DeploymentService", def, new DeploymentMessageReceiver());
            axisConfig.addService(deployService);
            _poller = poller;
        } catch (WSDLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class DeploymentMessageReceiver extends AbstractMessageReceiver {

        public void invokeBusinessLogic(MessageContext messageContext) throws AxisFault {
            String operation = messageContext.getAxisOperation().getName().getLocalPart();
            SOAPFactory factory = getSOAPFactory(messageContext);
            boolean unknown = false;

            try {
                if (operation.equals("deploy")) {
                    OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
                    OMElement zipPart = (OMElement) namePart.getNextOMSibling();
                    OMElement zip = (zipPart == null) ? null : zipPart.getFirstElement();
                    if (zip == null || !zipPart.getQName().getLocalPart().equals("package")
                            || !zip.getQName().getLocalPart().equals("zip"))
                        throw new OdeFault("Your message should contain an element named 'package' with a 'zip' element");

                    OMText binaryNode = (OMText) zip.getFirstOMChild();
                    if (binaryNode == null) {
                        throw new OdeFault("Empty binary node under <zip> element");
                    }
                    binaryNode.setOptimize(true);
                    try {
                        // We're going to create a directory under the deployment root and put
                        // files in there. The poller shouldn't pick them up so we're asking
                        // it to hold on for a while.
                        _poller.hold();

                        File dest = new File(_deployPath, namePart.getText() + "-" + _store.getCurrentVersion());
                        dest.mkdir();
                        unzip(dest, (DataHandler) binaryNode.getDataHandler());

                        // Check that we have a deploy.xml
                        File deployXml = new File(dest, "deploy.xml");
                        if (!deployXml.exists())
                            throw new OdeFault("The deployment doesn't appear to contain a deployment " +
                                    "descriptor in its root directory named deploy.xml, aborting.");

                        Collection<QName> deployed = _store.deploy(dest);

                        File deployedMarker = new File(_deployPath, dest.getName() + ".deployed");
                        deployedMarker.createNewFile();

                        // Telling the poller what we deployed so that it doesn't try to deploy it again
                        _poller.markAsDeployed(dest);
                        __log.info("Deployment of artifact " + dest.getName() + " successful.");

                        OMElement response = factory.createOMElement("response", null);

                        if (__log.isDebugEnabled()) __log.debug("Deployed package: "+dest.getName());
                        OMElement d = factory.createOMElement("name", null);
                        d.setText(dest.getName());
                        response.addChild(d);

                        for (QName pid : deployed) {
                            if (__log.isDebugEnabled()) __log.debug("Deployed PID: "+pid);
                            d = factory.createOMElement("id", null);
                            d.setText(pid);
                            response.addChild(d);
                        }
                        sendResponse(factory, messageContext, "deployResponse", response);
                    } finally {
                        _poller.release();
                    }
                } else if (operation.equals("undeploy")) {
                    OMElement part = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();

                    String pkg = part.getText();
                    File deploymentDir = new File(_deployPath, pkg);
                    if (!deploymentDir.exists())
                        throw new OdeFault("Couldn't find deployment package " + pkg + " in directory " + _deployPath);

                    try {
                        // We're going to create a directory under the deployment root and put
                        // files in there. The poller shouldn't pick them up so we're asking
                        // it to hold on for a while.
                        _poller.hold();

                        Collection<QName> undeployed = _store.undeploy(deploymentDir);

                        File deployedMarker = new File(_deployPath, pkg + ".deployed");
                        deployedMarker.delete();
                        FileUtils.deepDelete(new File(_deployPath, pkg));

                        OMElement response = factory.createOMElement("response", null);
                        response.setText("" + (undeployed.size() > 0));
                        sendResponse(factory, messageContext, "undeployResponse", response);
                        _poller.markAsUndeployed(deploymentDir);
                    } finally {
                        _poller.release();
                    }
                } else if (operation.equals("listDeployedPackages")) {
                    Collection<String> packageNames = _store.getPackages();
                    OMElement response = factory.createOMElement("deployedPackages", null);
                    for (String name : packageNames) {
                        OMElement nameElmt = factory.createOMElement(new QName( "http://www.apache.org/ode/deployapi","name"));
                        nameElmt.setText(name);
                        response.addChild(nameElmt);
                    }
                    sendResponse(factory, messageContext, "listDeployedPackagesResponse", response);
                } else if (operation.equals("listProcesses")) {
                    OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
                    List<QName> processIds = _store.listProcesses(namePart.getText());
                    OMElement response = factory.createOMElement("processIds", null);
                    for (QName qname : processIds) {
                        OMElement nameElmt = factory.createOMElement("id", null);
                        nameElmt.setText(qname);
                        response.addChild(nameElmt);
                    }
                    sendResponse(factory, messageContext, "listProcessResponse", response);
                } else if (operation.equals("getProcessPackage")) {
                    OMElement qnamePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
                    ProcessConf process = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart));
                    if (process == null) {
                        throw new OdeFault("Could not find process: " + qnamePart.getTextAsQName());
                    }
                    String packageName = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart)).getPackage();
                    OMElement response = factory.createOMElement("packageName", null);
                    response.setText(packageName);
                    sendResponse(factory, messageContext, "getProcessPackageResponse", response);
                } else unknown = true;
            } catch (Throwable t) {
                // Trying to extract a meaningful message
                Throwable source = t;
                while (source.getCause() != null && source.getCause() != source) source = source.getCause();
                __log.warn("Invocation of operation " + operation + " failed", t);
                throw new OdeFault("Invocation of operation " + operation + " failed: " + source.toString(), t);
            }
            if (unknown) throw new OdeFault("Unknown operation: '"
                    + messageContext.getAxisOperation().getName() + "'");
        }

        private File buildUnusedDir(File deployPath, String dirName) {
            int v = 1;
            while (new File(deployPath, dirName + "-" + v).exists()) v++;
            return new File(deployPath, dirName + "-" + v);
        }

        private void unzip(File dest, DataHandler dataHandler) throws AxisFault {
            try {
                ZipInputStream zis = new ZipInputStream(dataHandler.getDataSource().getInputStream());
                ZipEntry entry;
                // Processing the package
                while((entry = zis.getNextEntry()) != null) {
                    if(entry.isDirectory()) {
                        __log.debug("Extracting directory: " + entry.getName());
                        new File(dest, entry.getName()).mkdir();
                        continue;
                    }
                    __log.debug("Extracting file: " + entry.getName());
                    File destFile = new File(dest, entry.getName());
                    if (!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs();
                    copyInputStream(zis, new BufferedOutputStream(
                            new FileOutputStream(destFile)));
                }
                zis.close();
            } catch (IOException e) {
                throw new OdeFault("An error occured on deployment.", e);
            }
        }

        private void sendResponse(SOAPFactory factory, MessageContext messageContext, String op,
                                  OMElement response) throws AxisFault {
            MessageContext outMsgContext = Utils.createOutMessageContext(messageContext);
            outMsgContext.getOperationContext().addMessageContext(outMsgContext);

            SOAPEnvelope envelope = factory.getDefaultEnvelope();
            outMsgContext.setEnvelope(envelope);

            OMElement responseOp = factory.createOMElement(op, _pmapi);
            responseOp.addChild(response);
            envelope.getBody().addChild(responseOp);
            AxisEngine.send(outMsgContext);
        }
    }

    private static void copyInputStream(InputStream in, OutputStream out)
            throws IOException {
        byte[] buffer = new byte[1024];
        int len;
        while((len = in.read(buffer)) >= 0)
            out.write(buffer, 0, len);
        out.close();
    }

}


text:
package com.google.gdata.data.youtube;

import com.google.gdata.data.BaseFeed;
import com.google.gdata.data.ExtensionProfile;
import com.google.gdata.data.Kind;
import com.google.gdata.data.batch.BatchUtils;

/**
 * A feed of {@link CaptionTrackEntry}
 *
 *
 */
@Kind.Term(YouTubeNamespace.KIND_CAPTION_TRACK)
public class CaptionTrackFeed
    extends BaseFeed<CaptionTrackFeed, CaptionTrackEntry>{

  public CaptionTrackFeed() {
    super(CaptionTrackEntry.class);
    EntryUtils.setKind(this, YouTubeNamespace.KIND_CAPTION_TRACK);
  }

  public CaptionTrackFeed(BaseFeed<?, ?> base) {
    super(CaptionTrackEntry.class, base);
    EntryUtils.setKind(this, YouTubeNamespace.KIND_CAPTION_TRACK);
  }

  @Override
  public void declareExtensions(ExtensionProfile extProfile) {
    super.declareExtensions(extProfile);
    BatchUtils.declareExtensions(extProfile);
  }
}


text:
Count the frequency of letters in texts using parallel computation.

Parallelism is about doing things in parallel that can also be done
sequentially. A common example is counting the frequency of letters.
Create a function that returns the total frequency of each letter in a
list of texts and that employs parallelism.

# Java Tips

Single-threaded (non-concurrent) solutions can pass all tests [but the last.](https://www.youtube.com/watch?v=mJZZNHekEQw)  Your solution will be tested for concurrency by submitting it as a [Runnable](https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html) to an [ExecutorService.](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html) Your solution must leverage multiple [Threads](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html) to pass the final test.

Java documentation on [parallel streams](https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html) may provide some help.

As a stretch goal, consider if your implementation will work for characters with [diacritics or accents](https://en.wikipedia.org/wiki/Diacritic). For example, such solutions should not consider e and ë the same character. An example text for this case is [Wilhelmus](https://en.wikipedia.org/wiki/Wilhelmus), the Dutch national anthem.

# Running the tests

You can run all the tests for an exercise by entering

```sh
$ gradle test
```

in your terminal.

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.