text:
/*
 * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */
package javax.print.attribute.standard;

import java.util.Date;
import javax.print.attribute.Attribute;
import javax.print.attribute.DateTimeSyntax;
import javax.print.attribute.PrintJobAttribute;

/**
 * Class DateTimeAtCompleted is a printing attribute class, a date-time
 * attribute, that indicates the date and time at which the Print Job completed
 * (or was canceled or aborted).
 *

 * To construct a DateTimeAtCompleted attribute from separate values of the
 * year, month, day, hour, minute, and so on, use a {@link java.util.Calendar
 * Calendar} object to construct a {@link java.util.Date Date} object, then use
 * the {@link java.util.Date Date} object to construct the DateTimeAtCompleted
 * attribute. To convert a DateTimeAtCompleted attribute to separate values of
 * the year, month, day, hour, minute, and so on, create a {@link
 * java.util.Calendar Calendar} object and set it to the {@link java.util.Date
 * Date} from the DateTimeAtCompleted attribute.
 *

 * IPP Compatibility: The information needed to construct an IPP
 * "date-time-at-completed" attribute can be obtained as described above. The
 * category name returned by getName() gives the IPP attribute
 * name.
 *

 *
 * @author  Alan Kaminsky
 */
public final class DateTimeAtCompleted extends DateTimeSyntax
    implements PrintJobAttribute {

    private static final long serialVersionUID = 6497399708058490000L;

    /**
     * Construct a new date-time at completed attribute with the given {@link
     * java.util.Date Date} value.
     *
     * @param  dateTime  {@link java.util.Date Date} value.
     *
     * @exception  NullPointerException
     *     (unchecked exception) Thrown if dateTime is null.
     */
    public DateTimeAtCompleted(Date dateTime) {
        super (dateTime);
    }

    /**
     * Returns whether this date-time at completed attribute is equivalent to
     * the passed in object. To be equivalent, all of the following conditions
     * must be true:
     *

     *

     * object is not null.
     *

     * object is an instance of class DateTimeAtCompleted.
     *

     * This date-time at completed attribute's {@link java.util.Date Date} value
     * and object's {@link java.util.Date Date} value are equal.
     *

     *
     * @param  object  Object to compare to.
     *
     * @return  True if object is equivalent to this date-time
     *          at completed attribute, false otherwise.
     */
    public boolean equals(Object object) {
        return(super.equals (object) &&
               object instanceof DateTimeAtCompleted);
    }

// Exported operations inherited and implemented from interface Attribute.

    /**
     * Get the printing attribute class which is to be used as the "category"
     * for this printing attribute value.
         *

         * For class DateTimeAtCompleted, the category is class
         * DateTimeAtCompleted itself.
         *
         * @return  Printing attribute class (category), an instance of class
         *          {@link java.lang.Class java.lang.Class}.
         */
    public final Class<? extends Attribute> getCategory() {
        return DateTimeAtCompleted.class;
    }

    /**
     * Get the name of the category of which this attribute value is an
     * instance.
     *

     * For class DateTimeAtCompleted, the category name is
     * "date-time-at-completed".
     *
     * @return  Attribute category name.
     */
    public final String getName() {
        return "date-time-at-completed";
    }

}


text:
#pragma once

#include <string>

#include "envoy/common/exception.h"
#include "envoy/http/header_map.h"

namespace Envoy {
namespace Http {

/**
 * Indicates a non-recoverable protocol error that should result in connection termination.
 */
class CodecProtocolException : public EnvoyException {
public:
  CodecProtocolException(const std::string& message) : EnvoyException(message) {}
};

/**
 * Raised when outbound frame queue flood is detected.
 */
class FrameFloodException : public CodecProtocolException {
public:
  FrameFloodException(const std::string& message) : CodecProtocolException(message) {}
};

/**
 * Raised when a response is received on a connection that did not send a request. In practice
 * this can only happen on HTTP/1.1 connections.
 */
class PrematureResponseException : public EnvoyException {
public:
  PrematureResponseException(HeaderMapPtr&& headers)
      : EnvoyException(""), headers_(std::move(headers)) {}

  const HeaderMap& headers() { return *headers_; }

private:
  HeaderMapPtr headers_;
};

/**
 * Indicates a client (local) side error which should not happen.
 */
class CodecClientException : public EnvoyException {
public:
  CodecClientException(const std::string& message) : EnvoyException(message) {}
};

} // namespace Http
} // namespace Envoy

redpajama_set_name: RedPajamaGithub


text:
package leo.modules.procedures

sealed abstract class TermRenaming
object TermRenaming {
  final def apply(): TermRenaming = new TermRenamingImpl()

  private[this] final class TermRenamingImpl extends TermRenaming
}


text:
<?php

namespace Laravel\Achievements\Tests;

use Laravel\Achievements\Facades\Achievements;
use Laravel\Achievements\LaravelAchievements;
use Laravel\Achievements\Tests\Stubs\ReachLevelCriteria;
use Laravel\Achievements\Tests\Stubs\User;

class LaravelAchievementsTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->seedAchievements();
    }

    public function testInstance()
    {
        /**
         * @var User                $user
         * @var LaravelAchievements $achievements
         */
        $user = User::create(['name' => 'John Doe']);
        $achievements = app(LaravelAchievements::class);
        $achievements->registerCriterias([
            ReachLevelCriteria::class,
        ]);

        $count = $achievements->updateCriterias($user, 'reach_level', ['value' => 10]);

        $this->assertSame(3, $count);
        $this->assertSame(3, count($user->achievementCriterias));
    }

    public function testFacade()
    {
        /**
         * @var User $user
         */
        $user = User::create(['name' => 'John Doe']);
        Achievements::registerCriterias([
            ReachLevelCriteria::class,
        ]);

        $count = Achievements::updateCriterias($user, 'reach_level', ['value' => 10]);

        $this->assertSame(3, $count);
        $this->assertSame(3, count($user->achievementCriterias));
    }
}


text:
from django.contrib import admin

from core.models import Group
from .models import (
    Module, SubModule,
    GroupModule, GroupSubModule, GroupState
)

class MenuItemInline(admin.TabularInline):
    model = SubModule
    ordering = ('order',)
    extra = 0

@admin.register(Module)
class MenuAdmin(admin.ModelAdmin):
    list_display = ["text", 'order', 'match', 'is_deleted']
    fieldsets = [
        ["Module", {
            "fields": ('text', 'order', 'style', 'match')
        }],

    ]
    inlines = [MenuItemInline, ]

@admin.register(SubModule)
class SubMenuAdmin(admin.ModelAdmin):
    list_display = ["text", 'order', 'moduletext', 'reference', 'is_deleted']
    fieldsets = [
        ["SubModule", {
            "fields": ('text', 'module', 'order', 'style', 'match', 'reference')
        }],

    ]

class GroupSubModuleInline(admin.TabularInline):
    list_display = ['group_module', 'submodule']
    model = GroupSubModule
    extra = 0

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        field = super(GroupSubModuleInline, self).formfield_for_foreignkey(
            db_field, request, **kwargs)
        if db_field.name == 'submodule':
            if request._obj_ is not None:
                field.queryset = field.queryset.filter(
                    module=request._obj_.module)
            else:
                field.queryset = field.queryset.none()
        return field

@admin.register(GroupModule)
class GroupModuleAdmin(admin.ModelAdmin):
    list_display = ['group', 'module']
    inlines = [GroupSubModuleInline, ]

    def get_form(self, request, obj=None, **kwargs):
        request._obj_ = obj
        return super(GroupModuleAdmin, self).get_form(request, obj, **kwargs)

class GroupStateInline(admin.TabularInline):
    model = GroupState

@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
    list_display = ['name']
    inlines = [GroupStateInline, ]


text:
#ifndef TIN_CONTROLLERS_TERMINAL_TERMINALVISITOR_HPP
#define	TIN_CONTROLLERS_TERMINAL_TERMINALVISITOR_HPP

namespace tin { namespace controllers { namespace terminal
{
    class TerminalModule;

    namespace events
    {
        struct Terminate;
        struct SendMessage;
    }

    class TerminalVisitor
    {
        friend class tin::controllers::terminal::TerminalModule;

        tin::controllers::terminal::TerminalModule& controller;

        TerminalVisitor(tin::controllers::terminal::TerminalModule& controller);

    public:
        void visit(tin::controllers::terminal::events::Terminate &evt);
        void visit(tin::controllers::terminal::events::SendMessage &evt);
    };
}}}

#endif	/* TIN_CONTROLLERS_TERMINAL_TERMINALVISITOR_HPP */


text:
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'main',
    template: '
Hola Mundo Angular 4

{{mensaje}}

<hola-mundo></hola-mundo>
'
})
export class MainComponent implements OnInit {
    mensaje: string;

    constructor() { }

