text:
using System.Web.Mvc;
using eidss.model.Enums;
using eidss.model.Reports;
using eidss.model.Reports.Common;
using eidss.model.Schema;
using eidss.webclient.Utils;
using bv.model.Model.Core;
using eidss.model.Resources;
using bv.model.BLToolkit;
using eidss.model.Core;
using System.Collections.Generic;
using System;
using BLToolkit.EditableObjects;

namespace eidss.webclient.Controllers
{
   [AuthorizeEIDSS]
    public class ASSessionController : Controller
    {

        #region Session
        public ActionResult Index()
        {
            var accessor = AsSessionListItem.Accessor.Instance(null);
            IObject initObject = null;
            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                initObject = accessor.CreateNew(manager, null);
            }
            ViewBag.InitObject = initObject;
            ViewBag.Filter = SearchPanelHelper.GetDefaultFilter(accessor.SearchPanelMeta, initObject);

            return View(accessor);
        }

        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            FilterParams filter = SearchPanelHelper.SearchPanelParseValues(form, AsSessionListItem.Accessor.Instance(null).SearchPanelMeta);
            ViewBag.Filter = filter;
            ViewBag.InitObject = null;
            AsSessionListItem.AsSessionListItemGridModelList list = GetGridModelList(filter);
            ModelStorage.Put(Session.SessionID, AutoGridRoots.AsSessionList, AutoGridRoots.AsSessionList, "Grid", list);
            int totalRows = list.Count;
            return Json(new { data = list, total = totalRows }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Details(long? id, long? idfCampaign = null)
        {
            if (id == 0)
                id = null;
            ViewBag.OpenVetCase = null;
            ViewBag.EnableCampaignSelection = !idfCampaign.HasValue;

            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                var acc = AsSession.Accessor.Instance(null);
                AsSession session = null;
                if (id.HasValue)
                {
                    session = acc.SelectByKey(manager, id.Value);
                }
                else
                {
                    session = acc.CreateNewT(manager, null);
                    session.idfCampaign = idfCampaign;
                }

                ModelStorage.Put(Session.SessionID, session.idfMonitoringSession, session.idfMonitoringSession, null, session);
                ViewBag.IsReadOnly = session.idfsMonitoringSessionStatus == (long)AsSessionStatus.Closed;
                return View(session);
            }

        }

        [HttpGet]
        public ActionResult TryToSetCampaign(long idfSession, long? idfCampaign)
        {
            var session = ModelStorage.Get(Session.SessionID, idfSession, null) as AsSession;
            CompareModel data = null;
            ICloneable cloneable = session as ICloneable;
            IObject clone = cloneable.Clone() as IObject;
            session.Validation += object_ValidationDetails;
            session.SetValue("idfCampaign", idfCampaign.ToString());
            session.Validation -= object_ValidationDetails;
            data = session.Compare(clone);
            if (ViewData["ErrorMessage"] != null)
            {
                string name = "idfCampaign";
                object val = session.GetValue(name);
                string type = session.GetType(name);
                string valstr = val == null ? "" : val.ToString();
                data.Add(name, idfSession.ToString(), type, valstr, session.IsReadOnly(name), session.IsInvisible(name), session.IsRequired(name));
                data.Add("ErrorMessage", "ErrorMessage", "ErrorMessage",
                    String.Format("{0}:{1}",ViewData["ErrorType"].ToString(), ViewData["ErrorMessage"].ToString()),
                    false, false, false);
            }
            var json = new JsonResult { Data = data ?? new CompareModel(), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            return json;
        }

        [HttpPost]
        public ActionResult Details(long? id, long? idfCampaign, FormCollection form)
        {
            var key = long.Parse(form["idfMonitoringSession"]);
            var session = ModelStorage.Get(Session.SessionID, key, null) as AsSession;
            var clone = (IObject)session.Clone();

            ViewData["ErrorMessage"] = null;

            session._blnAllowCampaignReload = false;
            ViewBag.EnableCampaignSelection = !idfCampaign.HasValue;
            session.Validation += object_ValidationDetails;
            session.ParseFormCollection(form);

            bool createCasesTry = session._idfFarmForCaseCreation.HasValue;

            if (ViewData["ErrorMessage"] == null)
            {
                using (var manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
                {
                    var acc = AsSession.Accessor.Instance(null);
                    acc.Post(manager, session);
                }
            }

            session.Validation -= object_ValidationDetails;
            long createdCases = 0;

            if (createCasesTry && !string.IsNullOrWhiteSpace(session._strCreatedCases) && session._strCreatedCases != AsSession.NO_CASES_CREATED)
            {
                string[] ids = session._strCreatedCases.Split(new char[] { ',' });
                if (ids.Length == 1)
                {
                    createdCases = Convert.ToInt64(ids[0]);
                }
                else
                {
                    createdCases = -1;
                }
            }
            else
            {
                if (createCasesTry && ViewData["ErrorMessage"] == null)
                {
                    createdCases = -2;
                }

            }

            if (ViewData["ErrorMessage"] == null)
            {
                using (var manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
                {
                    var acc = AsSession.Accessor.Instance(null);
                    session = acc.SelectByKey(manager, key);
                    ModelStorage.Put(Session.SessionID, session.idfMonitoringSession, session.idfMonitoringSession, null, session);
                }
            }

            CompareModel comparision = new CompareModel();

            if (ViewData["ErrorMessage"] != null)
            {
                comparision.Add("ErrorMessage", "ErrorMessage", "ErrorMessage",
                                ViewData["ErrorMessage"].ToString(),
                                false, false, false);
            }
            else
            {
                comparision = session.Compare(clone);
                if (createCasesTry)
                {
                    comparision.Add("CasesCreated", "CasesCreated", "hidden", createdCases.ToString(), false, false, false);
                }
            }

            SessionRefreshHelper.RefreshObjectChildren(
                Session.SessionID,
                session,
                new Dictionary<string, EditableArrayList> {
                    {session.ObjectIdent + "Diseases", session.Diseases},
                    {session.ObjectIdent + "SummaryItems", session.SummaryItems},
                    {session.ObjectIdent + "Actions", session.Actions},
                    {session.ObjectIdent + "Cases", session.Cases},
                    {session.ObjectIdent + "Samples", session.DetailsTableView},
                    {session.ObjectIdent + "CaseTests", session.CaseTests},
                    {session.ObjectIdent + "CaseTestValidations", session.CaseTestValidations}
                });
            return Json(comparision, JsonRequestBehavior.AllowGet);
        }

        #endregion

        void object_ValidationDetails(object sender, ValidationEventArgs args)
        {
            ViewData["ErrorMessage"] = EidssMessages.GetValidationErrorMessage(args).Replace("*Species*", args.PropertyName);
            if (args.Pars != null && args.Pars.Length > 0)
            {
                ViewData["ErrorType"] = args.Pars[0];
            }
        }

        public ActionResult DetailsNonPostable(long idfSession, long idfCampaign)
        {
            ViewBag.OpenVetCase = null;

            var campaign = ModelStorage.Get(Session.SessionID, idfCampaign, null) as AsCampaign;

            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                var acc = AsSession.Accessor.Instance(null);
                AsSession session = null;
                if (idfSession > 0)
                {
                    session = campaign.Sessions.Find(s => s.idfMonitoringSession == idfSession).FullSession;
                }
                else
                {
                    session = acc.CreateNewT(manager, null);
                    session.CampaignInRamOnly = campaign;
                    session.idfCampaign = idfCampaign;
                }

                ViewBag.EnableCampaignSelection = false;

                ModelStorage.Put(Session.SessionID, session.idfMonitoringSession, session.idfMonitoringSession, null, session);
                return View(session);
            }
        }

        private bool ValidationHasErrors(CompareModel comparision)
        {
            if (ViewData["ErrorMessage"] != null)
            {
                comparision.Add("ErrorMessage", "ErrorMessage", "ErrorMessage",
                                ViewData["ErrorMessage"].ToString(),
                                false, false, false);
                return true;
            }
            return false;
        }

        [HttpPost]
        public ActionResult DetailsNonPostable(long idfSession, long idfCampaign, FormCollection form)
        {
            var key = long.Parse(form["idfMonitoringSession"]);
            var session = ModelStorage.Get(Session.SessionID, key, null) as AsSession;

            ViewData["ErrorMessage"] = null;

            session._blnAllowCampaignReload = false;
            ViewBag.EnableCampaignSelection = false;

            session.Validation += object_ValidationDetails;
            session.ParseFormCollection(form);

            using (var manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                var acc = AsSession.Accessor.Instance(null);
                acc.Validate(manager, session, true, false, true);
            }

            session.Validation -= object_ValidationDetails;

            CompareModel comparision = new CompareModel();
            if (!ValidationHasErrors(comparision))
            {
                var campaign = ModelStorage.Get(Session.SessionID, idfCampaign, null) as AsCampaign;
                try
                {

                    campaign.ValidateSessionAssignment(session);

                    using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
                    {
                        session.idfCampaign = null;
                        AsSession.Accessor.Instance(null).Post(manager, session);
                    }

                    if (campaign.Sessions.Find(x => x.idfMonitoringSession == key) == null)
                    {
                        AsCampaign.AssignCampaignToSession(campaign, session);
                    }
                    else
                    {
                        AsMonitoringSession.UpdateFromASSession(
                            campaign.Sessions.Find(x => x.idfMonitoringSession == key),
                            session,
                            campaign.idfCampaign);
                    }
                }
                catch (ValidationModelException e)
                {
                    ViewData["ErrorMessage"] = EidssMessages.GetValidationErrorMessage(e);
                    if (e.Pars != null && e.Pars.Length > 0)
                    {
                        ViewData["ErrorType"] = e.Pars[0];
                    }
                }

                ValidationHasErrors(comparision);
                SessionRefreshHelper.RefreshObjectChildren(
                       Session.SessionID,
                       session,
                       new Dictionary<string, EditableArrayList> {
                            {session.ObjectIdent + "Diseases", session.Diseases},
                            {session.ObjectIdent + "SummaryItems", session.SummaryItems},
                            {session.ObjectIdent + "Actions", session.Actions},
                            {session.ObjectIdent + "Cases", session.Cases},
                            {session.ObjectIdent + "Samples", session.DetailsTableView},
                            {session.ObjectIdent + "CaseTests", session.CaseTests},
                            {session.ObjectIdent + "CaseTestValidations", session.CaseTestValidations}
                        });
            }
            return Json(comparision, JsonRequestBehavior.AllowGet);
        }

        #region address methods

        [HttpPost]
        public ActionResult SelectRegion(long idfSession)
        {
            AsSession session = ModelStorage.Get(Session.SessionID, idfSession, null) as AsSession;
            return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new SelectList(session.RegionLookup, "idfsRegion", "strRegionName") };
        }

        [HttpPost]
        public ActionResult SelectRayon(long idfSession)
        {
            AsSession session = ModelStorage.Get(Session.SessionID, idfSession, null) as AsSession;
            return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new SelectList(session.RayonLookup, "idfsRayon", "strRayonName") };
        }

