text:
(function() {
  'use strict';

  function digestMarkup(scope, compile, markup) {
    var element = angular.element(markup);
    compile(element)(scope);

    scope.$apply();
    return element;
  }

  describe('hzDynamicTable directive', function () {
    var $scope, $compile, $qExtensions, markup;

    beforeEach(module('templates'));
    beforeEach(module('smart-table'));
    beforeEach(module('horizon.framework'));

    beforeEach(inject(function ($injector) {
      $compile = $injector.get('$compile');
      $scope = $injector.get('$rootScope').$new();
      $qExtensions = $injector.get('horizon.framework.util.q.extensions');

      $scope.config = {
        selectAll: true,
        expand: true,
        trackId: 'id',
        columns: [
          {id: 'animal', title: 'Animal', priority: 1},
          {id: 'type', title: 'Type', priority: 2},
          {id: 'diet', title: 'Diet', priority: 1, sortDefault: true}
        ]
      };

      $scope.safeTableData = [
        { id: '1', animal: 'cat', type: 'mammal', diet: 'fish', domestic: true },
        { id: '2', animal: 'snake', type: 'reptile', diet: 'mice', domestic: false },
        { id: '3', animal: 'sparrow', type: 'bird', diet: 'worms', domestic: false }
      ];

      markup =
        '<hz-dynamic-table config="config" items="safeTableData">' +
        '</hz-dynamic-table>';
    }));

    it('has the correct number of column headers', function() {
      var $element = digestMarkup($scope, $compile, markup);
      expect($element).toBeDefined();
      expect($element.find('thead tr:eq(0) th').length).toBe(5);
    });

    it('displays selectAll checkbox when config selectAll set to True', function() {
      var $element = digestMarkup($scope, $compile, markup);
      expect($element.find('thead tr:eq(0) th:first input').attr(
        'hz-select-all')).toBe('items');
    });

    it('does not display selectAll checkbox when config selectAll set to False', function() {
      $scope.config = {
        selectAll: false,
        expand: true,
        trackId: 'id',
        columns: [
          {id: 'animal', title: 'Animal', priority: 1},
          {id: 'type', title: 'Type', priority: 2},
          {id: 'diet', title: 'Diet', priority: 1, sortDefault: true}
        ]
      };
      var $element = digestMarkup($scope, $compile, markup);
      expect($element.find('thead tr:eq(0) th:first').hasClass('ng-hide')).toBe(true);
    });

    it('displays expander when config expand set to True', function() {
      var $element = digestMarkup($scope, $compile, markup);
      expect($element.find('thead tr:eq(0) th:eq(1)').hasClass('expander')).toBe(true);
    });

    it('does not display expander when config expand set to False', function() {
      $scope.config = {
        selectAll: true,
        expand: false,
        trackId: 'id',
        columns: [
          {id: 'animal', title: 'Animal', priority: 1},
          {id: 'type', title: 'Type', priority: 2},
          {id: 'diet', title: 'Diet', priority: 1, sortDefault: true}
        ]
      };
      var $element = digestMarkup($scope, $compile, markup);
      expect($element.find('thead tr:eq(0) th:eq(1)').hasClass('ng-hide')).toBe(true);
    });

    it('has the correct responsive priority classes', function() {
      var $element = digestMarkup($scope, $compile, markup);
      expect($element.find('tbody tr').length).toBe(7);
      expect($element.find('tbody tr:eq(0) td').length).toBe(5);
      expect($element.find('tbody tr:eq(2) td:eq(2)').hasClass('rsp-p1')).toBe(true);
      expect($element.find('tbody tr:eq(2) td:eq(3)').hasClass('rsp-p2')).toBe(true);
      expect($element.find('tbody tr:eq(2) td:eq(4)').hasClass('rsp-p1')).toBe(true);
    });

    it('has the correct number of rows (including detail rows and no items row)', function() {
      var $element = digestMarkup($scope, $compile, markup);
      expect($element.find('tbody tr').length).toBe(7);
      expect($element.find('tbody tr:eq(0) td').length).toBe(5);
      expect($element.find('tbody tr:eq(2) td:eq(2)').text()).toContain('snake');
      expect($element.find('tbody tr:eq(2) td:eq(3)').text()).toContain('reptile');
      expect($element.find('tbody tr:eq(2) td:eq(4)').text()).toContain('mice');
    });

    it('displays the default no items message if noItemsMessage is not set', function() {
      $scope.safeTableData = [];
      var $element = digestMarkup($scope, $compile, markup);
      expect($element.find('tbody td.no-rows-help').text()).toBe('No items to display.');
    });

    it('displays a custom no items message if noItemsMessage is provided', function() {
      $scope.safeTableData = [];
      $scope.config.noItemsMessage = 'A sample message';
      var $element = digestMarkup($scope, $compile, markup);
      expect($element.find('tbody td.no-rows-help').text()).toBe('A sample message');
    });

    it('has no search or action buttons if none configured', function() {
      var $element = digestMarkup($scope, $compile, markup);
      expect($element.find('.hz-dynamic-table-preamble').length).toBe(1);
      expect($element.find('.hz-dynamic-table-preamble').text().trim()).toBe('');
    });

    describe('search & action button preamble', function () {
      beforeEach(function () {
        $scope.filterFacets = [{label: 'Name', name: 'name'}];
        $scope.batchActions = [
          {
            id: 'action',
            service: {
              allowed: function () {
                return $qExtensions.booleanAsPromise(false);
              }
            },
            template: {type: 'create'}
          }
        ];
        markup =
          '<hz-dynamic-table config="config" items="safeTableData" ' +
          'filter-facets="filterFacets" batch-actions="batchActions">' +
          '</hz-dynamic-table>';
      });
    });

    describe('hzDetailRow directive', function() {

      it('compiles default detail row template', function() {
        var $element = digestMarkup($scope, $compile, markup);
        expect($element.find('tbody tr:eq(3) dt').text()).toContain('Animal');
        expect($element.find('tbody tr:eq(3) dd').text()).toContain('snake');
        expect($element.find('tbody tr:eq(3) dt').text()).toContain('Type');
        expect($element.find('tbody tr:eq(3) dd').text()).toContain('reptile');
        expect($element.find('tbody tr:eq(3) dt').text()).toContain('Diet');
        expect($element.find('tbody tr:eq(3) dd').text()).toContain('mice');
      });
    });

    describe('hzCell directive', function() {

      it('compiles template passed in from column configuration', function() {
        $scope.config = {
          selectAll: true,
          expand: false,
          trackId: 'id',
          columns: [
            {id: 'animal', title: 'Animal', classes: 'rsp-p1'},
            {id: 'type', title: 'Type', classes: 'rsp-p2',
              template: '{$ item.type $}'},
            {id: 'diet', title: 'Diet', classes: 'rsp-p1', sortDefault: true}
          ]
        };
        var $element = digestMarkup($scope, $compile, markup);
        expect($element.find('tbody tr:eq(2) td:eq(3) span').hasClass('fa fa-bolt')).toBe(true);
        expect($element.find('tbody tr:eq(2) td:eq(3) span').text()).toBe('bird');
      });

      it('properly filters the cell content given the filter name', function() {
        $scope.config = {
          selectAll: true,
          expand: false,
          trackId: 'id',
          columns: [
            {id: 'animal', title: 'Animal', priority: 1},
            {id: 'type', title: 'Type', priority: 2,
              template: '{$ item.type $}'},
            {id: 'diet', title: 'Diet', priority: 1, sortDefault: true},
            {id: 'domestic', title: 'Domestic', priority: 2, filters: ['yesno']}
          ]
        };
        var $element = digestMarkup($scope, $compile, markup);
        expect($element.find('tbody tr:eq(0) td:eq(5)').text()).toContain('Yes');
        expect($element.find('tbody tr:eq(1) td:eq(5)').text()).toContain('No');
        expect($element.find('tbody tr:eq(2) td:eq(5)').text()).toContain('No');
      });

      it('properly filters the cell content given a filter function', function() {
        function ishFunc(input) {
          return input.concat('-ish');
        }

        $scope.config = {
          selectAll: true,
          expand: false,
          trackId: 'id',
          columns: [
            {id: 'animal', title: 'Animal', priority: 1},
            {id: 'type', title: 'Type', priority: 2, filters: [ishFunc]},
            {id: 'diet', title: 'Diet', priority: 1, sortDefault: true},
            {id: 'domestic', title: 'Domestic', priority: 2}
          ]
        };
        var $element = digestMarkup($scope, $compile, markup);
        expect($element.find('tbody tr:eq(0) td:eq(3)').text()).toContain('mammal-ish');
        expect($element.find('tbody tr:eq(1) td:eq(3)').text()).toContain('reptile-ish');
        expect($element.find('tbody tr:eq(2) td:eq(3)').text()).toContain('bird-ish');
      });

      it('properly maps the cell content given a mapping', function() {

        $scope.config = {
          selectAll: true,
          expand: false,
          trackId: 'id',
          columns: [
            {id: 'animal', title: 'Animal', priority: 1,
              values: {
                cat: "Catamount",
                snake: "Serpent",
                sparrow: "CAPTAIN Jack Sparrow"
              }
            },
            {id: 'type', title: 'Type', priority: 2},
            {id: 'diet', title: 'Diet', priority: 1, sortDefault: true},
            {id: 'domestic', title: 'Domestic', priority: 2}
          ]
        };
        var $element = digestMarkup($scope, $compile, markup);
        expect($element.find('tbody tr:eq(0) td:eq(2)').text()).toContain('Catamount');
        expect($element.find('tbody tr:eq(1) td:eq(2)').text()).toContain('Serpent');
        expect($element.find('tbody tr:eq(2) td:eq(2)').text()).toContain('CAPTAIN Jack Sparrow');
      });

      it('properly adds a link with urlFunction', function() {
        $scope.config = {
          selectAll: true,
          expand: false,
          trackId: 'id',
          columns: [
            {id: 'animal', title: 'Animal', priority: 1,
              urlFunction: myFunction
            },
            {id: 'type', title: 'Type', priority: 2},
            {id: 'diet', title: 'Diet', priority: 1, sortDefault: true},
            {id: 'domestic', title: 'Domestic', priority: 2}
          ]
        };
        var $element = digestMarkup($scope, $compile, markup);
        expect($element.find('tbody tr:eq(0) td:eq(2) a').attr('href')).toBe('/here/cat');
        expect($element.find('tbody tr:eq(1) td:eq(2) a').attr('href')).toBe('/here/snake');
        expect($element.find('tbody tr:eq(2) td:eq(2) a').attr('href')).toBe('/here/sparrow');
        function myFunction(item) {
          return '/here/' + item.animal;
        }
      });
    });

  });
}());


text:
@class Session;

// This represents a web element accessible via :session/element/X where X is an
// opaque ID assigned by the server when the element is first located on the
// page.
@interface Element : HTTPVirtualDirectory {
 @private
  // The opaque ID assigned by the server.
  NSString* elementId_;
  Session* session_;
}

