public void testBasic() throws Exception {
    if (!Dpkg.available()) {
      return;
    }

    DebPackagingFormat packagingFormat = (DebPackagingFormat) lookup(PackagingFormat.ROLE, "deb");

    FileObject dpkgTest = VFS.getManager().resolveFile(getTestPath("target/deb-test"));
    FileObject packageRoot = dpkgTest.resolveFile("root");
    File packageFile = VfsUtil.asFile(dpkgTest.resolveFile("file.deb"));

    PackageVersion version = packageVersion("1.0", "123", false, some("1"));
    PackageParameters parameters =
        packageParameters(
                "mygroup",
                "myartifact",
                version,
                "id",
                "default-name",
                Option.<java.lang.String>none(),
                EMPTY,
                EMPTY)
            .contact("Kurt Cobain")
            .architecture("all");

    List<String> nil = List.nil();
    packagingFormat
        .start()
        .parameters(parameters)
        .debParameters(Option.<String>none(), some("devel"), false, nil, nil, nil, nil, nil, nil)
        .debug(true)
        .workingDirectory(packageRoot)
        .packageToFile(packageFile, ScriptUtil.Strategy.SINGLE);

    assertTrue(packageFile.canRead());
  }
Example #2
0
  @Override
  public void performIteration(NichingAlgorithm alg) {
    Preconditions.checkState(
        alg.getOptimisationProblem() instanceof DeratingOptimisationProblem,
        "DeratingNichePSO can only be used with DeratingOptimisationProblem.");
    DeratingOptimisationProblem problem =
        (DeratingOptimisationProblem) alg.getOptimisationProblem();

    List<PopulationBasedAlgorithm> subswarms =
        List.<PopulationBasedAlgorithm>iterableList(alg.getPopulations());
    subswarms =
        onMainSwarm(Algorithms.<PopulationBasedAlgorithm>initialise())
            .andThen(phase1(alg))
            .andThen(onSubswarms(clearDeratingSolutions(problem)))
            .andThen(phase2(alg))
            .andThen(joinAndMerge(alg, subswarms))
            .f(
                NichingSwarms.of(
                    alg.getMainSwarm(), Collections.<PopulationBasedAlgorithm>emptyList()))
            ._2();

    problem.clearSolutions();
    problem.addSolutions(
        subswarms
            .map(Solutions.getPosition().o(Algorithms.<PopulationBasedAlgorithm>getBestSolution()))
            .toCollection());
    alg.setPopulations(Lists.newLinkedList(subswarms.toCollection()));
    alg.getMainSwarm().setOptimisationProblem(problem);
    // dont need to set the main swarm because it gets reinitialised
  }
 /*
  * Reinitialises part of, or the whole, population
  * @param topology The population to be reinitialised
  */
 private void reinitialisePosition(fj.data.List<ClusterParticle> topology) {
   int index = 0;
   for (int i = index; i < topology.length(); i += reinitialisationInterval) {
     ClusterParticle c = topology.index(i);
     c.reinitialise();
     c.calculateFitness();
   }
 }
Example #4
0
  /**
   * Filters elements from this array by returning only elements which produce <code>true</code>
   * when the given function is applied to them.
   *
   * @param f The predicate function to filter on.
   * @return A new array whose elements all match the given predicate.
   */
  @SuppressWarnings("unchecked")
  public Array<A> filter(final F<A, Boolean> f) {
    List<A> x = List.nil();

    for (int i = a.length - 1; i >= 0; i--) {
      if (f.f((A) a[i])) x = x.cons((A) a[i]);
    }

    return x.toArray();
  }
Example #5
0
  /**
   * Returns a list projection of this array.
   *
   * @return A list projection of this array.
   */
  @SuppressWarnings("unchecked")
  public List<A> toList() {
    List<A> x = List.nil();

    for (int i = a.length - 1; i >= 0; i--) {
      x = x.cons((A) a[i]);
    }

    return x;
  }