    ngOnInit() {
        this.mensaje = "Bienvenidos";
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IntergalacticTravel.Contracts;

namespace IntergalacticTravel.Tests.Mocks
{
    public class MockedTeleportedStation : TeleportStation
    {
        public MockedTeleportedStation(IBusinessOwner owner, IEnumerable<IPath> galacticMap, ILocation location)
            : base(owner, galacticMap, location)
        {
        }

        public IBusinessOwner GetBusinnesOwner
        {
            get { return base.owner; }
        }

        public IEnumerable<IPath> GetGalacticMap
        {
            get { return base.galacticMap; }
        }

        public ILocation GetLocation
        {
            get { return base.location; }
        }

        public void AddResources(IResources res)
        {
            base.resources.Add(res);
        }
    }
}


text:
using System.Data.Entity;
using System.Linq;

namespace MysteryRiddles.Data.Repositories
{
    public class GenericRepository<T> : IRepository<T> where T : class
    {
        private DbContext db;
        private IDbSet<T> set;

        public GenericRepository(DbContext context)
        {
            this.db = context;
            this.set = context.Set<T>();
        }

        public virtual IQueryable<T> All()
        {
            return this.set;
        }

        public virtual T GetById(object id)
        {
            return this.set.Find(id);
        }

        public virtual void Add(T entity)
        {
            this.ChangeEntityState(entity, EntityState.Added);
        }

        public virtual void Update(T entity)
        {
            this.ChangeEntityState(entity, EntityState.Modified);
        }

        public virtual T Delete(T entity)
        {
            this.ChangeEntityState(entity, EntityState.Deleted);

            return entity;
        }

        public virtual T Delete(object id)
        {
            var entity = this.GetById(id);
            this.Delete(entity);
            return entity;
        }

        public virtual void Detach(T entity)
        {
            var entry = this.db.Entry(entity);

            entry.State = EntityState.Detached;
        }

        public int SaveChanges()
        {
            return this.db.SaveChanges();
        }

        public void Dispose()
        {
            this.db.Dispose();
        }

        protected void ChangeEntityState(T entity, EntityState state)
        {
            var entry = this.db.Entry(entity);

            if (entry.State == EntityState.Detached)
            {
                this.set.Attach(entity);
            }

            entry.State = state;
        }
    }
}


text:
using System;
using System.Linq;
using System.Xml.Linq;
using Orchard.Logging;
using Orchard.Recipes.Models;
using Orchard.Recipes.Services;
using WebAdvanced.Sitemap.Services;
using WebAdvanced.Sitemap.ViewModels;

namespace WebAdvanced.Sitemap.ImportExport
{
    public class SitemapRecipeHandler : IRecipeHandler
    {
        private readonly IAdvancedSitemapService _sitemapService;

        public SitemapRecipeHandler(IAdvancedSitemapService sitemapService)
        {
            _sitemapService = sitemapService;
            Logger = NullLogger.Instance;
        }

        public ILogger Logger { get; set; }

        public void ExecuteRecipeStep(RecipeContext recipeContext)
        {
            if (!String.Equals(recipeContext.RecipeStep.Name, SitemapCustomExportStep.ExportStep, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var stepElement = recipeContext.RecipeStep.Step;

            var indexingElement = stepElement.Element("Indexing");
            if (indexingElement != null)
            {
                var indexSettingsModels = indexingElement.Elements("Index").Select(element => new IndexSettingsModel
                {
                    Name = element.Attribute("Name").Value,
                    DisplayName = element.Attribute("DisplayName").Value,
                    IndexForDisplay = Convert.ToBoolean(element.Attribute("IndexForDisplay").Value),
                    IndexForXml = Convert.ToBoolean(element.Attribute("IndexForXml").Value),
                    Priority = Convert.ToInt32(element.Attribute("Priority").Value),
                    UpdateFrequency = element.Attribute("UpdateFrequency").Value
                });

                _sitemapService.SetIndexSettings(indexSettingsModels);
            }

            var customRoutesElement = stepElement.Element("CustomRoutes");
            if (customRoutesElement != null)
            {
                var customRouteModels = customRoutesElement.Elements("CustomRoute").Select(element => new CustomRouteModel
                {
                    Name = element.Attribute("Name").Value,
                    IndexForDisplay = Convert.ToBoolean(element.Attribute("IndexForDisplay").Value),
                    IndexForXml = Convert.ToBoolean(element.Attribute("IndexForXml").Value),
                    Priority = Convert.ToInt32(element.Attribute("Priority").Value),
                    UpdateFrequency = element.Attribute("UpdateFrequency").Value,
                    Url = element.Attribute("Url").Value
                });

                _sitemapService.SetCustomRoutes(customRouteModels);
            }

            var displayRoutesElement = stepElement.Element("DisplayRoutes");
            if (displayRoutesElement != null)
            {
                var routeSettingsModels = displayRoutesElement.Elements("DisplayRoute").Select(element => new RouteSettingsModel
                {
                    Name = element.Attribute("Name").Value,
                    Id = Convert.ToInt32(element.Attribute("Id").Value),
                    Active = Convert.ToBoolean(element.Attribute("Active").Value),
                    DisplayColumn = Convert.ToInt32(element.Attribute("DisplayColumn").Value),
                    DisplayLevels = Convert.ToInt32(element.Attribute("DisplayLevels").Value),
                    Slug = element.Attribute("Slug").Value,
                    Weight = Convert.ToInt32(element.Attribute("Weight").Value),
                });

                _sitemapService.SetRoutes(routeSettingsModels);
            }

            recipeContext.Executed = true;
        }
    }
}


text:
#region copyright

#endregion

namespace VZF.Controls
{
  using System.Web.UI;

  using YAF.Core;

  using YAF.Core.BBCode;
  using YAF.Types.Interfaces;
  using VZF.Utils;
  using YAF.Types;

  /// <summary>
  /// The localization support extensions.
  /// </summary>
  public static class LocalizationSupportExtensions
  {
    #region Public Methods

    /// <summary>
    /// The get current item.
    /// </summary>
    /// <param name="supportItem">
    /// The support Item.
    /// </param>
    /// <param name="currentControl">
    /// The current Control.
    /// </param>
    /// <returns>
    /// The get current item.
    /// </returns>
    public static string Localize([NotNull] this ILocalizationSupport supportItem, [NotNull] Control currentControl)
    {
      CodeContracts.ArgumentNotNull(supportItem, "supportItem");
      CodeContracts.ArgumentNotNull(currentControl, "currentControl");

      if (currentControl.Site != null && currentControl.Site.DesignMode == true)
      {
        return "[PAGE:{0}|TAG:{1}]".FormatWith(supportItem.LocalizedPage, supportItem.LocalizedTag);
      }
      else if (supportItem.LocalizedPage.IsSet() && supportItem.LocalizedTag.IsSet())
      {
        return YafContext.Current.Get<ILocalization>().GetText(supportItem.LocalizedPage, supportItem.LocalizedTag);
      }
      else if (supportItem.LocalizedTag.IsSet())
      {
        return YafContext.Current.Get<ILocalization>().GetText(supportItem.LocalizedTag);
      }

      return null;
    }

    /// <summary>
    /// The localize and render.
    /// </summary>
    /// <param name="supportedItem">
    /// The supported item.
    /// </param>
    /// <param name="currentControl">
    /// The current control.
    /// </param>
    /// <returns>
    /// The localize and render.
    /// </returns>
    public static string LocalizeAndRender([NotNull] this ILocalizationSupport supportedItem, [NotNull] BaseControl currentControl)
    {
      CodeContracts.ArgumentNotNull(supportedItem, "supportedItem");
      CodeContracts.ArgumentNotNull(currentControl, "currentControl");

      string localizedItem = supportedItem.Localize(currentControl);

      // convert from YafBBCode to HTML
      if (supportedItem.EnableBBCode)
      {
        localizedItem = currentControl.Get<IBBCode>().MakeHtml(localizedItem, true, false);
      }

      return localizedItem.FormatWith(supportedItem.Param0, supportedItem.Param1, supportedItem.Param2);
    }

    #endregion
  }
}


text:
package com.gmail.jakekinsella;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by jakekinsella on 9/23/16.
 */
public class JSONFileReader {

    private JSONObject jsonObject;

    private static final Logger logger = LogManager.getLogger();

    public JSONFileReader(String filePath) {
        this.parse(filePath);
    }

    public JSONObject getJSONObject() {
        return this.jsonObject;
    }

    private void parse(String filePath) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));

            String text = "";
            String line = br.readLine();
            while (line != null) {
                text += line;
                line = br.readLine();
            }

            br.close();

            JSONParser parser = new JSONParser();
            Object obj = parser.parse(text);
            this.jsonObject = (JSONObject) obj;
        } catch (IOException | ParseException e) {
            logger.error("Error in parsing JSON", e);
        }
    }
}


text:
@import EventKit;
@import EventKitUI;

@interface MEHEventDetailViewController () <UIScrollViewDelegate, EKEventEditViewDelegate>

@property (nonatomic, strong) UIImageView *mapImageView;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UITextView *descriptionTextView;
@property (nonatomic, strong) UILabel *locationLabel;
@property (nonatomic, strong) UILabel *descriptionLabel;
@property (nonatomic, strong) UIButton * addToCalendarButton;
@property (nonatomic, strong) UIScrollView *mapImageViewScrollView;
@property (nonatomic, strong) UIActivityIndicatorView *loadingView;

@end

@implementation MEHEventDetailViewController

-(void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = [UIColor whiteColor];
  UIFont *standardTitleFont = [UIFont fontWithName:@"AvenirNext" size:18.0f];
  self.mapImageView = [[UIImageView alloc]init];
  self.mapImageView.contentMode = UIViewContentModeScaleAspectFit;
  self.timeLabel = [UILabel new];
  self.timeLabel.textColor = [UIColor menloHacksGray];
  self.timeLabel.font = standardTitleFont;
  self.descriptionTextView = [[UITextView alloc]init];
  self.descriptionTextView.font = [UIFont fontWithName:@"AvenirNext" size:14.0f];
  self.descriptionTextView.textColor = [UIColor menloHacksGray];
  self.descriptionTextView.editable = NO;
  self.descriptionLabel = [UILabel new];
  self.descriptionLabel.textColor = [UIColor menloHacksPurple];
  self.descriptionLabel.font = standardTitleFont;
  self.descriptionLabel.numberOfLines = 0;
  self.descriptionLabel.textAlignment = NSTextAlignmentCenter;
  self.locationLabel = [UILabel new];
  self.locationLabel.textColor = [UIColor menloHacksGray];
  self.locationLabel.font = [UIFont fontWithName:@"AvenirNext" size:18.0f];
  self.addToCalendarButton = [[UIButton alloc]init];

  [self.addToCalendarButton setTitle:@"Add Event to Calendar" forState:UIControlStateNormal];
  self.addToCalendarButton.titleLabel.font = [UIFont fontWithName:@"AvenirNext" size:18.0f];
  [self.addToCalendarButton setTitleColor:[UIColor menloHacksPurple] forState:UIControlStateNormal];
  [self.addToCalendarButton addTarget:self
                               action:@selector(addToCalendar:)
                            forControlEvents:UIControlEventTouchDown];

  self.mapImageViewScrollView = [[UIScrollView alloc]init];
  self.mapImageViewScrollView.delegate = self;
  self.mapImageViewScrollView.maximumZoomScale = 3.0;
  self.mapImageViewScrollView.minimumZoomScale = 1.0;

  _loadingView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
  _loadingView.color = [UIColor menloHacksPurple];

  [AutolayoutHelper configureView:self.view
                         subViews:NSDictionaryOfVariableBindings(_mapImageViewScrollView, _timeLabel, _descriptionTextView, _descriptionLabel, _addToCalendarButton, _locationLabel)
                          constraints:@[@"H:|[_mapImageViewScrollView]|",
                                        @"V:|[_mapImageViewScrollView]-[_descriptionLabel]-[_locationLabel]-[_timeLabel]-[_descriptionTextView]-15-[_addToCalendarButton]-50-|",
                                        @"X:_locationLabel.centerX == superview.centerX",
                                        @"X:_descriptionLabel.centerX == superview.centerX",
                                        @"H:|-[_descriptionLabel]-|",
                                        @"X:_addToCalendarButton.centerX == superview.centerX",
                                        @"X:_timeLabel.centerX == superview.centerX",
                                        @"H:|-[_descriptionTextView]-|"]];

  [AutolayoutHelper configureView:_mapImageViewScrollView
                         subViews:NSDictionaryOfVariableBindings(_mapImageView, _loadingView)
                         constraints:@[@"H:|[_mapImageView]|",
                                       @"X:_mapImageView.centerY == superview.centerY",
                                       @"X:_loadingView.centerX == superview.centerX",
                                       @"X:_loadingView.centerY == superview.centerY"]];

  NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:_mapImageView
                                                                     attribute:NSLayoutAttributeWidth
                                                                     relatedBy:NSLayoutRelationEqual
                                                                        toItem:_mapImageViewScrollView
                                                                     attribute:NSLayoutAttributeWidth
                                                                    multiplier:1
                                                                      constant:0];

  NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:_mapImageView
                                                                      attribute:NSLayoutAttributeHeight
                                                                      relatedBy:NSLayoutRelationLessThanOrEqual
                                                                         toItem:_mapImageViewScrollView
                                                                      attribute:NSLayoutAttributeHeight
                                                                     multiplier:1
                                                                       constant:0];

  [self.view addConstraint:widthConstraint];
  [self.view addConstraint:heightConstraint];

  NSLayoutConstraint *scrollViewAspectRatio = [NSLayoutConstraint constraintWithItem:self.mapImageViewScrollView
                                                                           attribute:NSLayoutAttributeHeight
                                                                           relatedBy:NSLayoutRelationEqual
                                                                           toItem:self.mapImageViewScrollView
                                                                           attribute:NSLayoutAttributeWidth
                                                                            multiplier:.75
                                                                            constant:0];
  [self.view addConstraint:scrollViewAspectRatio];

  if(_event) {
    [self setEvent:_event];
  }

}

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

