text:
<?php
namespace Tqdev\PhpCrudApi;

use Tqdev\PhpCrudApi\Cache\CacheFactory;
use Tqdev\PhpCrudApi\Column\DefinitionService;
use Tqdev\PhpCrudApi\Column\ReflectionService;
use Tqdev\PhpCrudApi\Controller\CacheController;
use Tqdev\PhpCrudApi\Controller\ColumnController;
use Tqdev\PhpCrudApi\Controller\OpenApiController;
use Tqdev\PhpCrudApi\Controller\RecordController;
use Tqdev\PhpCrudApi\Controller\Responder;
use Tqdev\PhpCrudApi\Database\GenericDB;
use Tqdev\PhpCrudApi\Middleware\AuthorizationMiddleware;
use Tqdev\PhpCrudApi\Middleware\BasicAuthMiddleware;
use Tqdev\PhpCrudApi\Middleware\CorsMiddleware;
use Tqdev\PhpCrudApi\Middleware\CustomizationMiddleware;
use Tqdev\PhpCrudApi\Middleware\FirewallMiddleware;
use Tqdev\PhpCrudApi\Middleware\JwtAuthMiddleware;
use Tqdev\PhpCrudApi\Middleware\MultiTenancyMiddleware;
use Tqdev\PhpCrudApi\Middleware\PageLimitsMiddleware;
use Tqdev\PhpCrudApi\Middleware\Router\SimpleRouter;
use Tqdev\PhpCrudApi\Middleware\SanitationMiddleware;
use Tqdev\PhpCrudApi\Middleware\ValidationMiddleware;
use Tqdev\PhpCrudApi\Middleware\XsrfMiddleware;
use Tqdev\PhpCrudApi\OpenApi\OpenApiService;
use Tqdev\PhpCrudApi\Record\ErrorCode;
use Tqdev\PhpCrudApi\Record\RecordService;

class Api
{
    private $router;
    private $responder;
    private $debug;

    public function __construct(Config $config)
    {
        $db = new GenericDB(
            $config->getDriver(),
            $config->getAddress(),
            $config->getPort(),
            $config->getDatabase(),
            $config->getUsername(),
            $config->getPassword()
        );
        $cache = CacheFactory::create($config);
        $reflection = new ReflectionService($db, $cache, $config->getCacheTime());
        $responder = new Responder();
        $router = new SimpleRouter($responder, $cache, $config->getCacheTime());
        foreach ($config->getMiddlewares() as $middleware => $properties) {
            switch ($middleware) {
                case 'cors':
                    new CorsMiddleware($router, $responder, $properties);
                    break;
                case 'firewall':
                    new FirewallMiddleware($router, $responder, $properties);
                    break;
                case 'basicAuth':
                    new BasicAuthMiddleware($router, $responder, $properties);
                    break;
                case 'jwtAuth':
                    new JwtAuthMiddleware($router, $responder, $properties);
                    break;
                case 'validation':
                    new ValidationMiddleware($router, $responder, $properties, $reflection);
                    break;
                case 'sanitation':
                    new SanitationMiddleware($router, $responder, $properties, $reflection);
                    break;
                case 'multiTenancy':
                    new MultiTenancyMiddleware($router, $responder, $properties, $reflection);
                    break;
                case 'authorization':
                    new AuthorizationMiddleware($router, $responder, $properties, $reflection);
                    break;
                case 'xsrf':
                    new XsrfMiddleware($router, $responder, $properties);
                    break;
                case 'pageLimits':
                    new PageLimitsMiddleware($router, $responder, $properties, $reflection);
                    break;
                case 'customization':
                    new CustomizationMiddleware($router, $responder, $properties, $reflection);
                    break;
            }
        }
        foreach ($config->getControllers() as $controller) {
            switch ($controller) {
                case 'records':
                    $records = new RecordService($db, $reflection);
                    new RecordController($router, $responder, $records);
                    break;
                case 'columns':
                    $definition = new DefinitionService($db, $reflection);
                    new ColumnController($router, $responder, $reflection, $definition);
                    break;
                case 'cache':
                    new CacheController($router, $responder, $cache);
                    break;
                case 'openapi':
                    $openApi = new OpenApiService($reflection, $config->getOpenApiBase());
                    new OpenApiController($router, $responder, $openApi);
                    break;
            }
        }
        $this->router = $router;
        $this->responder = $responder;
        $this->debug = $config->getDebug();
    }

    public function handle(Request $request): Response
    {
        $response = null;
        try {
            $response = $this->router->route($request);
        } catch (\Throwable $e) {
            if ($e instanceof \PDOException) {
                if (strpos(strtolower($e->getMessage()), 'duplicate') !== false) {
                    return $this->responder->error(ErrorCode::DUPLICATE_KEY_EXCEPTION, '');
                }
                if (strpos(strtolower($e->getMessage()), 'default value') !== false) {
                    return $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
                }
                if (strpos(strtolower($e->getMessage()), 'allow nulls') !== false) {
                    return $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
                }
                if (strpos(strtolower($e->getMessage()), 'constraint') !== false) {
                    return $this->responder->error(ErrorCode::DATA_INTEGRITY_VIOLATION, '');
                }
            }
            $response = $this->responder->error(ErrorCode::ERROR_NOT_FOUND, $e->getMessage());
            if ($this->debug) {
                $response->addHeader('X-Debug-Info', 'Exception in ' . $e->getFile() . ' on line ' . $e->getLine());
            }
        }
        return $response;
    }
}


text:
package com.saulpower.GreenWireTest.database;

import java.util.List;
import de.greenrobot.dao.DaoException;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
 * Entity mapped to table LEDGER_ITEM.
 */
public class LedgerItem extends SyncBase  {

    private transient long ledgerItemsLedgerAccountId;
    private transient long personPersonId;
    private String postingDate;
    private String externalID;
    private Boolean isVoid;
    private String guid;
    private String name;
    private String tagString;
    private Long tenantID;
    private transient long saveResultSaveResultId;
    private Float debit;
    private String dateLastModified;
    private transient Long syncBaseId;
    private Float credit;
    private Boolean isDeleted;
    private Integer version;
    private Long id;
    private transient long ledgerAccountLedgerAccountId;
    private String dateCreated;
    private String notes;

    /** Used to resolve relations */
    private transient DaoSession daoSession;

    /** Used for active entity operations. */
    private transient LedgerItemDao myDao;
    private LedgerAccount ledgerAccount;
    private Long ledgerAccount__resolvedKey;
    private Person person;
    private Long person__resolvedKey;
    private SaveResult saveResult;
    private Long saveResult__resolvedKey;
    private List<Attachment> attachments;
    private List<CustomValue> customValues;

    public LedgerItem() {
    }

    public LedgerItem(Long id) {
        this.id = id;
        setDerivedEntityType(getClass().getCanonicalName());
    }