@property (nonatomic, readonly, copy) NSString *elementId;
@property (nonatomic, readonly, retain) Session *session;

// Designated initializer. Don't call this directly - instead
// use |elementWithId|.
- (id)initWithId:(NSString*)elementId
      andSession:(Session*)session;

// Create a new element.
+ (Element*)elementWithId:(NSString*)elementId
               andSession:(Session*)session;

// Get the JSON dictionary with this element's ID for transmission
// over the wire: |{"ELEMENT": "elementId"}|.
- (NSDictionary *)idDictionary;

// Locates the first element under this element that matches the given |query|.
// The |query| must have two keys:
// @li "using" - The locator strategy to use.
// @li "value" - The value to search for using the strategy.
// Returns the JSON representation of the located element.
-(NSDictionary*) findElement:(NSDictionary*)query;

// Locates every element on under this element matching the given |query|.
// The |query| must have two keys:
// @li "using" - The locator strategy to use.
// @li "value" - The value to search for using the strategy.
// Returns an array of elements in their JSON representation.
-(NSArray*) findElements:(NSDictionary*)query;

// Simulate a click on the element.
// Dictionary parameters are passed in by REST service, but are redundant
// with directory ID and are thus ignored.
- (void)click:(NSDictionary*)ignored;

// Clear the contents of this input field.
// Dictionary parameters are passed in by REST service, but are redundant
// with directory ID and are thus ignored.
- (void)clear:(NSDictionary*)ignored;

// Submit this form, or the form containing this element.
// Dictionary parameters are passed in by REST service, but are redundant
// with directory ID and are thus ignored.
- (void)submit:(NSDictionary*)ignored;

// The text contained in the element.
- (NSString *)text;

// Type these keys into the element.
// Dictionary parameters are passed in by REST service, but are redundant
// with directory ID and are thus ignored.
- (void)sendKeys:(NSDictionary *)dict;

// Is the element checked?
// This method is only valid on checkboxes and radio buttons.
- (NSNumber *)isChecked;

// Set the element's checked property.
// This method is only valid on checkboxes and radio buttons.
- (void)setChecked:(NSDictionary*)ignored;

// Toggle the element's checked property.
// This method is only valid on checkboxes and radio buttons.
// Dictionary parameters are passed in by REST service, but are redundant
// with directory ID and are thus ignored.
- (void)toggleSelected;

// Is the element enabled?
- (NSNumber *)isEnabled;

// Is the element displayed on the screen?
- (NSNumber *)isDisplayed;

// Get the attribute with the given name.
- (id)attribute:(NSString *)attributeName;

// Get the effective CSS property with the given name.
- (NSString*)css:(NSString*)property;

// Get the tag name of this element, not the value of the name attribute:
// will return "input" for the element <input name="foo">
- (NSString *)name;

@end

// Directory acts as a bridge, creating subdirectories on demand to handle
// requests to /session/:id/element/:elementId/equals/:other.
@interface ElementComparatorBridge : HTTPVirtualDirectory {
 @private
  Element* element_;
}

@property (nonatomic, readonly, retain) Element* element;

+ (ElementComparatorBridge*) comparatorBridgeFor:(Element*)element;
- (id) initFor:(Element*)element;

@end

// Temporary directory that handles element equality comparisons.
@interface ElementComparator : HTTPVirtualDirectory {
 @private
  ElementComparatorBridge* parentDirectory_;
  NSDictionary* otherElementId_;
}

- (id) initFor:(ElementComparatorBridge*)parentDirectory
   compareWith:(NSDictionary*)otherElementId;

- (id) compareElements;

@end

redpajama_set_name: RedPajamaGithub


