text:
package org.cloudio.morpheus.chat

import java.util.concurrent.atomic.AtomicLong

import org.morpheus.{wrapper, dimension, fragment}
import org.morpheus.Morpheus._
import org.morpheus.{SuperBase, DefaultCompositeStrategy, MutableMorphMirror}

/**
*
* Created by zslajchrt on 18/03/15.
*/
class Contacts {

}

// MODEL

trait ContactTypes {

  type ContactType <: Contact

  def createContact(id: Option[Long]): ContactType

  // todo: it could be generated by a macro
  implicit def specialize(contact: Contact): ContactType = contact match {
    case c: ContactType => c
    case _ =>
      // this should never be called
      val spec = createContact(Some(contact.id))
      spec.adopt(contact)
      spec
  }

}

trait ContactConfig {
  val id: Long
}

object ContactConfig {
  def apply(contactId: Long) = new ContactConfig {
    override val id: Long = contactId
  }
}

@fragment
trait Contact extends ContactConfig {
  var name: String = _
  var email: String = _

  def adopt(other: Contact): Unit = {
    name = other.name
    email = other.email
  }
}

trait ContactListConfig {
  val ownerId: Option[Long]
}

object ContactListConfig {
  def apply() = new ContactListConfig {
    override val ownerId = None
  }

  def apply(owner: Long) = new ContactListConfig {
    override val ownerId = Some(owner)
  }
}

trait ContactListOwnerLoader {
  this: ContactTypes =>

  def loadOwner(ownerId: Option[Long]): ContactType

}

@fragment
trait ContactList extends ContactListConfig {

  this: ContactTypes with ContactListOwnerLoader =>

  lazy val _owner: ContactType = loadOwner(ownerId)
  protected var _contacts: List[ContactType] = Nil

  def owner: ContactType = _owner

  def contacts: List[ContactType] = _contacts

}

// PERSISTENCE

trait ContactPersistenceConfig {
  def contactsDAO: ContactsDAO
}

object ContactPersistenceConfig {
  def apply(contDAO: ContactsDAO) = new ContactPersistenceConfig {
    override def contactsDAO: ContactsDAO = contDAO
  }
}

@fragment
trait ContactPersistence extends ContactPersistenceConfig {

  this: Contact =>

  def persist(): Unit = {
    contactsDAO.updateContact(this)
  }

  def refresh(): Unit = {
    contactsDAO.refreshContact(this)
  }
}

@fragment
trait ContactListPersistence extends ContactListOwnerLoader {

  this: ContactTypes with ContactList with ContactsDAO =>

  override def loadOwner(ownerId: Option[Long]): ContactType = {
    loadContact(ownerId)
  }

  def loadContacts(): Unit = {
    _contacts = loadAllContacts(_owner)
  }

  def addToContactList(newContact: ContactType): ContactType = {
    addToContactList(owner, newContact)
    _contacts ::= newContact
    newContact
  }

  def removeFromContactList(contact: ContactType): Unit = {
    removeFromContactList(owner, contact)
    _contacts = _contacts.filter(_.id != contact.id)
  }
}

trait Presentable {
  def present: String
}

trait Validating {
  def isValid: Boolean
}

@fragment
trait PrettyPrintedContactList extends Presentable {
  this: ContactList with HasPrettyPrintedContact =>

  //def present: String = s"ContactList: ${contacts.mkString(",")}"
  def present: String = {
    s"ContactList: ${contacts.map(_.present).mkString(";")}"
  }

}

@fragment
trait ValidatingContactList extends Validating {
  this: ContactList with HasValidatingContact =>

  override def isValid: Boolean = contacts.forall(_.isValid)
}

@fragment
trait PrettyPrintedContact extends Presentable {
  this: Contact =>

  def present: String = s"{id=$id, name=$name, email=$email}"
}

@fragment
trait ValidatingContact extends Validating {
  this: Contact =>

  def isValid: Boolean = {
    // todo
    true
  }
}

// DAO for the contacts
//@dimension()
trait ContactsDAO {

  type ContactType <: Contact

  def initContactPersistence(): Unit

  def loadAllContacts(owner: ContactType): List[ContactType]

  def addToContactList(owner: ContactType, newContact: ContactType): Unit

  def removeFromContactList(owner: ContactType, contact: ContactType): Unit

  def loadContact(id: Option[Long]): ContactType

  def updateContact(contact: Contact): Unit

  def refreshContact(contact: Contact)
}

class ContactsDAO$dimension extends SuperBase[ContactsDAO] with ContactsDAO {

  outer =>

  private def sup = $super$.asInstanceOf[ContactsDAO {type ContactType = outer.ContactType}]

  override def loadAllContacts(owner: ContactType): List[ContactType] = sup.loadAllContacts(owner)

  override def initContactPersistence(): Unit = sup.initContactPersistence()

  override def updateContact(contact: Contact): Unit = sup.updateContact(contact)

  override def removeFromContactList(owner: ContactType, contact: ContactType): Unit = sup.removeFromContactList(owner, contact)

  override def loadContact(id: Option[Long]): ContactType = sup.loadContact(id)

  override def refreshContact(contact: Contact): Unit = sup.refreshContact(contact)

  override def addToContactList(owner: ContactType, newContact: ContactType): Unit = sup.addToContactList(owner, newContact)
}

// MOCK PERSISTENCE

// todo: This is very important! It allows us to specialize the composite type by overriding the abstract type member
trait HasPrettyPrintedContact {
  type ContactType <: Contact with PrettyPrintedContact
}

trait HasValidatingContact {
  type ContactType <: Contact with ValidatingContact
}

@fragment
trait MockContactTypes extends ContactTypes with HasPrettyPrintedContact with HasValidatingContact {
  this: ContactsDAO =>

  val contactModel = parse[Contact with PrettyPrintedContact with ValidatingContact with ContactPersistence](true)
  type ContactType = contactModel.MutableLUB

  private val idGen = new AtomicLong()

  def createContact(id: Option[Long]): ContactType = {
    implicit val contactConfig = single[Contact, ContactConfig](ContactConfig(id.getOrElse(idGen.getAndIncrement)))
    implicit val contactPersConfig = single[ContactPersistence, ContactPersistenceConfig](ContactPersistenceConfig(this))
    val contactComp = singleton(contactModel, DefaultCompositeStrategy(contactModel))
    contactComp.make_~
  }

}

//trait MockContactTypesStatic extends ContactTypes with HasPrettyPrintedContact with HasValidatingContact {
//  //val contactModel = parse[Contact with PrettyPrintedContact with ValidatingContact with ContactPersistence with MockContactsDAO](true)
//  type ContactType = Contact with PrettyPrintedContact with ValidatingContact with ContactPersistence with MockContactsDAO with MockContactTypesStatic
//
//  private val idGen = new AtomicLong()
//
//  def createContact(idOpt: Option[Long]): ContactType = new Contact with PrettyPrintedContact with ValidatingContact with ContactPersistence with MockContactsDAO with MockContactTypesStatic {
//    override val id: Long = idOpt.getOrElse(idGen.getAndIncrement)
//
//  }
//
//}

trait MockContactsDAOConfig {
  type ContactType <: Contact
}

@fragment
trait MockContactsDAO extends ContactsDAO {

  this: ContactTypes =>

  private var contacts: Map[Long, ContactType] = Map.empty
  private var contactLists: Map[Long, List[Long]] = Map.empty

  def initContactPersistence() {
    // create the initial contacts
    loadContact(None)
    loadContact(None)
    loadContact(None)
    contactLists += (0l -> List(1l, 2l))
  }

  def loadAllContacts(owner: ContactType): List[ContactType] = contactLists.get(owner.id) match {
    case None => Nil
    case Some(cl) => cl.map[ContactType, List[ContactType]](contacts(_))
  }

  def refreshContact(contact: Contact): Unit = {
    contacts.get(contact.id) match {
      case None => sys.error(s"Missing contact ${contact.id}")
      case Some(persistentContact) =>
        contact.adopt(persistentContact)
    }
  }

  def updateContact(contact: Contact): Unit = {
    contacts += (contact.id -> contact)
  }

  def loadContact(idOpt: Option[Long]): ContactType = {
    idOpt match {
      case None =>
        val newContact = createContact(None)
        contacts += (newContact.id -> newContact)
        newContact
      case Some(id) =>
        contacts.get(id) match {
          case None => sys.error(s"Missing contact $id")
          case Some(contact) => contact
        }
    }
  }

  def removeFromContactList(owner: ContactType, contact: ContactType): Unit = {
    val updatedContacts = contactLists(owner.id).filter(id => id != contact.id)
    contactLists += (owner.id -> updatedContacts)
  }

  def addToContactList(owner: ContactType, newContact: ContactType): Unit = {
    contactLists.get(owner.id) match {
      case None =>
        contacts += (newContact.id -> newContact)
        contactLists += (owner.id -> List(newContact.id))
      case Some(existingContacts) =>
        contacts += (newContact.id -> newContact)
        contactLists += (owner.id -> (newContact.id :: existingContacts))
    }
  }

}

//@fragment
//trait MockContactsDAODyna extends MockContactsDAO {
//  this: ContactTypes =>
//}


text:
package com.moebuff.discord.utils;

import com.moebuff.discord.utils.reflect.FieldKit;

import java.lang.reflect.Field;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 取消后又可重复执行的任务
 *
 * @author muto
 */
public abstract class RepetitiveTask extends TimerTask {
    private Field state;
    private Object virgin;

    public RepetitiveTask() {
        state = FieldKit.getDeclaredField(TimerTask.class, "state");
        virgin = FieldKit.readStaticField(TimerTask.class, "VIRGIN");
    }