        [HttpPost]
        public ActionResult SelectSettlement(long idfSession)
        {
            AsSession session = ModelStorage.Get(Session.SessionID, idfSession, null) as AsSession;
            return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new SelectList(session.SettlementLookup, "idfsSettlement", "strSettlementName") };
        }
        #endregion

        [HttpGet]
        public ActionResult ASSessionPicker()
        {
            var accessor = AsSessionListItem.Accessor.Instance(null);
            IObject initObject = null;
            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                initObject = accessor.CreateNew(manager, null);
            }
            ViewBag.InitObject = initObject;
            FilterParams filter = SearchPanelHelper.GetDefaultFilter(accessor.SearchPanelMeta, initObject);
            ViewBag.Filter = filter;
            AsSessionListItem.AsSessionListItemGridModelList list = GetGridModelList(filter);
            ViewBag.GridItems = list;
            ModelStorage.Put(Session.SessionID, 0, AutoGridRoots.AsSessionSelectList, "Grid", list);

            return View(accessor);
        }

        [HttpPost]
        public ActionResult ASSessionPicker(string formData)
        {
            FilterParams filter = SearchPanelHelper.SearchPanelParseValues(formData, AsSessionListItem.Accessor.Instance(null).SearchPanelMeta);
            ViewBag.Filter = filter;
            ViewBag.InitObject = null;
            AsSessionListItem.AsSessionListItemGridModelList list = GetGridModelList(filter);
            ModelStorage.Put(Session.SessionID, 0, AutoGridRoots.AsSessionSelectList, "Grid", list);
            int totalRows = list.Count;
            return Json(new { data = list, total = totalRows }, JsonRequestBehavior.AllowGet);
        }

        private static AsSessionListItem.AsSessionListItemGridModelList GetGridModelList(FilterParams filter)
        {
            List<AsSessionListItem> items = GetAsSessionList(filter);
            var list = new AsSessionListItem.AsSessionListItemGridModelList(AutoGridRoots.AsSessionSelectList, items);
            return list;
        }

        private static List<AsSessionListItem> GetAsSessionList(FilterParams filter)
        {
            var accessor = AsSessionListItem.Accessor.Instance(null);
            using (var dbmanager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
            {
                List<AsSessionListItem> items = accessor.SelectListT(dbmanager, filter);
                return items;
            }
        }

        [HttpGet]
        public ActionResult ReportAsSampleCollectedList(long id)
        {
            byte[] report;
            using (var wrapper = new ReportClientWrapper())
            {
                report = wrapper.Client.ExportVetActiveSurveillanceSampleCollected( new BaseIdModel(ModelUserContext.CurrentLanguage, id, ModelUserContext.Instance.IsArchiveMode));
            }
            const string fileName = "ReportAsSampleCollectedList.pdf";
            Response.AppendHeader("content-disposition", "inline; filename=" + fileName);
            return File(report, "application/pdf", fileName);
        }

        [HttpGet]
        public ActionResult ReportAsSessionTests(long id)
        {
            byte[] report;
            using (var wrapper = new ReportClientWrapper())
            {
                var model = new LimTestModel(ModelUserContext.CurrentLanguage, id, false, ModelUserContext.Instance.IsArchiveMode);
                report = wrapper.Client.ExportLimTest( model);
            }
            const string fileName = "ReportAsSessionTests.pdf";
            Response.AppendHeader("content-disposition", "inline; filename=" + fileName);
            return File(report, "application/pdf", fileName);
        }

    }
}


text:
/* Main Stylesheet */

/* Box sizing styles: Apply a natural box layout model to all elements */
*,
*:before,
*:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

/* Author Custom Styles */

.yeogurt-info {
  text-align: center;
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
}