text:
namespace arc {

namespace {

// Used for converting RawIconPngData to ImageSkia.
constexpr size_t kBytesPerPixel = 4;  // BGRA
constexpr size_t kSmallIconSizeInDip = 16;
constexpr size_t kMaxIconSizeInPx = 200;

}  // namespace

ArcIntentHelperMojoAsh::ArcIntentHelperMojoAsh() = default;
ArcIntentHelperMojoAsh::~ArcIntentHelperMojoAsh() = default;

bool ArcIntentHelperMojoAsh::IsArcAvailable() {
  auto* arc_service_manager = ArcServiceManager::Get();
  return arc_service_manager && arc_service_manager->arc_bridge_service()
                                    ->intent_helper()
                                    ->IsConnected();
}

bool ArcIntentHelperMojoAsh::IsRequestUrlHandlerListAvailable() {
  auto* arc_service_manager = ArcServiceManager::Get();
  arc::mojom::IntentHelperInstance* instance = nullptr;

  if (arc_service_manager) {
    instance = ARC_GET_INSTANCE_FOR_METHOD(
        arc_service_manager->arc_bridge_service()->intent_helper(),
        RequestUrlHandlerList);
  }
  return instance;
}

bool ArcIntentHelperMojoAsh::IsRequestTextSelectionActionsAvailable() {
  auto* arc_service_manager = ArcServiceManager::Get();
  arc::mojom::IntentHelperInstance* instance = nullptr;

  if (arc_service_manager) {
    instance = ARC_GET_INSTANCE_FOR_METHOD(
        arc_service_manager->arc_bridge_service()->intent_helper(),
        RequestTextSelectionActions);
  }
  return instance;
}

bool ArcIntentHelperMojoAsh::RequestUrlHandlerList(
    const std::string& url,
    RequestUrlHandlerListCallback callback) {
  auto* arc_service_manager = ArcServiceManager::Get();
  arc::mojom::IntentHelperInstance* instance = nullptr;

  if (arc_service_manager) {
    instance = ARC_GET_INSTANCE_FOR_METHOD(
        arc_service_manager->arc_bridge_service()->intent_helper(),
        RequestUrlHandlerList);
  }
  if (!instance) {
    LOG(ERROR) << "Failed to get instance for RequestUrlHandlerList().";
    std::move(callback).Run(std::vector<IntentHandlerInfo>());
    return false;
  }

  instance->RequestUrlHandlerList(
      url, base::BindOnce(&ArcIntentHelperMojoAsh::OnRequestUrlHandlerList,
                          weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  return true;
}

void ArcIntentHelperMojoAsh::OnRequestUrlHandlerList(
    RequestUrlHandlerListCallback callback,
    std::vector<mojom::IntentHandlerInfoPtr> handlers) {
  std::vector<IntentHandlerInfo> converted_handlers;
  for (auto const& handler : handlers) {
    converted_handlers.push_back(IntentHandlerInfo(
        handler->name, handler->package_name, handler->activity_name,
        handler->is_preferred, handler->fallback_url));
  }
  std::move(callback).Run(std::move(converted_handlers));
}

bool ArcIntentHelperMojoAsh::RequestTextSelectionActions(
    const std::string& text,
    ui::ResourceScaleFactor scale_factor,
    RequestTextSelectionActionsCallback callback) {
  auto* arc_service_manager = ArcServiceManager::Get();
  arc::mojom::IntentHelperInstance* instance = nullptr;

  if (arc_service_manager) {
    instance = ARC_GET_INSTANCE_FOR_METHOD(
        arc_service_manager->arc_bridge_service()->intent_helper(),
        RequestTextSelectionActions);
  }
  if (!instance) {
    LOG(ERROR) << "Failed to get instance for RequestTextSelectionActions().";
    std::move(callback).Run(std::vector<TextSelectionAction>());
    return false;
  }

  instance->RequestTextSelectionActions(
      text, mojom::ScaleFactor(scale_factor),
      base::BindOnce(&ArcIntentHelperMojoAsh::OnRequestTextSelectionActions,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  return true;
}

void ArcIntentHelperMojoAsh::OnRequestTextSelectionActions(
    RequestTextSelectionActionsCallback callback,
    std::vector<mojom::TextSelectionActionPtr> actions) {
  size_t actions_count = actions.size();
  auto converted_actions = std::vector<TextSelectionAction*>(actions_count);
  TextSelectionAction** converted_actions_ptr = &converted_actions[0];
  base::RepeatingClosure barrier_closure = base::BarrierClosure(
      actions_count, base::BindOnce(
                         [](std::vector<TextSelectionAction*> actions,
                            RequestTextSelectionActionsCallback cb) {
                           std::vector<TextSelectionAction> actions_value;
                           for (auto* const action : actions) {
                             actions_value.push_back(std::move(*action));
                             // Delete each action explicitly to avoid a memory
                             // leak.
                             delete action;
                           }
                           std::move(cb).Run(std::move(actions_value));
                         },
                         std::move(converted_actions), std::move(callback)));

  for (size_t idx = 0; idx < actions_count; ++idx) {
    auto action = std::move(actions[idx]);
    TextSelectionAction** converted_action = &converted_actions_ptr[idx];

    // If action->icon doesn't meet the size condition, skip generating image.
    if (action->icon->width > kMaxIconSizeInPx ||
        action->icon->height > kMaxIconSizeInPx || action->icon->width == 0 ||
        action->icon->height == 0 ||
        action->icon->icon.size() !=
            (action->icon->width * action->icon->height * kBytesPerPixel)) {
      ConvertTextSelectionAction(converted_action, std::move(action),
                                 barrier_closure, gfx::ImageSkia());
      continue;
    }

    auto icon_png_data = std::move(action->icon->icon_png_data);
    apps::ArcRawIconPngDataToImageSkia(
        std::move(icon_png_data), kSmallIconSizeInDip,
        base::BindOnce(&ArcIntentHelperMojoAsh::ConvertTextSelectionAction,
                       weak_ptr_factory_.GetWeakPtr(), converted_action,
                       std::move(action), barrier_closure));
  }
}

void ArcIntentHelperMojoAsh::ConvertTextSelectionAction(
    TextSelectionAction** converted_action,
    mojom::TextSelectionActionPtr action,
    base::OnceClosure callback,
    const gfx::ImageSkia& image) {
  // Convert actions to crosapi::mojom::TextSelectionActionPtr from
  // arc::mojom::TextSelectionActionPtr and ImageSkia icon.

  // Generate app_id by looking up ArcAppListPrefs.
  Profile* profile = ArcSessionManager::Get()->profile();
  std::string app_id = ArcAppListPrefs::Get(profile)->GetAppIdByPackageName(
      action->activity->package_name);

  // The memory for this value is released at the barrier closure in
  // OnRequestTextSelectionAction() by explicitly deleting it.
  *converted_action = new TextSelectionAction(
      std::move(app_id), image,
      ActivityName(
          std::move(action->activity->package_name),
          std::move(action->activity->activity_name.value_or(std::string()))),
      std::move(action->title),
      IntentInfo(std::move(action->action_intent->action),
                 std::move(action->action_intent->categories),
                 std::move(action->action_intent->data),
                 std::move(action->action_intent->type),
                 action->action_intent->ui_bypassed,
                 std::move(action->action_intent->extras)));

  std::move(callback).Run();
}

bool ArcIntentHelperMojoAsh::HandleUrl(const std::string& url,
                                       const std::string& package_name) {
  auto* arc_service_manager = ArcServiceManager::Get();
  arc::mojom::IntentHelperInstance* instance = nullptr;

  if (arc_service_manager) {
    instance = ARC_GET_INSTANCE_FOR_METHOD(
        arc_service_manager->arc_bridge_service()->intent_helper(), HandleUrl);
  }
  if (!instance) {
    LOG(ERROR) << "Failed to get instance for HandleUrl().";
    return false;
  }

  instance->HandleUrl(url, package_name);
  return true;
}

bool ArcIntentHelperMojoAsh::HandleIntent(const IntentInfo& intent,
                                          const ActivityName& activity) {
  auto* arc_service_manager = ArcServiceManager::Get();
  arc::mojom::IntentHelperInstance* instance = nullptr;

  if (arc_service_manager) {
    instance = ARC_GET_INSTANCE_FOR_METHOD(
        arc_service_manager->arc_bridge_service()->intent_helper(),
        HandleIntent);
  }
  if (!instance) {
    LOG(ERROR) << "Failed to get instance for HandleIntent().";
    return false;
  }

  mojom::IntentInfoPtr converted_intent = mojom::IntentInfo::New();
  converted_intent->action = intent.action;
  converted_intent->categories = intent.categories;
  converted_intent->data = intent.data;
  converted_intent->type = intent.type;
  converted_intent->ui_bypassed = intent.ui_bypassed;
  converted_intent->extras = intent.extras;
  instance->HandleIntent(
      std::move(converted_intent),
      mojom::ActivityName::New(activity.package_name, activity.activity_name));
  return true;
}

bool ArcIntentHelperMojoAsh::AddPreferredPackage(
    const std::string& package_name) {
  auto* arc_service_manager = ArcServiceManager::Get();
  arc::mojom::IntentHelperInstance* instance = nullptr;

  if (arc_service_manager) {
    instance = ARC_GET_INSTANCE_FOR_METHOD(
        arc_service_manager->arc_bridge_service()->intent_helper(),
        AddPreferredPackage);
  }
  if (!instance) {
    LOG(ERROR) << "Failed to get instance for AddPreferedPackage().";
    return false;
  }

  instance->AddPreferredPackage(package_name);
  return true;
}

}  // namespace arc


text:
	ENGINE_VERSION_STRINGIFY(ENGINE_MAJOR_VERSION) \
	ENGINE_VERSION_TEXT(".") \
	ENGINE_VERSION_STRINGIFY(ENGINE_MINOR_VERSION) \
	ENGINE_VERSION_TEXT(".") \
	ENGINE_VERSION_STRINGIFY(ENGINE_PATCH_VERSION) \
	ENGINE_VERSION_TEXT("-") \
	ENGINE_VERSION_STRINGIFY(BUILT_FROM_CHANGELIST) \
	ENGINE_VERSION_TEXT("+") \
	ENGINE_VERSION_TEXT(BRANCH_NAME)


text:
Object.defineProperty(exports, '__esModule', {
  value: true,
});

exports.default = require('../lib/processors/makeStyles').default;


text:
<?php

namespace Hip\User\Event;

use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use \Hip\AppBundle\Entity;

/**
 * Class User
 * @package Hip\User\Event
 */
class UserEvent
{
    private $eventDispatcher;

    public function __construct(TraceableEventDispatcher $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * @param Entity\User $user
     * @param Request $request
     * @return null|Response
     */
    public function registrationInitialise(Entity\User $user, Request $request)
    {
        $event = new GetResponseUserEvent($user, $request);
        $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

        return $event->getResponse();
    }
}


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

namespace StatMaster.Data.Park.Progression
{
    class ProgressionCountDataValues
    {
        public List<uint> guestsCount = new List<uint>();
        public List<uint> employeesCount = new List<uint>();
        public List<uint> attractionsCount = new List<uint>();
        public List<uint> shopsCount = new List<uint>();
    }

    class ProgressionCountData : ProgressionData
    {

        public ProgressionCountData(string parkGuid, int sessionIdx)
        {
            dataVersionIdx = 1;
            minDataVersionIdx = 1;
            setSubFolder("park_" + parkGuid + "/session_" + sessionIdx);
            addHandle("progression_counts");
        }

        public override void addRange(Settings settings)
        {
            base.addRange(settings);
            rangeObjects.Add(new ProgressionCountDataValues());
        }

        public override void updateRange()
        {
            base.updateRange();
            ProgressionCountDataValues values = (ProgressionCountDataValues)rangeObjects[ranges.Count - 1];
            values.guestsCount.Add(Convert.ToUInt32(GameController.Instance.park.getGuests().Count));
            values.employeesCount.Add(Convert.ToUInt32(GameController.Instance.park.getEmployees().Count));
            values.attractionsCount.Add(Convert.ToUInt32(GameController.Instance.park.getAttractions().Count));
            values.shopsCount.Add(Convert.ToUInt32(GameController.Instance.park.getShops().Count));
        }

        protected override Dictionary<string, string> getValuesDict(int idx)
        {
            Dictionary<string, string> obj = new Dictionary<string, string>();

            ProgressionCountDataValues values = (ProgressionCountDataValues)rangeObjects[idx];

            obj.Add("guestsCount", Json.Serialize(values.guestsCount));
            obj.Add("employeesCount", Json.Serialize(values.employeesCount));
            obj.Add("attractionsCount", Json.Serialize(values.attractionsCount));
            obj.Add("shopsCount", Json.Serialize(values.shopsCount));

            return obj;
        }

        protected override bool addValueObj(object obj)
        {
            rangeObjects.Add((ProgressionCountDataValues)obj);
            return true;
        }
    }
}


text:
const path = require('path');
const assert = require('assert');

module.exports = {
	description: 'plugins can manipulate the options object',
	options: {
		plugins: [
			{
				options(options) {
					options.input = path.resolve(__dirname, 'answer.js');
				}
			}
		]
	},
	exports(answer) {
		assert.equal(answer, 42);
	}
};


text:
'use strict';
import React, {Component} from 'react';
import {connect} from 'react-redux';

const teams = require('../../data/teams');

import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableHighlight,
  Picker,
  Item
} from 'react-native';

import teamContainer from '../containers/teamContainer';
import userContainer from '../containers/userContainer';
import Login from './Login';
import Team from './Team';
import Dimensions from 'Dimensions';

const apiEndpoint = 'http://localhost:3001/';

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedTeam: 1610612739,
      updating: null
    };
  }

  fetchTeamDashboard() {
    this.setState({updating: true});
    const {mapTeamToStore} = this.props;
    fetch(apiEndpoint + this.state.selectedTeam)
      .then(response => response.text())
      .then(responseText => {
        mapTeamToStore(JSON.parse(responseText));
        this.setState({updating: false});
      })
      .catch(err => console.log('Error fetching team: ', err));
  }

  render() {
    const {user} = this.props;
    if (user) {
      return (
        <View style={styles.container}>
          <Image style={styles.logo} source={require('../MJlogowhitebackground.jpeg')}/>
          <Text style={styles.text}>Select a team:</Text>
          <Picker
            selectedValue={this.state.selectedTeam}
            onValueChange={(team) => {
            this.setState({selectedTeam: team});
          }}>
            {teams
              .map(function (team, i) {
                return <Picker.Item label={team.teamName} value={team.teamId} key={i}/>
              })}
          </Picker>
          <TouchableHighlight
            style={styles.submitButton}
            underlayColor='#949494'
            onPress={() => {
            this.fetchTeamDashboard();
            this.props.navigator.push({component: Team, title: "Show charts"});
          }}>
            <Text>Submit</Text>
          </TouchableHighlight>
        </View>
      )
    } else {
      return (<Login/>)
    }
  }
}

export default userContainer(teamContainer(Home));

const styles = StyleSheet.create({
  submitButton: {
    height: 50,
    alignSelf: 'stretch',
    backgroundColor: '#D9DADF',
    margin: 15,
    borderRadius: 5,
    justifyContent: 'center',
    alignItems: 'center'
  },
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#fff'
  },
  text: {
    textAlign: 'center',
    fontSize: 24,
    fontWeight: '100'
  },
  logo: {
    width: Dimensions
      .get('window')
      .width,
    resizeMode: Image.resizeMode.contain,
    marginBottom: -75
  }
});


text:
A portal to help citizens lobby their government for bills introduced by Senator Bernie Sanders

## Dependencies

- node.js
- browserify globally installed
- minify gloablly installed
- clean-css globally installed

## Project setup

### OS X, Linux, & Bash on Windows

`npm install` to install dependency packages

`./build.sh` to run the build toolchain.  the toolchain bundles dependencies into `js/bundle.js`, combines json bill datasets, and minifies bundled javascript source.

## Deployment

`./deploy.sh` to create a distribution `dist` folder, and push the distribution to the `origin/gh-pages` branch


text:
Example Themes
==============

Deploy Themes
-------------

You can either deploy the themes by copying to the themes folder or as modules.

### Copy

Simplest way to deploy the themes is to copy `src/main/resources/theme/*` to `standalone/configuration/themes/`.

### Module

Alternatively you can deploy as modules. This can be done by first running:

    mvn clean install
    $KEYCLOAK_HOME/bin/jboss-cli.sh --command="module add --name=org.keycloak.example.themes --resources=target/keycloak-example-themes.jar"

Then open $KEYCLOAK_HOME/standalone/configuration/keycloak-server.json and register the theme module by adding:

    "theme": {
        "module": {
            "modules": [ "org.keycloak.example.themes" ]
        }
    }

Sunrise Login Theme
-------------------

Example login theme that changes the look of the login forms. To enable the theme open the admin console, select your realm, click on `Theme`. In the dropdown for `Login Theme` select `sunrise`. Click `Save` and login to the realm to see the new theme in action.

Change Logo Theme
-----------------

To enable the theme open the admin console, select your realm, click on `Theme`. In the dropdowns for `Login Theme`, `Account Theme` and `Admin Console Theme` select `logo-example`. Click `Save` and login to the realm to see the new theme in action.

To change the theme for the welcome pages open `standalone/configuration/keycloak-server.json` find the config for `theme` and add 'welcomeTheme':

    "theme": {
        ...
        "welcomeTheme": "logo-example"
    },

One thing to note is that to change the admin console for the master admin console (`/auth/admin`) you need to change the theme for the master realm. Changing the admin console theme for any other realms will only change the admin console for that specific realm (for example `/auth/admin/myrealm/console`).


text:
/**
 * generated by Xtext
 */
package br.ufpe.cin.generator;