Example #6
0
 @Test
 public void testLift() {
   final Promise<Integer> p1 = promise(3), p2 = promise(4);
   final Promise<Integer> p3 = lift(addInts).f(p1, p2);
   assertEquals(7, (int) p3.claim());
   final List<Integer> list = list(1, 2, 3, 4);
   final List<Promise<Integer>> pList = list.map(Promises.<Integer>promise());
   Promise<Integer> p4 = pList.foldLeft(lift(addInts), promise(0));
   assertEquals(10, (int) p4.claim());
   assertEquals(
       10, (int) Promise.foldRight(Strategies.sequential, curry(addInts), 0).f(list).claim());
 }
 private boolean doesNotExist(final List<DBObject> existingIndexList, final DBObject indexObj) {
   DBObject[] indexes = new DBObject[existingIndexList.size()];
   existingIndexList.toArray(indexes);
   return !list(indexes)
       .exists(
           new F<DBObject, Boolean>() {
             @Override
             public Boolean f(final DBObject document) {
               DBObject keyObj = (DBObject) document.get("key");
               return keyObj.equals(indexObj);
             }
           });
 }
 private boolean doesNotExist(final List<DBObject> existingIndexList, final String indexName) {
   DBObject[] indexes = new DBObject[existingIndexList.size()];
   existingIndexList.toArray(indexes);
   return !list(indexes)
       .exists(
           new F<DBObject, Boolean>() {
             @Override
             public Boolean f(final DBObject document) {
               String keyName = (String) document.get("name");
               return keyName.equals(indexName);
             }
           });
 }
Example #9
0
  /** Default constructor. Creates a new instance of {@code ABC}. */
  public ABC() {
    this.initialisationStrategy = new ClonedPopulationInitialisationStrategy();
    initialisationStrategy.setEntityNumber(100);
    initialisationStrategy.setEntityType(new WorkerBee());

    workerBees = fj.data.List.nil();
    onlookerBees = fj.data.List.nil();

    explorerBee = new ExplorerBee();
    dancingSelectionStrategy = new RouletteWheelSelector();

    forageLimit = ConstantControlParameter.of(500);
    workerBeePercentage = ConstantControlParameter.of(0.5);
    explorerBeeUpdateLimit = ConstantControlParameter.of(1.0);
  }
Example #10
0
  /**
   * Attempt to read every available block from the input stream.
   *
   * <p>Note: this implementation reads at most 255 blocks which is way beyond any reasonable value.
   *
   * @return list of read records
   */
  public List<VaultRecord> readAll() {
    List<VaultRecord> records = list();
    try {
      int i = 255;
      while (i-- > 0) {
        final VaultRecord record = readRecord();
        records = records.cons(record);
      }
    } catch (final Exception e) {
      // We'll eventually run into an exception when reaching the end of the block, so ignoring
      // this.
    }

    return records;
  }
Example #11
0
  /**
   * Binds the given function across each element of this array with a final join.
   *
   * @param f The function to apply to each element of this array.
   * @return A new array after performing the map, then final join.
   */
  @SuppressWarnings({"unchecked"})
  public <B> Array<B> bind(final F<A, Array<B>> f) {
    List<Array<B>> x = List.nil();
    int len = 0;

    for (int i = a.length - 1; i >= 0; i--) {
      final Array<B> bs = f.f((A) a[i]);
      len = len + bs.length();
      x = x.cons(bs);
    }

    final Object[] bs = new Object[len];

    x.foreach(
        new F<Array<B>, Unit>() {
          private int i;

          public Unit f(final Array<B> x) {
            arraycopy(x.a, 0, bs, i, x.a.length);
            i = i + x.a.length;
            return unit();
          }
        });

    return new Array<B>(bs);
  }
  @Test
  public void testCreation() {
    Particle p1 =
        NichingFunctionsTest.createParticle(new MinimisationFitness(3.0), Vector.of(0.0, 1.0));
    Particle p2 =
        NichingFunctionsTest.createParticle(new MinimisationFitness(2.0), Vector.of(1.0, 1.0));
    Particle p3 =
        NichingFunctionsTest.createParticle(new MinimisationFitness(1.0), Vector.of(2.0, 2.0));

    PSO pso = new PSO();
    pso.getTopology().addAll(Arrays.asList(p1, p2, p3));

    ClosestNeighbourNicheCreationStrategy creator = new ClosestNeighbourNicheCreationStrategy();
    creator.setSwarmBehavior(new ParticleBehavior());
    NichingSwarms swarms =
        creator.f(NichingSwarms.of(pso, List.<PopulationBasedAlgorithm>nil()), p1);

    Assert.assertEquals(1, swarms._1().getTopology().size());
    Assert.assertEquals(
        Vector.of(2.0, 2.0), swarms._1().getTopology().get(0).getCandidateSolution());
    Assert.assertEquals(2, swarms._2().head().getTopology().size());
    Assert.assertEquals(
        Vector.of(0.0, 1.0), swarms._2().head().getTopology().get(0).getCandidateSolution());
    Assert.assertEquals(
        Vector.of(1.0, 1.0), swarms._2().head().getTopology().get(1).getCandidateSolution());
  }