.version {
  font-size: 14px;
  font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.logo {
  margin-top: 25px;
}

.links a {
  color: white;
  margin-right: 5px;
  margin-top: 20px;
  border-radius: 4px;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  background: #ed7c6c;
  display: inline-block;
  zoom: 1;
  line-height: normal;
  white-space: nowrap;
  vertical-align: baseline;
  text-align: center;
  cursor: pointer;
  font-size: 100%;
  padding: .5em 1em;
  text-decoration: none;
}

/* Styling on warning for users on IE7 or below */
.browsehappy {
  text-align: center;
  margin: 0;
  background: #fff8e2;
  color: #000;
  padding: 0.5em 0;
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.vbauer.herald.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author Vladislav Bauer
 */

public final class ServiceLoaderUtils {

    private ServiceLoaderUtils() {
        throw new UnsupportedOperationException();
    }

    public static <T> Collection<T> load(final Class<T> beanClass) {
        final ServiceLoader<T> serviceLoader = ServiceLoader.load(beanClass);
        final Iterator<T> iterator = serviceLoader.iterator();

        final List<T> result = new ArrayList<>();
        while (iterator.hasNext()) {
            result.add(iterator.next());
        }
        return result;
    }

}


text:
package org.usfirst.frc.team6317.robot.subsystems;

import edu.wpi.first.wpilibj.command.Subsystem;
import org.usfirst.frc.team6317.robot.*;

public class Shooter extends Subsystem {
	public boolean shooting = false;

	@Override
	public void initDefaultCommand(){

	}

	public void runShooter(double speed){
		RobotMap.shooterMotor.set(speed);
		shooting = true;
	}

	public void runShooter() {
		runShooter(-1);
	}

	public void stopShooter(){
		RobotMap.shooterMotor.set(0);
		shooting = false;
	}
	public void reverseShooter(){
		runShooter(1);
	}
}


text:
require_relative '../epson'

module ESC_POS
  module Specifications
    class Epson

      class TM_U220 < Base

        set :width,               40
        set :spaces_to_end_page,  5

      end

    end
  end
end


text:
package memory

import (
	"container/list"
	"fmt"
	"sync"

	"github.com/google/cadvisor/info"
	"github.com/google/cadvisor/sampling"
	"github.com/google/cadvisor/storage"
)

// containerStorage is used to store per-container information
type containerStorage struct {
	ref         info.ContainerReference
	prevStats   *info.ContainerStats
	sampler     sampling.Sampler
	recentStats *list.List
	maxNumStats int
	maxMemUsage uint64
	lock        sync.RWMutex
}

func (self *containerStorage) updatePrevStats(stats *info.ContainerStats) {
	if stats == nil || stats.Cpu == nil || stats.Memory == nil {
		// discard incomplete stats
		self.prevStats = nil
		return
	}
	if self.prevStats == nil {
		self.prevStats = &info.ContainerStats{
			Cpu:    &info.CpuStats{},
			Memory: &info.MemoryStats{},
		}
	}
	// make a deep copy.
	self.prevStats.Timestamp = stats.Timestamp
	*self.prevStats.Cpu = *stats.Cpu
	self.prevStats.Cpu.Usage.PerCpu = make([]uint64, len(stats.Cpu.Usage.PerCpu))
	for i, perCpu := range stats.Cpu.Usage.PerCpu {
		self.prevStats.Cpu.Usage.PerCpu[i] = perCpu
	}
	*self.prevStats.Memory = *stats.Memory
}

func (self *containerStorage) AddStats(stats *info.ContainerStats) error {
	self.lock.Lock()
	defer self.lock.Unlock()
	if self.prevStats != nil {
		sample, err := info.NewSample(self.prevStats, stats)
		if err != nil {
			return fmt.Errorf("wrong stats: %v", err)
		}
		if sample != nil {
			self.sampler.Update(sample)
		}
	}
	if stats.Memory != nil {
		if self.maxMemUsage < stats.Memory.Usage {
			self.maxMemUsage = stats.Memory.Usage
		}
	}
	if self.recentStats.Len() >= self.maxNumStats {
		self.recentStats.Remove(self.recentStats.Front())
	}
	self.recentStats.PushBack(stats)
	self.updatePrevStats(stats)
	return nil
}

func (self *containerStorage) RecentStats(numStats int) ([]*info.ContainerStats, error) {
	self.lock.RLock()
	defer self.lock.RUnlock()
	if self.recentStats.Len() < numStats || numStats < 0 {
		numStats = self.recentStats.Len()
	}
	ret := make([]*info.ContainerStats, 0, numStats)
	e := self.recentStats.Front()
	for i := 0; i < numStats; i++ {
		data, ok := e.Value.(*info.ContainerStats)
		if !ok {
			return nil, fmt.Errorf("The %vth element is not a ContainerStats", i)
		}
		ret = append(ret, data)
		e = e.Next()
		if e == nil {
			break
		}
	}
	return ret, nil
}

func (self *containerStorage) Samples(numSamples int) ([]*info.ContainerStatsSample, error) {
	self.lock.RLock()
	defer self.lock.RUnlock()
	if self.sampler.Len() < numSamples || numSamples < 0 {
		numSamples = self.sampler.Len()
	}
	ret := make([]*info.ContainerStatsSample, 0, numSamples)

	var err error
	self.sampler.Map(func(d interface{}) {
		if len(ret) >= numSamples || err != nil {
			return
		}
		sample, ok := d.(*info.ContainerStatsSample)
		if !ok {
			err = fmt.Errorf("An element in the sample is not a ContainerStatsSample")
		}
		ret = append(ret, sample)
	})
	if err != nil {
		return nil, err
	}
	return ret, nil
}

func (self *containerStorage) Percentiles(cpuPercentiles, memPercentiles []int) (*info.ContainerStatsPercentiles, error) {
	samples, err := self.Samples(-1)
	if err != nil {
		return nil, err
	}
	if len(samples) == 0 {
		return nil, nil
	}
	ret := info.NewPercentiles(samples, cpuPercentiles, memPercentiles)
	ret.MaxMemoryUsage = self.maxMemUsage
	return ret, nil
}

func newContainerStore(ref info.ContainerReference, maxNumSamples, maxNumStats int) *containerStorage {
	s := sampling.NewReservoirSampler(maxNumSamples)
	return &containerStorage{
		ref:         ref,
		recentStats: list.New(),
		sampler:     s,
		maxNumStats: maxNumStats,
	}
}

type InMemoryStorage struct {
	lock                sync.RWMutex
	containerStorageMap map[string]*containerStorage
	maxNumSamples       int
	maxNumStats         int
}

func (self *InMemoryStorage) AddStats(ref info.ContainerReference, stats *info.ContainerStats) error {
	var cstore *containerStorage
	var ok bool
	self.lock.Lock()
	if cstore, ok = self.containerStorageMap[ref.Name]; !ok {
		cstore = newContainerStore(ref, self.maxNumSamples, self.maxNumStats)
		self.containerStorageMap[ref.Name] = cstore
	}
	self.lock.Unlock()
	return cstore.AddStats(stats)
}

func (self *InMemoryStorage) Samples(name string, numSamples int) ([]*info.ContainerStatsSample, error) {
	var cstore *containerStorage
	var ok bool
	self.lock.RLock()
	if cstore, ok = self.containerStorageMap[name]; !ok {
		return nil, fmt.Errorf("unable to find data for container %v", name)
	}
	self.lock.RUnlock()

	return cstore.Samples(numSamples)
}

func (self *InMemoryStorage) RecentStats(name string, numStats int) ([]*info.ContainerStats, error) {
	var cstore *containerStorage
	var ok bool
	self.lock.RLock()
	if cstore, ok = self.containerStorageMap[name]; !ok {
		return nil, fmt.Errorf("unable to find data for container %v", name)
	}
	self.lock.RUnlock()

	return cstore.RecentStats(numStats)
}

func (self *InMemoryStorage) Percentiles(name string, cpuPercentiles, memPercentiles []int) (*info.ContainerStatsPercentiles, error) {
	var cstore *containerStorage
	var ok bool
	self.lock.RLock()
	if cstore, ok = self.containerStorageMap[name]; !ok {
		return nil, fmt.Errorf("unable to find data for container %v", name)
	}
	self.lock.RUnlock()

	return cstore.Percentiles(cpuPercentiles, memPercentiles)
}

func (self *InMemoryStorage) Close() error {
	self.lock.Lock()
	self.containerStorageMap = make(map[string]*containerStorage, 32)
	self.lock.Unlock()
	return nil
}

func New(maxNumSamples, maxNumStats int) storage.StorageDriver {
	ret := &InMemoryStorage{
		containerStorageMap: make(map[string]*containerStorage, 32),
		maxNumSamples:       maxNumSamples,
		maxNumStats:         maxNumStats,
	}
	return ret
}


text:
import pointOnFeature from '@turf/point-on-feature'
import {
  Circle,
  Geometry,
  GeometryCollection,
  LineString,
  MultiLineString,
  MultiPoint,
  MultiPolygon,
  Point,
  Polygon,
} from 'ol/geom'
import { circular as circularPolygon } from 'ol/geom/Polygon'
import { v4 as uuid } from 'uuid'
import { isPlainObject } from '../utils'
import { COORD_PRECISION, roundCoords } from './coord'
import { GeometryType } from './enums'

/**
 * @param {number|number[]} lonOrCoordinates
 * @param {number} [lat]
 * @return {Point}
 */
export function createPointGeom (lonOrCoordinates, lat) {
  const coordinates = Array.isArray(lonOrCoordinates)
    ? lonOrCoordinates
    : [lonOrCoordinates, lat]

  return new Point(coordinates)
}

/**
 * @param {Array<number[]>} points
 * @returns {LineString}
 */
export function createLineGeom (points) {
  return new LineString(points)
}

/**
 * @param {Array<Array<number[]>>} rings
 * @returns {Polygon}
 */
export function createPolygonGeom (rings) {
  return new Polygon(rings)
}

/**
 * @param {Array<number[]>} points
 * @returns {MultiPoint}
 */
export function createMultiPointGeom (points) {
  return new MultiPoint(points)
}

/**
 * @param {Array<Array<number[]>>} lines
 * @returns {MultiLineString}
 */
export function createMultiLineGeom (lines) {
  return new MultiLineString(lines)
}

/**
 * @param {Array<Array<Array<number[]>>>} polygons
 * @returns {MultiPolygon}
 */
export function createMultiPolygonGeom (polygons) {
  return new MultiPolygon(polygons)
}

/**
 * @param {Geometry[]} geoms
 * @returns {GeometryCollection}
 */
export function createGeomCollection (geoms) {
  return new GeometryCollection(geoms)
}

/**
 * @param {Coordinate|number[]} center
 * @param {number} radius
 * @return {Polygon}
 */
export function createCircularPolygon (center, radius) {
  return circularPolygon(center, radius)
}

/**
 * @param {Geometry|Object} geom
 * @return {boolean}
 * @throws {Error}
 */
export function isMultiGeom (geom) {
  const multiTypes = [
    GeometryType.MULTI_POINT,
    GeometryType.MULTI_LINE_STRING,
    GeometryType.MULTI_POLYGON,
    GeometryType.GEOMETRY_COLLECTION,
  ]

  return multiTypes.includes(geom.type || geom.getType())
}

/**
 * @param {Geometry|Object} geom
 * @return {SimpleGeometry|Object}
 * @throws {Error}
 */
export function toSimpleGeom (geom) {
  if (geom instanceof Circle) {
    geom = createPointGeom(geom.getCenter())
  } else if (geom.type === GeometryType.CIRCLE) {
    geom = { ...geom, type: GeometryType.POINT }
  }

  const type = geom.type || geom.getType()
  const complexTypes = [
    GeometryType.GEOMETRY_COLLECTION,
  ]

  if (complexTypes.includes(type) === false) {
    return geom
  }

  return (geom.geometries || geom.getGeometries())[0]
}

/**
 * @param {Geometry|Object} geom
 * @param {number} [precision=COORD_PRECISION]
 * @return {Coordinate|undefined}
 */
export function findPointOnSurface (geom, precision = COORD_PRECISION) {
  const simpleGeom = toSimpleGeom(geom)
  const pointFeature = pointOnFeature({
    type: simpleGeom.type || simpleGeom.getType(),
    coordinates: simpleGeom.coordinates || simpleGeom.getCoordinates(),
  })
  if (pointFeature?.geometry) {
    return roundCoords(
      pointFeature.geometry.type,
      pointFeature.geometry.coordinates,
      precision,
    )
  }
}

export function getGeometryId (geometry) {
  if (geometry instanceof Geometry) {
    return geometry.get('id')
  } else if (isPlainObject(geometry)) {
    return geometry.id
  }

  throw new Error('Illegal geometry argument')
}

export function setGeometryId (geometry, geometryId) {
  if (geometry instanceof Geometry) {
    geometry.set('id', geometryId)

    return geometry
  } else if (isPlainObject(geometry)) {
    geometry.id = geometryId

    return geometry
  }

  throw new Error('Illegal geometry argument')
}

export function initializeGeometry (geometry, defaultGeometryId) {
  if (getGeometryId(geometry) == null) {
    setGeometryId(geometry, defaultGeometryId || uuid())
  }

  return geometry
}

/**
 * @param value
 * @return {boolean}
 */
export function isCircleGeom (value) {
  return getGeomType(value) === GeometryType.CIRCLE
}

export function getGeomCoords (geom) {
  if (!geom) return

  const type = getGeomType(geom)
  switch (type) {
    case GeometryType.CIRCLE:
      return roundCoords(type, geom.coordinates || geom.getCenter())
    default:
      return roundCoords(type, geom.coordinates || geom.getCoordinates())
  }
}

export function getGeomType (geom) {
  if (geom instanceof Geometry) {
    return geom.getType()
  }
  return geom?.type
}


text:
permalink: /assets/js/scripts.min.js
---

{% capture scripts %}
  {% include assets/js/jquery-2.1.4.min.js %}
  {% include assets/js/bootstrap.min.js %}
  {% include assets/js/jquery.flexslider-min.js %}
  {% include assets/js/jquery.appear.js %}
  {% include assets/js/jquery.plugin.js %}
  {% include assets/js/jquery.simple-lightbox.min.js %}
  {% include assets/js/jquery.waypoints.min.js %}
  {% include assets/js/jquery.validate.min.js %}
  {% include assets/js/toastr.min.js %}
  {% include assets/js/jquery.bxslider.min.js %}
  {% include assets/js/startuply.js %}
  {% include assets/js/contact.js %}
{% endcapture %}

{{ scripts | uglify }}


text:
var ImageDataUtils;

(function() {
const DEFAULT_SNAP_SCAN_RANGE = 10;

function sign(a, b) {
    return (a > b) ? 1 : (a < b) ? -1 : 0;
}

function getPixelDelta(coord, endOffset, imageData) {
    var testOffset = ImageDataUtils.getOffset(coord, imageData),
        data = imageData.data;

    return Math.abs(data[endOffset]-data[testOffset])
            + Math.abs(data[endOffset+1]-data[testOffset+1])
            + Math.abs(data[endOffset+2]-data[testOffset+2])
            + Math.abs(data[endOffset+3]-data[testOffset+3]);
}

ImageDataUtils = {
    getCoords: function(offset, imageData) {
        var binWidth = imageData.width * 4;
        return {
            x: offset % binWidth,
            y: offset / binWidth | 0
        };
    },
    getOffset: function(coords, imageData) {
        return (coords.x + coords.y*imageData.width)*4;
    },
    getPixel: function(context, coord) {
        return context.getImageData(coord.x, coord.y, 1, 1).data;
    },
    getWindow: function getSnapToWindow(context, coord, windowSize) {
        var firstPixel = {x: Math.max(coord.x-windowSize, 0), y: Math.max(coord.y-windowSize, 0)};
        return {
            firstPixel: firstPixel,
            focusPixel: {x: coord.x-firstPixel.x, y: coord.y-firstPixel.y},
            imageData: context.getImageData(
                firstPixel.x,
                firstPixel.y,
                Math.min(2*windowSize, context.canvas.width-firstPixel.x),
                Math.min(2*windowSize, context.canvas.height-firstPixel.y))
        };
    },
    getLinePixels: function(context, coordStart, coordEnd) {
        // Extract the rectangle that contains our data
        var containingRect = LineUtils.containingRect(coordStart, coordEnd),
            image = context.getImageData(
                containingRect.x,
                containingRect.y,
                Math.min(containingRect.width+1, context.canvas.width-containingRect.x),     // Need to limit to image coords for Mozilla
                Math.min(containingRect.height+1, context.canvas.height-containingRect.y)),
            imageData = image.data;

        // Determine the properties of our line
        var len = LineUtils.distance(coordStart, coordEnd)|0;
        if (!len) {
            return;
        }

        // Create our destination image
        var line = context.createImageData(len, 1),
            lineData = line.data;

        LineUtils.walkLine(coordStart, coordEnd, function(t, coords) {
            var firstCoord = {x: Math.floor(coords.x), y: Math.floor(coords.y)},
                nextCoord = {x: Math.floor(coords.x), y: Math.ceil(coords.y)};

            var firstOffset = ImageDataUtils.getOffset(firstCoord, image),
                nextOffset = ImageDataUtils.getOffset(nextCoord, image);

            var xPercentage = 1-(coords.x-firstCoord.x),
                yPercentage = 1-(coords.y-firstCoord.y);
            function calcComponent(offset1, offset2) {
                return imageData[offset1 ]*xPercentage*yPercentage
                    + (imageData[offset1+4]||0)*(1-xPercentage)*yPercentage
                    + (imageData[offset2  ]||0)*xPercentage*(1-yPercentage)
                    + (imageData[offset2+4]||0)*(1-xPercentage)*(1-yPercentage);
            }

            var lineOffset = t*4;
            lineData[lineOffset]   = calcComponent(firstOffset,   nextOffset);
            lineData[lineOffset+1] = calcComponent(firstOffset+1, nextOffset+1);
            lineData[lineOffset+2] = calcComponent(firstOffset+2, nextOffset+2);
            lineData[lineOffset+3] = calcComponent(firstOffset+3, nextOffset+3);
        });

        return line;
    },
    getInitialSnapToTarget: function(edgeContext, coordStart, scanRange) {
        // Load the window we are concerned with right now
        var snapWindow = ImageDataUtils.getWindow(edgeContext, coordStart, scanRange || DEFAULT_SNAP_SCAN_RANGE),
            focusPixel = snapWindow.focusPixel,
            imageData = snapWindow.imageData,
            data = snapWindow.imageData.data,
            endOffset = ImageDataUtils.getOffset(focusPixel, snapWindow.imageData);

        // Setup our data tracker
        var maximum = focusPixel;
        maximum.distance = Infinity;
        maximum.delta = 0;

        function checkPixel(coord) {
            var delta = getPixelDelta(coord, endOffset, imageData);

            if (delta > 128) {
                coord.distance = Math.max(Math.abs(coord.x-focusPixel.x), Math.abs(coord.y-focusPixel.y));
                coord.delta = delta;
                if (coord.distance && (maximum.distance-coord.distance || coord.delta-maximum.delta) > 0) {
                    maximum = coord;
                }
            }
        }

        // Scan the window for any pixels that are dratically different
        var y = imageData.height;
        while (y--) {
            checkPixel({x: focusPixel.x, y: y});
        }

        var x = imageData.width;
        while (x--) {
            checkPixel({x: x, y: focusPixel.y});
        }

        // Move the return one pixel further along the path
        maximum.x = maximum.x+-1*sign(maximum.x, focusPixel.x)+snapWindow.firstPixel.x;
        maximum.y = maximum.y+-1*sign(maximum.y, focusPixel.y)+snapWindow.firstPixel.y;

        return maximum;
    },
    getSnapToTarget: function(edgeContext, coordStart, coordEnd, scanRange) {
        // Load the window we are concerned with right now
        var snapWindow = ImageDataUtils.getWindow(edgeContext, coordEnd, scanRange || DEFAULT_SNAP_SCAN_RANGE),
            imageData = snapWindow.imageData,
            data = imageData.data,
            endOffset = ImageDataUtils.getOffset(snapWindow.focusPixel, imageData),

            angle = LineUtils.slopeInRads(coordStart, coordEnd),
            shiftedStart = {x: coordStart.x-snapWindow.firstPixel.x, y: coordStart.y-snapWindow.firstPixel.y};

        var maximum = snapWindow.focusPixel;
        maximum.slopeDelta = 0;
        maximum.distance = LineUtils.distance(shiftedStart, maximum);
        maximum.delta = 0;

        // Scan the window for any pixels that are dratically different
        var y = imageData.height;
        while (y--) {
            var x = imageData.width;
            while (x--) {
                var coord = {x: x, y: y},
                    delta = getPixelDelta(coord, endOffset, imageData);

                if (delta > 128) {
                    coord.distance = LineUtils.distance(shiftedStart, coord);
                    coord.delta = delta;
                    coord.slopeDelta = Math.abs(LineUtils.slopeInRads(shiftedStart, coord)-angle);
                    if ((maximum.slopeDelta-coord.slopeDelta || coord.delta-maximum.delta || coord.distance-maximum.distance) > 0) {
                        maximum = coord;
                    }
                }
            }
        }

        maximum.x += snapWindow.firstPixel.x;
        maximum.y += snapWindow.firstPixel.y;

        return maximum;
    },
    getEdgeContext: function(el) {
        var loadOptions = {};
        Pixastic.process(ImageDataUtils.cloneCanvas(el), "edges", loadOptions);
        return loadOptions.resultCanvas.getContext("2d");
    },
    cloneCanvas: function(el) {
        var clone = document.createElement("canvas");
        clone.width = el.naturalWidth || el.width;
        clone.height = el.naturalHeight || el.height;
        clone.getContext("2d").drawImage(el, 0, 0);
        return clone;
    },
    createCanvasFromImageData: function(imageData) {
        var canvas = document.createElement("canvas");
        canvas.setAttribute("width", imageData.width);
        canvas.setAttribute("height", imageData.height);

        var context = canvas.getContext("2d");
        context.putImageData(imageData, 0, 0);

        return canvas;
    },
};
})();


text:
if (!ORYX.Plugins)
    ORYX.Plugins = new Object();

ORYX.Plugins.ResourcesBoDAdd = Clazz.extend({

    facade: undefined,

    construct: function(facade){

        this.facade = facade;

		this.active 		= false;
		this.raisedEventIds = [];

        this.facade.offer({
            'name': ORYX.I18N.ResourcesBoDAdd.name,
            'functionality': this.defineBoD.bind(this),
            'group': ORYX.I18N.ResourcesBoDAdd.group,
            'dropDownGroupIcon': ORYX.PATH + "images/bod.png",
            'icon': ORYX.PATH + "images/bod+.png",
            'description': ORYX.I18N.ResourcesBoDAdd.desc,
            'index': 3,
            'toggle': false,
            'minShape': 2,
            'maxShape': 0
        });

    },

	defineBoD: function(){
    	//variable declaration
    	var selectedElements = this.facade.getSelection(); //all selected elements
    	var taskElements = []; //all selected tasks
    	var selectedTasks; //new tasks to be separated
    	var i = 0; //counter
    	var len = selectedElements.length; //number of selected elements

    	//get only selected tasks
    	for (var index = 0; index < len; index++) {
    		var item = selectedElements[index];
    		if(item.properties["oryx-activitytype"] == "Task") {
    			taskElements[i] = item;
				if(taskElements[i].properties["oryx-id"] == "") {
					taskElements[i].setProperty("oryx-id", taskElements[i].id);
				}
    			if(i == 0) { //get ids of tasks to be bound
    				selectedTasks = taskElements[i].properties["oryx-id"];
    			} else {
    				selectedTasks = selectedTasks + "; " + taskElements[i].properties["oryx-id"];
    			}
    			i++;
    		}
    	}

		if (taskElements.length > 1) {
			for (var taskCounter = 0; taskCounter < taskElements.length; taskCounter++) {
				//variable declaration
				var savedBindingsData = [];	//already saved bindings
				var savedSeparationsData = false; //already saved separations

				//check whether other bindings are defined for current task
				if (taskElements[taskCounter].properties["oryx-bindingsofduties"] != "") {
					savedBindingsData = this.bindingsCheck(taskElements[taskCounter], selectedTasks);
					if (savedBindingsData[3] == true) {
						break;
					}
				} else {
					savedBindingsData[1] = 0; //total number of binding entries is 0 as field is empty
					savedBindingsData[2] = 0; //highest id used is 0 as no id is used
				}

				//check whether a contradicting separation is defined for current task
				if (taskElements[taskCounter].properties["oryx-separationofduties"] != ("")) {
					savedSeparationsData = this.separationsCheck(taskElements[taskCounter], selectedTasks);
					if (savedSeparationsData == true) {
						break;
					}
				}

				//write entry
				this.writeEntry(savedBindingsData, selectedTasks, taskElements[taskCounter]);
			}
		} else {
			alert("Please select at least two tasks to define constraints for.");
		}
    },

    bindingsCheck: function(taskElement, selectedTasks) { //check for existing bindings with same tasks
		var returnValue = [];
		//get previous binding of duties assignments
		var elementIds = []; //collection of used ids for saved separations
		var taskIds = []; //collection of saved task ids
		var totalCount = 0; //number of defined bindings for a specific task
    	var highestId = 1; //next element id for bindings of a specific task
    	var j = 0; //counter
    	var m = 0; //counter
    	var n = 0; //counter
		var bindings = taskElement.properties["oryx-bindingsofduties"]; //get saved bindings
    	bindings = bindings.toString();
    	//store saved bindings including task ids
    	var savedBindings = bindings.substring(0,bindings.indexOf(']'));
    	//extract number of entries and element ids of these entries
    	while(bindings.indexOf(',') > -1) {
    		if(j%2 == 1) { //get element ids as integer
    			elementIds[m] = parseInt(bindings.substring((bindings.indexOf('"')) + 1));
    			m++;
		    	bindings = bindings.substring((bindings.indexOf(',')) + 1);
    		} else if(j == 0) { //get total count as integer
    			totalCount = parseInt(bindings.substring((bindings.indexOf(':')) + 1));
    			bindings = bindings.substring((bindings.indexOf(',')) + 1);
    		} else { //get task ids of bindings
    			bindings = bindings.substring((bindings.indexOf('"')) + 1);
    			taskIds[n] = bindings.substring(0,bindings.indexOf('"'));
    			n++;
    			bindings = bindings.substring((bindings.indexOf(',')) + 1);
    		}
	        j++;
    	}
    	if(bindings.indexOf('"') > -1) {
    		taskIds[n] = bindings.substring((bindings.indexOf('"')) + 1);
    	} else {
    		taskIds[n] = bindings; //get last task ids entry
    	}
    	taskIds[n]= taskIds[n].substring(0,taskIds[n].indexOf('"'));

        //check whether entry does already exist
        var boundTasksCopy = selectedTasks; //working copy
        var singleTaskIdsInsertedBinding = []; //task ids of new bindings
        var singleTaskIdsSavedBindings = []; //task ids of saved bindings

        var y = 0; //counter

		var equal = false; //duplicate existing?

        //extract task ids of newly entered binding tasks
    	while(boundTasksCopy.indexOf(';') > -1) {
    		singleTaskIdsInsertedBinding[y] = boundTasksCopy.substring(0, boundTasksCopy.indexOf(';'));
    		boundTasksCopy = boundTasksCopy.substring((boundTasksCopy.indexOf(';'))+2);
	        y++;
        }
    	singleTaskIdsInsertedBinding[y] = boundTasksCopy;

        //extract task ids of stored binding tasks
        for(var index = 0; index < taskIds.length; index++) {
        	var z = 0; //counter
			var equalCounter = 0;
			while(taskIds[index].indexOf(';') > -1) {
        		singleTaskIdsSavedBindings[z] = taskIds[index].substring(0, taskIds[index].indexOf(';'));
        		taskIds[index] = taskIds[index].substring((taskIds[index].indexOf(';'))+2);
		        z++;
	        }
        	singleTaskIdsSavedBindings[z] = taskIds[index];
        	z++;

			//compare all collected tasks/ task ids
        	if(singleTaskIdsInsertedBinding.length == singleTaskIdsSavedBindings.length) {
        		for(var x = 0; x < singleTaskIdsSavedBindings.length; x++) {
        			for(var w = 0; w < singleTaskIdsInsertedBinding.length; w++) {
        				if(singleTaskIdsInsertedBinding[w] == singleTaskIdsSavedBindings[x]) {
        					equal = true;
        					break;
        				}
        				equal = false;
        			}
        			if(equal == false) { //one item of set 1 not found in set 2
    					break;
    				}
        		}
        	} else if(singleTaskIdsInsertedBinding.length > singleTaskIdsSavedBindings.length) {
        		for(var x = 0; x < singleTaskIdsSavedBindings.length; x++) {
        			for(var w = 0; w < singleTaskIdsInsertedBinding.length; w++) {
						if (singleTaskIdsInsertedBinding[w] == singleTaskIdsSavedBindings[x]) {
							equalCounter++;
							break;
						}
					}
					if(equalCounter == singleTaskIdsSavedBindings.length) { //all saved tasks are found in new entries
						var result = this.deleteBindingEntry(taskElement, (index+1)); //delete existing entry to write new entry later and following updating the entry
						savedBindings = result[0];
						totalCount = result[1];
						equalCounter = 0;
						break;
					}
				}
				equal = false;
        	} else {
        		for(var x = 0; x < singleTaskIdsInsertedBinding.length; x++) {
        			for(var w = 0; w < singleTaskIdsSavedBindings.length; w++) {
        				if(singleTaskIdsSavedBindings[w] == singleTaskIdsInsertedBinding[x]) {
        					equal = true;
        					break;
        				}
        				equal = false;
        			}
        			if(equal == false) { //one item of smaller set not found in bigger set
    					break;
    				}
        		}
        	}
			singleTaskIdsSavedBindings.splice(0,singleTaskIdsSavedBindings.length);
        	//entry does exist, that's why no new one needs to be done
	        if(equal == true) {
	        	break;
	        }
        }

    	//get highest element id
    	for(var index = 0; index < elementIds.length; index++) {
    		if(elementIds[index] > highestId) {
    			highestId = elementIds[index];
    		}
    	}
    	returnValue[0] = savedBindings;
    	returnValue[1] = totalCount;
    	returnValue[2] = highestId;
    	returnValue[3] = equal;
    	return returnValue;
    },

    separationsCheck: function(taskElement, selectedTasks) { //check for existing separation with same tasks
    	var returnValue;
		//get previous binding of duties assignments
		var boundTaskIds = []; //collection of saved task ids
    	var l = 0; //counter
    	var q = 0; //counter
		var separations = taskElement.properties["oryx-separationofduties"]; //get saved separations
    	separations = separations.toString();
    	//extract number of entries and element ids of these entries
    	while(separations.indexOf(',') > -1) {
    		if(l%2 == 1) { //ignore element ids
		    	separations = separations.substring((separations.indexOf(',')) + 1);
    		} else if(l == 0) { //ignore totalCount
    			separations = separations.substring((separations.indexOf(',')) + 1);
    		} else {
    			separations = separations.substring((separations.indexOf('"')) + 1);
    			boundTaskIds[q] = separations.substring(0,separations.indexOf('"'));
    			q++;
    			separations = separations.substring((separations.indexOf(',')) + 1);
    		}
	        l++;
    	}
    	if(separations.indexOf('"') > -1) {
    		boundTaskIds[q] = separations.substring((separations.indexOf('"')) + 1);
    	} else {
    		boundTaskIds[q] = separations; //never reached?
    	}
    	boundTaskIds[q]= boundTaskIds[q].substring(0,boundTaskIds[q].indexOf('"'));

        //check whether entry does already exist
        var separatedTasksCopy = selectedTasks; //working copy
        var singleTaskIdsInsertedSeparation = []; ////task ids of new separations
        var singleTaskIdsSavedSeparations = []; //task ids of saved separations
        var s = 0; //counter
        var t = 0; //counter
        var duplicate = false; //duplicate existing?

        //extract task ids of newly entered separation tasks
    	while(separatedTasksCopy.indexOf(';') > -1) {
    		singleTaskIdsInsertedSeparation[s] = separatedTasksCopy.substring(0, separatedTasksCopy.indexOf(';'));
    		separatedTasksCopy = separatedTasksCopy.substring((separatedTasksCopy.indexOf(';'))+2);
	        s++;
        }
    	singleTaskIdsInsertedSeparation[s] = separatedTasksCopy;

        //extract task ids of stored bound tasks
        for(var index = 0; index < boundTaskIds.length; index++) {
        	while(boundTaskIds[index].indexOf(';') > -1) {
        		singleTaskIdsSavedSeparations[t] = boundTaskIds[index].substring(0, boundTaskIds[index].indexOf(';'));
        		boundTaskIds[index] = boundTaskIds[index].substring((boundTaskIds[index].indexOf(';'))+2);
		        t++;
	        }
        	singleTaskIdsSavedSeparations[t] = boundTaskIds[index];

	        var check = 0;
        	if(singleTaskIdsInsertedSeparation.length >= singleTaskIdsSavedSeparations.length) {
        		for(var x = 0; x < singleTaskIdsSavedSeparations.length; x++) {
        			for(var w = 0; w < singleTaskIdsInsertedSeparation.length; w++) {
        				if(singleTaskIdsInsertedSeparation[w] == singleTaskIdsSavedSeparations[x]) {
        					check++;
        					if(check == 2) {
        						duplicate = true;
        					}
        					break;
        				}
        				duplicate = false;
        			}
        			if(duplicate == true) { //two items of set 1 found in set 2 --> contradicting
    					break;
    				}
        		}
        	} else {
        		for(var x = 0; x < singleTaskIdsInsertedSeparation.length; x++) {
        			for(var w = 0; w < singleTaskIdsSavedSeparations.length; w++) {
        				if(singleTaskIdsSavedSeparations[w] == singleTaskIdsInsertedSeparation[x]) {
        					check++;
        					if(check == 2) {
        						duplicate = true;
        					}
        					break;
        				}
        				duplicate = false;
        			}
        			if(duplicate == true) { //two items of set 1 found in set 2 --> contradicting
    					break;
    				}
        		}
        	}

	        if(duplicate == true) { //entry does exist, delete?
				var bodDelete = confirm("Do you want to delete the existing contradicting separation for allowing this binding constraint to be entered? Otherwise, this binding constraint will be discarded.");
				if(bodDelete == true) {
					this.findSeparationEntry(selectedTasks);
					duplicate = false;
				}
	        	break;
	        }
        }//end check whether separation entry does already exist

        returnValue = duplicate;
        return returnValue;
    },

    writeEntry: function(savedBindingsData, selectedTasks, taskElement) { //create JSON object and write to task attributes
    	if(savedBindingsData[1] > 0) { //saved entries do exist
    		savedBindingsData[1]++; //number of entries
    		savedBindingsData[2]++; //highestId needs to be higher than all found ids
    		savedBindingsData[0] = savedBindingsData[0].substring((savedBindingsData[0].indexOf(':'))+2);
    		savedBindingsData[0] = "{'totalCount':" + savedBindingsData[1] + savedBindingsData[0] + ", {bodId:\"" + savedBindingsData[2] + "\", BoundTasks:\"" + selectedTasks + "\"}]}";
    	} else { //first entry to be done
    		savedBindingsData[1] = 1;
    		savedBindingsData[2]++; //highestId needs to be higher than all found ids
    		savedBindingsData[0] = "{'totalCount':" + savedBindingsData[1] + ", 'items':[{bodId:\"" + savedBindingsData[2] + "\", BoundTasks:\"" + selectedTasks + "\"}]}";
    	}
    	taskElement.setProperty("oryx-bindingsofduties", savedBindingsData[0]);
    },

	deleteBindingEntry: function(taskElement, elementId) { //delete given entry from given task from binding contraints
		var returnValue = [];
		var bindings = taskElement.properties["oryx-bindingsofduties"]; //get saved separations
		var keptBindings;
		var temp;
		var totalCount = parseInt(bindings.substring((bindings.indexOf(':')) + 1));
		totalCount = totalCount - 1;
		if(totalCount > 0)  {
			bindings = bindings.substring(bindings.indexOf('[')); //{'totalCount':3, 'items':
			keptBindings = bindings.substring(0,bindings.indexOf('{')); //[
			bindings = bindings.substring(bindings.indexOf('{')); //[
			temp = bindings.substring(0,(bindings.indexOf('"')) + 1); //{bodId:"
			bindings = bindings.substring((bindings.indexOf('"')) + 1); //{bodId:"
			while(parseInt(bindings) != elementId) {
				keptBindings = keptBindings + temp + bindings.substring(0,(bindings.indexOf('{')) - 2); //'id'", BoundTasks:"task_a; task_b"}
				bindings = bindings.substring((bindings.indexOf('{')) - 2); //'id'", BoundTasks:"task_a; task_b"}
				temp = bindings.substring(0,((bindings.indexOf('"')) + 1)); //, {bodId:"
				bindings = bindings.substring((bindings.indexOf('"')) + 1); //, {bodId:"
			}
			bindings = bindings.substring((bindings.indexOf('}'))+3); //'bodId'", BoundTasks:"task_c; task_d; task_e"} or //{bodId:"'id'", BoundTasks:"task_c; task_d; task_e"},_
			var entry = "{'totalCount':" + totalCount + ", 'items':" + keptBindings + bindings + "]}";
			taskElement.setProperty("oryx-bindingsofduties", entry);

			entry = entry.toString();
			entry = entry.substring(0,entry.indexOf(']'));

		} else {
			var entry = "";
			taskElement.setProperty("oryx-bindingsofduties", entry);
		}

		returnValue[0] = entry;
		returnValue[1] = totalCount;
		return returnValue;
	},

	findSeparationEntry: function(taskIds) { //find separation entry with given task ids to be deleted at all affected tasks
		var taskIdsCopy = taskIds;
		var singleTaskIds = [];
		var s = 0;

		//extract task ids of affected tasks
    	while(taskIdsCopy.indexOf(';') > -1) {
    		singleTaskIds[s] = taskIdsCopy.substring(0, taskIdsCopy.indexOf(';'));
    		taskIdsCopy = taskIdsCopy.substring((taskIdsCopy.indexOf(';'))+2);
	        s++;
        }
    	singleTaskIds[s] = taskIdsCopy;

		taskIdsCopy = taskIds + ";";
		for (var m = 0; m < singleTaskIds.length; m++) { //go through all affected tasks
			var currentTask = this.getTaskById(singleTaskIds[m]);
			var separations = currentTask.properties["oryx-separationofduties"]; //get saved separations
			var separatedTaskIds = [];
			var totalCount = 0;
			var i = 0; //counter
			var j = 0; //counter
			while(separations.indexOf(',') > -1) {
	    		if(i%2 == 1) { //get element ids as integer
			    	separations = separations.substring((separations.indexOf(',')) + 1);
	    		} else if(i == 0) { //get totalCount
	    			totalCount = parseInt(separations.substring((separations.indexOf(':')) + 1));
					separations = separations.substring((separations.indexOf(',')) + 1);
	    		} else { //get task ids
	    			separations = separations.substring((separations.indexOf('"')) + 1);
	    			separatedTaskIds[j] = separations.substring(0,separations.indexOf('"'));
	    			j++;
	    			separations = separations.substring((separations.indexOf(',')) + 1);
	    		}
		        i++;
	    	}
			//transform id string into array - one constraint set equals one array entry
	    	if(separations.indexOf('"') > -1) {
	    		separatedTaskIds[j] = separations.substring((separations.indexOf('"')) + 1);
	    	} else {
	    		separatedTaskIds[j] = separations; //never reached??
	    	}
	    	separatedTaskIds[j]= separatedTaskIds[j].substring(0,separatedTaskIds[j].indexOf('"'));

			var singleTaskIdsStoredSeparation = [];

			//check each separation entry
			for (var index = 0; index < separatedTaskIds.length; index++) {
				var separatedTasksCopy = separatedTaskIds[index];
				var t = 0; //counter
				//extract task ids of stored elements
				while (separatedTasksCopy.indexOf(';') > -1) {
					singleTaskIdsStoredSeparation[t] = separatedTasksCopy.substring(0, separatedTasksCopy.indexOf(';'));
					separatedTasksCopy = separatedTasksCopy.substring((separatedTasksCopy.indexOf(';')) + 2);
					t++;
				}
				singleTaskIdsStoredSeparation[t] = separatedTasksCopy;

				if (singleTaskIds.length >= singleTaskIdsStoredSeparation.length) {
					var equalCounter = 0;
					for (var x = 0; x < singleTaskIdsStoredSeparation.length; x++) {
						for (var y = 0; y < singleTaskIds.length; y++) {
							if (singleTaskIdsStoredSeparation[x] == singleTaskIds[y]) {
								equalCounter++;
								break;
							}
						}
						if (equalCounter == singleTaskIdsStoredSeparation.length) { //entry found
							this.deleteSeparationEntry(currentTask, (index+1)); //delete entry
							break;
						}
					}
				}
				singleTaskIdsStoredSeparation.splice(0,singleTaskIdsStoredSeparation.length);
			}
		}
	},

	deleteSeparationEntry: function(taskElement, elementId) { //delete defined entry in given task
		var separations = taskElement.properties["oryx-separationofduties"]; //get saved separations
		var keptSeparations;
		var temp;
		var totalCount = parseInt(separations.substring((separations.indexOf(':')) + 1));
		totalCount = totalCount - 1;
		if(totalCount > 0)  { //remove specified entry
			separations = separations.substring(separations.indexOf('[')); //{'totalCount':3, 'items':
			keptSeparations = separations.substring(0,separations.indexOf('{')); //[
			separations = separations.substring(separations.indexOf('{')); //[
			temp = separations.substring(0,(separations.indexOf('"')) + 1); //{sodId:"
			separations = separations.substring((separations.indexOf('"')) + 1); //{sodId:"
			while(parseInt(separations) != elementId) {
				keptSeparations = keptSeparations + temp + separations.substring(0,(separations.indexOf('{')) - 2); //'id'", SeparatedTasks:"task_a; task_b"}
				separations = separations.substring((separations.indexOf('{')) - 2); //'id'", SeparatedTasks:"task_a; task_b"}
				temp = separations.substring(0,((separations.indexOf('"')) + 1)); //, {sodId:"
				separations = separations.substring((separations.indexOf('"')) + 1); //, {sodId:"
			}
			separations = separations.substring((separations.indexOf('}'))+3); //'sodId'", SeparatedTasks:"task_c; task_d; task_e"} or //{sodId:"'id'", SeparatedTasks:"task_c; task_d; task_e"},_
			var entry = "{'totalCount':" + totalCount + ", 'items':" + keptSeparations + separations + "]}";
			taskElement.setProperty("oryx-separationofduties", entry);

			entry = entry.toString();
			entry = entry.substring(0,entry.indexOf(']'));

		} else { //remove last entry
			var entry = "";
			taskElement.setProperty("oryx-separationofduties", entry);
		}
	},

	getTaskById: function(taskId){
		var shapes = this.facade.getCanvas().getChildShapes(true);
		var task;
		for (var index = 0; index < shapes.length; index++) {
    		if (shapes[index].properties["oryx-activitytype"] == "Task") {
				if (shapes[index].properties["oryx-id"] == taskId) {
					task = shapes[index];
					break;
				}
			}
    	}
		return task;
	}
});


text:
using System;
using KallynGowdy.ParserGenerator.Grammar;

namespace KallynGowdy.ParserGenerator.Definitions
{
	/// <summary>
	///     Defines an interface for objects that support matching themselves to terminals
	/// </summary>
	public interface ITerminalMatch<T>
		where T : IEquatable<T>
	{
		bool TerminalMatch(Terminal<T> terminal);
	}
}


text:
<?php
/**
 * @link https://github.com/old-town/old-town-workflow
 * @author  Malofeykin Andrey  <and-rey2@yandex.ru>
 */
namespace OldTown\Workflow\Loader\Traits;

/**
 * Class ConditionDescriptor
 *
 * @package OldTown\Workflow\Loader
 */
interface NameInterface
{
    /**
     * Возвращает имя
     *
     * @return string
     */
    public function getName();

    /**
     * Устанавливает имя
     *
     * @param $name
     *
     * @return $this
     */
    public function setName($name);
}


text:
local time_table = {}

Timer = {}

function Timer:new(sid)
    self.__index = self
    local ins = setmetatable({}, self)
    ins.timers = {}
    ins.sid = sid
    ins.tid = 0
    time_table[sid] = ins
    return ins
end

function Timer:settimer(interval, count, func, ...)
    self.tid = self.tid + 1
    local mark = os.time()
    local t = {mark, interval, count, func, ...}
    self.timers[self.tid] = t
    return self.tid
end

function Timer:update()
    for k, v in pairs(self.timers) do
        local t = os.time()
        local count = v[3]
        if t - v[2] >= v[1] then
            v[1] = t
            if count ~= nil then
                v[3] = count - 1
            end
            v[4](unpack(v, 5))

            if count ~= nil and count <= 1 then
                self:rmtimer(k)
            end
        end
    end
end

function Timer:rmtimer(tid)
    self.timers[tid] = nil
end

function Timer:activeTimer(tid)
    local timer = self.timers[tid]
    if timer then
        timer[1] = 0
    end
end

function TimerUpdate()
    for k, v in pairs(time_table) do
        v:update()
    end
end


text:
package com.jasongj.kafka;

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

import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.message.MessageAndMetadata;

public class DemoHighLevelConsumer {

	public static void main(String[] args) {
		args = new String[] { "zookeeper0:2181/kafka", "topic1", "group2", "consumer1" };
		if (args == null || args.length != 4) {
			System.err.println("Usage:\n\tjava -jar kafka_consumer.jar ${zookeeper_list} ${topic_name} ${group_name} ${consumer_id}");
			System.exit(1);
		}
		String zk = args[0];
		String topic = args[1];
		String groupid = args[2];
		String consumerid = args[3];
		Properties props = new Properties();
		props.put("zookeeper.connect", zk);
		props.put("group.id", groupid);
		props.put("client.id", "test");
		props.put("consumer.id", consumerid);
		props.put("auto.offset.reset", "largest");
		props.put("auto.commit.enable", "false");
		props.put("auto.commit.interval.ms", "60000");

		ConsumerConfig consumerConfig = new ConsumerConfig(props);
		ConsumerConnector consumerConnector = Consumer.createJavaConsumerConnector(consumerConfig);

		Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
		topicCountMap.put(topic, 1);
		Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumerConnector.createMessageStreams(topicCountMap);

		KafkaStream<byte[], byte[]> stream1 = consumerMap.get(topic).get(0);
		ConsumerIterator<byte[], byte[]> interator = stream1.iterator();
		while (interator.hasNext()) {
			MessageAndMetadata<byte[], byte[]> messageAndMetadata = interator.next();
			String message = String.format(
					"Topic:%s, GroupID:%s, Consumer ID:%s, PartitionID:%s, Offset:%s, Message Key:%s, Message Payload: %s",
					messageAndMetadata.topic(), groupid, consumerid, messageAndMetadata.partition(),
					messageAndMetadata.offset(), new String(messageAndMetadata.key()),
					new String(messageAndMetadata.message()));
			System.out.println(message);
			consumerConnector.commitOffsets();
		}
	}

}


text:
package org.smartx.summer.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * <p> 开启cache特性的注解, 详见{@link org.smartx.summer.interceptor.CacheAdvice} </p>
 *
 * <b>Creation Time:</b> 2016年10月21日
 *
 * @author binglin
 * @since summer 0.1
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableCache {
}


text:
prefpane > groupbox { margin: 0; }
prefpane .groupbox-body { -webkit-appearance: none; -moz-appearance: none; padding-left: 0; padding-right: 0; }
#web-developer-options { min-width: 45em; }
#web-developer-options-tools-pane spacer { width: 2em; }
#web-developer-syntax-highlight-browser { border: 1px solid #999; height: 150px !important; }


text:
    clear : both;
    height : 300px;
    margin-top : 20px;
    padding : 0px;
}
#employee_name {
    background : #fff url(../../images/student_details/ajax_result_underline.jpg) bottom left no-repeat;
    float : left;
    padding : 10px 10px 10px 0;
    text-decoration : none;
    width : 230px;
}
#employee_name a {
    color : #000;
    font-weight : bold;
    text-decoration : none;
}