import br.ufpe.cin.generator.Event;
import br.ufpe.cin.generator.MachineDeclared;
import br.ufpe.cin.tupi.EventsDecl;
import br.ufpe.cin.tupi.Guard;
import br.ufpe.cin.tupi.MachineBody;
import br.ufpe.cin.tupi.MachineDecl;
import br.ufpe.cin.tupi.Model;
import br.ufpe.cin.tupi.State;
import br.ufpe.cin.tupi.StateDecl;
import br.ufpe.cin.tupi.Transition;
import br.ufpe.cin.tupi.Type;
import com.google.common.base.Objects;
import java.util.HashMap;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.common.types.JvmTypeReference;
import org.eclipse.xtext.generator.IFileSystemAccess;
import org.eclipse.xtext.generator.IGenerator;
import org.eclipse.xtext.xbase.lib.IterableExtensions;

/**
 * Generates code from your model files on save.
 *
 * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#code-generation
 */
@SuppressWarnings("all")
public class TupiGenerator implements IGenerator {
  private HashMap<String, MachineDeclared> mapMachine = new HashMap<String, MachineDeclared>();

  private MachineDeclared machineMapped = null;

  private Event eventAux = null;

  @Override
  public void doGenerate(final Resource resource, final IFileSystemAccess fsa) {
    EList<EObject> _contents = resource.getContents();
    EObject _head = IterableExtensions.<EObject>head(_contents);
    this.createFiles(((Model) _head), fsa);
    this.mapMachine.clear();
  }

  public void createFiles(final Model model, final IFileSystemAccess fsa) {
    EList<MachineDecl> _machines = model.getMachines();
    for (final MachineDecl machine : _machines) {
      String _name = machine.getName();
      String _plus = (_name + ".dot");
      CharSequence _dotCode = this.toDotCode(machine);
      fsa.generateFile(_plus, _dotCode);
    }
  }

  public String className(final Resource res) {
    URI _uRI = res.getURI();
    String name = _uRI.lastSegment();
    int _indexOf = name.indexOf(".");
    return name.substring(0, _indexOf);
  }

  public CharSequence toDotCode(final MachineDecl machine) {
    StringConcatenation _builder = new StringConcatenation();
    CharSequence _declareMachine = this.declareMachine(machine);
    _builder.append(_declareMachine, "");
    _builder.newLineIfNotEmpty();
    return _builder;
  }

  public CharSequence declareMachine(final MachineDecl machine) {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("digraph ");
    String _name = machine.getName();
    _builder.append(_name, "");
    _builder.append(" {");
    _builder.newLineIfNotEmpty();
    _builder.append("\t");
    _builder.append("rankdir=LR;");
    _builder.newLine();
    _builder.append("\t");
    String _name_1 = machine.getName();
    MachineDeclared _machineDeclared = new MachineDeclared();
    MachineDeclared _put = this.mapMachine.put(_name_1, this.machineMapped = _machineDeclared);
    _builder.append(_put, "\t");
    _builder.newLineIfNotEmpty();
    {
      Type _superType = machine.getSuperType();
      boolean _notEquals = (!Objects.equal(_superType, null));
      if (_notEquals) {
        _builder.append("\t");
        Type _superType_1 = machine.getSuperType();
        JvmTypeReference _typeRef = _superType_1.getTypeRef();
        MachineDeclared _get = this.mapMachine.get(_typeRef);
        this.machineMapped.heritage(_get);
        _builder.newLineIfNotEmpty();
      }
    }
    _builder.append("\t");
    MachineBody _body = machine.getBody();
    this.createClass(_body);
    _builder.newLineIfNotEmpty();
    _builder.append("\t");
    MachineBody _body_1 = machine.getBody();
    CharSequence _declareBody = this.declareBody(_body_1);
    _builder.append(_declareBody, "\t");
    _builder.newLineIfNotEmpty();
    _builder.append("}");
    _builder.newLine();
    return _builder;
  }

  public void createClass(final MachineBody body) {
    StateDecl _statesDecl = body.getStatesDecl();
    EList<State> _states = _statesDecl.getStates();
    for (final State state : _states) {
      String _name = state.getName();
      boolean _contains = this.machineMapped.states.contains(_name);
      boolean _not = (!_contains);
      if (_not) {
        String _name_1 = state.getName();
        this.machineMapped.states.add(_name_1);
      }
    }
    EventsDecl _eventsDecl = body.getEventsDecl();
    EList<br.ufpe.cin.tupi.Event> _events = _eventsDecl.getEvents();
    for (final br.ufpe.cin.tupi.Event event : _events) {
      {
        for (final Event eventComp : this.machineMapped.events) {
          String _name_2 = event.getName();
          boolean _equals = eventComp.name.equals(_name_2);
          if (_equals) {
            this.machineMapped.events.remove(eventComp);
          }
        }
        String _name_3 = event.getName();
        Event _event = new Event(_name_3);
        this.machineMapped.events.add(this.eventAux = _event);
        EList<Transition> _transitions = event.getTransitions();
        for (final Transition trans : _transitions) {
          EList<String> _originStates = trans.getOriginStates();
          for (final String originState : _originStates) {
            {
              final String regex = originState.replace("*", ".*");
              for (final String state_1 : this.machineMapped.states) {
                boolean _matches = state_1.matches(regex);
                if (_matches) {
                  State _destState = trans.getDestState();
                  String _name_4 = _destState.getName();
                  Guard _guard = trans.getGuard();
                  String _name_5 = _guard.getName();
                  br.ufpe.cin.generator.Transition _transition = new br.ufpe.cin.generator.Transition(state_1, _name_4, _name_5);
                  this.eventAux.trans.add(_transition);
                }
              }
            }
          }
        }
      }
    }
  }

  public CharSequence declareBody(final MachineBody body) {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("//states");
    _builder.newLine();
    {
      for(final String state : this.machineMapped.states) {
        _builder.append(state, "");
        _builder.append(";");
        _builder.newLineIfNotEmpty();
      }
    }
    _builder.append("//edges");
    _builder.newLine();
    {
      for(final Event event : this.machineMapped.events) {
        {
          for(final br.ufpe.cin.generator.Transition tran : event.trans) {
            _builder.append(tran.originState, "");
            _builder.append("->");
            _builder.append(tran.destState, "");
            _builder.append(" [label=\"");
            _builder.append(event.name, "");
            _builder.append(" | ");
            _builder.append(tran.guard, "");
            _builder.append("\"]; ");
            _builder.newLineIfNotEmpty();
          }
        }
      }
    }
    return _builder;
  }
}


text:
import numpy
import time
from shogun import MSG_DEBUG

numpy.random.seed(17)
traindat = numpy.random.random_sample((10,10))
testdat = numpy.random.random_sample((10,10))
parameter_list=[[traindat,testdat,1.2],[traindat,testdat,1.4]]

def distance_director_euclidean (fm_train_real=traindat,fm_test_real=testdat,scale=1.2):
	try:
		from shogun import DirectorDistance
	except ImportError:
		print("recompile shogun with --enable-swig-directors")
		return
	import shogun as sg

	class DirectorEuclideanDistance(DirectorDistance):
		def __init__(self):
			DirectorDistance.__init__(self, True)
		def distance_function(self, idx_a, idx_b):
			seq1 = self.get_lhs().get_feature_vector(idx_a)
			seq2 = self.get_rhs().get_feature_vector(idx_b)
			return numpy.linalg.norm(seq1-seq2)

	feats_train=sg.create_features(fm_train_real)
	#feats_train.io.set_loglevel(MSG_DEBUG)
	feats_train.get_global_parallel().set_num_threads(1)
	feats_test=sg.create_features(fm_test_real)

	distance=sg.create_distance("EuclideanDistance")
	distance.init(feats_train, feats_test)

	ddistance=DirectorEuclideanDistance()
	ddistance.init(feats_train, feats_test)

	#print  "dm_train"
	t=time.perf_counter()
	dm_train=distance.get_distance_matrix()
	t1=time.perf_counter() - t

	#print  "ddm_train"
	t=time.perf_counter()
	ddm_train=ddistance.get_distance_matrix()
	t2=time.perf_counter() - t

	#print "dm_train", dm_train
	#print "ddm_train", ddm_train

	return dm_train, ddm_train

if __name__=='__main__':
	print('DirectorEuclideanDistance')
	distance_director_euclidean(*parameter_list[0])


text:
@interface ZenTableViewCell : UITableViewCell
@property(weak, nonatomic) IBOutlet UILabel *titleLabel;

@end


text:
static LAFAutoImporter *sharedPlugin;

@interface LAFAutoImporter()
@property (nonatomic, strong) NSBundle *bundle;
@end

@implementation LAFAutoImporter

static OSStatus lafHotKeyHandler(EventHandlerCallRef nextHandler, EventRef anEvent, void *userData) {

    EventHotKeyID lafRef;
    GetEventParameter(anEvent,kEventParamDirectObject,typeEventHotKeyID,NULL,sizeof(lafRef),NULL,&lafRef);
    switch (lafRef.id) {
        case 1:
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LAFShowHeaders" object:nil];
        }
        break;

    }
    return noErr;
}

+ (void)pluginDidLoad:(NSBundle *)plugin
{
    static dispatch_once_t onceToken;
    NSString *currentApplicationName = [[NSBundle mainBundle] infoDictionary][@"CFBundleName"];
    if ([currentApplicationName isEqual:@"Xcode"]) {
        dispatch_once(&onceToken, ^{
            sharedPlugin = [[self alloc] initWithBundle:plugin];
        });
    }
}

- (id)initWithBundle:(NSBundle *)plugin
{
    if (self = [super init]) {
        // init inspector
        [LAFIDENotificationHandler sharedHandler];

        // reference to plugin's bundle, for resource acccess
        self.bundle = plugin;

        [self loadKeyboardHandler];
    }
    return self;
}

- (void)loadKeyboardHandler {
    EventHotKeyRef lafHotKeyRef;
    EventHotKeyID lafHotKeyID;
    EventTypeSpec eventType;

    eventType.eventClass=kEventClassKeyboard;
    eventType.eventKind=kEventHotKeyPressed;
    InstallApplicationEventHandler(&lafHotKeyHandler,1,&eventType,NULL,NULL);

    lafHotKeyID.signature='lak1';
    lafHotKeyID.id=1;

    RegisterEventHotKey(kVK_ANSI_H, cmdKey+controlKey, lafHotKeyID, GetApplicationEventTarget(), 0, &lafHotKeyRef);
}

@end


text:
/** \file     TComCABACTables.h
    \brief    static class for CABAC tables
*/

#ifndef __TCOMCABACTABLES__
#define __TCOMCABACTABLES__

#include "TLibCommon/CommonDef.h"
#include "TLibCommon/TComRom.h"

//! \ingroup TLibCommon
//! \{

/**
 * \brief static class for CABAC tables
 */

class TComCABACTables
{
public:
  const static UChar  sm_aucLPSTable[1 << CONTEXT_STATE_BITS][4];
  const static UChar  sm_aucRenormTable[32];
};

//! \}

#endif