    LedgerItem(long ledgerItemsLedgerAccountId, long personPersonId, String postingDate, String externalID, Boolean isVoid, String guid, String name, String tagString, Long tenantID, long saveResultSaveResultId, Float debit, String dateLastModified, Long syncBaseId, Float credit, Boolean isDeleted, Integer version, Long id, long ledgerAccountLedgerAccountId, String dateCreated, String notes) {
        this.ledgerItemsLedgerAccountId = ledgerItemsLedgerAccountId;
        this.personPersonId = personPersonId;
        this.postingDate = postingDate;
        this.externalID = externalID;
        this.isVoid = isVoid;
        this.guid = guid;
        this.name = name;
        this.tagString = tagString;
        this.tenantID = tenantID;
        this.saveResultSaveResultId = saveResultSaveResultId;
        this.debit = debit;
        this.dateLastModified = dateLastModified;
        this.syncBaseId = syncBaseId;
        this.credit = credit;
        this.isDeleted = isDeleted;
        this.version = version;
        this.id = id;
        this.ledgerAccountLedgerAccountId = ledgerAccountLedgerAccountId;
        this.dateCreated = dateCreated;
        this.notes = notes;
    }

    public LedgerItem(long ledgerItemsLedgerAccountId, long personPersonId, String postingDate, String externalID, Boolean isVoid, String guid, String name, String tagString, Long tenantID, long saveResultSaveResultId, Float debit, String dateLastModified, Float credit, Boolean isDeleted, Integer version, Long id, long ledgerAccountLedgerAccountId, String dateCreated, String notes) {
        this.ledgerItemsLedgerAccountId = ledgerItemsLedgerAccountId;
        this.personPersonId = personPersonId;
        this.postingDate = postingDate;
        this.externalID = externalID;
        this.isVoid = isVoid;
        this.guid = guid;
        this.name = name;
        this.tagString = tagString;
        this.tenantID = tenantID;
        this.saveResultSaveResultId = saveResultSaveResultId;
        this.debit = debit;
        this.dateLastModified = dateLastModified;
        this.credit = credit;
        this.isDeleted = isDeleted;
        this.version = version;
        this.id = id;
        this.ledgerAccountLedgerAccountId = ledgerAccountLedgerAccountId;
        this.dateCreated = dateCreated;
        this.notes = notes;
        setDerivedEntityType(getClass().getCanonicalName());
    }

    /** called by internal mechanisms, do not call yourself. */
    @Override
    public void __setDaoSession(DaoSession daoSession) {
        super.__setDaoSession(daoSession);
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getLedgerItemDao() : null;
    }

    public long getLedgerItemsLedgerAccountId() {
        return ledgerItemsLedgerAccountId;
    }

    public void setLedgerItemsLedgerAccountId(long ledgerItemsLedgerAccountId) {
        this.ledgerItemsLedgerAccountId = ledgerItemsLedgerAccountId;
    }

    public long getPersonPersonId() {
        return personPersonId;
    }

    public void setPersonPersonId(long personPersonId) {
        this.personPersonId = personPersonId;
    }

    public String getPostingDate() {
        return postingDate;
    }

    public void setPostingDate(String postingDate) {
        this.postingDate = postingDate;
    }

    public String getExternalID() {
        return externalID;
    }

    public void setExternalID(String externalID) {
        this.externalID = externalID;
    }

    public Boolean getIsVoid() {
        return isVoid;
    }

    public void setIsVoid(Boolean isVoid) {
        this.isVoid = isVoid;
    }

    public String getGuid() {
        return guid;
    }

    public void setGuid(String guid) {
        this.guid = guid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTagString() {
        return tagString;
    }

    public void setTagString(String tagString) {
        this.tagString = tagString;
    }

    public Long getTenantID() {
        return tenantID;
    }

    public void setTenantID(Long tenantID) {
        this.tenantID = tenantID;
    }

    public long getSaveResultSaveResultId() {
        return saveResultSaveResultId;
    }

    public void setSaveResultSaveResultId(long saveResultSaveResultId) {
        this.saveResultSaveResultId = saveResultSaveResultId;
    }

    public Float getDebit() {
        return debit;
    }

    public void setDebit(Float debit) {
        this.debit = debit;
    }

    public String getDateLastModified() {
        return dateLastModified;
    }

    public void setDateLastModified(String dateLastModified) {
        this.dateLastModified = dateLastModified;
    }

    public Long getSyncBaseId() {
        return syncBaseId;
    }

    public void setSyncBaseId(Long syncBaseId) {
        this.syncBaseId = syncBaseId;
    }

    public Float getCredit() {
        return credit;
    }

    public void setCredit(Float credit) {
        this.credit = credit;
    }

    public Boolean getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(Boolean isDeleted) {
        this.isDeleted = isDeleted;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public long getLedgerAccountLedgerAccountId() {
        return ledgerAccountLedgerAccountId;
    }

    public void setLedgerAccountLedgerAccountId(long ledgerAccountLedgerAccountId) {
        this.ledgerAccountLedgerAccountId = ledgerAccountLedgerAccountId;
    }

    public String getDateCreated() {
        return dateCreated;
    }

    public void setDateCreated(String dateCreated) {
        this.dateCreated = dateCreated;
    }

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    /** To-one relationship, resolved on first access. */
    public LedgerAccount getLedgerAccount() {
        long __key = this.ledgerAccountLedgerAccountId;
        if (ledgerAccount__resolvedKey == null || !ledgerAccount__resolvedKey.equals(__key)) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            LedgerAccountDao targetDao = daoSession.getLedgerAccountDao();
            LedgerAccount ledgerAccountNew = targetDao.load(__key);
            synchronized (this) {
                ledgerAccount = ledgerAccountNew;
            	ledgerAccount__resolvedKey = __key;
            }
        }
        return ledgerAccount;
    }

    public void setLedgerAccount(LedgerAccount ledgerAccount) {
        if (ledgerAccount == null) {
            throw new DaoException("To-one property 'ledgerAccountLedgerAccountId' has not-null constraint; cannot set to-one to null");
        }
        synchronized (this) {
            this.ledgerAccount = ledgerAccount;
            ledgerAccountLedgerAccountId = ledgerAccount.getId();
            ledgerAccount__resolvedKey = ledgerAccountLedgerAccountId;
        }
    }

    /** To-one relationship, resolved on first access. */
    public Person getPerson() {
        long __key = this.personPersonId;
        if (person__resolvedKey == null || !person__resolvedKey.equals(__key)) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            PersonDao targetDao = daoSession.getPersonDao();
            Person personNew = targetDao.load(__key);
            synchronized (this) {
                person = personNew;
            	person__resolvedKey = __key;
            }
        }
        return person;
    }

    public void setPerson(Person person) {
        if (person == null) {
            throw new DaoException("To-one property 'personPersonId' has not-null constraint; cannot set to-one to null");
        }
        synchronized (this) {
            this.person = person;
            personPersonId = person.getId();
            person__resolvedKey = personPersonId;
        }
    }