.label-field-pair{
    margin:0 auto;
}


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

namespace Sdl.Community.GroupShareKit.Models.Response.TranslationMemory
{
    public class PlaceholderTagDefinition
    {
        /// <summary>
        /// Gets or sets the id
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// Gets or sets display text
        /// </summary>
        public string DisplayText { get; set; }
        /// <summary>
        /// Gets or sets tag content
        /// </summary>
        public string TagContent { get; set; }
        /// <summary>
        /// Gets or sets text equivalent
        /// </summary>
        public string TextEquivalent { get; set; }
        /// <summary>
        /// Gets or sets segmentation hint
        /// </summary>
        public string SegmentationHint { get; set; }
        /// <summary>
        /// Gets or sets subcontent
        /// </summary>
        public List<SubContent> SubContent { get; set; }
        /// <summary>
        /// Gets or sets metadata
        /// </summary>
        public Metadata Metadata { get; set; }
    }
}


text:
@class SCGoodsSetModel;
@interface SCGoodsSetCell : UICollectionViewCell
@property(nonatomic,strong)SCGoodsSetModel *listModel;
@end


text:
<title>LiveZilla Live Support - http://www.livezilla.net</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="pragma" content="no-cache">
<meta name="robots" content="follow">
<meta name="revisit-after" CONTENT="5">
<meta name="author" content="LiveZilla GmbH">
<meta name="description" content="LiveZilla Live Support Software For Your Website">
<meta name="keywords" content="livezilla, live support, live support, customer support, livechat, livehelp, help desk, helpdesk">
<meta http-equiv="refresh" content="20;url=./../index.php">