text:
$(document).ready(function () {

    $('#sections')
        .sortable({
            items: '.sortable',
            update: function (event, ui) {
                $('#sections li').each(function (i) {
                    section_order($(this), i);
                });
            }
        });

    $('.section_save').on('click', function () {
        section_save($(this));
    });

    $('.section_delete').on('click', function () {
        section_delete($(this));
    });

    $('.dm-item').on('click', function () {
        show_section($(this));
    });

    $('.dm-section-type a.dropdown-item').on('click', function () {
        section_type($(this));
    });

    $('[data-toggle="tooltip"]').tooltip();

});

/**
 * Section type selector in button
 * @param obj
 */
function section_type(obj) {
    var section_type = obj.html();
    var id = obj.parent().parent().parent().parent().data('id');
    var type_button = obj.parent().parent().find('.dm-section-type-top');

    $.ajax({
        type: 'POST',
        data: {
            submit: 'submit',
            mode: 'type',
            section_type: section_type,
            id: id
        },
        success: function (html) {
            console.log(html);
            type_button.html(section_type);
        }
    });
}

/**
 * Show section after click on anc pill
 *
 * @param obj
 */
function show_section(obj) {
    var id = obj.data('id');

    $('.dm-item').removeClass('text-white bg-blue');
    $('.dm-content').removeClass('active');

    obj.addClass('text-white bg-blue');
    $('.dm-content[data-id=' + id + ']').addClass('active');
}

/**
 * Update order in database
 */
function section_order(obj, i) {
    //console.log(obj);
    var id = obj.data('id');
    $.ajax({
        type: 'POST',
        data: {
            submit: 'submit',
            mode: 'order',
            id: id,
            order: i+1
        },
        success: function (html) {
            //console.log(html);
            //window.location.reload();
        }
    });
}

/**
 * Remove the section
 */
function section_delete(obj) {
    //console.log(obj);
    var id = obj.parent().parent().data('id');

    $.ajax({
        type: 'POST',
        data: {
            submit: 'submit',
            mode: 'delete',
            id: id
        },
        beforeSend: function () {
            obj.button('loading');
        },
        success: function (html) {
            //console.log(html);
            window.location.reload();
        },
        complete: function () {
            obj.button('reset');
        }
    });
}

/**
 * Update selected section
 *
 * @param obj
 */
function section_save(obj) {
    var id = obj.parent().parent().data('id');
    var title = obj.parent().parent().find('.dm_title').val();
    var section_id = obj.parent().parent().find('.dm_id').val();
    var section_class = obj.parent().parent().find('.dm_class').val();
    var content = obj.parent().parent().find('.dm-textarea').val();

    $.ajax({
        type: 'POST',
        data: {
            submit: 'submit',
            mode: 'update',
            id: id,
            title: title,
            section_id: section_id,
            section_class: section_class,
            content: content
        },
        beforeSend: function () {
            obj.attr('disabled', true);
        },
        success: function (html) {
            console.log(html);
            $('.dm-item[data-id=' + id + '] a').html(title);
            //panel_title.html(title);
            //window.location.reload();
        },
        complete: function () {
            obj.attr('disabled', false);
        }
    });
}


text:
#ifndef MEDIAINFODOWNLOADER_H
#define MEDIAINFODOWNLOADER_H

#include <QtCore>
#include <QtCore/QtGlobal>
#include <QHash>
#include <mediainfoplugininterface.h>

class MGConfItem;

struct RequestInfo
{
    QString type;
    QString info;
    QString plugin;
};

class MediaInfoDownloader : public QObject
{
    Q_OBJECT;

public:
    MediaInfoDownloader();
    ~MediaInfoDownloader();

    bool request(QString id, QString type, QString info);
    bool supported(QString type);

signals:
    void error(QString id, QString type, QString info, QString errorString);
    void ready(QString id, QString type, QString info, QString data);

private slots:
    void error(QString id, QString errorString);
    void ready(QString id, QString data);
    void enabledChanged();
    void disabledChanged();
    void priorityChanged();

private:
    QList<QPluginLoader *> m_plugins;
    QHash<QString, RequestInfo> m_requests;
    MGConfItem *enabledItem;
    bool enabled;
    MGConfItem *disabledItem;
    QStringList disabled;
    MGConfItem *priorityItem;
    QStringList priority;
};

#endif // MEDIAINFODOWNLOADER_H


text:
import classNames from "classnames";
import React from "react";

var DialSlice = React.createClass({
  displayName: "DialSlice",

  propTypes: {
    colorIndex: React.PropTypes.node,
    path: React.PropTypes.string.isRequired
  },

  render() {
    var classes = {
      arc: true
    };
    if (this.props.colorIndex != null) {
      classes["path-color-" + this.props.colorIndex] = true;
    }
    var classSet = classNames(classes);

    return (
      <g className={classSet}>
        <path d={this.props.path} />
      </g>
    );
  }
});

module.exports = DialSlice;


text:
/* @flow */

import React from 'react';
import ReactDOM from 'react-dom';

import {Router, Route, IndexRoute } from 'react-router';

import history from './app-history';

import App from './components/App';
import AdminPage from './components/AdminPage';
import OverviewPage from './components/OverviewPage';

import {signIn, signedIn} from './actions/actions';

// https://github.com/reactjs/react-router/blob/master/docs/Glossary.md#enterhook
function requireAuth(nextState, replace) {
    if (!signedIn) {
        const {pathname} = nextState.location;
        const root = '/';
        signIn(false)
            .then(() => {
                history.replace(pathname);
            })
            .catch(() => {
                history.replace(root)
            });

        replace(root);
    }
}

export default function () {
    ReactDOM.render(
        <Router history={history}>
            <Route path="/" component={App}>
                <IndexRoute component={OverviewPage} />
                <Route path="admin" component={AdminPage} onEnter={requireAuth}/>
            </Route>
        </Router>
        , document.getElementById('root'));
}


text:
var path = require('path');
var informer = require('../');
var assert = require('assert');
var fs = require('fs');
var fileNameExamples = require('./fileNameExamples');
var fileNameParser = require('../lib/file-name-parser');

describe('font-informer', function () {
	it('can parse .ttf files', function (done) {
		informer(path.join(__dirname, 'fonts/pathFont.ttf')).then(function(result) {
			assert.deepEqual(result, require('./expected.ttf.json'));
			done();
		});
	});
	it('can parse .woff files', function (done) {
		informer(path.join(__dirname, 'fonts/pathFont.woff')).then(function(result) {
			assert.deepEqual(result, require('./expected.woff.json'));
			done();
		});
	});
	it('can parse .eot files', function (done) {
		informer(path.join(__dirname, 'fonts/pathFont.eot')).then(function(result) {
			assert.deepEqual(result, require('./expected.eot.json'));
			done();
		});
	});
	it('can parse .svg files', function (done) {
		informer(path.join(__dirname, 'fonts/pathFont.svg')).then(function(result) {
			assert.deepEqual(result, require('./expected.svg.json'));
			done();
		});
	});

	describe('parsing buffers', function() {
		it('can parse .ttf buffers', function(done) {
			var file = path.join(__dirname, 'fonts', 'pathFont.ttf');
			informer(fs.readFileSync(file), 'pathFont.ttf').then(function(result) {
				assert.deepEqual(result, require('./expected.ttf.json'));
				done();
			});
		});
		it('can parse .woff buffers', function(done) {
			var file = path.join(__dirname, 'fonts', 'pathFont.woff');
			informer(fs.readFileSync(file), 'pathFont.woff').then(function(result) {
				assert.deepEqual(result, require('./expected.woff.json'));
				done();
			});
		});
		it('can parse .eot buffers', function(done) {
			var file = path.join(__dirname, 'fonts', 'pathFont.eot');
			informer(fs.readFileSync(file), 'pathFont.eot').then(function(result) {
				assert.deepEqual(result, require('./expected.eot.json'));
				done();
			});
		});
		it('can parse .svg buffers', function(done) {
			var file = path.join(__dirname, 'fonts', 'pathFont.svg');
			informer(fs.readFileSync(file), 'pathFont.svg').then(function(result) {
				assert.deepEqual(result, require('./expected.svg.json'));
				done();
			});
		});
	});

	describe('parsing filenames', function() {
		it('can parse common filenames', function(done) {
			fileNameExamples.forEach(function(example) {
				const result = fileNameParser(example.input);
				assert.deepEqual(result, example.expected);
			});
			done();
		})
	})
});


text:
/**
 * @file permutations.h
 * @brief Permutations over Hypercubes and their slices.
 **/
#ifndef _PERMUTATIONS_H_
#define _PERMUTATIONS_H_

#include "PAlgebra.h"
#include "matching.h"
#include "hypercube.h"

//! A simple permutation is just a vector with p[i]=\pi_i
typedef Vec<long> Permut;

//! Apply a permutation to a vector, out[i]=in[p1[i]] (NOT in-place)
template<class T>
void applyPermToVec(Vec<T>& out, const Vec<T>& in, const Permut& p1);
template<class T>
void applyPermToVec(vector<T>& out, const vector<T>& in, const Permut& p1);

//! Apply two permutations to a vector out[i]=in[p2[p1[i]]] (NOT in-place)
template<class T>
void applyPermsToVec(Vec<T>& out, const Vec<T>& in,
		      const Permut& p2, const Permut& p1);
template<class T>
void applyPermsToVec(vector<T>& out, const vector<T>& in,
		      const Permut& p2, const Permut& p1);

//! @brief A random size-n permutation
void randomPerm(Permut& perm, long n);

/**
 * @class ColPerm
 * @brief Permuting a single dimension (column) of a hypercube
 *
 * ColPerm is derived from a HyperCube<long>, and it uses the cube object
 * to store the actual permutation data. The interpretation of this data,
 * however, depends on the data member dim.
 *
 * The cube is partitioned into columns of size n = getDim(dim):
 * a single column consists of the n entries whose indices i have the
 * same coordinates in all dimensions other than dim.  The entries
 * in any such column foem a permutation on [0..n).
 *
 * For a given ColPerm perm, one way to access each column is as follows:
 *   for slice_index = [0..perm.getProd(0, dim))
 *     CubeSlice slice(perm, slice_index, dim)
 *     for col_index = [0..perm.getProd(dim+1))
 *        getHyperColumn(column, slice, col_index)
 *
 * Another way is to use the getCoord and addCoord methods.
 *
 * For example, permuting a 2x3x2 cube along dim=1 (the 2nd dimention), we
 * could have the data vector as  [ 1  1  0  2  2  0  2  0  1  1  0  2 ].
 * This means the four columns are
 * permuted by the permutations     [ 1     0     2                      ]
 *                                  [    1     2     0                   ]
 *                                  [                   2     1     0    ]
 *                                  [                      0     1     2 ].
 * Written explicitly, we get:      [ 2  3  0  5  4  1 10  7  8  9  6 11 ].
 *
 * Another representation that we provide is by "shift amount": how many
 * slots each element needs to move inside its small permutation. For the
 * example above, this will be:     [ 1    -1     0                      ]
 *                                  [    2    -1    -1                   ]
 *                                  [                   2     0    -2    ]
 *                                  [                      0     0     0 ]
 * so we write the permutatation as [ 1  1 -1  1  0 -2  2  0  0  0 -2  0 ].
 **/