-(void)setEvent:(MEHEvent *)event {
  _event = event;
  _loadingView.hidden = NO;
  [_loadingView startAnimating];

    __weak typeof(self) weakSelf = self;

    [self.mapImageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_event.location.mapURL]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(!strongSelf) {
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            strongSelf.mapImageView.image = image;
            [strongSelf.loadingView stopAnimating];
            strongSelf.loadingView.hidden = YES;
        });
    } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(!strongSelf) {
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [strongSelf.loadingView stopAnimating];
            strongSelf.loadingView.hidden = YES;
        });

    }];

  NSString *timeText;
  if(event.endTime) {
    self.addToCalendarButton.hidden = NO;
    timeText = [NSString stringWithFormat:@"%@ - %@", [NSDate formattedShortTimeFromDate:event.startTime], [NSDate formattedShortTimeFromDate:event.endTime]];
  }
  else {
    timeText = [NSDate formattedShortTimeFromDate:event.startTime];
    self.addToCalendarButton.hidden = YES;
  }
  self.timeLabel.text = timeText;
  self.locationLabel.text = [NSString stringWithFormat:@"Location: %@", event.location.locationName];
  self.descriptionTextView.text = event.longDescription;
  self.descriptionLabel.text = event.shortDescription;

}

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
  return _mapImageView;
}

-(void)addToCalendar: (UIButton *)sender {
  EKEventStore * eventStore = [[EKEventStore alloc] init];
    NSString *eventID = self.event.serverID;
  [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError * _Nullable error) {
    if(granted) {
      EKEvent *event = [EKEvent eventWithEventStore:eventStore];
        MEHEvent *localEvent = [MEHEvent objectForPrimaryKey:eventID];

        event.title = localEvent.shortDescription;

      event.location = localEvent.location.locationName;
      event.startDate = localEvent.startTime;
      event.endDate = localEvent.endTime;

      [event setCalendar:[eventStore defaultCalendarForNewEvents]];

        dispatch_async(dispatch_get_main_queue(), ^{
            EKEventEditViewController *eventViewController = [[EKEventEditViewController alloc] init];
              eventViewController.event = event;
              eventViewController.eventStore = eventStore;
              eventViewController.editViewDelegate = self;
              [self presentViewController:eventViewController animated:YES completion:nil];
        });
    }
    else {

    }
  }];

}