    /**
     * 在执行 {@link #cancel()} 后,复位 {@link TimerTask}。
     *
     * @param t 执行该任务的计时器
     * @return 取消任务所给出的返回值
     */
    public boolean purge(Timer t) {
        boolean result = super.cancel();
        t.purge();//移除所有已取消的任务
        FieldKit.writeField(state, this, virgin);//复位
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package linalg;

public interface IAlgebra {

	public IMatrix createMatrix(double[] data);

	public IMatrix createMatrix(double[][] data);

	public IMatrix createZeros(int n, int m);

	public IMatrix createOnes(int n, int m);

	public IMatrix createEye(int n);

	public IMatrix createDiag(double[] data);

	public IMatrix invert(IMatrix arg);

	public IMatrix invertPositive(IMatrix arg) throws NonPosDefMatrixException;

	public IMatrix solve(IMatrix A, IMatrix B);

	public IMatrix solvePositive(IMatrix A, IMatrix B)
			throws NonPosDefMatrixException;

	public void solvePositiveInPlace(IMatrix A, IMatrix B)
			throws NonPosDefMatrixException;

	public IMatrix cholesky(IMatrix arg) throws NonPosDefMatrixException;

	/**
	 * Compute the singular value decomposition: arg = U*S*V'
	 *
	 * @return An array that holds the matrices: U, S ad V
	 */
	public IMatrix[] svd(IMatrix arg);

	public double determinant(IMatrix A);

}


text:
Poll Up

A free, simple polling web application

{{quest.question}}

Created by {{quest.username}}

                    <input class='form-control' ng-model='newQ' placeholder="Enter Question">

                        <input class='form-control' ng-model='choice.value' placeholder='Enter an option'>

                    <button class = 'btn btn-primary' ng-click='addOption()'>+ Option</button>
                    <button class = "btn btn-primary" ng-click='addQuestion()'>Add Question</button>

Log-in or sign-up to post a question!


text:
module APN
  module Backend
    autoload :Sidekiq,     'apn/backend/sidekiq'
    autoload :Resque,      'apn/backend/resque'

    class Simple
      def notify(*args)
        Thread.new do
          APN.notify_sync(*args)
        end
      end
    end

    class Null
      def notify(*args)
        APN.logger.info { "Null Backend sending message #{token}" }
      end
    end
  end
end


text:
import json
import os
from string import Template

ARCHITECTURE_FOLDER = "architecture"
DEFAULTS_FOLDER = "defaults"
TEMPLATES_FOLDER = "templates"

def convert_to_string(element):
	if type(element) == type(""):
		return element
	if type(element) == type([]) or type(element) == type((1,)) or type(element) == type({}):
		return "\n".join(element)
	return str(element)

class TemplateFile(object):
	def __init__(self, base_template, defaults = None):
		with open(base_template) as template:
			self.string_template = ''.join(template.readlines())
			self.parameters = {}
			if defaults is not None:
				with open(defaults) as fdefaults:
					self.parameters = json.load(fdefaults)

	def add_parameter(self, name, value):
		self.parameters[name] = value

	def save_to(self, output_filename):
		temp = Template(self.string_template)
		repl = temp.substitute(self.parameters)
		with open(output_filename, 'w') as output:
			output.write(repl)

class ReprClass(object):
	def __init__(self, parameters_filename, structure_template_filename, method_template_filename, attribute_template_filename):
		self.attributes = {}
		with open(parameters_filename) as data_file:
			data = json.load(data_file)
			self.type = data["type"]
			self.namespace = data["namespace"]
			self.hierarchy = data["hierarchy"]
			self.ItemName = data["ItemName"]
			self.structure_template_filename = structure_template_filename
			self.methods = self.process_methods(data["methods"])
			self.attributes = self.process_attribtues(data["attributes"])

	def process_methods(self, methods):
		new_attr = {}
		with open(os.path.join(TEMPLATES_FOLDER, self.method_template_filename)) as template_method:
			str_template = '\n'.join(template_method.readlines())
			for method in methods:
				template = Template(str_template)
				methods[method]["methodName"] = method
				parameters = methods[method]["parameters"]
				methods[method]["parameters"] = ",".join([parameter + " " + parameters[parameter] for parameter in parameters])
				new_attr[method] = template.substitute(methods[method])
		return new_attr

	def get_method_template_filename(self):
		return self.method_template_filename

	def process_attribtues(self, attributes):
		new_attr = {}
		with open(os.path.join(TEMPLATES_FOLDER, "attribute-template.txt")) as template_attribute:
			str_template = '\n'.join(template_attribute.readlines())
			for attribute in attributes:
				template = Template(str_template)
				attributes[attribute]["attributeName"] = attribute
				new_attr[attribute] = template.substitute(attributes[attribute])
		return new_attr

	def get_as_parameters(self):
		params = {}
		params["type"] = self.type
		params["namespace"] = self.namespace
		params["hierarchy"] = self.hierarchy
		params["ItemName"] = self.ItemName
		params["MethodsContainer"] = "\n".join(self.methods.values())
		params["AttributesContainer"] = "\n".join(self.attributes.values())
		return params

	def build_from_template(self):
		template = TemplateFile(os.path.join(TEMPLATES_FOLDER, self.structure_template_filename), defaults)
		params = self.get_as_parameters()
		for parameter in parameters:
			template.add_parameter(parameter, convert_to_string(parameters[parameter]))
		template.save_to(output)

def resolve_architecture(arch_file_path):
	with open(arch_file_path) as arch_file_description:
		arch_conf = json.load(arch_file_description)
	return [ create_class_representantion(arch_conf[arch_desc]) for arch_desc in arch_conf ]

def create_class_representantion(description):
	return ReprClass(description["filename"], description["method_template_filename"], description["attribute_template_filename"])

def build_architecture(elements):
	for element in elements:
		element.build_from_template()

def main():
	build_architecture(resolve_architecture("architecture.json"))

if __name__ == "__main__":
	main()


text:
import { EntityBase } from '../EntityBase';
import { Person } from './Person';

/// <code-import> Place custom imports between <code-import> tags

/// </code-import>

export class ProfileFaculty extends EntityBase {
   // Generated code. Do not place code below this line.
   personId: number;
   bio: string;
   homeStation: string;
   isCourseAdmin: boolean;
   isReportViewer: boolean;
   academyId: string;
   person: Person;

   /// <code> Place custom code between <code> tags

   /// </code>

}


text:
'''
Created by auto_sdk on 2015.04.21
'''
from aliyun.api.base import RestApi
class Ecs20140526DescribeEipAddressesRequest(RestApi):
	def __init__(self,domain='ecs.aliyuncs.com',port=80):
		RestApi.__init__(self,domain, port)
		self.AllocationId = None
		self.EipAddress = None
		self.PageNumber = None
		self.PageSize = None
		self.RegionId = None
		self.Status = None

	def getapiname(self):
		return 'ecs.aliyuncs.com.DescribeEipAddresses.2014-05-26'


text:
/**
 * Package containing geometry related classes.
 *
 * @author Régis Ramillien
 */
package com.web4enterprise.pdf.core.geometry;


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.cloud.spanner.pgadapter.statements.local;

import com.google.api.core.InternalApi;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.ResultSets;
import com.google.cloud.spanner.Type;
import com.google.cloud.spanner.Type.StructField;
import com.google.cloud.spanner.connection.StatementResult;
import com.google.cloud.spanner.pgadapter.statements.BackendConnection;
import com.google.cloud.spanner.pgadapter.statements.BackendConnection.QueryResult;
import com.google.common.collect.ImmutableList;

/*
 * Django sends this statement to get the list of all the relations present in the database.
 * After getting that list, Django searches for django_migrations table to check if it can perform migrations
 * Since we will be returning an empty resultset, Django will not perform migrations as it won't find the django_migrations table.
 * And this behavior shown by the Django is the intended behaviour because anyway we don't support migrations.
 * */

@InternalApi
public class DjangoGetTableNamesStatement implements LocalStatement {
  public static final DjangoGetTableNamesStatement INSTANCE = new DjangoGetTableNamesStatement();

  private DjangoGetTableNamesStatement() {}

  @Override
  public String[] getSql() {
    return new String[] {
      "\n"
          + "            SELECT\n"
          + "                c.relname,\n"
          + "                CASE\n"
          + "                    WHEN c.relispartition THEN 'p'\n"
          + "                    WHEN c.relkind IN ('m', 'v') THEN 'v'\n"
          + "                    ELSE 't'\n"
          + "                END\n"
          + "            FROM pg_catalog.pg_class c\n"
          + "            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"
          + "            WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v')\n"
          + "                AND n.nspname NOT IN ('pg_catalog', 'pg_toast')\n"
          + "                AND pg_catalog.pg_table_is_visible(c.oid)\n"
          + "        "
    };
  }

  @Override
  public StatementResult execute(BackendConnection backendConnection) {
    ResultSet resultSet =
        ResultSets.forRows(
            Type.struct(
                StructField.of("relname", Type.string()), StructField.of("case", Type.string())),
            ImmutableList.of());

    return new QueryResult(resultSet);
  }
}


text:
package com.google.identitytoolkit;

import com.google.gson.JsonObject;

import net.oauth.jsontoken.Checker;
import net.oauth.jsontoken.JsonToken;
import net.oauth.jsontoken.JsonTokenParser;
import net.oauth.jsontoken.crypto.SignatureAlgorithm;
import net.oauth.jsontoken.discovery.VerifierProviders;

import java.security.SignatureException;

/**
 * Helper to verify the access token from Token Service.
 */
public class TokenServiceHelper {
  public static final String ID_TOKEN_EMAIL = "email";
  public static final String ID_TOKEN_USER_ID = "user_id";
  public static final String SUB_FIELD = "sub";
  private final JsonTokenParser parser;

  public TokenServiceHelper(String audience, RpcHelper rpcHelper) {
    super();
    VerifierProviders verifierProviders = new VerifierProviders();
    verifierProviders.setVerifierProvider(SignatureAlgorithm.RS256,
        new TokenServiceVerifierManager(rpcHelper));
    parser = new JsonTokenParser(verifierProviders, new AudienceChecker(audience));
  }

  public JsonToken verifyAndDeserialize(String token)
      throws SignatureException {
    return parser.verifyAndDeserialize(token);
  }

  /**
   * Checks the token is indeed for this RP.
   */
  public static class AudienceChecker implements Checker {

    private final String expectedAudience;

    public AudienceChecker(String audience) {
      this.expectedAudience = audience;
    }

    @Override
    public void check(JsonObject payload) throws SignatureException {
      if (!payload.has(SUB_FIELD)) {
        throw new SignatureException("No sub field in payload.");
      }
      String subject = payload.get(SUB_FIELD).getAsString();
      if (!expectedAudience.split("[-\\.]")[0].equals(subject.split("[-@]")[0])) {
        throw new SignatureException(String.format(
            "Subject prefix mismatch: %s. Should start with: %s", subject, expectedAudience));
      }
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using CherrySeed.Configuration.Exceptions;
using CherrySeed.EntityDataProvider;
using CherrySeed.EntitySettings;
using CherrySeed.PrimaryKeyIdGeneration;
using CherrySeed.PrimaryKeyIdGeneration.ApplicationGeneration;
using CherrySeed.Repositories;
using CherrySeed.TypeTransformations;
using CherrySeed.Utils;

namespace CherrySeed.Configuration
{
    public class SeederConfigurationBuilder : ISeederConfigurationBuilder
    {
        private readonly Dictionary<Type, EntitySettingBuilder> _entitySettingBuilders;
        private int _order = 1;

        // Settings
        private string _emptyStringMarker;
        private readonly List<string> _defaultPrimaryKeyNames;
        private IRepository _defaultRepository;
        private readonly IdGenerationSetting _defaultIdGeneration;
        private bool _isClearBeforeSeedingEnabled;
        private Action<Dictionary<string, string>, object> _beforeSaveAction;
        private Action<Dictionary<string, string>, object> _afterSaveAction;
        private IDataProvider _dataProvider;
        private readonly Dictionary<Type, ITypeTransformation> _typeTransformations;

        public SeederConfigurationBuilder()
        {
            _entitySettingBuilders = new Dictionary<Type, EntitySettingBuilder>();

            _typeTransformations = new Dictionary<Type, ITypeTransformation>
            {
                { typeof(string), new StringTransformation("$EMPTY$") },
                { typeof(int), new IntegerTransformation() },
                { typeof(DateTime), new DateTimeTransformation() },
                { typeof(bool), new BooleanTransformation() },
                { typeof(Guid), new GuidTransformation() },
                { typeof(Enum), new EnumTransformation() },
                { typeof(double), new DoubleTransformation() },
                { typeof(decimal), new DecimalTransformation() }
            };

            // set defaults
            _defaultPrimaryKeyNames = new List<string> { "Id", "ID", "{ClassName}Id" };
            _defaultIdGeneration = new IdGenerationSetting
            {
                Generator = new DatabasePrimaryKeyIdGeneration()
            };
            _isClearBeforeSeedingEnabled = true;
        }

        public SeederConfiguration Build()
        {
            var entitySettings = _entitySettingBuilders.Values
                .Select(b => b.Build(
                    _defaultRepository,
                    _defaultIdGeneration,
                    _defaultPrimaryKeyNames))
                .ToList();

            if (!string.IsNullOrEmpty(_emptyStringMarker))
            {
                if (!(_typeTransformations[typeof(string)] is StringTransformation))
                {
                    throw new ConfigurationException("EmptyString marker can not be set, because the string transformation logic is overriden from you.", null);
                }

                _typeTransformations[typeof(string)] = new StringTransformation(_emptyStringMarker);
            }

            var configuration = new SeederConfiguration
            {
                AfterSaveAction = _afterSaveAction,
                BeforeSaveAction = _beforeSaveAction,
                DataProvider = _dataProvider,
                DefaultIdGeneration = _defaultIdGeneration,
                DefaultPrimaryKeyNames = _defaultPrimaryKeyNames,
                DefaultRepository = _defaultRepository,
                EntitySettings = entitySettings,
                IsClearBeforeSeedingEnabled = _isClearBeforeSeedingEnabled,
                TypeTransformations = _typeTransformations
            };

            var configurationValidator = new SeederConfigurationValidator();
            configurationValidator.IsValid(configuration);

            return configuration;
        }

        public IEntitySettingBuilder<T> ForEntity<T>()
        {
            var entityType = typeof(T);

            if (_entitySettingBuilders.ContainsKey(entityType))
            {
                return _entitySettingBuilders[entityType] as IEntitySettingBuilder<T>;
            }

            var entitySettingBuilder = new EntitySettingBuilder<T>(entityType, _order++);
            _entitySettingBuilders.Add(entityType, entitySettingBuilder);

            return entitySettingBuilder;
        }

        public void WithDataProvider(IDataProvider dataProvider)
        {
            _dataProvider = dataProvider;
        }

        public void AddTypeTransformation(Type type, ITypeTransformation transformation)
        {
            _typeTransformations.AddOrReplace(type, transformation);
        }

        public void WithDefaultPrimaryKeyNames(params string[] primaryKeyNames)
        {
            _defaultPrimaryKeyNames.AddRange(primaryKeyNames);
        }

        public void WithRepository(IRepository repository)
        {
            _defaultRepository = repository;
        }

        public void DisableClearBeforeSeeding()
        {
            _isClearBeforeSeedingEnabled = false;
        }

        public void BeforeSave(Action<Dictionary<string, string>, object> beforeSaveAction)
        {
            _beforeSaveAction = beforeSaveAction;
        }

        public void AfterSave(Action<Dictionary<string, string>, object> afterSaveAction)
        {
            _afterSaveAction = afterSaveAction;
        }

        public void DisablePrimaryKeyIdGeneration()
        {
            _defaultIdGeneration.Generator = null;
        }

        public void WithPrimaryKeyIdGenerationInApplicationAsInteger(int startId = 1, int steps = 1)
        {
            _defaultIdGeneration.Generator = new ApplicationPrimaryKeyIdGeneration
            {
                Generator = new IntegerPrimaryKeyIdGenerator(startId, steps)
            };
        }

        public void WithPrimaryKeyIdGenerationInApplicationAsGuid()
        {
            _defaultIdGeneration.Generator = new ApplicationPrimaryKeyIdGeneration
            {
                Generator = new GuidPrimaryKeyIdGenerator()
            };
        }

        public void WithPrimaryKeyIdGenerationInApplicationAsString(string prefix = "", int startId = 1, int steps = 1)
        {
            _defaultIdGeneration.Generator = new ApplicationPrimaryKeyIdGeneration
            {
                Generator = new StringPrimaryKeyIdGenerator(prefix, startId, steps)
            };
        }

        public void WithCustomPrimaryKeyIdGenerationInApplication(IPrimaryKeyIdGenerator generator)
        {
            _defaultIdGeneration.Generator = new ApplicationPrimaryKeyIdGeneration
            {
                Generator = generator
            };
        }

        public void WithEmptyStringMarker(string marker)
        {
            _emptyStringMarker = marker;
        }
    }
}


text:
namespace BattleRoom {

// apply settings

    void CircleBoundary::applySettings(ResourceDescriptor settings) {

        m_center.applySettings(settings.getSubResource("Center"));

        ResourceDescriptor sub = settings.getSubResource("Radius");
        if (isNotEmpty(sub.getValue())) {
            m_radius = toMeters(sub.getValue());
        }
    }

    ResourceDescriptor CircleBoundary::getSettings() const {
        ResourceDescriptor rd("Boundary", "Circle");
        std::vector<ResourceDescriptor> subs = {};

        ResourceDescriptor sub = m_center.getSettings();
        sub.setKey("Center");
        subs.push_back(sub);

        subs.emplace_back("Radius", std::to_string(m_radius));

        rd.setSubResources(subs);
        return rd;
    }

// constructor

    CircleBoundary::CircleBoundary(ResourceDescriptor settings)
            : m_center(Vector2D(0, 0)),
              m_radius(0) {
        applySettings(std::move(settings));
    }

    Boundary *CircleBoundary::clone() const {
        return new CircleBoundary(*this);
    }

// other functions

    bool CircleBoundary::contains(Vector2D delta) const {
        return m_radius >= delta.minus(m_center).magnitude();
    }

    Projection1D CircleBoundary::projectOnto(Vector2D axis) const {
        (void) axis; // unused
        return {-m_radius, m_radius};
    }

    std::vector<Vector2D> CircleBoundary::getSideNormals() const {
        std::vector<Vector2D> returnvec;
        returnvec.clear();
        return returnvec;
    }

} // BattleRoom namespace


text:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:sca="http://www.springframework.org/schema/sca" xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/sca http://www.osoa.org/xmlns/sca/1.0/spring-sca.xsd">

	<bean id="entityServiceBean" parent="DefaultBaseTransactionProxy">
		<property name="proxyInterfaces">
			<list>
				<value>org.gocom.components.coframe.entityauth.IEntityService</value>
			</list>
		</property>
		<property name="target">
			<bean id="entityService" class="org.gocom.components.coframe.entityauth.EntityService">
			</bean>
		</property>
	</bean>

	<bean id="entityCapRuleServiceBean" parent="DefaultBaseTransactionProxy">
		<property name="proxyInterfaces">
			<list>
				<value>org.gocom.components.coframe.entityauth.IEntityCapRuleService</value>
			</list>
		</property>
		<property name="target">
			<bean id="entityCapRuleService" class="org.gocom.components.coframe.entityauth.EntityCapRuleService">
			</bean>
		</property>
	</bean>

	<bean id="entityAuthServiceBean" parent="DefaultBaseTransactionProxy">
		<property name="proxyInterfaces">
			<list>
				<value>org.gocom.components.coframe.entityauth.IEntityAuthService</value>
			</list>
		</property>
		<property name="target">
			<bean id="entityAuthService" class="org.gocom.components.coframe.entityauth.EntityAuthService">
			</bean>
		</property>
	</bean>

	<bean id="valuePoolService"
		class="org.gocom.components.coframe.entityauth.ValuePoolService">
	</bean>
</beans>


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CQRS.Light.Core;
using FluentAssertions;
using CQRS.Light.Contracts;
using Moq;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;

namespace CQRS.Light.Core.Tests
{
    [TestClass]
    public class EventStoreTests
    {
        [TestInitialize]
        public void TestInitialize()
        {
            EventStore.Instance.Reset();
        }

        [TestMethod]
        public void EventStore_ShouldOnlyBeOneInstance()
        {
            var a = EventStore.Instance;
            var b = EventStore.Instance;

            a.Should().Be(b);
        }

        [TestMethod]
        public void EventStore_ConfigureShouldNotAllowNulls()
        {
            EventStore.Instance.Invoking(x => x.Configure(null, null, null)).ShouldThrow<ArgumentNullException>();
        }

        [TestMethod]
        public void EventStore_ConfigureShouldNotAllowAnyNulls()
        {
            var repo = new Mock<IRepository<AggregateEvent>>();

            EventStore.Instance.Invoking(x => x.Configure(repo.Object, null, null))
                .ShouldThrow<ArgumentNullException>();
        }

        [TestMethod]
        public void EventStore_ConfigureShouldReallyNotAllowAnyNulls()
        {
            var repo = new Mock<IRepository<AggregateEvent>>();
            var serializationStrategy = new Mock<ISerializationStrategy>();

            EventStore.Instance.Invoking(x => x.Configure(repo.Object, serializationStrategy.Object, null))
                .ShouldThrow<ArgumentNullException>();
        }

        [TestMethod]
        public void EventStore_GetAllAsyncShouldThrowExceptionIfConfigureHasNotBeenCalled()
        {
            EventStore.Instance.Awaiting(x => x.GetAllAsync()).ShouldThrow<InvalidOperationException>();
        }

        [TestMethod]
        public void EventStore_GetAllAsyncShouldUseTheRepo()
        {
            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAllAsync()).Returns(Task.FromResult<IEnumerable<AggregateEvent>>(null)).Verifiable();
            var serializationStrategy = new Mock<ISerializationStrategy>();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            EventStore.Instance.Awaiting(x => x.GetAllAsync()).ShouldNotThrow();
        }

        [TestMethod]
        public void EventStore_GetAllAsyncUntilShouldThrowExceptionIfConfigureHasNotBeenCalled()
        {
            var until = DateTime.UtcNow;
            EventStore.Instance.Awaiting(x => x.GetAllAsync(until)).ShouldThrow<InvalidOperationException>();
        }

        [TestMethod]
        public async Task EventStore_GetAllAsyncUntilShouldUseTheRepo()
        {
            var until = DateTime.UtcNow;
            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                    new List<AggregateEvent>() {
                        new AggregateEvent() { CreatedOn = until.AddMinutes(-1) },
                        new AggregateEvent() { CreatedOn = until.AddMinutes(-10) },
                        new AggregateEvent() { CreatedOn = until.AddMinutes(1) },
                    }.AsQueryable()))
                .Verifiable();
            var serializationStrategy = new Mock<ISerializationStrategy>();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.GetAllAsync(until);

            result.Should().NotBeNull();
            var count = result.Count();
            count.Should().Be(2);
        }

        [TestMethod]
        public void EventStore_CountAsyncShouldThrowExceptionIfConfigureHasNotBeenCalled()
        {
            EventStore.Instance.Awaiting(x => x.CountAsync()).ShouldThrow<InvalidOperationException>();
        }

        [TestMethod]
        public async Task EventStore_CountAsyncShouldUseTheRepo()
        {
            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.CountAsync()).Returns(Task.FromResult<long>(1234)).Verifiable();
            var serializationStrategy = new Mock<ISerializationStrategy>();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.CountAsync();

            result.Should().Be(1234);
        }

        [TestMethod]
        public void EventStore_SaveAsyncShouldThrowExceptionIfConfigureHasNotBeenCalled()
        {
            EventStore.Instance.Awaiting(x => x.SaveAsync(new AggregateEvent())).ShouldThrow<InvalidOperationException>();
        }

        [TestMethod]
        public async Task EventStore_SaveAsyncShouldUseTheRepo()
        {
            var @event = new AggregateEvent();
            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.SaveAsync(@event)).Returns(Task.FromResult<object>(null)).Verifiable();
            var serializationStrategy = new Mock<ISerializationStrategy>();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            await EventStore.Instance.SaveAsync(@event);

            repo.Verify(x => x.SaveAsync(@event), Times.Once);
        }

        [TestMethod]
        public void EventStore_GetEventsAsyncShouldThrowExceptionIfConfigureHasNotBeenCalled()
        {
            EventStore.Instance.Awaiting(x => x.GetEventsAsync<TestEvent>()).ShouldThrow<InvalidOperationException>();
        }

        [TestMethod]
        public async Task EventStore_GetEventsAsyncShouldReturnOnlyTEvents()
        {
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.NewGuid(), AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent2).AssemblyQualifiedName, AggregateId = Guid.NewGuid(), AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };
            var event3 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.NewGuid(), AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-3), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2, event3
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent)))
                .Returns(new TestEvent()).Verifiable();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.GetEventsAsync<TestEvent>();

            result.Should().NotBeNull();
            result.Count().Should().Be(2);

            repo.Verify(x => x.GetAsync(), Times.Once);
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent)), Times.Exactly(2));
        }

        [TestMethod]
        public void EventStore_LatestEventTimestampAsyncShouldThrowExceptionIfConfigureHasNotBeenCalled()
        {
            EventStore.Instance.Awaiting(x => x.LatestEventTimestampAsync(Guid.Empty))
                .ShouldThrow<InvalidOperationException>();
        }

        [TestMethod]
        public async Task EventStore_LatestEventTimestampAsyncShouldUseTheRepoAndMatchTheLatestEventDate()
        {
            var latest = DateTime.UtcNow.AddMinutes(-3);
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent2).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };
            var event3 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = latest, Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2, event3
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.LatestEventTimestampAsync(Guid.Empty);

            result.Should().Be(latest);

            repo.Verify(x => x.GetAsync(), Times.Once);
        }

        [TestMethod]
        public async Task EventStore_LatestEventTimestampAsyncShouldUseTheRepoAndReturnDateTimeMinIfNoEventsAreFound()
        {
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent2).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };
            var event3 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-3), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2, event3
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.LatestEventTimestampAsync(Guid.NewGuid());

            result.Should().Be(DateTime.MinValue);

            repo.Verify(x => x.GetAsync(), Times.Once);
        }

        [TestMethod]
        public void EventStore_GetByIdAsyncShouldThrowExceptionIfConfigureHasNotBeenCalled()
        {
            EventStore.Instance.Awaiting(x => x.GetByIdAsync<TestAggregate>(Guid.Empty))
                .ShouldThrow<InvalidOperationException>();
        }

        [TestMethod]
        public async Task EventStore_GetByIdAsyncShouldReturnDefaultTForNoEvents()
        {
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };
            var event3 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-3), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2, event3
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent)))
                .Returns(new TestEvent()).Verifiable();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.GetByIdAsync<TestAggregateRoot>(Guid.Empty);

            result.Should().NotBeNull();
            result.WasApplyEventCalled.Should().BeTrue();

            repo.Verify(x => x.GetAsync(), Times.Once);
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent)), Times.Exactly(3));

        }

        [TestMethod]
        public void EventStore_GetByIdAsyncShouldThrowExceptionIfNoAcceptableConstructorIsFound()
        {
           var repo = new Mock<IRepository<AggregateEvent>>();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            EventStore.Instance.Awaiting(x => x.GetByIdAsync<MissingConstructorAggregateRoot>(Guid.Empty))
                .ShouldThrow<NotImplementedException>();
        }

        [TestMethod]
        public void EventStore_GetByIdAsyncShouldThrowExceptionIfNoAcceptableApplyEventMethodIsFound()
        {
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent2).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent)))
                .Returns(new TestEvent()).Verifiable();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            EventStore.Instance.Awaiting(x => x.GetByIdAsync<TestAggregateRoot>(Guid.Empty))
                .ShouldThrow<NotImplementedException>();

            repo.Verify(x => x.GetAsync(), Times.Once);
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent)), Times.Once);
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent2)), Times.Once);

        }

        [TestMethod]
        public void EventStore_GetByIdUntilAsyncShouldThrowExceptionIfConfigureHasNotBeenCalled()
        {
            var until = DateTime.UtcNow.AddMinutes(-5);

            EventStore.Instance.Awaiting(x => x.GetByIdAsync<TestAggregate>(Guid.Empty, until))
                .ShouldThrow<InvalidOperationException>();
        }

        [TestMethod]
        public async Task EventStore_GetByIdUntilAsyncShouldReturnDefaultTForNoEvents()
        {
            var until = DateTime.UtcNow.AddMinutes(-5);
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };
            var event3 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-3), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2, event3
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent)))
                .Returns(new TestEvent()).Verifiable();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.GetByIdAsync<TestAggregateRoot>(Guid.Empty, until);

            result.Should().NotBeNull();
            result.WasApplyEventCalled.Should().BeTrue();

            repo.Verify(x => x.GetAsync(), Times.Once);
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent)), Times.Exactly(3));

        }

        [TestMethod]
        public void EventStore_GetByIdUntilAsyncShouldThrowExceptionIfNoAcceptableConstructorIsFound()
        {
            var until = DateTime.UtcNow.AddMinutes(-5);
            var repo = new Mock<IRepository<AggregateEvent>>();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            EventStore.Instance.Awaiting(x => x.GetByIdAsync<MissingConstructorAggregateRoot>(Guid.Empty, until))
                .ShouldThrow<NotImplementedException>();
        }

        [TestMethod]
        public void EventStore_GetByIdUntilAsyncShouldThrowExceptionIfNoAcceptableApplyEventMethodIsFound()
        {
            var until = DateTime.UtcNow.AddMinutes(-5);
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent2).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent)))
                .Returns(new TestEvent()).Verifiable();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            EventStore.Instance.Awaiting(x => x.GetByIdAsync<TestAggregateRoot>(Guid.Empty, until))
                .ShouldThrow<NotImplementedException>();

            repo.Verify(x => x.GetAsync(), Times.Once);
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent)), Times.Once);
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent2)), Times.Once);

        }

        [TestMethod]
        public void EventStore_GetByIdObjectAsyncShouldThrowExceptionIfConfigureHasNotBeenCalled()
        {
            EventStore.Instance.Awaiting(x => x.GetByIdAsync(Guid.Empty))
                .ShouldThrow<InvalidOperationException>();
        }

        [TestMethod]
        public async Task EventStore_GetByIdObjectAsyncShouldReturnDefaultTForNoEvents()
        {
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregateRoot).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregateRoot).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };
            var event3 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregateRoot).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-3), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2, event3
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent)))
                .Returns(new TestEvent()).Verifiable();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.GetByIdAsync(Guid.Empty);

            result.Should().NotBeNull();
            result.Should().BeOfType(typeof(TestAggregateRoot));
            var aggregateRoot = result as TestAggregateRoot;
            aggregateRoot.Should().NotBeNull();
            aggregateRoot.WasApplyEventCalled.Should().BeTrue();

            repo.Verify(x => x.GetAsync(), Times.Exactly(2));
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent)), Times.Exactly(3));

        }

        [TestMethod]
        public void EventStore_GetByIdObjectAsyncShouldThrowExceptionIfNoAcceptableConstructorIsFound()
        {
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent2).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregate).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            EventStore.Instance.Awaiting(x => x.GetByIdAsync(Guid.Empty))
                .ShouldThrow<NotImplementedException>();
        }

        [TestMethod]
        public void EventStore_GetByIdObjectAsyncShouldThrowExceptionIfNoAcceptableApplyEventMethodIsFound()
        {
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregateRoot).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent2).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregateRoot).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent)))
                .Returns(new TestEvent()).Verifiable();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent2)))
                .Returns(new TestEvent2()).Verifiable();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            EventStore.Instance.Awaiting(x => x.GetByIdAsync(Guid.Empty))
                .ShouldThrow<NotImplementedException>();

            repo.Verify(x => x.GetAsync(), Times.Exactly(2));
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent)), Times.Once);
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent2)), Times.Once);

        }

        [TestMethod]
        public async Task EventStore_GetByIdObjectAsyncShouldReturnNullIfNoEvents()
        {
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregateRoot).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregateRoot).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };
            var event3 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = typeof(TestAggregateRoot).AssemblyQualifiedName, CreatedOn = DateTime.UtcNow.AddMinutes(-3), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2, event3
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent)))
                .Returns(new TestEvent()).Verifiable();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.GetByIdAsync(Guid.NewGuid());

            result.Should().BeNull();

            repo.Verify(x => x.GetAsync(), Times.Exactly(1));
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent)), Times.Never);

        }

        [TestMethod]
        public async Task EventStore_GetByIdObjectAsyncShouldReturnNullIfEvenContainsAndInvalidAggregateType()
        {
            var event1 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = "SomeRandomAggregateRoot", CreatedOn = DateTime.UtcNow.AddMinutes(-5), Id = Guid.Empty, SerializedEvent = "{}" };
            var event2 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = "SomeRandomAggregateRoot", CreatedOn = DateTime.UtcNow.AddMinutes(-4), Id = Guid.Empty, SerializedEvent = "{}" };
            var event3 = new AggregateEvent() { EventType = typeof(TestEvent).AssemblyQualifiedName, AggregateId = Guid.Empty, AggregateIdType = typeof(Guid).ToString(), AggregateType = "SomeRandomAggregateRoot", CreatedOn = DateTime.UtcNow.AddMinutes(-3), Id = Guid.Empty, SerializedEvent = "{}" };

            var repo = new Mock<IRepository<AggregateEvent>>();
            repo.Setup(x => x.GetAsync())
                .Returns(Task.FromResult<IQueryable<AggregateEvent>>(
                new List<AggregateEvent>()
                {
                    event1, event2, event3
                }.AsQueryable()))
                .Verifiable();

            var serializationStrategy = new Mock<ISerializationStrategy>();
            serializationStrategy.Setup(x => x.Deserialize("{}", typeof(TestEvent)))
                .Returns(new TestEvent()).Verifiable();
            var aggregateBus = new Mock<IAggregateBus>();

            EventStore.Instance.Configure(repo.Object, serializationStrategy.Object, aggregateBus.Object);

            var result = await EventStore.Instance.GetByIdAsync(Guid.Empty);

            result.Should().BeNull();

            repo.Verify(x => x.GetAsync(), Times.Exactly(1));
            serializationStrategy.Verify(x => x.Deserialize("{}", typeof(TestEvent)), Times.Never);

        }
    }
}


