passwordComponent.put(dbms, usernamePassword.getValue()); });
protected ArrayList<IWare> findWaresOfInterest(List<Pair<IWare, Number>> sortedNeeds) { ArrayList<IWare> waresOfInterest = new ArrayList<>(); // wares to be delivered to hometown for (Pair<IWare, Number> need : sortedNeeds) { if (need.getValue().doubleValue() < 0 || waresOfInterest.isEmpty()) { waresOfInterest.add(need.getKey()); } else if (waresOfInterest.size() < 2) { // Have at least 2 entries in the list waresOfInterest.add(need.getKey()); } else { break; // list is sorted by value increasing order } } return waresOfInterest; }
/** * Check if the <code>ware</code> is needed in a city. * @param knowledge of the city that should be checked. * @param ware for which should be checked. * @return true if there is not much of the ware around. */ public boolean isNeeded(ICityProductionConsumptionKnowledge knowledge, IWare ware) { List<Pair<IWare, Number>> needs = getMostNeededWares(knowledge); for (Pair<IWare, Number> need : needs) { if (need.getKey().equals(ware) && need.getValue().intValue() < 10) { return true; } else if (need.getKey().equals(ware) || need.getValue().intValue() > 10) { return false; } } return false; }
/** * Distribute the income to all the participants in a convoy. */ private void distributeCostsToAllConvoyParticipants(IConvoy convoy, Pair<Integer, Integer> amountBougth, int loaded, double discountBonus) { Map<IPlayer, Integer> capacityMap = convoy.getCapacityPerOwner(); long totalPrice = (long) Math.rint(-amountBougth.getValue() * loaded * discountBonus); updatePlayerByCapacityPercentage(convoy, capacityMap, totalPrice); } private void distributeIncomeToConvoyParticipants(IConvoy vessel, int avgPrice, int sold) {
/** * Instantiate a new service simulator compatible to the given config pair. * * @param configPair contains the simulation target and the type of service to simulate. * @return the simulator * @throws InstantiationException is thrown if any error occurs during the instantiation. * @throws InterruptedException is thrown if the current thread was externally interrupted. */ @Override public AbstractServiceSimulator newInstance(final Pair<UnitController, ServiceType> configPair) throws InstantiationException, InterruptedException { try { // try to return costum service simulator final String serviceSimulatorClassName = AbstractServiceSimulator.class.getPackage().getName() + "." + StringProcessor.transformUpperCaseToCamelCase(configPair.getValue().name()) + "Simulator"; return ((Class<? extends AbstractServiceSimulator>) Class.forName(serviceSimulatorClassName)).getConstructor(UnitController.class).newInstance(configPair.getKey()); } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | java.lang.InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException ex) { ExceptionPrinter.printHistory("Could not find custom service simulator for " + configPair.getValue().getClass().getName() + "[" + configPair.getValue().name() + "]", ex, LOGGER, LogLevel.DEBUG); } // return generic service simulator return new GenericServiceSimulator(configPair.getKey(), configPair.getValue()); } }
@Override public Map<RoleType, Pair<String, Type>> getRoleVarTypeMap() { if (roleVarTypeMap == null) { if (varTypeRoleMap != null) { roleVarTypeMap = new HashMap<>(); varTypeRoleMap.forEach((var, tpair) -> { RoleType rt = tpair.getValue(); if (rt != null) roleVarTypeMap.put(rt, new Pair<>(var, tpair.getKey())); }); } else roleVarTypeMap = computeRoleVarTypeMap(); } return roleVarTypeMap; } }
private void render() { Pair<Mesh, Material> meshAndMaterial = meshAndMaterialToRender.getAndSet(null); if (meshAndMaterial != null) { planarRegionMeshView.setMesh(meshAndMaterial.getKey()); planarRegionMeshView.setMaterial(meshAndMaterial.getValue()); } }
final Pair<String, Integer> index1 = orderedIndices.get(i); final Pair<String, Integer> index2 = orderedIndices.get(j); final Skeleton3D skeleton1 = inputFrames.get(index1.getKey()).getSkeletons().get(index1.getValue()); final Skeleton3D skeleton2 = inputFrames.get(index2.getKey()).getSkeletons().get(index2.getValue()); if (index1.getKey().equals(index2.getKey()) || skeleton1.isEmpty() || skeleton2.isEmpty()) { distances[i][j] = Double.MAX_VALUE;
private Optional<ICity> findNearestCityWithNeed(ICity city, IAIPlayer player, IWare ware, INavigableVessel vessel, ICity excludeCity) { IProductionConsumptionKnowledge knowledge = player.getProductionAndConsumptionKnowledge(); List<ICity> cityList = mapService.getNonBlockadedCitiesOrderedByDistance(city, vessel); cityList.remove(excludeCity); for (ICity iCity : cityList) { ICityProductionConsumptionKnowledge cityProduction = knowledge.getKnowlege(iCity); List<Pair<IWare, Number>> mostNeeded = getMostNeededWares(cityProduction); for (Pair<IWare, Number> pair : mostNeeded) { if (pair.getKey().equals(ware) && pair.getValue().intValue() < 10) { return Optional.of(iCity); } } } return Optional.empty(); }
private void updateMeshView(MeshView meshViewToUpdate, Pair<Mesh, Material> meshMaterial) { meshViewToUpdate.setMesh(meshMaterial.getKey()); meshViewToUpdate.setMaterial(meshMaterial.getValue()); }
/** * Figure out the ware that are most needed in the city. The need is calculated upon the knowledge * of the production, consumption and sotred amount. If a ware is not consumed at all it is not needed at * all, compared to wares that have more consumption than stored + produced. Also consider the amount of that ware * that is loaded on the <code>vessel</code>. That ware is treated the same way as if it stored in the city, with the * effect that on the first call the most needed ware might be BEER, but once an amount is bought the most needed ware might * change. * @param knowledge base knowledge * @param vessel on which the wares are loaded. * @return sorted list Pair of wares and their importants. The lower the number the more important. */ public List<Pair<IWare, Number>> getMostNeededWares(ICityProductionConsumptionKnowledge knowledge, INavigableVessel vessel) { List<Pair<IWare, Number>> sortedNeeds = getMostNeededWares(knowledge); for (ListIterator<Pair<IWare, Number>> iterator = sortedNeeds.listIterator(); iterator.hasNext(); ) { Pair<IWare, Number> need = iterator.next(); if (vessel.getWare(need.getKey()).getAmount() > 0) { int value = need.getValue().intValue() + vessel.getWare(need.getKey()).getAmount(); iterator.remove(); iterator.add(new Pair<>(need.getKey(), value)); } } return sortedNeeds.stream().sorted(new WareNeedComparator()).collect(Collectors.toList()); }
public static Rule createPropertyChainRule(String ruleId, RelationType relation, String fromRoleId, String toRoleId, LinkedHashMap<RelationType, Pair<String, String>> chain, MindmapsGraph graph){ Stack<String> varNames = new Stack<>(); varNames.push("x"); Set<VarAdmin> bodyVars = new HashSet<>(); chain.forEach( (relType, rolePair) ->{ String varName = createFreshVariable(Sets.newHashSet(varNames), "x"); VarAdmin var = Graql.var().isa(relType.getId()) .rel(rolePair.getKey(), varNames.peek()) .rel(rolePair.getValue(), varName).admin(); varNames.push(varName); bodyVars.add(var); }); Var headVar = Graql.var().isa(relation.getId()).rel(fromRoleId, "x").rel(toRoleId, varNames.peek()); String body = Patterns.conjunction(bodyVars).toString() + ";"; String head = headVar.toString() + ";"; return graph.putRule(ruleId, body, head, graph.getMetaRuleInference()); }
public ScriptExecutor(Collection<Pair<String, String>> libraries, String scriptName, String scriptCode, Map<String,Object> globalObjects) { scriptEngine = (NashornScriptEngine)new NashornScriptEngineFactory().getScriptEngine(); bindings = new SimpleBindings(); bindings.putAll(globalObjects); scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); libraries.forEach(p->{ bindings.put(NASHORN_SCRIPT_FILE_NAME, p.getKey()); try { scriptEngine.eval(p.getValue()); } catch (ScriptException e) { throw new RuntimeException(e); } }); try { bindings.put(NASHORN_SCRIPT_FILE_NAME, scriptName); compiledScript = scriptEngine.compile(scriptCode); } catch (ScriptException e) { throw new RuntimeException(e); } }
@Override public void handle(long now) { if (show.get() && root.getChildren().isEmpty()) root.getChildren().add(footstepGraphMeshView); else if (!show.get() && !root.getChildren().isEmpty()) root.getChildren().clear(); if (reset.getAndSet(false)) { footstepGraphToRender.set(null); footstepGraphMeshView.setMesh(null); footstepGraphMeshView.setMaterial(null); return; } Pair<Mesh, Material> newMesh = footstepGraphToRender.get(); if (newMesh != null) { footstepGraphMeshView.setMesh(newMesh.getKey()); footstepGraphMeshView.setMaterial(newMesh.getValue()); } }
@Override public void initializeTradeCycle(IAIPlayer player, INavigableVessel vessel) { // find closest city having producing one of the tradable wares. Pair<ICity, IWare> pair = findClosestCityProducingTradableWare(player, vessel); Optional<ICity> optCity = shipService.findCity(vessel); if (optCity.isPresent()) { if (optCity.get().equals(pair.getKey())) { // in start city handleBuyWaresInStartCity(player, vessel, optCity.get()); } else { // in different city handleBuyWaresReturnToStartCity(player, vessel, optCity.get(), pair.getKey()); } } else { TravelToTradeStep travelTo = createTravelToStep(vessel, pair.getKey()); append(player, vessel, travelTo); } DynamicTradeRouteMissionData missionData = new DynamicTradeRouteMissionData(); missionData.setWare(pair.getValue()); player.setTradeMission(vessel, missionData); } @VisibleForTesting
@Override public void handle(long now) { if (show.get() && root.getChildren().isEmpty()) { root.getChildren().addAll(bodyPathMeshView); } else if (!show.get() && !root.getChildren().isEmpty()) { root.getChildren().clear(); } if (reset.getAndSet(false)) { bodyPathMeshView.setMesh(null); bodyPathMeshView.setMaterial(null); bodyPathMeshToRender.set(null); return; } Pair<Mesh, Material> newMesh = bodyPathMeshToRender.getAndSet(null); if (newMesh != null) { if (VERBOSE) PrintTools.info(this, "Rendering body path line."); bodyPathMeshView.setMesh(newMesh.getKey()); bodyPathMeshView.setMaterial(newMesh.getValue()); } }
@Override public void handleShipArrivesInPort(IShipEntersPortEvent event) { INavigableVessel vessel = event.getShip(); if (isMatchingTradeStrategy(vessel)) { IAIPlayer player = (IAIPlayer) vessel.getOwner(); ICity city = event.getCity(); IProductionConsumptionKnowledge globalKnowledge = player.getProductionAndConsumptionKnowledge(); DynamicTradeRouteMissionData missionData = (DynamicTradeRouteMissionData) player.getTradeMission(vessel); int wareAmount = vessel.getWare(missionData.getWare()).getAmount(); if (wareAmount > 0) { // TODO: andi 10/27/17 when selling all wares in this city we still travel one further: #631 List<IWare> wareOfInterest = Collections.singletonList(missionData.getWare()); ICity nextStop = findNextStopForSelling(city, globalKnowledge, wareOfInterest, vessel, city); addDefaultTradeSteps(vessel, player, city, nextStop, new HashSet<>(), new HashSet<>(), false); } else { Pair<ICity, IWare> pair = findClosestCityProducingTradableWare(player, vessel); missionData.setWare(pair.getValue()); handleBuyWaresReturnToStartCity(player, vessel, city, pair.getKey()); } } } }
public <R> RulesEvaluator<T> build() { //TODO add logic for node validators //and all rules and pass through boolean filter RulesEvaluator<T> evaluator = null; if (ruleList.isEmpty()) { evaluator = new RulesEvaluator<>( monitoredWrapped, filter(monitoredWrapped, not(monitoredWrapped)) ); } else { List testList = new ArrayList(); for (Pair<SerializableConsumer, Function<T, ?>> pair : ruleList) { SerializableConsumer<? extends R> rule = pair.getKey(); Function<T, R> supplier = (Function<T, R>) pair.getValue(); testList.add(buildTest(rule, monitoredWrapped, supplier).build()); } evaluator = new RulesEvaluator<>( filterMatch(monitoredWrapped, and(testList.toArray())), filterMatch(monitoredWrapped, nand(testList.toArray())) ); } EventPublsher publisher = new EventPublsher(); publisher.addEventSource(monitoredWrapped); publisher = GenerationContext.SINGLETON.addOrUseExistingNode(publisher); publisher.addValidatedSource(evaluator.passedNotifier()); SINGLETON.addOrUseExistingNode(new LogNotifier(evaluator.failedNotifier())); return evaluator; } }
private Pair<Integer, Integer> buyWareFromCity(IPlayer player, ICity city, int availableAmountCity, IWare ware, long cash, int amountToBuy, int maxAvgPrice) { Pair<Integer, Integer> affordable = calculateAffordableAmountToBuy(ware, cash, amountToBuy, availableAmountCity, maxAvgPrice); amountToBuy = affordable.getKey(); int avgPriceCompleteAmount = affordable.getValue(); if (amountToBuy == 0) { return new Pair<>(0, 0); } int movedAmount = city.move(ware, -amountToBuy, player); if (amountToBuy != -movedAmount) { avgPriceCompleteAmount = computablePrice.buyPrice(ware, new SimpleIntegerProperty(city.getWare(ware).getAmount() + movedAmount), new ConstantIntegerBinding(movedAmount)); amountToBuy = -movedAmount; } return new Pair<>(amountToBuy, avgPriceCompleteAmount); }