class ColPerm : public HyperCube<long> {
private:
  long dim;
  ColPerm(); // disabled

public:

  explicit ColPerm(const CubeSignature& _sig): HyperCube<long>(_sig)
  { dim = -1; }

  long getPermDim() const {return dim;}
  void setPermDim(long _dim) {
    assert(_dim >= 0 && _dim < getNumDims());
    dim = _dim;
  }

  void makeExplicit(Permut& out) const;    // Write the permutation explicitly

  //! For each position in the data vector, compute how many slots it should be
  //! shifted inside its small permutation. Returns zero if all the shift amount
  //! are zero, nonzero values otherwise.
  long getShiftAmounts(Permut& out) const;

  //! Get multiple layers of a Benes permutation network. Returns in out[i][j]
  //! the shift amount to move item j in the i'th layer. Also isID[i]=true if
  //! the i'th layer is the identity (i.e., contains only 0 shift amounts).
  void getBenesShiftAmounts(Vec<Permut>& out, Vec<bool>& idID, const Vec<long>& benesLvls) const;

 //! A test/debugging method
  void printout(ostream& s) { // a test/debugging method
    s << "Cube signature: " << getSig() << endl;
    s << "  dim="<<dim<<endl;
    s << "  data="<<getData()<<endl;
  }
};
ostream& operator<< (ostream &s, const ColPerm& p);

/**
 * @brief Takes a permutation pi over m-dimensional cube C=Z_{n1} x...x Z_{nm}
 * and expresses pi as a product pi = rho_{2m-1} o ... o rho_2 o rho_1 where
 * each rho_i is a column permutation along one dimension. Specifically for
 * i<m, the permutations rho_i and rho_{2(m-1)-i} permute the i'th dimension
 **/
void breakPermByDim(vector<ColPerm>& out,
		    const Permut &pi, const CubeSignature& sig);

/**
 * @class GeneralBenesNetwork
 * @brief Implementation of generalized Benes Permutation Network
 **/
class GeneralBenesNetwork {
private:
  long n; // size of perm, n > 1, not necessarily power of 2
  long k; // recursion depth, k = least integer k s/t 2^k >= n

  Vec< Vec<short> > level;
    // there are 2*k - 1 levels, each wity n nodes.
    // level[i][j] is 0, 1, or -1,
    //   which designates an edge from node j at level i
    //   to node j + level[i][j]*shamt(i) at level i+1

  GeneralBenesNetwork(); // default constructor disabled

public:
  //! computes recursion depth k for generalized Benes network of size n.
  //! the actual number of levels in the network is 2*k-1
  static long depth(long n) {
    long k = 1;
    while ((1L << k) < n) k++;
    return k;
  }

  //! maps a level number i = 0..2*k-2 to a recursion depth d = 0..k-1
  //! using the formula d = (k-1)-|(k-1)-i|
  static long levelToDepthMap(long n, long k, long i) {
    assert(i >= 0 && i < 2*k-1);
    return (k-1) - labs((k-1)-i);
  }

  //! shift amount for level number i=0..2*k-2 using the formula
  //! ceil( floor(n/2^d) / 2), where d = levelToDepthMap(i)
  static long shamt(long n, long k, long i) {
    long d = levelToDepthMap(n, k, i);
    return ((n >> d) + 1) >> 1;
  }

  long getDepth() const { return k; }
  long getSize() const { return n; }
  long getNumLevels() const { return 2*k-1; }

  const Vec<short>& getLevel(long i) const
  {
    assert(i >= 0 && i < 2*k-1);
    return level[i];
  }

  long levelToDepthMap(long i) const { return levelToDepthMap(n, k, i); }
  long shamt(long i) const { return shamt(n, k, i); }

  // constructor
  GeneralBenesNetwork(const Permut& perm);

  // test correctness

  bool testNetwork(const Permut& perm) const;
};

/**
 * @class FullBinaryTree
 * @brief A simple implementation of full binary trees (each non-leaf has 2 children)
 */
template<class T> class FullBinaryTree;

//! @class TreeNode
//! @brief A node in a full binary tree.
//!
//! These nodes are in a vector, so we use indexes rather than pointers
template<class T> class TreeNode {
  T data;
  long parent;
  long leftChild, rightChild;
  long prev, next; // useful, e.g., to connect all leaves in a list

  void makeNullIndexes() {parent = leftChild = rightChild = prev = next = -1;}

public:
  TreeNode() { makeNullIndexes(); }
  explicit TreeNode(const T& d): data(d) { makeNullIndexes(); }

  T& getData() { return data; }
  const T& getData() const { return data; }

  long getParent() const { return parent; }
  long getLeftChild() const { return leftChild; }
  long getRightChild() const { return rightChild; }
  long getPrev() const { return prev; }
  long getNext() const { return next; }

  friend class FullBinaryTree<T>;
};

// A binary tree, the root is always the node at index 0
template<class T> class FullBinaryTree {
  long aux;       // a "foreign key" for this tree (holds generator index)
  vector< TreeNode<T> > nodes;
  long nLeaves;           // how many leaves in this tree
  long frstLeaf, lstLeaf; // index of the first/last leaves

public:
  FullBinaryTree(long _aux=0)
    { aux=_aux; nLeaves=0; frstLeaf=lstLeaf=-1; } // empty tree

  explicit FullBinaryTree(const T& d, long _aux=0) // tree with only a root
  {
    aux = _aux;
    nLeaves = 1;
    TreeNode<T> n(d);
    nodes.push_back(n);
    frstLeaf = lstLeaf = 0;
  }

  void putDataInRoot(const T& d)
  {
    if (nodes.size()==0) { // make new root
      TreeNode<T> n(d);
      nodes.push_back(n);
      frstLeaf = lstLeaf = 0;
      nLeaves = 1;
    }
    else nodes[0].data = d; // Root exists, just update data
  }

  // Provide some of the interfaces of the underlying vector
  long size() { return (long) nodes.size(); }

  TreeNode<T>& operator[](long i) { return nodes[i]; }
  const TreeNode<T>& operator[](long i) const { return nodes[i]; }

  TreeNode<T>& at(long i) { return nodes.at(i); }
  const TreeNode<T>& at(long i) const { return nodes.at(i); }

  T& DataOfNode(long i) { return nodes.at(i).data; }
  const T& DataOfNode(long i) const { return nodes.at(i).data; }

  long getAuxKey() const { return aux; }
  void setAuxKey(long _aux) { aux=_aux; }

  long getNleaves() const { return nLeaves; }
  long firstLeaf() const { return frstLeaf; }
  long nextLeaf(long i) const { return nodes.at(i).next; }
  long prevLeaf(long i) const { return nodes.at(i).prev; }
  long lastLeaf() const { return lstLeaf; }

  long rootIdx() const { return 0; }
  long parentIdx(long i) const { return nodes.at(i).parent; }
  long leftChildIdx(long i) const { return nodes.at(i).leftChild; }
  long rightChildIdx(long i) const { return nodes.at(i).rightChild; }

  void printout(ostream &s, long idx=0) const {
    s << "[" <<aux<<" ";
    s << nodes[idx].getData();
    if (leftChildIdx(idx)>=0) printout(s, leftChildIdx(idx));
    if (rightChildIdx(idx)>=0) printout(s, rightChildIdx(idx));
    s << "] ";
  }
  //  friend istream& operator>> (istream &s, DoubleCRT &d);

  //! If the parent is a leaf, add to it tho children with the given data,
  //! else just update the data of the two children of this parent.
  //! Returns the index of the left child, the right-child index is one
  //! more than the left-child index.
  long addChildren(long prntIdx, const T& leftData, const T& rightData);

  //! Remove all nodes in the tree except for the root
  void collapseToRoot()
  {
    if (nodes.size() > 1) {
      nodes.resize(1);
      frstLeaf = lstLeaf = 0;
      nLeaves = 1;
    }
  }
};
template <class T>
long FullBinaryTree<T>::addChildren(long prntIdx,
				    const T& leftData, const T& rightData)
{
  assert (prntIdx >= 0 && prntIdx < (long)(nodes.size()));

  // If parent is a leaf, add to it two children
  if (nodes[prntIdx].leftChild==-1 && nodes[prntIdx].rightChild==-1) {
    long childIdx = nodes.size();
    TreeNode<T> n1(leftData);
    nodes.push_back(n1); // add left child to vector
    TreeNode<T> n2(rightData);
    nodes.push_back(n2);// add right child to vector

    TreeNode<T>& parent = nodes[prntIdx];
    TreeNode<T>& left = nodes[childIdx];
    TreeNode<T>& right = nodes[childIdx+1];

    parent.leftChild = childIdx;            // point to children from parent
    parent.rightChild= childIdx+1;
    left.parent = right.parent = prntIdx; // point to parent from children

    // remove parent and insert children to the linked list of leaves
    left.prev = parent.prev;
    left.next = childIdx+1;
    right.prev = childIdx;
    right.next = parent.next;
    if (parent.prev>=0) { // parent was not the 1st leaf
      nodes[parent.prev].next = childIdx;
      parent.prev = -1;
    }
    else // parent was the first leaf, now its left child is 1st
      frstLeaf = childIdx;

    if (parent.next>=0) { // parent was not the last leaf
      nodes[parent.next].prev = childIdx+1;
      parent.next = -1;
    }
    else // parent was the last leaf, now its left child is last
      lstLeaf = childIdx+1;

    nLeaves++; // we replaced a leaf by a parent w/ two leaves
  }
  else { // parent is not a leaf, update the two children
    TreeNode<T>& parent = nodes[prntIdx];
    assert(parent.leftChild>=0 && parent.rightChild>=0);

    TreeNode<T>& left = nodes[parent.leftChild];
    TreeNode<T>& right = nodes[parent.rightChild];
    left.data = leftData;
    right.data = rightData;
  }
  return nodes[prntIdx].leftChild;
}

//! A minimal description of a generator for the purpose of building tree
class GenDescriptor {
public:
  long genIdx; // the index of the corresponding generator in Zm*/(p)
  long order;  // the order of this generator (or a smaller subcube)
  bool good;   // is this a good generator?

  GenDescriptor(long _order, bool _good, long gen=0) {
    genIdx = gen; order = _order; good = _good;
  }

  GenDescriptor() { }
};

//! A node in a tree relative to some generator
class SubDimension {
  static const Vec<long> dummyBenes; // Useful for initialization
 public:
  long size;   // size of cube slice, same as 'order' in GenDescriptor
  bool good;   // good or bad
  long e;      // shift-by-1 in this sub-dim is done via X -> X^{g^e}