    /** To-one relationship, resolved on first access. */
    public SaveResult getSaveResult() {
        long __key = this.saveResultSaveResultId;
        if (saveResult__resolvedKey == null || !saveResult__resolvedKey.equals(__key)) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            SaveResultDao targetDao = daoSession.getSaveResultDao();
            SaveResult saveResultNew = targetDao.load(__key);
            synchronized (this) {
                saveResult = saveResultNew;
            	saveResult__resolvedKey = __key;
            }
        }
        return saveResult;
    }

    public void setSaveResult(SaveResult saveResult) {
        if (saveResult == null) {
            throw new DaoException("To-one property 'saveResultSaveResultId' has not-null constraint; cannot set to-one to null");
        }
        synchronized (this) {
            this.saveResult = saveResult;
            saveResultSaveResultId = saveResult.getId();
            saveResult__resolvedKey = saveResultSaveResultId;
        }
    }

    /** To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target entity. */
    public List<Attachment> getAttachments() {
        if (attachments == null) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            AttachmentDao targetDao = daoSession.getAttachmentDao();
            List<Attachment> attachmentsNew = targetDao._queryLedgerItem_Attachments(id);
            synchronized (this) {
                if(attachments == null) {
                    attachments = attachmentsNew;
                }
            }
        }
        return attachments;
    }

    /** Resets a to-many relationship, making the next get call to query for a fresh result. */
    public synchronized void resetAttachments() {
        attachments = null;
    }

    /** To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target entity. */
    public List<CustomValue> getCustomValues() {
        if (customValues == null) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            CustomValueDao targetDao = daoSession.getCustomValueDao();
            List<CustomValue> customValuesNew = targetDao._queryLedgerItem_CustomValues(id);
            synchronized (this) {
                if(customValues == null) {
                    customValues = customValuesNew;
                }
            }
        }
        return customValues;
    }

    /** Resets a to-many relationship, making the next get call to query for a fresh result. */
    public synchronized void resetCustomValues() {
        customValues = null;
    }

    /** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }

    /** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }

    /** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.jpasecurity.persistence.security;

import static org.junit.Assert.assertEquals;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import org.hibernate.Query;
import org.jpasecurity.Alias;
import org.jpasecurity.TestEntityManager;
import org.jpasecurity.model.FieldAccessAnnotationTestBean;
import org.jpasecurity.security.authentication.TestSecurityContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

/**
 * @author Arne Limburg
 */
public class CriteriaAccessRulesGeneratorTest {

    public static final String USER = "user";

    @Rule
    public TestEntityManager entityManager
        = new TestEntityManager("annotation-based-field-access-criteria-access-rules-test");

    private CriteriaBuilder criteriaBuilder;
    private FieldAccessAnnotationTestBean accessibleBean;
    private FieldAccessAnnotationTestBean inaccessibleBean;

    @Before
    public void setUp() {
        TestSecurityContext.authenticate("admin", "admin");
        inaccessibleBean = new FieldAccessAnnotationTestBean("");
        accessibleBean = new FieldAccessAnnotationTestBean(USER, inaccessibleBean);
        entityManager.getTransaction().begin();
        entityManager.persist(inaccessibleBean);
        entityManager.persist(accessibleBean);
        entityManager.getTransaction().commit();
        entityManager.clear();
        criteriaBuilder = entityManager.getCriteriaBuilder();
    }

    @After
    public void tearDown() {
        TestSecurityContext.authenticate("admin", "admin");
        entityManager.getTransaction().begin();
        entityManager.remove(entityManager.merge(accessibleBean));
        entityManager.remove(entityManager.merge(inaccessibleBean));
        entityManager.getTransaction().commit();
        TestSecurityContext.authenticate(null);
    }