text:
Right now please do not trust what is on this repository. Thank you.

# breakout-boards
A collection of breakout boards


text:
package com.nextBook.database.entity;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.io.Serializable;

@Entity
@Table(name = "users")
public class Users extends BaseEntity implements Serializable {

  @Id
  @NotNull
  @GeneratedValue(generator = "increment")
  @GenericGenerator(name="increment", strategy = "increment")
  @Column(name = "user_id", unique = true, nullable = false)
  private int user_id;

  @NotNull
  @Column(name = "user_name")
  private String user_name;

  @NotNull
  @Column(name = "user_password")
  private String user_password;

  @Column(name = "email")
  private String email;

  @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
  @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
  private List<User_roles> roles;

  /*
  @OneToMany(mappedBy = "bookPerUser", fetch = FetchType.EAGER)
  @Cascade({CascadeType.SAVE_UPDATE ,CascadeType.DELETE})
  private Set<UserBooksEntity> booksForUser;
  */

  @ManyToMany(fetch = FetchType.EAGER, cascade = javax.persistence.CascadeType.ALL)
  @JoinTable(name = "user_books",
          joinColumns = { @JoinColumn(name = "user_id", nullable = false, updatable = false)},
          inverseJoinColumns = {@JoinColumn(name = "id_books", nullable = false, updatable = false)})
  private Set<Book> booksForUser;