Thank you for using LiveZilla!

You will be redirected to the LiveZilla Server Page of this installation
shortly - Please click if redirection doesn't work ...

		LiveZilla Live Support - http://www.livezilla.net


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Laboulbenia cubensis Thaxt.

### Remarks
null


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width; initial-scale=1.0, maximum-scale=1">
    <link href="/public/favicon.ico" rel="shortcut icon" type="image/x-icon">
    <link href="http://gmpg.org/xfn/11" rel="profile">

    <title>
      Hola ·
      Blog de Pablo
    </title>

    <link rel="stylesheet" href="/public/css/hyde.css">
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Belleza|Sarina">

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/touch-icon-144-precomposed.png">
    <link rel="shortcut icon" href="/public/favicon.png">

    <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

Blog

Este es el blog de Pablo.

              Download

              GitHub project

Currently v1.0

© 2013. All rights reserved.

Hola

  06 Feb 2012

Este es un post de prueba

Hasta luego.

Related Posts


text:
/**
 * Contains a {@link javax.sql.DataSource} implementation.
 *
 * <p>This package also has some integration classes for the Spring Framework.
 */
package com.tzavellas.poolng.ds;


text:
from django.db import models

# Create your models here.
from wham.fields import WhamCharField, WhamTextField, WhamIntegerField, \
    WhamManyToManyField, WhamFloatField, WhamForeignKey