    @Test
    public void isNullAccessRule() {
        check(
            "isNull",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name is null");
    }

    @Test
    public void isNotNullAccessRule() {
        check(
            "isNotNull",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name is not null");
    }

    @Test
    public void inStaticStringsAccessRule() {
        check(
            "inStaticStrings",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name in (:param0)");
    }

    @Test
    public void inSubSelectAccessRule() {
        check(
            "inSubSelect",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name"
                + " in (select b.name from FieldAccessAnnotationTestBean as b)");
    }

    @Test
    public void notInStaticStringsAccessRule() {
        check(
            "notRefInStaticStrings",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name not in (:param0)");
    }

    @Test
    public void notInSubSelectAccessRule() {
        check(
            "notRefInSubSelect",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name"
                + " not in (select b.name from FieldAccessAnnotationTestBean as b)");
    }

    @Test
    public void refNotInStaticStringsAccessRule() {
        check(
            "refNotInStaticStrings",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name not in (:param0)");
    }

    @Test
    public void refNotInSubSelectAccessRule() {
        check(
            "refNotInSubSelect",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name"
                + " not in (select b.name from FieldAccessAnnotationTestBean as b)");
    }

    @Test
    public void subSelectJoiningAccessRule() {
        check(
            "subSelectJoining",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name"
                + " not in (select b.name from FieldAccessAnnotationTestBean as b,"
                + " FieldAccessAnnotationTestBean as p where b.parent=p)");
    }

    @Test
    public void subSelectJoiningMoreDottingAccessRule() {
        check(
            "subSelectJoiningMoreDotting",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name"
                + " not in (select b.name from FieldAccessAnnotationTestBean as b,"
                + " FieldAccessAnnotationTestBean as p where b.parent.parent=p)");
    }

    @Test
    public void notEqual1AccessRule() {
        check(
            "notEqual1",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name"
                + " not in (select b.name from FieldAccessAnnotationTestBean as b where b.id<>0)");
    }

    @Test
    public void notEqual2AccessRule() {
        check(
            "notEqual2",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.name"
                + " not in (select b.name from FieldAccessAnnotationTestBean as b where b.id<>0)");
    }

    @Test
    public void integerParameterAccessRule() {
        TestSecurityContext.register(new Alias("CURRENT_ID"), 1);
        check(
            "parameter",
            "select alias0 from FieldAccessAnnotationTestBean as alias0 where alias0.id=:CURRENT_ID");
    }

    private void check(Object roleName, String expectedQuery) {
        TestSecurityContext.authenticate("admin", roleName);
        CriteriaQuery<FieldAccessAnnotationTestBean> criteriaQuery
            = criteriaBuilder.createQuery(FieldAccessAnnotationTestBean.class);
        criteriaQuery.from(FieldAccessAnnotationTestBean.class);
        TypedQuery<FieldAccessAnnotationTestBean> entityQuery = entityManager.createQuery(criteriaQuery);
        String queryString = entityQuery.unwrap(Query.class).getQueryString();
        assertEquals(expectedQuery, queryString);
    }
}


text:
class BackwardGotcha < Gotcha::Base

  MIN_STRING_LENGTH = 8
  MAX_STRING_LENGTH = 15

  CHARS = ('a'..'z').to_a + ('0'..'9').to_a

  def initialize
    string_length = rand(MAX_STRING_LENGTH - MIN_STRING_LENGTH) + MIN_STRING_LENGTH
    string = (0...string_length).collect { CHARS[Kernel.rand(CHARS.length)] }.join

    @question = "What is '#{string}' backwards?"
    @answer = string.reverse
  end

end

Gotcha.register_type BackwardGotcha


text:
using System.Linq;
using Itinero.Optimization.Solvers.Tours;
using Itinero.Optimization.Solvers.Tours.Sequences;
using Itinero.Optimization.Strategies.Random;
using Xunit;

namespace Itinero.Optimization.Tests.Solvers.Tours.Sequences
{
    public class IReadOnlyTourExtensionTests
    {
        [Fact]
        public void RandomSequence_ShouldSelectRandomWithProperSize()
        {
            var tour = new Tour(new [] { 0, 1, 2, 3, 4 }, 0);

            for (var t = 0; t < 100; t++)
            {
                var size = RandomGenerator.Default.Generate(tour.Count - 1) + 1;
                var s = tour.RandomSequence(size);

                Assert.Equal(size, s.Length);

                var index = tour.GetIndexOf(s[0]);
                for (var i = 0; i < s.Length; i++)
                {
                    var expected = tour.GetVisitAt((index + i) % tour.Count);
                    Assert.Equal(expected, s[i]);
                }
            }
        }

        [Fact]
        public void RandomSequence_ShouldSelectRandomBetweenSizes()
        {
            var tour = new Tour(new [] { 0, 1, 2, 3, 4 }, 0);

            for (var t = 0; t < 100; t++)
            {
                RandomGenerator.Default.Generate2(tour.Count, out var minSize, out var maxSize);
                if (minSize > maxSize)
                {
                    var m = minSize;
                    minSize = maxSize;
                    maxSize = m;
                }

                var s = tour.RandomSequence(minSize, maxSize);

                Assert.True(s.Length >= minSize && s.Length <= maxSize);

                if (s.Length <= 0) continue;
                var index = tour.GetIndexOf(s[0]);
                for (var i = 0; i < s.Length; i++)
                {
                    var expected = tour.GetVisitAt((index + i) % tour.Count);
                    Assert.Equal(expected, s[i]);
                }
            }
        }

        [Fact]
        public void ReadOnlyTourRemovedSequence_ShouldRemoveSequenceAtBeginning()
        {
            var tour = new Tour(new [] { 0, 1, 2, 3, 4 }, 0);
            var s = new Sequence(new[] { 0, 1, 2});

            var tourReadonly = tour.WithoutSequence(s);
            Assert.NotNull(tourReadonly);
            Assert.Equal(3, tourReadonly.First);
            Assert.Equal(3, tourReadonly.Last);
            Assert.Equal(2, tourReadonly.Count);
            var removed = tourReadonly.ToArray();
            Assert.Equal(2, removed.Length);
            Assert.Equal(3, removed[0]);
            Assert.Equal(4, removed[1]);
        }

        [Fact]
        public void ReadOnlyTourRemovedSequence_ShouldRemoveSequenceAtEnd()
        {
            var tour = new Tour(new [] { 0, 1, 2, 3, 4 }, 0);
            var s = new Sequence(new[] { 2, 3, 4 });

            var tourReadonly = tour.WithoutSequence(s);
            Assert.NotNull(tourReadonly);
            Assert.Equal(0, tourReadonly.First);
            Assert.Equal(0, tourReadonly.Last);
            Assert.Equal(2, tourReadonly.Count);
            var removed = tourReadonly.ToArray();
            Assert.Equal(2, removed.Length);
            Assert.Equal(0, removed[0]);
            Assert.Equal(1, removed[1]);
        }

        [Fact]
        public void ReadOnlyTourRemovedSequence_ShouldRemoveSequenceInMiddle()
        {
            var tour = new Tour(new [] { 0, 1, 2, 3, 4 }, 0);
            var s = new Sequence(new[] { 1, 2, 3 });

            var tourReadonly = tour.WithoutSequence(s);
            Assert.NotNull(tourReadonly);
            Assert.Equal(0, tourReadonly.First);
            Assert.Equal(0, tourReadonly.Last);
            Assert.Equal(2, tourReadonly.Count);
            var removed = tourReadonly.ToArray();
            Assert.Equal(2, removed.Length);
            Assert.Equal(0, removed[0]);
            Assert.Equal(4, removed[1]);
        }

        [Fact]
        public void ReadOnlyTourRemovedSequence_ShouldRemoveSequenceOverFirst()
        {
            var tour = new Tour(new [] { 0, 1, 2, 3, 4 }, 0);
            var s = new Sequence(new[] { 4, 0, 1 });

            var tourReadonly = tour.WithoutSequence(s);
            Assert.NotNull(tourReadonly);
            Assert.Equal(2, tourReadonly.First);
            Assert.Equal(2, tourReadonly.Last);
            Assert.Equal(2, tourReadonly.Count);
            var removed = tourReadonly.ToArray();
            Assert.Equal(2, removed.Length);
            Assert.Equal(2, removed[0]);
            Assert.Equal(3, removed[1]);
        }

        [Fact]
        public void ReadOnlyTourRemovedSequence_ShouldRemoveEverything()
        {
            var tour = new Tour(new [] { 0, 1, 2, 3, 4 }, 0);
            var s = new Sequence(new[] { 0, 1, 2, 3, 4 });

            var tourReadonly = tour.WithoutSequence(s);
            Assert.Null(tourReadonly);
        }

        [Fact]
        public void CheapestInsertion_Sequence_ShouldCalculateCheapestLocationClosed()
        {
            var matrix = new [] {
                new float[] { 0, 1, 2, 3, 4 },
                new float[] { 4, 0, 1, 2, 3 },
                new float[] { 3, 4, 0, 1, 2 },
                new float[] { 2, 3, 4, 0, 1 },
                new float[] { 1, 2, 3, 4, 0 }};

            var tour = new Tour(new [] { 0, 1, 2, 3, 4 }, 0);
            var s = new Sequence(new[] { 4, 0, 1 });
            var tourReadOnly = tour.WithoutSequence(s);

            var result = tourReadOnly.CalculateCheapest((x, y) => matrix[x][y], new Sequence(new[] {1}));
            Assert.Equal(0, result.cost);
            Assert.Equal(3, result.location.From);
            Assert.Equal(2, result.location.To);
        }
    }
}


text:
package main

import (
	"bytes"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"math/rand"
	"os"
	"os/exec"
	"os/user"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"text/template"
	"time"

	"github.com/BurntSushi/toml"
)

func defaultConfigDir() string {
	return filepath.Join(xdgConfigDir(), "remote-do")
}

func xdgConfigDir() string {
	if d := os.Getenv("XDG_CONFIG_HOME"); d != "" {
		return d
	}
	var h string
	if u, err := user.Current(); err == nil {
		h = u.HomeDir
	} else {
		h = os.Getenv("HOME")
	}
	return filepath.Join(h, ".config")
}

var (
	configDir      = flag.String("configdir", defaultConfigDir(), "path to configuration directory")
	selectedRemote = flag.String("remote", "", "remote server to use (defaults to default in config)")
	namePre        = flag.String("name", "", "prefix to give session file")
)

func usage() {
	fmt.Fprintln(os.Stderr, "remote-do [args] cmd args...")
	flag.PrintDefaults()
	os.Exit(1)
}

func main() {
	rand.Seed(time.Now().UnixNano())
	log.SetPrefix("remote-do: ")
	log.SetFlags(0)
	flag.Usage = usage
	flag.Parse()
	if flag.NArg() == 0 {
		flag.Usage()
	}
	config, err := loadConfig(*configDir)
	if err != nil {
		log.Fatal(err)
	}
	remoteName := *selectedRemote
	if remoteName == "" {
		remoteName = config.DefaultRemote
	}
	if remoteName == "" {
		log.Fatal("no selected or default remote")
	}
	remote, ok := config.Remotes[remoteName]
	if !ok {
		log.Fatalf("selected remote %q has no config", remoteName)
	}
	if hasRelativeRemotePaths(remote) {
		remHome, err := getRemoteHome(remote)
		if err != nil {
			log.Fatalf("unable to get remote home directory: %v", err)
		}
		remote = resolveRelative(remote, remHome)
	}
	pre := ""
	if *namePre != "" {
		pre = *namePre + "-"
	}
	session, f, err := mkSessionFile(pre)
	if err != nil {
		log.Fatal(err)
	}

	remCacheDir := path.Join(remote.TopDir, "cache")
	remSessionDir := path.Join(remote.TopDir, session)
	remTempDir := remSessionDir + "-tmp"

	fmt.Println("clearing data and copying files...")
	_ = cexec("ssh", remote.Host, fmt.Sprintf(
		"rm -rf '%s'; [[ -d '%s' ]] && cp -R '%s' '%s'",
		remSessionDir, remCacheDir, remCacheDir, remSessionDir))
	args := []string{"-az", "--delete", "."}
	if _, err := os.Stat(".remote-do-ignore"); err == nil {
		args = []string{"-az", "--delete", "--exclude-from=.remote-do-ignore", "."}
	}
	err = cexec("rsync", append(args, remote.Host+":"+remSessionDir+"/")...)
	if err != nil {
		log.Fatalf("failed to copy files: %v", err)
	}
	err = cexec("ssh", remote.Host,
		fmt.Sprintf("rsync -a --delete '%s/' '%s'", remSessionDir, remCacheDir))
	if err != nil {
		log.Fatalf("failed to update remote cache: %v", err)
	}

	fmt.Println("running commands...")
	if !strings.HasPrefix(remote.JunestHome, "/") {
		remote.JunestHome = "$HOME/" + remote.JunestHome
	}
	if !strings.HasPrefix(remote.JunestRepo, "/") {
		remote.JunestRepo = "$HOME/" + remote.JunestRepo
	}
	outerBody, err := execTmpl(outerBodyTmpl, struct {
		TempDir    string
		JunestCmd  []string
		SessionDir string
	}{
		TempDir:    remTempDir,
		JunestCmd:  []string{"JUNEST_HOME=" + remote.JunestHome, path.Join(remote.JunestRepo, "bin", "junest")},
		SessionDir: remSessionDir,
	})
	if err != nil {
		log.Fatalf("unable to execute outerBody template: %v", err)
	}
	cmdRun, err := execTmpl(cmdRunTmpl, struct {
		InnerBody  string
		OuterBody  string
		SessionDir string
		Cmd        []string
	}{
		InnerBody:  innerBody,
		OuterBody:  outerBody,
		SessionDir: remSessionDir,
		Cmd:        flag.Args(),
	})
	if err != nil {
		log.Fatalf("unable to execute cmdRun template: %v", err)
	}

	if err := cexec("ssh", remote.Host, cmdRun); err != nil {
		log.Fatalf("error running command: %v", err)
	}

	err = sessionBodyTmpl.Execute(f, struct {
		Host       string
		SessionDir string
		TempDir    string
		Cmd        []string
	}{
		Host:       remote.Host,
		SessionDir: remSessionDir,
		TempDir:    remTempDir,
		Cmd:        flag.Args(),
	})
	if err != nil {
		log.Fatalf("unable to execute sessionBody template: %v", err)
	}

	f.Close()
	os.Chmod(session, 0755)
	fmt.Println(session)
}

func getRemoteHome(r Remote) (string, error) {
	out, err := exec.Command("ssh", r.Host, "echo", "$HOME").CombinedOutput()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(out)), nil
}

func cexec(name string, args ...string) error {
	cmd := exec.Command(name, args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func execTmpl(t *template.Template, data interface{}) (string, error) {
	var buf bytes.Buffer
	err := t.Execute(&buf, data)
	return buf.String(), err
}

const innerBody = `#!/usr/bin/env bash
export TMPDIR=/runtmp
cd "${0%/*}"
cmd=$1
shift
"$cmd" "$@"
`

const outerBody = `#!/usr/bin/env bash
mkdir -p "{{.TempDir}}"
env {{range $i, $e := .JunestCmd}}"{{$e}}" {{end}} -p "-b {{.TempDir}}:/runtmp" \
	"{{.SessionDir}}/remote-inner.bash" "$@"
`

const cmdRun = `\
echo '{{.OuterBody}}'>'{{.SessionDir}}/remote-outer.bash' && \
echo '{{.InnerBody}}'>'{{.SessionDir}}/remote-inner.bash' && \
chmod a+x '{{.SessionDir}}/remote-inner.bash' '{{.SessionDir}}/remote-outer.bash' && \
'{{.SessionDir}}/remote-outer.bash' {{range $i, $e := .Cmd}}'{{$e}}' {{end}}
`

const sessionBody = `#!/usr/bin/env bash
if [[ $1 == clean ]]; then
	# clean will delete files for us that are in the home directory.
	# This lets us safely use root to do so without worrying about
	# deleting unwanted things.
	# This is required because of the permissions docker files are
	# written with.
	ssh "{{.Host}}" "rm -rf '{{.SessionDir}}' '{{.TempDir}}'"
	rm -f "$0"
elif [[ $1 == cmd ]]; then
	echo {{range $i, $e := .Cmd}}{{$e}} {{end}}
else
	echo "usage: $0 cmd|clean" >&2
	exit 1
fi
`

var (
	outerBodyTmpl   = template.Must(template.New("outerBody").Parse(outerBody))
	cmdRunTmpl      = template.Must(template.New("cmdRun").Parse(cmdRun))
	sessionBodyTmpl = template.Must(template.New("sessionBody").Parse(sessionBody))
)

func mkSessionFile(namePre string) (string, *os.File, error) {
Start:
	session := namePre + "session." + strconv.FormatInt(rand.Int63(), 36)[:5]
	f, err := os.OpenFile(session, os.O_EXCL|os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		if os.IsExist(err) {
			goto Start
		}
	}
	return session, f, err
}

const configTmpl = `
# Example config file (formatted using TOML).
# You should set default-remote and it's config.
#
#default-remote = default
#
#[remotes.default]
#host = www.example.com
#top-dir = /path/to/dir # or path/to/dir to be relative to your home dir
#junest-repo = /path/to/dir
#junest-home = /path/to/dir
`

func resolveRelative(r Remote, home string) Remote {
	for _, sp := range [...]*string{&r.TopDir, &r.JunestRepo, &r.JunestHome} {
		if !strings.HasPrefix(*sp, "/") {
			*sp = path.Join(home, *sp)
		}
	}
	return r
}

func hasRelativeRemotePaths(r Remote) bool {
	for _, s := range [...]string{r.TopDir, r.JunestRepo, r.JunestHome} {
		if !strings.HasPrefix(s, "/") {
			return true
		}
	}
	return false
}

type Remote struct {
	Host       string `toml:"host"`
	TopDir     string `toml:"top-dir"`
	JunestRepo string `toml:"junest-repo"`
	JunestHome string `toml:"junest-home"`
}

type Config struct {
	DefaultRemote string            `toml:"default-remote"`
	Remotes       map[string]Remote `toml:"remotes"`
}

func loadConfig(d string) (*Config, error) {
	if fi, err := os.Stat(d); err != nil || !fi.IsDir() {
		os.MkdirAll(d, 0755)
	}
	cp := filepath.Join(d, "config.toml")
	if _, err := os.Stat(cp); err != nil {
		ioutil.WriteFile(cp, []byte(configTmpl), 0644)
		return nil, fmt.Errorf("missing config, created skeleton at %s", cp)
	}

	var config Config
	_, err := toml.DecodeFile(cp, &config)
	return &config, err
}


text:
using System.Collections.Generic;

namespace NExtra.IO
{
    /// <summary>
    /// This interface can be implemented by classes that
    /// can match file and directory paths with a pattern,
    /// e.g. *.txt, b*, a*.txt.
    /// </summary>
    /// <remarks>
    /// Author:     Daniel Saidi [daniel.saidi@gmail.com]
    /// Link:       http://danielsaidi.github.com/nextra
    /// </remarks>
    public interface IPathPatternMatcher
    {
        bool IsAnyMatch(string path, IEnumerable<string> patterns);
        bool IsMatch(string path, string pattern);
    }
}


text:
package xal.extension.jels.tools.math;

import xal.tools.math.fnc.poly.RealUnivariatePolynomial;

/**
 *

 * Represents a model function of the form: ( x1 + x2(x0/x-1) + x3/2(x0/x-1)^2 +
 * ... + xn/(n-1)!(x0/x-1)^(n-1) ) / x1 where x0,x1,...,xn are parameters.

 *
 *

 * This is an encapsulation of a TTF function as is used in TraceWin. The class
 * is extended from UnivariateRealPolynomial just so it can be easily switched
 * with it.

 *
 * @author Ivo List
 * @author Juan F. Esteban Müller <juanf.estebanmuller@esss.se>
 *
 */
public class InverseRealPolynomial extends RealUnivariatePolynomial {

    /*
     *  Local Attributes
     */
    /**
     * the vector of coefficients
     */
    private double[] m_arrCoef = null;

    /*
      * Initialization
     */
    /**
     * Creates an empty polynomial object, the zero polynomial.
     */
    public InverseRealPolynomial() {
    }

    /**
     * Creates and initializes a polynomial to the specified coefficients.
     *
     * @param arrCoef
     */
    public InverseRealPolynomial(double[] arrCoef) {
        this.setCoefArray(arrCoef);
    }

    /**
     * Set the entire coefficient array. The coefficient array is arranged in
     * order of ascending indeterminate order.
     *
     * @param arrCoef double array of coefficients.
     */
    @Override
    public void setCoefArray(double[] arrCoef) {
        this.m_arrCoef = arrCoef.clone();
    }

    /*
     * Attribute Queries
     */
    /**
     * @return the degree of the polynomial. That is, the highest indeterminant
     * order for all the nonzero coefficients.
     */
    @Override
    public int getDegree() {
        return this.getCoefs().length - 1;
    }

    /**
     * Get the specified coefficient value.
     *
     * If the value of iOrder is larger than the size of the
     * coefficient array then the coefficient is assumed to have value zero.
     *
     * @param iOrder index of coefficient
     * @return coefficient
     */
    @Override
    public double getCoef(int iOrder) {
        if (this.m_arrCoef.length == 0) {
            return 0.0;
        }
        if (iOrder >= this.m_arrCoef.length) {
            return 0.0;
        }

        return this.m_arrCoef[iOrder];
    }

    /**
     * Return the entire array of coefficients.
     *
     * @return the entire coefficient array
     */
    @Override
    public double[] getCoefs() {
        return this.m_arrCoef;
    }

    /*
     *  Polynomial operations
     */
    /**
     * Evaluate the model function for the specified value: (x1 + x2(x0/x-1) +
     * x3/2(x0/x-1)^2 + ... + xn/(n-1)!(x0/x-1)^(n-1)) / x1 where x0,x1,...,xn
     * are coefficients.
     *
     * @param dblVal indeterminate value to evaluate the model function at
     * @return
     */
    @Override
    public double evaluateAt(double dblVal) {
        if (this.m_arrCoef == null || this.m_arrCoef.length == 0) {
            return 1.0;
        }

        double x0 = m_arrCoef[0];
        if (x0 == 0.0) {
            return 1.0;
        }

        int length = this.m_arrCoef.length;      // number of coefficients
        double dblAccum = 0.0;                 // accumulator

        for (int n = length - 1; n >= 1; n--) {
            double f = 1.;
            for (int j = 2; j < n; j++) {
                f *= j;
            }
            dblAccum += this.getCoef(n) * Math.pow(x0 / dblVal - 1, n - 1) / f;
        }

        return dblAccum / m_arrCoef[1];
    }

    /**
     * Evaluate derivative of the model function for the specified value of the
     * indeterminate. If the coefficient vector has not been specified, it
     * return 0.
     *
     * (-x2(x0 x^-2) - x3(x0/x-1)(x0 x^-2) - ... - xn/(n-2)!(x0/x-1)^(n-2)(x0
     * x^-2)) / x1 where x0,x1,...,xn are coefficients.
     *
     * @param dblVal indeterminate value to evaluate the model function
     * derivative
     */
    @Override
    public double derivativeAt(double dblVal) {
        if (this.m_arrCoef == null || this.m_arrCoef.length == 0) {
            return 0.0;
        }

        double x0 = m_arrCoef[0];
        // number of coefficients
        int length = this.m_arrCoef.length;
        // accumulator
        double dblAccum = 0.0;

        for (int n = length - 1; n >= 2; n--) {
            double f = 1.;
            for (int j = 2; j < n - 1; j++) {
                f *= j;
            }
            dblAccum += this.getCoef(n) * Math.pow(x0 / dblVal - 1, n - 2) * x0 / dblVal / dblVal / f;
        }

        return -dblAccum / m_arrCoef[1];
    }

    public InverseRealPolynomial plus(InverseRealPolynomial polyAddend) {
        throw new UnsupportedOperationException();
    }

    public InverseRealPolynomial times(InverseRealPolynomial polyFac) {
        throw new UnsupportedOperationException();
    }

    /*
     * Testing and Debugging
     */
    /**
     * Construct and return a textual representation of the contents of this
     * model function as a String object.
     *
     * @return a String representation of the model function contents
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        int length = this.getDegree();

        String x0 = Double.toString(this.getCoef(0));
        String strPoly = "(" + Double.toString(this.getCoef(1));

        for (int n = 2; n <= length; n++) {
            strPoly += " + " + this.getCoef(n) + "(" + x0 + "/x)^" + (n - 1);
        }

        return strPoly + ")/x1";
    }

}


text:
playground
==========

misc stupid stuff and experiments


text:
const path = require('path')
const getRepositoryName = require('git-repo-name').sync
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OpenBrowserPlugin = require('open-browser-webpack-plugin')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
const SETTINGS = require('./settings')

const production = process.env.NODE_ENV === 'production'
const pagesBuild = process.env.BUILD === 'pages'

const stylesLoaders = [
  {
    loader: 'css-loader',
    options: { minimize: production },
  },
  'postcss-loader',
]

const loaders = [
  {
    test: /\.(js|jsx)$/,
    loader: 'babel-loader',
    include: path.join(__dirname, 'src'),
    exclude: /node_modules/,
  },

  {
    test: /\.(css|scss)$/,
    loader: production
      ? ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: stylesLoaders,
        })
      : ['style-loader', ...stylesLoaders],
  },

  {
    test: /\.(svg|png|jpg|jpeg|gif|woff|woff2|otf|ttf|eot)$/,
    loader: 'url-loader',
  },
]

const pluginsBase = [
  new HtmlWebpackPlugin({ template: 'template.ejs' }),
  new FaviconsWebpackPlugin(SETTINGS.FAVICONS),
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify(process.env.NODE_ENV || ''),
    },
  }),
]

const developmentPlugins = [
  ...pluginsBase,
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NamedModulesPlugin(),
  new OpenBrowserPlugin({ url: `http://localhost:${SETTINGS.PORT}` }),
]

const productionPlugins = [
  ...pluginsBase,
  new LodashModuleReplacementPlugin(),
  new ExtractTextPlugin('[name].css'),
  new webpack.optimize.OccurrenceOrderPlugin(),
  new webpack.optimize.UglifyJsPlugin({
    beautify: false,
    comments: false,
    compress: {
      sequences: true,
      booleans: true,
      loops: true,
      unused: false,
      warnings: false,
      drop_console: true,
      unsafe: true,
    },
  }),
]

module.exports = {
  devtool: production ? 'cheap-module-source-map' : 'eval',

  entry: production
    ? path.join(__dirname, './src/index')
    : [
        'react-hot-loader/patch',
        `webpack-dev-server/client?http://localhost:${SETTINGS.PORT}`,
        'webpack/hot/only-dev-server',
        path.join(__dirname, './src/index'),
      ],

  output: {
    path: SETTINGS.PUBLIC_PATH,
    filename: 'bundle.js',
    publicPath: pagesBuild ? `/${getRepositoryName()}/` : '/',
  },

  resolve: {
    modules: [path.join(__dirname, 'src'), 'node_modules'],
    extensions: ['.js', '.jsx'],
  },

  module: { loaders },
  plugins: production ? productionPlugins : developmentPlugins,
}


text:
"""Define package constants."""
import logging

LOGGER = logging.getLogger(__package__)

DEFAULT_USER_AGENT = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
    "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Safari/605.1.15"
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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.
-->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:cxf="http://camel.apache.org/schema/cxf"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
         http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd">

    <!-- notice address is just relative to the servlet mapping -->
    <cxf:cxfEndpoint id="inventoryEndpoint"
                     address="/inventory"
                     serviceClass="camelinaction.inventory.InventoryEndpoint"/>

</beans>


text:
class Spike
{
public:
	Spike();
	Spike(int CellID, double SpikeTime_Seconds);
	void Dump(void);
	int CellID;
	double SpikeTime_Seconds;	// Spike time from start of frame, in seconds
};

class SpikeStream
{
public:
	// Spike stream default constructor
	SpikeStream();
	// Construct a SpikeStream from a given array of spikes
	SpikeStream(Spike *Spikes, int MaxSpikes, bool IsInput);
	// Construct a SpikeStream from a given array of spikes, using a provided sample rate
	SpikeStream(Spike *Spikes, int MaxSpikes, bool IsInput, double SampleRate_Hz);

	// Set the sample rate for the current SpikeStream
	void SetSampleRate_Hz(double SampleRate_Hz);

	// Resets the current step to the start of the frame.  Requires SampleRate_Hz to be set
	void NewFrame(void);
	// Steps the SpikeStream to the next sample.  Requires SampleRate_Hz to be set
	void Step(void);

	// Causes a spike to be logged for the given CellID at the given time.  Times must never decrease across subsequent calls to Fire in any frame
	void Fire(int CellID, double SpikeTime_Seconds);
	// Causes a spike to be logged for the given CellID at the current sample step time.  Requires SampleRate_Hz to be set
	void Fire(int CellID);

	// This method returns the number of spikes between the given start and end times, (inclusive), for the given CellID
	int CountSpikes(int CellID, double StartTime_Seconds, double EndTime_Seconds);
	// This method returns the number of spikes between the given start and end times, (inclusive), for the given set of CellIDs
	int CountSpikes(int *CellIDs, int NumCellIDs, double StartTime_Seconds, double EndTime_Seconds);
	// This method returns the number of spikes in the current sample interval for the given CellID
	int CountSpikes(int CellID);
	// This method returns the number of spikes in the current sample interval for the given set of CellIDs
	int CountSpikes(int *CellIDs, int NumCellIDs);

	// Writes a formatted display of the current stream contents to cout
	void Dump(void);

private:
	void Init(Spike *Spikes, int MaxSpikes, bool IsInput);
	void FindStepIndices(void);

	bool IsInput;
	int MaxSpikes;
	int CurSpikes;
	Spike *Spikes;
	double SampleRate_Hz;
	double SecondsPerSample;
	double CurStepStart_Seconds;
	double CurStepEnd_Seconds;
	int CurStepIndexStart;
	int CurStepIndexEnd;
	bool DataAvailableInCurrentTimeStep;
};

#endif


text:
package pia.dao;

import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Qualifier
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
public @interface JPADAO {

}


text:
/*eslint max-nested-callbacks: 0*/
/*jscs:disable requirePaddingNewLinesInObjects*/
/*jscs:disable jsDoc*/

define([
    'underscore',
    'uiRegistry',
    'Magento_Ui/js/form/components/collection/item'
], function (_, registry, Constr) {
    'use strict';

    describe('Magento_Ui/js/form/components/collection/item', function () {
        var obj = new Constr({
            provider: 'provName',
            name: '',
            index: ''
        });

        registry.set('provName', {
            on: function () {
            },
            get: function () {
            },
            set: function () {
            }
        });

        describe('"initProperties" method', function () {
            it('Check for defined ', function () {
                expect(obj.hasOwnProperty('initProperties')).toBeDefined();
            });
            it('Check answer type', function () {
                var type = typeof obj.initProperties;

                expect(type).toEqual('function');
            });
            it('Check returned value if method called without arguments', function () {
                expect(obj.initProperties()).toBeDefined();
            });
            it('Check returned value type if method called without arguments', function () {
                var type = typeof obj.initProperties();

                expect(type).toEqual('object');
            });
            it('Check "displayed" property', function () {
                obj.displayed = null;
                obj.initProperties();
                expect(obj.displayed).toEqual([]);
            });
        });
        describe('"initObservable" method', function () {
            it('Check for defined ', function () {
                expect(obj.hasOwnProperty('initObservable')).toBeDefined();
            });
            it('Check answer type', function () {
                var type = typeof obj.initObservable;

                expect(type).toEqual('function');
            });
            it('Check returned value if method called without arguments', function () {
                expect(obj.initObservable()).toBeDefined();
            });
            it('Check returned value type if method called without arguments', function () {
                var type = typeof obj.initObservable();

                expect(type).toEqual('object');
            });
            it('Check called "this.observe" method', function () {
                obj.observe = jasmine.createSpy();
                obj.initObservable();
                expect(obj.observe).toHaveBeenCalled();
            });
        });
        describe('"initElement" method', function () {
            it('Check for defined ', function () {
                expect(obj.hasOwnProperty('initElement')).toBeDefined();
            });
            it('Check answer type', function () {
                var type = typeof obj.initElement;

                expect(type).toEqual('function');
            });
            it('Check returned value if method called with object argument', function () {
                var arg = {
                    initContainer: function () {
                    }
                };

                expect(obj.initElement(arg)).toBeDefined();
            });
            it('Check returned value type if method called with object argument', function () {
                var arg = {
                        initContainer: function () {
                        }
                    },
                    type = typeof obj.initElement(arg);

                expect(type).toEqual('object');
            });
            it('Check called "this.insertToIndexed" method with object argument', function () {
                var arg = {
                    initContainer: function () {
                    }
                };

                obj.insertToIndexed = jasmine.createSpy();
                obj.initElement(arg);
                expect(obj.insertToIndexed).toHaveBeenCalledWith(arg);
            });
        });
        describe('"insertToIndexed" method', function () {
            it('Check for defined ', function () {
                expect(obj.hasOwnProperty('insertToIndexed')).toBeDefined();
            });
            it('Check answer type', function () {
                var type = typeof obj.insertToIndexed;

                expect(type).toEqual('function');
            });
            it('Check called "insertToIndexed" method with object argument', function () {
                var arg = {
                    initContainer: function () {
                    }
                };

                obj.insertToIndexed(arg);
                expect(obj.insertToIndexed).toHaveBeenCalledWith(arg);
            });
        });
        describe('"formatPreviews" method', function () {
            it('Check for defined ', function () {
                expect(obj.hasOwnProperty('formatPreviews')).toBeDefined();
            });
            it('Check answer type', function () {
                var type = typeof obj.formatPreviews;

                expect(type).toEqual('function');
            });
            it('Check returned value if call method with array arguments', function () {
                expect(obj.formatPreviews(['1', '2', '3'])).toEqual(
                    [
                        {
                            'items': ['1'],
                            'separator': ' ',
                            'prefix': ''
                        },
                        {
                            'items': ['2'],
                            'separator': ' ',
                            'prefix': ''
                        },
                        {
                            'items': ['3'],
                            'separator': ' ',
                            'prefix': ''
                        }
                    ]
                );
            });
        });
        describe('"buildPreview" method', function () {
            it('Check for defined ', function () {
                expect(obj.hasOwnProperty('buildPreview')).toBeDefined();
            });
            it('Check answer type', function () {
                var type = typeof obj.buildPreview;

                expect(type).toEqual('function');
            });
            it('Check returned value if method called with object argument', function () {
                var arg = {
                    items: [],
                    prefix: 'magento'
                };

                expect(obj.buildPreview(arg)).toBeDefined();
            });
            it('Check returned value type if method called with object argument', function () {
                var arg = {
                        items: [],
                        prefix: 'magento'
                    },
                    type = typeof obj.buildPreview(arg);

                expect(type).toEqual('string');
            });
            it('Check called "this.getPreview" method with object argument', function () {
                var arg = {
                    items: [],
                    prefix: 'magento'
                };

                obj.getPreview = jasmine.createSpy().and.callFake(function () {
                    return [];
                });
                obj.buildPreview(arg);
                expect(obj.getPreview).toHaveBeenCalledWith(arg.items);
            });
        });
        describe('"hasPreview" method', function () {
            it('Check for defined ', function () {
                expect(obj.hasOwnProperty('hasPreview')).toBeDefined();
            });
            it('Check answer type', function () {
                var type = typeof obj.hasPreview;

                expect(type).toEqual('function');
            });
            it('Check returned value type if method called with object argument', function () {
                var arg = {
                        items: [],
                        prefix: 'magento'
                    },
                    type = typeof obj.hasPreview(arg);

                expect(type).toEqual('boolean');
            });
            it('Check called "this.getPreview" method with object argument', function () {
                var arg = {
                    items: [],
                    prefix: 'magento'
                };

                obj.getPreview = jasmine.createSpy().and.callFake(function () {
                    return [];
                });
                obj.hasPreview(arg);
                expect(obj.getPreview).toHaveBeenCalledWith(arg.items);
            });
        });
        describe('"getPreview" method', function () {
            it('Check for defined ', function () {
                expect(obj.hasOwnProperty('getPreview')).toBeDefined();
            });
            it('Check answer type', function () {
                var type = typeof obj.getPreview;

                expect(type).toEqual('function');
            });
            it('Check returned value type if method called with object argument', function () {
                var arg = {
                        items: [],
                        prefix: 'magento'
                    },
                    type = typeof obj.getPreview(arg);

                expect(type).toEqual('object');
            });
        });
    });
});


text:
[![CI Status](http://img.shields.io/travis/pourhadi/SuperSerial.svg?style=flat)](https://travis-ci.org/pourhadi/SuperSerial)
[![Version](https://img.shields.io/cocoapods/v/SuperSerial.svg?style=flat)](http://cocoapods.org/pods/SuperSerial)
[![License](https://img.shields.io/cocoapods/l/SuperSerial.svg?style=flat)](http://cocoapods.org/pods/SuperSerial)
[![Platform](https://img.shields.io/cocoapods/p/SuperSerial.svg?style=flat)](http://cocoapods.org/pods/SuperSerial)

## Usage

SuperSerial uses Swift's Mirror to automatically infer a struct's stored variables, allowing for hassle-free out-of-the-box JSON serialization. Conforming that struct to AutoSerializable allows for easy deserialization as well.

Also supports custom serialization for structs and object types.

See header comments for more details.

    struct Person {
        let name:String
        let age:Int
    }

    extension Person:AutoSerializable {
        init?(withValuesForKeys: [String : Serializable]) {
            self.name = withValuesForKeys["name"] as! String
            self.age = withValuesForKeys["age"] as! Int
        }
    }

    let people:[Serializable] = [Person(name: "Bob", age: 30), Person(name: "Lisa", age: 32), Person(name: "Mark", age: 29)]

Specify the types that can be serialized and deserialized:

    SuperSerial.serializableTypes = [Person.self]

Serialize and deserialize:

    let serialized = Serialized(fromArray: people)
    let jsonString = serialized.toString()
    let fromString = Serialized(serializedString: jsonString)
    let deserialized = fromString?.deserialize()

## Requirements

## Installation

SuperSerial is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "SuperSerial"
```

## Author

Daniel Pourhadi, dan@pourhadi.com

## License

SuperSerial is available under the MIT license. See the LICENSE file for more info.