  // A Benes leaf corresponds to either one or two Benes networks, depending
  // on whther or not it is in the middle. If this object is in the middle
  // then scndBenes.length()==0, else scndBenes.length()>=1. Each of the two
  // Benes network can be "trivial", i.e., collapsed to a single layer, which
  // is denoted by benes.length()==1.
  Vec<long> frstBenes;
  Vec<long> scndBenes;

  explicit SubDimension(long sz=0,bool gd=false,long ee=0,
			const Vec<long>& bns1=dummyBenes,
			const Vec<long>& bns2=dummyBenes)
  { size=sz; good=gd; e=ee; frstBenes=bns1; scndBenes=bns2; }

  long totalLength() const { return frstBenes.length()+scndBenes.length(); }
  /*  SubDimension& operator=(const SubDimension& other)
    { genIdx=other.genIdx; size=other.size;
      e=other.e; good=other.good; benes=other.benes;
      return *this;
      }
  */
  friend ostream& operator<< (ostream &s, const SubDimension &tree);
};
typedef FullBinaryTree<SubDimension> OneGeneratorTree;// tree for one generator

//! A vector of generator trees, one per generator in Zm*/(p)
class GeneratorTrees  {
  long depth; // How many layers in this permutation network
  Vec<OneGeneratorTree> trees;
  Permut map2cube, map2array;

 public:
  GeneratorTrees() {depth=0;} // default constructor

  // GeneratorTrees(const Vec<OneGeneratorTree>& _trees): trees(_trees)
  //  {depth=0;}
  //
  // Initialze trees with only the roots.
  //  GeneratorTrees(const Vec<SubDimension>& dims);

  long numLayers() const { return depth; } // depth of permutation network
  long numTrees() const { return trees.length(); }   // how many trees
  long getSize() const { return map2cube.length(); } // hypercube size

  OneGeneratorTree& operator[](long i) { return trees[i]; }
  const OneGeneratorTree& operator[](long i) const { return trees[i]; }
  OneGeneratorTree& at(long i) { return trees.at(i); }
  const OneGeneratorTree& at(long i) const { return trees.at(i); }

  OneGeneratorTree& getGenTree(long i) { return trees.at(i); }
  const OneGeneratorTree& getGenTree(long i) const { return trees.at(i); }

  const Permut& mapToCube() const { return map2cube; }
  const Permut& mapToArray() const { return map2array; }
  Permut& mapToCube() { return map2cube; }
  Permut& mapToArray() { return map2array; }

  long mapToCube(long i) const { return map2cube[i]; }
  long mapToArray(long i) const { return map2array[i]; }

  //! Get the "crude" cube dimensions corresponding to the vector of trees,
  //! the ordered vector with one dimension per tree
  void getCubeDims(Vec<long>& dims) const;

  //! Get the "fine" cube dimensions corresponding to the vector of trees,
  //! the ordered vector with one dimension per leaf in all the trees.
  void getCubeSubDims(Vec<long>& dims) const;

  // Returns coordinates of i relative to leaves of the tree
  //  void getCoordinates(Vec<long>&, long i) const;

  //! Compute the trees corresponding to the "optimal" way of breaking
  //! a permutation into dimensions, subject to some constraints. Returns
  //! the cost (# of 1D shifts) of this colution.
  //! Returns NTL_MAX_LONG if no solution
  long buildOptimalTrees(const Vec<GenDescriptor>& vec, long depthBound);

  /**
   * @brief Computes permutations mapping between linear array and the cube.
   *
   * If the cube dimensions (i.e., leaves of tree) are n1,n2,...,nt and
   * N=\prod_j n_j is the size of the cube, then an integer i can be
   * represented in either the mixed base of the n_j's or in "CRT basis"
   * relative to the leaves: Namely either
   *                            i = \sum_{j<=t}  i_j  * \prod_{k>j} n_k,
   *                         or i = \sum_leaf i'_leaf * leaf.e mod N.
   *
   * The breakPermByDim procedure expects its input in the mixed-base
   * representation, and the maps are used to convert back and forth.
   * Specifically, let (i'_1,...,i'_t) be the CRT representation of i in
   * this cube, and j = \sum_{j=1}^t i'_j * \prod_{k>j} n_k, then we have
   * map2cube[i]=j and map2array[j]=i.
   **/
  void ComputeCubeMapping();

  friend ostream& operator<< (ostream &s, const GeneratorTrees &t);
};

// Permutation networks

class Ctxt;
class EncryptedArray;
class PermNetwork;

//! @class PermNetLayer
//! @brief The information needed to apply one layer of a permutation network
class PermNetLayer {
  long genIdx; // shift-by-1 in this layer is done via X -> X^{g^e}
  long e;
  Vec<long> shifts; // shifts[i] is how much to shift slot i
  bool isID; // a silly optimization, does this layer copmute the identity?

  friend class PermNetwork;
  friend ostream& operator<< (ostream &s, const PermNetwork &net);
 public:
  long getGenIdx() const { return genIdx; }
  long getE() const { return e; }
  const Vec<long>& getShifts() const { return shifts; }
  bool isIdentity() const { return isID; }
};

//! A full permutation network
class PermNetwork {
  Vec<PermNetLayer> layers;

  //! Copmute one or more layers corresponding to one network of a leaf
  void setLayers4Leaf(long lyrIdx, const ColPerm& p, const Vec<long>& benesLvls,
		      long gIdx, const SubDimension& leafData,
		      const Permut& map2cube);

public:
  PermNetwork() {}; // empty network
  PermNetwork(const Permut& pi,const GeneratorTrees& trees)
    { buildNetwork(pi, trees); }

  long depth() const { return layers.length(); }

  //! Take as input a permutation pi and the trees of all the generators,
  //! and prepares the permutation network for this pi
  void buildNetwork(const Permut& pi, const GeneratorTrees& trees);

  //! Apply network to permute a ciphertext
  void applyToCtxt(Ctxt& c, const EncryptedArray& ea) const;

  //! Apply network to array, used mostly for debugging
  void applyToCube(HyperCube<long>& v) const;

  //! Apply network to plaintext polynomial, used mostly for debugging
  void applyToPtxt(ZZX& p, const EncryptedArray& ea) const;

  const PermNetLayer& getLayer(long i) const {return layers[i];}

  friend ostream& operator<< (ostream &s, const PermNetwork &net);
};

#endif /* ifndef _PERMUTATIONS_H_ */


text:
exports.viewDatabase = function(req, res) {
  var ctx = {
    title: 'Viewing Database: ' + req.dbName,
    colls: req.collections[req.dbName]
  };
  res.render('database', ctx);
}


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * The following config items are for the integration of
 * the Smarty template parsing system into CodeIgniter.
 *
 * @author	JohnHeroHD <johnherohd@gmail.com>
 * @author	Eric 'Aken' Roberts <eric@cryode.com>
 * @link	https://github.com/JohnHeroHD/Codeigniter-Smarty
 * @version	1.0.1
 */

/*
|--------------------------------------------------------------------------
| Template Directory
|--------------------------------------------------------------------------
|
| Set the directory where your templates (view files) are located
| WITH TRAILING SLASH. Most users will not need to change this
| directory. It is pre-set to CodeIgniter's default views directory.
|
| Default: APPPATH . 'views/';
|
*/
$config['smarty_template_dir'] = APPPATH . 'views/';

/*
|--------------------------------------------------------------------------
| File Extension
|--------------------------------------------------------------------------
|
| Set the file extension of the templates (views) you're
| using with the Smarty template library.
|
| Common examples: php, tpl, phtml
| Default: php
|
*/
$config['smarty_template_ext'] = 'tpl';

/*
|--------------------------------------------------------------------------
| Compiled Directory
|--------------------------------------------------------------------------
|
| Set the location of the compiled folder for Smarty files
| WITH TRAILING SLASH. This directory is required! Also,
| make sure it has write permissions set.
|
| Default: APPPATH . 'cache/smarty/';
|
*/
$config['smarty_compile_dir'] = ROOTPATH . 'storage/cache/smarty/';