from wham.models import WhamModel

class EventbriteMeta:
    base_url = 'https://www.eventbriteapi.com/v3/'
    requires_oauth_token = True

class EventbriteVenue(WhamModel):

    id = WhamCharField(max_length=255, primary_key=True)
    name = WhamTextField()
    latitude = WhamFloatField()
    longitude = WhamFloatField()

    city = WhamTextField(wham_result_path=('address', 'city'), null=True)
    country = WhamTextField(wham_result_path=('address', 'country'), null=True)
    region = WhamTextField(wham_result_path=('address', 'region'), null=True)
    address_1 = WhamTextField(wham_result_path=('address', 'address_1'), null=True)
    address_2 = WhamTextField(wham_result_path=('address', 'address_2'), null=True)
    country_name = WhamTextField(wham_result_path=('address', 'country_name'), null=True)

    class Meta:
        db_table = 'eventbrite_venue'

    def __unicode__(self):
        return self.name

class EventbriteEvent(WhamModel):

    id = WhamCharField(max_length=255, primary_key=True)
    name = WhamTextField(wham_result_path=('name', 'text'))
    resource_uri = WhamTextField()
    url = WhamTextField()
    capacity = WhamIntegerField()
    venue = WhamForeignKey(EventbriteVenue, null=True) #this should be a foreign key! But we only support m2m so far.

    class WhamMeta(EventbriteMeta):
        endpoint = 'events'

        class Search:
            endpoint = 'events/search'
            results_path = ('events',)

    class Meta:
        db_table = 'eventbrite_event'

    def __unicode__(self):
        return self.name


text:
'use strict';

var braces = require('braces');
var uniq = require('array-uniq');
var slice = require('array-slice');

module.exports = function expand() {
  var args = slice(arguments);
  var len = args.length;
  var i = 0;
  var fn;

  var patterns = [];

  while (i < len) {
    var arg = args[i++];

    if (typeof arg === 'string') {
      patterns.push(arg);
    }

    if (Array.isArray(arg)) {
      patterns.push.apply(patterns, arg);
    }

    if (typeof arg === 'function') {
      fn = arg;
      break;
    }
  }

  var plen = patterns.length;
  var arr = [];
  var j = 0;

  while (j < plen) {
    arr.push.apply(arr, braces(patterns[j++], fn));
  }
  return uniq(arr);
};

//# sourceMappingURL=filter-compiled.js.map


text:
require 'spec_helper'