Example #13
0
  @Override
  public Object fromBinaryJava(byte[] bytes, Class<?> manifest) {
    OrderFormat orderFormat =
        SerializationExtension.get(system).deserialize(bytes, OrderFormat.class).get();

    return new Order(orderFormat.id, List.iterableList(orderFormat.items), orderFormat.cancelled);
  }
  @Test
  public void offspringCreation() {
    Individual i1 = new Individual();
    Individual i2 = new Individual();

    i1.put(Property.CANDIDATE_SOLUTION, Vector.of(0.0, 1.0, 2.0, 3.0, 4.0));
    i2.put(Property.CANDIDATE_SOLUTION, Vector.of(5.0, 6.0, 7.0, 8.0, 9.0));

    i1.setFitnessCalculator(new MockFitnessCalculator());
    i2.setFitnessCalculator(new MockFitnessCalculator());

    List<Individual> parents = Lists.newArrayList(i1, i2);

    CrossoverOperator crossoverStrategy = new CrossoverOperator();
    crossoverStrategy.setCrossoverStrategy(new OnePointCrossoverStrategy());
    crossoverStrategy.setCrossoverProbability(ConstantControlParameter.of(1.0));
    List<Individual> children = crossoverStrategy.crossover(fj.data.List.iterableList(parents));

    Vector child1 = (Vector) children.get(0).getPosition();
    Vector child2 = (Vector) children.get(1).getPosition();
    Vector parent1 = (Vector) i1.getPosition();
    Vector parent2 = (Vector) i2.getPosition();

    Assert.assertEquals(2, children.size());
    for (int i = 0; i < i1.getDimension(); i++) {
      Assert.assertNotSame(child1.get(i), parent1.get(i));
      Assert.assertNotSame(child1.get(i), parent2.get(i));
      Assert.assertNotSame(child2.get(i), parent1.get(i));
      Assert.assertNotSame(child2.get(i), parent2.get(i));
    }
  }
 @Override
 public List<ApplicationDTO> getList() throws InterruptedException {
   try {
     final ObjectMapper mapper = new ObjectMapper();
     return array(mapper.readValue(jsonApplications, ApplicationDTO[].class))
         .toList()
         .sort(ord(curry(ordering)));
   } catch (IOException e) {
     return List.nil();
   }
 }
Example #16
0
 /**
  * Sequence through the option monad.
  *
  * @param a The list of option to sequence.
  * @return The option of list after sequencing.
  */
 public static <A> Option<List<A>> sequence(final List<Option<A>> a) {
   return a.isEmpty()
       ? some(List.<A>nil())
       : a.head()
           .bind(
               new F<A, Option<List<A>>>() {
                 public Option<List<A>> f(final A aa) {
                   return sequence(a.tail()).map(cons_(aa));
                 }
               });
 }
Example #17
0
 /**
  * Sequences through the right side of the either monad with a list of values.
  *
  * @param a The list of values to sequence with the either monad.
  * @return A sequenced value.
  */
 public static <B, X> Either<X, List<B>> sequenceRight(final List<Either<X, B>> a) {
   return a.isEmpty()
       ? Either.<X, List<B>>right(List.<B>nil())
       : a.head()
           .right()
           .bind(
               new Func<B, Either<X, List<B>>>() {
                 public Either<X, List<B>> f(final B bb) {
                   return sequenceRight(a.tail()).right().map(cons_(bb));
                 }
               });
 }