  public Users() {
    roles = new ArrayList<>();
    booksForUser = new HashSet<Book>(0);
  }

  public Users(int id, String username, String password, String email) {
    this();
    this.user_id = id;
    this.user_name = username;
    this.user_password = password;
    this.email = email;
  }

  public int getId() {
    return user_id;
  }

  public int getUser_id() {
    return user_id;
  }

  public void setUser_id(int user_id) {
    this.user_id = user_id;
  }

  public String getUser_name() {
    return user_name;
  }

  public void setUser_name(String user_name) {
    this.user_name = user_name;
  }

  public String getUser_password() {
    return user_password;
  }

  public void setUser_password(String user_password) {
    this.user_password = user_password;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public List<User_roles> getRoles() {
    return this.roles;
  }

  public void setRoles(List<User_roles> newRoles) {
    this.roles = newRoles;
  }

  public Set<Book> getBooksForUser() {
    return booksForUser;
  }

  public void setBooksForUser(Set<Book> books) {
    this.booksForUser = books;
  }

  public String toLog() {
    return "Id: " + user_id + ", Username: " + user_name + ", Password: " + user_password + ", Email: " + email;
  }

  @Override
  public String toString() {
    String newLine = System.getProperty("line.separator");
    String user = "User id: " + user_id + newLine;
    user += "Username: " + user_name + newLine;
    user += "Password: " + user_password + newLine;
    user += "Email: " + email + newLine;

    return user;
  }
}


text:
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_shared.h"
#include "xfs_format.h"
#include "xfs_log_format.h"
#include "xfs_trans_resv.h"
#include "xfs_ag.h"
#include "xfs_sb.h"
#include "xfs_mount.h"
#include "xfs_da_format.h"
#include "xfs_trans_space.h"
#include "xfs_inode.h"
#include "xfs_da_btree.h"
#include "xfs_attr_leaf.h"
#include "xfs_bmap_btree.h"

/*
 * Calculate the maximum length in bytes that would be required for a local
 * attribute value as large attributes out of line are not logged.
 */
STATIC int
xfs_log_calc_max_attrsetm_res(
	struct xfs_mount	*mp)
{
	int			size;
	int			nblks;