text: Deprecated in favor of [stackage-curator](https://github.com/fpco/stackage-curator)


text:
package org.brooth.jeta.apt;

/**
 * @author Oleg Khalidov (brooth@gmail.com)
 */
public class ProcessingException extends RuntimeException {

    public ProcessingException() {
    }

    public ProcessingException(String message) {
        super(message);
    }

    public ProcessingException(String message, Throwable cause) {
        super(message, cause);
    }

    public ProcessingException(Throwable cause) {
        super(cause);
    }

    public ProcessingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}


text:
var koa = require('koa'),
    app = koa(),
    Q = require("q"),
    redis = require("redis"),
    brain = require("brain"),
    cors = require('koa-cors'),
    client = redis.createClient(),
    router = require('koa-router'),
    net = new brain.NeuralNetwork(),
    bodyParser = require("koa-body-parser");

app.use(cors());
app.use(bodyParser());
app.use(router(app));

client.on("error", function (err) {
  console.log("Error " + err);
});

app.get('/', function *(next) {
  var start = new Date().getTime();
  var data_set = Q.ninvoke(client, 'lrange', 'test', 0, -1).then(function (data) {
    if(data.length===0) return false;
    data = data.map(function (a) { return JSON.parse(a); })
    net.train(data);
    return {
        prediction: net.run({ r: 1, g: 0.4, b: 0 }),
        time: new Date().getTime() - start
     };
  });
  this.body = yield data_set;
});

app.post('/insert', function *(next) {
  var body = this.request.body;
  console.log(body);
  if(body.r!==undefined && body.g!==undefined && body.b!==undefined && body.output!==undefined){
    var stringify_me = {
      input: {
        r: Number(body.r),
        g: Number(body.g),
        b: Number(body.b)
      },
      output:{}
    };
    if(body.output==='0'){
      stringify_me.output.white=1;
    }else{
      stringify_me.output.black=1;
    };
    client.rpush("test", JSON.stringify(stringify_me), redis.print);
  };

  this.status = 200;
});

if (!module.parent) {
  app.listen(3000);
  console.log('koa fired up on port 3000');
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview MultiDevice setup screen for login/OOBE.
 */
login.createScreen('MultiDeviceSetupScreen', 'multidevice-setup', function() {
  return {
    get defaultControl() {
      return $('multidevice-setup-impl');
    },

    /**
     * This is called after resources are updated.
     */
    updateLocalizedContent() {
      $('multidevice-setup-impl').updateLocalizedContent();
    },
  };
});


text:
What is Linux VPS Hosting?
============================================================

 ![what is linux vps hosting](https://www.rosehosting.com/blog/wp-content/uploads/2017/03/what-is-linux-vps-hosting.jpg)

If you have a site that gets a lot of traffic, or at least, is expected to generate a lot of traffic, then you might want to consider getting a [Linux VPS hosting][6] package. A Linux VPS hosting package is also one of your best options if you want more control over the things that are installed on the server where your website is hosted at. Here are some of the frequently asked questions about Linux VPS hosting, answered.

### What does Linux VPS stand for?

Basically, Linux VPS stands for a virtual private server running on a Linux system. A virtual private server is a virtual server hosted on a physical server. A server is virtual if it runs in a host computer's memory. The host computer, in turn, can run a few other virtual servers.

### So I have to share a server with other users?

In most cases, yes. However, this does not mean that you will suffer from downtime or decreased performance. Each virtual server can run its own operating system, and each of these systems can be administered independently of each other. A virtual private server has its own operating system, data, and applications that are separated from all the other systems, applications, and data on the physical host server and the other virtual servers.

Despite sharing the physical server with other virtual private servers, you can still enjoy the benefits of a more expensive dedicated server without spending a lot of money for the service.

### What are the benefits of a Linux VPS hosting service?

There are many benefits when using a Linux VPS hosting service, including ease of use, increased security, and improved reliability at a lower total cost of ownership. However, for most webmasters, programmers, designers, and developers, the true benefit of a Linux VPS is the flexibility. Each virtual private server is isolated with its own operating environment, which means that you can easily and safely install the operating system that you prefer or need—in this case, Linux—as well as remove or add software and applications easily whenever you want to.

You can also modify the environment of your VPS to suit your performance needs, as well as improve the experience of your site's users or visitors. Flexibility can be the advantage you need to set you apart from your competitors.

Note that some Linux VPS providers won't give you full root access to your Linux VPS, in which case you'll have limited functionality. Be sure to get a [Linux VPS where you'll have full access to the VPS][7], so you can modify anything you want.

### Is Linux VPS hosting for everyone?

Yes! Even if you run a personal blog dedicated to your interests, you can surely benefit from a Linux VPS hosting package. If you are building and developing a website for a company, you would also enjoy the benefits. Basically, if you are expecting growth and heavy site traffic on your website, then a Linux VPS is for you.

Individuals and companies that want more flexibility in their customization and development options should definitely go for a Linux VPS, especially those who are looking to get great performance and service without paying for a dedicated server, which could eat up a huge chunk of the site's operating costs.

### I don't know how to work with Linux, can I still use a Linux VPS?

Of course! If you get a fully managed Linux VPS, your provider will manage the server for you, and most probably, will install and configure anything you want to run on your Linux VPS. If you get a VPS from us, we'll take care of your server 24/7 and we'll install, configure and optimize anything for you. All these services are included for free with all our [Managed Linux VPS hosting][8] packages.

So if you use our hosting services, it means that you get to enjoy the benefits of a Linux VPS, without any knowledge of working with Linux.

Another option to easy the use of a Linux VPS for beginners is to get a [VPS with cPanel][9], [DirectAdmin][10] or any [other hosting control panel][11]. If you use a control panel, you can manage your server via a GUI, which is a lot easier, especially for beginners. Although, [managing a Linux VPS from the command line][12] is fun and you can learn a lot by doing that.

### How different is a Linux VPS from a dedicated server?

As mentioned earlier, a virtual private server is just a virtual partition on a physical host computer. The physical server is divided into several virtual servers, which could diffuse the cost and overhead expenses between the users of the virtual partitions. This is why a Linux VPS is comparatively cheaper than a [dedicated server][13], which, as its name implies, is dedicated to only one user. For a more detailed overview of the differences, check our [Physical Server (dedicated) vs Virtual Server (VPS) comparison][14].

Aside from being more cost-efficient than dedicated servers, Linux virtual private servers often run on host computers that are more powerful than dedicated servers—performance and capacity are often greater than dedicated servers.

### I want to move from a shared hosting environment to a Linux VPS, can I do that?

If you currently use [shared hosting][15], you can easily move to a Linux VPS. One option is to [do it yourself][16], but the migration process can be a bit complicated and is definitely not recommended for beginners. Your best option is to find a host that offers [free website migrations][17] and let them do it for you. You can even move from shared hosting with a control panel to a Linux VPS without a control panel.

### Any more questions?

Feel free to leave a comment below.

If you get a VPS from us, our expert Linux admins will help you with anything you need with your Linux VPS and will answer any questions you have about working with your Linux VPS. Our admins are available 24/7 and will take care of your request immediately.

PS. If you liked this post please share it with your friends on the social networks using the buttons below or simply leave a reply in the comments section. Thanks.

--------------------------------------------------------------------------------

via: https://www.rosehosting.com/blog/what-is-linux-vps-hosting/

作者:[https://www.rosehosting.com ][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]:https://www.rosehosting.com/blog/what-is-linux-vps-hosting/
[1]:https://www.rosehosting.com/blog/what-is-linux-vps-hosting/
[2]:https://www.rosehosting.com/blog/what-is-linux-vps-hosting/#comments
[3]:https://www.rosehosting.com/blog/category/guides/
[4]:https://plus.google.com/share?url=https://www.rosehosting.com/blog/what-is-linux-vps-hosting/
[5]:http://www.linkedin.com/shareArticle?mini=true&url=https://www.rosehosting.com/blog/what-is-linux-vps-hosting/&title=What%20is%20Linux%20VPS%20Hosting%3F&summary=If%20you%20have%20a%20site%20that%20gets%20a%20lot%20of%20traffic,%20or%20at%20least,%20is%20expected%20to%20generate%20a%20lot%20of%20traffic,%20then%20you%20might%20want%20to%20consider%20getting%20a%20Linux%20VPS%20hosting%20package.%20A%20Linux%20VPS%20hosting%20package%20is%20also%20one%20of%20your%20best%20options%20if%20you%20want%20more%20...
[6]:https://www.rosehosting.com/linux-vps-hosting.html
[7]:https://www.rosehosting.com/linux-vps-hosting.html
[8]:https://www.rosehosting.com/linux-vps-hosting.html
[9]:https://www.rosehosting.com/cpanel-hosting.html
[10]:https://www.rosehosting.com/directadmin-hosting.html
[11]:https://www.rosehosting.com/control-panel-hosting.html
[12]:https://www.rosehosting.com/blog/basic-shell-commands-after-putty-ssh-logon/
[13]:https://www.rosehosting.com/dedicated-servers.html
[14]:https://www.rosehosting.com/blog/physical-server-vs-virtual-server-all-you-need-to-know/
[15]:https://www.rosehosting.com/linux-shared-hosting.html
[16]:https://www.rosehosting.com/blog/from-shared-to-vps-hosting/
[17]:https://www.rosehosting.com/website-migration.html


text:
using Newtonsoft.Json;

namespace BlInfoApiWrapper.Dto
{
    public class GetDetailsResponseItem
    {
        [JsonProperty(PropertyName = "auditor")]
        public string Auditor { get; set; }
        [JsonProperty(PropertyName = "bg")]
        public string Bg { get; set; }
        [JsonProperty(PropertyName = "box")]
        public string Box { get; set; }
        [JsonProperty(PropertyName = "city")]
        public string City { get; set; }
        [JsonProperty(PropertyName = "comment")]
        public string Comment { get; set; }
        [JsonProperty(PropertyName = "country")]
        public string Country { get; set; }
        [JsonProperty(PropertyName = "email")]
        public string Email { get; set; }
        [JsonProperty(PropertyName = "fax")]
        public string Fax { get; set; }
        [JsonProperty(PropertyName = "mobile")]
        public string Mobile { get; set; }
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }
        [JsonProperty(PropertyName = "orgNumber")]
        public string OrganisationNumber { get; set; }
        [JsonProperty(PropertyName = "pg")]
        public string Pg { get; set; }
        [JsonProperty(PropertyName = "phone")]
        public string Phone { get; set; }
        [JsonProperty(PropertyName = "street")]
        public string Street { get; set; }
        [JsonProperty(PropertyName = "web")]
        public string Web { get; set; }
        [JsonProperty(PropertyName = "zip")]
        public string Zip { get; set; }

        public GetDetailsResponseItem()
        {
            Auditor = string.Empty;
            Bg = string.Empty;
            Box = string.Empty;
            City = string.Empty;
            Comment = string.Empty;
            Country = string.Empty;
            Email = string.Empty;
            Fax = string.Empty;
            Mobile = string.Empty;
            Name = string.Empty;
            OrganisationNumber = string.Empty;
            Pg = string.Empty;
            Phone = string.Empty;
            Street = string.Empty;
            Web = string.Empty;
            Zip = string.Empty;
        }
    }
}


text:
package com.whd.wifikeyview.preferences.fragments;

import com.whd.wifikeyview.R;

import android.os.Bundle;
import android.preference.PreferenceFragment;

public class ShowPasswordPreferences extends PreferenceFragment {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.preferences_showpassword);
	}
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Neo.Wallets.SQLite;

namespace Neo.UnitTests
{
    [TestClass]
    public class UT_UserWalletAccount
    {
        [TestMethod]
        public void TestGenerator()
        {
            UserWalletAccount account = new UserWalletAccount(UInt160.Zero, ProtocolSettings.Default);
            Assert.IsNotNull(account);
        }

        [TestMethod]
        public void TestGetHasKey()
        {
            UserWalletAccount account = new UserWalletAccount(UInt160.Zero, ProtocolSettings.Default);
            Assert.AreEqual(false, account.HasKey);
        }

        [TestMethod]
        public void TestGetKey()
        {
            UserWalletAccount account = new UserWalletAccount(UInt160.Zero, ProtocolSettings.Default);
            Assert.AreEqual(null, account.GetKey());
        }
    }
}


text:
<?php
namespace Bootstrap\Form\View\Helper\Element;
use Zend\Form\View\Helper\FormText;
use Zend\Form\ElementInterface;
use Bootstrap\Util;

/**
 *
 * @author alexandre
 *
 */
class Text extends FormText
{
    /* (non-PHPdoc)
     * @see \Zend\Form\View\Helper\FormInput::render()
    */
    public function render(ElementInterface $element) {
    	$element->setAttribute('class',Util::addWords('form-control',$element->getAttribute('class')));
    	return parent::render ($element);
    }
}

?>


text:
SpecBegin(ARWebViewCacheHost);

__block ARWebViewCacheHost *sut;

it(@"it generates the same cache configuration objects on webviews", ^{
    sut = [[ARWebViewCacheHost alloc] init];

    WKWebView *webView = [sut dequeueWebView];
    [webView stopLoading];

    WKWebView *webView2 = [sut dequeueWebView];
    [webView2 stopLoading];

    expect(webView.configuration.processPool).to.equal(webView2.configuration.processPool);
});

it(@"it generates a webviews that is already requesting a blank url", ^{
    sut = [[ARWebViewCacheHost alloc] init];

    WKWebView *webView = [sut dequeueWebView];
    NSURL *url = webView.backForwardList.currentItem.URL;
    [webView stopLoading];

    expect(url.path).to.equal(@"/dev/blank");
});

SpecEnd