describe UsersController do

  def mock_user(stubs={})
    (@mock_user ||= mock_model(User).as_null_object).tap do |user|
      user.stub(stubs) unless stubs.empty?
    end
  end

  describe "GET index" do
    it "assigns all users as @users" do
      User.stub(:all) { [mock_user] }
      get :index
      assigns(:users).should eq([mock_user])
    end
  end

  describe "GET show" do
    it "assigns the requested user as @user" do
      User.stub(:find).with("37") { mock_user }
      get :show, :id => "37"
      assigns(:user).should be(mock_user)
    end
  end

  describe "GET new" do
    it "assigns a new user as @user" do
      User.stub(:new) { mock_user }
      get :new
      assigns(:user).should be(mock_user)
    end
  end

  describe "GET edit" do
    it "assigns the requested user as @user" do
      User.stub(:find).with("37") { mock_user }
      get :edit, :id => "37"
      assigns(:user).should be(mock_user)
    end
  end

  describe "POST create" do

    describe "with valid params" do
      it "assigns a newly created user as @user" do
        User.stub(:new).with({'these' => 'params'}) { mock_user(:save => true) }
        post :create, :user => {'these' => 'params'}
        assigns(:user).should be(mock_user)
      end

      it "redirects to the created user" do
        User.stub(:new) { mock_user(:save => true) }
        post :create, :user => {}
        response.should redirect_to(user_url(mock_user))
      end
    end

    describe "with invalid params" do
      it "assigns a newly created but unsaved user as @user" do
        User.stub(:new).with({'these' => 'params'}) { mock_user(:save => false) }
        post :create, :user => {'these' => 'params'}
        assigns(:user).should be(mock_user)
      end

      it "re-renders the 'new' template" do
        User.stub(:new) { mock_user(:save => false) }
        post :create, :user => {}
        response.should render_template("new")
      end
    end

  end

  describe "PUT update" do

    describe "with valid params" do
      it "updates the requested user" do
        User.should_receive(:find).with("37") { mock_user }
        mock_user.should_receive(:update_attributes).with({'these' => 'params'})
        put :update, :id => "37", :user => {'these' => 'params'}
      end

      it "assigns the requested user as @user" do
        User.stub(:find) { mock_user(:update_attributes => true) }
        put :update, :id => "1"
        assigns(:user).should be(mock_user)
      end

      it "redirects to the user" do
        User.stub(:find) { mock_user(:update_attributes => true) }
        put :update, :id => "1"
        response.should redirect_to(user_url(mock_user))
      end
    end

    describe "with invalid params" do
      it "assigns the user as @user" do
        User.stub(:find) { mock_user(:update_attributes => false) }
        put :update, :id => "1"
        assigns(:user).should be(mock_user)
      end

      it "re-renders the 'edit' template" do
        User.stub(:find) { mock_user(:update_attributes => false) }
        put :update, :id => "1"
        response.should render_template("edit")
      end
    end

  end

  describe "DELETE destroy" do
    it "destroys the requested user" do
      User.should_receive(:find).with("37") { mock_user }
      mock_user.should_receive(:destroy)
      delete :destroy, :id => "37"
    end

    it "redirects to the users list" do
      User.stub(:find) { mock_user }
      delete :destroy, :id => "1"
      response.should redirect_to(users_url)
    end
  end

end


text:
title: "How GitLab works remotely"
date: 2014-07-03
categories:
author: Job van der Voort
---

GitLab is a fully remote company, meaning that all of us (currently six) work 100% of our time from home or any other place in the world. We're not the first to do this, [Wordpress](http://blogs.hbr.org/2013/03/how-wordpress-thrives-with-a-1/) does it on a much larger scale, but it might be nice for high-growth startups to see how we handle it. It doesn't require as much tools or effort as you might think.

Currently we're based in Ukraine (1), Serbia (1) and The Netherlands (4).

## Morning Meeting