	size = xfs_attr_leaf_entsize_local_max(mp->m_sb.sb_blocksize) -
	       MAXNAMELEN - 1;
	nblks = XFS_DAENTER_SPACE_RES(mp, XFS_ATTR_FORK);
	nblks += XFS_B_TO_FSB(mp, size);
	nblks += XFS_NEXTENTADD_SPACE_RES(mp, size, XFS_ATTR_FORK);

	return  M_RES(mp)->tr_attrsetm.tr_logres +
		M_RES(mp)->tr_attrsetrt.tr_logres * nblks;
}

/*
 * Iterate over the log space reservation table to figure out and return
 * the maximum one in terms of the pre-calculated values which were done
 * at mount time.
 */
STATIC void
xfs_log_get_max_trans_res(
	struct xfs_mount	*mp,
	struct xfs_trans_res	*max_resp)
{
	struct xfs_trans_res	*resp;
	struct xfs_trans_res	*end_resp;
	int			log_space = 0;
	int			attr_space;

	attr_space = xfs_log_calc_max_attrsetm_res(mp);

	resp = (struct xfs_trans_res *)M_RES(mp);
	end_resp = (struct xfs_trans_res *)(M_RES(mp) + 1);
	for (; resp < end_resp; resp++) {
		int		tmp = resp->tr_logcount > 1 ?
				      resp->tr_logres * resp->tr_logcount :
				      resp->tr_logres;
		if (log_space < tmp) {
			log_space = tmp;
			*max_resp = *resp;		/* struct copy */
		}
	}