Example #18
0
 /**
  * Sequences through the left side of the either monad with a list of values.
  *
  * @param a The list of values to sequence with the either monad.
  * @return A sequenced value.
  */
 public static <A, X> Either<List<A>, X> sequenceLeft(final List<Either<A, X>> a) {
   return a.isEmpty()
       ? Either.<List<A>, X>left(List.<A>nil())
       : a.head()
           .left()
           .bind(
               new Func<A, Either<List<A>, X>>() {
                 public Either<List<A>, X> f(final A aa) {
                   return sequenceLeft(a.tail()).left().map(cons_(aa));
                 }
               });
 }
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response invoices(@Context HttpServletRequest request) throws SQLException, IOException {
    authService.guardAuthenticatedUser(request);

    try (Connection c = dataSource.getConnection()) {
      List<UUID> ids = registrationsSqlMapper.all(c).map(x -> x.fst());
      List<RegistrationsSqlMapper.Registration> all = Option.somes(ids.traverseIO(ioify(c)).run());
      JsonRootNode overview =
          object(
              field(
                  "received",
                  array(
                      all.filter(x -> x.tuple.state == RegistrationState.RECEIVED)
                          .map(RegistrationsRestService::json))),
              field(
                  "invoicing",
                  array(
                      all.filter(x -> x.tuple.state == RegistrationState.INVOICING)
                          .map(RegistrationsRestService::json))),
              field(
                  "paid",
                  array(
                      all.filter(x -> x.tuple.state == RegistrationState.PAID)
                          .map(RegistrationsRestService::json))));
      return Response.ok(ArgoUtils.format(overview)).build();
    }
  }
  /** @param pso The {@link PSO} to have an iteration applied. */
  @Override
  public void performIteration(final PSO pso) {
    final fj.data.List<Particle> topology = pso.getTopology();
    this.calculateAbsoluteAverages(pso);
    this.updateInertia(pso);
    final F<Particle, Particle> first =
        new F<Particle, Particle>() {
          @Override
          public Particle f(Particle current) {
            WeightedInertiaVelocityProvider wp =
                (WeightedInertiaVelocityProvider) current.getVelocityProvider(); // put
            wp.setInertiaWeight(inertiaWeight);
            current.updateVelocity();
            current.updatePosition();

            boundaryConstraint.enforce(current);
            return current;
          }
        };

    final F<Particle, Particle> second =
        new F<Particle, Particle>() {
          public Particle f(Particle current) {
            current.calculateFitness();
            for (Particle other : pso.getNeighbourhood().f(topology, current)) {
              if (current
                      .getSocialFitness()
                      .compareTo(other.getNeighbourhoodBest().getSocialFitness())
                  > 0) {
                other.setNeighbourhoodBest(current);
              }
            }

            return current;
          }
        };

    pso.setTopology(topology.map(first).map(second));
  }
Example #21
0
 /**
  * Returns all the right values in the given list.
  *
  * @param es The list of possible right values.
  * @return All the right values in the given list.
  */
 public static <A, B> List<B> rights(final List<Either<A, B>> es) {
   return es.foldRight(
       new Func<Either<A, B>, Func<List<B>, List<B>>>() {
         public Func<List<B>, List<B>> f(final Either<A, B> e) {
           return new Func<List<B>, List<B>>() {
             public List<B> f(final List<B> bs) {
               return e.isRight() ? bs.cons(e.right().value()) : bs;
             }
           };
         }
       },
       List.<B>nil());
 }
Example #22
0
 /**
  * Returns all the left values in the given list.
  *
  * @param es The list of possible left values.
  * @return All the left values in the given list.
  */
 public static <A, B> List<A> lefts(final List<Either<A, B>> es) {
   return es.foldRight(
       new Func<Either<A, B>, Func<List<A>, List<A>>>() {
         public Func<List<A>, List<A>> f(final Either<A, B> e) {
           return new Func<List<A>, List<A>>() {
             public List<A> f(final List<A> as) {
               return e.isLeft() ? as.cons(e.left().value()) : as;
             }
           };
         }
       },
       List.<A>nil());
 }