Every morning at 8:00 CET (note: you have to know your timezones working remotely) we have a morning meeting with the whole team. Nowadays we use [vLine](https://vline.com/) for this, as Google Hangouts was unreliable with more than four people.

![our morning meeting](/images/remotely/meeting.png)

<!--more-->

We keep an agenda in Google Docs, and limit it to 45 minutes. Anyone can add anything on the agenda. Every call starts with a round of 'What did you do yesterday?', where everyone tells what they did *after* work; almost always worth some laughs. Next we go over the points and note in the agenda what the follow-up is for each item.
In depth discussions are moved to later or after the call with only the relevant participants, rather than having three people doze off while the rest talks about webserver worker optimization.

## Worktimes

People are free to choose when to work, but most of us work during regular office hours. The flexibility that remote working brings makes that we don't have to worry about living life at the end of the day. This is a daily sight in our Slack:

![During the day we not only work.](/images/remotely/slack.png)

Everyone in GitLab actually goes to a gym, does some kind of dancing or sports in another way. As it is with a startup, there is always a lot of work to do today and more tomorrow. We find that it works best to work when you work best.

## Communication

We prefer asynchronous communication and specifically GitLab issues. By mentioning someone, that person can reply whenever they have time to reply. It's usually not a good idea to [interrupt someone](http://heeris.id.au/2013/this-is-why-you-shouldnt-interrupt-a-programmer).

For all other communication we use [Slack](https://www.slack.com) and one of the video call platforms, such as [Google Hangouts](http://www.google.com/hangouts/), [Skype](http://www.skype.com/nl/) and [vLine](https://vline.com/). For communication with our customers, we do the exact same thing.

## Social and Happiness

Every single week, everyone talks individually with Sytse (GitLab CEO) about their happiness. He makes sure everyone is happy and not lacking anything. That works really well.

Besides the morning meetings and weekly calls with Sytse, we also meet up in the physical world to work or -more frequently- eat and drink together. If we can't meet in person, we have a hangout online. With every release of GitLab (22nd of each month!) we have a call together where everyone gets their favorite drink and we just have some -remote- fun together.

Working remotely, at least for GitLab, is quite a lot of fun.


text:
#ifndef __TestJson_h__
#define __TestJson_h__

#include "../TestBasic.h"

class TestJson : public TestBasic
{
	public :

		CREATE_FUNC ( TestJson );

	protected :

		virtual KDbool		init ( KDvoid );

		virtual KDvoid		ccTouchesEnded ( CCSet* pTouches, CCEvent* pEvent );

		KDvoid				Encoding ( KDvoid );

		KDvoid				Decoding ( KDvoid );

	protected :

		CCLabelTTF*			m_pLabel;
};

#endif	// __TestJson_h__


text:
package com.lightcrafts.media.jai.codecimpl;
import java.awt.image.BufferedImage;
import java.awt.image.ComponentSampleModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.io.FilterInputStream;
import java.io.InputStream;
import java.io.IOException;
import com.lightcrafts.media.jai.codec.ImageDecoderImpl;
import com.lightcrafts.media.jai.codec.ImageDecodeParam;
import com.lightcrafts.media.jai.codec.JPEGDecodeParam;
import com.lightcrafts.media.jai.codecimpl.ImagingListenerProxy;
import com.lightcrafts.media.jai.codecimpl.util.ImagingException;
import com.sun.image.codec.jpeg.ImageFormatException;

/**
 * @since EA2
 */
public class JPEGImageDecoder extends ImageDecoderImpl {

    public JPEGImageDecoder(InputStream input,
                            ImageDecodeParam param) {
        super(input, param);
    }

    public RenderedImage decodeAsRenderedImage(int page) throws IOException {
        if (page != 0) {
            throw new IOException(JaiI18N.getString("JPEGImageDecoder0"));
        }
        try {
            return new JPEGImage(input, param);
        } catch(Exception e) {
            throw CodecUtils.toIOException(e);
        }
    }
}

/**
 * FilterInputStream subclass which does not support mark/reset.
 * Used to work around a failure of com.sun.image.codec.jpeg.JPEGImageDecoder
 * in which decodeAsBufferedImage() blocks in reset() if a corrupted JPEG
 * image is encountered.
 */
class NoMarkStream extends FilterInputStream {
    NoMarkStream(InputStream in) {
        super(in);
    }

    /**
     * Disallow mark/reset.
     */
    public boolean markSupported() {
        return false;
    }

    /**
     * Disallow close() from closing the stream passed in.
     */
    public final void close() throws IOException {
        // Deliberately do nothing.
    }
}

class JPEGImage extends SimpleRenderedImage {

    /**
     * Mutex for the entire class to circumvent thread unsafety of
     * com.sun.image.codec.jpeg.JPEGImageDecoder implementation.
     */
    private static final Object LOCK = new Object();

    private Raster theTile = null;

    /**
     * Construct a JPEGmage.
     *
     * @param stream The JPEG InputStream.
     * @param param The decoding parameters.
     */
    public JPEGImage(InputStream stream, ImageDecodeParam param) {
        // If the supplied InputStream supports mark/reset wrap it so
        // it does not.
        if(stream.markSupported()) {
            stream = new NoMarkStream(stream);
        }

        // Lock the entire class to work around lack of thread safety
        // in com.sun.image.codec.jpeg.JPEGImageDecoder implementation.
        BufferedImage image = null;
        synchronized(LOCK) {
            com.sun.image.codec.jpeg.JPEGImageDecoder decoder =
                com.sun.image.codec.jpeg.JPEGCodec.createJPEGDecoder(stream);
            try {
                // decodeAsBufferedImage performs default color conversions
                image = decoder.decodeAsBufferedImage();
            } catch (ImageFormatException e) {
                String message = JaiI18N.getString("JPEGImageDecoder1");
                sendExceptionToListener(message, (Exception)e);
//                throw new RuntimeException(JaiI18N.getString("JPEGImageDecoder1"));
            } catch (IOException e) {
                String message = JaiI18N.getString("JPEGImageDecoder1");
                sendExceptionToListener(message, (Exception)e);
//                throw new RuntimeException(JaiI18N.getString("JPEGImageDecoder2"));
            }
        }

        minX = 0;
        minY = 0;
        tileWidth = width = image.getWidth();
        tileHeight = height = image.getHeight();

        // Force image to have a ComponentSampleModel if it does not have one
        // and the ImageDecodeParam is either null or is a JPEGDecodeParam
        // with 'decodeToCSM' set to 'true'.
        if ((param == null ||
             (param instanceof JPEGDecodeParam &&
              ((JPEGDecodeParam)param).getDecodeToCSM())) &&
            !(image.getSampleModel() instanceof ComponentSampleModel)) {

            int type = -1;
            int numBands = image.getSampleModel().getNumBands();
            if (numBands == 1) {
                type = BufferedImage.TYPE_BYTE_GRAY;
            } else if (numBands == 3) {
                type = BufferedImage.TYPE_3BYTE_BGR;
            } else if (numBands == 4) {
                type = BufferedImage.TYPE_4BYTE_ABGR;
            } else {
                throw new RuntimeException(JaiI18N.getString("JPEGImageDecoder3"));
            }

            BufferedImage bi = new BufferedImage(width, height, type);
            bi.getWritableTile(0, 0).setRect(image.getWritableTile(0, 0));
            bi.releaseWritableTile(0, 0);
            image = bi;
        }

        sampleModel = image.getSampleModel();
        colorModel = image.getColorModel();

        theTile = image.getWritableTile(0, 0);
    }

    public synchronized Raster getTile(int tileX, int tileY) {
        if (tileX != 0 || tileY != 0) {
            throw new IllegalArgumentException(JaiI18N.getString("JPEGImageDecoder4"));
        }

        return theTile;
    }

    public void dispose() {
        theTile = null;
    }

    private void sendExceptionToListener(String message, Exception e) {
        ImagingListenerProxy.errorOccurred(message, new ImagingException(message, e),
                               this, false);
    }
}


text:
import renpy.store as store
import renpy.exports as renpy
import os
import datetime
from inspect import currentframe, getframeinfo

class Logger(store.object):

    instances = []

    def __init__(self, fileLoc, verbosity=True, failQuietly=False):
        self.fileLoc = fileLoc
        self.failQueitly = failQuietly
        self.fw = open(self.fileLoc, 'w')
        self.fw.write("File initialization completed...")
        self.fw.close()
        self.psp()

        self.tags = {}
        self.tags["__main__"] = verbosity

        self.indentSize = 0
        #add instance to instance list
        Logger.instances.append(self)

    def writeTo(self, textString, indent=0, verbose=True, shift=None, tag=None):
        if tag != None:
            try:
                tagValue = self.tags[tag]
            except:
                tagValue = True
        else:
            tagValue = True

        if self.tags["__main__"] and tagValue:
            try:
                self.fa = open(self.fileLoc, 'a')
            except IOError:
                try:
                    self.fa = open(store._config.gamedir + self.fileLoc, 'a')
                except IOError:
                    if not failQuietly:
                        self.error("Logger file was not found at:\n" + self.fileLoc + "\nor\n" + store._config.gamedir + self.fileLoc)
                    else:
                        return
            indentSize = ""
            if indent != 0:
                for i in xrange(indent):
                    indentSize += "\t"
            else:
                for i in xrange(self.indentSize):
                    indentSize += "\t"
            if shift == "up":
                indentSize += "\t"
            elif shift == "down":
                if indentSize > 0:
                    indentSize = indentSize[:-1]

            self.fa.write("[" + unicode(datetime.datetime.now()) + "] " + indentSize + textString + "\n")
            self.fa.close()
        else:
            if not verbose:
                try:
                    self.fa = open(self.fileLoc, 'a')
                except IOError:
                    try:
                        self.fa = open(store._config.gamedir + self.fileLoc, 'a')
                    except IOError:
                        if not failQuietly:
                            self.error("Logger file was not found at:\n" + self.fileLoc + "\nor\n" + store._config.gamedir + self.fileLoc)
                        else:
                            return
                indentSize = ""
                if indent != 0:
                    for i in xrange(indent):
                        indentSize += "\t"
                else:
                    for i in xrange(self.indentSize):
                        indentSize += "\t"
                if shift == "up":
                    indentSize += "\t"
                elif shift == "down":
                    if indentSize > 0:
                        indentSize = indentSize[:-1]

                self.fa.write("[" + unicode(datetime.datetime.now()) + "] " + indentSize + textString + "\n")
                self.fa.close()

    def up(self):
        if self.indentSize <= 0:
            self.indentSize += 1

    def down(self):
        if self.indentSize < 0:
            self.indentSize -= 1

    def setVerbosity(self, newValue):
        self.verbosity = newValue

    def getVerbosity(self):
        return self.verbosity

    def mute(self):
        self.setVerbosity(False)

    def unmute(self):
        self.setVerbosity(True)

    def newTag(self, tag, value=False):
        if not self.tags.has_key("tag"):
            try:
                self.tags[tag] = value
            except NameError:
                self.tags[tag] = False

    def setTag(self, tag, value):
        if self.tags.has_key(tag):
            self.tags[tag] = value

    #format macros

    def insertLabel(self, label):
        #new in V2.0, the function must open the file in append mode and close it when done
        try:
            self.fa = open(self.fileLoc, 'a')
        except IOError:
            try:
                self.fa = open(store._config.gamedir + self.fileLoc, 'a')
            except IOError:
                if not failQuietly:
                    self.error("Logger file was not found at:\n" + self.fileLoc + "\nor\n" + store._config.gamedir + self.fileLoc)
                else:
                    self.mute()
                    return

        splatLen = len(label) + 4 #+4 is for a space on either side and an asterisk on both sides of the string

        for x in xrange(splatLen):
            self.fa.write("*")

        self.fa.write("\n")

        self.fa.write("* " + label + " *\n")

        for x in xrange(splatLen):
            self.fa.write("*")
        self.fa.write("\n")
        self.fa.close()

    def pump(self):
        self.fa = open(self.fileLoc, 'a')
        self.fa.write("\n")
        self.fa.close()

    def dpump(self):
        self.pump()
        self.pump()

    def splat(self):
        self.fa = open(self.fileLoc, 'a')
        self.fa.write("************************************************************************************\n")
        self.fa.close()

    def dsplat(self):
        self.splat()
        self.splat()

    def psp(self):
        self.pump()
        self.splat()
        self.pump()

    def pdsp(self):
        self.pump()
        self.dsplat()
        self.pump()

    def repeat(self, input): #takes string or char and repeats it until the output string is 84 characters long, set to match the splat length
        self.fa = open(self.fileLoc, 'a')
        inputSize = len(input)
        defaultWidth = 84
        printfull = 84/inputSize
        printLeftOver = 84%inputSize
        outputString = ""
        for x in xrange(printfull):
            outputString += input
        for x in xrange(printLeftOver-1):
            outputString += input[x]
        self.fa.write(outputString)
        self.fa.close()

    def failQuietly(self):
        self.failQuetly = True

    def failLoudly(self):
        self.failQuietly = False

##################################################################################
## Error Logging

#Syntax for getting the frame info :

#        from inspect import currentframe, getframeinfo
#        frameinfo = getframeinfo(currentframe())
#        msg = "For whatever reason, no file was loaded."
#        myLogger.error(msg, frameinfo, True)

def postError(msg, log=True, frameinfo=None):
    if log:
        logError(msg, frameinfo)
    renpy.error(str(msg))

def logError(msg, frameinfo):
    if frameinfo != None:
        for x in xrange(len(Logger.instances)):
                    Logger.instances[x].pump()
                    Logger.instances[x].dsplat()
                    Logger.instances[x].writeTo("\n\n************\nError!\nAt line: " + str(frameinfo.lineno) +
                                                       "\nin file: " + str(frameinfo.filename) +
                                                       "\nError message: " + msg)
    else:
        for x in xrange(len(Logger.instances)):
                    Logger.instances[x].pump()
                    Logger.instances[x].dsplat()
                    Logger.instances[x].writeTo("\n\n************\nError!\n" +
                                                       "Error message: " + str(msg))


text:
package io.netty.handler.codec.spdy;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.IllegalReferenceCountException;
import io.netty.util.internal.StringUtil;

/**
 * The default {@link SpdyDataFrame} implementation.
 */
public class DefaultSpdyDataFrame extends DefaultSpdyStreamFrame implements SpdyDataFrame {

    private final ByteBuf data;

    /**
     * Creates a new instance.
     *
     * @param streamId the Stream-ID of this frame
     */
    public DefaultSpdyDataFrame(int streamId) {
        this(streamId, Unpooled.buffer(0));
    }

    /**
     * Creates a new instance.
     *
     * @param streamId  the Stream-ID of this frame
     * @param data      the payload of the frame. Can not exceed {@link SpdyCodecUtil#SPDY_MAX_LENGTH}
     */
    public DefaultSpdyDataFrame(int streamId, ByteBuf data) {
        super(streamId);
        if (data == null) {
            throw new NullPointerException("data");
        }
        this.data = validate(data);
    }

    private static ByteBuf validate(ByteBuf data) {
        if (data.readableBytes() > SpdyCodecUtil.SPDY_MAX_LENGTH) {
            throw new IllegalArgumentException("data payload cannot exceed "
                    + SpdyCodecUtil.SPDY_MAX_LENGTH + " bytes");
        }
        return data;
    }

    @Override
    public SpdyDataFrame setStreamId(int streamId) {
        super.setStreamId(streamId);
        return this;
    }

    @Override
    public SpdyDataFrame setLast(boolean last) {
        super.setLast(last);
        return this;
    }

    @Override
    public ByteBuf content() {
        if (data.refCnt() <= 0) {
            throw new IllegalReferenceCountException(data.refCnt());
        }
        return data;
    }

    @Override
    public SpdyDataFrame copy() {
        SpdyDataFrame frame = new DefaultSpdyDataFrame(streamId(), content().copy());
        frame.setLast(isLast());
        return frame;
    }

    @Override
    public SpdyDataFrame duplicate() {
        SpdyDataFrame frame = new DefaultSpdyDataFrame(streamId(), content().duplicate());
        frame.setLast(isLast());
        return frame;
    }

    @Override
    public int refCnt() {
        return data.refCnt();
    }

    @Override
    public SpdyDataFrame retain() {
        data.retain();
        return this;
    }

    @Override
    public SpdyDataFrame retain(int increment) {
        data.retain(increment);
        return this;
    }

    @Override
    public SpdyDataFrame touch() {
        data.touch();
        return this;
    }

    @Override
    public SpdyDataFrame touch(Object hint) {
        data.touch(hint);
        return this;
    }

    @Override
    public boolean release() {
        return data.release();
    }

    @Override
    public boolean release(int decrement) {
        return data.release(decrement);
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder()
            .append(StringUtil.simpleClassName(this))
            .append("(last: ")
            .append(isLast())
            .append(')')
            .append(StringUtil.NEWLINE)
            .append("--> Stream-ID = ")
            .append(streamId())
            .append(StringUtil.NEWLINE)
            .append("--> Size = ");
        if (refCnt() == 0) {
            buf.append("(freed)");
        } else {
            buf.append(content().readableBytes());
        }
        return buf.toString();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Blog - Free Bulma template</title>
    <link rel="icon" type="image/png" sizes="32x32" href="../images/favicon.png">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

    <link rel="stylesheet" href="https://unpkg.com/bulma@0.7.4/css/bulma.min.css" />
    <link rel="stylesheet" type="text/css" href="../css/blog.css">

                            Home

                            Examples

                            Features

                            Team

                            Archives

                            Help

                                Account

                                    Dashboard

                                    Profile

                                    Settings

                                Logout

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed eiusmod tempor incididunt ut labore et dolore magna aliqua

Introducing a new feature for paid subscribers

                                    @skeetskeet
                                    May 10, 2018

Non arcu risus quis varius quam quisque. Dictum varius duis at consectetur lorem. Posuere sollicitudin aliquam ultrices sagittis orci a scelerisque purus semper.

Metus aliquam eleifend mi in nulla posuere sollicitudin aliquam ultrices. In hac habitasse platea dictumst vestibulum rhoncus est pellentesque elit. Accumsan lacus vel facilisis volutpat. Non sodales neque sodales ut etiam.
                                Est pellentesque elit ullamcorper dignissim cras tincidunt lobortis feugiat vivamus.

How to properly center tags in bulma?

 Proper centering of tags in bulma is done with class:
level-item

                                Voluptat ut farmacium tellus in metus vulputate. Feugiat in fermentum posuere urna nec. Pharetra convallis posuere morbi leo urna molestie.
                                Accumsan lacus vel facilisis volutpat est velit egestas. Fermentum leo vel orci porta. Faucibus interdum posuere lorem ipsum.

Sapien eget mi proin sed 🔱

                                    @daria on February 17, 2018

                                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Accumsan lacus vel facilisis volutpat est velit egestas. Sapien eget mi proin sed. Sit amet mattis vulputate enim.

                                Commodo ullamcorper a lacus vestibulum sed arcu. Fermentum leo vel orci porta non. Proin fermentum leo vel orci porta non pulvinar. Imperdiet proin fermentum leo vel. Tortor posuere ac ut consequat semper viverra. Vestibulum lectus mauris ultrices eros.

Lectus vestibulum mattis ullamcorper velit sed ullamcorper morbi. Cras tincidunt lobortis feugiat vivamus.

                                In eu mi bibendum neque egestas congue quisque egestas diam. Enim nec dui nunc mattis enim ut tellus. Ut morbi tincidunt augue interdum velit euismod in. At in tellus integer feugiat scelerisque varius morbi enim nunc. Vitae suscipit tellus mauris a diam.
                                Arcu non sodales neque sodales ut etiam sit amet.

                                 Nemo enim ipsam voluptatem quia.

                                    Natus error sit voluptatem

Cras tincidunt lobortis feugiat vivamus.

                                    @angela on October 7, 2017

                                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Accumsan lacus vel facilisis volutpat est velit egestas. Sapien eget mi proin sed. Sit amet mattis vulputate enim.

                                Commodo ullamcorper a lacus vestibulum sed arcu. Fermentum leo vel orci porta non. Proin fermentum leo vel orci porta non pulvinar. Imperdiet proin fermentum leo vel. Tortor posuere ac ut consequat semper viverra. Vestibulum lectus mauris ultrices eros.

"Everyone should be able to do one card trick, tell two jokes, and recite three poems, in case they are ever trapped in an elevator."

                                In eu mi bibendum neque egestas congue quisque egestas diam. Enim nec dui nunc mattis enim ut tellus. Ut morbi tincidunt augue interdum velit euismod in. At in tellus integer feugiat scelerisque varius morbi enim nunc. Vitae suscipit tellus mauris a diam.
                                Arcu non sodales neque sodales ut etiam sit amet.