	if (attr_space > log_space) {
		*max_resp = M_RES(mp)->tr_attrsetm;	/* struct copy */
		max_resp->tr_logres = attr_space;
	}
}

/*
 * Calculate the minimum valid log size for the given superblock configuration.
 * Used to calculate the minimum log size at mkfs time, and to determine if
 * the log is large enough or not at mount time. Returns the minimum size in
 * filesystem block size units.
 */
int
xfs_log_calc_minimum_size(
	struct xfs_mount	*mp)
{
	struct xfs_trans_res	tres = {0};
	int			max_logres;
	int			min_logblks = 0;
	int			lsunit = 0;

	xfs_log_get_max_trans_res(mp, &tres);

	max_logres = xfs_log_calc_unit_res(mp, tres.tr_logres);
	if (tres.tr_logcount > 1)
		max_logres *= tres.tr_logcount;

	if (xfs_sb_version_haslogv2(&mp->m_sb) && mp->m_sb.sb_logsunit > 1)
		lsunit = BTOBB(mp->m_sb.sb_logsunit);

	/*
	 * Two factors should be taken into account for calculating the minimum
	 * log space.
	 * 1) The fundamental limitation is that no single transaction can be
	 *    larger than half size of the log.
	 *
	 *    From mkfs.xfs, this is considered by the XFS_MIN_LOG_FACTOR
	 *    define, which is set to 3. That means we can definitely fit
	 *    maximally sized 2 transactions in the log. We'll use this same
	 *    value here.
	 *
	 * 2) If the lsunit option is specified, a transaction requires 2 LSU
	 *    for the reservation because there are two log writes that can
	 *    require padding - the transaction data and the commit record which
	 *    are written separately and both can require padding to the LSU.
	 *    Consider that we can have an active CIL reservation holding 2*LSU,
	 *    but the CIL is not over a push threshold, in this case, if we
	 *    don't have enough log space for at one new transaction, which
	 *    includes another 2*LSU in the reservation, we will run into dead
	 *    loop situation in log space grant procedure. i.e.
	 *    xlog_grant_head_wait().
	 *
	 *    Hence the log size needs to be able to contain two maximally sized
	 *    and padded transactions, which is (2 * (2 * LSU + maxlres)).
	 *
	 * Also, the log size should be a multiple of the log stripe unit, round
	 * it up to lsunit boundary if lsunit is specified.
	 */
	if (lsunit) {
		min_logblks = roundup_64(BTOBB(max_logres), lsunit) +
			      2 * lsunit;
	} else
		min_logblks = BTOBB(max_logres) + 2 * BBSIZE;
	min_logblks *= XFS_MIN_LOG_FACTOR;

	return XFS_BB_TO_FSB(mp, min_logblks);
}


text:
<?php

namespace Roots\Sage\Assets;

/**
 * Scripts and stylesheets
 *
 * Enqueue stylesheets in the following order:
 * 1. /theme/dist/styles/main.css
 *
 * Enqueue scripts in the following order:
 * 1. /theme/dist/scripts/modernizr.js
 * 2. /theme/dist/scripts/main.js
 */

class JsonManifest {
  private $manifest;

  public function __construct($manifest_path) {
    if (file_exists($manifest_path)) {
      $this->manifest = json_decode(file_get_contents($manifest_path), true);
    } else {
      $this->manifest = [];
    }
  }

  public function get() {
    return $this->manifest;
  }

  public function getPath($key = '', $default = null) {
    $collection = $this->manifest;
    if (is_null($key)) {
      return $collection;
    }
    if (isset($collection[$key])) {
      return $collection[$key];
    }
    foreach (explode('.', $key) as $segment) {
      if (!isset($collection[$segment])) {
        return $default;
      } else {
        $collection = $collection[$segment];
      }
    }
    return $collection;
  }
}

function asset_path($filename) {
  $dist_path = get_template_directory_uri() . DIST_DIR;
  $directory = dirname($filename) . '/';
  $file = basename($filename);
  static $manifest;

  if (empty($manifest)) {
    $manifest_path = get_template_directory() . DIST_DIR . 'assets.json';
    $manifest = new JsonManifest($manifest_path);
  }

  if (array_key_exists($file, $manifest->get())) {
    return $dist_path . $directory . $manifest->get()[$file];
  } else {
    return $dist_path . $directory . $file;
  }
}

function qf_init() {
  if (!is_admin()) {
    wp_deregister_script('jquery');
    wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js', FALSE, '2.1.4', TRUE);      wp_enqueue_script('jquery');
  }
}
add_action('init', __NAMESPACE__ . '\\qf_init');

/**
* Dequeue the Emoji script.
*/
function disable_emoji_dequeue_script() {
  wp_dequeue_script( 'emoji' );
}
add_action( 'wp_print_scripts', __NAMESPACE__ . '\\disable_emoji_dequeue_script', 100 );

/**
* Remove the emoji styles.
*/
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'wp_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_styles', 'print_emoji_styles');
remove_action( 'admin_print_scripts','print_emoji_detection_script');

function assets() {
  wp_enqueue_style('sage_css', asset_path('styles/main.css'), false, null);

  if (is_single() && comments_open() && get_option('thread_comments')) {
    wp_enqueue_script('comment-reply');
  }

  wp_enqueue_script('modernizr', asset_path('scripts/modernizr.js'), [], null, true);
  wp_enqueue_script('sage_js', asset_path('scripts/main.js'), ['jquery'], null, true);
}
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\assets', 100);


text:
/*
 *test_pi_cs_rewrite .c
 *
 *      Author: Pankaj Purandare
 */

#include "common.h"

#include "mem_manager/mem_mgr.h"
#include "log/logger.h"
#include "configuration/option.h"
#include "configuration/option_parser.h"
#include "model/list/list.h"
#include "model/node/nodetype.h"
#include "parser/parser.h"
#include "model/query_operator/query_operator.h"
#include "analysis_and_translate/translator.h"
#include "provenance_rewriter/pi_cs_rewrites/pi_cs_main.h"
#include "rewriter.h"

/* if OCI is not available then add dummy versions */
#if HAVE_A_BACKEND

int
main (int argc, char* argv[])
{
    Node *result;
    Node *qoModel;
    Node *rewriteQoModel;

    READ_OPTIONS_AND_INIT("testpicsrewrite", "Run all stages on input and output rewritten SQL, but only use pi-cs rewritter.");

    // read from terminal
    if (getStringOption("input.sql") == NULL)
    {
        result = parseStream(stdin);

        DEBUG_LOG("Address of returned node is <%p>", result);
        ERROR_LOG("PARSE RESULT FROM STREAM IS <%s>", beatify(nodeToString(result)));
    }
    // parse input string
    else
    {
        result = parseFromString(getStringOption("input.sql"));

        DEBUG_LOG("Address of returned node is <%p>", result);
        ERROR_LOG("PARSE RESULT FROM STRING IS:\n%s", beatify(nodeToString(result)));
    }

    qoModel = translateParse(result);
    ERROR_LOG("TRANSLATION RESULT FROM STRING IS:\n%s", beatify(nodeToString(qoModel)));
    ERROR_LOG("SIMPLIFIED OPERATOR TREE:\n%s", operatorToOverviewString(qoModel));

    QueryOperator *op = (QueryOperator *) getHeadOfListP((List *) qoModel);
    rewriteQoModel = (Node *) rewritePI_CS((ProvenanceComputation *) op);
    ERROR_LOG("REWRITTEN PROVENANCE RESULT IS:\n%s", beatify(nodeToString(rewriteQoModel)));
    ERROR_LOG("REWRITTEN PROVENANCE RESULT IS:\n%s", operatorToOverviewString(rewriteQoModel));

    shutdownApplication();

    return EXIT_SUCCESS;
}

/* if no backend db plugin is available replace with dummy test */
#else

int main()
{
    return EXIT_SUCCESS;
}

#endif


text:
var expect = require('chai').expect;
var assert = require('chai').assert;
var mongoose = require ('mongoose');
mongoose.models = {};
mongoose.modelSchemas = {};