Example #23
0
  private List<Integer> getNeighbourhood(final E e) {
    int currentIteration = getIteration();
    if (currentIteration > lastIteration || nHoods == null || perCall) {
      lastIteration = currentIteration;
      nHoods =
          getNeighbourhoods(distanceMeasure, radius, neighbourhoodSize)
              .f(
                  P.p(
                      List.<Entity>iterableList((java.util.List<Entity>) entities).zipIndex(),
                      List.<List<Integer>>nil()));
    }

    final int index = entities.indexOf(e);
    return nHoods
        .find(
            new F<List<Integer>, Boolean>() {
              @Override
              public Boolean f(List<Integer> a) {
                return a.exists(Equal.intEqual.eq(index));
              }
            })
        .orSome(List.single(index));
  }
Example #24
0
  @Path("/events/{eventName}/sessions")
  @GET
  public Response getSessionsForEvent(@PathParam("eventName") final String eventName) {
    IncogitoUri incogitoUri = new IncogitoUri(incogito.getConfiguration().baseurl);
    F<List<Session>, List<SessionXml>> sessionToXmlList =
        List.<Session, SessionXml>map_()
            .f(
                XmlFunctions.sessionToXml
                    .f(incogitoUri.restEvents().eventUri(eventName))
                    .f(incogitoUri.events().eventUri(eventName)));

    return toJsr311(
        incogito
            .getSessions(eventName)
            .ok()
            .map(compose(SessionListXml.sessionListXml, sessionToXmlList)));
  }
Example #25
0
  /** {@inheritDoc} */
  @Override
  public void algorithmInitialisation() {
    topology =
        fj.data.List.iterableList(initialisationStrategy.<HoneyBee>initialise(optimisationProblem));

    int numWorkerBees = (int) (workerBeePercentage.getParameter() * topology.length());
    P2<fj.data.List<HoneyBee>, fj.data.List<HoneyBee>> split = topology.splitAt(numWorkerBees);
    this.workerBees = split._1();
    this.onlookerBees =
        split
            ._2()
            .map(
                new F<HoneyBee, HoneyBee>() {
                  public HoneyBee f(HoneyBee b) {
                    return new OnlookerBee((WorkerBee) b);
                  }
                });

    explorerBee.setExplorerBeeUpdateLimit(this.explorerBeeUpdateLimit);
  }
Example #26
0
  public void performIteration(final TuningAlgorithm alg) {
    final List<Vector> parameterList = alg.getParameterList();

    // TODO: deal with maximisation problems
    results =
        results.snoc(
            parameterList.map(
                new F<Vector, OptimisationSolution>() {
                  @Override
                  public OptimisationSolution f(Vector a) {
                    return new OptimisationSolution(a, alg.evaluate(a));
                  }
                }));

    // (+1 because iterations start at 0)
    if (alg.getIterations() + 1 >= minProblems.getParameter() && parameterList.length() != 1) {
      List<List<Double>> data =
          results.map(
              List.<OptimisationSolution, Double>map_().f(getFitness().andThen(getValue())));
      P2<Double, Double> friedman = StatsTests.friedman(0.05, data);

      if (friedman._1() > friedman._2()) {
        final List<Integer> indexes = StatsTests.postHoc(0.05, friedman._1(), data);
        alg.setParameterList(indexes.map(flip(Utils.<Vector>index()).f(parameterList)));

        results =
            results.map(
                new F<List<OptimisationSolution>, List<OptimisationSolution>>() {
                  @Override
                  public List<OptimisationSolution> f(final List<OptimisationSolution> a) {
                    return indexes.map(flip(Utils.<OptimisationSolution>index()).f(a));
                  }
                });
      }
    }
  }
Example #27
0
 public static <T> List<T> listFromArray(T[] ar) {
   List<T> l = List.nil();
   for (T x : ar) l = l.snoc(x);
   return l;
 }
Example #28
0
 public static void main(final String[] args) {
   final List<Integer> a = list(1, 2, 3);
   final List<Integer> b = a.map(add.f(42));
   listShow(intShow).println(b); // [43,44,45]
 }
Example #29
0
 public static <T> boolean contains(List<T> l, F<T, Boolean> f) {
   Option<T> o = l.find(f);
   return o.isSome();
 }
Example #30
0
 /**
  * Returns a single element list if this projection has a value, otherwise an empty list.
  *
  * @return A single element list if this projection has a value, otherwise an empty list.
  */
 public List<B> toList() {
   return isRight() ? single(value()) : List.<B>nil();
 }