- (void)eventEditViewController:(EKEventEditViewController *)controller
          didCompleteWithAction:(EKEventEditViewAction)action {

  [self dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
from pynt import task

tasks_run = []

@task()
def clean(directory='/tmp'):
    tasks_run.append('clean[%s]' % directory)

@task(clean)
def html():
    tasks_run.append('html')

@task()
def tests(*test_names):
    tasks_run.append('tests[%s]' % ','.join(test_names))

@task(clean)
def copy_file(from_, to, fail_on_error='True'):
    tasks_run.append('copy_file[%s,%s,%s]' % (from_, to, fail_on_error))

@task(clean)
def start_server(port='80', debug='True'):
    tasks_run.append('start_server[%s,%s]' % (port, debug))

@task(ignore=True)
def ignored(file, contents):
    tasks_run.append('append_to_file[%s,%s]' % (file, contents))

@task(clean, ignored)
def append_to_file(file, contents):
    tasks_run.append('append_to_file[%s,%s]' % (file, contents))

@task(ignored)
def echo(*args,**kwargs):
    args_str = []
    if args:
        args_str.append(','.join(args))
    if kwargs:
        args_str.append(','.join("%s=%s" %  (kw, kwargs[kw]) for kw in sorted(kwargs)))

    tasks_run.append('echo[%s]' % ','.join(args_str))


text:
package leap.core.validation;

import java.lang.annotation.Annotation;
import java.util.Locale;

import leap.core.i18n.MessageSource;
import leap.lang.annotation.Nullable;
import leap.lang.exception.ObjectNotFoundException;

public interface ValidationManager {

	/**
	 * Returns a {@link MessageSource} for resolving error messages.
	 */
	MessageSource getMessageSource();

	/**
	 * Returns the instance of {@link BeanValidator} for validating a bean.
	 */
	BeanValidator getBeanValidator();

	String getErrorMessage(Validator validator);

	String getErrorMessage(Validator validator,Locale locale);

	String getErrorMessage(Validator validator,String title);

	String getErrorMessage(Validator validator,String title,Locale locale);

	Validator createValidator(Annotation constraint,Class<?> valueType) throws ObjectNotFoundException;

	Validator tryCreateValidator(Annotation constraint,Class<?> valueType);

	/**
	 * Creates a new {@link Validation}.
	 */
	Validation createValidation();

	/**
	 * Creates a new {@link Validation}.
	 */
	Validation createValidation(@Nullable Errors errors);
}


text:
import argparse
from scrapy.crawler import CrawlerProcess
from cse.CommentSpider import CommentSpider
from cse.__init__ import __version__
from cse.__init__ import __title__

def main(args=None):
    """The main routine."""

    # parse args
    parser = argparse.ArgumentParser(description='Crawl a specific news website for comments')
    parser.add_argument('--version', action='version', version=__title__ + __version__)
    parser.add_argument('-s','--sitemap', action='append', dest='sitemaps', default=[], help='sitemaps that should be crawled. can be used multiple times.')
    parser.add_argument('-u','--url', action='append', dest='urls', default=[],  help='specific URLs that should be crawled. can be used multiple times.')
    args = parser.parse_args()

    print("This is the main routine.")

    # for now just call the crawler/spider
    crawl(args)

def crawl(args=None):
    process = CrawlerProcess({
        'USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
        'LOG_LEVEL': 'DEBUG',
        'CONCURRENT_REQUESTS_PER_DOMAIN': 1
    })

    process.crawl(CommentSpider, sitemaps=args.sitemaps, urls=args.urls)
    process.start() # the script will block here until the crawling is finished

if __name__ == "__main__":
    main()


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

namespace SceneNavi.ROMHandler
{
    public interface ISceneTableEntry : IHeaderParent
    {
        ushort GetNumber();
        void SetNumber(ushort number);

        string GetDMAFilename();
        string GetName();

        uint GetSceneStartAddress();
        uint GetSceneEndAddress();

        bool IsValid();
        bool IsAllZero();

        byte[] GetData();
        List<HeaderLoader> GetSceneHeaders();
        bool IsInROM();
        bool IsNameExternal();
        HeaderLoader GetCurrentSceneHeader();
        void SetCurrentSceneHeader(HeaderLoader header);

        HeaderCommands.Actors GetActiveTransitionData();
        HeaderCommands.Actors GetActiveSpawnPointData();
        HeaderCommands.SpecialObjects GetActiveSpecialObjs();
        HeaderCommands.Waypoints GetActiveWaypoints();
        HeaderCommands.Collision GetActiveCollision();
        HeaderCommands.SettingsSoundScene GetActiveSettingsSoundScene();
        HeaderCommands.EnvironmentSettings GetActiveEnvSettings();

        void SaveTableEntry();
        void ReadScene(HeaderCommands.Rooms forcerooms = null);
    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Motel API Documentation</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					Motel API Documentation

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited

					Menu

					Globals

Motel API Documentation

Motel: Side-effect free data-fetching

Remote data dependencies

React is a function of state, so one of our jobs as developers is making that state available. Sometimes it's available locally; either hard-coded in the source or provided by the user. Other times it's available remotely; for example stored in the cloud. These remote data dependencies are essentially the "R" in CRUD.

The vacancy observer pattern

Typically, in order to know when to fetch remote data dependencies, we're forced to use lifecycle events, which are side effects. This lib uses the vacancy observer pattern to fetch remote data dependencies without side effects, thus keeping UI logic closer to the pure function of application state ideal.

Prerequisites

This lib has no dependencies or requirements of React.

The prerequisite is rather that you're using an approach where state is managed centrally, and where UI components are a pure function of application state. React+Redux and Elm are both examples of this.

Installation

npm install motel

API Documentation

Documentation is available under the docs/ folder of this repo, and also online.

Quick Example

In your main.js entry-point

Import or require this library.

import Motel from 'motel';
const Motel = require('motel');

Grab a reference to the "mount node" of your app.

const mountNode = document.querySelector('#root');

Initialize the motel instance. This exists for the lifetime of the app.

const vacancies = Motel.create();

Setup handler for all vacancies as they occur.

vacancies.observe('*', (url, dispatch) => {
  dispatch({ type: 'requested', url });
  const response = await fetcfh(url);
  const data = await response.json();
  dispatch({ type: 'received', url, data });
});

Capture the output of the above callbacks.

vacancies.subscribe(action => store.dipatch(action));

Start observing vacancies on the DOM subtree of the mount node.

vacancies.connect(mountNode);

In any React component

Simply render data vacancies on any component with a remote data dependency.

function UserProfile(props) {
  return (
    <div data-vacancy="/api/users/xxxxxxxx">
      ...content here...
    </div>
  );
}

Further examples

For more in-depth examples, refer to examples.md in this same repo.

				readme.md

						Globals

						Motel

						Dispatcher

						Motel<wbr>Options

						Pattern<wbr>Callback

						Pattern<wbr>Match

						Pattern<wbr>Observer

						Reg<wbr>Exp<wbr>Callback

						Reg<wbr>Exp<wbr>Observer

						Telemetry<wbr>Handler

						Wildcard<wbr>Callback

						Wildcard<wbr>Observer

						Exit<wbr>Promise

						Observer

						Telemetry<wbr>Level

						DEFAULT_<wbr>OPTIONS

						ERROR_<wbr>LEVELS

						ERROR_<wbr>THRESHOLD

						TELEMETRY_<wbr>LEVELS

						VACANCY_<wbr>ATTRIBUTE

						console<wbr>Telemetry<wbr>Handler

						create<wbr>Publish<wbr>Func

						process<wbr>Match

						tick

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Type alias with type parameter

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
@interface KVGameScene : SKScene

@end


text:
package org.apache.stratos.integration.tests.application;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.common.beans.application.ApplicationBean;
import org.apache.stratos.common.beans.policy.deployment.ApplicationPolicyBean;
import org.apache.stratos.integration.tests.RestConstants;
import org.apache.stratos.integration.tests.StratosTestServerManager;
import org.apache.stratos.integration.tests.TopologyHandler;
import org.apache.stratos.messaging.domain.application.Application;
import org.apache.stratos.messaging.domain.application.ApplicationStatus;
import org.apache.stratos.messaging.domain.application.ClusterDataHolder;
import org.apache.stratos.messaging.domain.instance.ClusterInstance;
import org.apache.stratos.messaging.domain.topology.Cluster;
import org.apache.stratos.messaging.domain.topology.Member;
import org.apache.stratos.messaging.domain.topology.Service;
import org.apache.stratos.messaging.message.receiver.application.ApplicationManager;
import org.apache.stratos.messaging.message.receiver.topology.TopologyManager;
import org.testng.annotations.Test;

import java.util.*;

import static junit.framework.Assert.*;

/**
 * This will handle the scale-up and scale-down of a particular cluster bursting test cases
 */
public class PartitionOneAfterAnotherClusterTest extends StratosTestServerManager {
    private static final Log log = LogFactory.getLog(SampleApplicationsTest.class);
    private static final String RESOURCES_PATH = "/partition-round-robin-cluster-test";

    @Test
    public void testDeployApplication() {
        try {
            log.info("-------------------------------Started Partition One after another test case-------------------------------");
            TopologyHandler topologyHandler = TopologyHandler.getInstance();
            String autoscalingPolicyId = "autoscaling-policy-3";

            boolean addedScalingPolicy = restClient.addEntity(RESOURCES_PATH + RestConstants.AUTOSCALING_POLICIES_PATH
                            + "/" + autoscalingPolicyId + ".json",
                    RestConstants.AUTOSCALING_POLICIES, RestConstants.AUTOSCALING_POLICIES_NAME);
            assertEquals(addedScalingPolicy, true);

            boolean addedC1 = restClient.addEntity(RESOURCES_PATH + RestConstants.CARTRIDGES_PATH + "/" + "c7.json",
                    RestConstants.CARTRIDGES, RestConstants.CARTRIDGES_NAME);
            assertEquals(addedC1, true);

            boolean addedN1 = restClient.addEntity(RESOURCES_PATH + RestConstants.NETWORK_PARTITIONS_PATH + "/" +
                            "network-partition-11.json",
                    RestConstants.NETWORK_PARTITIONS, RestConstants.NETWORK_PARTITIONS_NAME);
            assertEquals(addedN1, true);

            boolean addedDep = restClient.addEntity(RESOURCES_PATH + RestConstants.DEPLOYMENT_POLICIES_PATH + "/" +
                            "deployment-policy-5.json",
                    RestConstants.DEPLOYMENT_POLICIES, RestConstants.DEPLOYMENT_POLICIES_NAME);
            assertEquals(addedDep, true);

            boolean added = restClient.addEntity(RESOURCES_PATH + RestConstants.APPLICATIONS_PATH + "/" +
                            "single-cluster-scaling-test.json", RestConstants.APPLICATIONS,
                    RestConstants.APPLICATIONS_NAME);
            assertEquals(added, true);

            ApplicationBean bean = (ApplicationBean) restClient.getEntity(RestConstants.APPLICATIONS,
                    "single-cluster-scaling-test", ApplicationBean.class, RestConstants.APPLICATIONS_NAME);
            assertEquals(bean.getApplicationId(), "single-cluster-scaling-test");

            boolean addAppPolicy = restClient.addEntity(RESOURCES_PATH + RestConstants.APPLICATION_POLICIES_PATH + "/" +
                            "application-policy-4.json", RestConstants.APPLICATION_POLICIES,
                    RestConstants.APPLICATION_POLICIES_NAME);
            assertEquals(addAppPolicy, true);

            ApplicationPolicyBean policyBean = (ApplicationPolicyBean) restClient.getEntity(
                    RestConstants.APPLICATION_POLICIES,
                    "application-policy-4", ApplicationPolicyBean.class,
                    RestConstants.APPLICATION_POLICIES_NAME);

            //deploy the application
            String resourcePath = RestConstants.APPLICATIONS + "/" + "single-cluster-scaling-test" +
                    RestConstants.APPLICATIONS_DEPLOY + "/" + "application-policy-4";
            boolean deployed = restClient.deployEntity(resourcePath,
                    RestConstants.APPLICATIONS_NAME);
            assertEquals(deployed, true);

            //Application active handling
            topologyHandler.assertApplicationStatus(bean.getApplicationId(),
                    ApplicationStatus.Active);

            //Cluster active handling
            topologyHandler.assertClusterActivation(bean.getApplicationId());

            //Verifying whether members got created using round robin algorithm
            assertClusterWithRoundRobinAlgorithm(bean.getApplicationId());

            //Removing one member from cluster and check for auto healing

            boolean removedAuto = restClient.removeEntity(RestConstants.AUTOSCALING_POLICIES,
                    autoscalingPolicyId, RestConstants.AUTOSCALING_POLICIES_NAME);
            assertEquals(removedAuto, false);

            boolean removedNet = restClient.removeEntity(RestConstants.NETWORK_PARTITIONS,
                    "network-partition-11",
                    RestConstants.NETWORK_PARTITIONS_NAME);
            //Trying to remove the used network partition
            assertEquals(removedNet, false);

            boolean removedDep = restClient.removeEntity(RestConstants.DEPLOYMENT_POLICIES,
                    "deployment-policy-5", RestConstants.DEPLOYMENT_POLICIES_NAME);
            assertEquals(removedDep, false);

            //Un-deploying the application
            String resourcePathUndeploy = RestConstants.APPLICATIONS + "/" + "single-cluster-scaling-test" +
                    RestConstants.APPLICATIONS_UNDEPLOY;

            boolean unDeployed = restClient.undeployEntity(resourcePathUndeploy,
                    RestConstants.APPLICATIONS_NAME);
            assertEquals(unDeployed, true);

            boolean undeploy = topologyHandler.assertApplicationUndeploy("single-cluster-scaling-test");
            if (!undeploy) {
                //Need to forcefully undeploy the application
                log.info("Force undeployment is going to start for the [application] " + "single-cluster-scaling-test");

                restClient.undeployEntity(RestConstants.APPLICATIONS + "/" + "single-cluster-scaling-test" +
                        RestConstants.APPLICATIONS_UNDEPLOY + "?force=true", RestConstants.APPLICATIONS);

                boolean forceUndeployed = topologyHandler.assertApplicationUndeploy("single-cluster-scaling-test");
                assertEquals(String.format("Forceful undeployment failed for the application %s",
                        "single-cluster-scaling-test"), forceUndeployed, true);

            }

            boolean removed = restClient.removeEntity(RestConstants.APPLICATIONS, "single-cluster-scaling-test",
                    RestConstants.APPLICATIONS_NAME);
            assertEquals(removed, true);

            ApplicationBean beanRemoved = (ApplicationBean) restClient.getEntity(RestConstants.APPLICATIONS,
                    "single-cluster-scaling-test", ApplicationBean.class, RestConstants.APPLICATIONS_NAME);
            assertEquals(beanRemoved, null);

            boolean removedC1 = restClient.removeEntity(RestConstants.CARTRIDGES, "c7",
                    RestConstants.CARTRIDGES_NAME);
            assertEquals(removedC1, true);

            removedAuto = restClient.removeEntity(RestConstants.AUTOSCALING_POLICIES,
                    autoscalingPolicyId, RestConstants.AUTOSCALING_POLICIES_NAME);
            assertEquals(removedAuto, true);

            removedDep = restClient.removeEntity(RestConstants.DEPLOYMENT_POLICIES,
                    "deployment-policy-5", RestConstants.DEPLOYMENT_POLICIES_NAME);
            assertEquals(removedDep, true);

            removedNet = restClient.removeEntity(RestConstants.NETWORK_PARTITIONS,
                    "network-partition-11", RestConstants.NETWORK_PARTITIONS_NAME);
            assertEquals(removedNet, false);

            boolean removeAppPolicy = restClient.removeEntity(RestConstants.APPLICATION_POLICIES,
                    "application-policy-4", RestConstants.APPLICATION_POLICIES_NAME);
            assertEquals(removeAppPolicy, true);

            removedNet = restClient.removeEntity(RestConstants.NETWORK_PARTITIONS,
                    "network-partition-11", RestConstants.NETWORK_PARTITIONS_NAME);
            assertEquals(removedNet, true);

            log.info("-------------------------------Ended Partition one after another test case-------------------------------");

        } catch (Exception e) {
            log.error("An error occurred while handling  application bursting", e);
            assertTrue("An error occurred while handling  application bursting", false);
        }
    }

    /**
     * Assert application activation
     *
     * @param applicationName
     */
    private void assertClusterWithRoundRobinAlgorithm(String applicationName) {
        Application application = ApplicationManager.getApplications().getApplication(applicationName);
        assertNotNull(String.format("Application is not found: [application-id] %s",
                applicationName), application);

        Set<ClusterDataHolder> clusterDataHolderSet = application.getClusterDataRecursively();
        for (ClusterDataHolder clusterDataHolder : clusterDataHolderSet) {
            String serviceName = clusterDataHolder.getServiceType();
            String clusterId = clusterDataHolder.getClusterId();
            Service service = TopologyManager.getTopology().getService(serviceName);
            assertNotNull(String.format("Service is not found: [application-id] %s [service] %s",
                    applicationName, serviceName), service);

            Cluster cluster = service.getCluster(clusterId);
            assertNotNull(String.format("Cluster is not found: [application-id] %s [service] %s [cluster-id] %s",
                    applicationName, serviceName, clusterId), cluster);

            for (ClusterInstance instance : cluster.getInstanceIdToInstanceContextMap().values()) {
                List<String> partitionsUsedInMembers = new ArrayList<String>();
                Map<String, List<Long>> partitionIdToMembersMap = new HashMap<String, List<Long>>();
                for (Member member : cluster.getMembers()) {
                    String partitionId = member.getPartitionId();
                    if (!partitionIdToMembersMap.containsKey(partitionId)) {
                        List<Long> members = new ArrayList<Long>();
                        members.add(member.getInitTime());
                        partitionIdToMembersMap.put(partitionId, members);
                    } else {
                        partitionIdToMembersMap.get(partitionId).add(member.getInitTime());
                    }
                    if (!partitionsUsedInMembers.contains(partitionId)) {
                        partitionsUsedInMembers.add(partitionId);
                    }
                }
                String p1 = "network-partition-11-partition-1";
                String p2 = "network-partition-11-partition-2";
                List<Long> p1InitTime = partitionIdToMembersMap.get(p1);
                Collections.sort(p1InitTime);

                List<Long> p2InitTime = partitionIdToMembersMap.get(p2);
                Collections.sort(p2InitTime);

                List<Long> allInitTime = new ArrayList<Long>();
                allInitTime.addAll(p1InitTime);
                allInitTime.addAll(p2InitTime);
                Collections.sort(allInitTime);

                int p1Index = -1;
                int p2Index = -1;
                String previousPartition = null;
                for (int i = 0; i < allInitTime.size(); i++) {
                    if (previousPartition == null) {
                        if (p1InitTime.get(0) == allInitTime.get(i)) {
                            previousPartition = p1;
                            p1Index++;
                        } else if (p2InitTime.get(0) == allInitTime.get(i)) {
                            previousPartition = p2;
                            p2Index++;

                        }
                    } else if (previousPartition.equals(p1)) {
                        p2Index++;
                        previousPartition = p2;
                        assertEquals("Partition-2 doesn't not contain correct values in current " +
                                "iteration", allInitTime.get(i), p2InitTime.get(p2Index));
                        if (p1Index >= 0) {
                            assertEquals("Partition-1 doesn't not contain correct values in the " +
                                    "previous iteration", allInitTime.get(i - 1), p1InitTime.get(p1Index));
                            if (p1Index + 1 <= (p1InitTime.size() - 1) && i + 1 <= (allInitTime.size() - 1)) {
                                assertEquals("Partition-1 doesn't not contain correct " +
                                                "values in the next iteration",
                                        allInitTime.get(i + 1), p1InitTime.get(p1Index + 1));

                            }
                        }
                    } else {
                        p1Index++;
                        previousPartition = p1;
                        assertEquals("Partition-1 doesn't not contain correct values in current " +
                                "iteration", allInitTime.get(i), p1InitTime.get(p1Index));
                        if (p2Index >= 0) {
                            assertEquals("Partition-2 doesn't not contain correct values  " +
                                    "in the previous iteration", allInitTime.get(i - 1), p2InitTime.get(p2Index));
                            if ((p2Index + 1) <= (p2InitTime.size() - 1) && (i + 1) <= (allInitTime.size() - 1)) {
                                assertEquals("Partition-2 doesn't not contain correct values  " +
                                                "in the next iteration",
                                        allInitTime.get(i + 1), p2InitTime.get(p2Index + 1));
                            }
                        }
                    }

                }

            }

        }

    }
}


text:
int
main(int argc, char* argv[]) {
	if (argc < 2) {
		getUsage(argv[0]);
		std::cout << "-loop value: number of get images (default 100)" << std::endl;
		std::cout << "-delay value: delay between acquisition in addition to "
		             "framerate (default 66ms)"
		          << std::endl;
		return 1;
	}
	int loop = 100;
	if (cmdOptionExists(argc, argv, "-loop")) {
		loop = std::atoi(getCmdOption(argc, argv, "-loop").c_str());
	}
	int delay = 66;
	if (cmdOptionExists(argc, argv, "-delay")) {
		delay = std::atoi(getCmdOption(argc, argv, "-delay").c_str());
	}
	try {
		Camera cam(argc, argv);
		if (cmdOptionExists(argc, argv, "--info")) {
			std::cout << "(INFO) loop number: " << loop << std::endl;
			std::cout << "(INFO) delay: " << delay << std::endl;
		}
		std::cout << "(INFO) Test...START" << std::endl;
		cam.openDevice();
		cam.setResolution();
		cam.setFrameRate();
		cam.initMmapStreaming();
		cam.startStreaming();
		// Acquisition
		std::vector<std::unique_ptr<std::uint8_t>> buffers;
		for (int i = 0; i < loop; ++i) {
			buffers.push_back(cam.getImage());
			std::this_thread::sleep_for(std::chrono::milliseconds(1000 / cam.fps() + delay));
		}
		cam.stopStreaming();
		cam.unInitMmapStreaming();
		cam.closeDevice();
		std::cout << "(INFO) Test...DONE" << std::endl;

		std::cout << "(INFO) Dump result...START" << std::endl;
		// Dump to disk
		int i = 0;
		for (auto const& it : buffers) {
			try {
				std::stringstream filename;
				filename << "image_" << std::setw(3) << std::setfill('0') << i++ << ".ppm";
				cam.writeBuffer2PPM(filename.str(), cam.width(), cam.height(), it.get());
			} catch (const std::exception& e) {
				std::cerr << "(ERROR) loop " << i - 1 << ": " << e.what() << std::endl;
			}
		}
		buffers.clear();
		std::cout << "(INFO) Dump result...DONE" << std::endl;
	} catch (std::exception& e) {
		std::cerr << "(ERROR) " << e.what() << std::endl;
		return 2;
	}
	return 0;
}


text:
package simpledb;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;

public class ImputeMean extends Impute {

    private static final long serialVersionUID = 1L;

	private TableStats tableStats = null;

    /**
     * Impute missing data for a column by using the mean of the
     * non-missing elements of the same column. Thus, this method requires that
     * we store all of the child tuples in a buffer until the child is
     * exhausted. Alternately, we could try to make use of the histograms for the table.
     * @param child
     */
    public ImputeMean(Collection<String> dropFields, DbIterator child){
        super(dropFields, child);

        // get tablestats?
        int thisTableId = -1;
        Catalog catalog = Database.getCatalog();
        Iterator<Integer> it = catalog.tableIdIterator();
        while (it.hasNext()){
		int tableId = it.next();
		if (catalog.getTupleDesc(tableId).equals(td)){
			thisTableId = tableId;
			break;
		}
        }
        if (thisTableId != -1){
		String tablename = catalog.getTableName(thisTableId);
		this.tableStats = TableStats.getTableStats(tablename);
        }
    }

    public ImputeMean(DbIterator child) {
        this(null, child);
    }

    @Override
    public void rewind() throws DbException, TransactionAbortedException {
        child.rewind();
    }

    @Override
    protected Tuple fetchNext() throws DbException, TransactionAbortedException {
        if (this.tableStats == null){
            throw new DbException("TableStats not loaded.");
        }

        if (child.hasNext()){
            Tuple t = child.next();
            if (t.hasMissingFields()){
                return impute(t);
            } else {
                return t;
            }
        } else {
            return null;
        }
    }

    private Tuple impute(Tuple t) throws DbException {
        Tuple tc = new Tuple(t);

        for (int j : dropFieldsIndices){
            // Don't impute if not missing.
            if (!tc.getField(j).isMissing())
                continue;

            // set to mean
            tc.setField(j, new IntField((int) tableStats.estimateMean(j)));
        }

        return tc;
    }

    /*
     * Time is zero because we can compute in streaming fashion.
     * @see simpledb.Impute#getEstimatedTime(simpledb.ImputedPlan)
     */
	@Override
	public double getEstimatedTime(ImputedPlan subplan) {
		return 0;
	}

    /*
     * Can conceive this as O(n m_i)
     * @see simpledb.Impute#getEstimatedCost(ImputedPlan)
     */
	@Override
	public double getEstimatedPenalty(ImputedPlan subplan) {
		double numTuples = subplan.cardinality();
		Set<QualifiedName> dirtySet = subplan.getDirtySet();

		double sum = 0.0;
		for (QualifiedName qn : dirtySet){
			int qni = subplan.getPlan().getTupleDesc().fieldNameToIndex(qn);
			double var = subplan.getTableStats().estimateVariance(qni);
			sum += var;
		}
		return sum / numTuples;
	}

	public void setTableStats(ImputedPlan subplan){
		this.tableStats = subplan.getTableStats();
	}

}


text:
declare module "robotjs" {
  export default class robotjs {
    static keyTap(...args);
  }
}


text:
envvars=( DB_SERVER DB_PORT DB_ROOT_PASS DB_USER DB_USER_PASS ADMIN_USER ADMIN_PASS CERT_COUNTRY CERT_STATE CERT_CITY CERT_COMPANY DOMAIN)
for v in $envvars
do
	if [[ -z $$v ]]; then echo "$v is unset"; exit 1; fi
done

start() {
	service traffic_ops start
	exec tail -f /var/log/traffic_ops/traffic_ops.log
}

init() {
	local postinstall_input_file="postinstall-input.json"
	cat > "$postinstall_input_file" <<- ENDOFMESSAGE
{
  "/opt/traffic_ops/app/conf/production/database.conf":[
    {
      "Database type":"Pg",
      "config_var":"type"
    },
    {
      "Database name":"$DB_NAME",
      "config_var":"dbname"
    },
    {
      "Database server hostname IP or FQDN":"$DB_SERVER",
      "config_var":"hostname"
    },
    {
      "Database port number":"$DB_PORT",
      "config_var":"port"
    },
    {
      "Traffic Ops database user":"$DB_USER",
      "config_var":"user"
    },
    {
      "Traffic Ops database password":"$DB_USER_PASS",
      "config_var":"password",
      "hidden":"1"
    }
  ],
  "/opt/traffic_ops/app/db/dbconf.yml":[
    {
      "Database server root (admin) user":"postgres",
      "config_var":"pgUser"
    },
    {
      "Database server admin password":"$DB_ROOT_PASS",
      "config_var":"pgPassword",
      "hidden":"1"
    },
    {
      "Download Maxmind Database?":"yes",
      "config_var":"maxmind"
    }
  ],
  "/opt/traffic_ops/app/conf/cdn.conf":[
    {
      "Generate a new secret?":"yes",
      "config_var":"genSecret"
    },
    {
      "Port to serve on?": "443",
      "config_var": "port"
    },
    {
      "Number of workers?": "12",
      "config_var":"workers"
    },
    {
      "Traffic Ops url?": "https://$HOSTNAME",
      "config_var": "base_url"
    },
    {
      "Number of secrets to keep?":"1",
      "config_var":"keepSecrets"
    }
  ],
  "/opt/traffic_ops/app/conf/ldap.conf":[
    {
      "Do you want to set up LDAP?":"no",
      "config_var":"setupLdap"
    },
    {
      "LDAP server hostname":"",
      "config_var":"host"
    },
    {
      "LDAP Admin DN":"",
      "config_var":"admin_dn"
    },
    {
      "LDAP Admin Password":"",
      "config_var":"admin_pass",
      "hidden":"1"
    },
    {
      "LDAP Search Base":"",
      "config_var":"search_base"
    }
  ],
  "/opt/traffic_ops/install/data/json/users.json":[
    {
      "Administration username for Traffic Ops":"$ADMIN_USER",
      "config_var":"tmAdminUser"
    },
    {
      "Password for the admin user":"$ADMIN_PASS",
      "config_var":"tmAdminPw",
      "hidden":"1"
    }
  ],
  "/opt/traffic_ops/install/data/profiles/":[
    {
      "Add custom profiles?":"no",
      "config_var":"custom_profiles"
    }
  ],
  "/opt/traffic_ops/install/data/json/openssl_configuration.json":[
    {
      "Do you want to generate a certificate?":"yes",
      "config_var":"genCert"
    },
    {
      "Country Name (2 letter code)":"$CERT_COUNTRY",
      "config_var":"country"
    },
    {
      "State or Province Name (full name)":"$CERT_STATE",
      "config_var":"state"
    },
    {
      "Locality Name (eg, city)":"$CERT_CITY",
      "config_var":"locality"
    },
    {
      "Organization Name (eg, company)":"$CERT_COMPANY",
      "config_var":"company"
    },
    {
      "Organizational Unit Name (eg, section)":"",
      "config_var":"org_unit"
    },
    {
      "Common Name (eg, your name or your server's hostname)":"$HOSTNAME",
      "config_var":"common_name"
    },
    {
      "RSA Passphrase":"passphrase",
      "config_var":"rsaPassword",
      "hidden":"1"
    }
  ],
  "/opt/traffic_ops/install/data/json/profiles.json":[
    {
      "Traffic Ops url":"https://$HOSTNAME",
      "config_var":"tm.url"
    },
    {
      "Human-readable CDN Name.  (No whitespace, please)":"cdn",
      "config_var":"cdn_name"
    },
    {
      "Health Polling Interval (milliseconds)":"8000",
      "config_var":"health_polling_int"
    },
    {
      "DNS sub-domain for which your CDN is authoritative":"$HOSTNAME.$DOMAIN",
      "config_var":"dns_subdomain"
    },
    {
      "TLD SOA admin":"traffic_ops",
      "config_var":"soa_admin"
    },
    {
      "TrafficServer Drive Prefix":"/dev/ram",
      "config_var":"driver_prefix"
    },
    {
      "TrafficServer RAM Drive Prefix":"/dev/ram",
      "config_var":"ram_drive_prefix"
    },
    {
      "TrafficServer RAM Drive Letters (comma separated)":"1",
      "config_var":"ram_drive_letters"
    },
    {
      "Health Threshold Load Average":"25",
      "config_var":"health_thresh_load_avg"
    },
    {
      "Health Threshold Available Bandwidth in Kbps":"1750000",
      "config_var":"health_thresh_kbps"
    },
    {
      "Traffic Server Health Connection Timeout (milliseconds)":"2000",
      "config_var":"health_connect_timeout"
    }
  ]
}
	ENDOFMESSAGE

	# TODO determine if term, user are necessary
	export TERM=xterm && export USER=root && /opt/traffic_ops/install/bin/postinstall -cfile "$postinstall_input_file"

	# Only listen on IPv4, not IPv6, because Docker doesn't provide a v6 interface by default. See http://mojolicious.org/perldoc/Mojo/Server/Daemon#listen
	sed -i -e 's#https://\[::\]#https://127\.0\.0\.1#' /opt/traffic_ops/app/conf/cdn.conf
	service traffic_ops restart

	TRAFFIC_OPS_URI="https://localhost"

	TMP_TO_COOKIE="$(curl -v -s -k -X POST --data '{ "u":"'"$ADMIN_USER"'", "p":"'"$ADMIN_PASS"'" }' $TRAFFIC_OPS_URI/api/1.2/user/login 2>&1 | grep 'Set-Cookie' | sed -e 's/.*mojolicious=\(.*\); expires.*/\1/')"
	echo "Got cookie: $TMP_TO_COOKIE"

	TMP_DOMAIN=$DOMAIN
	sed -i -- "s/{{.Domain}}/$TMP_DOMAIN/g" /profile.origin.traffic_ops
	echo "Got domain: $TMP_DOMAIN"

	echo "Importing origin"
	curl -v -k -X POST -H "Cookie: mojolicious=$TMP_TO_COOKIE" -F "filename=profile.origin.traffic_ops" -F "profile_to_import=@/profile.origin.traffic_ops" $TRAFFIC_OPS_URI/profile/doImport

	curl -v -k -X POST -H "Cookie: mojolicious=$TMP_TO_COOKIE" --data-urlencode "division.name=East" $TRAFFIC_OPS_URI/division/create
	TMP_DIVISION_ID="$(curl -s -k -X GET -H "Cookie: mojolicious=$TMP_TO_COOKIE" $TRAFFIC_OPS_URI/region/add | grep --color=never -oE "<option value=\"[0-9]+\">East</option>" | grep --color=never -oE "[0-9]+")"
	echo "Got division ID: $TMP_DIVISION_ID"

	curl -v -k -X POST -H "Cookie: mojolicious=$TMP_TO_COOKIE" --data-urlencode "region.name=Eastish" --data-urlencode "region.division_id=$TMP_DIVISION_ID" $TRAFFIC_OPS_URI/region/create
	TMP_REGION_ID="$(curl -s -k -X GET -H "Cookie: mojolicious=$TMP_TO_COOKIE" $TRAFFIC_OPS_URI/api/1.2/regions.json | python -c 'import json,sys;obj=json.load(sys.stdin);match=[x["id"] for x in obj["response"] if x["name"]=="Eastish"]; print match[0]')"
	echo "Got region ID: $TMP_REGION_ID"

	TMP_CACHEGROUP_TYPE="$(curl -s -k -X GET -H "Cookie: mojolicious=$TMP_TO_COOKIE" $TRAFFIC_OPS_URI/api/1.2/types.json | python -c 'import json,sys;obj=json.load(sys.stdin);match=[x["id"] for x in obj["response"] if x["name"]=="MID_LOC"]; print match[0]')"
	echo "Got cachegroup type ID: $TMP_CACHEGROUP_TYPE"

	curl -v -k -X POST -H "Cookie: mojolicious=$TMP_TO_COOKIE" --data-urlencode "cg_data.name=mid-east" --data-urlencode "cg_data.short_name=east" --data-urlencode "cg_data.latitude=0" --data-urlencode "cg_data.longitude=0" --data-urlencode "cg_data.parent_cachegroup_id=-1" --data-urlencode "cg_data.type=$TMP_CACHEGROUP_TYPE" $TRAFFIC_OPS_URI/cachegroup/create
	TMP_CACHEGROUP_ID="$(curl -s -k -X GET -H "Cookie: mojolicious=$TMP_TO_COOKIE" $TRAFFIC_OPS_URI/api/1.2/cachegroups.json | python -c 'import json,sys;obj=json.load(sys.stdin);match=[x["id"] for x in obj["response"] if x["name"]=="mid-east"]; print match[0]')"
	echo "Got cachegroup ID: $TMP_CACHEGROUP_ID"

	TMP_CACHEGROUP_EDGE_TYPE="$(curl -s -k -X GET -H "Cookie: mojolicious=$TMP_TO_COOKIE" $TRAFFIC_OPS_URI/api/1.2/types.json | python -c 'import json,sys;obj=json.load(sys.stdin);match=[x["id"] for x in obj["response"] if x["name"]=="EDGE_LOC"]; print match[0]')"
	echo "Got cachegroup type ID: $TMP_CACHEGROUP_EDGE_TYPE"

	curl -v -k -X POST -H "Cookie: mojolicious=$TMP_TO_COOKIE" --data-urlencode "cg_data.name=edge-east" --data-urlencode "cg_data.short_name=eeast" --data-urlencode "cg_data.latitude=0" --data-urlencode "cg_data.longitude=0" --data-urlencode "cg_data.parent_cachegroup_id=$TMP_CACHEGROUP_ID" --data-urlencode "cg_data.type=$TMP_CACHEGROUP_EDGE_TYPE" $TRAFFIC_OPS_URI/cachegroup/create
	TMP_CACHEGROUP_EDGE_ID="$(curl -s -k -X GET -H "Cookie: mojolicious=$TMP_TO_COOKIE" $TRAFFIC_OPS_URI/api/1.2/cachegroups.json | python -c 'import json,sys;obj=json.load(sys.stdin);match=[x["id"] for x in obj["response"] if x["name"]=="edge-east"]; print match[0]')"
	echo "Got cachegroup edge ID: $TMP_CACHEGROUP_EDGE_ID"

	curl -v -k -X POST -H "Cookie: mojolicious=$TMP_TO_COOKIE" --data-urlencode "location.name=plocation-nyc-1" --data-urlencode "location.short_name=nyc" --data-urlencode "location.address=1 Main Street" --data-urlencode "location.city=nyc" --data-urlencode "location.state=NY" --data-urlencode "location.zip=12345" --data-urlencode "location.poc=" --data-urlencode "location.phone=" --data-urlencode "location.email=no@no.no" --data-urlencode "location.comments=" --data-urlencode "location.region=$TMP_REGION_ID" $TRAFFIC_OPS_URI/phys_location/create

	echo "INITIALIZED=1" >> /etc/environment
}

source /etc/environment
if [ -z "$INITIALIZED" ]; then init; fi
start


text:
<?xml version="1.0" encoding="UTF-8"?>
<Export generator="Cache" version="25">
<Class name="iKnow.SetAnalysis.SetMembers">
<Super>%Persistent</Super>
<TimeCreated>62895,76071.431432</TimeCreated>

<Property name="SetId">
<Type>iKnow.SetAnalysis.Sets</Type>
</Property>

<Property name="Member">
<Type>%String</Type>
</Property>

<Property name="Score">
<Type>%Integer</Type>
</Property>

<Property name="Frequency">
<Type>%Integer</Type>
</Property>

<Property name="ScoreSets">
<Type>%String</Type>
<Parameter name="MAXLEN" value="1000"/>
</Property>

<Property name="Approved">
<Type>%Boolean</Type>
</Property>

<Index name="idxSet">
<Properties>SetId</Properties>
</Index>

<Storage name="Default">
<Type>%Library.CacheStorage</Type>
<DataLocation>^iKnow.SetAnalysis.SetMembersD</DataLocation>
<DefaultData>SetMembersDefaultData</DefaultData>
<IdLocation>^iKnow.SetAnalysis.SetMembersD</IdLocation>
<IndexLocation>^iKnow.SetAnalysis.SetMembersI</IndexLocation>
<StreamLocation>^iKnow.SetAnalysis.SetMembersS</StreamLocation>
<ExtentSize>100000</ExtentSize>
<Data name="SetMembersDefaultData">
<Value name="1">
<Value>%%CLASSNAME</Value>
</Value>
<Value name="2">
<Value>Set</Value>
</Value>
<Value name="3">
<Value>Member</Value>
</Value>
<Value name="4">
<Value>SetId</Value>
</Value>
<Value name="5">
<Value>MemberId</Value>
</Value>
<Value name="6">
<Value>Score</Value>
</Value>
<Value name="7">
<Value>Frequency</Value>
</Value>
<Value name="8">
<Value>ScoreSets</Value>
</Value>
</Data>
</Storage>
</Class>
</Export>


text:
// $Id: nAxisGeneratorCartesianPos.hpp,v 1.1.1.1 2003/12/02 20:32:06 kgadeyne Exp $
// Copyright (C) 2003 Klaas Gadeyne <klaas.gadeyne@mech.kuleuven.ac.be>
//                    Wim Meeussen  <wim.meeussen@mech.kuleuven.ac.be>
// Copyright (C) 2010 Ruben Smits <ruben.smits@mech.kuleuven.be>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//

#ifndef __CARTESIAN_GENERATOR_POS_H__
#define __CARTESIAN_GENERATOR_POS_H__

#include <rtt/TaskContext.hpp>
#include <rtt/Port.hpp>
#include <rtt/os/TimeService.hpp>

#include <geometry_msgs/typekit/Types.h>
#include <tf_conversions/tf_kdl.h>

#include <kdl/velocityprofile_trap.hpp>
#include <kdl/kdl.hpp>
#include <kdl/frames.hpp>

#include <string>

namespace MotionControl
{
    /**
     * This class implements a TaskContext that creates a path in
     * Cartesian space between the current cartesian position and a
     * new desired cartesian position. It uses trapezoidal
     * velocity-profiles for every dof using a maximum velocity and a
     * maximum acceleration. It generates frame and twist setpoints
     * which can be used by MotionControl::CartesianControllerPos,
     * MotionControl::CartesianControllerPosVel or MotionControl::CartesianControllerVel.
     *
     */
    class CartesianGeneratorPos : public RTT::TaskContext
    {
    public:
        /**
         * Constructor of the class.
         *
         * @param name name of the TaskContext
         */
        CartesianGeneratorPos(std::string name);
        virtual ~CartesianGeneratorPos();

        virtual bool configureHook();
        virtual bool startHook();
        virtual void updateHook();
        virtual void stopHook();
        virtual void cleanupHook();

    private:
        bool moveTo(geometry_msgs::Pose pose, double time=0);
        void resetPosition();

      KDL::Frame                        m_traject_end, m_traject_begin;
      KDL::Frame                        m_position_desi_local;
      KDL::Twist                        m_velocity_desi_local, m_velocity_begin_end, m_velocity_delta;
      KDL::Twist                        m_maximum_velocity, m_maximum_acceleration;
      geometry_msgs::Twist              m_gm_maximum_velocity, m_gm_maximum_acceleration;

      std::vector<KDL::VelocityProfile_Trap>      m_motion_profile;
      RTT::os::TimeService::ticks                     m_time_begin;
      RTT::os::TimeService::Seconds                   m_time_passed;
      double                                      m_max_duration;

      bool                                        m_is_moving,m_once;
      std::string								  move_started_event;
      std::string								  move_finished_event;

    protected:
      /// Dataport containing the current measured end-effector
      /// frame, shared with MotionControl::CartesianSensor
      RTT::InputPort< geometry_msgs::Pose >   m_position_meas_port;

      /// Dataport containing the current desired end-effector
      /// frame, shared with MotionControl::CartesianControllerPos,
      /// MotionControl::CartesianControllerPosVel
      RTT::OutputPort< geometry_msgs::Pose >  m_position_desi_port;
      /// Dataport containing the current desired end-effector
      /// twist, shared with MotionControl::CartesianControllerPosVel,
      /// MotionControl::CartesianControllerVel
      RTT::OutputPort< geometry_msgs::Twist >  m_velocity_desi_port;

      RTT::OutputPort<std::string> event_port;

  }; // class
} //namespace

#include <rtt/Component.hpp>
ORO_CREATE_COMPONENT( MotionControl::CartesianGeneratorPos )

#endif // __CARTESIAN_GENERATOR_POS_H__


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Definition of new Model -->
<model name="wf1:workflowmodel"
    xmlns="http://www.alfresco.org/model/dictionary/1.0">

    <!-- Optional meta-data about the model -->
    <description>wf1 sample model</description>
    <author>Ernesto Revilla</author>
    <version>1.0</version>

    <!-- Imports are required to allow references to definitions in other models -->
    <imports>
        <import uri="http://www.alfresco.org/model/dictionary/1.0"
            prefix="d" />
        <import uri="http://www.alfresco.org/model/bpm/1.0"
            prefix="bpm" />
    </imports>

    <!-- Introduction of new namespaces defined by this model -->
    <namespaces>
        <namespace uri="http://www.erny.org/model/wf1/1.0"
            prefix="wf1" />
    </namespaces>

    <types>
        <!--  Start form -->
        <type name="wf1:start">
            <parent>bpm:startTask</parent>
            <properties>
                <property name="wf1:country">
                    <type>d:text</type>
                    <mandatory>true</mandatory>
                    <multiple>false</multiple>
                </property>
                <property name="wf1:initiator">
                    <type>d:text</type>
                    <mandatory>true</mandatory>
                    <multiple>false</multiple>
                </property>
                <property name="wf1:opportunityName">
                    <type>d:text</type>
                    <mandatory>true</mandatory>
                    <multiple>false</multiple>
                </property>
            </properties>
        </type>

        <!-- Opportunity form -->
        <type name="wf1:fill_data">
            <parent>bpm:workflowTask</parent>
            <properties>
            </properties>
        </type>

        <!-- Approve form -->
        <type name="wf1:approve">
            <parent>bpm:workflowTask</parent>
            <properties>
            </properties>
        </type>

        <!-- Legal approve form -->
        <type name="wf1:approve_legal">
            <parent>bpm:workflowTask</parent>
            <properties>
            </properties>
        </type>

        <!-- Rework form -->
        <type name="wf1:rework">
            <parent>bpm:workflowTask</parent>
            <properties>
            </properties>
        </type>

        <!-- Decide rework form -->
        <type name="wf1:decide_rework">
            <parent>bpm:workflowTask</parent>
            <properties>
            </properties>
        </type>

        <!-- Fill legal data form -->
        <type name="wf1:fill_legal_data">
            <parent>bpm:workflowTask</parent>
            <properties>
            </properties>
        </type>

        <!-- Approve legal data form -->
        <type name="wf1:approve_legal_data">
            <parent>bpm:workflowTask</parent>
            <properties>
            </properties>
        </type>

        <!-- CEO Approve data form -->
        <type name="wf1:ceo_approve">
            <parent>bpm:workflowTask</parent>
            <properties>
            </properties>
        </type>

        <!-- Upload signed document form -->
        <type name="wf1:upload_document">
            <parent>bpm:workflowTask</parent>
            <properties>
            </properties>
        </type>

    </types>

</model>


text:
<?php
/* @var $this ManageStocksController */
/* @var $model Stock */

$this->breadcrumbs=array(
	'Stocks'=>array('index'),
	'Create',
);

$this->menu=array(
	array('label'=>'List Stock', 'url'=>array('index')),
	array('label'=>'Manage Stock', 'url'=>array('admin')),
);
?>

Create Stock

<?php $this->renderPartial('_form', array('model'=>$model)); ?>


text:
package dependency

import (
	"errors"
	"fmt"
)

// Parse a string into a Dependency object. The input should look something
// like "foo, bar | baz".
func Parse(in string) (*Dependency, error) {
	ibuf := Input{Index: 0, Data: in}
	dep := &Dependency{Relations: []Relation{}}
	err := parseDependency(&ibuf, dep)
	if err != nil {
		return nil, err
	}
	return dep, nil
}

// Input Model {{{

/*
 */
type Input struct {
	Data  string
	Index int
}

/*
 */
func (i *Input) Peek() byte {
	if (i.Index) >= len(i.Data) {
		return 0
	}
	return i.Data[i.Index]
}

/*
 */
func (i *Input) Next() byte {
	chr := i.Peek()
	i.Index++
	return chr
}

// }}}

// Parse Helpers {{{

/* */
func eatWhitespace(input *Input) {
	for {
		peek := input.Peek()
		switch peek {
		case '\r', '\n', ' ', '\t':
			input.Next()
			continue
		}
		break
	}
}

// }}}

// Dependency Parser {{{

/* */
func parseDependency(input *Input, ret *Dependency) error {
	eatWhitespace(input)

	for {
		peek := input.Peek()
		switch peek {
		case 0: /* EOF, yay */
			return nil
		case ',': /* Next relation set */
			input.Next()
			eatWhitespace(input)
			continue
		}
		err := parseRelation(input, ret)
		if err != nil {
			return err
		}
	}
}

// }}}

// Relation Parser {{{

/* */
func parseRelation(input *Input, dependency *Dependency) error {
	eatWhitespace(input) /* Clean out leading whitespace */

	ret := &Relation{Possibilities: []Possibility{}}

	for {
		peek := input.Peek()
		switch peek {
		case 0, ',': /* EOF, or done with this relation! yay */
			dependency.Relations = append(dependency.Relations, *ret)
			return nil
		case '|': /* Next Possi */
			input.Next()
			eatWhitespace(input)
			continue
		}
		err := parsePossibility(input, ret)
		if err != nil {
			return err
		}
	}
}

// }}}

// Possibility Parser {{{

/* */
func parsePossibility(input *Input, relation *Relation) error {
	eatWhitespace(input) /* Clean out leading whitespace */

	peek := input.Peek()
	if peek == '$' {
		/* OK, nice. So, we've got a substvar. Let's eat it. */
		return parseSubstvar(input, relation)
	}

	/* Otherwise, let's punt and build it up ourselves. */

	ret := &Possibility{
		Name:          "",
		Version:       nil,
		Architectures: &ArchSet{Architectures: []Arch{}},
		StageSets:     []StageSet{},
		Substvar:      false,
	}

	for {
		peek := input.Peek()
		switch peek {
		case ':':
			err := parseMultiarch(input, ret)
			if err != nil {
				return err
			}
			continue
		case ' ':
			err := parsePossibilityControllers(input, ret)
			if err != nil {
				return err
			}
			continue
		case ',', '|', 0: /* I'm out! */
			if ret.Name == "" {
				return errors.New("No package name in Possibility")
			}
			relation.Possibilities = append(relation.Possibilities, *ret)
			return nil
		}
		/* Not a control, let's append */
		ret.Name += string(input.Next())
	}
}

func parseSubstvar(input *Input, relation *Relation) error {
	eatWhitespace(input)
	input.Next() /* Assert ch == '$' */
	input.Next() /* Assert ch == '{' */

	ret := &Possibility{
		Name:     "",
		Version:  nil,
		Substvar: true,
	}

	for {
		peek := input.Peek()
		switch peek {
		case 0:
			return errors.New("Oh no. Reached EOF before substvar finished")
		case '}':
			input.Next()
			relation.Possibilities = append(relation.Possibilities, *ret)
			return nil
		}
		ret.Name += string(input.Next())
	}
}

/* */
func parseMultiarch(input *Input, possi *Possibility) error {
	input.Next() /* mandated to be a : */
	name := ""
	for {
		peek := input.Peek()
		switch peek {
		case ',', '|', 0, ' ', '(', '[', '<':
			arch, err := ParseArch(name)
			if err != nil {
				return err
			}
			possi.Arch = arch
			return nil
		default:
			name += string(input.Next())
		}
	}
	return nil
}

/* */
func parsePossibilityControllers(input *Input, possi *Possibility) error {
	for {
		eatWhitespace(input) /* Clean out leading whitespace */
		peek := input.Peek()
		switch peek {
		case ',', '|', 0:
			return nil
		case '(':
			if possi.Version != nil {
				return errors.New(
					"Only one Version relation per Possibility, please!",
				)
			}
			err := parsePossibilityVersion(input, possi)
			if err != nil {
				return err
			}
			continue
		case '[':
			if len(possi.Architectures.Architectures) != 0 {
				return errors.New(
					"Only one Arch relation per Possibility, please!",
				)
			}
			err := parsePossibilityArchs(input, possi)
			if err != nil {
				return err
			}
			continue
		case '<':
			err := parsePossibilityStageSet(input, possi)
			if err != nil {
				return err
			}
			continue
		}
		return fmt.Errorf("Trailing garbage in a Possibility: %c", peek)
	}
	return nil
}

/* */
func parsePossibilityVersion(input *Input, possi *Possibility) error {
	eatWhitespace(input)
	input.Next() /* mandated to be ( */
	// assert ch == '('
	version := VersionRelation{}

	err := parsePossibilityOperator(input, &version)
	if err != nil {
		return err
	}

	err = parsePossibilityNumber(input, &version)
	if err != nil {
		return err
	}

	input.Next() /* OK, let's tidy up */
	// assert ch == ')'

	possi.Version = &version
	return nil
}

/* */
func parsePossibilityOperator(input *Input, version *VersionRelation) error {
	eatWhitespace(input)
	leader := input.Next() /* may be 0 */

	if leader == '=' {
		/* Great, good enough. */
		version.Operator = "="
		return nil
	}

	/* This is always one of:
	 * >=, <=, <<, >> */
	secondary := input.Next()
	if leader == 0 || secondary == 0 {
		return errors.New("Oh no. Reached EOF before Operator finished")
	}

	operator := string([]rune{rune(leader), rune(secondary)})

	switch operator {
	case ">=", "<=", "<<", ">>":
		version.Operator = operator
		return nil
	}

	return fmt.Errorf(
		"Unknown Operator in Possibility Version modifier: %s",
		operator,
	)

}

/* */
func parsePossibilityNumber(input *Input, version *VersionRelation) error {
	eatWhitespace(input)
	for {
		peek := input.Peek()
		switch peek {
		case 0:
			return errors.New("Oh no. Reached EOF before Number finished")
		case ')':
			return nil
		}
		version.Number += string(input.Next())
	}
}

/* */
func parsePossibilityArchs(input *Input, possi *Possibility) error {
	eatWhitespace(input)
	input.Next() /* Assert ch == '[' */

	for {
		peek := input.Peek()
		switch peek {
		case 0:
			return errors.New("Oh no. Reached EOF before Arch list finished")
		case ']':
			input.Next()
			return nil
		}

		err := parsePossibilityArch(input, possi)
		if err != nil {
			return err
		}
	}
}

/* */
func parsePossibilityArch(input *Input, possi *Possibility) error {
	eatWhitespace(input)
	arch := ""

	// Exclamation marks may be prepended to each of the names. (It is not
	// permitted for some names to be prepended with exclamation marks while
	// others aren't.)
	hasNot := input.Peek() == '!'
	if hasNot {
		input.Next() // '!'
	}
	if len(possi.Architectures.Architectures) == 0 {
		possi.Architectures.Not = hasNot
	} else if possi.Architectures.Not != hasNot {
		return errors.New("Either the entire arch list needs negations, or none of it does -- no mix and match :/")
	}

	for {
		peek := input.Peek()
		switch peek {
		case 0:
			return errors.New("Oh no. Reached EOF before Arch list finished")
		case '!':
			return errors.New("You can only negate whole blocks :(")
		case ']', ' ': /* Let our parent deal with both of these */
			archObj, err := ParseArch(arch)
			if err != nil {
				return err
			}
			possi.Architectures.Architectures = append(
				possi.Architectures.Architectures,
				*archObj,
			)
			return nil
		}
		arch += string(input.Next())
	}
}

/* */
func parsePossibilityStageSet(input *Input, possi *Possibility) error {
	eatWhitespace(input)
	input.Next() /* Assert ch == '<' */

	stageSet := StageSet{}
	for {
		peek := input.Peek()
		switch peek {
		case 0:
			return errors.New("Oh no. Reached EOF before StageSet finished")
		case '>':
			input.Next()
			possi.StageSets = append(possi.StageSets, stageSet)
			return nil
		}

		err := parsePossibilityStage(input, &stageSet)
		if err != nil {
			return err
		}
	}
}

/* */
func parsePossibilityStage(input *Input, stageSet *StageSet) error {
	eatWhitespace(input)

	stage := Stage{}
	for {
		peek := input.Peek()
		switch peek {
		case 0:
			return errors.New("Oh no. Reached EOF before Stage finished")
		case '!':
			input.Next()
			if stage.Not {
				return errors.New("Double-negation (!!) of a single Stage is not permitted :(")
			}
			stage.Not = !stage.Not
		case '>', ' ': /* Let our parent deal with both of these */
			stageSet.Stages = append(stageSet.Stages, stage)
			return nil
		}
		stage.Name += string(input.Next())
	}
}

// }}}

// vim: foldmethod=marker


text:
//
// AppShell.xaml.cpp
// Implementation of the AppShell class
//

#include "pch.h"
#include "BasicPage.xaml.h"
#include "BasicSubPage.xaml.h"
#include "CommandBarPage.xaml.h"
#include "DrillInPage.xaml.h"
#include "NavMenuItem.h"
#include "NavMenuListView.h"
#include "AppShell.xaml.h"

using namespace Platform;
using namespace Windows::UI::Core;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

using namespace NavigationMenuSample::Controls;

namespace NavigationMenuSample
{
    AppShell^ AppShell::_current;

    /// <summary>
    /// Initializes a new instance of the AppShell, sets the static 'Current' reference,
    /// adds callbacks for Back requests and changes in the SplitView's DisplayMode, and
    /// provide the nav menu list with the data to display.
    /// </summary>
    AppShell::AppShell()
    {
        InitializeComponent();

        Loaded += ref new Windows::UI::Xaml::RoutedEventHandler(this, &AppShell::OnLoaded);

		RootSplitView->RegisterPropertyChangedCallback(
			SplitView::DisplayModeProperty,
			ref new DependencyPropertyChangedCallback(this, &AppShell::RootSplitViewDisplayModeChangedCallback));

        SystemNavigationManager::GetForCurrentView()->BackRequested +=
            ref new EventHandler<Windows::UI::Core::BackRequestedEventArgs^>(this, &AppShell::SystemNavigationManager_BackRequested);

        // Declare the top level nav items
        navlist = ref new Vector<NavMenuItem^>();
        navlist->Append(
            ref new NavMenuItem (
                "Basic Page",
                Symbol::Contact,
                TypeName(Views::BasicPage::typeid)));
        navlist->Append(
            ref new NavMenuItem (
                "CommandBar Page",
                Symbol::Edit,
                TypeName(Views::CommandBarPage::typeid)));
        navlist->Append(
            ref new NavMenuItem(
                "Drill In Page",
                Symbol::Favorite,
                TypeName(Views::DrillInPage::typeid)));

        NavMenuList->ItemsSource = navlist;
    }

    Frame^ AppShell::AppFrame::get()
    {
        return frame;
    }

    void AppShell::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs ^e)
    {
        AppShell::_current = this;

        TogglePaneButton->Focus(Windows::UI::Xaml::FocusState::Programmatic);
    }

    /// <summary>
    /// Default keyboard focus movement for any unhandled keyboarding
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void AppShell::AppShell_KeyDown(Object^ sender, KeyRoutedEventArgs^ e)
    {
        FocusNavigationDirection direction = FocusNavigationDirection::None;
        switch (e->Key)
        {
        case Windows::System::VirtualKey::Left:
        case Windows::System::VirtualKey::GamepadDPadLeft:
        case Windows::System::VirtualKey::GamepadLeftThumbstickLeft:
        case Windows::System::VirtualKey::NavigationLeft:
            direction = FocusNavigationDirection::Left;
            break;
        case Windows::System::VirtualKey::Right:
        case Windows::System::VirtualKey::GamepadDPadRight:
        case Windows::System::VirtualKey::GamepadLeftThumbstickRight:
        case Windows::System::VirtualKey::NavigationRight:
            direction = FocusNavigationDirection::Right;
            break;

        case Windows::System::VirtualKey::Up:
        case Windows::System::VirtualKey::GamepadDPadUp:
        case Windows::System::VirtualKey::GamepadLeftThumbstickUp:
        case Windows::System::VirtualKey::NavigationUp:
            direction = FocusNavigationDirection::Up;
            break;

        case Windows::System::VirtualKey::Down:
        case Windows::System::VirtualKey::GamepadDPadDown:
        case Windows::System::VirtualKey::GamepadLeftThumbstickDown:
        case Windows::System::VirtualKey::NavigationDown:
            direction = FocusNavigationDirection::Down;
            break;
        }

        if (direction != FocusNavigationDirection::None)
        {
            Control^ control = dynamic_cast<Control^>(FocusManager::FindNextFocusableElement(direction));
            if (control != nullptr)
            {
                control->Focus(Windows::UI::Xaml::FocusState::Programmatic);
            }
        }
    }

    void AppShell::SystemNavigationManager_BackRequested(Object^ sender, Windows::UI::Core::BackRequestedEventArgs^ e)
    {
        if (!e->Handled && AppFrame->CanGoBack)
        {
            e->Handled = true;
            AppFrame->GoBack();
        }
    }

    /// <summary>
    /// Navigate to the Page for the selected <paramref name="listViewItem"/>.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="listViewItem"></param>
    void AppShell::NavMenuList_ItemInvoked(Object^ sender, ListViewItem^ listViewItem)
    {
        auto item = (NavMenuItem^)((NavMenuListView^)(sender))->ItemFromContainer(listViewItem);

        if (item != nullptr)
        {
            if (item->DestPage.Name != AppFrame->CurrentSourcePageType.Name)
            {
                AppFrame->Navigate(item->DestPage, item->Arguments);
            }
        }
    }

    void AppShell::OnNavigatingToPage(Object^ sender, NavigatingCancelEventArgs^ e)
    {
        if (e->NavigationMode == NavigationMode::Back)
        {
            NavMenuItem^ item = nullptr;
            for (auto p : navlist)
            {
                if (p->DestPage.Name == e->SourcePageType.Name)
                {
                    item = p;
                    break;
                }
            }

            if (item == nullptr && AppFrame->BackStackDepth > 0)
            {
                // In cases where a page drills into sub-pages then we'll highlight the most recent
                // navigation menu item that appears in the BackStack
                for (auto entry : AppFrame->BackStack)
                {
                    Object^ p = nullptr;
                    for (auto p : navlist)
                    {
                        if (p->DestPage.Name == entry->SourcePageType.Name)
                        {
                            item = p;
                            break;
                        }
                    }
                }
            }

            auto container = (ListViewItem^)NavMenuList->ContainerFromItem(item);

            // While updating the selection state of the item prevent it from taking keyboard focus.  If a
            // user is invoking the back button via the keyboard causing the selected nav menu item to change
            // then focus will remain on the back button.
            if (container != nullptr) container->IsTabStop = false;
            NavMenuList->SetSelectedItem(container);
            if (container != nullptr) container->IsTabStop = true;
        }
    }

    void AppShell::OnNavigatedToPage(Object^ sender, NavigationEventArgs^ e)
    {
        // After a successful navigation set keyboard focus to the loaded page
        if (e->Content != nullptr && dynamic_cast<Page^>(e->Content) != nullptr)
        {
            auto control = (Page^)e->Content;
            control->Loaded += ref new RoutedEventHandler(this, &AppShell::Page_Loaded);
        }

        // Update the Back button depending on whether we can go Back.
        SystemNavigationManager::GetForCurrentView()->AppViewBackButtonVisibility =
            AppFrame->CanGoBack ?
            Windows::UI::Core::AppViewBackButtonVisibility::Visible :
            Windows::UI::Core::AppViewBackButtonVisibility::Collapsed;
    }

    void AppShell::Page_Loaded(Object^ sender, RoutedEventArgs^ e)
    {
        ((Page^)sender)->Focus(Windows::UI::Xaml::FocusState::Programmatic);
        CheckTogglePaneButtonSizeChanged();
    }

    /// <summary>
    /// Callback when the SplitView's Pane is toggled open or close.  When the Pane is not visible
    /// then the floating hamburger may be occluding other content in the app unless it is aware.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void AppShell::TogglePaneButton_Checked(Object^ sender, RoutedEventArgs^ e)
    {
        CheckTogglePaneButtonSizeChanged();
    }

	/// <summary>
	/// Ensure that we update the reported size of the TogglePaneButton when the SplitView's
	/// DisplayMode changes.
	/// </summary>
	void AppShell::RootSplitViewDisplayModeChangedCallback(DependencyObject^ sender, DependencyProperty^ dp)
	{
		CheckTogglePaneButtonSizeChanged();
	}

    /// <summary>
    /// Check for the conditions where the navigation pane does not occupy the space under the floating
    /// hamburger button and trigger the event.
    /// </summary>
    void AppShell::CheckTogglePaneButtonSizeChanged()
    {
        if (RootSplitView->DisplayMode == SplitViewDisplayMode::Inline ||
            RootSplitView->DisplayMode == SplitViewDisplayMode::Overlay)
        {
            auto transform = TogglePaneButton->TransformToVisual(this);
            auto rect = transform->TransformBounds(Rect(0, 0, (float)TogglePaneButton->ActualWidth, (float)TogglePaneButton->ActualHeight));
            _togglePaneButtonRect = rect;
        }
        else
        {
            _togglePaneButtonRect = Rect();
        }

        TogglePaneButtonRectChanged(this, TogglePaneButtonRect);
    }

    /// <summary>
    /// Enable accessibility on each nav menu item by setting the AutomationProperties.Name on each container
    /// using the associated Label of each item.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    void AppShell::NavMenuItemContainerContentChanging(ListViewBase^ sender, ContainerContentChangingEventArgs^ args)
    {
        if (!args->InRecycleQueue && args->Item != nullptr && dynamic_cast<NavMenuItem^>(args->Item) != nullptr)
        {
            args->ItemContainer->SetValue(Windows::UI::Xaml::Automation::AutomationProperties::NameProperty, ((NavMenuItem^)args->Item)->Label);
        }
        else
        {
            args->ItemContainer->ClearValue(Windows::UI::Xaml::Automation::AutomationProperties::NameProperty);
        }
    }
}