// db connection
mongoose.connect('mongodb://localhost/calls', function(err) {
    if(err) {
        console.log('DB connection error', err);
        process.exit(1);
    } else {
        console.log('DB connection successful');
    }
});

var costCalculator = require('./controller/costCalculator');

describe('Cost calculator', function (){

    it('Should return 7c on one minute web browser call', function (done){

        var call = {
            duration: 60,
            accountName: "test1",
            talkdeskAccountName: "+14735348611",
            customerPhoneNumber: "+351961918192",
            forwardPhoneNumber: null
        };
        // talkdesk-number-cost + external-number-cost + profit-margin
        var talkdeskNumberCost = 0.01; // Grenada, default price
        var externalNumberCost = 0.01; // web browser
        var profitMargin = 0.05; //default
        var totalCost = call.duration/60.0 * (talkdeskNumberCost + externalNumberCost + profitMargin);

        costCalculator.calculateCost(call, function (result){
            expect(result).to.equal(totalCost);
            done();
        });
    })
});

describe ('Country prices info file import', function (){

    it ('Should return properly JSON data', function (done){
        var filePath = './Twilio - Voice Prices.test.csv';
        var expected = [
            {
                name:  'Afghanistan',
                rate: 0.29,
                phoneStartsWith: ['93']
            },
            {
                name:  'Afghanistan',
                rate: 0.415,
                phoneStartsWith: ['9370', '9372', '9375', '9376', '9377', '9378', '9379']
            },
            {
                name:  'Albania',
                rate: 0.475,
                phoneStartsWith: ['35566', '35567', '35568', '35569']
            },
            {
                name:  'Albania',
                rate: 1.705,
                phoneStartsWith: ['3554249']
            },
            {
                name:  'Burkina Faso',
                rate: 0.29,
                phoneStartsWith: ['226']
            }
        ];

        assert.doesNotThrow(function (){
            costCalculator.getCountryInfoFromFile(filePath, function successCallback(data){
                expect(data).to.eql(expected);
                done();
            });

        });

    })

});


text:
<?php

namespace Respect\Validation\Exceptions;

class CntrlException extends AlphaException
{
    public static $defaultTemplates = [
        self::MODE_DEFAULT => [
            self::STANDARD => '{{name}} must contain only control characters',
            self::EXTRA => '{{name}} must contain only control characters and "{{additionalChars}}"',
        ],
        self::MODE_NEGATIVE => [
            self::STANDARD => '{{name}} must not contain control characters',
            self::EXTRA => '{{name}} must not contain control characters or "{{additionalChars}}"',
        ],
    ];
}


text:
<?php namespace Tarsana\Command\Commands;

use Tarsana\Command\Helpers\SyntaxHelper;
use Tarsana\Command\SubCommand;
use Tarsana\Syntax\ArraySyntax;
use Tarsana\Syntax\ObjectSyntax;
use Tarsana\Syntax\OptionalSyntax;
use Tarsana\Syntax\Syntax;

class HelpCommand extends SubCommand {

    protected $helper;

    protected function init()
    {
        $this->name('Help')
             ->description('Shows the help message.');
        $this->helper = SyntaxHelper::instance();
    }

    protected function setupSubCommands()
    {
        return $this;
    }

    protected function execute()
    {
        $parent = $this->parent;

        $text = "<info>{$parent->name}</info> version <info>{$parent->version}</info>"
              . "

{$parent->description}

"
              . $this->syntaxHelp()
              . $this->optionsHelp()
              . $this->subCommandsHelp();

        $this->console()->out($text);
    }

    protected function syntaxHelp() : string
    {
        $syntax = $this->parent->syntax();
        $helper = $this->helper;
        $text   = '';

        if ($syntax) {
            $string = $helper->asString($syntax);
            $text  .= "Syntax: <success>[options] {$string}</success>
"
                    . "Arguments:
";
            foreach ($syntax->fields() as $name => $s) {
                $text .= $this->fieldHelp($name, $s);
            }
        }

        return $text;
    }

    protected function optionsHelp() : string
    {
        $options = array_keys($this->parent->options());
        $text = '';
        if (!empty($options)) {
            $text .= 'Options:
';
            foreach ($options as $name) {
                $description = $this->parent()->describe($name);
                $text .= "<tab><warn>{$name}</warn> {$description}
";
            }
        }

        return $text;
    }

    protected function subCommandsHelp() : string
    {
        $subCommands = $this->parent->commands();
        $text = '';
        if (!empty($subCommands)) {
            $text .= 'SubCommands:
';
            foreach ($subCommands as $name => $cmd) {
                $text .= "<tab><warn>{$name}</warn> {$cmd->description()}
";
            }
        }

        return $text;
    }

    protected function fieldHelp(
        string $name, Syntax $s, string $prefix = '', int $level = 1
    ) : string
    {
        $tabs = str_repeat('<tab>', $level);
        $optional = ($s instanceof OptionalSyntax);
        if ($optional)
            $default = 'default: ' . json_encode($s->getDefault());
        else
            $default = 'required';
        $description = $this->parent()->describe($prefix.$name);
        $syntax = $this->helper->asString($s);
        $text   = "{$tabs}<warn>{$name}</warn> <success>{$syntax}</success>"
                . " {$description} <info>({$default})</info>
";
        $level ++;
        $prefix .= $name . '.';
        foreach ($this->helper->fields($s) as $field => $syntax) {
            $text .= $this->fieldHelp($field, $syntax, $prefix, $level);
        }

        return $text;
    }

}


text:
// TODO: File is named 01_SelectItem.js to ensure it is compiled before the
// others that depend on it, but after 00_ListItem.js.
// A better way to support this would be if Helma offered an inlcude() method...

SelectItem = ListItem.extend({
	_types: 'select',
	_scale: true,

	getOptions: function() {
		return { scaleToFit: !!this.size };
	},

	render: function(baseForm, name, value, param, out) {
		var options = this.toOptions(this.collection || this.options);
		if (this.allowNull)
			options.unshift({ name: '', value: 'null' });

		// Convert to id
		if (value != null && value instanceof HopObject)
			value = value.getFullId();
		// Mark the selected
		options.each(function(option) {
			if (option.value == value)
				option.selected = true;
		});
		var select = {
			name: name, className: this.className
		};
		if (this.size)
			select.size = this.size;

		var buttons = this.renderButtons(baseForm, name, true);
		// Double clicking onto the select input also edits the entry
		if (buttons)
			select.onDblClick = baseForm.renderHandle('select_edit', [name],
					this.getEditParam());
		select.options = options;
		select.multiple = true;
		Html.select(select, out);
		if (buttons)
			out.write(buttons);
	},

	convert: function(value) {
		// Only convert back to HopObject if the options are a HopObject
		// collection
		if ((this.collection || this.options) instanceof HopObject)
			value = HopObject.get(value);
		// Only convert if the current value is not the collection itself,
		// as we cannot override collections (this happens e.g. when
		// using a select item for simply creating a list of objects, not
		// actually selecting and that is associated with a object mapping).
		if (this.collection && !this.linkedCollection) {
			if (this.collection == this.getValue())
				return EditForm.DONT_APPLY;
			// Make sure the specified object is defined in the collection
			if (value && this.collection.indexOf(value) == -1)
				value = null;
		}
		return value;
	},

	getButtons: function(baseForm, name) {
		var editParam = this.getEditParam();
		var selParam = this.type == 'multiselect'
				? [ name + '_left', name + '_right' ]
				: [ name ];

		var buttons = [];
		if (this.prototypes || this.editable) {
			buttons.push({
				value: 'Edit',
				onClick: baseForm.renderHandle('select_edit', selParam,
						editParam)
			});
		}
		if (this.movable) {
			buttons.push({
				value: 'Move',
				name: name + '_move',
				onClick: baseForm.renderHandle('select_move', name, selParam,
						editParam)
			});
		}
		if (this.prototypes) {
			buttons.push(this.getPrototypeChooserButton(baseForm, {
				value: 'New'
			}), {
				value: 'Delete',
				onClick: baseForm.renderHandle('select_remove', selParam,
						editParam)
			});
		}
		return buttons;
	},

	// toOptions returns an array with option descriptions:
	// possible values for param:
	// - a HopObject, the children become options (name, _id)
	// - a JavaScript array with options (is return unmodified)
	toOptions: function(param) {
		var options = null;
		if (param != null) {
			if (param instanceof Array) {
				options = param;
			} else if (param instanceof HopObject) {
				options = [];
				var list = param.list();
				for (var i = 0, l = list.length; i < l; i++) {
					var obj = list[i];
					if (obj) {
						options.push({
							name: EditForm.getEditName(obj, true),
							value: obj.getFullId()
						});
					}
				}
				/*
				options = param.list().each(function(obj) {
					if (obj) {
						this.push({
							name: EditForm.getEditName(obj, true),
							value: obj.getFullId()
						});
					}
				}, []);
				*/
			}
		}
		if (options) {
			for (var i = 0, l = options.length; i < l; i++) {
				var option = options[i];
				if (typeof option != 'object') {
					options[i] = {
						name: option,
						value: option
					};
				}
			}
		} else {
			options  = [];
		}
		return options;
	}
});


text:
<?php
namespace SparkTests;

use PHPUnit_Framework_TestCase as TestCase;
use Spark\Adr\Input;
use Spark\Application;
use Spark\Router;
use SparkTests\Fake\FakeInput;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\Uri;

class RouterTest extends TestCase
{
    public function testRouterDispatchAndInjection()
    {
        $app = Application::boot();
        $router = $app->getRouter();
        $router->get('/', 'SparkTests\Fake\FakeDomain');

        /**
         * @var $route Router\Route
         */
        $route = current($router->getRoutes());
        $this->assertInstanceOf('\Spark\Router\Route', $route);
        $this->assertEquals('Spark\Responder\JsonResponder', $route->getResponder());
        $this->assertEquals('Spark\Adr\Input', $route->getInput());
        $this->assertEquals('SparkTests\Fake\FakeDomain', $route->getDomain());

    }

    public function testRouteInput()
    {
        $input = new Input();
        $request = (new ServerRequest)
            ->withAttribute("attribute", "true")
            ->withQueryParams(["query" => "true"]);

        $output = $input($request);

        $this->assertEquals("true", $output["query"]);
        $this->assertEquals("true", $output["attribute"]);
    }

    public function testRouteDefaults()
    {
        $app = Application::boot();

        $router = $app->getRouter();

        $input = 'SparkTest\Fake\FakeInput';
        $router->setDefaultInput($input);
        $responder = 'SparkTest\Fake\FakeResponder';
        $router->setDefaultResponder($responder);

        $route = $router->get('/', 'SparkTest\Fake\FakeDomain');

        $this->assertEquals($input, $route->getInput());
        $this->assertEquals($responder, $route->getResponder());

    }

    public function routeMethodProvider()
    {
        return [
            ['get', Router::GET],
            ['post', Router::POST],
            ['put', Router::PUT],
            ['patch', Router::PATCH],
            ['head', Router::HEAD],
            ['options', Router::OPTIONS],
        ];
    }

    /**
     * @dataProvider routeMethodProvider
     */
    public function testRoutes($method)
    {
        $router = Application::boot()->getRouter();
        $route = $router->$method('/test', '\SparkTests\Fake\FakeDomain');

        $this->assertInstanceOf('Spark\Router\Route', $route);
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Globalization;

namespace Cms.Buildeploy.Tasks
{
    class NugetArchive : IPackageArchive
    {
        private readonly string tempPath;
        private readonly string nugetPath;
        private readonly string nuspecFile;
        private readonly string version;
        private readonly string outputDir;
        private readonly Dictionary<string, string> properties = new Dictionary<string, string>();

        internal NugetArchive(string nugetPath, string nuspecFile, string outputDir, string version, TaskLoggingHelper log)
        {
            this.nugetPath = nugetPath;
            this.nuspecFile = nuspecFile;
            this.version = version;
            Log = log;
            tempPath = CreateTempDirectory();
            this.outputDir = Path.GetFullPath(outputDir);
        }

        private static string CreateTempDirectory()
        {
            string directory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(directory);
            return directory;
        }

        internal string PushLocation
        {
            get;
            set;
        }

        internal string ApiKey
        {
            get;
            set;
        }

        internal void AddProperty(string name, string value)
        {
            properties.Add(name, value);
        }

        private string BuildPropertiesString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (var entry in properties)
            {
                sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1};", entry.Key, entry.Value);
            }

            return sb.ToString();
        }

        private TaskLoggingHelper Log
        {
            get;
            set;
        }

        public void AddEntry(string entryName, DateTime dateTime, System.IO.FileStream stream)
        {
            string fileName = Path.Combine(tempPath, entryName);
            string directory = Path.GetDirectoryName(fileName);
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);
            using (var destStream = File.Create(fileName))
            {
                stream.CopyTo(destStream);
            }

            File.SetLastWriteTime(fileName, dateTime);
        }

        public bool Finish()
        {
            StringBuilder commandLine = new StringBuilder();
            string nupkgTempDirectory = CreateTempDirectory();
            try
            {
                commandLine.AppendFormat(CultureInfo.InvariantCulture, "pack \"{0}\"  -NoPackageAnalysis -BasePath \"{1}\" -OutputDirectory \"{2}\" -Version {3}", nuspecFile, tempPath, nupkgTempDirectory, version);
                foreach (var fileName in Directory.GetFiles(nupkgTempDirectory))
                    File.Move(fileName, Path.Combine(outputDir, Path.GetFileName(fileName)));
                string propertiesString = BuildPropertiesString();
                if (!string.IsNullOrWhiteSpace(propertiesString))
                    commandLine.AppendFormat(CultureInfo.InvariantCulture, " -Properties {0}", propertiesString);
                Log.LogMessage(MessageImportance.Low, "NuGet.exe path: {0} ", nugetPath);
                if (!RunNuget(commandLine.ToString()))
                    return false;
                string packageFileName = Directory.GetFiles(nupkgTempDirectory, "*.nupkg").Single();
                string pushCommandLine = CreatePushCommandLine(packageFileName);
                if (!string.IsNullOrWhiteSpace(pushCommandLine))
                {
                    Log.LogMessage(MessageImportance.Normal, "Pushing package {0} to {1}", Path.GetFileName(packageFileName), PushLocation);
                    if (!RunNuget(pushCommandLine))
                        return false;
                    Log.LogMessage(MessageImportance.Normal, "Push complete.");
                }

                string destFileName = Path.Combine(outputDir, Path.GetFileName(packageFileName));
                if (File.Exists(destFileName))
                {
                    Log.LogError("Cannot copy package to '{0}', file already exists.", destFileName);
                    return false;
                }

                File.Copy(packageFileName, destFileName);
                Log.LogMessage(MessageImportance.Normal, "Created package '{0}'", destFileName);
                return true;
            }
            finally
            {
                TryRemoveTempDirectory(nupkgTempDirectory);
            }
        }

        private string CreatePushCommandLine(string packageFileName)
        {
            if (!string.IsNullOrWhiteSpace(PushLocation))
            {
                StringBuilder sb = new StringBuilder("push ");
                sb.Append(packageFileName);
                if (!string.IsNullOrWhiteSpace(ApiKey))
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, " -ApiKey {0}", ApiKey);
                }

                sb.AppendFormat(CultureInfo.InvariantCulture, " -Source \"{0}\"", PushLocation);
                return sb.ToString();
            }
            else
                return null;
        }

        private bool RunNuget(string commandLine)
        {
            Log.LogMessage(MessageImportance.Low, "Running NuGet.exe with command line arguments: {0}", commandLine);
            var exitCode = SilentProcessRunner.ExecuteCommand(nugetPath, commandLine, tempPath, output => Log.LogMessage(MessageImportance.Low, output), error => Log.LogError("NUGET: {0}", error));
            if (exitCode != 0)
            {
                Log.LogError("There was an error calling NuGet. Please see the output above for more details. Command line: '{0}' {1}", nugetPath, commandLine);
                return false;
            }

            return true;
        }

        public void Dispose()
        {
            TryRemoveTempDirectory(tempPath);
        }

        private static void TryRemoveTempDirectory(string tempDirectory)
        {
            if (Directory.Exists(tempDirectory))
            {
                try
                {
                    Directory.Delete(tempDirectory, true);
                }
                catch (IOException)
                {
                }
            }
        }
    }
}


text:
exopy.measurement.container module
=============================

.. automodule:: exopy.measurement.container
    :members:
    :undoc-members:
    :show-inheritance:


text:
module Washington
  VERSION = "0.1.0"
end


text:
/**
 * after obtaining data from closure files, use converter to massage the data into the formats
 * we want
 */
exports.convertDatetimeData = convertDatetimeData;
exports.convertNumberData = convertNumberData;

var parsePattern = require('./parser').parsePattern;

function convertNumberData(dataObj, currencySymbols) {
  var numberFormats = {},

  numberFormats = {
    DECIMAL_SEP: dataObj.DECIMAL_SEP,
    GROUP_SEP: dataObj.GROUP_SEP,
    PATTERNS: [parsePattern(dataObj.DECIMAL_PATTERN),
               parsePattern(dataObj.CURRENCY_PATTERN)]
  }

  if (currencySymbols[dataObj.DEF_CURRENCY_CODE]) {
    numberFormats.CURRENCY_SYM = currencySymbols[dataObj.DEF_CURRENCY_CODE][1];
  } else {
    if (dataObj.DEF_CURRENCY_CODE == 'MTL') {
      numberFormats.CURRENCY_SYM = '₤'; //for some reason this is missing in closure
    } else {
      // if there is no corresponding currency symbol, just use currency code.
      var code = numberFormats.CURRENCY_SYM = dataObj.DEF_CURRENCY_CODE;
      console.log(code +' has no currency symbol in closure, used ' + code + ' instead!');
    }
  }
  return numberFormats;
}

function convertDatetimeData(dataObj) {
  var datetimeFormats = {};

  datetimeFormats.MONTH = dataObj.MONTHS;
  datetimeFormats.SHORTMONTH = dataObj.SHORTMONTHS;
  datetimeFormats.DAY = dataObj.WEEKDAYS;
  datetimeFormats.SHORTDAY = dataObj.SHORTWEEKDAYS;
  datetimeFormats.AMPMS = dataObj.AMPMS;
  datetimeFormats.ERAS = dataObj.ERAS;
  datetimeFormats.ERANAMES = dataObj.ERANAMES;

  datetimeFormats.medium      = dataObj.DATEFORMATS[2] + ' ' + dataObj.TIMEFORMATS[2];
  datetimeFormats.short       = dataObj.DATEFORMATS[3] + ' ' + dataObj.TIMEFORMATS[3];
  datetimeFormats.fullDate    = dataObj.DATEFORMATS[0];
  datetimeFormats.longDate    = dataObj.DATEFORMATS[1];
  datetimeFormats.mediumDate  = dataObj.DATEFORMATS[2];
  datetimeFormats.shortDate   = dataObj.DATEFORMATS[3];
  datetimeFormats.mediumTime  = dataObj.TIMEFORMATS[2];
  datetimeFormats.shortTime   = dataObj.TIMEFORMATS[3];

  return datetimeFormats;
}