file_id
stringlengths
5
10
content
stringlengths
110
41.7k
repo
stringlengths
7
108
path
stringlengths
8
211
token_length
int64
35
8.19k
original_comment
stringlengths
11
5.72k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
73
41.6k
39056_2
package be.one16.barka.klant.adapter.out.order; import be.one16.barka.domain.exceptions.EntityNotFoundException; import be.one16.barka.klant.adapter.mapper.order.OrderJpaEntityMapper; import be.one16.barka.klant.adapter.out.repository.OrderRepository; import be.one16.barka.klant.common.OrderType; import be.one16.barka.klant.domain.Order; import be.one16.barka.klant.ports.out.order.CreateOrderPort; import be.one16.barka.klant.ports.out.order.DeleteOrderPort; import be.one16.barka.klant.ports.out.order.LoadOrdersPort; import be.one16.barka.klant.ports.out.order.UpdateOrderPort; import org.springframework.core.Ordered; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Component; import java.util.Optional; import java.util.UUID; @Component @org.springframework.core.annotation.Order(Ordered.HIGHEST_PRECEDENCE) public class OrderDBAdapter implements LoadOrdersPort, CreateOrderPort, UpdateOrderPort, DeleteOrderPort { private final OrderRepository orderRepository; private final OrderJpaEntityMapper orderJpaEntityMapper; public OrderDBAdapter(OrderRepository orderRepository, OrderJpaEntityMapper orderJpaEntityMapper) { this.orderRepository = orderRepository; this.orderJpaEntityMapper = orderJpaEntityMapper; } @Override public Order retrieveOrderById(UUID id) { OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(id); return orderJpaEntityMapper.mapJpaEntityToOrder(orderJpaEntity); } @Override public Page<Order> retrieveOrdersByFilterAndSort(String naam, Pageable pageable) { Specification<OrderJpaEntity> specification = Specification.where(naam == null ? null : (Specification<OrderJpaEntity>) ((root, query, builder) -> builder.like(root.get("naam"), "%" + naam + "%"))); return orderRepository.findAll(specification, PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort())) .map(orderJpaEntityMapper::mapJpaEntityToOrder); } @Override public void createOrder(Order order) { int year = order.getDatum().getYear(); OrderJpaEntity orderJpaEntity = new OrderJpaEntity(); orderJpaEntity.setUuid(order.getOrderId()); orderJpaEntity.setOrderType(order.getOrderType()); orderJpaEntity.setNaam(order.getNaam()); orderJpaEntity.setOpmerkingen(order.getOpmerkingen()); orderJpaEntity.setDatum(order.getDatum()); orderJpaEntity.setJaar(year); orderJpaEntity.setKlantId(order.getKlantId()); orderJpaEntity.setReparatieNummer(order.getReparatieNummer()); orderJpaEntity.setOrderNummer(order.getOrderNummer()); orderJpaEntity.setSequence(decideOnSequence(order)); orderRepository.save(orderJpaEntity); } @Override public void updateOrder(Order order) { int year = order.getDatum().getYear(); OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(order.getOrderId()); orderJpaEntity.setOrderType(order.getOrderType()); orderJpaEntity.setNaam(order.getNaam()); orderJpaEntity.setOpmerkingen(order.getOpmerkingen()); orderJpaEntity.setDatum(order.getDatum()); orderJpaEntity.setJaar(year); orderJpaEntity.setKlantId(order.getKlantId()); orderJpaEntity.setReparatieNummer(order.getReparatieNummer()); orderJpaEntity.setOrderNummer(order.getOrderNummer()); orderJpaEntity.setSequence(decideOnSequence(order)); orderRepository.save(orderJpaEntity); } @Override public void deleteOrder(UUID id) { OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(id); orderRepository.delete(orderJpaEntity); } private OrderJpaEntity getOrderJpaEntityById(UUID id) { return orderRepository.findByUuid(id).orElseThrow(() -> new EntityNotFoundException(String.format("Order with uuid %s doesn't exist", id))); } private int decideOnSequence(Order order){ int year = order.getDatum().getYear(); int sequence = 0; OrderType orderType = order.getOrderType(); //Enkel voor facturen, anders 0 if(orderType==OrderType.FACTUUR){ //Enkel wanneer er nog geen orderNummer bestaat, maken we een nieuwe sequence aan if(order.getOrderNummer()!=null) { Optional<OrderJpaEntity> factuur = orderRepository.findTopByJaarOrderBySequenceDesc(year); int sequenceLastFactuur = 0; if (!factuur.isEmpty()) { sequenceLastFactuur = factuur.get().getSequence(); sequence = sequenceLastFactuur + 1; }else{ //Wanneer er geen factuur gevonden wordt, is dit de eerste factuur sequence = 1; } }else{ //Anders blijft de sequence dezelfde OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(order.getOrderId()); sequence = orderJpaEntity.getSequence(); } } return sequence; } }
Floovera/fietsenbogaerts
klant/src/main/java/be/one16/barka/klant/adapter/out/order/OrderDBAdapter.java
1,371
//Wanneer er geen factuur gevonden wordt, is dit de eerste factuur
line_comment
nl
package be.one16.barka.klant.adapter.out.order; import be.one16.barka.domain.exceptions.EntityNotFoundException; import be.one16.barka.klant.adapter.mapper.order.OrderJpaEntityMapper; import be.one16.barka.klant.adapter.out.repository.OrderRepository; import be.one16.barka.klant.common.OrderType; import be.one16.barka.klant.domain.Order; import be.one16.barka.klant.ports.out.order.CreateOrderPort; import be.one16.barka.klant.ports.out.order.DeleteOrderPort; import be.one16.barka.klant.ports.out.order.LoadOrdersPort; import be.one16.barka.klant.ports.out.order.UpdateOrderPort; import org.springframework.core.Ordered; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Component; import java.util.Optional; import java.util.UUID; @Component @org.springframework.core.annotation.Order(Ordered.HIGHEST_PRECEDENCE) public class OrderDBAdapter implements LoadOrdersPort, CreateOrderPort, UpdateOrderPort, DeleteOrderPort { private final OrderRepository orderRepository; private final OrderJpaEntityMapper orderJpaEntityMapper; public OrderDBAdapter(OrderRepository orderRepository, OrderJpaEntityMapper orderJpaEntityMapper) { this.orderRepository = orderRepository; this.orderJpaEntityMapper = orderJpaEntityMapper; } @Override public Order retrieveOrderById(UUID id) { OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(id); return orderJpaEntityMapper.mapJpaEntityToOrder(orderJpaEntity); } @Override public Page<Order> retrieveOrdersByFilterAndSort(String naam, Pageable pageable) { Specification<OrderJpaEntity> specification = Specification.where(naam == null ? null : (Specification<OrderJpaEntity>) ((root, query, builder) -> builder.like(root.get("naam"), "%" + naam + "%"))); return orderRepository.findAll(specification, PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort())) .map(orderJpaEntityMapper::mapJpaEntityToOrder); } @Override public void createOrder(Order order) { int year = order.getDatum().getYear(); OrderJpaEntity orderJpaEntity = new OrderJpaEntity(); orderJpaEntity.setUuid(order.getOrderId()); orderJpaEntity.setOrderType(order.getOrderType()); orderJpaEntity.setNaam(order.getNaam()); orderJpaEntity.setOpmerkingen(order.getOpmerkingen()); orderJpaEntity.setDatum(order.getDatum()); orderJpaEntity.setJaar(year); orderJpaEntity.setKlantId(order.getKlantId()); orderJpaEntity.setReparatieNummer(order.getReparatieNummer()); orderJpaEntity.setOrderNummer(order.getOrderNummer()); orderJpaEntity.setSequence(decideOnSequence(order)); orderRepository.save(orderJpaEntity); } @Override public void updateOrder(Order order) { int year = order.getDatum().getYear(); OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(order.getOrderId()); orderJpaEntity.setOrderType(order.getOrderType()); orderJpaEntity.setNaam(order.getNaam()); orderJpaEntity.setOpmerkingen(order.getOpmerkingen()); orderJpaEntity.setDatum(order.getDatum()); orderJpaEntity.setJaar(year); orderJpaEntity.setKlantId(order.getKlantId()); orderJpaEntity.setReparatieNummer(order.getReparatieNummer()); orderJpaEntity.setOrderNummer(order.getOrderNummer()); orderJpaEntity.setSequence(decideOnSequence(order)); orderRepository.save(orderJpaEntity); } @Override public void deleteOrder(UUID id) { OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(id); orderRepository.delete(orderJpaEntity); } private OrderJpaEntity getOrderJpaEntityById(UUID id) { return orderRepository.findByUuid(id).orElseThrow(() -> new EntityNotFoundException(String.format("Order with uuid %s doesn't exist", id))); } private int decideOnSequence(Order order){ int year = order.getDatum().getYear(); int sequence = 0; OrderType orderType = order.getOrderType(); //Enkel voor facturen, anders 0 if(orderType==OrderType.FACTUUR){ //Enkel wanneer er nog geen orderNummer bestaat, maken we een nieuwe sequence aan if(order.getOrderNummer()!=null) { Optional<OrderJpaEntity> factuur = orderRepository.findTopByJaarOrderBySequenceDesc(year); int sequenceLastFactuur = 0; if (!factuur.isEmpty()) { sequenceLastFactuur = factuur.get().getSequence(); sequence = sequenceLastFactuur + 1; }else{ //Wanneer er<SUF> sequence = 1; } }else{ //Anders blijft de sequence dezelfde OrderJpaEntity orderJpaEntity = getOrderJpaEntityById(order.getOrderId()); sequence = orderJpaEntity.getSequence(); } } return sequence; } }
21042_24
package org.gertje.abacus.translator.javascript.nodevisitors; import org.gertje.abacus.nodes.AddNode; import org.gertje.abacus.nodes.AndNode; import org.gertje.abacus.nodes.AssignmentNode; import org.gertje.abacus.nodes.BinaryOperationNode; import org.gertje.abacus.nodes.BooleanNode; import org.gertje.abacus.nodes.DateNode; import org.gertje.abacus.nodes.DecimalNode; import org.gertje.abacus.nodes.DivideNode; import org.gertje.abacus.nodes.EqNode; import org.gertje.abacus.nodes.FactorNode; import org.gertje.abacus.nodes.FunctionNode; import org.gertje.abacus.nodes.GeqNode; import org.gertje.abacus.nodes.GtNode; import org.gertje.abacus.nodes.IfNode; import org.gertje.abacus.nodes.IntegerNode; import org.gertje.abacus.nodes.LeqNode; import org.gertje.abacus.nodes.LtNode; import org.gertje.abacus.nodes.ModuloNode; import org.gertje.abacus.nodes.MultiplyNode; import org.gertje.abacus.nodes.NegativeNode; import org.gertje.abacus.nodes.NeqNode; import org.gertje.abacus.nodes.Node; import org.gertje.abacus.nodes.NotNode; import org.gertje.abacus.nodes.NullNode; import org.gertje.abacus.nodes.OrNode; import org.gertje.abacus.nodes.PositiveNode; import org.gertje.abacus.nodes.PowerNode; import org.gertje.abacus.nodes.StatementListNode; import org.gertje.abacus.nodes.StringNode; import org.gertje.abacus.nodes.SubstractNode; import org.gertje.abacus.nodes.VariableNode; import org.gertje.abacus.nodevisitors.AbstractNodeVisitor; import org.gertje.abacus.nodevisitors.VisitingException; import org.gertje.abacus.token.Token; import org.gertje.abacus.types.Type; import java.util.Stack; public class JavaScriptTranslator extends AbstractNodeVisitor<Void, VisitingException> { /** * Deze stack gebruiken we om gedeeltelijke vertalingen in op te slaan. */ protected Stack<String> partStack; /** * Deze stack gebruiken we om variabelen die we gebruiken binnen een ifNode op te slaan. Dit is nodig omdat * JavaScript anders met NULL waardes omgaat dan Abacus. */ protected Stack<String> variableStack; /** * Deze stack gebruiken we om afgeleide if-statements in op te slaan, dit is inclusief toekenning aan een variabele. */ protected Stack<String> declarationStack; /** * Constructor. */ public JavaScriptTranslator() { partStack = new Stack<String>(); variableStack = new Stack<String>(); declarationStack = new Stack<String>(); } public String translate(Node node) throws VisitingException { ExpressionTranslator expressionTranslator = new ExpressionTranslator(node); StringBuilder translation = new StringBuilder(); // Wrap de expressie in een closure. Wanneer er geen declaraties zijn en er zijn geen controles op null en de // node is een NodeList, dan is deze closure onnodig. Voorlopig laat ik dit wel zo. translation.append("(function(){") .append(expressionTranslator.getDeclarations()) .append(expressionTranslator.getNullableCheck()) .append("return ").append(expressionTranslator.getExpression()).append(";") .append("})()"); return translation.toString(); } @Override public Void visit(AddNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "+"); return null; } @Override public Void visit(AndNode node) throws VisitingException { ExpressionTranslator lhsExpression = new ExpressionTranslator(node.getLhs()); ExpressionTranslator rhsExpression = new ExpressionTranslator(node.getRhs()); // Bouw javascript op die StringBuilder translation = new StringBuilder(); translation .append("var _").append(variableStack.size()).append("=(function(){") .append("var _l=(function(){") .append(lhsExpression.getDeclarations()) .append(lhsExpression.getNullableCheck()) .append("return ").append(lhsExpression.getExpression()) .append("})();") .append("if(_l===false)return false;") .append("var _r=(function(){") .append(rhsExpression.getDeclarations()) .append(rhsExpression.getNullableCheck()) .append("return ").append(rhsExpression.getExpression()) .append("})();") .append("if(_r===false)return false;") .append("if(_l==null||_r==null)return null;") .append("return true;") .append("})()"); declarationStack.push(translation.toString()); String variable = "_" + variableStack.size(); partStack.push(variable); variableStack.push(variable); return null; } @Override public Void visit(AssignmentNode node) throws VisitingException { node.getLhs().accept(this); // Pop tussendoor even de assignee van de variabelestack om te voorkomen dat we controleren of de assignee niet // null is. Anders zou je zoiets krijgen: a = 3 --> (function(){if(a==null)return null;return a = 3;})() variableStack.pop(); node.getRhs().accept(this); String rhsScript = partStack.pop(); String lhsScript = partStack.pop(); // Cast the rhs if neccesary. if (node.getLhs().getType() == Type.INTEGER && node.getRhs().getType() == Type.DECIMAL) { // Use de double tilde to do the casting. Single tilde is the NOT operator. JavaScript bitwise operators // cast their operands to signed 32-bits integer values. rhsScript = "~~" + rhsScript; } String script = parenthesize(node.getPrecedence(), node.getLhs().getPrecedence(), lhsScript) + "=" + parenthesize(node.getPrecedence(), node.getRhs().getPrecedence(), rhsScript); partStack.push(script); return null; } @Override public Void visit(BooleanNode node) throws VisitingException { if (node.getValue() == null) { partStack.push("null"); } else { partStack.push(node.getValue().booleanValue() ? "true" : "false"); } return null; } @Override public Void visit(DateNode node) throws VisitingException { // TODO: data (meervoud van datum) kunnen we nog niet parsen... partStack.push("new Date('TODO')"); return null; } @Override public Void visit(DivideNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "/"); return null; } @Override public Void visit(EqNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "=="); return null; } @Override public Void visit(FactorNode node) throws VisitingException { node.getArgument().accept(this); partStack.push("(" + partStack.pop() + ")"); return null; } @Override public Void visit(DecimalNode node) throws VisitingException { if (node.getValue() == null) { partStack.push("null"); } else { partStack.push(node.getValue().toString()); } return null; } @Override public Void visit(FunctionNode node) throws VisitingException { // Loop eerst over alle parameters heen, om de stack op te bouwen. for (Node childNode : node.getParameters()) { childNode.accept(this); } String arguments = ""; // Haal evenveel elementen van de stack als er zojuist bijgekomen zijn. for (int i = 0; i < node.getParameters().size(); i++) { arguments = partStack.pop() + (i != 0 ? "," : "") + arguments; } partStack.push(node.getIdentifier() + "(" + arguments + ")"); return null; } @Override public Void visit(GeqNode node) throws VisitingException { createScriptForBinaryOperationNode(node, ">="); return null; } @Override public Void visit(GtNode node) throws VisitingException { createScriptForBinaryOperationNode(node, ">"); return null; } @Override public Void visit(IfNode node) throws VisitingException { ExpressionTranslator conditionTranslator = new ExpressionTranslator(node.getCondition()); ExpressionTranslator ifBodyTranslator = new ExpressionTranslator(node.getIfBody()); ExpressionTranslator elseBodyTranslator = new ExpressionTranslator(node.getElseBody()); // Bouw javascript op die StringBuilder ifExpression = new StringBuilder(); ifExpression .append("var _").append(variableStack.size()).append(" = (function(){") .append(conditionTranslator.getDeclarations()) .append(conditionTranslator.getNullableCheck()) .append("if(").append(conditionTranslator.getExpression()).append("){") .append(ifBodyTranslator.getDeclarations()) .append(ifBodyTranslator.getNullableCheck()) .append("return ").append(ifBodyTranslator.getExpression()).append(";") .append("}else{") .append(elseBodyTranslator.getDeclarations()) .append(elseBodyTranslator.getNullableCheck()) .append("return ").append(elseBodyTranslator.getExpression()).append(";") .append("}") .append("})()"); declarationStack.push(ifExpression.toString()); String variable = "_" + variableStack.size(); partStack.push(variable); variableStack.push(variable); return null; } @Override public Void visit(IntegerNode node) throws VisitingException { if (node.getValue() == null) { partStack.push("null"); } else { partStack.push(node.getValue().toString()); } return null; } @Override public Void visit(LeqNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "<="); return null; } @Override public Void visit(LtNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "<"); return null; } @Override public Void visit(ModuloNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "%"); return null; } @Override public Void visit(MultiplyNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "*"); return null; } @Override public Void visit(NegativeNode node) throws VisitingException { node.getArgument().accept(this); partStack.push("-" + partStack.pop()); return null; } @Override public Void visit(NeqNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "!="); return null; } @Override public Void visit(NotNode node) throws VisitingException { node.getArgument().accept(this); partStack.push("!" + partStack.pop()); return null; } @Override public Void visit(NullNode node) throws VisitingException { partStack.push("null"); return null; } @Override public Void visit(OrNode node) throws VisitingException { ExpressionTranslator lhsExpression = new ExpressionTranslator(node.getLhs()); ExpressionTranslator rhsExpression = new ExpressionTranslator(node.getRhs()); // Bouw javascript op die StringBuilder translation = new StringBuilder(); translation .append("var _").append(variableStack.size()).append("=(function(){") .append("var _l=(function(){") .append(lhsExpression.getDeclarations()) .append(lhsExpression.getNullableCheck()) .append("return ").append(lhsExpression.getExpression()) .append("})();") .append("if(_l===true)return true;") .append("var _r=(function(){") .append(rhsExpression.getDeclarations()) .append(rhsExpression.getNullableCheck()) .append("return ").append(rhsExpression.getExpression()) .append("})();") .append("if(_r===true)return true;") .append("if(_l==null||_r==null)return null;") .append("return false;") .append("})()"); declarationStack.push(translation.toString()); String variable = "_" + variableStack.size(); partStack.push(variable); variableStack.push(variable); return null; } @Override public Void visit(PositiveNode node) throws VisitingException { node.getArgument().accept(this); partStack.push(partStack.pop()); return null; } @Override public Void visit(PowerNode node) throws VisitingException { node.getBase().accept(this); node.getPower().accept(this); String power = partStack.pop(); String base = partStack.pop(); partStack.push("Math.pow(" + base + ", " + power + ")"); return null; } @Override public Void visit(StatementListNode node) throws VisitingException { // Wanneer er 1 statement in de lijst zit hoeven we dit statement niet te bundelen in een closure. if (node.size() == 1) { // Haal het ene element op en zorg dat het op de stack terecht komt. node.get(0).accept(this); // Doe NIETS: stack.push(stack.pop()); return null; } // Er zitten meerdere statements in de lijst, bundel ze in een closure. String closure = "(function(){"; // Haal evenveel elementen van de stack als er zojuist bijgekomen zijn. for (int i = 0; i < node.size(); i++) { // Bewaar het aantal variabelen dat nu op de variabelen stack zit. int variableStackSize = variableStack.size(); // Zorg dat de JavaScript voor dit ene element op de stack komt. node.get(i).accept(this); // Wanneer dit niet het laatste statement is moeten we alle variabelen die nog op de stack zitten poppen om // te voorkomen dat we allerlei checks op null gaan doen. if (i < node.size() - 1) { for (int j = 0; j < variableStack.size() - variableStackSize; j++) { variableStack.pop(); } } // Zet voor het laatste statement 'return '. closure += (i == node.size() - 1 ? "return ": "") + partStack.pop() + ";"; } closure += "})()"; partStack.push(closure); return null; } @Override public Void visit(StringNode node) throws VisitingException { if (node.getValue() == null) { partStack.push("null"); } else { partStack.push("'" + node.getValue() + "'"); } return null; } @Override public Void visit(SubstractNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "-"); return null; } @Override public Void visit(VariableNode node) throws VisitingException { // Duw de identifier op de variabelen stack, doe dit zodat we hierover kunnen beschikken in een IfNode. Dit doen // we omdat JavaScript anders omgaat met NULL-waardes dan Abacus. variableStack.push(node.getIdentifier()); partStack.push(node.getIdentifier()); return null; } /** * Voegt indien nodig haakjes om het JavaScript stukje. * * @param parentNodePrecedence getal van volgorde van executie van de parent node. * @param childNodePrecedence getal van volgorde van executie van de child node. * @param part Het stukje JavaScript. * @return het JavaScript stukje met, indien nodig, haakjes eromheen. */ protected static String parenthesize(int parentNodePrecedence, int childNodePrecedence, String part) { // Wanneer deze node een lagere prio heeft dan de node onder hem moeten we haakjes toevoegen. if (parentNodePrecedence < childNodePrecedence) { part = "(" + part + ")"; } return part; } /** * Maakt JavaScript aan voor een node die een lhs en een rhs side heeft. * @param node De node die een binaire operatie voorstelt. * @param operator De JavaScript representatie van de operatie. * @throws VisitingException */ protected void createScriptForBinaryOperationNode(BinaryOperationNode node, String operator) throws VisitingException { node.getLhs().accept(this); node.getRhs().accept(this); String rhsScript = partStack.pop(); String lhsScript = partStack.pop(); String script = parenthesize(node.getPrecedence(), node.getLhs().getPrecedence(), lhsScript) + operator + parenthesize(node.getPrecedence(), node.getRhs().getPrecedence(), rhsScript); partStack.push(script); } /** * Inner klasse om een expressie te kunnen vertalen. (Let op: met expressie bedoel ik hier een onderdeel van een * if-statement, zie ook {@link org.gertje.abacus.parser.Parser#expression(Token)} .) */ private class ExpressionTranslator { /** StringBuilder om de declaraties in op te bouwen. */ StringBuilder declarations; /** StringBuilder om de nullable controle in op te bouwen. */ StringBuilder nullableCheck; /** String om de expressie in op te bouwen. */ String expression; /** * Maakt een nieuwe instantie aan. Vertaal de expressie en bouw nodige gedeelten op. * @throws VisitingException */ private ExpressionTranslator(Node node) throws VisitingException { declarations = new StringBuilder(); nullableCheck = new StringBuilder(); // Haal de grootte van de stapel met variabelen op, zodat we straks weten hoeveel we eraf moeten halen. int size = variableStack.size(); // Visit de node. node.accept(JavaScriptTranslator.this); expression = partStack.pop(); createNullableScript(size); // Loop over alle elementen in de ifStatementStack heen, om deze achter elkaar te plakken. while(!declarationStack.empty()) { declarations.append(declarationStack.pop()).append(";"); } } /** * Maakt het gedeelte waar gecontroleerd wordt of alle variabelen wel netjes gezet zijn. Dit doen we omdat * JavaScript anders met null-waarden omgaat dan Abacus. * * @param size De grootte van de variabelestack voordat de node waarvoor nullablescript aangemaakt moet worden * ge-visit was. */ protected void createNullableScript(int size) { // Wanneer de index tot waar we de stack moeten poppen kleiner of gelijk is aan de stackgrootte zijn we klaar. if (size >= variableStack.size()) { return; } // Open de if. nullableCheck.append("if("); // Loop over de variabelen heen die null kunnen zijn. while(variableStack.size() > size) { // Controleer of de variabele gelijk is aan null. nullableCheck.append(variableStack.pop()).append("==null"); // Wanneer dit niet de laatste in de stack is moeten we het 'of' teken erachter aan tonen. if (variableStack.size() != size) { nullableCheck.append("||"); } } // Sluit de if, wanneer aan de conditie voldaan wordt geven we null terug. nullableCheck.append(")return null;"); } public StringBuilder getDeclarations() { return declarations; } public StringBuilder getNullableCheck() { return nullableCheck; } public String getExpression() { return expression; } } }
gmulders/translator-javascript
src/main/java/org/gertje/abacus/translator/javascript/nodevisitors/JavaScriptTranslator.java
5,039
// Wanneer dit niet het laatste statement is moeten we alle variabelen die nog op de stack zitten poppen om
line_comment
nl
package org.gertje.abacus.translator.javascript.nodevisitors; import org.gertje.abacus.nodes.AddNode; import org.gertje.abacus.nodes.AndNode; import org.gertje.abacus.nodes.AssignmentNode; import org.gertje.abacus.nodes.BinaryOperationNode; import org.gertje.abacus.nodes.BooleanNode; import org.gertje.abacus.nodes.DateNode; import org.gertje.abacus.nodes.DecimalNode; import org.gertje.abacus.nodes.DivideNode; import org.gertje.abacus.nodes.EqNode; import org.gertje.abacus.nodes.FactorNode; import org.gertje.abacus.nodes.FunctionNode; import org.gertje.abacus.nodes.GeqNode; import org.gertje.abacus.nodes.GtNode; import org.gertje.abacus.nodes.IfNode; import org.gertje.abacus.nodes.IntegerNode; import org.gertje.abacus.nodes.LeqNode; import org.gertje.abacus.nodes.LtNode; import org.gertje.abacus.nodes.ModuloNode; import org.gertje.abacus.nodes.MultiplyNode; import org.gertje.abacus.nodes.NegativeNode; import org.gertje.abacus.nodes.NeqNode; import org.gertje.abacus.nodes.Node; import org.gertje.abacus.nodes.NotNode; import org.gertje.abacus.nodes.NullNode; import org.gertje.abacus.nodes.OrNode; import org.gertje.abacus.nodes.PositiveNode; import org.gertje.abacus.nodes.PowerNode; import org.gertje.abacus.nodes.StatementListNode; import org.gertje.abacus.nodes.StringNode; import org.gertje.abacus.nodes.SubstractNode; import org.gertje.abacus.nodes.VariableNode; import org.gertje.abacus.nodevisitors.AbstractNodeVisitor; import org.gertje.abacus.nodevisitors.VisitingException; import org.gertje.abacus.token.Token; import org.gertje.abacus.types.Type; import java.util.Stack; public class JavaScriptTranslator extends AbstractNodeVisitor<Void, VisitingException> { /** * Deze stack gebruiken we om gedeeltelijke vertalingen in op te slaan. */ protected Stack<String> partStack; /** * Deze stack gebruiken we om variabelen die we gebruiken binnen een ifNode op te slaan. Dit is nodig omdat * JavaScript anders met NULL waardes omgaat dan Abacus. */ protected Stack<String> variableStack; /** * Deze stack gebruiken we om afgeleide if-statements in op te slaan, dit is inclusief toekenning aan een variabele. */ protected Stack<String> declarationStack; /** * Constructor. */ public JavaScriptTranslator() { partStack = new Stack<String>(); variableStack = new Stack<String>(); declarationStack = new Stack<String>(); } public String translate(Node node) throws VisitingException { ExpressionTranslator expressionTranslator = new ExpressionTranslator(node); StringBuilder translation = new StringBuilder(); // Wrap de expressie in een closure. Wanneer er geen declaraties zijn en er zijn geen controles op null en de // node is een NodeList, dan is deze closure onnodig. Voorlopig laat ik dit wel zo. translation.append("(function(){") .append(expressionTranslator.getDeclarations()) .append(expressionTranslator.getNullableCheck()) .append("return ").append(expressionTranslator.getExpression()).append(";") .append("})()"); return translation.toString(); } @Override public Void visit(AddNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "+"); return null; } @Override public Void visit(AndNode node) throws VisitingException { ExpressionTranslator lhsExpression = new ExpressionTranslator(node.getLhs()); ExpressionTranslator rhsExpression = new ExpressionTranslator(node.getRhs()); // Bouw javascript op die StringBuilder translation = new StringBuilder(); translation .append("var _").append(variableStack.size()).append("=(function(){") .append("var _l=(function(){") .append(lhsExpression.getDeclarations()) .append(lhsExpression.getNullableCheck()) .append("return ").append(lhsExpression.getExpression()) .append("})();") .append("if(_l===false)return false;") .append("var _r=(function(){") .append(rhsExpression.getDeclarations()) .append(rhsExpression.getNullableCheck()) .append("return ").append(rhsExpression.getExpression()) .append("})();") .append("if(_r===false)return false;") .append("if(_l==null||_r==null)return null;") .append("return true;") .append("})()"); declarationStack.push(translation.toString()); String variable = "_" + variableStack.size(); partStack.push(variable); variableStack.push(variable); return null; } @Override public Void visit(AssignmentNode node) throws VisitingException { node.getLhs().accept(this); // Pop tussendoor even de assignee van de variabelestack om te voorkomen dat we controleren of de assignee niet // null is. Anders zou je zoiets krijgen: a = 3 --> (function(){if(a==null)return null;return a = 3;})() variableStack.pop(); node.getRhs().accept(this); String rhsScript = partStack.pop(); String lhsScript = partStack.pop(); // Cast the rhs if neccesary. if (node.getLhs().getType() == Type.INTEGER && node.getRhs().getType() == Type.DECIMAL) { // Use de double tilde to do the casting. Single tilde is the NOT operator. JavaScript bitwise operators // cast their operands to signed 32-bits integer values. rhsScript = "~~" + rhsScript; } String script = parenthesize(node.getPrecedence(), node.getLhs().getPrecedence(), lhsScript) + "=" + parenthesize(node.getPrecedence(), node.getRhs().getPrecedence(), rhsScript); partStack.push(script); return null; } @Override public Void visit(BooleanNode node) throws VisitingException { if (node.getValue() == null) { partStack.push("null"); } else { partStack.push(node.getValue().booleanValue() ? "true" : "false"); } return null; } @Override public Void visit(DateNode node) throws VisitingException { // TODO: data (meervoud van datum) kunnen we nog niet parsen... partStack.push("new Date('TODO')"); return null; } @Override public Void visit(DivideNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "/"); return null; } @Override public Void visit(EqNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "=="); return null; } @Override public Void visit(FactorNode node) throws VisitingException { node.getArgument().accept(this); partStack.push("(" + partStack.pop() + ")"); return null; } @Override public Void visit(DecimalNode node) throws VisitingException { if (node.getValue() == null) { partStack.push("null"); } else { partStack.push(node.getValue().toString()); } return null; } @Override public Void visit(FunctionNode node) throws VisitingException { // Loop eerst over alle parameters heen, om de stack op te bouwen. for (Node childNode : node.getParameters()) { childNode.accept(this); } String arguments = ""; // Haal evenveel elementen van de stack als er zojuist bijgekomen zijn. for (int i = 0; i < node.getParameters().size(); i++) { arguments = partStack.pop() + (i != 0 ? "," : "") + arguments; } partStack.push(node.getIdentifier() + "(" + arguments + ")"); return null; } @Override public Void visit(GeqNode node) throws VisitingException { createScriptForBinaryOperationNode(node, ">="); return null; } @Override public Void visit(GtNode node) throws VisitingException { createScriptForBinaryOperationNode(node, ">"); return null; } @Override public Void visit(IfNode node) throws VisitingException { ExpressionTranslator conditionTranslator = new ExpressionTranslator(node.getCondition()); ExpressionTranslator ifBodyTranslator = new ExpressionTranslator(node.getIfBody()); ExpressionTranslator elseBodyTranslator = new ExpressionTranslator(node.getElseBody()); // Bouw javascript op die StringBuilder ifExpression = new StringBuilder(); ifExpression .append("var _").append(variableStack.size()).append(" = (function(){") .append(conditionTranslator.getDeclarations()) .append(conditionTranslator.getNullableCheck()) .append("if(").append(conditionTranslator.getExpression()).append("){") .append(ifBodyTranslator.getDeclarations()) .append(ifBodyTranslator.getNullableCheck()) .append("return ").append(ifBodyTranslator.getExpression()).append(";") .append("}else{") .append(elseBodyTranslator.getDeclarations()) .append(elseBodyTranslator.getNullableCheck()) .append("return ").append(elseBodyTranslator.getExpression()).append(";") .append("}") .append("})()"); declarationStack.push(ifExpression.toString()); String variable = "_" + variableStack.size(); partStack.push(variable); variableStack.push(variable); return null; } @Override public Void visit(IntegerNode node) throws VisitingException { if (node.getValue() == null) { partStack.push("null"); } else { partStack.push(node.getValue().toString()); } return null; } @Override public Void visit(LeqNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "<="); return null; } @Override public Void visit(LtNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "<"); return null; } @Override public Void visit(ModuloNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "%"); return null; } @Override public Void visit(MultiplyNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "*"); return null; } @Override public Void visit(NegativeNode node) throws VisitingException { node.getArgument().accept(this); partStack.push("-" + partStack.pop()); return null; } @Override public Void visit(NeqNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "!="); return null; } @Override public Void visit(NotNode node) throws VisitingException { node.getArgument().accept(this); partStack.push("!" + partStack.pop()); return null; } @Override public Void visit(NullNode node) throws VisitingException { partStack.push("null"); return null; } @Override public Void visit(OrNode node) throws VisitingException { ExpressionTranslator lhsExpression = new ExpressionTranslator(node.getLhs()); ExpressionTranslator rhsExpression = new ExpressionTranslator(node.getRhs()); // Bouw javascript op die StringBuilder translation = new StringBuilder(); translation .append("var _").append(variableStack.size()).append("=(function(){") .append("var _l=(function(){") .append(lhsExpression.getDeclarations()) .append(lhsExpression.getNullableCheck()) .append("return ").append(lhsExpression.getExpression()) .append("})();") .append("if(_l===true)return true;") .append("var _r=(function(){") .append(rhsExpression.getDeclarations()) .append(rhsExpression.getNullableCheck()) .append("return ").append(rhsExpression.getExpression()) .append("})();") .append("if(_r===true)return true;") .append("if(_l==null||_r==null)return null;") .append("return false;") .append("})()"); declarationStack.push(translation.toString()); String variable = "_" + variableStack.size(); partStack.push(variable); variableStack.push(variable); return null; } @Override public Void visit(PositiveNode node) throws VisitingException { node.getArgument().accept(this); partStack.push(partStack.pop()); return null; } @Override public Void visit(PowerNode node) throws VisitingException { node.getBase().accept(this); node.getPower().accept(this); String power = partStack.pop(); String base = partStack.pop(); partStack.push("Math.pow(" + base + ", " + power + ")"); return null; } @Override public Void visit(StatementListNode node) throws VisitingException { // Wanneer er 1 statement in de lijst zit hoeven we dit statement niet te bundelen in een closure. if (node.size() == 1) { // Haal het ene element op en zorg dat het op de stack terecht komt. node.get(0).accept(this); // Doe NIETS: stack.push(stack.pop()); return null; } // Er zitten meerdere statements in de lijst, bundel ze in een closure. String closure = "(function(){"; // Haal evenveel elementen van de stack als er zojuist bijgekomen zijn. for (int i = 0; i < node.size(); i++) { // Bewaar het aantal variabelen dat nu op de variabelen stack zit. int variableStackSize = variableStack.size(); // Zorg dat de JavaScript voor dit ene element op de stack komt. node.get(i).accept(this); // Wanneer dit<SUF> // te voorkomen dat we allerlei checks op null gaan doen. if (i < node.size() - 1) { for (int j = 0; j < variableStack.size() - variableStackSize; j++) { variableStack.pop(); } } // Zet voor het laatste statement 'return '. closure += (i == node.size() - 1 ? "return ": "") + partStack.pop() + ";"; } closure += "})()"; partStack.push(closure); return null; } @Override public Void visit(StringNode node) throws VisitingException { if (node.getValue() == null) { partStack.push("null"); } else { partStack.push("'" + node.getValue() + "'"); } return null; } @Override public Void visit(SubstractNode node) throws VisitingException { createScriptForBinaryOperationNode(node, "-"); return null; } @Override public Void visit(VariableNode node) throws VisitingException { // Duw de identifier op de variabelen stack, doe dit zodat we hierover kunnen beschikken in een IfNode. Dit doen // we omdat JavaScript anders omgaat met NULL-waardes dan Abacus. variableStack.push(node.getIdentifier()); partStack.push(node.getIdentifier()); return null; } /** * Voegt indien nodig haakjes om het JavaScript stukje. * * @param parentNodePrecedence getal van volgorde van executie van de parent node. * @param childNodePrecedence getal van volgorde van executie van de child node. * @param part Het stukje JavaScript. * @return het JavaScript stukje met, indien nodig, haakjes eromheen. */ protected static String parenthesize(int parentNodePrecedence, int childNodePrecedence, String part) { // Wanneer deze node een lagere prio heeft dan de node onder hem moeten we haakjes toevoegen. if (parentNodePrecedence < childNodePrecedence) { part = "(" + part + ")"; } return part; } /** * Maakt JavaScript aan voor een node die een lhs en een rhs side heeft. * @param node De node die een binaire operatie voorstelt. * @param operator De JavaScript representatie van de operatie. * @throws VisitingException */ protected void createScriptForBinaryOperationNode(BinaryOperationNode node, String operator) throws VisitingException { node.getLhs().accept(this); node.getRhs().accept(this); String rhsScript = partStack.pop(); String lhsScript = partStack.pop(); String script = parenthesize(node.getPrecedence(), node.getLhs().getPrecedence(), lhsScript) + operator + parenthesize(node.getPrecedence(), node.getRhs().getPrecedence(), rhsScript); partStack.push(script); } /** * Inner klasse om een expressie te kunnen vertalen. (Let op: met expressie bedoel ik hier een onderdeel van een * if-statement, zie ook {@link org.gertje.abacus.parser.Parser#expression(Token)} .) */ private class ExpressionTranslator { /** StringBuilder om de declaraties in op te bouwen. */ StringBuilder declarations; /** StringBuilder om de nullable controle in op te bouwen. */ StringBuilder nullableCheck; /** String om de expressie in op te bouwen. */ String expression; /** * Maakt een nieuwe instantie aan. Vertaal de expressie en bouw nodige gedeelten op. * @throws VisitingException */ private ExpressionTranslator(Node node) throws VisitingException { declarations = new StringBuilder(); nullableCheck = new StringBuilder(); // Haal de grootte van de stapel met variabelen op, zodat we straks weten hoeveel we eraf moeten halen. int size = variableStack.size(); // Visit de node. node.accept(JavaScriptTranslator.this); expression = partStack.pop(); createNullableScript(size); // Loop over alle elementen in de ifStatementStack heen, om deze achter elkaar te plakken. while(!declarationStack.empty()) { declarations.append(declarationStack.pop()).append(";"); } } /** * Maakt het gedeelte waar gecontroleerd wordt of alle variabelen wel netjes gezet zijn. Dit doen we omdat * JavaScript anders met null-waarden omgaat dan Abacus. * * @param size De grootte van de variabelestack voordat de node waarvoor nullablescript aangemaakt moet worden * ge-visit was. */ protected void createNullableScript(int size) { // Wanneer de index tot waar we de stack moeten poppen kleiner of gelijk is aan de stackgrootte zijn we klaar. if (size >= variableStack.size()) { return; } // Open de if. nullableCheck.append("if("); // Loop over de variabelen heen die null kunnen zijn. while(variableStack.size() > size) { // Controleer of de variabele gelijk is aan null. nullableCheck.append(variableStack.pop()).append("==null"); // Wanneer dit niet de laatste in de stack is moeten we het 'of' teken erachter aan tonen. if (variableStack.size() != size) { nullableCheck.append("||"); } } // Sluit de if, wanneer aan de conditie voldaan wordt geven we null terug. nullableCheck.append(")return null;"); } public StringBuilder getDeclarations() { return declarations; } public StringBuilder getNullableCheck() { return nullableCheck; } public String getExpression() { return expression; } } }
64603_3
package be.intecBrussel.IceCreamShop.application; import be.intecBrussel.IceCreamShop.application.eatables.Eatable; import be.intecBrussel.IceCreamShop.application.eatables.Flavor; import be.intecBrussel.IceCreamShop.application.eatables.MagnumType; import be.intecBrussel.IceCreamShop.application.sellers.IceCreamSalon; import be.intecBrussel.IceCreamShop.application.sellers.IceCreamSeller; import be.intecBrussel.IceCreamShop.application.sellers.PriceList; import static be.intecBrussel.IceCreamShop.application.eatables.Flavor.*; public class IceCreamApp { public static void main(String[] args) { //Maak een PriceList instantie aan = OK PriceList salonPriceList = new PriceList(2.00, 3.00, 3.50); //Maak een IceCreamSalon instantie aan met behulp van de price list en steek deze in een //IceCreamSeller variabele. IceCreamSalon newIceCreamSalon = new IceCreamSalon(salonPriceList); IceCreamSeller iceCreamSellerVar = newIceCreamSalon; System.out.println(newIceCreamSalon); //Bestel enkele ijsjes (order methoden), steek deze in een array van Eatable = OK System.out.println("Now making orders ...\n"); Eatable[] myEatables = new Eatable[]{ newIceCreamSalon.orderCone(new Flavor[]{VANILLA,CHOCOLATE,PISTACHE,STRAWBERRY}), newIceCreamSalon.orderIceRocket(), newIceCreamSalon.orderCone(new Flavor[]{STRAWBERRY,PISTACHE,STRAWBERRY}), newIceCreamSalon.orderMagnum(MagnumType.MILKCHOCOLATE), newIceCreamSalon.orderMagnum(MagnumType.ALPINENUTS), newIceCreamSalon.orderMagnum(MagnumType.ROMANTICSTRAWBERRIES), newIceCreamSalon.orderMagnum(MagnumType.WHITECHOCOLATE) }; //Roep van deze ijsjes de eat methode aan = OK System.out.println("Now eating ..."); for (Eatable e:myEatables) { e.eat(); } //Aan het einde van je applicatie print je de profit af van de icecreamseller = OK System.out.println("\nTotal profit voor deze icecreamseller: "+iceCreamSellerVar.getProfit()); } }
Tesh-nician/NewIceCreamShopWithMaven
src/main/java/be/intecBrussel/IceCreamShop/application/IceCreamApp.java
589
//Roep van deze ijsjes de eat methode aan = OK
line_comment
nl
package be.intecBrussel.IceCreamShop.application; import be.intecBrussel.IceCreamShop.application.eatables.Eatable; import be.intecBrussel.IceCreamShop.application.eatables.Flavor; import be.intecBrussel.IceCreamShop.application.eatables.MagnumType; import be.intecBrussel.IceCreamShop.application.sellers.IceCreamSalon; import be.intecBrussel.IceCreamShop.application.sellers.IceCreamSeller; import be.intecBrussel.IceCreamShop.application.sellers.PriceList; import static be.intecBrussel.IceCreamShop.application.eatables.Flavor.*; public class IceCreamApp { public static void main(String[] args) { //Maak een PriceList instantie aan = OK PriceList salonPriceList = new PriceList(2.00, 3.00, 3.50); //Maak een IceCreamSalon instantie aan met behulp van de price list en steek deze in een //IceCreamSeller variabele. IceCreamSalon newIceCreamSalon = new IceCreamSalon(salonPriceList); IceCreamSeller iceCreamSellerVar = newIceCreamSalon; System.out.println(newIceCreamSalon); //Bestel enkele ijsjes (order methoden), steek deze in een array van Eatable = OK System.out.println("Now making orders ...\n"); Eatable[] myEatables = new Eatable[]{ newIceCreamSalon.orderCone(new Flavor[]{VANILLA,CHOCOLATE,PISTACHE,STRAWBERRY}), newIceCreamSalon.orderIceRocket(), newIceCreamSalon.orderCone(new Flavor[]{STRAWBERRY,PISTACHE,STRAWBERRY}), newIceCreamSalon.orderMagnum(MagnumType.MILKCHOCOLATE), newIceCreamSalon.orderMagnum(MagnumType.ALPINENUTS), newIceCreamSalon.orderMagnum(MagnumType.ROMANTICSTRAWBERRIES), newIceCreamSalon.orderMagnum(MagnumType.WHITECHOCOLATE) }; //Roep van<SUF> System.out.println("Now eating ..."); for (Eatable e:myEatables) { e.eat(); } //Aan het einde van je applicatie print je de profit af van de icecreamseller = OK System.out.println("\nTotal profit voor deze icecreamseller: "+iceCreamSellerVar.getProfit()); } }
165847_72
package com.cw.demo.fingerprint.gaa; //import android.annotation.SuppressLint; //import android.app.Activity; //import android.content.DialogInterface; //import android.hardware.usb.UsbDevice; //import android.hardware.usb.UsbManager; //import android.os.AsyncTask; //import android.os.Bundle; //import android.os.Handler; //import android.support.v7.app.AlertDialog; //import android.text.method.ScrollingMovementMethod; //import android.util.Log; //import android.view.KeyEvent; //import android.view.View; //import android.view.View.OnClickListener; //import android.view.WindowManager; //import android.widget.Button; //import android.widget.ImageView; //import android.widget.ProgressBar; //import android.widget.TextView; //import android.widget.Toast; // //import com.cw.demo.MyApplication; //import com.cw.demo.R; //import com.cw.fpgaasdk.GaaApiBHMDevice; //import com.cw.fpgaasdk.GaaApiBase; //import com.cw.fpgaasdk.GaaFingerFactory; //import com.cw.serialportsdk.USB.USBFingerManager; //import com.cw.serialportsdk.utils.DataUtils; //import com.fm.bio.ID_Fpr; // // //public class NewFpGAAActivity extends Activity implements OnClickListener { public class NewFpGAAActivity{ } // // private static final String TAG = "CwGAAActivity"; // ProgressBar bar; // ImageView fingerImage; // Button capture; // Button enroll; // Button enroll2; // Button search; // Button stop; // Button infos; // Button clear; // TextView msgText; // boolean globalControl = true; // // // public GAA_API mGaaApi; // public GaaApiBase mGaaApi; // // // @SuppressLint("HandlerLeak") // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // Log.i(TAG, "------------onCreate--------------"); // // setContentView(R.layout.fragment_capture_gaa); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // // initview(); // } // // // @Override // protected void onStart() { // super.onStart(); // Log.i(TAG, "------------onStart--------------"); // open(); // } // // @Override // protected void onResume() { // super.onResume(); // Log.i(TAG, "------------onResume--------------"); // // } // // @Override // protected void onRestart() { // super.onRestart(); // Log.i(TAG, "------------onRestart--------------"); // } // // @Override // protected void onStop() { // super.onStop(); // Log.i(TAG, "------------onStop--------------"); // // close(); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // Log.i(TAG, "------------onDestroy--------------"); // } // // public void initview() { // bar = findViewById(R.id.bar); // fingerImage = findViewById(R.id.fingerImage); // capture = findViewById(R.id.capture); // enroll = findViewById(R.id.enroll); // search = findViewById(R.id.search); // enroll2 = findViewById(R.id.enroll2); // stop = findViewById(R.id.stop); // infos = findViewById(R.id.infos); // clear = findViewById(R.id.clear); // msgText = findViewById(R.id.msg); // msgText.setMovementMethod(ScrollingMovementMethod.getInstance()); // // capture.setOnClickListener(this); // enroll.setOnClickListener(this); // search.setOnClickListener(this); // enroll2.setOnClickListener(this); // stop.setOnClickListener(this); // infos.setOnClickListener(this); // clear.setOnClickListener(this); // } // // private void open() { // MyApplication.getApp().showProgressDialog(this, getString(R.string.fp_usb_init)); // USBFingerManager.getInstance(this).openUSB(new USBFingerManager.OnUSBFingerListener() { // @Override // public void onOpenUSBFingerSuccess(String device, UsbManager usbManager, UsbDevice usbDevice) { // MyApplication.getApp().cancleProgressDialog(); // if (device.equals(GaaApiBase.ZiDevice)) { // //新固件 // mGaaApi = new GaaFingerFactory().createGAAFinger(GaaApiBase.ZiDevice,NewFpGAAActivity.this); // //// mGaaApi = new GAANewAPI(NewFpGAAActivity.this); // int ret = mGaaApi.openGAA(); // if (ret == GaaApiBase.LIVESCAN_SUCCESS) { // updateMsg("open device success 1"); // } else if (ret == GaaApiBase.LIVESCAN_NOTINIT) { // updateMsg("not init"); // } else if (ret == GaaApiBase.LIVESCAN_AUTH_FAILED) { // updateMsg("auth failed"); // } else { // updateMsg("unknown " + ret); // } // // } else if (device.equals(GaaApiBase.BHMDevice)) { // //旧固件 // mGaaApi = new GaaFingerFactory().createGAAFinger(GaaApiBase.BHMDevice,NewFpGAAActivity.this); // // //// mGaaApi = new GAAOldAPI(NewFpGAAActivity.this); // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // int ret = ((GaaApiBHMDevice)mGaaApi).openGAA(); // if (ret == GaaApiBase.LIVESCAN_SUCCESS) { // updateMsg("open device success 2"); // } else if (ret == GaaApiBase.LIVESCAN_NOTINIT) { // updateMsg("not init"); // } else if (ret == GaaApiBase.LIVESCAN_AUTH_FAILED) { // updateMsg("auth failed"); // } else { // String msg = mGaaApi.ErrorInfo(ret); // updateMsg("unknown " + ret); // updateMsg("msg =" + msg); // } // } // },1000); // } else { // updateMsg("开发包和指纹模块不一致! 请联系商务 " + device); //// Toast.makeText(NewFpGAAActivity.this, "device ="+device, Toast.LENGTH_SHORT).show(); // Toast.makeText(NewFpGAAActivity.this, "开发包和指纹模块不一致! 请联系商务", Toast.LENGTH_SHORT).show(); // } // } // // @Override // public void onOpenUSBFingerFailure(String error,int errorCode) { // Log.e(TAG, error); // MyApplication.getApp().cancleProgressDialog(); // Toast.makeText(NewFpGAAActivity.this, error, Toast.LENGTH_SHORT).show(); // } // }); // // } // // private void close() { // btnStatus(true); // globalControl = false; // updateMsg("设备已关闭"); // if (mGaaApi != null) { // mGaaApi.closeGAA(); // } // USBFingerManager.getInstance(this).closeUSB(); // } // // @Override // public void onClick(View v) { // switch (v.getId()) { // case R.id.capture: // globalControl = true; // btnStatus(false); // UpAsyncTask asyncTask_up = new UpAsyncTask(); // asyncTask_up.execute(1); // break; // case R.id.enroll: // btnStatus(false); // // globalControl = true; // ImputAsyncTask asyncTask = new ImputAsyncTask(); // asyncTask.execute(1); // break; // case R.id.enroll2: //// btnStatus(false); //// //// globalControl = true; //// ImputAsyncTask2 asyncTask2 = new ImputAsyncTask2(); //// asyncTask2.execute(1); // break; // case R.id.search: // btnStatus(false); // globalControl = true; // SearchAsyncTask asyncTask_search = new SearchAsyncTask(); // asyncTask_search.execute(1); // break; // case R.id.stop: // btnStatus(true); // globalControl = false; // fingerImage.setImageBitmap(null); // break; // // case R.id.infos: //// getInfos(); // break; // case R.id.clear: // updateMsg(null); // // if (GaaApiBase.LIVESCAN_SUCCESS != mGaaApi.PSEmpty()) { // updateMsg("清空指纹库失败"); // } // updateMsg("清空指纹库成功"); // break; // } // } // // /** // * 采集图片 // */ // @SuppressLint("StaticFieldLeak") // public class UpAsyncTask extends AsyncTask<Integer, String, Integer> { // // @Override // protected Integer doInBackground(Integer... params) { // int ret = 0; // while (true) { // // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() != GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // publishProgress("mGaaApi.PSGetImage():" + mGaaApi.PSGetImage()); // sleep(20); // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // // if (globalControl == false) { // return -1; // } // publishProgress("mGaaApi.PSGetImage():" + mGaaApi.PSGetImage()); // sleep(10); // } // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != ID_Fpr.LIVESCAN_SUCCESS) { // publishProgress("上传图像失败:" + ret); // continue; // } // publishProgress("OK"); // } // } // // // @Override // protected void onPreExecute() { // updateMsg("显示图片,请在传感器放上手指"); // return; // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // updateMsg(values[0]); // } // } // // /** // * 录入指纹 // */ // @SuppressLint("StaticFieldLeak") // public class ImputAsyncTask extends AsyncTask<Integer, String, Integer> { // int Progress = 0; // // @Override // protected Integer doInBackground(Integer... params) { // int cnt = 1; // int ret; // // while (true) { // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() != GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // // sleep(20); // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // sleep(10); // } // // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != GaaApiBase.LIVESCAN_SUCCESS) { // publishProgress("上传图像失败:" + ret); // continue; // } // publishProgress("OK"); // // byte[] mFeature = new byte[ID_Fpr.LIVESCAN_FEATURE_SIZE]; // int[] fingerId = new int[1]; // //生成模板 // if ((ret = mGaaApi.PSGenChar(mFeature, fingerId)) != GaaApiBase.LIVESCAN_SUCCESS) { // publishProgress("生成特征失败:" + ret); // continue; // } else { // publishProgress("updateProgress"); // } // // String s = DataUtils.bytesToHexString(mFeature); // publishProgress(s); // publishProgress("录入指纹成功,=====>ID:" + fingerId[0]); // return 0; // } // } // // @Override // protected void onPostExecute(Integer result) { // globalControl = false; // if (0 == result) { // bar.setProgress(100); // btnStatus(true); // } else { // bar.setProgress(0); // updateMsg("指纹录入失败,请重新录入"); // globalControl = false; // } // } // // @Override // protected void onPreExecute() { // updateMsg("录入指纹=>开始,请放上手指"); // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // if (values[0].equals("updateProgress")) { // Progress += 50; // bar.setProgress(Progress); // return; // } // updateMsg(values[0]); // } // } // // long time; // // /** // * 搜索指纹 // */ // @SuppressLint("StaticFieldLeak") // public class SearchAsyncTask extends AsyncTask<Integer, String, Integer> { // @Override // protected Integer doInBackground(Integer... params) { // int ret; // int[] fingerId = new int[1]; // while (true) { // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // sleep(20); // } // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != GaaApiBase.LIVESCAN_SUCCESS) { // continue; // } // publishProgress("OK"); // // byte[] mFeature = new byte[ID_Fpr.LIVESCAN_FEATURE_SIZE]; // if (mGaaApi.PSGenChar(mFeature) != GaaApiBase.LIVESCAN_SUCCESS) { // continue; // } // time = System.currentTimeMillis(); // // int code = mGaaApi.PSSearch(mFeature, fingerId); // if (GaaApiBase.LIVESCAN_SUCCESS != code) {//mGaaApi.PSSearch(mFeature, fingerId) // publishProgress("没有找到此指纹"); // publishProgress("code = "+code); // continue; // } // //// int[] fingerId1 = new int[3]; //// mGaaApi.newTime(mFeature, fingerId1); // // updateMsg("search time = " + (System.currentTimeMillis() - time)); // publishProgress("成功搜索到此指纹,ID===> 0 =" + fingerId[0]); //// publishProgress("成功搜索到此指纹,ID===> 0 =" + fingerId1[0]+",1 = "+fingerId1[1]+",2 = "+fingerId1[2]); // } // } // // // @Override // protected void onPreExecute() { // updateMsg("搜索指纹=>开始,请放上手指"); // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // updateMsg(values[0]); // } // } // // private void updateFingerImg(byte[] fpBmp) { // try { // updateMsg("updateFingerImg"); //// Bitmap bitmap = BitmapFactory.decodeByteArray(fpBmp, 0, fpBmp.length); //// fingerImage.setImageBitmap(bitmap); // fingerImage.setImageBitmap(mGaaApi.DataToBmp(fpBmp)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // // switch (keyCode) { // case KeyEvent.KEYCODE_BACK: // if (MyApplication.getApp().isShowingProgress()) // { // MyApplication.getApp().cancleProgressDialog(); // return true; // } // // Log.i(TAG, "点击了返回键"); // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle(R.string.general_tips); // builder.setMessage(R.string.general_exit); // // //设置确定按钮 // builder.setNegativeButton(R.string.general_yes, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // finish(); // } // }); // //设置取消按钮 // builder.setPositiveButton(R.string.general_no, null); // //显示提示框 // builder.show(); // break; // } // return super.onKeyDown(keyCode, event); // } // // public void updateMsg(final String msg) { // if (msg == null) { // msgText.setText(""); // msgText.scrollTo(0, 0); // return; // } // // runOnUiThread(new Runnable() { // @Override // public void run() { // //获取当前行数 // int lineCount = msgText.getLineCount(); // if (lineCount > 2000) { // //大于100行自动清零 // msgText.setText(""); // msgText.setText(msg); // } else { // //小于100行追加 // msgText.append("\n" + msg); // } // // //当前文本高度 // int scrollAmount = msgText.getLayout().getLineTop(msgText.getLineCount()) - msgText.getHeight(); // if (scrollAmount > 0) { // msgText.scrollTo(0, scrollAmount); // } else { // msgText.scrollTo(0, 0); // } //// int offset = lineCount * msgText.getLineHeight(); //// if (offset > msgText.getHeight()) { //// msgText.scrollTo(0, offset - msgText.getLineHeight()); //// txt_mmm.scrollTo(0, scrollAmount); //// } // } // }); // } // // private void btnStatus(boolean status) { // capture.setEnabled(status); // enroll.setEnabled(status); // search.setEnabled(status); // stop.setEnabled(!status); // infos.setEnabled(status); // clear.setEnabled(status); // bar.setProgress(0); // } // // /** // * 延时 // * // * @param time // */ // private void sleep(long time) { // try { // Thread.sleep(time); // } catch (Exception e) { // e.toString(); // } // } //}
CoreWise/CWDemo
app/src/main/java/com/cw/demo/fingerprint/gaa/NewFpGAAActivity.java
5,137
// int ret = 0;
line_comment
nl
package com.cw.demo.fingerprint.gaa; //import android.annotation.SuppressLint; //import android.app.Activity; //import android.content.DialogInterface; //import android.hardware.usb.UsbDevice; //import android.hardware.usb.UsbManager; //import android.os.AsyncTask; //import android.os.Bundle; //import android.os.Handler; //import android.support.v7.app.AlertDialog; //import android.text.method.ScrollingMovementMethod; //import android.util.Log; //import android.view.KeyEvent; //import android.view.View; //import android.view.View.OnClickListener; //import android.view.WindowManager; //import android.widget.Button; //import android.widget.ImageView; //import android.widget.ProgressBar; //import android.widget.TextView; //import android.widget.Toast; // //import com.cw.demo.MyApplication; //import com.cw.demo.R; //import com.cw.fpgaasdk.GaaApiBHMDevice; //import com.cw.fpgaasdk.GaaApiBase; //import com.cw.fpgaasdk.GaaFingerFactory; //import com.cw.serialportsdk.USB.USBFingerManager; //import com.cw.serialportsdk.utils.DataUtils; //import com.fm.bio.ID_Fpr; // // //public class NewFpGAAActivity extends Activity implements OnClickListener { public class NewFpGAAActivity{ } // // private static final String TAG = "CwGAAActivity"; // ProgressBar bar; // ImageView fingerImage; // Button capture; // Button enroll; // Button enroll2; // Button search; // Button stop; // Button infos; // Button clear; // TextView msgText; // boolean globalControl = true; // // // public GAA_API mGaaApi; // public GaaApiBase mGaaApi; // // // @SuppressLint("HandlerLeak") // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // Log.i(TAG, "------------onCreate--------------"); // // setContentView(R.layout.fragment_capture_gaa); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // // initview(); // } // // // @Override // protected void onStart() { // super.onStart(); // Log.i(TAG, "------------onStart--------------"); // open(); // } // // @Override // protected void onResume() { // super.onResume(); // Log.i(TAG, "------------onResume--------------"); // // } // // @Override // protected void onRestart() { // super.onRestart(); // Log.i(TAG, "------------onRestart--------------"); // } // // @Override // protected void onStop() { // super.onStop(); // Log.i(TAG, "------------onStop--------------"); // // close(); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // Log.i(TAG, "------------onDestroy--------------"); // } // // public void initview() { // bar = findViewById(R.id.bar); // fingerImage = findViewById(R.id.fingerImage); // capture = findViewById(R.id.capture); // enroll = findViewById(R.id.enroll); // search = findViewById(R.id.search); // enroll2 = findViewById(R.id.enroll2); // stop = findViewById(R.id.stop); // infos = findViewById(R.id.infos); // clear = findViewById(R.id.clear); // msgText = findViewById(R.id.msg); // msgText.setMovementMethod(ScrollingMovementMethod.getInstance()); // // capture.setOnClickListener(this); // enroll.setOnClickListener(this); // search.setOnClickListener(this); // enroll2.setOnClickListener(this); // stop.setOnClickListener(this); // infos.setOnClickListener(this); // clear.setOnClickListener(this); // } // // private void open() { // MyApplication.getApp().showProgressDialog(this, getString(R.string.fp_usb_init)); // USBFingerManager.getInstance(this).openUSB(new USBFingerManager.OnUSBFingerListener() { // @Override // public void onOpenUSBFingerSuccess(String device, UsbManager usbManager, UsbDevice usbDevice) { // MyApplication.getApp().cancleProgressDialog(); // if (device.equals(GaaApiBase.ZiDevice)) { // //新固件 // mGaaApi = new GaaFingerFactory().createGAAFinger(GaaApiBase.ZiDevice,NewFpGAAActivity.this); // //// mGaaApi = new GAANewAPI(NewFpGAAActivity.this); // int ret = mGaaApi.openGAA(); // if (ret == GaaApiBase.LIVESCAN_SUCCESS) { // updateMsg("open device success 1"); // } else if (ret == GaaApiBase.LIVESCAN_NOTINIT) { // updateMsg("not init"); // } else if (ret == GaaApiBase.LIVESCAN_AUTH_FAILED) { // updateMsg("auth failed"); // } else { // updateMsg("unknown " + ret); // } // // } else if (device.equals(GaaApiBase.BHMDevice)) { // //旧固件 // mGaaApi = new GaaFingerFactory().createGAAFinger(GaaApiBase.BHMDevice,NewFpGAAActivity.this); // // //// mGaaApi = new GAAOldAPI(NewFpGAAActivity.this); // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // int ret = ((GaaApiBHMDevice)mGaaApi).openGAA(); // if (ret == GaaApiBase.LIVESCAN_SUCCESS) { // updateMsg("open device success 2"); // } else if (ret == GaaApiBase.LIVESCAN_NOTINIT) { // updateMsg("not init"); // } else if (ret == GaaApiBase.LIVESCAN_AUTH_FAILED) { // updateMsg("auth failed"); // } else { // String msg = mGaaApi.ErrorInfo(ret); // updateMsg("unknown " + ret); // updateMsg("msg =" + msg); // } // } // },1000); // } else { // updateMsg("开发包和指纹模块不一致! 请联系商务 " + device); //// Toast.makeText(NewFpGAAActivity.this, "device ="+device, Toast.LENGTH_SHORT).show(); // Toast.makeText(NewFpGAAActivity.this, "开发包和指纹模块不一致! 请联系商务", Toast.LENGTH_SHORT).show(); // } // } // // @Override // public void onOpenUSBFingerFailure(String error,int errorCode) { // Log.e(TAG, error); // MyApplication.getApp().cancleProgressDialog(); // Toast.makeText(NewFpGAAActivity.this, error, Toast.LENGTH_SHORT).show(); // } // }); // // } // // private void close() { // btnStatus(true); // globalControl = false; // updateMsg("设备已关闭"); // if (mGaaApi != null) { // mGaaApi.closeGAA(); // } // USBFingerManager.getInstance(this).closeUSB(); // } // // @Override // public void onClick(View v) { // switch (v.getId()) { // case R.id.capture: // globalControl = true; // btnStatus(false); // UpAsyncTask asyncTask_up = new UpAsyncTask(); // asyncTask_up.execute(1); // break; // case R.id.enroll: // btnStatus(false); // // globalControl = true; // ImputAsyncTask asyncTask = new ImputAsyncTask(); // asyncTask.execute(1); // break; // case R.id.enroll2: //// btnStatus(false); //// //// globalControl = true; //// ImputAsyncTask2 asyncTask2 = new ImputAsyncTask2(); //// asyncTask2.execute(1); // break; // case R.id.search: // btnStatus(false); // globalControl = true; // SearchAsyncTask asyncTask_search = new SearchAsyncTask(); // asyncTask_search.execute(1); // break; // case R.id.stop: // btnStatus(true); // globalControl = false; // fingerImage.setImageBitmap(null); // break; // // case R.id.infos: //// getInfos(); // break; // case R.id.clear: // updateMsg(null); // // if (GaaApiBase.LIVESCAN_SUCCESS != mGaaApi.PSEmpty()) { // updateMsg("清空指纹库失败"); // } // updateMsg("清空指纹库成功"); // break; // } // } // // /** // * 采集图片 // */ // @SuppressLint("StaticFieldLeak") // public class UpAsyncTask extends AsyncTask<Integer, String, Integer> { // // @Override // protected Integer doInBackground(Integer... params) { // int ret<SUF> // while (true) { // // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() != GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // publishProgress("mGaaApi.PSGetImage():" + mGaaApi.PSGetImage()); // sleep(20); // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // // if (globalControl == false) { // return -1; // } // publishProgress("mGaaApi.PSGetImage():" + mGaaApi.PSGetImage()); // sleep(10); // } // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != ID_Fpr.LIVESCAN_SUCCESS) { // publishProgress("上传图像失败:" + ret); // continue; // } // publishProgress("OK"); // } // } // // // @Override // protected void onPreExecute() { // updateMsg("显示图片,请在传感器放上手指"); // return; // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // updateMsg(values[0]); // } // } // // /** // * 录入指纹 // */ // @SuppressLint("StaticFieldLeak") // public class ImputAsyncTask extends AsyncTask<Integer, String, Integer> { // int Progress = 0; // // @Override // protected Integer doInBackground(Integer... params) { // int cnt = 1; // int ret; // // while (true) { // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() != GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // // sleep(20); // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // sleep(10); // } // // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != GaaApiBase.LIVESCAN_SUCCESS) { // publishProgress("上传图像失败:" + ret); // continue; // } // publishProgress("OK"); // // byte[] mFeature = new byte[ID_Fpr.LIVESCAN_FEATURE_SIZE]; // int[] fingerId = new int[1]; // //生成模板 // if ((ret = mGaaApi.PSGenChar(mFeature, fingerId)) != GaaApiBase.LIVESCAN_SUCCESS) { // publishProgress("生成特征失败:" + ret); // continue; // } else { // publishProgress("updateProgress"); // } // // String s = DataUtils.bytesToHexString(mFeature); // publishProgress(s); // publishProgress("录入指纹成功,=====>ID:" + fingerId[0]); // return 0; // } // } // // @Override // protected void onPostExecute(Integer result) { // globalControl = false; // if (0 == result) { // bar.setProgress(100); // btnStatus(true); // } else { // bar.setProgress(0); // updateMsg("指纹录入失败,请重新录入"); // globalControl = false; // } // } // // @Override // protected void onPreExecute() { // updateMsg("录入指纹=>开始,请放上手指"); // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // if (values[0].equals("updateProgress")) { // Progress += 50; // bar.setProgress(Progress); // return; // } // updateMsg(values[0]); // } // } // // long time; // // /** // * 搜索指纹 // */ // @SuppressLint("StaticFieldLeak") // public class SearchAsyncTask extends AsyncTask<Integer, String, Integer> { // @Override // protected Integer doInBackground(Integer... params) { // int ret; // int[] fingerId = new int[1]; // while (true) { // if (globalControl == false) { // return -1; // } // while (mGaaApi.PSGetImage() == GaaApiBase.LIVESCAN_NO_FINGER) { // if (globalControl == false) { // return -1; // } // sleep(20); // } // if ((ret = mGaaApi.PSUpImage(mGaaApi.PS_FingerBuf)) != GaaApiBase.LIVESCAN_SUCCESS) { // continue; // } // publishProgress("OK"); // // byte[] mFeature = new byte[ID_Fpr.LIVESCAN_FEATURE_SIZE]; // if (mGaaApi.PSGenChar(mFeature) != GaaApiBase.LIVESCAN_SUCCESS) { // continue; // } // time = System.currentTimeMillis(); // // int code = mGaaApi.PSSearch(mFeature, fingerId); // if (GaaApiBase.LIVESCAN_SUCCESS != code) {//mGaaApi.PSSearch(mFeature, fingerId) // publishProgress("没有找到此指纹"); // publishProgress("code = "+code); // continue; // } // //// int[] fingerId1 = new int[3]; //// mGaaApi.newTime(mFeature, fingerId1); // // updateMsg("search time = " + (System.currentTimeMillis() - time)); // publishProgress("成功搜索到此指纹,ID===> 0 =" + fingerId[0]); //// publishProgress("成功搜索到此指纹,ID===> 0 =" + fingerId1[0]+",1 = "+fingerId1[1]+",2 = "+fingerId1[2]); // } // } // // // @Override // protected void onPreExecute() { // updateMsg("搜索指纹=>开始,请放上手指"); // } // // @Override // protected void onProgressUpdate(String... values) { // if (values[0].equals("OK")) { // updateFingerImg(mGaaApi.PS_FingerBuf); // return; // } // updateMsg(values[0]); // } // } // // private void updateFingerImg(byte[] fpBmp) { // try { // updateMsg("updateFingerImg"); //// Bitmap bitmap = BitmapFactory.decodeByteArray(fpBmp, 0, fpBmp.length); //// fingerImage.setImageBitmap(bitmap); // fingerImage.setImageBitmap(mGaaApi.DataToBmp(fpBmp)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // // switch (keyCode) { // case KeyEvent.KEYCODE_BACK: // if (MyApplication.getApp().isShowingProgress()) // { // MyApplication.getApp().cancleProgressDialog(); // return true; // } // // Log.i(TAG, "点击了返回键"); // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle(R.string.general_tips); // builder.setMessage(R.string.general_exit); // // //设置确定按钮 // builder.setNegativeButton(R.string.general_yes, new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // finish(); // } // }); // //设置取消按钮 // builder.setPositiveButton(R.string.general_no, null); // //显示提示框 // builder.show(); // break; // } // return super.onKeyDown(keyCode, event); // } // // public void updateMsg(final String msg) { // if (msg == null) { // msgText.setText(""); // msgText.scrollTo(0, 0); // return; // } // // runOnUiThread(new Runnable() { // @Override // public void run() { // //获取当前行数 // int lineCount = msgText.getLineCount(); // if (lineCount > 2000) { // //大于100行自动清零 // msgText.setText(""); // msgText.setText(msg); // } else { // //小于100行追加 // msgText.append("\n" + msg); // } // // //当前文本高度 // int scrollAmount = msgText.getLayout().getLineTop(msgText.getLineCount()) - msgText.getHeight(); // if (scrollAmount > 0) { // msgText.scrollTo(0, scrollAmount); // } else { // msgText.scrollTo(0, 0); // } //// int offset = lineCount * msgText.getLineHeight(); //// if (offset > msgText.getHeight()) { //// msgText.scrollTo(0, offset - msgText.getLineHeight()); //// txt_mmm.scrollTo(0, scrollAmount); //// } // } // }); // } // // private void btnStatus(boolean status) { // capture.setEnabled(status); // enroll.setEnabled(status); // search.setEnabled(status); // stop.setEnabled(!status); // infos.setEnabled(status); // clear.setEnabled(status); // bar.setProgress(0); // } // // /** // * 延时 // * // * @param time // */ // private void sleep(long time) { // try { // Thread.sleep(time); // } catch (Exception e) { // e.toString(); // } // } //}
28168_9
package org.thomasmore.oo3.course.resortui.facade; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.Stateless; import org.thomasmore.oo3.course.resortui.business.entity.BungalowEntity; import org.thomasmore.oo3.course.resortui.business.entity.CustomerEntity; import org.thomasmore.oo3.course.resortui.business.entity.ParkEntity; import org.thomasmore.oo3.course.resortui.business.entity.ReservationEntity; import org.thomasmore.oo3.course.resortui.controller.ScheduleController; import org.thomasmore.oo3.course.resortui.dao.BungalowDao; import org.thomasmore.oo3.course.resortui.dao.CustomerDao; import org.thomasmore.oo3.course.resortui.dao.ParkDao; import org.thomasmore.oo3.course.resortui.dao.ReservationDao; import org.thomasmore.oo3.course.resortui.model.ReservationListDetailDto; import org.thomasmore.oo3.course.resortui.model.ReservationPageDto; @Stateless public class ReservationFacade { @EJB private ScheduleController schedulecontroller; @EJB private ReservationDao reservationsDao; @EJB private BungalowDao bungalowsDao; @EJB private CustomerDao customersDao; @EJB private ParkDao parkDao; private final SimpleDateFormat dateDate = new SimpleDateFormat("dd/MM/yyyy"); @PostConstruct public void init() { schedulecontroller.LoadBungalowSchedule(); } public ReservationPageDto loadReservationOverviewPage(String editId, String deleteId) { ReservationPageDto dto = new ReservationPageDto(); if (editId != null) { ReservationEntity reservationEntity = reservationsDao.findById(editId); if (reservationEntity != null) { dto.getDetail().setId(reservationEntity.getId()); dto.getDetail().setBungalowName(reservationEntity.getBungalowName()); dto.getDetail().setCustomerName(reservationEntity.getCustomerName()); dto.getDetail().setEndDate(reservationEntity.getEndDate()); dto.getDetail().setEndDateFormatted(reservationEntity.getEndDateFormatted()); dto.getDetail().setEndTime(reservationEntity.getEndTime()); dto.getDetail().setParkName(reservationEntity.getParkName()); dto.getDetail().setStartDate(reservationEntity.getStartDate()); dto.getDetail().setStartDateFormatted(reservationEntity.getStartDateFormatted()); dto.getDetail().setStartTime(reservationEntity.getStartTime()); } schedulecontroller.LoadBungalowSchedule(); } if (deleteId != null) { reservationsDao.deleteById(deleteId); schedulecontroller.LoadBungalowSchedule(); } List<CustomerEntity> customers = customersDao.listAll(); for (CustomerEntity customer : customers) { dto.getCustomerList().add(customer.getFirstname() + " " + customer.getLastname()); } List<ParkEntity> parks = parkDao.listAll(); for (ParkEntity park : parks) { dto.getParkList().add(park.getName()); } List<BungalowEntity> bungalows = bungalowsDao.listAll(); for (BungalowEntity bungalow : bungalows) { dto.getBungalowList().add(bungalow.getName()); } List<ReservationEntity> reservations = reservationsDao.listAll(); for (ReservationEntity reservation : reservations) { ReservationListDetailDto listDetail = new ReservationListDetailDto(); listDetail.setId(reservation.getId()); listDetail.setBungalowName(reservation.getBungalowName()); listDetail.setCustomerName(reservation.getCustomerName()); // Datum formateren listDetail.setStartDateFormatted(schedulecontroller.DateAndTime(reservation.getStartDate(), reservation.getStartTime())); listDetail.setEndDateFormatted(schedulecontroller.DateAndTime(reservation.getEndDate(), reservation.getEndTime())); try { listDetail.setStartDate(schedulecontroller.parseDate(listDetail.getStartDateFormatted())); listDetail.setStartDate(schedulecontroller.parseDate(listDetail.getEndDateFormatted())); } catch (ParseException ex) { Logger.getLogger(EventFacade.class.getName()).log(Level.SEVERE, null, ex); } listDetail.setStartDate(reservation.getStartTime()); listDetail.setEndDate(reservation.getEndTime()); // Tot hier wordt datum geformateerd listDetail.setParkName(reservation.getParkName()); dto.getList().add(listDetail); } return dto; } public ReservationPageDto add(ReservationPageDto dto) { ReservationEntity reservationEntity = null; //als de id niet geset is kennen we hem 1 toe; if (dto.getDetail().getId() == null || dto.getDetail().getId().isEmpty()) { dto.getDetail().setId(UUID.randomUUID().toString()); } else { reservationEntity = reservationsDao.findById(dto.getDetail().getId()); } if (reservationEntity == null) { reservationEntity = new ReservationEntity(); } reservationEntity.setId(dto.getDetail().getId()); reservationEntity.setBungalowName(dto.getDetail().getBungalowName()); reservationEntity.setCustomerName(dto.getDetail().getCustomerName()); reservationEntity.setEndDate(dto.getDetail().getEndDate()); reservationEntity.setEndDateFormatted(dto.getDetail().getEndDateFormatted()); reservationEntity.setEndTime(dto.getDetail().getEndTime()); reservationEntity.setParkName(dto.getDetail().getParkName()); reservationEntity.setStartDate(dto.getDetail().getStartDate()); reservationEntity.setStartDateFormatted(dto.getDetail().getStartDateFormatted()); reservationEntity.setStartTime(dto.getDetail().getStartTime()); reservationsDao.save(reservationEntity); schedulecontroller.LoadBungalowSchedule(); return dto; } public String checkBooking(ReservationPageDto dto) { // Check of begintijd na eindtijd komt if (dto.getDetail().getStartDate().after(dto.getDetail().getEndDate())) { return "begindateAfterEnddate"; } // Check of begintijd voor vandaag komt if (dto.getDetail().getStartDate().before(schedulecontroller.yesterday())) { return "beginDateBeforeToday"; } // Dubbele boeking nagaan List<ReservationEntity> reservations = reservationsDao.listAll(); for (ReservationEntity res : reservations) { // Voeg datum en tijd samen Date reservationStartDate = res.getStartDate(); Date reservationEndDate = res.getEndDate(); Date dtoStartDate = dto.getDetail().getStartDate(); Date dtoEndDate = dto.getDetail().getEndDate(); System.out.println(reservationStartDate + ", " + reservationEndDate + ", " + dtoStartDate + ", " + dtoEndDate); // Checkt of datum en tijd tussen een reeds geboekte tijd ligt voor een bepaalde locatie // OPGELET! De !=null moet aanwezig zijn want anders wordt een nullpointer gegeven wanneer vergeleken wordt met een lege waarde if (// Nullpointers vermijden reservationStartDate != null && reservationEndDate != null && res.getBungalowName() != null && // Check of gekozen datum niet dezelfde datum is dan begin of einddatum (dtoStartDate.equals(reservationStartDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.equals(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoStartDate.equals(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.equals(reservationStartDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || // Als reservation tussen begin en einddatum ligt en Zelfde locatie heeft (dtoStartDate.before(reservationStartDate) && dtoEndDate.after(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || // Als begintijd = binnen range of eindtijd is binnen range (dtoStartDate.after(reservationStartDate) && dtoStartDate.before(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.after(reservationStartDate) && dtoEndDate.before(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName()))) { return "doubleBooking: <p>Locatie " + res.getBungalowName() + " is reeds volboekt van</p><p>" + res.getStartDateFormatted() + " tot " + res.getEndDateFormatted() + ".</p><p>Gelieve andere datum te selecteren.</p>"; } } add(dto); return ""; } }
EliasSerneels/Project1
ResortUI/src/main/java/org/thomasmore/oo3/course/resortui/facade/ReservationFacade.java
2,176
// Als reservation tussen begin en einddatum ligt en Zelfde locatie heeft
line_comment
nl
package org.thomasmore.oo3.course.resortui.facade; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.Stateless; import org.thomasmore.oo3.course.resortui.business.entity.BungalowEntity; import org.thomasmore.oo3.course.resortui.business.entity.CustomerEntity; import org.thomasmore.oo3.course.resortui.business.entity.ParkEntity; import org.thomasmore.oo3.course.resortui.business.entity.ReservationEntity; import org.thomasmore.oo3.course.resortui.controller.ScheduleController; import org.thomasmore.oo3.course.resortui.dao.BungalowDao; import org.thomasmore.oo3.course.resortui.dao.CustomerDao; import org.thomasmore.oo3.course.resortui.dao.ParkDao; import org.thomasmore.oo3.course.resortui.dao.ReservationDao; import org.thomasmore.oo3.course.resortui.model.ReservationListDetailDto; import org.thomasmore.oo3.course.resortui.model.ReservationPageDto; @Stateless public class ReservationFacade { @EJB private ScheduleController schedulecontroller; @EJB private ReservationDao reservationsDao; @EJB private BungalowDao bungalowsDao; @EJB private CustomerDao customersDao; @EJB private ParkDao parkDao; private final SimpleDateFormat dateDate = new SimpleDateFormat("dd/MM/yyyy"); @PostConstruct public void init() { schedulecontroller.LoadBungalowSchedule(); } public ReservationPageDto loadReservationOverviewPage(String editId, String deleteId) { ReservationPageDto dto = new ReservationPageDto(); if (editId != null) { ReservationEntity reservationEntity = reservationsDao.findById(editId); if (reservationEntity != null) { dto.getDetail().setId(reservationEntity.getId()); dto.getDetail().setBungalowName(reservationEntity.getBungalowName()); dto.getDetail().setCustomerName(reservationEntity.getCustomerName()); dto.getDetail().setEndDate(reservationEntity.getEndDate()); dto.getDetail().setEndDateFormatted(reservationEntity.getEndDateFormatted()); dto.getDetail().setEndTime(reservationEntity.getEndTime()); dto.getDetail().setParkName(reservationEntity.getParkName()); dto.getDetail().setStartDate(reservationEntity.getStartDate()); dto.getDetail().setStartDateFormatted(reservationEntity.getStartDateFormatted()); dto.getDetail().setStartTime(reservationEntity.getStartTime()); } schedulecontroller.LoadBungalowSchedule(); } if (deleteId != null) { reservationsDao.deleteById(deleteId); schedulecontroller.LoadBungalowSchedule(); } List<CustomerEntity> customers = customersDao.listAll(); for (CustomerEntity customer : customers) { dto.getCustomerList().add(customer.getFirstname() + " " + customer.getLastname()); } List<ParkEntity> parks = parkDao.listAll(); for (ParkEntity park : parks) { dto.getParkList().add(park.getName()); } List<BungalowEntity> bungalows = bungalowsDao.listAll(); for (BungalowEntity bungalow : bungalows) { dto.getBungalowList().add(bungalow.getName()); } List<ReservationEntity> reservations = reservationsDao.listAll(); for (ReservationEntity reservation : reservations) { ReservationListDetailDto listDetail = new ReservationListDetailDto(); listDetail.setId(reservation.getId()); listDetail.setBungalowName(reservation.getBungalowName()); listDetail.setCustomerName(reservation.getCustomerName()); // Datum formateren listDetail.setStartDateFormatted(schedulecontroller.DateAndTime(reservation.getStartDate(), reservation.getStartTime())); listDetail.setEndDateFormatted(schedulecontroller.DateAndTime(reservation.getEndDate(), reservation.getEndTime())); try { listDetail.setStartDate(schedulecontroller.parseDate(listDetail.getStartDateFormatted())); listDetail.setStartDate(schedulecontroller.parseDate(listDetail.getEndDateFormatted())); } catch (ParseException ex) { Logger.getLogger(EventFacade.class.getName()).log(Level.SEVERE, null, ex); } listDetail.setStartDate(reservation.getStartTime()); listDetail.setEndDate(reservation.getEndTime()); // Tot hier wordt datum geformateerd listDetail.setParkName(reservation.getParkName()); dto.getList().add(listDetail); } return dto; } public ReservationPageDto add(ReservationPageDto dto) { ReservationEntity reservationEntity = null; //als de id niet geset is kennen we hem 1 toe; if (dto.getDetail().getId() == null || dto.getDetail().getId().isEmpty()) { dto.getDetail().setId(UUID.randomUUID().toString()); } else { reservationEntity = reservationsDao.findById(dto.getDetail().getId()); } if (reservationEntity == null) { reservationEntity = new ReservationEntity(); } reservationEntity.setId(dto.getDetail().getId()); reservationEntity.setBungalowName(dto.getDetail().getBungalowName()); reservationEntity.setCustomerName(dto.getDetail().getCustomerName()); reservationEntity.setEndDate(dto.getDetail().getEndDate()); reservationEntity.setEndDateFormatted(dto.getDetail().getEndDateFormatted()); reservationEntity.setEndTime(dto.getDetail().getEndTime()); reservationEntity.setParkName(dto.getDetail().getParkName()); reservationEntity.setStartDate(dto.getDetail().getStartDate()); reservationEntity.setStartDateFormatted(dto.getDetail().getStartDateFormatted()); reservationEntity.setStartTime(dto.getDetail().getStartTime()); reservationsDao.save(reservationEntity); schedulecontroller.LoadBungalowSchedule(); return dto; } public String checkBooking(ReservationPageDto dto) { // Check of begintijd na eindtijd komt if (dto.getDetail().getStartDate().after(dto.getDetail().getEndDate())) { return "begindateAfterEnddate"; } // Check of begintijd voor vandaag komt if (dto.getDetail().getStartDate().before(schedulecontroller.yesterday())) { return "beginDateBeforeToday"; } // Dubbele boeking nagaan List<ReservationEntity> reservations = reservationsDao.listAll(); for (ReservationEntity res : reservations) { // Voeg datum en tijd samen Date reservationStartDate = res.getStartDate(); Date reservationEndDate = res.getEndDate(); Date dtoStartDate = dto.getDetail().getStartDate(); Date dtoEndDate = dto.getDetail().getEndDate(); System.out.println(reservationStartDate + ", " + reservationEndDate + ", " + dtoStartDate + ", " + dtoEndDate); // Checkt of datum en tijd tussen een reeds geboekte tijd ligt voor een bepaalde locatie // OPGELET! De !=null moet aanwezig zijn want anders wordt een nullpointer gegeven wanneer vergeleken wordt met een lege waarde if (// Nullpointers vermijden reservationStartDate != null && reservationEndDate != null && res.getBungalowName() != null && // Check of gekozen datum niet dezelfde datum is dan begin of einddatum (dtoStartDate.equals(reservationStartDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.equals(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoStartDate.equals(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.equals(reservationStartDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || // Als reservation<SUF> (dtoStartDate.before(reservationStartDate) && dtoEndDate.after(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || // Als begintijd = binnen range of eindtijd is binnen range (dtoStartDate.after(reservationStartDate) && dtoStartDate.before(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName())) || (dtoEndDate.after(reservationStartDate) && dtoEndDate.before(reservationEndDate) && dto.getDetail().getBungalowName().equals(res.getBungalowName()))) { return "doubleBooking: <p>Locatie " + res.getBungalowName() + " is reeds volboekt van</p><p>" + res.getStartDateFormatted() + " tot " + res.getEndDateFormatted() + ".</p><p>Gelieve andere datum te selecteren.</p>"; } } add(dto); return ""; } }
16294_16
package net.daansander.coder; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.java.JavaPlugin; import java.math.BigDecimal; /** * Created by Daan on 22-5-2015. */ /** * implements Listener is zodat bukkit weet dat hier evenementen afspelen */ public class Coder extends JavaPlugin implements Listener { /** * CoderDojo Cheat Sheat door Daan Meijer * @author Daan Meijer */ /** * int = een normaal nummer en kan maximaal 2^31-1 hebben. * double = een normaal nummer met decimalen zoals: 10.34531 * boolean = is een schakelaar het kan waar of niet waar zijn * long = is groot het kan een heel groot getal zijn zoals: 9349641242334513 * float = is een soort van double * byte = is erg klein * short = is een soort van byte maar dan groter * * public = open voor elke class * protected = alleen voor classes die het 'extenden' * private = is alleen voor de class zelf * static = is open voor iedereen * final = kan je niet veranderen * synchronized = heeft voorang op alle codes * * * new = maak een nieuwe instancie aan van een class * throw = gooi een error * abstract = methods die in de class moeten zitten * interface = volledig abstracte methods * */ public void onEnable() { //Hiermee kun je events registreren /** * this staat voor deze class */ Bukkit.getServer().getPluginManager().registerEvents(this , this); //Hier maken wij een 'Runnable aan' die om de seconde iets doet Bukkit.getServer().getScheduler().runTaskTimer(this, new Runnable() { @Override public void run() { //Hier gaat gebeuren dat op de server iedere 1 seconde de bericht "1 Seconde voorbij" wordt gebroadcast(gestuurd) Bukkit.broadcastMessage("1 Seconde voorbij"); } //Java werkt in 'ticks' 20 ticks zijn 1 seconde dus 10 ticks is een halve seconde },0, 20l); } //Hiermee wordt een event aangegeven @EventHandler //onPlayerJoin is de naam je kan er zelf wat voor verzinnen //PlayerJoinEvent is een van de vele evenementen ik neem deze als voorbeeld //Als je een beetje engels zie je Player dus de player Join dus met als de player het spel joind en Event en dan is dan het Event //Dus deze event wordt gecalled wanneer er een player joind public void onPlayerJoin(PlayerJoinEvent e) { //Hier kan je dingen in uit voeren als iemand joind } //Dit is voor een command @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { //Hier checken wij of de command maakt niet uit in hoofdletters of niet "command" is if(cmd.getName().equalsIgnoreCase("command")) { //Hier kunnen we dingen uitvoeren als de command "command wordt uitgevoerd" } return true; } }
CoderDojoRotterdam/minecraft-mod-workshop
src/me/daansander/coderdojo/Main.java
836
//Hier checken wij of de command maakt niet uit in hoofdletters of niet "command" is
line_comment
nl
package net.daansander.coder; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.java.JavaPlugin; import java.math.BigDecimal; /** * Created by Daan on 22-5-2015. */ /** * implements Listener is zodat bukkit weet dat hier evenementen afspelen */ public class Coder extends JavaPlugin implements Listener { /** * CoderDojo Cheat Sheat door Daan Meijer * @author Daan Meijer */ /** * int = een normaal nummer en kan maximaal 2^31-1 hebben. * double = een normaal nummer met decimalen zoals: 10.34531 * boolean = is een schakelaar het kan waar of niet waar zijn * long = is groot het kan een heel groot getal zijn zoals: 9349641242334513 * float = is een soort van double * byte = is erg klein * short = is een soort van byte maar dan groter * * public = open voor elke class * protected = alleen voor classes die het 'extenden' * private = is alleen voor de class zelf * static = is open voor iedereen * final = kan je niet veranderen * synchronized = heeft voorang op alle codes * * * new = maak een nieuwe instancie aan van een class * throw = gooi een error * abstract = methods die in de class moeten zitten * interface = volledig abstracte methods * */ public void onEnable() { //Hiermee kun je events registreren /** * this staat voor deze class */ Bukkit.getServer().getPluginManager().registerEvents(this , this); //Hier maken wij een 'Runnable aan' die om de seconde iets doet Bukkit.getServer().getScheduler().runTaskTimer(this, new Runnable() { @Override public void run() { //Hier gaat gebeuren dat op de server iedere 1 seconde de bericht "1 Seconde voorbij" wordt gebroadcast(gestuurd) Bukkit.broadcastMessage("1 Seconde voorbij"); } //Java werkt in 'ticks' 20 ticks zijn 1 seconde dus 10 ticks is een halve seconde },0, 20l); } //Hiermee wordt een event aangegeven @EventHandler //onPlayerJoin is de naam je kan er zelf wat voor verzinnen //PlayerJoinEvent is een van de vele evenementen ik neem deze als voorbeeld //Als je een beetje engels zie je Player dus de player Join dus met als de player het spel joind en Event en dan is dan het Event //Dus deze event wordt gecalled wanneer er een player joind public void onPlayerJoin(PlayerJoinEvent e) { //Hier kan je dingen in uit voeren als iemand joind } //Dit is voor een command @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { //Hier checken<SUF> if(cmd.getName().equalsIgnoreCase("command")) { //Hier kunnen we dingen uitvoeren als de command "command wordt uitgevoerd" } return true; } }
13738_9
/** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */ import java.awt.*; import java.awt.event.*; import java.awt.FlowLayout; import java.util.Scanner; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ static int lengte = 250; // (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ private Paard h1, h2, h3, h4, h5; // (2) Declareer hier h1, h2, h3, h4 van het type Paard // Deze paarden instantieer je later in het programma private JButton button; //(3) Declareer een button met de naam button van het type JButton private JPanel panel; private JLabel label1; /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); frame.setSize(420,250);/* (4) Geef het frame een breedte van 400 en hoogte van 150 */ frame.createGUI(); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. **/ h1 = new Paard("Toska", Color.black); h2 = new Paard("Moonshine",Color.cyan); h3 = new Paard("Amerigo", Color.pink); h4 = new Paard("Vlekje",Color.gray); h5 = new Paard("Bonnie", Color.green); /** Loop tot een paard over de finish is*/ while (h1.getAfstand() < lengte && h2.getAfstand() < lengte && h3.getAfstand() < lengte && h4.getAfstand() < lengte && h5.getAfstand() < lengte) { h1.run(); h2.run(); h3.run(); h4.run(); h5.run(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ pauzeer(100); g.setColor(Color.white); g.fillRect(0,0,300,200); g.setColor(Color.red);/* (5) Geef de finish streep een rode kleur */ g.fillRect(lengte+35, 0, 3, 200); tekenPaard(g,h1); tekenPaard(g,h2); tekenPaard(g,h3); tekenPaard(g,h4); tekenPaard(g,h5); } /** Kijk welk paard gewonnen heeft */ if (h1.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!"); } if (h2.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!"); } if (h3.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!"); } if (h4.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!"); } if (h5.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h5.getNaam() + " gewonnen!"); } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new JPanel(); panel.setPreferredSize(new Dimension(320, 200)); panel.setBackground(Color.white); window.add(panel); button = new JButton("Run!"); /* (9) Zet hier de tekst Run! op de button */ window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { Image image = Toolkit.getDefaultToolkit().getImage("./horse.jpg"); g.drawImage(image,h.getAfstand(),30*h.getPaardNummer(),this); //g.setColor(h.getKleur()); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace(paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } }
itbc-bin/1819-owe5a-afvinkopdracht3-MichelledeGroot
Race.java
1,700
/**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. **/
block_comment
nl
/** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */ import java.awt.*; import java.awt.event.*; import java.awt.FlowLayout; import java.util.Scanner; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ static int lengte = 250; // (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ private Paard h1, h2, h3, h4, h5; // (2) Declareer hier h1, h2, h3, h4 van het type Paard // Deze paarden instantieer je later in het programma private JButton button; //(3) Declareer een button met de naam button van het type JButton private JPanel panel; private JLabel label1; /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); frame.setSize(420,250);/* (4) Geef het frame een breedte van 400 en hoogte van 150 */ frame.createGUI(); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /**(6) Creatie van<SUF>*/ h1 = new Paard("Toska", Color.black); h2 = new Paard("Moonshine",Color.cyan); h3 = new Paard("Amerigo", Color.pink); h4 = new Paard("Vlekje",Color.gray); h5 = new Paard("Bonnie", Color.green); /** Loop tot een paard over de finish is*/ while (h1.getAfstand() < lengte && h2.getAfstand() < lengte && h3.getAfstand() < lengte && h4.getAfstand() < lengte && h5.getAfstand() < lengte) { h1.run(); h2.run(); h3.run(); h4.run(); h5.run(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ pauzeer(100); g.setColor(Color.white); g.fillRect(0,0,300,200); g.setColor(Color.red);/* (5) Geef de finish streep een rode kleur */ g.fillRect(lengte+35, 0, 3, 200); tekenPaard(g,h1); tekenPaard(g,h2); tekenPaard(g,h3); tekenPaard(g,h4); tekenPaard(g,h5); } /** Kijk welk paard gewonnen heeft */ if (h1.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!"); } if (h2.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!"); } if (h3.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!"); } if (h4.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!"); } if (h5.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h5.getNaam() + " gewonnen!"); } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new JPanel(); panel.setPreferredSize(new Dimension(320, 200)); panel.setBackground(Color.white); window.add(panel); button = new JButton("Run!"); /* (9) Zet hier de tekst Run! op de button */ window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { Image image = Toolkit.getDefaultToolkit().getImage("./horse.jpg"); g.drawImage(image,h.getAfstand(),30*h.getPaardNummer(),this); //g.setColor(h.getKleur()); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace(paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } }
156331_2
/* * Copyright (c) 2014, Netherlands Forensic Institute * All rights reserved. */ package nl.minvenj.nfi.common_source_identification; import java.awt.color.CMMException; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import javax.imageio.ImageIO; import nl.minvenj.nfi.common_source_identification.filter.FastNoiseFilter; import nl.minvenj.nfi.common_source_identification.filter.ImageFilter; import nl.minvenj.nfi.common_source_identification.filter.WienerFilter; import nl.minvenj.nfi.common_source_identification.filter.ZeroMeanTotalFilter; public final class CommonSourceIdentification { static final File TESTDATA_FOLDER = new File("testdata"); static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input"); // public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg"); public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG"); static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat"); static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output"); static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat"); public static void main(final String[] args) throws IOException { long start = System.currentTimeMillis(); long end = 0; // Laad de input file in final BufferedImage image = readImage(INPUT_FILE); end = System.currentTimeMillis(); System.out.println("Load image: " + (end-start) + " ms."); // Zet de input file om in 3 matrices (rood, groen, blauw) start = System.currentTimeMillis(); final float[][][] rgbArrays = convertImageToFloatArrays(image); end = System.currentTimeMillis(); System.out.println("Convert image:" + (end-start) + " ms."); // Bereken van elke matrix het PRNU patroon (extractie stap) start = System.currentTimeMillis(); for (int i = 0; i < 3; i++) { extractImage(rgbArrays[i]); } end = System.currentTimeMillis(); System.out.println("PRNU extracted: " + (end-start) + " ms."); // Schrijf het patroon weg als een Java object writeJavaObject(rgbArrays, OUTPUT_FILE); System.out.println("Pattern written"); // Controleer nu het gemaakte bestand final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE); final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE); for (int i = 0; i < 3; i++) { // Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)! compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f); } System.out.println("Validation completed"); //This exit is inserted because the program will otherwise hang for a about a minute //most likely explanation for this is the fact that the FFT library spawns a couple //of threads which cannot be properly destroyed System.exit(0); } private static BufferedImage readImage(final File file) throws IOException { final InputStream fileInputStream = new FileInputStream(file); try { final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream)); if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) { return image; } } catch (final CMMException e) { // Image file is unsupported or corrupt } catch (final RuntimeException e) { // Internal error processing image file } catch (final IOException e) { // Error reading image from disk } finally { fileInputStream.close(); } // Image unreadable or too smalld array return null; } private static float[][][] convertImageToFloatArrays(final BufferedImage image) { final int width = image.getWidth(); final int height = image.getHeight(); final float[][][] pixels = new float[3][height][width]; final ColorModel colorModel = ColorModel.getRGBdefault(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { final int pixel = image.getRGB(x, y); // aa bb gg rr pixels[0][y][x] = colorModel.getRed(pixel); pixels[1][y][x] = colorModel.getGreen(pixel); pixels[2][y][x] = colorModel.getBlue(pixel); } } return pixels; } private static void extractImage(final float[][] pixels) { final int width = pixels[0].length; final int height = pixels.length; long start = System.currentTimeMillis(); long end = 0; final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height); fastNoiseFilter.apply(pixels); end = System.currentTimeMillis(); System.out.println("Fast Noise Filter: " + (end-start) + " ms."); start = System.currentTimeMillis(); final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height); zeroMeanTotalFilter.apply(pixels); end = System.currentTimeMillis(); System.out.println("Zero Mean Filter: " + (end-start) + " ms."); start = System.currentTimeMillis(); final ImageFilter wienerFilter = new WienerFilter(width, height); wienerFilter.apply(pixels); end = System.currentTimeMillis(); System.out.println("Wiener Filter: " + (end-start) + " ms."); } public static Object readJavaObject(final File inputFile) throws IOException { final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile))); try { return inputStream.readObject(); } catch (final ClassNotFoundException e) { throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e); } finally { inputStream.close(); } } private static void writeJavaObject(final Object object, final File outputFile) throws IOException { final OutputStream outputStream = new FileOutputStream(outputFile); try { final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream)); objectOutputStream.writeObject(object); objectOutputStream.close(); } finally { outputStream.close(); } } private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) { for (int i = 0; i < expected.length; i++) { for (int j = 0; j < expected[i].length; j++) { if (Math.abs(actual[i][j] - expected[i][j]) > delta) { System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]); return false; } } } return true; } }
JungleComputing/common-source-identification-desktop
src/main/java/nl/minvenj/nfi/common_source_identification/CommonSourceIdentification.java
1,999
// Laad de input file in
line_comment
nl
/* * Copyright (c) 2014, Netherlands Forensic Institute * All rights reserved. */ package nl.minvenj.nfi.common_source_identification; import java.awt.color.CMMException; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import javax.imageio.ImageIO; import nl.minvenj.nfi.common_source_identification.filter.FastNoiseFilter; import nl.minvenj.nfi.common_source_identification.filter.ImageFilter; import nl.minvenj.nfi.common_source_identification.filter.WienerFilter; import nl.minvenj.nfi.common_source_identification.filter.ZeroMeanTotalFilter; public final class CommonSourceIdentification { static final File TESTDATA_FOLDER = new File("testdata"); static final File INPUT_FOLDER = new File(TESTDATA_FOLDER, "input"); // public static final File INPUT_FILE = new File(INPUT_FOLDER, "test.jpg"); public static final File INPUT_FILE = new File("/var/scratch/bwn200/Dresden/2748x3664/Kodak_M1063_4_12664.JPG"); static final File EXPECTED_PATTERN_FILE = new File(INPUT_FOLDER, "expected.pat"); static final File OUTPUT_FOLDER = new File(TESTDATA_FOLDER, "output"); static final File OUTPUT_FILE = new File(OUTPUT_FOLDER, "test.pat"); public static void main(final String[] args) throws IOException { long start = System.currentTimeMillis(); long end = 0; // Laad de<SUF> final BufferedImage image = readImage(INPUT_FILE); end = System.currentTimeMillis(); System.out.println("Load image: " + (end-start) + " ms."); // Zet de input file om in 3 matrices (rood, groen, blauw) start = System.currentTimeMillis(); final float[][][] rgbArrays = convertImageToFloatArrays(image); end = System.currentTimeMillis(); System.out.println("Convert image:" + (end-start) + " ms."); // Bereken van elke matrix het PRNU patroon (extractie stap) start = System.currentTimeMillis(); for (int i = 0; i < 3; i++) { extractImage(rgbArrays[i]); } end = System.currentTimeMillis(); System.out.println("PRNU extracted: " + (end-start) + " ms."); // Schrijf het patroon weg als een Java object writeJavaObject(rgbArrays, OUTPUT_FILE); System.out.println("Pattern written"); // Controleer nu het gemaakte bestand final float[][][] expectedPattern = (float[][][]) readJavaObject(EXPECTED_PATTERN_FILE); final float[][][] actualPattern = (float[][][]) readJavaObject(OUTPUT_FILE); for (int i = 0; i < 3; i++) { // Het patroon zoals dat uit PRNU Compare komt, bevat een extra matrix voor transparantie. Deze moeten we overslaan (+1)! compare2DArray(expectedPattern[i + 1], actualPattern[i], 0.0001f); } System.out.println("Validation completed"); //This exit is inserted because the program will otherwise hang for a about a minute //most likely explanation for this is the fact that the FFT library spawns a couple //of threads which cannot be properly destroyed System.exit(0); } private static BufferedImage readImage(final File file) throws IOException { final InputStream fileInputStream = new FileInputStream(file); try { final BufferedImage image = ImageIO.read(new BufferedInputStream(fileInputStream)); if ((image != null) && (image.getWidth() >= 0) && (image.getHeight() >= 0)) { return image; } } catch (final CMMException e) { // Image file is unsupported or corrupt } catch (final RuntimeException e) { // Internal error processing image file } catch (final IOException e) { // Error reading image from disk } finally { fileInputStream.close(); } // Image unreadable or too smalld array return null; } private static float[][][] convertImageToFloatArrays(final BufferedImage image) { final int width = image.getWidth(); final int height = image.getHeight(); final float[][][] pixels = new float[3][height][width]; final ColorModel colorModel = ColorModel.getRGBdefault(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { final int pixel = image.getRGB(x, y); // aa bb gg rr pixels[0][y][x] = colorModel.getRed(pixel); pixels[1][y][x] = colorModel.getGreen(pixel); pixels[2][y][x] = colorModel.getBlue(pixel); } } return pixels; } private static void extractImage(final float[][] pixels) { final int width = pixels[0].length; final int height = pixels.length; long start = System.currentTimeMillis(); long end = 0; final ImageFilter fastNoiseFilter = new FastNoiseFilter(width, height); fastNoiseFilter.apply(pixels); end = System.currentTimeMillis(); System.out.println("Fast Noise Filter: " + (end-start) + " ms."); start = System.currentTimeMillis(); final ImageFilter zeroMeanTotalFilter = new ZeroMeanTotalFilter(width, height); zeroMeanTotalFilter.apply(pixels); end = System.currentTimeMillis(); System.out.println("Zero Mean Filter: " + (end-start) + " ms."); start = System.currentTimeMillis(); final ImageFilter wienerFilter = new WienerFilter(width, height); wienerFilter.apply(pixels); end = System.currentTimeMillis(); System.out.println("Wiener Filter: " + (end-start) + " ms."); } public static Object readJavaObject(final File inputFile) throws IOException { final ObjectInputStream inputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFile))); try { return inputStream.readObject(); } catch (final ClassNotFoundException e) { throw new IOException("Cannot read pattern: " + inputFile.getAbsolutePath(), e); } finally { inputStream.close(); } } private static void writeJavaObject(final Object object, final File outputFile) throws IOException { final OutputStream outputStream = new FileOutputStream(outputFile); try { final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream)); objectOutputStream.writeObject(object); objectOutputStream.close(); } finally { outputStream.close(); } } private static boolean compare2DArray(final float[][] expected, final float[][] actual, final float delta) { for (int i = 0; i < expected.length; i++) { for (int j = 0; j < expected[i].length; j++) { if (Math.abs(actual[i][j] - expected[i][j]) > delta) { System.err.println("de waarde op " + i + "," + j + " is " + actual[i][j] + " maar had moeten zijn " + expected[i][j]); return false; } } } return true; } }
167440_13
package roborally.model; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; import be.kuleuven.cs.som.annotate.Basic; import be.kuleuven.cs.som.annotate.Immutable; import roborally.property.Position; import roborally.exception.IllegalPositionException; import roborally.filter.EnergyFilter; import roborally.filter.Filter; import roborally.filter.OrientationFilter; import roborally.filter.PositionFilter; import roborally.filter.WeightFilter; /** * Een klasse om een bord voor te stellen. * * @author Bavo Goosens (1e bachelor informatica, r0297884), Samuel Debruyn (1e bachelor informatica, r0305472) * * @invar Een bord moet ten alle tijden een geldige hoogte en breedte hebben. * |isValidHeight(getHeight()) * |isValidWidth(getWidth()) * * @version 1.1 */ public class Board{ /** * De breedte van het bord. */ private final long width; /** * De hoogte van het bord. */ private final long height; /** * Indien het object vernietigd is wordt dit true. */ private boolean isTerminated = false; /** * Deze HashMap houdt een lijst van HashSets bij per Position met in elke HashSet alle objecten op die plaats. */ protected final HashMap <Position, HashSet<Entity>> map; /** * De maximale breedte die een bord kan hebben. */ private static final long UPPER_BOUND_WIDTH = Long.MAX_VALUE; /** * De minimale breedte die een bord kan hebben. */ private static final long LOWER_BOUND_WIDTH = 0; /** * De maximale hoogte die een bord kan hebben. */ private static final long UPPER_BOUND_HEIGHT = Long.MAX_VALUE; /** * De minimale hoogte die een bord kan hebben. */ private static final long LOWER_BOUND_HEIGHT = 0; /** * Deze constructor maakt een nieuw bord aan. * * @pre ... * |isValidWidth(width) * * @pre ... * |isValidHeight(height) * * @param height * De hoogte van het nieuwe bord. * * @param width * De breedte van het nieuwe bord. * * @post Het bord heeft een map gekregen. * |new.map != null * * @post Het bord heeft een hoogte gekregen. * |new.getHeight() == height * * @post Het bord heeft een breedte gekregen. * |new.getWidth() == width */ public Board (long width , long height){ this.height = height; this.width = width; this.map = new HashMap<Position, HashSet<Entity>>(); } /** * Deze methode geeft alle objecten terug op een positie. * * @param pos * De positie waar gekeken moet worden. * * @return De HashSet met alle objecten op deze positie. * |map.get(pos) */ public HashSet<Entity> getEntityOnPosition(Position pos){ return map.get(pos); } /** * Deze methode verwijdert een object uit het bord. * * @param ent * De entity die verwijderd moet worden. * * @throws IllegalPositionException * Het object bevindt zich niet op een juiste positie in dit bord. * |ent.getBoard().isValidPosition(ent.getPosition()) * * @post De gegeven entity bevindt zich niet langer op een bord. * |new.getEntityOnPosition(ent.getPosition()) == null || new.map.containsKey(pos) == false */ public void removeEntity(Entity ent) throws IllegalPositionException{ Position pos = ent.getPosition(); if(!ent.getBoard().isValidPosition(pos)){ throw new IllegalPositionException(pos); } map.get(pos).remove(ent); cleanBoardPosition(pos); } /** * Deze methode kijkt na of het bord leeg is op deze positie, indien dat zo is wordt een mogelijke opgeslagen lege HashSet verwijderd. * * @param pos * De positie in het bord die moet nagekeken worden. * * @post De positie is leeg indien er geen objecten meer stonden. * |if(map.containsKey(pos) && !map.get(pos).isEmpty() && map.get(pos) != null) * | new.map.containsKey(pos) == false */ public void cleanBoardPosition(Position pos){ if(map.containsKey(pos)){ if(map.get(pos) == null){ map.remove(pos); }else if(map.get(pos).isEmpty()){ map.remove(pos); } } } /** * Deze methode kijkt na of een object op een plaats geplaatst kan worden. * * @param pos * De positie die moet nagekeken worden. * * @param entity * Het object waarvoor dit nagekeken moet worden. * * @return Boolean die true is als de positie niet door een muur of een robot ingenomen is. * |if(!isValidPosition(pos)) * | false * |if(getEntityOnPosition(pos) == null) * | true * |if(getEntityOnPosition(pos).isEmpty()) * | true * |Iterator<Entity> itr = place.iterator(); * |while(itr.hasNext()){ * | Entity ent = itr.next(); * | if (ent instanceof Wall) * | false * | if(ent instanceof Robot && entity instanceof Robot) * | false * |} * |true */ public boolean isPlacableOnPosition(Position pos, Entity entity){ if (!isValidPosition(pos)) return false; HashSet<Entity> place = getEntityOnPosition(pos); if(place == null) return true; if (place.isEmpty()) return true; Iterator<Entity> itr = place.iterator(); while(itr.hasNext()){ Entity ent = itr.next(); if (ent instanceof Wall) return false; if(ent instanceof Robot && entity instanceof Robot) return false; } return true; } /** * Deze methode plaatst een object op het bord. * * @param key * De positie waar het object geplaatst moet worden. * * @param entity * Het object dat op het bord geplaatst moet worden. * * @throws IllegalPositionException * De plaats in het bord is niet beschikbaar. * |!isPlacableOnPosition(key, entity) * * @post Als de positie op het bord beschikbaar was staat het object op deze positie. * |new.getEntityOnPosition.contains(entity) * */ public void putEntity(Position key, Entity entity) throws IllegalPositionException{ if (!isPlacableOnPosition(key, entity)) throw new IllegalPositionException(key); if(getEntityOnPosition(key) == null) map.put(key, new HashSet<Entity>()); getEntityOnPosition(key).add(entity); } /** * Deze methode geeft alle objecten van een bepaale klasse op het bord terug. * * @param type * De klasse waarvan objecten gezocht moeten worden. * * @return Een set met alle objecten van de gegeven klasse op het bord. * |Collection<HashSet<Entity>> coll = map.values(); * |Set<Entity> result = new HashSet<Entity>(); * |for(HashSet<Entity> place: coll){ * | Iterator<Entity> itr = place.iterator(); * | while(itr.hasNext()){ * | Entity current = itr.next(); * | if(current.getClass() == type) * | result.add(current); * | } * |} * |result */ public Set<Entity> getEntitiesOfType(Class type){ Collection<HashSet<Entity>> coll = map.values(); Set<Entity> result = new HashSet<Entity>(); for(HashSet<Entity> place: coll){ Iterator<Entity> itr = place.iterator(); while(itr.hasNext()){ Entity current = itr.next(); if(current.getClass() == type) result.add(current); } } return result; } /** * Deze inspector geeft een boolean die true is wanneer de hoogte toegestaan is en in het andere geval false. * * @param height * De hoogte die nagekeken moet worden. * * @return Boolean die true is wanneer de hoogte toegestaan is en in het andere geval false. * |(height > Board.LOWER_BOUND_HEIGHT) && (height < Board.UPPER_BOUND_HEIGHT) */ @Basic public static boolean isValidHeight(long height){ return (height > LOWER_BOUND_HEIGHT) && (height <= UPPER_BOUND_HEIGHT); } /** * Inspector om na te gaan of een gegeven breedte width een toegestane waarde is. * * @param width * De breedte die nagekeken moet worden. * * @return Boolean die true is wanneer de breedte toegestaan is en in het andere geval false. * |(width > Board.LOWER_BOUND_WIDTH) && (width < Board.UPPER_BOUND_WIDTH) */ @Basic public static boolean isValidWidth(long width){ return (width > LOWER_BOUND_WIDTH) && (width <= UPPER_BOUND_WIDTH); } /** * Inspector die de breedte van dit bord teruggeeft. * * @return De breedte van dit bord. * |width */ @Basic @Immutable public long getWidth() { return width; } /** * Inspector die de hoogte van dit bord teruggeeft. * * @return De hoogte van dit bord. * |height */ @Basic @Immutable public long getHeight() { return height; } /** * Deze methode kijkt na of een positie op het bord geldig is. * * @param position * De positie waarop nagekeken moet worden. * * @return Boolean die true is als de positie geldig is, false indien niet. * |if(position == null) * | false * |if (position.getX() > getWidth() || position.getX() < LOWER_BOUND_WIDTH || position.getY() > getHeight() || position.getY() < LOWER_BOUND_HEIGHT) * | false * |true */ public boolean isValidPosition(Position position){ if(position == null) return false; if (position.getX() > getWidth() || position.getX() < LOWER_BOUND_WIDTH || position.getY() > getHeight() || position.getY() < LOWER_BOUND_HEIGHT) return false; return true; } /** * Deze methode voegt 2 borden samen. Elementen uit het 2de bord die niet op dit bord geplaatst kunnen worden, worden getermineerd. * * @param board2 * Het bord dat moet samengevoegd worden met dit bord. * * @post Het 2de bord is getermineerd. * |(new board2).isTerminated() */ public void merge(Board board2) { Set<Position> keys2 = board2.map.keySet(); for(Position pos2: keys2){ if(this.isValidPosition(pos2)){ HashSet<Entity> ents2 = board2.getEntityOnPosition(pos2); for(Entity ent2: ents2){ if(isPlacableOnPosition(pos2, ent2)){ ent2.removeFromBoard(); ent2.putOnBoard(this, pos2); }else{ for(Position neighbour: pos2.getNeighbours(this)){ if(isPlacableOnPosition(neighbour, ent2)){ ent2.removeFromBoard(); ent2.putOnBoard(this, neighbour); break; } } } } } } board2.terminate(); } /** * Deze methode kijkt na of het bord getermineerd is of niet. * * @return Boolean die true is als het bord getermineerd is. * |isTerminated */ public boolean isTerminated(){ return isTerminated; } /** * Deze methode termineert het bord en alle objecten op het bord. * * @post Het bord is getermineerd. * |new.isTerminated() == true * * @post Het bord is leeg. * |new.map.values() == null */ public void terminate(){ Collection<HashSet<Entity>> c = map.values(); if(c != null){ for (HashSet<Entity> ents : c){ if(ents != null){ Position pos = ents.iterator().next().getPosition(); for (Entity ent : ents){ ent.destroy(); } cleanBoardPosition(pos); } } } isTerminated = true; } /** * Deze methode geeft een willekeurige positie terug die geldig is voor het bord van de robot. * * @param robot * De robot waarvoor een willekeurige positie moet teruggegeven worden. * * @return |Random rand = new Random(); * |Position teleport = new Position(nextLong(rand, robot.getBoard().getWidth()), nextLong(rand, robot.getBoard().getHeight())); * |if (robot.getBoard().isPlacableOnPosition(teleport, robot)) * | teleport * |getRandomPosition(robot) */ protected static Position getRandomPosition(Robot robot) { Random rand = new Random(); Position teleport = new Position(nextLong(rand, robot.getBoard().getWidth()), nextLong(rand, robot.getBoard().getHeight())); if (robot.getBoard().isPlacableOnPosition(teleport, robot)) return teleport; return getRandomPosition(robot); } /** * Deze methode geeft een willekeurige long terug op basis van een random en een bereik. * * @param rand * De random waarmee een willekeurige long gemaakt moet worden. * * @param n * De maximale waarde van het bereik waarin de long gegenereerd moet worden. * * @see java.util.Random#nextInt(int n) */ private static long nextLong(Random rand, long n) { long bits, val; do { bits = (rand.nextLong() << 1) >>> 1; val = bits % n; } while (bits-val+(n-1) < 0L); return val; } /** * Deze methode geeft een iterator terug met een bepaalde conditie (Filter). * * @param filter * Deze filter bepaalt de conditie voor de iterator. * * @return Een nieuwe iterator met alle objecten op het bord die voldoen aan de gegeven filter. */ public Iterator<Entity> getEntitiesWithFilter(Filter filter){ Collection<HashSet<Entity>> coll = map.values(); final Set<Entity> entities = new HashSet<Entity>(); for(HashSet<Entity> place: coll){ Iterator<Entity> itr = place.iterator(); while(itr.hasNext()){ Entity current = itr.next(); if(filter instanceof PositionFilter){ if(filter.evaluateObject(current.getPosition())) entities.add(current); } if(filter instanceof OrientationFilter && current instanceof Robot){ if(filter.evaluateObject(((Robot) current).getEnergy())) entities.add(current); } if(filter instanceof WeightFilter){ if(current instanceof Robot){ if(filter.evaluateObject(((Robot) current).getTotalWeight())) entities.add(current); } if(current instanceof Item){ if(filter.evaluateObject(((Item) current).getWeight())) entities.add(current); } } if(filter instanceof EnergyFilter){ if(current instanceof Robot){ if(filter.evaluateObject(((Robot) current).getEnergy())) entities.add(current); } if(current instanceof Battery){ if(filter.evaluateObject(((Battery) current).getEnergy())) entities.add(current); } if(current instanceof RepairKit){ if(filter.evaluateObject(((RepairKit) current).getEnergy())) entities.add(current); } } } } return new Iterator<Entity>(){ @Override public boolean hasNext() { return entItr.hasNext(); } @Override public Entity next() { last = entItr.next(); return last; } @Override public void remove() { last.removeFromBoard(); } private Iterator<Entity> entItr = entities.iterator(); private Entity last; }; } }
sdebruyn/student-Java-game-Roborally
src/roborally/model/Board.java
4,575
/** * Deze methode kijkt na of een object op een plaats geplaatst kan worden. * * @param pos * De positie die moet nagekeken worden. * * @param entity * Het object waarvoor dit nagekeken moet worden. * * @return Boolean die true is als de positie niet door een muur of een robot ingenomen is. * |if(!isValidPosition(pos)) * | false * |if(getEntityOnPosition(pos) == null) * | true * |if(getEntityOnPosition(pos).isEmpty()) * | true * |Iterator<Entity> itr = place.iterator(); * |while(itr.hasNext()){ * | Entity ent = itr.next(); * | if (ent instanceof Wall) * | false * | if(ent instanceof Robot && entity instanceof Robot) * | false * |} * |true */
block_comment
nl
package roborally.model; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; import be.kuleuven.cs.som.annotate.Basic; import be.kuleuven.cs.som.annotate.Immutable; import roborally.property.Position; import roborally.exception.IllegalPositionException; import roborally.filter.EnergyFilter; import roborally.filter.Filter; import roborally.filter.OrientationFilter; import roborally.filter.PositionFilter; import roborally.filter.WeightFilter; /** * Een klasse om een bord voor te stellen. * * @author Bavo Goosens (1e bachelor informatica, r0297884), Samuel Debruyn (1e bachelor informatica, r0305472) * * @invar Een bord moet ten alle tijden een geldige hoogte en breedte hebben. * |isValidHeight(getHeight()) * |isValidWidth(getWidth()) * * @version 1.1 */ public class Board{ /** * De breedte van het bord. */ private final long width; /** * De hoogte van het bord. */ private final long height; /** * Indien het object vernietigd is wordt dit true. */ private boolean isTerminated = false; /** * Deze HashMap houdt een lijst van HashSets bij per Position met in elke HashSet alle objecten op die plaats. */ protected final HashMap <Position, HashSet<Entity>> map; /** * De maximale breedte die een bord kan hebben. */ private static final long UPPER_BOUND_WIDTH = Long.MAX_VALUE; /** * De minimale breedte die een bord kan hebben. */ private static final long LOWER_BOUND_WIDTH = 0; /** * De maximale hoogte die een bord kan hebben. */ private static final long UPPER_BOUND_HEIGHT = Long.MAX_VALUE; /** * De minimale hoogte die een bord kan hebben. */ private static final long LOWER_BOUND_HEIGHT = 0; /** * Deze constructor maakt een nieuw bord aan. * * @pre ... * |isValidWidth(width) * * @pre ... * |isValidHeight(height) * * @param height * De hoogte van het nieuwe bord. * * @param width * De breedte van het nieuwe bord. * * @post Het bord heeft een map gekregen. * |new.map != null * * @post Het bord heeft een hoogte gekregen. * |new.getHeight() == height * * @post Het bord heeft een breedte gekregen. * |new.getWidth() == width */ public Board (long width , long height){ this.height = height; this.width = width; this.map = new HashMap<Position, HashSet<Entity>>(); } /** * Deze methode geeft alle objecten terug op een positie. * * @param pos * De positie waar gekeken moet worden. * * @return De HashSet met alle objecten op deze positie. * |map.get(pos) */ public HashSet<Entity> getEntityOnPosition(Position pos){ return map.get(pos); } /** * Deze methode verwijdert een object uit het bord. * * @param ent * De entity die verwijderd moet worden. * * @throws IllegalPositionException * Het object bevindt zich niet op een juiste positie in dit bord. * |ent.getBoard().isValidPosition(ent.getPosition()) * * @post De gegeven entity bevindt zich niet langer op een bord. * |new.getEntityOnPosition(ent.getPosition()) == null || new.map.containsKey(pos) == false */ public void removeEntity(Entity ent) throws IllegalPositionException{ Position pos = ent.getPosition(); if(!ent.getBoard().isValidPosition(pos)){ throw new IllegalPositionException(pos); } map.get(pos).remove(ent); cleanBoardPosition(pos); } /** * Deze methode kijkt na of het bord leeg is op deze positie, indien dat zo is wordt een mogelijke opgeslagen lege HashSet verwijderd. * * @param pos * De positie in het bord die moet nagekeken worden. * * @post De positie is leeg indien er geen objecten meer stonden. * |if(map.containsKey(pos) && !map.get(pos).isEmpty() && map.get(pos) != null) * | new.map.containsKey(pos) == false */ public void cleanBoardPosition(Position pos){ if(map.containsKey(pos)){ if(map.get(pos) == null){ map.remove(pos); }else if(map.get(pos).isEmpty()){ map.remove(pos); } } } /** * Deze methode kijkt<SUF>*/ public boolean isPlacableOnPosition(Position pos, Entity entity){ if (!isValidPosition(pos)) return false; HashSet<Entity> place = getEntityOnPosition(pos); if(place == null) return true; if (place.isEmpty()) return true; Iterator<Entity> itr = place.iterator(); while(itr.hasNext()){ Entity ent = itr.next(); if (ent instanceof Wall) return false; if(ent instanceof Robot && entity instanceof Robot) return false; } return true; } /** * Deze methode plaatst een object op het bord. * * @param key * De positie waar het object geplaatst moet worden. * * @param entity * Het object dat op het bord geplaatst moet worden. * * @throws IllegalPositionException * De plaats in het bord is niet beschikbaar. * |!isPlacableOnPosition(key, entity) * * @post Als de positie op het bord beschikbaar was staat het object op deze positie. * |new.getEntityOnPosition.contains(entity) * */ public void putEntity(Position key, Entity entity) throws IllegalPositionException{ if (!isPlacableOnPosition(key, entity)) throw new IllegalPositionException(key); if(getEntityOnPosition(key) == null) map.put(key, new HashSet<Entity>()); getEntityOnPosition(key).add(entity); } /** * Deze methode geeft alle objecten van een bepaale klasse op het bord terug. * * @param type * De klasse waarvan objecten gezocht moeten worden. * * @return Een set met alle objecten van de gegeven klasse op het bord. * |Collection<HashSet<Entity>> coll = map.values(); * |Set<Entity> result = new HashSet<Entity>(); * |for(HashSet<Entity> place: coll){ * | Iterator<Entity> itr = place.iterator(); * | while(itr.hasNext()){ * | Entity current = itr.next(); * | if(current.getClass() == type) * | result.add(current); * | } * |} * |result */ public Set<Entity> getEntitiesOfType(Class type){ Collection<HashSet<Entity>> coll = map.values(); Set<Entity> result = new HashSet<Entity>(); for(HashSet<Entity> place: coll){ Iterator<Entity> itr = place.iterator(); while(itr.hasNext()){ Entity current = itr.next(); if(current.getClass() == type) result.add(current); } } return result; } /** * Deze inspector geeft een boolean die true is wanneer de hoogte toegestaan is en in het andere geval false. * * @param height * De hoogte die nagekeken moet worden. * * @return Boolean die true is wanneer de hoogte toegestaan is en in het andere geval false. * |(height > Board.LOWER_BOUND_HEIGHT) && (height < Board.UPPER_BOUND_HEIGHT) */ @Basic public static boolean isValidHeight(long height){ return (height > LOWER_BOUND_HEIGHT) && (height <= UPPER_BOUND_HEIGHT); } /** * Inspector om na te gaan of een gegeven breedte width een toegestane waarde is. * * @param width * De breedte die nagekeken moet worden. * * @return Boolean die true is wanneer de breedte toegestaan is en in het andere geval false. * |(width > Board.LOWER_BOUND_WIDTH) && (width < Board.UPPER_BOUND_WIDTH) */ @Basic public static boolean isValidWidth(long width){ return (width > LOWER_BOUND_WIDTH) && (width <= UPPER_BOUND_WIDTH); } /** * Inspector die de breedte van dit bord teruggeeft. * * @return De breedte van dit bord. * |width */ @Basic @Immutable public long getWidth() { return width; } /** * Inspector die de hoogte van dit bord teruggeeft. * * @return De hoogte van dit bord. * |height */ @Basic @Immutable public long getHeight() { return height; } /** * Deze methode kijkt na of een positie op het bord geldig is. * * @param position * De positie waarop nagekeken moet worden. * * @return Boolean die true is als de positie geldig is, false indien niet. * |if(position == null) * | false * |if (position.getX() > getWidth() || position.getX() < LOWER_BOUND_WIDTH || position.getY() > getHeight() || position.getY() < LOWER_BOUND_HEIGHT) * | false * |true */ public boolean isValidPosition(Position position){ if(position == null) return false; if (position.getX() > getWidth() || position.getX() < LOWER_BOUND_WIDTH || position.getY() > getHeight() || position.getY() < LOWER_BOUND_HEIGHT) return false; return true; } /** * Deze methode voegt 2 borden samen. Elementen uit het 2de bord die niet op dit bord geplaatst kunnen worden, worden getermineerd. * * @param board2 * Het bord dat moet samengevoegd worden met dit bord. * * @post Het 2de bord is getermineerd. * |(new board2).isTerminated() */ public void merge(Board board2) { Set<Position> keys2 = board2.map.keySet(); for(Position pos2: keys2){ if(this.isValidPosition(pos2)){ HashSet<Entity> ents2 = board2.getEntityOnPosition(pos2); for(Entity ent2: ents2){ if(isPlacableOnPosition(pos2, ent2)){ ent2.removeFromBoard(); ent2.putOnBoard(this, pos2); }else{ for(Position neighbour: pos2.getNeighbours(this)){ if(isPlacableOnPosition(neighbour, ent2)){ ent2.removeFromBoard(); ent2.putOnBoard(this, neighbour); break; } } } } } } board2.terminate(); } /** * Deze methode kijkt na of het bord getermineerd is of niet. * * @return Boolean die true is als het bord getermineerd is. * |isTerminated */ public boolean isTerminated(){ return isTerminated; } /** * Deze methode termineert het bord en alle objecten op het bord. * * @post Het bord is getermineerd. * |new.isTerminated() == true * * @post Het bord is leeg. * |new.map.values() == null */ public void terminate(){ Collection<HashSet<Entity>> c = map.values(); if(c != null){ for (HashSet<Entity> ents : c){ if(ents != null){ Position pos = ents.iterator().next().getPosition(); for (Entity ent : ents){ ent.destroy(); } cleanBoardPosition(pos); } } } isTerminated = true; } /** * Deze methode geeft een willekeurige positie terug die geldig is voor het bord van de robot. * * @param robot * De robot waarvoor een willekeurige positie moet teruggegeven worden. * * @return |Random rand = new Random(); * |Position teleport = new Position(nextLong(rand, robot.getBoard().getWidth()), nextLong(rand, robot.getBoard().getHeight())); * |if (robot.getBoard().isPlacableOnPosition(teleport, robot)) * | teleport * |getRandomPosition(robot) */ protected static Position getRandomPosition(Robot robot) { Random rand = new Random(); Position teleport = new Position(nextLong(rand, robot.getBoard().getWidth()), nextLong(rand, robot.getBoard().getHeight())); if (robot.getBoard().isPlacableOnPosition(teleport, robot)) return teleport; return getRandomPosition(robot); } /** * Deze methode geeft een willekeurige long terug op basis van een random en een bereik. * * @param rand * De random waarmee een willekeurige long gemaakt moet worden. * * @param n * De maximale waarde van het bereik waarin de long gegenereerd moet worden. * * @see java.util.Random#nextInt(int n) */ private static long nextLong(Random rand, long n) { long bits, val; do { bits = (rand.nextLong() << 1) >>> 1; val = bits % n; } while (bits-val+(n-1) < 0L); return val; } /** * Deze methode geeft een iterator terug met een bepaalde conditie (Filter). * * @param filter * Deze filter bepaalt de conditie voor de iterator. * * @return Een nieuwe iterator met alle objecten op het bord die voldoen aan de gegeven filter. */ public Iterator<Entity> getEntitiesWithFilter(Filter filter){ Collection<HashSet<Entity>> coll = map.values(); final Set<Entity> entities = new HashSet<Entity>(); for(HashSet<Entity> place: coll){ Iterator<Entity> itr = place.iterator(); while(itr.hasNext()){ Entity current = itr.next(); if(filter instanceof PositionFilter){ if(filter.evaluateObject(current.getPosition())) entities.add(current); } if(filter instanceof OrientationFilter && current instanceof Robot){ if(filter.evaluateObject(((Robot) current).getEnergy())) entities.add(current); } if(filter instanceof WeightFilter){ if(current instanceof Robot){ if(filter.evaluateObject(((Robot) current).getTotalWeight())) entities.add(current); } if(current instanceof Item){ if(filter.evaluateObject(((Item) current).getWeight())) entities.add(current); } } if(filter instanceof EnergyFilter){ if(current instanceof Robot){ if(filter.evaluateObject(((Robot) current).getEnergy())) entities.add(current); } if(current instanceof Battery){ if(filter.evaluateObject(((Battery) current).getEnergy())) entities.add(current); } if(current instanceof RepairKit){ if(filter.evaluateObject(((RepairKit) current).getEnergy())) entities.add(current); } } } } return new Iterator<Entity>(){ @Override public boolean hasNext() { return entItr.hasNext(); } @Override public Entity next() { last = entItr.next(); return last; } @Override public void remove() { last.removeFromBoard(); } private Iterator<Entity> entItr = entities.iterator(); private Entity last; }; } }
92309_4
package lolstats.eldin.com.lolstats; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import com.robrua.orianna.api.core.RiotAPI; import com.robrua.orianna.api.dto.BaseRiotAPI; import com.robrua.orianna.type.core.common.Region; import com.robrua.orianna.type.dto.currentgame.Mastery; import com.robrua.orianna.type.dto.currentgame.Participant; import com.robrua.orianna.type.dto.currentgame.Rune; import com.robrua.orianna.type.dto.league.League; import com.robrua.orianna.type.dto.staticdata.BasicDataStats; import com.robrua.orianna.type.dto.staticdata.Champion; import com.robrua.orianna.type.dto.staticdata.ChampionList; import com.robrua.orianna.type.dto.staticdata.MasteryList; import com.robrua.orianna.type.dto.staticdata.RuneList; import com.robrua.orianna.type.dto.staticdata.SummonerSpellList; import com.robrua.orianna.type.dto.stats.ChampionStats; import com.robrua.orianna.type.dto.summoner.Summoner; import com.robrua.orianna.type.exception.APIException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Eldin on 18-5-2015. */ public class currentMatch extends AsyncTask<Void, Void, Void>{ static String sName; String userName; ArrayList<String> Summoners = new ArrayList<>(); ArrayList<String> Champpicks = new ArrayList<>(); ArrayList<String> Divs = new ArrayList<>(); ArrayList<Long> SummonerSpell1 = new ArrayList<>(); ArrayList<Long> SummonerSpell2 = new ArrayList<>(); ArrayList<String> SummonerKills = new ArrayList<>(); ArrayList<String> SummonerDeaths = new ArrayList<>(); ArrayList<String> SummonerAssists = new ArrayList<>(); Double blueKans; String[] sortedChamps; public boolean sFound; ProgressDialog p; Activity mActivity; int blueScore = 0; int redScore = 0; Activity o; public currentMatch(Activity activity){ mActivity = activity; } @Override protected void onPreExecute(){ p = ProgressDialog.show(mActivity, "Loading", "Retrieving and calculating data..", true); } @Override protected Void doInBackground(Void... params) { try { BaseRiotAPI.setMirror(Region.NA); BaseRiotAPI.setRegion(Region.NA); BaseRiotAPI.setAPIKey("ebe43318-cee4-4d2a-bf19-1c195a32aa93"); // Zoekt de summoner op stopt hem in een map Map<String, com.robrua.orianna.type.dto.summoner.Summoner> summoners = BaseRiotAPI.getSummonersByName(sName); // zorgt ervoor dat de key lowercase is en geen spaties meer bevat String lCase = sName.toLowerCase(); String sumName = lCase.replaceAll("\\s+", ""); // hier haalt die hem eruit met de key com.robrua.orianna.type.dto.summoner.Summoner summoner = summoners.get(sumName); // pakt de summoner id en naam userName = summoner.getName(); long sd = summoner.getId(); // doet de server request naar riot en haalt alle static data op van runes. RuneList runes = BaseRiotAPI.getRunes(); // stopt de runes in een lijst List<com.robrua.orianna.type.dto.staticdata.Rune> runess = new ArrayList<>(runes.getData().values()); // server call riot, static data masteries MasteryList masteryList = BaseRiotAPI.getMasteries(); // list mastery enzo List<com.robrua.orianna.type.dto.staticdata.Mastery> masteryArray = new ArrayList<>(masteryList.getData().values()); ChampionList champs = BaseRiotAPI.getChampions(); Champion testchampname = BaseRiotAPI.getChampion(89); String test = testchampname.getName(); List<Champion> champions = new ArrayList<>(champs.getData().values()); String[] nrOfChamps = new String[champions.size()]; Log.d("Test champid", champions.get(79).getName() + " " + nrOfChamps.length + "."); Log.d("Test title", champions.get(79).getTitle() + "."); Log.d("Test key", champions.get(79).getKey() + "."); Log.d("Test spell", champions.get(79).getSpells() + "."); for(int x = 0; x < nrOfChamps.length; x++){ nrOfChamps [x] = champions.get(x).getName(); if(x == nrOfChamps.length - 1){ Arrays.sort(nrOfChamps); sortedChamps = nrOfChamps; } } Log.d("Array sorted ", Arrays.toString(sortedChamps)); List<Participant> p = BaseRiotAPI.getCurrentGame(sd).getParticipants(); List<ChampionStats> r = BaseRiotAPI.getRankedStats(sd).getChampions(); for (int i = 0; i < p.size(); i++) { long b = 0; String pName = p.get(i).getSummonerName(); long champ = p.get(i).getChampionId(); long team = p.get(i).getTeamId(); b = champ; Champion champy = BaseRiotAPI.getChampion(b); String chosenchamp = champy.getName(); long pId = p.get(i).getSummonerId(); long sums1 = p.get(i).getSpell1Id(); long sums2 = p.get(i).getSpell2Id(); Summoners.add(pName); Champpicks.add(chosenchamp); SummonerSpell1.add(sums1); SummonerSpell2.add(sums2); int games = r.get(i).getStats().getTotalSessionsPlayed(); int kills = r.get(i).getStats().getTotalChampionKills(); int deaths = r.get(i).getStats().getTotalDeathsPerSession(); int assists = r.get(i).getStats().getTotalAssists(); String avgKills = kda(games, kills); String avgDeaths = kda(games, deaths); String avgAssists = kda(games, assists); SummonerKills.add(avgKills); SummonerDeaths.add(avgDeaths); SummonerAssists.add(avgAssists); String div = null; try { Map<Long, List<League>> league = BaseRiotAPI.getSummonerLeagueEntries(pId); div = league.get(pId).get(0).getTier() + " " + league.get(pId).get(0).getEntries().get(0).getDivision(); } catch (APIException e) { div = "unranked"; } Divs.add(div); if (team == 100) { blueScore += (int)getdMap(div); Log.d("Blue team", pName + " as " + chosenchamp + " " + div + " "+ sums1 + " " + sums2 + " " + getdMap(div) + blueScore + " " + games + " "+ avgKills + " "+ avgDeaths + " " + avgAssists); } else { Log.d("Red team", pName + " as " + chosenchamp + " " + div + " "+ sums1 + " " + sums2 + " " + getdMap(div) + redScore); redScore += (int)getdMap(div); } } blueKans = kans(blueScore, redScore); sFound = true; }catch (APIException e){ sFound = false; Log.d("apiex","apiex"); } catch (NullPointerException e){ sFound = false; Log.d("nullex","nullex"); } return null; } @Override protected void onPostExecute(Void unused){ p.dismiss(); if (sFound){ super.onPostExecute(unused); Intent intent = new Intent(mActivity, currentMatchPage.class); intent.putExtra("name", sName); intent.putStringArrayListExtra("SummonerNames", Summoners); intent.putStringArrayListExtra("Picks", Champpicks); intent.putStringArrayListExtra("Divisions", Divs); intent.putStringArrayListExtra("Kills", SummonerKills); intent.putStringArrayListExtra("Deaths", SummonerDeaths); intent.putStringArrayListExtra("Assists", SummonerAssists); intent.putExtra("blueKans", blueKans); intent.putExtra("Summoner1Div", Divs.get(0)); intent.putExtra("Summoner2Div",Divs.get(1)); intent.putExtra("Summoner3Div",Divs.get(2)); intent.putExtra("Summoner4Div",Divs.get(3)); intent.putExtra("Summoner5Div",Divs.get(4)); intent.putExtra("Summoner6Div",Divs.get(5)); intent.putExtra("Summoner7Div",Divs.get(6)); intent.putExtra("Summoner8Div",Divs.get(7)); intent.putExtra("Summoner9Div",Divs.get(8)); intent.putExtra("Summoner10Div",Divs.get(9)); intent.putExtra("Summoner1Spell1", SummonerSpell1.get(0)); intent.putExtra("Summoner1Spell2", SummonerSpell2.get(0)); intent.putExtra("Summoner2Spell1", SummonerSpell1.get(1)); intent.putExtra("Summoner2Spell2", SummonerSpell2.get(1)); intent.putExtra("Summoner3Spell1", SummonerSpell1.get(2)); intent.putExtra("Summoner3Spell2", SummonerSpell2.get(2)); intent.putExtra("Summoner4Spell1", SummonerSpell1.get(3)); intent.putExtra("Summoner4Spell2", SummonerSpell2.get(3)); intent.putExtra("Summoner5Spell1", SummonerSpell1.get(4)); intent.putExtra("Summoner5Spell2", SummonerSpell2.get(4)); intent.putExtra("Summoner6Spell1", SummonerSpell1.get(5)); intent.putExtra("Summoner6Spell2", SummonerSpell2.get(5)); intent.putExtra("Summoner7Spell1", SummonerSpell1.get(6)); intent.putExtra("Summoner7Spell2", SummonerSpell2.get(6)); intent.putExtra("Summoner8Spell1", SummonerSpell1.get(7)); intent.putExtra("Summoner8Spell2", SummonerSpell2.get(7)); intent.putExtra("Summoner9Spell1", SummonerSpell1.get(8)); intent.putExtra("Summoner9Spell2", SummonerSpell2.get(8)); intent.putExtra("Summoner10Spell1", SummonerSpell1.get(9)); intent.putExtra("Summoner10Spell2", SummonerSpell2.get(9)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mActivity.startActivity(intent); } else { AlertDialog.Builder builder1 = new AlertDialog.Builder(mActivity); builder1.setMessage("Summoner not in game."); builder1.setCancelable(true); builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); final AlertDialog alert11 = builder1.create(); alert11.show(); } } public Object getdMap(String div){ HashMap dMap = new HashMap<String, Integer>(); dMap.put("BRONZE V", 0); dMap.put("BRONZE IV", 1); dMap.put("BRONZE III", 2); dMap.put("BRONZE II", 3); dMap.put("BRONZE I", 4); dMap.put("SILVER V", 6); dMap.put("SILVER IV", 8); dMap.put("SILVER III", 10); dMap.put("SILVER II", 12); dMap.put("SILVER I", 14); dMap.put("GOLD V", 17); dMap.put("GOLD IV", 20); dMap.put("GOLD III", 23); dMap.put("GOLD II", 26); dMap.put("GOLD I", 29); dMap.put("PLATINUM V", 33); dMap.put("PLATINUM IV", 37); dMap.put("PLATINUM III", 41); dMap.put("PLATINUM II", 45); dMap.put("PLATINUM I", 49); dMap.put("DIAMOND V", 54); dMap.put("DIAMOND IV", 59); dMap.put("DIAMOND III", 64); dMap.put("DIAMOND II", 69); dMap.put("DIAMOND I", 74); dMap.put("MASTER I", 80); dMap.put("CHALLENGER 1", 90); dMap.put("unranked", 34); return dMap.get(div); } public double kans(int a, int b){ double diff; diff = a - b; diff = diff * 1.5; return 50 + diff; } public String kda(int games, int data){ String x; try{ x = data / games + ""; } catch (Exception e){ x = "0"; } return x; } }
Eldin61/LoLStats
app/src/main/java/lolstats/eldin/com/lolstats/currentMatch.java
3,583
// pakt de summoner id en naam
line_comment
nl
package lolstats.eldin.com.lolstats; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import com.robrua.orianna.api.core.RiotAPI; import com.robrua.orianna.api.dto.BaseRiotAPI; import com.robrua.orianna.type.core.common.Region; import com.robrua.orianna.type.dto.currentgame.Mastery; import com.robrua.orianna.type.dto.currentgame.Participant; import com.robrua.orianna.type.dto.currentgame.Rune; import com.robrua.orianna.type.dto.league.League; import com.robrua.orianna.type.dto.staticdata.BasicDataStats; import com.robrua.orianna.type.dto.staticdata.Champion; import com.robrua.orianna.type.dto.staticdata.ChampionList; import com.robrua.orianna.type.dto.staticdata.MasteryList; import com.robrua.orianna.type.dto.staticdata.RuneList; import com.robrua.orianna.type.dto.staticdata.SummonerSpellList; import com.robrua.orianna.type.dto.stats.ChampionStats; import com.robrua.orianna.type.dto.summoner.Summoner; import com.robrua.orianna.type.exception.APIException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Eldin on 18-5-2015. */ public class currentMatch extends AsyncTask<Void, Void, Void>{ static String sName; String userName; ArrayList<String> Summoners = new ArrayList<>(); ArrayList<String> Champpicks = new ArrayList<>(); ArrayList<String> Divs = new ArrayList<>(); ArrayList<Long> SummonerSpell1 = new ArrayList<>(); ArrayList<Long> SummonerSpell2 = new ArrayList<>(); ArrayList<String> SummonerKills = new ArrayList<>(); ArrayList<String> SummonerDeaths = new ArrayList<>(); ArrayList<String> SummonerAssists = new ArrayList<>(); Double blueKans; String[] sortedChamps; public boolean sFound; ProgressDialog p; Activity mActivity; int blueScore = 0; int redScore = 0; Activity o; public currentMatch(Activity activity){ mActivity = activity; } @Override protected void onPreExecute(){ p = ProgressDialog.show(mActivity, "Loading", "Retrieving and calculating data..", true); } @Override protected Void doInBackground(Void... params) { try { BaseRiotAPI.setMirror(Region.NA); BaseRiotAPI.setRegion(Region.NA); BaseRiotAPI.setAPIKey("ebe43318-cee4-4d2a-bf19-1c195a32aa93"); // Zoekt de summoner op stopt hem in een map Map<String, com.robrua.orianna.type.dto.summoner.Summoner> summoners = BaseRiotAPI.getSummonersByName(sName); // zorgt ervoor dat de key lowercase is en geen spaties meer bevat String lCase = sName.toLowerCase(); String sumName = lCase.replaceAll("\\s+", ""); // hier haalt die hem eruit met de key com.robrua.orianna.type.dto.summoner.Summoner summoner = summoners.get(sumName); // pakt de<SUF> userName = summoner.getName(); long sd = summoner.getId(); // doet de server request naar riot en haalt alle static data op van runes. RuneList runes = BaseRiotAPI.getRunes(); // stopt de runes in een lijst List<com.robrua.orianna.type.dto.staticdata.Rune> runess = new ArrayList<>(runes.getData().values()); // server call riot, static data masteries MasteryList masteryList = BaseRiotAPI.getMasteries(); // list mastery enzo List<com.robrua.orianna.type.dto.staticdata.Mastery> masteryArray = new ArrayList<>(masteryList.getData().values()); ChampionList champs = BaseRiotAPI.getChampions(); Champion testchampname = BaseRiotAPI.getChampion(89); String test = testchampname.getName(); List<Champion> champions = new ArrayList<>(champs.getData().values()); String[] nrOfChamps = new String[champions.size()]; Log.d("Test champid", champions.get(79).getName() + " " + nrOfChamps.length + "."); Log.d("Test title", champions.get(79).getTitle() + "."); Log.d("Test key", champions.get(79).getKey() + "."); Log.d("Test spell", champions.get(79).getSpells() + "."); for(int x = 0; x < nrOfChamps.length; x++){ nrOfChamps [x] = champions.get(x).getName(); if(x == nrOfChamps.length - 1){ Arrays.sort(nrOfChamps); sortedChamps = nrOfChamps; } } Log.d("Array sorted ", Arrays.toString(sortedChamps)); List<Participant> p = BaseRiotAPI.getCurrentGame(sd).getParticipants(); List<ChampionStats> r = BaseRiotAPI.getRankedStats(sd).getChampions(); for (int i = 0; i < p.size(); i++) { long b = 0; String pName = p.get(i).getSummonerName(); long champ = p.get(i).getChampionId(); long team = p.get(i).getTeamId(); b = champ; Champion champy = BaseRiotAPI.getChampion(b); String chosenchamp = champy.getName(); long pId = p.get(i).getSummonerId(); long sums1 = p.get(i).getSpell1Id(); long sums2 = p.get(i).getSpell2Id(); Summoners.add(pName); Champpicks.add(chosenchamp); SummonerSpell1.add(sums1); SummonerSpell2.add(sums2); int games = r.get(i).getStats().getTotalSessionsPlayed(); int kills = r.get(i).getStats().getTotalChampionKills(); int deaths = r.get(i).getStats().getTotalDeathsPerSession(); int assists = r.get(i).getStats().getTotalAssists(); String avgKills = kda(games, kills); String avgDeaths = kda(games, deaths); String avgAssists = kda(games, assists); SummonerKills.add(avgKills); SummonerDeaths.add(avgDeaths); SummonerAssists.add(avgAssists); String div = null; try { Map<Long, List<League>> league = BaseRiotAPI.getSummonerLeagueEntries(pId); div = league.get(pId).get(0).getTier() + " " + league.get(pId).get(0).getEntries().get(0).getDivision(); } catch (APIException e) { div = "unranked"; } Divs.add(div); if (team == 100) { blueScore += (int)getdMap(div); Log.d("Blue team", pName + " as " + chosenchamp + " " + div + " "+ sums1 + " " + sums2 + " " + getdMap(div) + blueScore + " " + games + " "+ avgKills + " "+ avgDeaths + " " + avgAssists); } else { Log.d("Red team", pName + " as " + chosenchamp + " " + div + " "+ sums1 + " " + sums2 + " " + getdMap(div) + redScore); redScore += (int)getdMap(div); } } blueKans = kans(blueScore, redScore); sFound = true; }catch (APIException e){ sFound = false; Log.d("apiex","apiex"); } catch (NullPointerException e){ sFound = false; Log.d("nullex","nullex"); } return null; } @Override protected void onPostExecute(Void unused){ p.dismiss(); if (sFound){ super.onPostExecute(unused); Intent intent = new Intent(mActivity, currentMatchPage.class); intent.putExtra("name", sName); intent.putStringArrayListExtra("SummonerNames", Summoners); intent.putStringArrayListExtra("Picks", Champpicks); intent.putStringArrayListExtra("Divisions", Divs); intent.putStringArrayListExtra("Kills", SummonerKills); intent.putStringArrayListExtra("Deaths", SummonerDeaths); intent.putStringArrayListExtra("Assists", SummonerAssists); intent.putExtra("blueKans", blueKans); intent.putExtra("Summoner1Div", Divs.get(0)); intent.putExtra("Summoner2Div",Divs.get(1)); intent.putExtra("Summoner3Div",Divs.get(2)); intent.putExtra("Summoner4Div",Divs.get(3)); intent.putExtra("Summoner5Div",Divs.get(4)); intent.putExtra("Summoner6Div",Divs.get(5)); intent.putExtra("Summoner7Div",Divs.get(6)); intent.putExtra("Summoner8Div",Divs.get(7)); intent.putExtra("Summoner9Div",Divs.get(8)); intent.putExtra("Summoner10Div",Divs.get(9)); intent.putExtra("Summoner1Spell1", SummonerSpell1.get(0)); intent.putExtra("Summoner1Spell2", SummonerSpell2.get(0)); intent.putExtra("Summoner2Spell1", SummonerSpell1.get(1)); intent.putExtra("Summoner2Spell2", SummonerSpell2.get(1)); intent.putExtra("Summoner3Spell1", SummonerSpell1.get(2)); intent.putExtra("Summoner3Spell2", SummonerSpell2.get(2)); intent.putExtra("Summoner4Spell1", SummonerSpell1.get(3)); intent.putExtra("Summoner4Spell2", SummonerSpell2.get(3)); intent.putExtra("Summoner5Spell1", SummonerSpell1.get(4)); intent.putExtra("Summoner5Spell2", SummonerSpell2.get(4)); intent.putExtra("Summoner6Spell1", SummonerSpell1.get(5)); intent.putExtra("Summoner6Spell2", SummonerSpell2.get(5)); intent.putExtra("Summoner7Spell1", SummonerSpell1.get(6)); intent.putExtra("Summoner7Spell2", SummonerSpell2.get(6)); intent.putExtra("Summoner8Spell1", SummonerSpell1.get(7)); intent.putExtra("Summoner8Spell2", SummonerSpell2.get(7)); intent.putExtra("Summoner9Spell1", SummonerSpell1.get(8)); intent.putExtra("Summoner9Spell2", SummonerSpell2.get(8)); intent.putExtra("Summoner10Spell1", SummonerSpell1.get(9)); intent.putExtra("Summoner10Spell2", SummonerSpell2.get(9)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mActivity.startActivity(intent); } else { AlertDialog.Builder builder1 = new AlertDialog.Builder(mActivity); builder1.setMessage("Summoner not in game."); builder1.setCancelable(true); builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); final AlertDialog alert11 = builder1.create(); alert11.show(); } } public Object getdMap(String div){ HashMap dMap = new HashMap<String, Integer>(); dMap.put("BRONZE V", 0); dMap.put("BRONZE IV", 1); dMap.put("BRONZE III", 2); dMap.put("BRONZE II", 3); dMap.put("BRONZE I", 4); dMap.put("SILVER V", 6); dMap.put("SILVER IV", 8); dMap.put("SILVER III", 10); dMap.put("SILVER II", 12); dMap.put("SILVER I", 14); dMap.put("GOLD V", 17); dMap.put("GOLD IV", 20); dMap.put("GOLD III", 23); dMap.put("GOLD II", 26); dMap.put("GOLD I", 29); dMap.put("PLATINUM V", 33); dMap.put("PLATINUM IV", 37); dMap.put("PLATINUM III", 41); dMap.put("PLATINUM II", 45); dMap.put("PLATINUM I", 49); dMap.put("DIAMOND V", 54); dMap.put("DIAMOND IV", 59); dMap.put("DIAMOND III", 64); dMap.put("DIAMOND II", 69); dMap.put("DIAMOND I", 74); dMap.put("MASTER I", 80); dMap.put("CHALLENGER 1", 90); dMap.put("unranked", 34); return dMap.get(div); } public double kans(int a, int b){ double diff; diff = a - b; diff = diff * 1.5; return 50 + diff; } public String kda(int games, int data){ String x; try{ x = data / games + ""; } catch (Exception e){ x = "0"; } return x; } }
86240_2
package sprint; import notification.behaviours.NotificationBehaviourTypes; import pipeline.DevelopmentPipeline; import pipeline.IPipeline; import pipeline.ReleasePipeline; import project.BacklogItem; import sprint.enums.Goal; import sprint.states.*; import sprintreport.ISprintReportBuilder; import sprintreport.domain.ISprintReport; import user.DeveloperUser; import user.LeadDeveloperUser; import user.ScrumMasterUser; import user.TesterUser; import java.time.LocalDate; import java.util.Date; //TODO: Auto state switch van ini naar inprogress en inprogress naar finished public class Sprint { SprintBacklog sprintBacklog; Goal goal; String name; Date startDate; Date endDate; boolean resultsGood; ISprintReport sprintReport; ISprintReportBuilder reportBuilder; DeveloperUser[] developers; TesterUser[] testers; LeadDeveloperUser leadDeveloper; ScrumMasterUser scrumMaster; String reviewSummary; LocalDate currentDate; LocalDate yesterdayDate; //states SprintState state; SprintState sprintInitialisedState; SprintState sprintInProgressState; SprintState sprintFinishedState; SprintState sprintFinalState; SprintState sprintReleaseDoingState; SprintState sprintReleaseFinishedState; SprintState sprintReleaseCancelledState; SprintState sprintReleaseErrorState; IPipeline pipeline; // SUGGESTION: Decided to make this email by default NotificationBehaviourTypes notificationBehaviourType; // = NotificationBehaviourTypes.EMAIL; public Sprint(Goal goal, String name, Date startDate, Date endDate, DeveloperUser[] developers, TesterUser[] testers, LeadDeveloperUser leadDeveloper, ScrumMasterUser scrumMaster, NotificationBehaviourTypes notificationBehaviourType){ this.notificationBehaviourType = notificationBehaviourType; this.goal = goal; this.name = name; this.startDate = startDate; this.endDate = endDate; this.resultsGood = false; this.developers = developers; this.testers = testers; this.leadDeveloper = leadDeveloper; this.scrumMaster = scrumMaster; this.sprintInitialisedState = new SprintInitializedState(this); this.sprintInProgressState = new SprintInProgressState(this); this.sprintFinishedState = new SprintFinishedState(this); this.sprintFinalState = new SprintFinalState(this); this.sprintReleaseDoingState = new SprintReleaseDoingState(this); this.sprintReleaseFinishedState = new SprintReleaseFinishedState(this); this.sprintReleaseCancelledState = new SprintReleaseCancelledState(this); this.sprintReleaseErrorState = new SprintReleaseErrorState(this); this.state = sprintInitialisedState; currentDate = LocalDate.now(); yesterdayDate = LocalDate.now().minusDays(1); this.reviewSummary = null; this.setupPipeline(); // TODO: fix het wanneer een sprint wordt aangemaakt met een enddate in verleden // if(currentDate.isAfter(this.endDate)){} } // THIS CAN NOT BE DONE BECAUSE JAVA FOR SOME DUMB REASON DOES NOT ALLOW ANY CODE BEFORE CALLING OVERLOADED CONSTRUCTOR MAKING ITS USAGE COMPLETELEY WORTHLESS. // SUPER ANOYING, GIVES A LOT MORE CODE COMPLEXITY // public Sprint(Goal goal, String name, Date startDate, Date endDate, DeveloperUser[] developers, TesterUser[] testers, // LeadDeveloperUser leadDeveloper, ScrumMasterUser scrumMaster, NotificationBehaviourTypes notificationBehaviourType){ // this.notificationBehaviourType = notificationBehaviourType; // // this(goal, name, startDate, endDate, developers, testers, leadDeveloper, scrumMaster); // } private void setupPipeline(){ //// Runnable onPipelineSuccessLambda = () -> { try { this.state.setStateToSprintReleaseFinished(); String message = "Pipeline finished successfully."; this.state.notifyScrummaster(message); this.state.notifyProductOwner(message); System.out.println(message); } catch (Exception e) { throw new RuntimeException(e); } // this cannot fail and this is set to satisfy java }; Runnable onPipelineFailLambda = ()-> { try { this.state.setStateToSprintReleasedError(); String message = "Sprint has failed"; this.state.notifyScrummaster(message); System.out.println(message); } catch (Exception e) { throw new RuntimeException(e); } // this cannot fail and this is set to satisfy java }; //// if(this.goal == Goal.REVIEW){ IPipeline p = new DevelopmentPipeline(){ public void onPipelineSuccess(){ System.out.println("Pipeline succeeded"); onPipelineSuccessLambda.run(); } public void onPipelineFail() { System.out.println("Pipeline failed"); onPipelineFailLambda.run(); } }; this.pipeline = p; } else if(this.goal == Goal.RELEASE){ IPipeline p = new ReleasePipeline(){ public void onPipelineSuccess(){onPipelineSuccessLambda.run();} public void onPipelineFail() {onPipelineFailLambda.run();} }; this.pipeline = p; } } public void setState(SprintState stateParameter) throws Exception { //if(this.state != stateParameter){ // throw new Exception("Sprint state not changed. Try again!"); //} this.state = stateParameter; System.out.println("Sprint state set to: " + this.state); } public NotificationBehaviourTypes getNotificationBehaviourType() { return notificationBehaviourType; } public void setNotificationBehaviourType(NotificationBehaviourTypes notificationBehaviourType) { this.notificationBehaviourType = notificationBehaviourType; } public String getName() { return name; } public String getReviewSummary() { return reviewSummary; } public SprintState getState() { return state; } public SprintState getStateInProgress(){ return this.sprintInProgressState; } public void setName(String name) throws Exception { state.changeName(name); } public void setNameOverrideState(String name){ this.name = name; } public void setStartDate(Date date) throws Exception { state.changeStartDate(date); } public void setStartDateOverrideState(Date date){ this.startDate = date; } public void setEndDate(Date date) throws Exception { state.changeEndDate(date); } public void setEndDateOverrideState(Date date){ this.endDate = date; } public void addSprintBacklog(SprintBacklog sprintBacklog) throws Exception { state.addSprintBacklog(sprintBacklog); } public void addSprintBacklogOverrideState(SprintBacklog sprintBacklog){ this.sprintBacklog = sprintBacklog; this.sprintBacklog.setSprint(this); // TODO: NEW: Sprint backlog is beging set on all backlogitems as well for(BacklogItem backlogItem : this.sprintBacklog.getBacklogItems()){ backlogItem.setSprintBacklog(sprintBacklog); } } public SprintBacklog getSprintBacklog() { return sprintBacklog; } public ScrumMasterUser getScrumMaster() { return scrumMaster; } public LeadDeveloperUser getLeadDeveloper() { return leadDeveloper; } public TesterUser[] getTesters() { return testers; } public IPipeline getPipeline() { return pipeline; } public void addReviewSummary(String summary) throws Exception { this.state.addReviewSummary(summary); } public String addReviewSummaryStateOverride(String summary){ this.reviewSummary = summary; return summary; } // public Sprint(DeveloperUser[] developers) { // this.developers = developers; // } public void setStateToSprintInProgress() throws Exception { this.state.setInProgress(); } public void setStateToSprintFinished() throws Exception { this.state.setFinished(); } public void setStateToSprintFinal(){ } public void executeRelease() throws Exception { this.state.executeRelease(); } public void executePipeline() throws Exception { this.state.executePipeline(); } public void setStateToSprintReleaseDoing(){ // this.pipeline.startPipeline(); // if(this.pipeline.getSuccess()){ // this.setStateToSprintReleaseFinished(); // } // else{ // this.setStateToSprintReleaseError(); // } } public void setStateToSprintReleaseFinished(){ } public void setStateToSprintReleaseCancelled(){ } public void setStateToSprintReleaseError(){ } public SprintState getSprintInitialisedState() { return sprintInitialisedState; } public SprintState getSprintInProgressState() { return sprintInProgressState; } public SprintState getSprintFinishedState() { return sprintFinishedState; } public SprintState getSprintFinalState() { return sprintFinalState; } public SprintState getSprintReleaseDoingState() { return sprintReleaseDoingState; } public SprintState getSprintReleaseFinishedState() { return sprintReleaseFinishedState; } public SprintState getSprintReleaseCancelledState() { return sprintReleaseCancelledState; } public SprintState getSprintReleaseErrorState() { return sprintReleaseErrorState; } public Date getStartDate() { return startDate; //.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } public Date getEndDate() { return endDate; //.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } public Goal getGoal() { return goal; } }
mjlpjacoavans/avans-devops-project
src/main/java/sprint/Sprint.java
2,383
// TODO: fix het wanneer een sprint wordt aangemaakt met een enddate in verleden
line_comment
nl
package sprint; import notification.behaviours.NotificationBehaviourTypes; import pipeline.DevelopmentPipeline; import pipeline.IPipeline; import pipeline.ReleasePipeline; import project.BacklogItem; import sprint.enums.Goal; import sprint.states.*; import sprintreport.ISprintReportBuilder; import sprintreport.domain.ISprintReport; import user.DeveloperUser; import user.LeadDeveloperUser; import user.ScrumMasterUser; import user.TesterUser; import java.time.LocalDate; import java.util.Date; //TODO: Auto state switch van ini naar inprogress en inprogress naar finished public class Sprint { SprintBacklog sprintBacklog; Goal goal; String name; Date startDate; Date endDate; boolean resultsGood; ISprintReport sprintReport; ISprintReportBuilder reportBuilder; DeveloperUser[] developers; TesterUser[] testers; LeadDeveloperUser leadDeveloper; ScrumMasterUser scrumMaster; String reviewSummary; LocalDate currentDate; LocalDate yesterdayDate; //states SprintState state; SprintState sprintInitialisedState; SprintState sprintInProgressState; SprintState sprintFinishedState; SprintState sprintFinalState; SprintState sprintReleaseDoingState; SprintState sprintReleaseFinishedState; SprintState sprintReleaseCancelledState; SprintState sprintReleaseErrorState; IPipeline pipeline; // SUGGESTION: Decided to make this email by default NotificationBehaviourTypes notificationBehaviourType; // = NotificationBehaviourTypes.EMAIL; public Sprint(Goal goal, String name, Date startDate, Date endDate, DeveloperUser[] developers, TesterUser[] testers, LeadDeveloperUser leadDeveloper, ScrumMasterUser scrumMaster, NotificationBehaviourTypes notificationBehaviourType){ this.notificationBehaviourType = notificationBehaviourType; this.goal = goal; this.name = name; this.startDate = startDate; this.endDate = endDate; this.resultsGood = false; this.developers = developers; this.testers = testers; this.leadDeveloper = leadDeveloper; this.scrumMaster = scrumMaster; this.sprintInitialisedState = new SprintInitializedState(this); this.sprintInProgressState = new SprintInProgressState(this); this.sprintFinishedState = new SprintFinishedState(this); this.sprintFinalState = new SprintFinalState(this); this.sprintReleaseDoingState = new SprintReleaseDoingState(this); this.sprintReleaseFinishedState = new SprintReleaseFinishedState(this); this.sprintReleaseCancelledState = new SprintReleaseCancelledState(this); this.sprintReleaseErrorState = new SprintReleaseErrorState(this); this.state = sprintInitialisedState; currentDate = LocalDate.now(); yesterdayDate = LocalDate.now().minusDays(1); this.reviewSummary = null; this.setupPipeline(); // TODO: fix<SUF> // if(currentDate.isAfter(this.endDate)){} } // THIS CAN NOT BE DONE BECAUSE JAVA FOR SOME DUMB REASON DOES NOT ALLOW ANY CODE BEFORE CALLING OVERLOADED CONSTRUCTOR MAKING ITS USAGE COMPLETELEY WORTHLESS. // SUPER ANOYING, GIVES A LOT MORE CODE COMPLEXITY // public Sprint(Goal goal, String name, Date startDate, Date endDate, DeveloperUser[] developers, TesterUser[] testers, // LeadDeveloperUser leadDeveloper, ScrumMasterUser scrumMaster, NotificationBehaviourTypes notificationBehaviourType){ // this.notificationBehaviourType = notificationBehaviourType; // // this(goal, name, startDate, endDate, developers, testers, leadDeveloper, scrumMaster); // } private void setupPipeline(){ //// Runnable onPipelineSuccessLambda = () -> { try { this.state.setStateToSprintReleaseFinished(); String message = "Pipeline finished successfully."; this.state.notifyScrummaster(message); this.state.notifyProductOwner(message); System.out.println(message); } catch (Exception e) { throw new RuntimeException(e); } // this cannot fail and this is set to satisfy java }; Runnable onPipelineFailLambda = ()-> { try { this.state.setStateToSprintReleasedError(); String message = "Sprint has failed"; this.state.notifyScrummaster(message); System.out.println(message); } catch (Exception e) { throw new RuntimeException(e); } // this cannot fail and this is set to satisfy java }; //// if(this.goal == Goal.REVIEW){ IPipeline p = new DevelopmentPipeline(){ public void onPipelineSuccess(){ System.out.println("Pipeline succeeded"); onPipelineSuccessLambda.run(); } public void onPipelineFail() { System.out.println("Pipeline failed"); onPipelineFailLambda.run(); } }; this.pipeline = p; } else if(this.goal == Goal.RELEASE){ IPipeline p = new ReleasePipeline(){ public void onPipelineSuccess(){onPipelineSuccessLambda.run();} public void onPipelineFail() {onPipelineFailLambda.run();} }; this.pipeline = p; } } public void setState(SprintState stateParameter) throws Exception { //if(this.state != stateParameter){ // throw new Exception("Sprint state not changed. Try again!"); //} this.state = stateParameter; System.out.println("Sprint state set to: " + this.state); } public NotificationBehaviourTypes getNotificationBehaviourType() { return notificationBehaviourType; } public void setNotificationBehaviourType(NotificationBehaviourTypes notificationBehaviourType) { this.notificationBehaviourType = notificationBehaviourType; } public String getName() { return name; } public String getReviewSummary() { return reviewSummary; } public SprintState getState() { return state; } public SprintState getStateInProgress(){ return this.sprintInProgressState; } public void setName(String name) throws Exception { state.changeName(name); } public void setNameOverrideState(String name){ this.name = name; } public void setStartDate(Date date) throws Exception { state.changeStartDate(date); } public void setStartDateOverrideState(Date date){ this.startDate = date; } public void setEndDate(Date date) throws Exception { state.changeEndDate(date); } public void setEndDateOverrideState(Date date){ this.endDate = date; } public void addSprintBacklog(SprintBacklog sprintBacklog) throws Exception { state.addSprintBacklog(sprintBacklog); } public void addSprintBacklogOverrideState(SprintBacklog sprintBacklog){ this.sprintBacklog = sprintBacklog; this.sprintBacklog.setSprint(this); // TODO: NEW: Sprint backlog is beging set on all backlogitems as well for(BacklogItem backlogItem : this.sprintBacklog.getBacklogItems()){ backlogItem.setSprintBacklog(sprintBacklog); } } public SprintBacklog getSprintBacklog() { return sprintBacklog; } public ScrumMasterUser getScrumMaster() { return scrumMaster; } public LeadDeveloperUser getLeadDeveloper() { return leadDeveloper; } public TesterUser[] getTesters() { return testers; } public IPipeline getPipeline() { return pipeline; } public void addReviewSummary(String summary) throws Exception { this.state.addReviewSummary(summary); } public String addReviewSummaryStateOverride(String summary){ this.reviewSummary = summary; return summary; } // public Sprint(DeveloperUser[] developers) { // this.developers = developers; // } public void setStateToSprintInProgress() throws Exception { this.state.setInProgress(); } public void setStateToSprintFinished() throws Exception { this.state.setFinished(); } public void setStateToSprintFinal(){ } public void executeRelease() throws Exception { this.state.executeRelease(); } public void executePipeline() throws Exception { this.state.executePipeline(); } public void setStateToSprintReleaseDoing(){ // this.pipeline.startPipeline(); // if(this.pipeline.getSuccess()){ // this.setStateToSprintReleaseFinished(); // } // else{ // this.setStateToSprintReleaseError(); // } } public void setStateToSprintReleaseFinished(){ } public void setStateToSprintReleaseCancelled(){ } public void setStateToSprintReleaseError(){ } public SprintState getSprintInitialisedState() { return sprintInitialisedState; } public SprintState getSprintInProgressState() { return sprintInProgressState; } public SprintState getSprintFinishedState() { return sprintFinishedState; } public SprintState getSprintFinalState() { return sprintFinalState; } public SprintState getSprintReleaseDoingState() { return sprintReleaseDoingState; } public SprintState getSprintReleaseFinishedState() { return sprintReleaseFinishedState; } public SprintState getSprintReleaseCancelledState() { return sprintReleaseCancelledState; } public SprintState getSprintReleaseErrorState() { return sprintReleaseErrorState; } public Date getStartDate() { return startDate; //.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } public Date getEndDate() { return endDate; //.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } public Goal getGoal() { return goal; } }
42094_3
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nl.hmh.OldManOPA.model.decorator; import java.util.Vector; import nl.hmh.OldManOPA.model.INode; import nl.hmh.OldManOPA.model.Strategy; import nl.hmh.OldManOPA.model.Node; /** * * @author Pehr */ public class INodeConcreteDecorator extends INodeDecorator { public INodeConcreteDecorator(Node component) { super(component); } void writeResult(boolean result){ //String className = component.getClass().getName(); Strategy strat = ((Node)component).getStrategy(); String stratname = strat.getClass().getSimpleName(); System.out.print(stratname + "\t="); System.out.print((result ? "1\n" : "0 \n")); } @Override public boolean calculate(int iter) { //hier hoeft iter niet opgehoogd te worden, dat doet INodeDecorator zelf boolean result = this.component.calculate(iter); writeResult(result); if(result) return true; return false; } }
PehrGit/HowToPayHereFor
OldManOPA/src/nl/hmh/OldManOPA/model/decorator/INodeConcreteDecorator.java
322
//hier hoeft iter niet opgehoogd te worden, dat doet INodeDecorator zelf
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nl.hmh.OldManOPA.model.decorator; import java.util.Vector; import nl.hmh.OldManOPA.model.INode; import nl.hmh.OldManOPA.model.Strategy; import nl.hmh.OldManOPA.model.Node; /** * * @author Pehr */ public class INodeConcreteDecorator extends INodeDecorator { public INodeConcreteDecorator(Node component) { super(component); } void writeResult(boolean result){ //String className = component.getClass().getName(); Strategy strat = ((Node)component).getStrategy(); String stratname = strat.getClass().getSimpleName(); System.out.print(stratname + "\t="); System.out.print((result ? "1\n" : "0 \n")); } @Override public boolean calculate(int iter) { //hier hoeft<SUF> boolean result = this.component.calculate(iter); writeResult(result); if(result) return true; return false; } }
17196_7
package com.liyafeng.practice; import android.content.Context; import android.os.Build; import android.os.Trace; /** * Created by liyafeng on 16/11/2017. */ public class Tools { /** * 说说Android 编译打包的过程 * <p> * http://blog.csdn.net/luoshengyang/article/details/8744683 * http://mouxuejie.com/blog/2016-08-04/build-and-package-flow-introduction/ * <p> * 说说zipalign? * https://www.jianshu.com/p/10bc0c632eda * * https://blog.csdn.net/jiangwei0910410003/article/details/50628894 * (Android逆向之旅---解析编译之后的Resource.arsc文件格式) * * ===========加固流程====== * https://www.jianshu.com/p/4ff48b761ff6 (Android应用加固原理) * */ void a1(Context context) { context.getResources().getDrawable(R.drawable.build_simplified); context.getResources().getDrawable(R.drawable.build_apk); context.getResources().getDrawable(R.drawable.build_all); /* * 首先将java文件,R.java,编译成class(字节码)文件 * 将工程的字节码文件,和library(依赖库)中的字节码文件合并成dex文件 * 将values中的文件(strings.xml color.xml styles.xml)用aapt 打包到resources.arsc中 * 将dex文件、resources.arsc、layout和drawable中的xml和png文件、lib中的so * assets中的js或者html,一起用apkbuilder,压缩到apk文件中 * 然后后用jarsigner 对apk进行签名,防止apk被修改 * 最后用zipalign ,将apk包中的内容对齐,这有利于资源的查找速度 * 比如我们apk安装时home应用会读取其中的app名称和图标,读取应用的 * 权限等,如果对齐有利于查找(就像代码格式化后有利于阅读一样) * * * ===============R文件有什么作用 R.java========== * R文件在 项目/build/generate/source/r/[build_type]/[包名]/R.java * * 默认有attr、drawable、layout、string等四个静态内部类 * 他是资源的字典 * * */ } /** * android studio 目录下build/下的文件夹都是什么作用? */ public void a1_1() { /* * The "generated" folder contains java code generated by Android Studio for the module. The primary file here is "R.java" which assigns symbolic names to each of the items in the "res" directory so they can be referenced in java source code. *The "intermediates" folder contains individual files that are created during the build process and which are eventually combined to produce the "apk" file. * *The output folder is missing because the module ".iml" file explicitly excludes it with the following statement: * *<excludeFolder url="file://$MODULE_DIR$/build/outputs" /> * *Remove that line and the "output" directory will appear under build. */ } /** * android-apt的使用? * https://joyrun.github.io/2016/07/19/AptHelloWorld/ * https://www.jianshu.com/p/2494825183c5 * https://juejin.im/entry/584a29a5128fe1006c7923a5 */ public void a1_2() { /* * 最早我们用android-apt 这个工具,但是现在已经不维护了 * 因为Gradle推出了官方的处理工具 annotationProcessor * * Annotation Processing Tool 注解处理工具,用注解来生成代码 */ //这是以前的android-apt工具使用 // buildscript { // repositories { // jcenter() // } // dependencies { // classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' // } // } // apply plugin: 'com.neenbedankt.android-apt' // dependencies { // compile 'org.greenrobot:eventbus:3.0.0' // apt'org.greenrobot:eventbus-annotation-processor:3.0.1'//apt // } //Gradle自带的 annotationProcessor // dependencies { // compile 'org.greenrobot:eventbus:3.0.0' // annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1' // } } /** * 谈谈你对安卓签名的理解? * https://blog.csdn.net/jiangwei0910410003/article/details/50402000(signapk.jar源码分析) * https://juejin.im/entry/575ed0bb1532bc00609c3aa9 * https://maoao530.github.io/2017/01/31/apk-sign/ */ public void a2(Context context) { /* * 整个过程用到了SHA-1 的hash算法,和RSA非对称加密 * 首先签名过程就是在apk(压缩包)中生成一个META-INF文件夹,里面有三个文件 * MANIFEST.MF CERT.SF CERT.RSA 文件,我们就是靠这三个文件来验证apk是没有 * 被修改过的。 * 而产生这三个文件的程序就是用 apksigner.jar用xxx.keystore来生成的, * xxx.keystore中存储了公钥和私钥 ,而生成xxx.keystore 需要用keytool.jar这个工具 * keytool -genkeypair -v -keyalg DSA -keysize 1024 -sigalg SHA1withDSA -validity 20000 -keystore D:\xxx.keystore -alias 别名 -keypass 使用密码 -storepass 打包密码? * apksigner 签名时用的是pk8和x509.pem文件,xxx.keystore文件可以转化为他们 * apksigner.jar 源码分析 源码位置:com/android/signapk/sign.java * 1,首先生成MANIFEST.MF 文件,apksigner.jar对工程中所有文件的内容做Sha-1计算, * 生成摘要信息,然后对摘要进行Base64编码,然后将 name:[文件名] sha1-digest:[摘要] * 这个键值对写入文件中。(这样能保证每个文件内容没有被修改过,因为修改了sha1值会变) * 2,生成CERT.SF,对MANIFEST.MF 文件做sha1生成摘要信息,然后base64编码 * 将sha1-digest-manifest:[摘要]写入文件首部 * 对MANIFEST.MF中的每个“键值对”做sha-1,然后base64编码,写入 name:[key] sha1-digest:[摘要] * (这样就能保证MANIFEST.MF 中的“键值对”没有被修改过) * 3,生成CERT.RSA,里面存储了签名使用的算法,公钥信息,然后将CERT.SF和前面的信息用私钥加密 * 然后写入文件结尾(这样就保证了前面所以文件都不能被修改,因为用公钥解密这个密文,得出 * 的结果要和之前的信息一致) */ context.getResources().getDrawable(R.drawable.cert_rsa); } /** * 查看证书sha256指纹 * * keytool -list -v -keystore xxx.jks */ public void a2_1(){} /** * apk反编译的流程? * x.509是什么? */ public void a3(Context context) { /* * ===================apk中的内容===================== * 将apk后缀改为zip,解压即可 * apk中有 * class.dex这个是所有java文件编译成class后合并为一个或多个dex文件 * resource.arsc 这个是所有res文件和id的映射 * lib 一般是so库 * assets 不会编译这个,是存放静态资源,比如html js文件 * AndroidManifest.xml 里面声名权限,四大组件等信息 * MATA_INF 签名信息,保证apk内容不被篡改,保证是指定私钥签名的 * 而不是他人伪造的apk * * 这里我们只能看到资源文件,而代码在dex中看不到,必须要反编译 * * apktool反编译后再values下有个public.xml * type:类型名 * name:资源名 * id:资源的id * 类型的话有这么几种: * drawable,menu,layout,string,attr,color,style等 * * =============反编译流程================ * 如果加固请先反加固 * 然后用 apktool 来解压出apk的内容 * 里面java代码是dex ,用dex2jar转换 * 然后jar 用 jd-gui 或者 jdx(可以反混淆) 来反编译,获得java文件,看到代码 * 如果是只要一些资源文件或者so文件,那么就第一步就可以看到了 * * ===================apktool ============================= * apktool 下载 https://ibotpeaches.github.io/Apktool/install/ * 反编译出的资源,能查看出Manifest的内容,还有string ,value,layout中的文本 * 正常解压出来查看是乱码!!! * apk d[ecode] filename 注意不是 -d * 这个需要jdk,配置环境变量 * https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html * * apktool使用方法 * https://ibotpeaches.github.io/Apktool/documentation/ * * ------也可以使用 Android Studio 自带的apk分析来查看包内容 * * ------补充 * apk和zip包没有区别,你可以用mac 的unzip命令直接解压apk * 也能看到里面的内容,但是AndroidManifest.xml你是看不到内容的,xml布局文件你也看不到内容 * 你只能看到一些图片资源,和so文件等。要看到xml里面内容还得用apktool这个工具 * * * ===========dex2jar * dex2jar 下载 https://sourceforge.net/projects/dex2jar/files/ * d2j-dex2jar.bat filename.dex 转化为jar包 * mac用 sh d2j-dex2jar.sh file.dex * 解压后再 file.dex 同级目录下生成转换后的jar * * 然后这个jar就能用 jd-gui打开了,而且能save source 导出源文件 * * 如果执行命令需要权限,那么手动修改权限(MAC) * chmod -R +x [dir] * 解压后的目录默认在用户根目录下: ~/[name]-dex2jar.jar * * -------查看jar中的内容------------- * jd-gui http://jd.benow.ca/ * 点击jd-gui.exe 开启程序,打开上面转化后的jar包,然后就可以查看代码了 * * 或者直接复制到Android studio中的lib中,把jar包添加依赖,然后就自动反编译了 * ===========================从新打包============================= * 使用 apktool b[uild] -o new.apk <反编译后的文件夹名称> * 这样就生成了 new.apk,但是这种没有 META-INF文件夹,安装会提示失败 * 因为这个没有签名。 * 所以我们对它签名,先要生成签名文件,xx.keystore,用keytool这个工具,这个是jdk中的 * keytool -genkey -alias demo.keystore -keyalg RSA -validity 40000 -keystore demo.keystore * 生成了demo.keystore ,然后我们要用jarsigner.exe(也是jdk中的)对apk进行签名 * jarsigner -verbose -keystore demo.keystore new.apk demo.keystore * 这样就在apk中生成了MATE-INF文件夹 * 然后我们就可以安装了,但是要把之前安装的程序删除,因为我们的签名文件不一样 * 否则会提示更新冲突,和之前的签名文件不一致,导致安装失败 * * * jarsigner -verbose -keystore [您的私钥存放路径] -signedjar [签名后文件存放路径] [未签名的文件路径] [您的证书名称] * * =========apksigner============ * https://developer.android.google.cn/studio/command-line/apksigner * * apksigner sign --ks release.jks app.apk * * apksigner在Android sdk,build-tools下 * * * * ====================x.509是什么?====================== * 是一种证书的格式,规定了公钥name:value的一些格式 * */ context.getResources().getDrawable(R.drawable.cert_rsa); } /** * 如何自定义Gradle插件? * https://kotlintc.com/articles/3075 */ public void a4() { /* * 具体可以看项目中的Module:hotfixcustomgradplugin * 一个gradle插件就是一个groovy项目 * 具体就是mian/groovy/包名/MyPlugin.groovy * 和resources/META-INF/gradle-plugins/插件名称.properties * 里面指定插件实现的类,implementation-class=com.liyafeng.plugin.MyPlugin * 这两个文件有了后就可以生成插件了 * 当然我们要使用groovy的插件 apply plugin: 'groovy' * 依赖产生插件的包 * compile gradleApi() * compile localGroovy() * * 然后我们要用maven的插件来将jar包(插件)来发布到maven仓库 * * 在另一个项目中添加meven库的路径,用classpath指定使用哪个库 * 然后apply plugin '插件名'来使用插件 * * 这样我们点击run的时候就会执行我们的插件代码,我们能获取到Project对象 * 就能做一些操作,比如动态生成代码 *==================================================== * 在build.gradle 中apply plugin'插件名' 会执行插件中的apply(Project p)方法 * Project代表整个工程的信息。在里面我们可以做自己的自定义操作 * 我们可以自定义 自己的 Extension ,(一个Extension代表一个 花括号name{}) * * 这样我们就可以读取用户在build.gradle中的name{ }中用户设置的值 */ } /** * 如何使用Gradle的transform处理字节码? * <p> * https://bintray.com/android/android-tools/com.android.tools.build.transform-api(官方库) * <p> * javassist 官方库 * https://mvnrepository.com/artifact/org.javassist/javassist */ public void a5() { /* * 其实这就是自定义一个Gradle插件(需要新建一个工程并且发布到仓库) * 在这个插件中我们自定义Transform类,来对class文件进行处理 * 然后我们在要处理字节码的工程中引用这个插件。 * 然后make module ,我们的插件就能执行了。 * * 所以说要使用这个类(api),就得先学会如何自定义gradle插件并使用 * 然后我们再在插件中加入自定义的Transform * */ } /** * 对Gradle的理解? * <p> * https://segmentfault.com/a/1190000004229002 (专门讲gradle的一个系列) */ public void a6() { /* * Gradle是一个软件,他帮我们构建一个Module,打包成apk * 但是真正打包的执行者是我们在 build.gradle中设置的插件 * apply plugin: 'com.android.application' * 而这个插件是在Project的build.gradle中配置的 * buildscript { //这里要指定我们具体的构建脚本 * repositories { * //指定构建插件所在的库的地址 * //(jcenter就代表会去https://bintray.com/bintray/jcenter 这个网站上下载对应的jar包) * jcenter() * } * dependencies { * //指定插件 组名,项目名,版本号,然后下载里面的jar包 * classpath 'com.android.tools.build:gradle:3.0.1' * //下载的位置就是 Android Studio安装目录下 * //xxx\Android Studio\gradle\m2repository\com\android\tools\build\gradle\[版本号]\gradle-[版本号].jar * * } * } * * 在apply plugin: 'com.android.application' 应用了这个插件后 * 我们就能调用里面的方法,去做一些编译时的配置 * 我们看到google为android打包写的gradle插件 gradle-3.0.1.jar中 * 也有很多自定义的Plugin,这些都是编译的时候进行一些处理 * * * */ } /** * 描述清点击 Android Studio 的 build 按钮后发生了什么? */ public void a7() { /* * 点击build,gradle会执行 google为android写的插件 * com.android.application * * 这个插件的下载位置在Android Studio目录下 * \gradle\m2repository\com\android\tools\build\gradle\3.0.1\gradle-3.0.1.jar * 里面的META-INF\gradle-plugin\com.android.application.properties * 中指定了要执行插件的类 * implementation-class=com.android.build.gradle.AppPlugin * * 然后会执行AppPlugin类中的apply(Project p)方法 * 然后所有的调用都在这里执行各种task * * 具体的task我们可以在Android Studio 右侧的Gradle栏看到 * 接下来这些task做的就是编译打包的流程 */ } //region git /** * git 流是怎样的 */ public void a8(Context context) { /* * */ context.getResources().getDrawable(R.drawable.git); } //endregion //region systrace /** * 如何使用systrace * https://developer.android.google.cn/studio/command-line/systrace(官方介绍) * https://zhuanlan.zhihu.com/p/27331842 (田维术的讲解) */ public void a9() { /* * systrace 在sdk的platform-tools/systrace中 * 用来分析app运行的时间信息,方法的耗时 * 它是用Python写的,最终生成html的结果 * * */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Trace.beginSection("lll"); Trace.endSection(); } } //endregion /** * 查找依赖库的指定版本 * 去jcenter这个网站输入包名即可 * <p> * https://bintray.com/bintray/jcenter * <p> * http://jcenter.bintray.com/包名 */ public void a10() { } /** * 图片压缩 * https://pngquant.org * tinypng.com * 我们对图片压缩很有必要 * 用ps给出的图是 32-bit color 的 * 我们压缩后变为 8bit-color ,Android加载后足足小了三倍!! * 效果还是很明显的 */ public void a11() { } /** * ============查看二进制文件=========== * Sublime Text的插件包里面就有一个很好用的HexViewer,基本能满足需求。 * 使用方式:快捷键Command+Shift+P,选择Package Control: Install Package安装插件搜索HexViewer并等待安装成功 * 打开要查看的二进制文件,这个时候还是没有以HexViewer模式 * 打开的按下快捷键Command+Shift+P, * 搜索并选择HexViewer: Toggle Hex View,回车骚等片刻后即可 * * 作者:大熊 * 链接:https://www.zhihu.com/question/22281280/answer/853433490 * 来源:知乎 * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 * * * */ void a12(){} }
pop1234o/BestPracticeApp
Practicelib/src/main/java/com/liyafeng/practice/Tools.java
5,122
// apply plugin: 'com.neenbedankt.android-apt'
line_comment
nl
package com.liyafeng.practice; import android.content.Context; import android.os.Build; import android.os.Trace; /** * Created by liyafeng on 16/11/2017. */ public class Tools { /** * 说说Android 编译打包的过程 * <p> * http://blog.csdn.net/luoshengyang/article/details/8744683 * http://mouxuejie.com/blog/2016-08-04/build-and-package-flow-introduction/ * <p> * 说说zipalign? * https://www.jianshu.com/p/10bc0c632eda * * https://blog.csdn.net/jiangwei0910410003/article/details/50628894 * (Android逆向之旅---解析编译之后的Resource.arsc文件格式) * * ===========加固流程====== * https://www.jianshu.com/p/4ff48b761ff6 (Android应用加固原理) * */ void a1(Context context) { context.getResources().getDrawable(R.drawable.build_simplified); context.getResources().getDrawable(R.drawable.build_apk); context.getResources().getDrawable(R.drawable.build_all); /* * 首先将java文件,R.java,编译成class(字节码)文件 * 将工程的字节码文件,和library(依赖库)中的字节码文件合并成dex文件 * 将values中的文件(strings.xml color.xml styles.xml)用aapt 打包到resources.arsc中 * 将dex文件、resources.arsc、layout和drawable中的xml和png文件、lib中的so * assets中的js或者html,一起用apkbuilder,压缩到apk文件中 * 然后后用jarsigner 对apk进行签名,防止apk被修改 * 最后用zipalign ,将apk包中的内容对齐,这有利于资源的查找速度 * 比如我们apk安装时home应用会读取其中的app名称和图标,读取应用的 * 权限等,如果对齐有利于查找(就像代码格式化后有利于阅读一样) * * * ===============R文件有什么作用 R.java========== * R文件在 项目/build/generate/source/r/[build_type]/[包名]/R.java * * 默认有attr、drawable、layout、string等四个静态内部类 * 他是资源的字典 * * */ } /** * android studio 目录下build/下的文件夹都是什么作用? */ public void a1_1() { /* * The "generated" folder contains java code generated by Android Studio for the module. The primary file here is "R.java" which assigns symbolic names to each of the items in the "res" directory so they can be referenced in java source code. *The "intermediates" folder contains individual files that are created during the build process and which are eventually combined to produce the "apk" file. * *The output folder is missing because the module ".iml" file explicitly excludes it with the following statement: * *<excludeFolder url="file://$MODULE_DIR$/build/outputs" /> * *Remove that line and the "output" directory will appear under build. */ } /** * android-apt的使用? * https://joyrun.github.io/2016/07/19/AptHelloWorld/ * https://www.jianshu.com/p/2494825183c5 * https://juejin.im/entry/584a29a5128fe1006c7923a5 */ public void a1_2() { /* * 最早我们用android-apt 这个工具,但是现在已经不维护了 * 因为Gradle推出了官方的处理工具 annotationProcessor * * Annotation Processing Tool 注解处理工具,用注解来生成代码 */ //这是以前的android-apt工具使用 // buildscript { // repositories { // jcenter() // } // dependencies { // classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' // } // } // apply plugin:<SUF> // dependencies { // compile 'org.greenrobot:eventbus:3.0.0' // apt'org.greenrobot:eventbus-annotation-processor:3.0.1'//apt // } //Gradle自带的 annotationProcessor // dependencies { // compile 'org.greenrobot:eventbus:3.0.0' // annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1' // } } /** * 谈谈你对安卓签名的理解? * https://blog.csdn.net/jiangwei0910410003/article/details/50402000(signapk.jar源码分析) * https://juejin.im/entry/575ed0bb1532bc00609c3aa9 * https://maoao530.github.io/2017/01/31/apk-sign/ */ public void a2(Context context) { /* * 整个过程用到了SHA-1 的hash算法,和RSA非对称加密 * 首先签名过程就是在apk(压缩包)中生成一个META-INF文件夹,里面有三个文件 * MANIFEST.MF CERT.SF CERT.RSA 文件,我们就是靠这三个文件来验证apk是没有 * 被修改过的。 * 而产生这三个文件的程序就是用 apksigner.jar用xxx.keystore来生成的, * xxx.keystore中存储了公钥和私钥 ,而生成xxx.keystore 需要用keytool.jar这个工具 * keytool -genkeypair -v -keyalg DSA -keysize 1024 -sigalg SHA1withDSA -validity 20000 -keystore D:\xxx.keystore -alias 别名 -keypass 使用密码 -storepass 打包密码? * apksigner 签名时用的是pk8和x509.pem文件,xxx.keystore文件可以转化为他们 * apksigner.jar 源码分析 源码位置:com/android/signapk/sign.java * 1,首先生成MANIFEST.MF 文件,apksigner.jar对工程中所有文件的内容做Sha-1计算, * 生成摘要信息,然后对摘要进行Base64编码,然后将 name:[文件名] sha1-digest:[摘要] * 这个键值对写入文件中。(这样能保证每个文件内容没有被修改过,因为修改了sha1值会变) * 2,生成CERT.SF,对MANIFEST.MF 文件做sha1生成摘要信息,然后base64编码 * 将sha1-digest-manifest:[摘要]写入文件首部 * 对MANIFEST.MF中的每个“键值对”做sha-1,然后base64编码,写入 name:[key] sha1-digest:[摘要] * (这样就能保证MANIFEST.MF 中的“键值对”没有被修改过) * 3,生成CERT.RSA,里面存储了签名使用的算法,公钥信息,然后将CERT.SF和前面的信息用私钥加密 * 然后写入文件结尾(这样就保证了前面所以文件都不能被修改,因为用公钥解密这个密文,得出 * 的结果要和之前的信息一致) */ context.getResources().getDrawable(R.drawable.cert_rsa); } /** * 查看证书sha256指纹 * * keytool -list -v -keystore xxx.jks */ public void a2_1(){} /** * apk反编译的流程? * x.509是什么? */ public void a3(Context context) { /* * ===================apk中的内容===================== * 将apk后缀改为zip,解压即可 * apk中有 * class.dex这个是所有java文件编译成class后合并为一个或多个dex文件 * resource.arsc 这个是所有res文件和id的映射 * lib 一般是so库 * assets 不会编译这个,是存放静态资源,比如html js文件 * AndroidManifest.xml 里面声名权限,四大组件等信息 * MATA_INF 签名信息,保证apk内容不被篡改,保证是指定私钥签名的 * 而不是他人伪造的apk * * 这里我们只能看到资源文件,而代码在dex中看不到,必须要反编译 * * apktool反编译后再values下有个public.xml * type:类型名 * name:资源名 * id:资源的id * 类型的话有这么几种: * drawable,menu,layout,string,attr,color,style等 * * =============反编译流程================ * 如果加固请先反加固 * 然后用 apktool 来解压出apk的内容 * 里面java代码是dex ,用dex2jar转换 * 然后jar 用 jd-gui 或者 jdx(可以反混淆) 来反编译,获得java文件,看到代码 * 如果是只要一些资源文件或者so文件,那么就第一步就可以看到了 * * ===================apktool ============================= * apktool 下载 https://ibotpeaches.github.io/Apktool/install/ * 反编译出的资源,能查看出Manifest的内容,还有string ,value,layout中的文本 * 正常解压出来查看是乱码!!! * apk d[ecode] filename 注意不是 -d * 这个需要jdk,配置环境变量 * https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html * * apktool使用方法 * https://ibotpeaches.github.io/Apktool/documentation/ * * ------也可以使用 Android Studio 自带的apk分析来查看包内容 * * ------补充 * apk和zip包没有区别,你可以用mac 的unzip命令直接解压apk * 也能看到里面的内容,但是AndroidManifest.xml你是看不到内容的,xml布局文件你也看不到内容 * 你只能看到一些图片资源,和so文件等。要看到xml里面内容还得用apktool这个工具 * * * ===========dex2jar * dex2jar 下载 https://sourceforge.net/projects/dex2jar/files/ * d2j-dex2jar.bat filename.dex 转化为jar包 * mac用 sh d2j-dex2jar.sh file.dex * 解压后再 file.dex 同级目录下生成转换后的jar * * 然后这个jar就能用 jd-gui打开了,而且能save source 导出源文件 * * 如果执行命令需要权限,那么手动修改权限(MAC) * chmod -R +x [dir] * 解压后的目录默认在用户根目录下: ~/[name]-dex2jar.jar * * -------查看jar中的内容------------- * jd-gui http://jd.benow.ca/ * 点击jd-gui.exe 开启程序,打开上面转化后的jar包,然后就可以查看代码了 * * 或者直接复制到Android studio中的lib中,把jar包添加依赖,然后就自动反编译了 * ===========================从新打包============================= * 使用 apktool b[uild] -o new.apk <反编译后的文件夹名称> * 这样就生成了 new.apk,但是这种没有 META-INF文件夹,安装会提示失败 * 因为这个没有签名。 * 所以我们对它签名,先要生成签名文件,xx.keystore,用keytool这个工具,这个是jdk中的 * keytool -genkey -alias demo.keystore -keyalg RSA -validity 40000 -keystore demo.keystore * 生成了demo.keystore ,然后我们要用jarsigner.exe(也是jdk中的)对apk进行签名 * jarsigner -verbose -keystore demo.keystore new.apk demo.keystore * 这样就在apk中生成了MATE-INF文件夹 * 然后我们就可以安装了,但是要把之前安装的程序删除,因为我们的签名文件不一样 * 否则会提示更新冲突,和之前的签名文件不一致,导致安装失败 * * * jarsigner -verbose -keystore [您的私钥存放路径] -signedjar [签名后文件存放路径] [未签名的文件路径] [您的证书名称] * * =========apksigner============ * https://developer.android.google.cn/studio/command-line/apksigner * * apksigner sign --ks release.jks app.apk * * apksigner在Android sdk,build-tools下 * * * * ====================x.509是什么?====================== * 是一种证书的格式,规定了公钥name:value的一些格式 * */ context.getResources().getDrawable(R.drawable.cert_rsa); } /** * 如何自定义Gradle插件? * https://kotlintc.com/articles/3075 */ public void a4() { /* * 具体可以看项目中的Module:hotfixcustomgradplugin * 一个gradle插件就是一个groovy项目 * 具体就是mian/groovy/包名/MyPlugin.groovy * 和resources/META-INF/gradle-plugins/插件名称.properties * 里面指定插件实现的类,implementation-class=com.liyafeng.plugin.MyPlugin * 这两个文件有了后就可以生成插件了 * 当然我们要使用groovy的插件 apply plugin: 'groovy' * 依赖产生插件的包 * compile gradleApi() * compile localGroovy() * * 然后我们要用maven的插件来将jar包(插件)来发布到maven仓库 * * 在另一个项目中添加meven库的路径,用classpath指定使用哪个库 * 然后apply plugin '插件名'来使用插件 * * 这样我们点击run的时候就会执行我们的插件代码,我们能获取到Project对象 * 就能做一些操作,比如动态生成代码 *==================================================== * 在build.gradle 中apply plugin'插件名' 会执行插件中的apply(Project p)方法 * Project代表整个工程的信息。在里面我们可以做自己的自定义操作 * 我们可以自定义 自己的 Extension ,(一个Extension代表一个 花括号name{}) * * 这样我们就可以读取用户在build.gradle中的name{ }中用户设置的值 */ } /** * 如何使用Gradle的transform处理字节码? * <p> * https://bintray.com/android/android-tools/com.android.tools.build.transform-api(官方库) * <p> * javassist 官方库 * https://mvnrepository.com/artifact/org.javassist/javassist */ public void a5() { /* * 其实这就是自定义一个Gradle插件(需要新建一个工程并且发布到仓库) * 在这个插件中我们自定义Transform类,来对class文件进行处理 * 然后我们在要处理字节码的工程中引用这个插件。 * 然后make module ,我们的插件就能执行了。 * * 所以说要使用这个类(api),就得先学会如何自定义gradle插件并使用 * 然后我们再在插件中加入自定义的Transform * */ } /** * 对Gradle的理解? * <p> * https://segmentfault.com/a/1190000004229002 (专门讲gradle的一个系列) */ public void a6() { /* * Gradle是一个软件,他帮我们构建一个Module,打包成apk * 但是真正打包的执行者是我们在 build.gradle中设置的插件 * apply plugin: 'com.android.application' * 而这个插件是在Project的build.gradle中配置的 * buildscript { //这里要指定我们具体的构建脚本 * repositories { * //指定构建插件所在的库的地址 * //(jcenter就代表会去https://bintray.com/bintray/jcenter 这个网站上下载对应的jar包) * jcenter() * } * dependencies { * //指定插件 组名,项目名,版本号,然后下载里面的jar包 * classpath 'com.android.tools.build:gradle:3.0.1' * //下载的位置就是 Android Studio安装目录下 * //xxx\Android Studio\gradle\m2repository\com\android\tools\build\gradle\[版本号]\gradle-[版本号].jar * * } * } * * 在apply plugin: 'com.android.application' 应用了这个插件后 * 我们就能调用里面的方法,去做一些编译时的配置 * 我们看到google为android打包写的gradle插件 gradle-3.0.1.jar中 * 也有很多自定义的Plugin,这些都是编译的时候进行一些处理 * * * */ } /** * 描述清点击 Android Studio 的 build 按钮后发生了什么? */ public void a7() { /* * 点击build,gradle会执行 google为android写的插件 * com.android.application * * 这个插件的下载位置在Android Studio目录下 * \gradle\m2repository\com\android\tools\build\gradle\3.0.1\gradle-3.0.1.jar * 里面的META-INF\gradle-plugin\com.android.application.properties * 中指定了要执行插件的类 * implementation-class=com.android.build.gradle.AppPlugin * * 然后会执行AppPlugin类中的apply(Project p)方法 * 然后所有的调用都在这里执行各种task * * 具体的task我们可以在Android Studio 右侧的Gradle栏看到 * 接下来这些task做的就是编译打包的流程 */ } //region git /** * git 流是怎样的 */ public void a8(Context context) { /* * */ context.getResources().getDrawable(R.drawable.git); } //endregion //region systrace /** * 如何使用systrace * https://developer.android.google.cn/studio/command-line/systrace(官方介绍) * https://zhuanlan.zhihu.com/p/27331842 (田维术的讲解) */ public void a9() { /* * systrace 在sdk的platform-tools/systrace中 * 用来分析app运行的时间信息,方法的耗时 * 它是用Python写的,最终生成html的结果 * * */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Trace.beginSection("lll"); Trace.endSection(); } } //endregion /** * 查找依赖库的指定版本 * 去jcenter这个网站输入包名即可 * <p> * https://bintray.com/bintray/jcenter * <p> * http://jcenter.bintray.com/包名 */ public void a10() { } /** * 图片压缩 * https://pngquant.org * tinypng.com * 我们对图片压缩很有必要 * 用ps给出的图是 32-bit color 的 * 我们压缩后变为 8bit-color ,Android加载后足足小了三倍!! * 效果还是很明显的 */ public void a11() { } /** * ============查看二进制文件=========== * Sublime Text的插件包里面就有一个很好用的HexViewer,基本能满足需求。 * 使用方式:快捷键Command+Shift+P,选择Package Control: Install Package安装插件搜索HexViewer并等待安装成功 * 打开要查看的二进制文件,这个时候还是没有以HexViewer模式 * 打开的按下快捷键Command+Shift+P, * 搜索并选择HexViewer: Toggle Hex View,回车骚等片刻后即可 * * 作者:大熊 * 链接:https://www.zhihu.com/question/22281280/answer/853433490 * 来源:知乎 * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 * * * */ void a12(){} }
78979_0
package bussimulator; import com.thoughtworks.xstream.XStream; import bussimulator.Halte.Positie; public class Bus{ private Bedrijven bedrijf; private Lijnen lijn; private int halteNummer; private int totVolgendeHalte; private int richting; private boolean bijHalte; private String busID; Bus(Lijnen lijn, Bedrijven bedrijf, int richting){ this.lijn=lijn; this.bedrijf=bedrijf; this.richting=richting; this.halteNummer = -1; this.totVolgendeHalte = 0; this.bijHalte = false; this.busID = "Niet gestart"; } public void setbusID(int starttijd){ this.busID=starttijd+lijn.name()+richting; } public void naarVolgendeHalte(){ Positie volgendeHalte = lijn.getHalte(halteNummer+richting).getPositie(); totVolgendeHalte = lijn.getHalte(halteNummer).afstand(volgendeHalte); } public boolean halteBereikt(){ halteNummer+=richting; bijHalte=true; if ((halteNummer>=lijn.getLengte()-1) || (halteNummer == 0)) { System.out.printf("Bus %s heeft eindpunt (halte %s, richting %d) bereikt.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting); return true; } else { System.out.printf("Bus %s heeft halte %s, richting %d bereikt.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting); naarVolgendeHalte(); } return false; } public void start() { halteNummer = (richting==1) ? 0 : lijn.getLengte()-1; System.out.printf("Bus %s is vertrokken van halte %s in richting %d.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting); naarVolgendeHalte(); } public boolean move(){ boolean eindpuntBereikt = false; bijHalte=false; if (halteNummer == -1) { start(); } else { totVolgendeHalte--; if (totVolgendeHalte==0){ eindpuntBereikt=halteBereikt(); } } return eindpuntBereikt; } public void sendETAs(int nu){ int i=0; Bericht bericht = new Bericht(lijn.name(),bedrijf.name(),busID,nu); if (bijHalte) { ETA eta = new ETA(lijn.getHalte(halteNummer).name(),lijn.getRichting(halteNummer)*richting,0); bericht.ETAs.add(eta); } Positie eerstVolgende=lijn.getHalte(halteNummer+richting).getPositie(); int tijdNaarHalte=totVolgendeHalte+nu; for (i = halteNummer+richting ; !(i>=lijn.getLengte()) && !(i < 0); i=i+richting ){ tijdNaarHalte+= lijn.getHalte(i).afstand(eerstVolgende); ETA eta = new ETA(lijn.getHalte(i).name(), lijn.getRichting(i)*richting,tijdNaarHalte); // System.out.println(bericht.lijnNaam + " naar halte" + eta.halteNaam + " t=" + tijdNaarHalte); bericht.ETAs.add(eta); eerstVolgende=lijn.getHalte(i).getPositie(); } bericht.eindpunt=lijn.getHalte(i-richting).name(); sendBericht(bericht); } public void sendLastETA(int nu){ Bericht bericht = new Bericht(lijn.name(),bedrijf.name(),busID,nu); String eindpunt = lijn.getHalte(halteNummer).name(); ETA eta = new ETA(eindpunt,lijn.getRichting(halteNummer)*richting,0); bericht.ETAs.add(eta); bericht.eindpunt = eindpunt; sendBericht(bericht); } public void sendBericht(Bericht bericht){ //TODO gebruik XStream om het binnengekomen bericht om te zetten // naar een XML bestand (String) XStream xstream = new XStream(); //TODO zorg er voor dat de XML-tags niet het volledige pad van de // omgezettte klassen bevat xstream.alias("Bericht", Bericht.class); // xstream.alias(?????); //TODO maak de XML String aan en verstuur het bericht String xml = xstream.toXML(bericht); Producer producer = new Producer(); producer.sendBericht(xml); } }
reneoun/EAI
eai_bussimulatorStudenten/Simulator/bussimulator/Bus.java
1,246
// System.out.println(bericht.lijnNaam + " naar halte" + eta.halteNaam + " t=" + tijdNaarHalte);
line_comment
nl
package bussimulator; import com.thoughtworks.xstream.XStream; import bussimulator.Halte.Positie; public class Bus{ private Bedrijven bedrijf; private Lijnen lijn; private int halteNummer; private int totVolgendeHalte; private int richting; private boolean bijHalte; private String busID; Bus(Lijnen lijn, Bedrijven bedrijf, int richting){ this.lijn=lijn; this.bedrijf=bedrijf; this.richting=richting; this.halteNummer = -1; this.totVolgendeHalte = 0; this.bijHalte = false; this.busID = "Niet gestart"; } public void setbusID(int starttijd){ this.busID=starttijd+lijn.name()+richting; } public void naarVolgendeHalte(){ Positie volgendeHalte = lijn.getHalte(halteNummer+richting).getPositie(); totVolgendeHalte = lijn.getHalte(halteNummer).afstand(volgendeHalte); } public boolean halteBereikt(){ halteNummer+=richting; bijHalte=true; if ((halteNummer>=lijn.getLengte()-1) || (halteNummer == 0)) { System.out.printf("Bus %s heeft eindpunt (halte %s, richting %d) bereikt.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting); return true; } else { System.out.printf("Bus %s heeft halte %s, richting %d bereikt.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting); naarVolgendeHalte(); } return false; } public void start() { halteNummer = (richting==1) ? 0 : lijn.getLengte()-1; System.out.printf("Bus %s is vertrokken van halte %s in richting %d.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer)*richting); naarVolgendeHalte(); } public boolean move(){ boolean eindpuntBereikt = false; bijHalte=false; if (halteNummer == -1) { start(); } else { totVolgendeHalte--; if (totVolgendeHalte==0){ eindpuntBereikt=halteBereikt(); } } return eindpuntBereikt; } public void sendETAs(int nu){ int i=0; Bericht bericht = new Bericht(lijn.name(),bedrijf.name(),busID,nu); if (bijHalte) { ETA eta = new ETA(lijn.getHalte(halteNummer).name(),lijn.getRichting(halteNummer)*richting,0); bericht.ETAs.add(eta); } Positie eerstVolgende=lijn.getHalte(halteNummer+richting).getPositie(); int tijdNaarHalte=totVolgendeHalte+nu; for (i = halteNummer+richting ; !(i>=lijn.getLengte()) && !(i < 0); i=i+richting ){ tijdNaarHalte+= lijn.getHalte(i).afstand(eerstVolgende); ETA eta = new ETA(lijn.getHalte(i).name(), lijn.getRichting(i)*richting,tijdNaarHalte); // System.out.println(bericht.lijnNaam +<SUF> bericht.ETAs.add(eta); eerstVolgende=lijn.getHalte(i).getPositie(); } bericht.eindpunt=lijn.getHalte(i-richting).name(); sendBericht(bericht); } public void sendLastETA(int nu){ Bericht bericht = new Bericht(lijn.name(),bedrijf.name(),busID,nu); String eindpunt = lijn.getHalte(halteNummer).name(); ETA eta = new ETA(eindpunt,lijn.getRichting(halteNummer)*richting,0); bericht.ETAs.add(eta); bericht.eindpunt = eindpunt; sendBericht(bericht); } public void sendBericht(Bericht bericht){ //TODO gebruik XStream om het binnengekomen bericht om te zetten // naar een XML bestand (String) XStream xstream = new XStream(); //TODO zorg er voor dat de XML-tags niet het volledige pad van de // omgezettte klassen bevat xstream.alias("Bericht", Bericht.class); // xstream.alias(?????); //TODO maak de XML String aan en verstuur het bericht String xml = xstream.toXML(bericht); Producer producer = new Producer(); producer.sendBericht(xml); } }
82917_12
package welker.linkchecker.models; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import welker.linkchecker.controllers.Operations; import welker.linkchecker.views.GUI; public class TextFileDataset { private Operations controller; private GUI gui; private File file; private int col856; private int colTitle; private int colAuthor; private int colBibNumber; private String delimiter; public TextFileDataset(GUI gui){ this.gui = gui; } public boolean loadFile(){ //try opening the file //System.out.println("Sending update to UI.."); gui.writeToStatusLabel("Locating text file..."); //System.out.println("Creating File object..."); this.file = new File(gui.getTextInputFileName().getText()); BufferedReader reader = null; try{ //System.out.println("Creating BufferedReader object..."); reader = new BufferedReader(new FileReader(file)); reader.close(); } catch(FileNotFoundException e){ gui.writeToActivityLog("Input file not found.\r\n" + e.getMessage()); return false; } catch(IOException e){ gui.writeToActivityLog("Input file failed to load.\r\n" + e.getMessage()); return false; } return true; } /* * Loop through the text file and create LinkCheckerRecords for each text row */ public ArrayList<Link> returnParsedRecords(){ this.getColumnNumbers(); this.getDelimiter(); try{ //open the file gui.writeToStatusLabel("Reading data from text file..."); BufferedReader reader = null; reader = new BufferedReader(new FileReader(file)); String text = null; //create an array for holding the output records ArrayList<Link> records = new ArrayList(); //decide how many rows to skip due to header and the user-specified skip values int skip = 0; if(gui.getHeaderRow().isSelected()){ skip ++; } if(gui.getTextRecordsToSkip().getText().isEmpty() == false){ skip += Integer.valueOf(gui.getTextRecordsToSkip().getText()); } //loop through lines of the text file int rowCount = 1; while((text = reader.readLine()) != null){ //skip the first X rows as defined above if(rowCount > skip){ //get new LinkCheckerRecords and merge them with the master array ArrayList<Link> newRecords = lineToLinkCheckerRecords(text); records.addAll(newRecords); } rowCount ++; } return records; } catch(FileNotFoundException e){ gui.writeToActivityLog("Input file not found.\r\n" + e.getMessage()); return null; } catch(IOException e){ gui.writeToActivityLog("Input file failed to load."); return null; } } private ArrayList<Link> lineToLinkCheckerRecords(String text){ ArrayList<Link> records = new ArrayList(); //split the line by the delimiter String[] fields = text.split(delimiter); //get the various data elements String bibNumber = fields[colBibNumber - 1]; String m856 = fields[col856 - 1]; String author = fields[colAuthor - 1]; String title = fields[colTitle - 1]; //get all the 856 data present in the text file's field String[] m856s = m856.split(";"); //create a new Link for each 856 data point for(String thism856 : m856s){ //only create it if this 856 data point has a URL, identified by the substring http if(thism856.indexOf("http") != -1){ Link record = new Link(gui, title, author, thism856, bibNumber); //push this record to the array records.add(record); } } return records; } /* * Get the column locations from the user interface */ private void getColumnNumbers(){ col856 = Integer.valueOf(gui.getM856ColNum().getText()); colTitle = Integer.valueOf(gui.getTitleColNum().getText()); colAuthor = Integer.valueOf(gui.getAuthorColNum().getText()); colBibNumber = Integer.valueOf(gui.getBibColNum().getText()); } /* * Get the delimiter from the user interface */ private void getDelimiter(){ delimiter = null; switch(gui.getInputDelimiter().getSelectionModel().getSelectedIndex()){ case 0: delimiter = "\t"; break; case 1: delimiter = "~"; break; default: delimiter = "\t"; break; } } }
jswelker/ezcheck
src/welker/linkchecker/models/TextFileDataset.java
1,285
//get the various data elements
line_comment
nl
package welker.linkchecker.models; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import welker.linkchecker.controllers.Operations; import welker.linkchecker.views.GUI; public class TextFileDataset { private Operations controller; private GUI gui; private File file; private int col856; private int colTitle; private int colAuthor; private int colBibNumber; private String delimiter; public TextFileDataset(GUI gui){ this.gui = gui; } public boolean loadFile(){ //try opening the file //System.out.println("Sending update to UI.."); gui.writeToStatusLabel("Locating text file..."); //System.out.println("Creating File object..."); this.file = new File(gui.getTextInputFileName().getText()); BufferedReader reader = null; try{ //System.out.println("Creating BufferedReader object..."); reader = new BufferedReader(new FileReader(file)); reader.close(); } catch(FileNotFoundException e){ gui.writeToActivityLog("Input file not found.\r\n" + e.getMessage()); return false; } catch(IOException e){ gui.writeToActivityLog("Input file failed to load.\r\n" + e.getMessage()); return false; } return true; } /* * Loop through the text file and create LinkCheckerRecords for each text row */ public ArrayList<Link> returnParsedRecords(){ this.getColumnNumbers(); this.getDelimiter(); try{ //open the file gui.writeToStatusLabel("Reading data from text file..."); BufferedReader reader = null; reader = new BufferedReader(new FileReader(file)); String text = null; //create an array for holding the output records ArrayList<Link> records = new ArrayList(); //decide how many rows to skip due to header and the user-specified skip values int skip = 0; if(gui.getHeaderRow().isSelected()){ skip ++; } if(gui.getTextRecordsToSkip().getText().isEmpty() == false){ skip += Integer.valueOf(gui.getTextRecordsToSkip().getText()); } //loop through lines of the text file int rowCount = 1; while((text = reader.readLine()) != null){ //skip the first X rows as defined above if(rowCount > skip){ //get new LinkCheckerRecords and merge them with the master array ArrayList<Link> newRecords = lineToLinkCheckerRecords(text); records.addAll(newRecords); } rowCount ++; } return records; } catch(FileNotFoundException e){ gui.writeToActivityLog("Input file not found.\r\n" + e.getMessage()); return null; } catch(IOException e){ gui.writeToActivityLog("Input file failed to load."); return null; } } private ArrayList<Link> lineToLinkCheckerRecords(String text){ ArrayList<Link> records = new ArrayList(); //split the line by the delimiter String[] fields = text.split(delimiter); //get the<SUF> String bibNumber = fields[colBibNumber - 1]; String m856 = fields[col856 - 1]; String author = fields[colAuthor - 1]; String title = fields[colTitle - 1]; //get all the 856 data present in the text file's field String[] m856s = m856.split(";"); //create a new Link for each 856 data point for(String thism856 : m856s){ //only create it if this 856 data point has a URL, identified by the substring http if(thism856.indexOf("http") != -1){ Link record = new Link(gui, title, author, thism856, bibNumber); //push this record to the array records.add(record); } } return records; } /* * Get the column locations from the user interface */ private void getColumnNumbers(){ col856 = Integer.valueOf(gui.getM856ColNum().getText()); colTitle = Integer.valueOf(gui.getTitleColNum().getText()); colAuthor = Integer.valueOf(gui.getAuthorColNum().getText()); colBibNumber = Integer.valueOf(gui.getBibColNum().getText()); } /* * Get the delimiter from the user interface */ private void getDelimiter(){ delimiter = null; switch(gui.getInputDelimiter().getSelectionModel().getSelectedIndex()){ case 0: delimiter = "\t"; break; case 1: delimiter = "~"; break; default: delimiter = "\t"; break; } } }
123552_1
package afvink3; /** * Paard class * * @author Martijn van der Bruggen * @version alpha release * (c) Hogeschool van Arnhem en Nijmegen * * Dit bestand niet aanpassen. Aanroepen vanuit Race * * */ import java.util.Random; import java.awt.*; public class Paard { private int afstand, paardNummer; private static int aantal = 0; private String naam; private Color kleur; Random random = new Random(); /* Constructor voor Paard */ Paard(String name, Color kl) { this.naam = name; this.kleur = kl; this.afstand = 0; paardNummer = ++aantal; } public String getNaam() { return this.naam; } public int getAfstand() { return this.afstand; } public int getPaardNummer() { return paardNummer; } public Color getKleur() { return kleur; } public void run() { afstand = afstand + random.nextInt(11); System.out.println(naam + " is op positie " + afstand); } }
itbc-bin/1819-owe5a-afvinkopdracht3-LexBosch
afvink3/Paard.java
303
/* Constructor voor Paard */
block_comment
nl
package afvink3; /** * Paard class * * @author Martijn van der Bruggen * @version alpha release * (c) Hogeschool van Arnhem en Nijmegen * * Dit bestand niet aanpassen. Aanroepen vanuit Race * * */ import java.util.Random; import java.awt.*; public class Paard { private int afstand, paardNummer; private static int aantal = 0; private String naam; private Color kleur; Random random = new Random(); /* Constructor voor Paard<SUF>*/ Paard(String name, Color kl) { this.naam = name; this.kleur = kl; this.afstand = 0; paardNummer = ++aantal; } public String getNaam() { return this.naam; } public int getAfstand() { return this.afstand; } public int getPaardNummer() { return paardNummer; } public Color getKleur() { return kleur; } public void run() { afstand = afstand + random.nextInt(11); System.out.println(naam + " is op positie " + afstand); } }
186809_0
package com.nhlstenden.JabberPoint.Slides; import com.nhlstenden.JabberPoint.Styles.Style; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.ImageObserver; import java.util.Vector; /** <p>Een slide. Deze klasse heeft tekenfunctionaliteit.</p> * @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */ public class Slide { public final static int WIDTH = 1200; public final static int HEIGHT = 800; // De titel wordt apart bewaard private String title; // De slide-items worden in een Vector bewaard private Vector<SlideItem> items; public Slide() { this.items = new Vector<SlideItem>(); } // Voeg een SlideItem toe public void append(SlideItem anItem) { this.items.addElement(anItem); } // Geef de titel van de slide public String getTitle() { return this.title; } // Verander de titel van de slide public void setTitle(String newTitle) { this.title = newTitle; } public Vector<SlideItem> getItems() { return this.items; } public void setItems(Vector<SlideItem> items) { this.items = items; } // Maak een TextItem van String, en voeg het TextItem toe public void appendTextItem(int level, String message) { this.append(new TextItem(level, message)); } // Geef het betreffende SlideItem public SlideItem getSlideItem(int number) { return (SlideItem) this.items.elementAt(number); } // Geef alle SlideItems in een Vector public Vector<SlideItem> getSlideItems() { return this.items; } // Geef de afmeting van de Slide public int getSize() { return this.items.size(); } // Teken de slide public void draw(Graphics graphics, Rectangle area, ImageObserver view) { float scale = this.getScale(area); int y = area.y; // De titel wordt apart behandeld SlideItem slideItem = new TextItem(0, this.getTitle()); Style style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; for (int number = 0; number < this.getSize(); number++) { slideItem = (SlideItem) this.getSlideItems().elementAt(number); style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; } } // Geef de schaal om de slide te kunnen tekenen private float getScale(Rectangle area) { return Math.min(((float) area.width) / ((float) WIDTH), ((float) area.height) / ((float) HEIGHT)); } }
jariolyslager/SoftwareQuality
src/main/java/com/nhlstenden/JabberPoint/Slides/Slide.java
950
/** <p>Een slide. Deze klasse heeft tekenfunctionaliteit.</p> * @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */
block_comment
nl
package com.nhlstenden.JabberPoint.Slides; import com.nhlstenden.JabberPoint.Styles.Style; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.ImageObserver; import java.util.Vector; /** <p>Een slide. Deze<SUF>*/ public class Slide { public final static int WIDTH = 1200; public final static int HEIGHT = 800; // De titel wordt apart bewaard private String title; // De slide-items worden in een Vector bewaard private Vector<SlideItem> items; public Slide() { this.items = new Vector<SlideItem>(); } // Voeg een SlideItem toe public void append(SlideItem anItem) { this.items.addElement(anItem); } // Geef de titel van de slide public String getTitle() { return this.title; } // Verander de titel van de slide public void setTitle(String newTitle) { this.title = newTitle; } public Vector<SlideItem> getItems() { return this.items; } public void setItems(Vector<SlideItem> items) { this.items = items; } // Maak een TextItem van String, en voeg het TextItem toe public void appendTextItem(int level, String message) { this.append(new TextItem(level, message)); } // Geef het betreffende SlideItem public SlideItem getSlideItem(int number) { return (SlideItem) this.items.elementAt(number); } // Geef alle SlideItems in een Vector public Vector<SlideItem> getSlideItems() { return this.items; } // Geef de afmeting van de Slide public int getSize() { return this.items.size(); } // Teken de slide public void draw(Graphics graphics, Rectangle area, ImageObserver view) { float scale = this.getScale(area); int y = area.y; // De titel wordt apart behandeld SlideItem slideItem = new TextItem(0, this.getTitle()); Style style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; for (int number = 0; number < this.getSize(); number++) { slideItem = (SlideItem) this.getSlideItems().elementAt(number); style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; } } // Geef de schaal om de slide te kunnen tekenen private float getScale(Rectangle area) { return Math.min(((float) area.width) / ((float) WIDTH), ((float) area.height) / ((float) HEIGHT)); } }
11692_19
// Mastermind versie 1.0 // author: Caspar Steinebach import java.util.*; // Import Library public class Main { // Hoofdklasse static char[] codeComputer = new char[4]; static char[] codeMens = new char[4]; static String doorgeven = "abcd"; public static void main(String[] args) { clearScreen(); System.out.println("** MASTERMIND - Caspar Steinebach **"); System.out.println("toets 'q' om het spel te verlaten"); lijstLettersRandom(); while (true) { lettersKloppen(); checkRun(); } } static void clearScreen() { System.out.flush(); } static void lijstLettersRandom() { // Deze methode laat de computer een code genereren. String alfabet = "abcdef"; // Dit zijn de beschikbare letters. Random r = new Random(); // een nieuwe randomgeneratoer wordt aangemaakt met de naam 'r'. for (int i = 0; i < 4; i++) { // forloop om een dobbelsteen te gooien. char willekeur = alfabet.charAt(r.nextInt(6)); // willekeurig karakter uit de string alfabet (uit die 6 karaters) wordt gekozen. codeComputer[i] = willekeur; // karakters worden in de charArray 'codeComputer' gestopt. } //System.out.println(codeComputer); doorgeven = String.valueOf(codeComputer); // 'codeComputer' wordt omgezet in een string en opgeslagen in de string 'doorgeven' } static void lettersKloppen() { //deze methode laat de gebruiker letters intoetsen en slaat ze op in een Array System.out.println("-------------------------------------"); System.out.println("Voer je code in: 4 letters (a t/m f)"); Scanner scanner = new Scanner(System.in); String invoer = scanner.nextLine(); if (invoer.equals("q")){ // Als de gebruiker 'q' intoetst dan eindigt het spel System.out.print("Bedankt en tot ziens!"); System.exit(0); } codeMens = invoer.toCharArray(); // De string invoer wordt in losse leters omgezet en in de charArray 'codeMens' gezet. Om later weer te gebruiken als het spel over is. (zie regel 67). } static void checkRun() { // deze methode checkt op juiste letters op de juiste plek int lettersJuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan. int goedeLettersOnjuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan. for (int i = 0; i < 4; i++) { // Forloop om door de verschillende lettercombinaties te lopen en te checken of if (codeComputer[i] == codeMens[i]) { // de combinatie klopt. Als die klopt heeft de speler de code gekraakt. lettersJuistePlek += 1; // Bij elke goede letter gaat de teller 1 omhoog. } } if (lettersJuistePlek == 4) { // Als de teller op '4' staat dan heeft de speler alle letters goed geraden en System.out.println("********** Gewonnen! **********"); // is de code gekraakt. Een felicitatie valt de speler ten deel. System.out.println("De juiste codecombinatie was : " + doorgeven); System.exit(0); // Het spel is afgelopen en wordt automatisch afgesloten. } lettersJuistePlek = 0; // Als niet alle letters goed zijn, dan betekent dat dat de code niet gekraakt is. // In dat geval wordt de teller weer op '0' gezet en worden de cijfers opnieuw if (codeComputer[0] == codeMens[0]) { // met elkaar vergeleken. Hier de eerste letter. lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[0]) { // hij wordt veregeleken met andere letters goedeLettersOnjuistePlek += 1; // als die ergens op een andere plek voorkomt dan wordt de teller met 1 verhoogt } } } if (codeComputer[1] == codeMens[1]) { // Hier de tweede letter. lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt if (codeComputer[i] == codeMens[1]) { goedeLettersOnjuistePlek += 1; } } } if (codeComputer[2] == codeMens[2]) { // Hier de derde letter lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[2]) { goedeLettersOnjuistePlek += 1; } } } if (codeComputer[3] == codeMens[3]) { // Hier de vierde letter lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[3]) { goedeLettersOnjuistePlek += 1; } } } System.out.println("Aantal letters op de juiste plek: " + lettersJuistePlek); // Een print van hoeveel letters er op de juiste plek staan. System.out.println("Aantal goede letters op een onjuiste plek: " + goedeLettersOnjuistePlek); // Een print wordt gemaakt van hoeveel letters er voorkomend zijn maar niet op de juiste plek staan. } } /* Mastermind De opdracht Programmeer het spel Mastermind tegen de computer, waarbij je gebruik maakt van Object Oriented Programming. Hieronder staat het spelverloop uitgelegd. Spelverloop De computer kiest random vier letters uit de verzameling {a, b, c, d, e, f}. De gekozen rij wordt verder “code” genoemd. De volgorde is van belang; een letter mag vaker voorkomen. De gebruiker moet de verborgen code proberen te achterhalen. De gebruiker geeft een code van vier letters op. De computer geeft een reactie op de ingegeven code, door te antwoorden met: -> het aantal correcte letters die op de juiste plaats staan -> het aantal correcte letters dat NIET op de juiste plaats staat De gebruiker geeft nu een nieuwe code op, gebaseerd op deze nieuwe informatie. Als alle vier letters op de juiste plaats staan, is de code gekraakt en het spel ten einde. Een lopend spel kan worden beëindigd door het invoeren van een q; alle andere invoer moet ofwel correct zijn (dus in de verzameling voorkomen), ofwel resulteren in opnieuw bevragen van de gebruiker */
CasparSteinebach/Qien1
Mastermind/Mastermind.java
1,845
// is de code gekraakt. Een felicitatie valt de speler ten deel.
line_comment
nl
// Mastermind versie 1.0 // author: Caspar Steinebach import java.util.*; // Import Library public class Main { // Hoofdklasse static char[] codeComputer = new char[4]; static char[] codeMens = new char[4]; static String doorgeven = "abcd"; public static void main(String[] args) { clearScreen(); System.out.println("** MASTERMIND - Caspar Steinebach **"); System.out.println("toets 'q' om het spel te verlaten"); lijstLettersRandom(); while (true) { lettersKloppen(); checkRun(); } } static void clearScreen() { System.out.flush(); } static void lijstLettersRandom() { // Deze methode laat de computer een code genereren. String alfabet = "abcdef"; // Dit zijn de beschikbare letters. Random r = new Random(); // een nieuwe randomgeneratoer wordt aangemaakt met de naam 'r'. for (int i = 0; i < 4; i++) { // forloop om een dobbelsteen te gooien. char willekeur = alfabet.charAt(r.nextInt(6)); // willekeurig karakter uit de string alfabet (uit die 6 karaters) wordt gekozen. codeComputer[i] = willekeur; // karakters worden in de charArray 'codeComputer' gestopt. } //System.out.println(codeComputer); doorgeven = String.valueOf(codeComputer); // 'codeComputer' wordt omgezet in een string en opgeslagen in de string 'doorgeven' } static void lettersKloppen() { //deze methode laat de gebruiker letters intoetsen en slaat ze op in een Array System.out.println("-------------------------------------"); System.out.println("Voer je code in: 4 letters (a t/m f)"); Scanner scanner = new Scanner(System.in); String invoer = scanner.nextLine(); if (invoer.equals("q")){ // Als de gebruiker 'q' intoetst dan eindigt het spel System.out.print("Bedankt en tot ziens!"); System.exit(0); } codeMens = invoer.toCharArray(); // De string invoer wordt in losse leters omgezet en in de charArray 'codeMens' gezet. Om later weer te gebruiken als het spel over is. (zie regel 67). } static void checkRun() { // deze methode checkt op juiste letters op de juiste plek int lettersJuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan. int goedeLettersOnjuistePlek = 0; // Een int wordt aangemaakt die als teller genereert om de gebruiker te laten weten hoeveel letters op de juiste plek staan. for (int i = 0; i < 4; i++) { // Forloop om door de verschillende lettercombinaties te lopen en te checken of if (codeComputer[i] == codeMens[i]) { // de combinatie klopt. Als die klopt heeft de speler de code gekraakt. lettersJuistePlek += 1; // Bij elke goede letter gaat de teller 1 omhoog. } } if (lettersJuistePlek == 4) { // Als de teller op '4' staat dan heeft de speler alle letters goed geraden en System.out.println("********** Gewonnen! **********"); // is de<SUF> System.out.println("De juiste codecombinatie was : " + doorgeven); System.exit(0); // Het spel is afgelopen en wordt automatisch afgesloten. } lettersJuistePlek = 0; // Als niet alle letters goed zijn, dan betekent dat dat de code niet gekraakt is. // In dat geval wordt de teller weer op '0' gezet en worden de cijfers opnieuw if (codeComputer[0] == codeMens[0]) { // met elkaar vergeleken. Hier de eerste letter. lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[0]) { // hij wordt veregeleken met andere letters goedeLettersOnjuistePlek += 1; // als die ergens op een andere plek voorkomt dan wordt de teller met 1 verhoogt } } } if (codeComputer[1] == codeMens[1]) { // Hier de tweede letter. lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { // Als de eerste letter niet overeenkomst gaan we kijen of hij vaker voorkomt if (codeComputer[i] == codeMens[1]) { goedeLettersOnjuistePlek += 1; } } } if (codeComputer[2] == codeMens[2]) { // Hier de derde letter lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[2]) { goedeLettersOnjuistePlek += 1; } } } if (codeComputer[3] == codeMens[3]) { // Hier de vierde letter lettersJuistePlek += 1; // Teller 'lettersJuistePlek' gaat 1 omhoog als die klopt } else { for (int i = 0; i < 4; i++) { if (codeComputer[i] == codeMens[3]) { goedeLettersOnjuistePlek += 1; } } } System.out.println("Aantal letters op de juiste plek: " + lettersJuistePlek); // Een print van hoeveel letters er op de juiste plek staan. System.out.println("Aantal goede letters op een onjuiste plek: " + goedeLettersOnjuistePlek); // Een print wordt gemaakt van hoeveel letters er voorkomend zijn maar niet op de juiste plek staan. } } /* Mastermind De opdracht Programmeer het spel Mastermind tegen de computer, waarbij je gebruik maakt van Object Oriented Programming. Hieronder staat het spelverloop uitgelegd. Spelverloop De computer kiest random vier letters uit de verzameling {a, b, c, d, e, f}. De gekozen rij wordt verder “code” genoemd. De volgorde is van belang; een letter mag vaker voorkomen. De gebruiker moet de verborgen code proberen te achterhalen. De gebruiker geeft een code van vier letters op. De computer geeft een reactie op de ingegeven code, door te antwoorden met: -> het aantal correcte letters die op de juiste plaats staan -> het aantal correcte letters dat NIET op de juiste plaats staat De gebruiker geeft nu een nieuwe code op, gebaseerd op deze nieuwe informatie. Als alle vier letters op de juiste plaats staan, is de code gekraakt en het spel ten einde. Een lopend spel kan worden beëindigd door het invoeren van een q; alle andere invoer moet ofwel correct zijn (dus in de verzameling voorkomen), ofwel resulteren in opnieuw bevragen van de gebruiker */
14991_12
package com.novi.gymmanagementapi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GymManagementApiApplication { public static void main(String[] args) { SpringApplication.run(GymManagementApiApplication.class, args); } //todo • 1. Technisch ontwerp schrijven ============================================================================ //Bevat een titelblad, inleiding en inhoudsopgave. In het documenten zitten geen verwijzingen naar afbeeldingen en informatie buiten het document zelf. //Beschrijft het probleem en de manier waarop deze applicatie dat probleem oplost. //Beschrijft wat de applicatie moet kunnen middels een sommering van 25 functionele en niet functionele eisen. //Bevat één klassendiagram van alle entiteiten. Dit klassendiagram is taal- en platformafhankelijk en hoeft geen methodes te bevatten. //todo • Bevat minimaal twee volledig uitgewerkte sequentiediagrammen waarin alle architecturale lagen (controller, service, repository) voorkomen. Zorg ervoor dat deze diagrammen klasse- en methodenamen bevatten. //================================================================================================================== //2. Verantwoordingsdocument in PDF ================================================================================ //Minimaal 5 beargumenteerde technische keuzes. //Een beschrijving van minimaal 5 limitaties van de applicatie en beargumentatie van de mogelijke doorontwikkelingen. //Een link naar jouw project op Github. //================================================================================================================== //todo • 3. Broncode Spring Boot =================================================================================== //Het is een REST-ful webservice die data beheert via endpoints. //De applicatie is beveiligd en bevat minimaal 2 en maximaal 3 user-rollen met verschillende mogelijkheden. //De applicatie en database zijn onafhankelijk van elkaar waardoor het mogelijk is om eventueel naar een ander database systeem te wisselen (zoals MySQL, PostgreSQL, SQLite). //Communicatie met de database vindt plaats door middel van repositories. De database kan in de vorm van CRUD operaties of complexere, samengestelde, queries bevraagd worden. //De database is relationeel en bevat minimaal een 1 one-to-one relatie en 1 one-to-many relatie. //De applicatie maakt het mogelijk om bestanden (zoals muziek, PDF’s of afbeeldingen) te uploaden en te downloaden. (huiswerk les van 1 november) //todo • De application context van de applicatie wordt getest met Spring Boot test, WebMvc en JUnit. //todo • Het systeem wordt geleverd met een valide set aan data en unit-tests worden voorzien van eigen test data. //================================================================================================================== //todo • 4. Installatie handleiding ================================================================================ //Een inhoudsopgave en inleiding, met daarin een korte beschrijving van de functionaliteit van de applicatie en de gebruikte technieken. //Een lijst van benodigdheden om de applicatie te kunnen runnen (zoals applicaties, runtime environments of andere benodigdheden. //Een stappenplan met installatie instructies. //Een lijst met (test)gebruikers en user-rollen. //Een Postman collectie, die gebruikt kan worden om jouw applicatie te testen. //todo • Een lijst van REST-endpoints, inclusief voorbeelden van de JSON-requests. Deze voorbeelden moeten uitgeschreven zijn zoals in Postman, zodat je ze gemakkelijk kunt selecteren, kopiëren en plakken. Hierin leg je ook uit hoe de endpoints beveiligd zijn. }
MrPeanutButterz/GymManagementApi
src/main/java/com/novi/gymmanagementapi/GymManagementApiApplication.java
833
//De applicatie is beveiligd en bevat minimaal 2 en maximaal 3 user-rollen met verschillende mogelijkheden.
line_comment
nl
package com.novi.gymmanagementapi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GymManagementApiApplication { public static void main(String[] args) { SpringApplication.run(GymManagementApiApplication.class, args); } //todo • 1. Technisch ontwerp schrijven ============================================================================ //Bevat een titelblad, inleiding en inhoudsopgave. In het documenten zitten geen verwijzingen naar afbeeldingen en informatie buiten het document zelf. //Beschrijft het probleem en de manier waarop deze applicatie dat probleem oplost. //Beschrijft wat de applicatie moet kunnen middels een sommering van 25 functionele en niet functionele eisen. //Bevat één klassendiagram van alle entiteiten. Dit klassendiagram is taal- en platformafhankelijk en hoeft geen methodes te bevatten. //todo • Bevat minimaal twee volledig uitgewerkte sequentiediagrammen waarin alle architecturale lagen (controller, service, repository) voorkomen. Zorg ervoor dat deze diagrammen klasse- en methodenamen bevatten. //================================================================================================================== //2. Verantwoordingsdocument in PDF ================================================================================ //Minimaal 5 beargumenteerde technische keuzes. //Een beschrijving van minimaal 5 limitaties van de applicatie en beargumentatie van de mogelijke doorontwikkelingen. //Een link naar jouw project op Github. //================================================================================================================== //todo • 3. Broncode Spring Boot =================================================================================== //Het is een REST-ful webservice die data beheert via endpoints. //De applicatie<SUF> //De applicatie en database zijn onafhankelijk van elkaar waardoor het mogelijk is om eventueel naar een ander database systeem te wisselen (zoals MySQL, PostgreSQL, SQLite). //Communicatie met de database vindt plaats door middel van repositories. De database kan in de vorm van CRUD operaties of complexere, samengestelde, queries bevraagd worden. //De database is relationeel en bevat minimaal een 1 one-to-one relatie en 1 one-to-many relatie. //De applicatie maakt het mogelijk om bestanden (zoals muziek, PDF’s of afbeeldingen) te uploaden en te downloaden. (huiswerk les van 1 november) //todo • De application context van de applicatie wordt getest met Spring Boot test, WebMvc en JUnit. //todo • Het systeem wordt geleverd met een valide set aan data en unit-tests worden voorzien van eigen test data. //================================================================================================================== //todo • 4. Installatie handleiding ================================================================================ //Een inhoudsopgave en inleiding, met daarin een korte beschrijving van de functionaliteit van de applicatie en de gebruikte technieken. //Een lijst van benodigdheden om de applicatie te kunnen runnen (zoals applicaties, runtime environments of andere benodigdheden. //Een stappenplan met installatie instructies. //Een lijst met (test)gebruikers en user-rollen. //Een Postman collectie, die gebruikt kan worden om jouw applicatie te testen. //todo • Een lijst van REST-endpoints, inclusief voorbeelden van de JSON-requests. Deze voorbeelden moeten uitgeschreven zijn zoals in Postman, zodat je ze gemakkelijk kunt selecteren, kopiëren en plakken. Hierin leg je ook uit hoe de endpoints beveiligd zijn. }
63867_11
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eu.seebetter.ini.chips; import ch.unizh.ini.jaer.chip.retina.AETemporalConstastRetina; import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor; import ch.unizh.ini.jaer.projects.davis.frames.DavisFrameAviWriter; import eu.seebetter.ini.chips.davis.AutoExposureController; import eu.seebetter.ini.chips.davis.DavisAutoShooter; import net.sf.jaer.eventio.FlexTimePlayer; import net.sf.jaer.eventprocessing.filter.ApsDvsEventFilter; import net.sf.jaer.util.avioutput.JaerAviWriter; /** Constants for DAVIS AE data format such as raw address encodings. * * @author Christian/Tobi (added IMU) * @see eu.seebetter.ini.chips.davis.DavisBaseCamera */ abstract public class DavisChip extends AETemporalConstastRetina { /** Field for decoding pixel address and data type */ public static final int YSHIFT = 22, YMASK = 511 << YSHIFT, // 9 bits from bits 22 to 30 XSHIFT = 12, XMASK = 1023 << XSHIFT, // 10 bits from bits 12 to 21 POLSHIFT = 11, POLMASK = 1 << POLSHIFT, // , // 1 bit at bit 11 EVENT_TYPE_SHIFT = 10, EVENT_TYPE_MASK = 3 << EVENT_TYPE_SHIFT, // these 2 bits encode readout type for APS and // other event type (IMU/DVS) for EXTERNAL_INPUT_EVENT_ADDR = 1 << EVENT_TYPE_SHIFT, // This special address is is for external pin input events IMU_SAMPLE_VALUE = 3 << EVENT_TYPE_SHIFT, // this special code is for IMU sample events HW_BGAF = 5, HW_TRACKER_CM = 6, HW_TRACKER_CLUSTER = 7, HW_OMC_EVENT = 4; // event code cannot be higher than 7 // in 3 bits /** Special event addresses for external input pin events */ public static final int // See DavisFX3HardwareInterface line 334 (tobi) EXTERNAL_INPUT_EVENT_ADDR_FALLING = 2 + EXTERNAL_INPUT_EVENT_ADDR, EXTERNAL_INPUT_ADDR_RISING = 3 + EXTERNAL_INPUT_EVENT_ADDR, EXTERNAL_INPUT_EVENT_ADDR_PULSE = 4 + EXTERNAL_INPUT_EVENT_ADDR; /* Detects bit indicating a DVS external event of type IMU */ public static final int IMUSHIFT = 0, IMUMASK = 1 << IMUSHIFT; /* Address-type refers to data if is it an "address". This data is either an AE address or ADC reading or an IMU * sample. */ public static final int ADDRESS_TYPE_MASK = 0x80000000, ADDRESS_TYPE_DVS = 0x00000000, ADDRESS_TYPE_APS = 0x80000000, ADDRESS_TYPE_IMU = 0x80000C00; /** Maximal ADC value */ public static final int ADC_BITS = 10, MAX_ADC = (1 << ADC_BITS) - 1; public static final int ADC_NUMBER_OF_TRAILING_ZEROS = Integer.numberOfTrailingZeros(DavisChip.ADC_READCYCLE_MASK); /** For ADC data, the data is defined by the reading cycle (0:reset read, 1 * first read, 2 second read, which is deprecated and not used). */ public static final int ADC_DATA_MASK = MAX_ADC, ADC_READCYCLE_SHIFT = 10, ADC_READCYCLE_MASK = 0xC00; /** Property change events fired when these properties change */ public static final String PROPERTY_FRAME_RATE_HZ = "DavisChip.FRAME_RATE_HZ", PROPERTY_MEASURED_EXPOSURE_MS = "ApsDvsChip.EXPOSURE_MS"; public static final String PROPERTY_AUTO_EXPOSURE_ENABLED = "autoExposureEnabled"; public DavisChip() { addDefaultEventFilter(ApsDvsEventFilter.class); addDefaultEventFilter(ApsFrameExtractor.class); addDefaultEventFilter(FlexTimePlayer.class); addDefaultEventFilter(DavisAutoShooter.class); addDefaultEventFilter(DavisFrameAviWriter.class); removeDefaultEventFilter(JaerAviWriter.class); addDefaultEventFilter(JaerAviWriter.class); } /** Returns maximum ADC count value * * @return max value, e.g. 1023 */ abstract public int getMaxADC(); /** Turns off bias generator * * @param powerDown * true to turn off */ abstract public void setPowerDown(boolean powerDown); /** Returns measured frame rate * * @return frame rate in Hz */ abstract public float getFrameRateHz(); /** Returns start of exposure time in timestamp tick units (us). Note this is * particularly relevant for global shutter mode. For rolling shutter * readout mode, this time is the start of exposure time of the first * column. * * @return start of exposure time in timestamp units (us). */ abstract public int getFrameExposureStartTimestampUs(); /** Returns end of exposure time in timestamp tick units (us). Note this is * particularly relevant for global shutter mode. For rolling shutter * readout mode, this time is the last value read from last column. * * @return start of exposure time in timestamp units (us). */ abstract public int getFrameExposureEndTimestampUs(); /** Returns measured exposure time * * @return exposure time in ms */ abstract public float getMeasuredExposureMs(); /** Triggers the taking of one snapshot, i.e, triggers a frame capture. */ abstract public void takeSnapshot(); /** Turns on/off ADC * * @param adcEnabled * true to turn on */ abstract public void setADCEnabled(boolean adcEnabled); /** Controls exposure value automatically if auto exposure is enabled. */ abstract public void controlExposure(); /** Returns the automatic APS exposure controller * * @return the controller */ abstract public AutoExposureController getAutoExposureController(); /** Sets threshold for automatically triggers snapshot images * * @param thresholdEvents * set to zero to disable automatic snapshots */ abstract public void setAutoshotThresholdEvents(int thresholdEvents); /** Returns threshold * * @return threshold. Zero means auto-shot is disabled. */ abstract public int getAutoshotThresholdEvents(); /** Sets whether automatic exposure control is enabled * * @param yes */ abstract public void setAutoExposureEnabled(boolean yes); /** Returns if automatic exposure control is enabled. * * @return */ abstract public boolean isAutoExposureEnabled(); /** Returns if the image histogram should be displayed. * * @return true if it should be displayed. */ abstract public boolean isShowImageHistogram(); /** Sets if the image histogram should be displayed. * * @param yes * true to show histogram */ abstract public void setShowImageHistogram(boolean yes); /** Returns the frame counter value. This value is set on each end-of-frame * sample. * * @return the frameCount */ public abstract int getFrameCount(); }
idsc-frazzoli/jaer-core
src/eu/seebetter/ini/chips/DavisChip.java
1,894
// in 3 bits
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eu.seebetter.ini.chips; import ch.unizh.ini.jaer.chip.retina.AETemporalConstastRetina; import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor; import ch.unizh.ini.jaer.projects.davis.frames.DavisFrameAviWriter; import eu.seebetter.ini.chips.davis.AutoExposureController; import eu.seebetter.ini.chips.davis.DavisAutoShooter; import net.sf.jaer.eventio.FlexTimePlayer; import net.sf.jaer.eventprocessing.filter.ApsDvsEventFilter; import net.sf.jaer.util.avioutput.JaerAviWriter; /** Constants for DAVIS AE data format such as raw address encodings. * * @author Christian/Tobi (added IMU) * @see eu.seebetter.ini.chips.davis.DavisBaseCamera */ abstract public class DavisChip extends AETemporalConstastRetina { /** Field for decoding pixel address and data type */ public static final int YSHIFT = 22, YMASK = 511 << YSHIFT, // 9 bits from bits 22 to 30 XSHIFT = 12, XMASK = 1023 << XSHIFT, // 10 bits from bits 12 to 21 POLSHIFT = 11, POLMASK = 1 << POLSHIFT, // , // 1 bit at bit 11 EVENT_TYPE_SHIFT = 10, EVENT_TYPE_MASK = 3 << EVENT_TYPE_SHIFT, // these 2 bits encode readout type for APS and // other event type (IMU/DVS) for EXTERNAL_INPUT_EVENT_ADDR = 1 << EVENT_TYPE_SHIFT, // This special address is is for external pin input events IMU_SAMPLE_VALUE = 3 << EVENT_TYPE_SHIFT, // this special code is for IMU sample events HW_BGAF = 5, HW_TRACKER_CM = 6, HW_TRACKER_CLUSTER = 7, HW_OMC_EVENT = 4; // event code cannot be higher than 7 // in 3<SUF> /** Special event addresses for external input pin events */ public static final int // See DavisFX3HardwareInterface line 334 (tobi) EXTERNAL_INPUT_EVENT_ADDR_FALLING = 2 + EXTERNAL_INPUT_EVENT_ADDR, EXTERNAL_INPUT_ADDR_RISING = 3 + EXTERNAL_INPUT_EVENT_ADDR, EXTERNAL_INPUT_EVENT_ADDR_PULSE = 4 + EXTERNAL_INPUT_EVENT_ADDR; /* Detects bit indicating a DVS external event of type IMU */ public static final int IMUSHIFT = 0, IMUMASK = 1 << IMUSHIFT; /* Address-type refers to data if is it an "address". This data is either an AE address or ADC reading or an IMU * sample. */ public static final int ADDRESS_TYPE_MASK = 0x80000000, ADDRESS_TYPE_DVS = 0x00000000, ADDRESS_TYPE_APS = 0x80000000, ADDRESS_TYPE_IMU = 0x80000C00; /** Maximal ADC value */ public static final int ADC_BITS = 10, MAX_ADC = (1 << ADC_BITS) - 1; public static final int ADC_NUMBER_OF_TRAILING_ZEROS = Integer.numberOfTrailingZeros(DavisChip.ADC_READCYCLE_MASK); /** For ADC data, the data is defined by the reading cycle (0:reset read, 1 * first read, 2 second read, which is deprecated and not used). */ public static final int ADC_DATA_MASK = MAX_ADC, ADC_READCYCLE_SHIFT = 10, ADC_READCYCLE_MASK = 0xC00; /** Property change events fired when these properties change */ public static final String PROPERTY_FRAME_RATE_HZ = "DavisChip.FRAME_RATE_HZ", PROPERTY_MEASURED_EXPOSURE_MS = "ApsDvsChip.EXPOSURE_MS"; public static final String PROPERTY_AUTO_EXPOSURE_ENABLED = "autoExposureEnabled"; public DavisChip() { addDefaultEventFilter(ApsDvsEventFilter.class); addDefaultEventFilter(ApsFrameExtractor.class); addDefaultEventFilter(FlexTimePlayer.class); addDefaultEventFilter(DavisAutoShooter.class); addDefaultEventFilter(DavisFrameAviWriter.class); removeDefaultEventFilter(JaerAviWriter.class); addDefaultEventFilter(JaerAviWriter.class); } /** Returns maximum ADC count value * * @return max value, e.g. 1023 */ abstract public int getMaxADC(); /** Turns off bias generator * * @param powerDown * true to turn off */ abstract public void setPowerDown(boolean powerDown); /** Returns measured frame rate * * @return frame rate in Hz */ abstract public float getFrameRateHz(); /** Returns start of exposure time in timestamp tick units (us). Note this is * particularly relevant for global shutter mode. For rolling shutter * readout mode, this time is the start of exposure time of the first * column. * * @return start of exposure time in timestamp units (us). */ abstract public int getFrameExposureStartTimestampUs(); /** Returns end of exposure time in timestamp tick units (us). Note this is * particularly relevant for global shutter mode. For rolling shutter * readout mode, this time is the last value read from last column. * * @return start of exposure time in timestamp units (us). */ abstract public int getFrameExposureEndTimestampUs(); /** Returns measured exposure time * * @return exposure time in ms */ abstract public float getMeasuredExposureMs(); /** Triggers the taking of one snapshot, i.e, triggers a frame capture. */ abstract public void takeSnapshot(); /** Turns on/off ADC * * @param adcEnabled * true to turn on */ abstract public void setADCEnabled(boolean adcEnabled); /** Controls exposure value automatically if auto exposure is enabled. */ abstract public void controlExposure(); /** Returns the automatic APS exposure controller * * @return the controller */ abstract public AutoExposureController getAutoExposureController(); /** Sets threshold for automatically triggers snapshot images * * @param thresholdEvents * set to zero to disable automatic snapshots */ abstract public void setAutoshotThresholdEvents(int thresholdEvents); /** Returns threshold * * @return threshold. Zero means auto-shot is disabled. */ abstract public int getAutoshotThresholdEvents(); /** Sets whether automatic exposure control is enabled * * @param yes */ abstract public void setAutoExposureEnabled(boolean yes); /** Returns if automatic exposure control is enabled. * * @return */ abstract public boolean isAutoExposureEnabled(); /** Returns if the image histogram should be displayed. * * @return true if it should be displayed. */ abstract public boolean isShowImageHistogram(); /** Sets if the image histogram should be displayed. * * @param yes * true to show histogram */ abstract public void setShowImageHistogram(boolean yes); /** Returns the frame counter value. This value is set on each end-of-frame * sample. * * @return the frameCount */ public abstract int getFrameCount(); }
73609_62
package org.ontologyengineering.conceptdiagrams.web.client.ui.shapes; /** * Author: Michael Compton<br> * Date: September 2015<br> * See license information in base directory. */ import com.ait.lienzo.client.core.event.*; import com.ait.lienzo.client.core.shape.Layer; import com.ait.lienzo.client.core.shape.Node; import com.ait.lienzo.client.core.shape.Rectangle; import com.ait.lienzo.client.core.types.BoundingBox; import com.ait.lienzo.client.core.types.Point2D; import org.ontologyengineering.conceptdiagrams.web.shared.presenter.DiagramCanvas; import org.ontologyengineering.conceptdiagrams.web.client.ui.LienzoDiagramCanvas; import org.ontologyengineering.conceptdiagrams.web.shared.concretesyntax.ConcreteDiagramElement; /** * Draws a bounding box around the shape with small drag boxes at the corners. * <p/> * As the boxes are moved or the external bounding box is draged, it calls back to the internal shape. (at the moment * these call backs are largely ignored - one option is to redo the underlying concrete and abstract syntax on each drag * end; the option taken at the moment is to allow all the drags and move, but not change the real onscreen * representation or the underlying representations until the shape is un selected) */ public class LienzoDragBoundsBoxes extends LienzoDiagramShape<ConcreteDiagramElement, Node> { private LienzoDiagramShape boundedShape; private Rectangle rubberband; private Rectangle[] dragBoxes; private static final int topLeft = 0; // corners private static final int topRight = 1; private static final int botRight = 2; private static final int botLeft = 3; private static final int top = 4; // sides for selection boxes private static final int right = 5; private static final int bot = 6; private static final int left = 7; private static final double dragBoxSize = 6; private Point2D unitTest; // FIXME : this should probably catch zoom events and resize the lines etc apropriately // and maybe move things if they are on say drag layer public LienzoDragBoundsBoxes(LienzoDiagramCanvas canvas, LienzoDiagramShape shapeToBound) { super(canvas); boundedShape = shapeToBound; rubberband = new Rectangle(1, 1); rubberband.setStrokeColor(rubberBandColour); rubberband.setDraggable(false); rubberband.setListening(false); representation = rubberband; dragBoxes = new Rectangle[8]; for (int i = 0; i < 8; i++) { dragBoxes[i] = new Rectangle(dragBoxSize, dragBoxSize); dragBoxes[i].setStrokeColor(dragBoxColour); dragBoxes[i].setFillColor(dragBoxColour); dragBoxes[i].setDraggable(true); } addHandlers(); unitTest = new Point2D(); } @Override public BoundingBox getBoundingBox() { // should not be called also not quite right because the drag boxes will extend beyond this. return boundedShape.getBoundingBox(); } @Override public void dragBoundsMoved(BoundingBox newBoundingBox) { } public void draw(Layer layer) { BoundingBox boundBox = boundedShape.getBoundingBox(); Point2D unit = getUnitTest(); Point2D widthHeight = new Point2D(); boundedShape.getLayer().getViewport().getTransform().transform(new Point2D(boundBox.getWidth(), boundBox.getHeight()), widthHeight); Point2D xy = new Point2D(); boundedShape.getLayer().getViewport().getTransform().transform(new Point2D(boundedShape.getDiagramElement().getX(), boundedShape.getDiagramElement().getY()), xy); redrawRubberband(); boundedShape.getLayer().getViewport().getDragLayer().add(rubberband); redrawDragBoxes(); for (int i = 0; i < 8; i++) { boundedShape.getLayer().add(dragBoxes[i]); } addZoomPanHandlers(); batch(); } // FIXME ... can't ever get this to register???? ... make sure it's registering events on other layers? private void addZoomPanHandlers() { if (getLayer() != null) { getLayer().getScene().getViewport().addViewportTransformChangedHandler(new ViewportTransformChangedHandler() { public void onViewportTransformChanged(ViewportTransformChangedEvent viewportTransformChangedEvent) { redraw(); } }); } } // does a test for what the point (1,1) translates to in the current viewport private Point2D getUnitTest() { if (boundedShape != null && boundedShape.getLayer() != null) { Point2D unit = new Point2D(1, 1); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(unit, unitTest); } return unitTest; } private void redrawRubberband() { BoundingBox boundBox = boundedShape.getBoundingBox(); Point2D unit = getUnitTest(); Point2D widthHeight = new Point2D(); boundedShape.getLayer().getViewport().getTransform().transform(new Point2D(boundBox.getWidth(), boundBox.getHeight()), widthHeight); Point2D xy = new Point2D(); boundedShape.getLayer().getViewport().getTransform().transform(new Point2D(boundedShape.getDiagramElement().getX(), boundedShape.getDiagramElement().getY()), xy); setRubberband(xy.getX(), xy.getY(), widthHeight.getX(), widthHeight.getY()); rubberband.setStrokeWidth(unit.getX() * rubberbandLineWidth); } private void setRubberband(double x, double y, double width, double height) { rubberband.setWidth(width); rubberband.setHeight(height); rubberband.setX(x); rubberband.setY(y); } @Override public void redraw() { redrawDragBoxes(); //redrawRubberband(); batch(); } private void setDragBoxSizes(Point2D unit) { for (int i = 0; i < 8; i++) { dragBoxes[i].setWidth(unit.getX() * dragBoxSize). setHeight(unit.getX() * dragBoxSize); } } protected void batch() { if (getLayer() != null) { getLayer().batch(); } if (dragBoxes[0] != null && dragBoxes[0].getLayer() != null) { dragBoxes[0].getLayer().batch(); } } private void dragByDelta(double dx, double dy) { Point2D topLeft = new Point2D(); // of the on screen shape boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); double newX = topLeft.getX() + dx; double newY = topLeft.getY() + dy; double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); setRubberband(newX, newY, newWidth, newHeight); redraw(); } private void addHandlers() { // no rubber band for select on the canvas ... probably bad way to handle this, the canvas should be in control for (int i = 0; i < 8; i++) { dragBoxes[i].addNodeMouseDownHandler(new NodeMouseDownHandler() { public void onNodeMouseDown(NodeMouseDownEvent event) { // FIXME //getCanvas().removeRubberBandRectangle(); //getCanvas().setMode(DiagramCanvas.ModeTypes.SELECTION); //getCanvas().turnOffDragSelect(); } }); } for (int i = 0; i < 8; i++) { dragBoxes[i].addNodeDragEndHandler(new NodeDragEndHandler() { public void onNodeDragEnd(NodeDragEndEvent nodeDragEndEvent) { Point2D newTopLeft = new Point2D(rubberband.getX(), rubberband.getY()); Point2D newbotRight = new Point2D(rubberband.getX() + rubberband.getWidth(), rubberband.getY() + rubberband.getHeight()); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(newTopLeft, newTopLeft); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(newbotRight, newbotRight); boundedShape.dragBoundsMoved(new BoundingBox(newTopLeft, newbotRight)); } }); } // all these are screen coords ... we just care about the rubberband rectangle dragBoxes[topLeft].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { Point2D botRight = new Point2D(); // of the on screen shape BoundingBox bbox = boundedShape.getBoundingBox(); boundedShape.getLayer().getViewport().getTransform().transform( new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); double newX = rubberband.getX(); double newY = rubberband.getY(); double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX()); double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY()); if (width >= ConcreteDiagramElement.curveMinWidth) { newWidth = width; newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX()); } if (height >= ConcreteDiagramElement.curveMinHeight) { newHeight = height; newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY()); } setRubberband(newX, newY, newWidth, newHeight); redraw(); } }); dragBoxes[topRight].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { Point2D topLeft = new Point2D(); // of the on screen shape boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); Point2D botRight = new Point2D(); // of the on screen shape BoundingBox bbox = boundedShape.getBoundingBox(); boundedShape.getLayer().getViewport().getTransform().transform( new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); double newX = rubberband.getX(); double newY = rubberband.getY(); double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY()); if (width >= ConcreteDiagramElement.curveMinWidth) { newWidth = width; newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); } if (height >= ConcreteDiagramElement.curveMinHeight) { newHeight = height; newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY()); } setRubberband(newX, newY, newWidth, newHeight); redraw(); } }); dragBoxes[botLeft].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { Point2D topLeft = new Point2D(); // of the on screen shape boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); Point2D botRight = new Point2D(); // of the on screen shape BoundingBox bbox = boundedShape.getBoundingBox(); boundedShape.getLayer().getViewport().getTransform().transform( new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); double newX = rubberband.getX(); double newY = rubberband.getY(); double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX()); double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); if (width >= ConcreteDiagramElement.curveMinWidth) { newWidth = width; newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX()); } if (height >= ConcreteDiagramElement.curveMinHeight) { newHeight = height; newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); } setRubberband(newX, newY, newWidth, newHeight); redraw(); } }); dragBoxes[botRight].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { Point2D topLeft = new Point2D(); // of the on screen shape boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); double newX = rubberband.getX(); double newY = rubberband.getY(); double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); if (width >= ConcreteDiagramElement.curveMinWidth) { newWidth = width; newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); } if (height >= ConcreteDiagramElement.curveMinHeight) { newHeight = height; newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); } setRubberband(newX, newY, newWidth, newHeight); redraw(); } }); dragBoxes[top].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy()); } }); dragBoxes[right].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy()); } }); dragBoxes[bot].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy()); } }); dragBoxes[left].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy()); } }); } // all relative to the rubber band, not the original shape private void redrawDragBoxes() { // hmmm don't quite understand bounding boxes ... sometimes they seem to be local, othertimes global? // BoundingBox bbox = rubberband.getBoundingBox(); Point2D topleftXY = new Point2D(); Point2D widthHeight = new Point2D(); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(new Point2D(rubberband.getX(), rubberband.getY()), topleftXY); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(new Point2D(rubberband.getWidth(), rubberband.getHeight()), widthHeight); Point2D unit = getUnitTest(); // no need to keep calculating // FIXME should be transforms for this right?? ok as is - cause we have done the translation to get a unit size? double dboxLeftX = topleftXY.getX() - (unit.getX() * dragBoxSize); double dboxTopY = topleftXY.getY() - (unit.getX() * dragBoxSize); double dboxCentreX = topleftXY.getX() + ((widthHeight.getX() / 2) - (unit.getX() * dragBoxSize / 2)); double dboxCentreY = topleftXY.getY() + ((widthHeight.getY() / 2) - (unit.getX() * dragBoxSize / 2)); setDragBoxSizes(unit); // FIXME need to set the drag bounds dragBoxes[topLeft].setX(dboxLeftX); dragBoxes[topLeft].setY(dboxTopY); dragBoxes[topRight].setX((topleftXY.getX() + widthHeight.getX())); dragBoxes[topRight].setY(dboxTopY); dragBoxes[botRight].setX(topleftXY.getX() + widthHeight.getX()); dragBoxes[botRight].setY(topleftXY.getY() + widthHeight.getY()); dragBoxes[botLeft].setX(dboxLeftX); dragBoxes[botLeft].setY(topleftXY.getY() + widthHeight.getY()); dragBoxes[top].setX(dboxCentreX); dragBoxes[top].setY(dboxTopY); dragBoxes[right].setX((topleftXY.getX() + widthHeight.getX())); dragBoxes[right].setY(dboxCentreY); dragBoxes[bot].setX(dboxCentreX); dragBoxes[bot].setY(topleftXY.getY() + widthHeight.getY()); dragBoxes[left].setX(dboxLeftX); dragBoxes[left].setY(dboxCentreY); } public void drawDragRepresentation() { } @Override public void setAsSelected() { } public void undraw() { unDrawDragRepresentation(); } public void unDrawDragRepresentation() { if (getLayer() != null) { Layer rubberbandLayer = getLayer(); rubberbandLayer.remove(rubberband); rubberbandLayer.batch(); } if (dragBoxes[0] != null && dragBoxes[0].getLayer() != null) { Layer boxesLayer = dragBoxes[0].getLayer(); for (Rectangle r : dragBoxes) { boxesLayer.remove(r); } boxesLayer.batch(); } } @Override public void setAsUnSelected() { } public void addLabel(String labelText) { // no labels } } // old code for resize on those corner boxes // //dragBoxes[top].addNodeDragMoveHandler(new NodeDragMoveHandler() { //public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { // Point2D topLeft = new Point2D(); // of the on screen shape // boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); // // Point2D botRight = new Point2D(); // of the on screen shape // BoundingBox bbox = boundedShape.getBoundingBox(); // boundedShape.getLayer().getViewport().getTransform().transform( // new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), // boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); // // double newX = rubberband.getX(); // double newY = rubberband.getY(); // double newWidth = rubberband.getWidth(); // double newHeight = rubberband.getHeight(); // // double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY()); // // if (height >= ConcreteDiagramElement.curveMinHeight) { // newHeight = height; // newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY()); // } // // setRubberband(newX, newY, newWidth, newHeight); // // redraw(); // } // }); // // dragBoxes[right].addNodeDragMoveHandler(new NodeDragMoveHandler() { //public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { // Point2D topLeft = new Point2D(); // of the on screen shape // boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); // // double newX = rubberband.getX(); // double newY = rubberband.getY(); // double newWidth = rubberband.getWidth(); // double newHeight = rubberband.getHeight(); // // double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); // // if (width >= ConcreteDiagramElement.curveMinWidth) { // newWidth = width; // newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); // } // // setRubberband(newX, newY, newWidth, newHeight); // // redraw(); // } // }); // // dragBoxes[bot].addNodeDragMoveHandler(new NodeDragMoveHandler() { //public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { // Point2D topLeft = new Point2D(); // of the on screen shape // boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); // // double newX = rubberband.getX(); // double newY = rubberband.getY(); // double newWidth = rubberband.getWidth(); // double newHeight = rubberband.getHeight(); // // double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); // // if (height >= ConcreteDiagramElement.curveMinHeight) { // newHeight = height; // newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); // } // // setRubberband(newX, newY, newWidth, newHeight); // // redraw(); // } // }); // // dragBoxes[left].addNodeDragMoveHandler(new NodeDragMoveHandler() { //public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { // // Point2D botRight = new Point2D(); // of the on screen shape // BoundingBox bbox = boundedShape.getBoundingBox(); // boundedShape.getLayer().getViewport().getTransform().transform( // new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), // boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); // // double newX = rubberband.getX(); // double newY = rubberband.getY(); // double newWidth = rubberband.getWidth(); // double newHeight = rubberband.getHeight(); // // double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX()); // // if (width >= ConcreteDiagramElement.curveMinWidth) { // newWidth = width; // newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX()); // } // // setRubberband(newX, newY, newWidth, newHeight); // // redraw(); // } // });
MichaelJCompton/ConceptDiagrams
src/main/java/org/ontologyengineering/conceptdiagrams/web/client/ui/shapes/LienzoDragBoundsBoxes.java
6,072
// newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY());
line_comment
nl
package org.ontologyengineering.conceptdiagrams.web.client.ui.shapes; /** * Author: Michael Compton<br> * Date: September 2015<br> * See license information in base directory. */ import com.ait.lienzo.client.core.event.*; import com.ait.lienzo.client.core.shape.Layer; import com.ait.lienzo.client.core.shape.Node; import com.ait.lienzo.client.core.shape.Rectangle; import com.ait.lienzo.client.core.types.BoundingBox; import com.ait.lienzo.client.core.types.Point2D; import org.ontologyengineering.conceptdiagrams.web.shared.presenter.DiagramCanvas; import org.ontologyengineering.conceptdiagrams.web.client.ui.LienzoDiagramCanvas; import org.ontologyengineering.conceptdiagrams.web.shared.concretesyntax.ConcreteDiagramElement; /** * Draws a bounding box around the shape with small drag boxes at the corners. * <p/> * As the boxes are moved or the external bounding box is draged, it calls back to the internal shape. (at the moment * these call backs are largely ignored - one option is to redo the underlying concrete and abstract syntax on each drag * end; the option taken at the moment is to allow all the drags and move, but not change the real onscreen * representation or the underlying representations until the shape is un selected) */ public class LienzoDragBoundsBoxes extends LienzoDiagramShape<ConcreteDiagramElement, Node> { private LienzoDiagramShape boundedShape; private Rectangle rubberband; private Rectangle[] dragBoxes; private static final int topLeft = 0; // corners private static final int topRight = 1; private static final int botRight = 2; private static final int botLeft = 3; private static final int top = 4; // sides for selection boxes private static final int right = 5; private static final int bot = 6; private static final int left = 7; private static final double dragBoxSize = 6; private Point2D unitTest; // FIXME : this should probably catch zoom events and resize the lines etc apropriately // and maybe move things if they are on say drag layer public LienzoDragBoundsBoxes(LienzoDiagramCanvas canvas, LienzoDiagramShape shapeToBound) { super(canvas); boundedShape = shapeToBound; rubberband = new Rectangle(1, 1); rubberband.setStrokeColor(rubberBandColour); rubberband.setDraggable(false); rubberband.setListening(false); representation = rubberband; dragBoxes = new Rectangle[8]; for (int i = 0; i < 8; i++) { dragBoxes[i] = new Rectangle(dragBoxSize, dragBoxSize); dragBoxes[i].setStrokeColor(dragBoxColour); dragBoxes[i].setFillColor(dragBoxColour); dragBoxes[i].setDraggable(true); } addHandlers(); unitTest = new Point2D(); } @Override public BoundingBox getBoundingBox() { // should not be called also not quite right because the drag boxes will extend beyond this. return boundedShape.getBoundingBox(); } @Override public void dragBoundsMoved(BoundingBox newBoundingBox) { } public void draw(Layer layer) { BoundingBox boundBox = boundedShape.getBoundingBox(); Point2D unit = getUnitTest(); Point2D widthHeight = new Point2D(); boundedShape.getLayer().getViewport().getTransform().transform(new Point2D(boundBox.getWidth(), boundBox.getHeight()), widthHeight); Point2D xy = new Point2D(); boundedShape.getLayer().getViewport().getTransform().transform(new Point2D(boundedShape.getDiagramElement().getX(), boundedShape.getDiagramElement().getY()), xy); redrawRubberband(); boundedShape.getLayer().getViewport().getDragLayer().add(rubberband); redrawDragBoxes(); for (int i = 0; i < 8; i++) { boundedShape.getLayer().add(dragBoxes[i]); } addZoomPanHandlers(); batch(); } // FIXME ... can't ever get this to register???? ... make sure it's registering events on other layers? private void addZoomPanHandlers() { if (getLayer() != null) { getLayer().getScene().getViewport().addViewportTransformChangedHandler(new ViewportTransformChangedHandler() { public void onViewportTransformChanged(ViewportTransformChangedEvent viewportTransformChangedEvent) { redraw(); } }); } } // does a test for what the point (1,1) translates to in the current viewport private Point2D getUnitTest() { if (boundedShape != null && boundedShape.getLayer() != null) { Point2D unit = new Point2D(1, 1); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(unit, unitTest); } return unitTest; } private void redrawRubberband() { BoundingBox boundBox = boundedShape.getBoundingBox(); Point2D unit = getUnitTest(); Point2D widthHeight = new Point2D(); boundedShape.getLayer().getViewport().getTransform().transform(new Point2D(boundBox.getWidth(), boundBox.getHeight()), widthHeight); Point2D xy = new Point2D(); boundedShape.getLayer().getViewport().getTransform().transform(new Point2D(boundedShape.getDiagramElement().getX(), boundedShape.getDiagramElement().getY()), xy); setRubberband(xy.getX(), xy.getY(), widthHeight.getX(), widthHeight.getY()); rubberband.setStrokeWidth(unit.getX() * rubberbandLineWidth); } private void setRubberband(double x, double y, double width, double height) { rubberband.setWidth(width); rubberband.setHeight(height); rubberband.setX(x); rubberband.setY(y); } @Override public void redraw() { redrawDragBoxes(); //redrawRubberband(); batch(); } private void setDragBoxSizes(Point2D unit) { for (int i = 0; i < 8; i++) { dragBoxes[i].setWidth(unit.getX() * dragBoxSize). setHeight(unit.getX() * dragBoxSize); } } protected void batch() { if (getLayer() != null) { getLayer().batch(); } if (dragBoxes[0] != null && dragBoxes[0].getLayer() != null) { dragBoxes[0].getLayer().batch(); } } private void dragByDelta(double dx, double dy) { Point2D topLeft = new Point2D(); // of the on screen shape boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); double newX = topLeft.getX() + dx; double newY = topLeft.getY() + dy; double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); setRubberband(newX, newY, newWidth, newHeight); redraw(); } private void addHandlers() { // no rubber band for select on the canvas ... probably bad way to handle this, the canvas should be in control for (int i = 0; i < 8; i++) { dragBoxes[i].addNodeMouseDownHandler(new NodeMouseDownHandler() { public void onNodeMouseDown(NodeMouseDownEvent event) { // FIXME //getCanvas().removeRubberBandRectangle(); //getCanvas().setMode(DiagramCanvas.ModeTypes.SELECTION); //getCanvas().turnOffDragSelect(); } }); } for (int i = 0; i < 8; i++) { dragBoxes[i].addNodeDragEndHandler(new NodeDragEndHandler() { public void onNodeDragEnd(NodeDragEndEvent nodeDragEndEvent) { Point2D newTopLeft = new Point2D(rubberband.getX(), rubberband.getY()); Point2D newbotRight = new Point2D(rubberband.getX() + rubberband.getWidth(), rubberband.getY() + rubberband.getHeight()); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(newTopLeft, newTopLeft); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(newbotRight, newbotRight); boundedShape.dragBoundsMoved(new BoundingBox(newTopLeft, newbotRight)); } }); } // all these are screen coords ... we just care about the rubberband rectangle dragBoxes[topLeft].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { Point2D botRight = new Point2D(); // of the on screen shape BoundingBox bbox = boundedShape.getBoundingBox(); boundedShape.getLayer().getViewport().getTransform().transform( new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); double newX = rubberband.getX(); double newY = rubberband.getY(); double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX()); double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY()); if (width >= ConcreteDiagramElement.curveMinWidth) { newWidth = width; newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX()); } if (height >= ConcreteDiagramElement.curveMinHeight) { newHeight = height; newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY()); } setRubberband(newX, newY, newWidth, newHeight); redraw(); } }); dragBoxes[topRight].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { Point2D topLeft = new Point2D(); // of the on screen shape boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); Point2D botRight = new Point2D(); // of the on screen shape BoundingBox bbox = boundedShape.getBoundingBox(); boundedShape.getLayer().getViewport().getTransform().transform( new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); double newX = rubberband.getX(); double newY = rubberband.getY(); double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY()); if (width >= ConcreteDiagramElement.curveMinWidth) { newWidth = width; newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); } if (height >= ConcreteDiagramElement.curveMinHeight) { newHeight = height; newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY()); } setRubberband(newX, newY, newWidth, newHeight); redraw(); } }); dragBoxes[botLeft].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { Point2D topLeft = new Point2D(); // of the on screen shape boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); Point2D botRight = new Point2D(); // of the on screen shape BoundingBox bbox = boundedShape.getBoundingBox(); boundedShape.getLayer().getViewport().getTransform().transform( new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); double newX = rubberband.getX(); double newY = rubberband.getY(); double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX()); double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); if (width >= ConcreteDiagramElement.curveMinWidth) { newWidth = width; newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX()); } if (height >= ConcreteDiagramElement.curveMinHeight) { newHeight = height; newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); } setRubberband(newX, newY, newWidth, newHeight); redraw(); } }); dragBoxes[botRight].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { Point2D topLeft = new Point2D(); // of the on screen shape boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); double newX = rubberband.getX(); double newY = rubberband.getY(); double newWidth = rubberband.getWidth(); double newHeight = rubberband.getHeight(); double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); if (width >= ConcreteDiagramElement.curveMinWidth) { newWidth = width; newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); } if (height >= ConcreteDiagramElement.curveMinHeight) { newHeight = height; newY = Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); } setRubberband(newX, newY, newWidth, newHeight); redraw(); } }); dragBoxes[top].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy()); } }); dragBoxes[right].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy()); } }); dragBoxes[bot].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy()); } }); dragBoxes[left].addNodeDragMoveHandler(new NodeDragMoveHandler() { public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { dragByDelta(nodeDragMoveEvent.getDragContext().getDx(), nodeDragMoveEvent.getDragContext().getDy()); } }); } // all relative to the rubber band, not the original shape private void redrawDragBoxes() { // hmmm don't quite understand bounding boxes ... sometimes they seem to be local, othertimes global? // BoundingBox bbox = rubberband.getBoundingBox(); Point2D topleftXY = new Point2D(); Point2D widthHeight = new Point2D(); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(new Point2D(rubberband.getX(), rubberband.getY()), topleftXY); boundedShape.getLayer().getViewport().getTransform().getInverse().transform(new Point2D(rubberband.getWidth(), rubberband.getHeight()), widthHeight); Point2D unit = getUnitTest(); // no need to keep calculating // FIXME should be transforms for this right?? ok as is - cause we have done the translation to get a unit size? double dboxLeftX = topleftXY.getX() - (unit.getX() * dragBoxSize); double dboxTopY = topleftXY.getY() - (unit.getX() * dragBoxSize); double dboxCentreX = topleftXY.getX() + ((widthHeight.getX() / 2) - (unit.getX() * dragBoxSize / 2)); double dboxCentreY = topleftXY.getY() + ((widthHeight.getY() / 2) - (unit.getX() * dragBoxSize / 2)); setDragBoxSizes(unit); // FIXME need to set the drag bounds dragBoxes[topLeft].setX(dboxLeftX); dragBoxes[topLeft].setY(dboxTopY); dragBoxes[topRight].setX((topleftXY.getX() + widthHeight.getX())); dragBoxes[topRight].setY(dboxTopY); dragBoxes[botRight].setX(topleftXY.getX() + widthHeight.getX()); dragBoxes[botRight].setY(topleftXY.getY() + widthHeight.getY()); dragBoxes[botLeft].setX(dboxLeftX); dragBoxes[botLeft].setY(topleftXY.getY() + widthHeight.getY()); dragBoxes[top].setX(dboxCentreX); dragBoxes[top].setY(dboxTopY); dragBoxes[right].setX((topleftXY.getX() + widthHeight.getX())); dragBoxes[right].setY(dboxCentreY); dragBoxes[bot].setX(dboxCentreX); dragBoxes[bot].setY(topleftXY.getY() + widthHeight.getY()); dragBoxes[left].setX(dboxLeftX); dragBoxes[left].setY(dboxCentreY); } public void drawDragRepresentation() { } @Override public void setAsSelected() { } public void undraw() { unDrawDragRepresentation(); } public void unDrawDragRepresentation() { if (getLayer() != null) { Layer rubberbandLayer = getLayer(); rubberbandLayer.remove(rubberband); rubberbandLayer.batch(); } if (dragBoxes[0] != null && dragBoxes[0].getLayer() != null) { Layer boxesLayer = dragBoxes[0].getLayer(); for (Rectangle r : dragBoxes) { boxesLayer.remove(r); } boxesLayer.batch(); } } @Override public void setAsUnSelected() { } public void addLabel(String labelText) { // no labels } } // old code for resize on those corner boxes // //dragBoxes[top].addNodeDragMoveHandler(new NodeDragMoveHandler() { //public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { // Point2D topLeft = new Point2D(); // of the on screen shape // boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); // // Point2D botRight = new Point2D(); // of the on screen shape // BoundingBox bbox = boundedShape.getBoundingBox(); // boundedShape.getLayer().getViewport().getTransform().transform( // new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), // boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); // // double newX = rubberband.getX(); // double newY = rubberband.getY(); // double newWidth = rubberband.getWidth(); // double newHeight = rubberband.getHeight(); // // double height = Math.max(nodeDragMoveEvent.getY(), botRight.getY()) - Math.min(nodeDragMoveEvent.getY(), botRight.getY()); // // if (height >= ConcreteDiagramElement.curveMinHeight) { // newHeight = height; // newY = Math.min(nodeDragMoveEvent.getY(), botRight.getY()); // } // // setRubberband(newX, newY, newWidth, newHeight); // // redraw(); // } // }); // // dragBoxes[right].addNodeDragMoveHandler(new NodeDragMoveHandler() { //public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { // Point2D topLeft = new Point2D(); // of the on screen shape // boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); // // double newX = rubberband.getX(); // double newY = rubberband.getY(); // double newWidth = rubberband.getWidth(); // double newHeight = rubberband.getHeight(); // // double width = Math.max(nodeDragMoveEvent.getX(), topLeft.getX()) - Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); // // if (width >= ConcreteDiagramElement.curveMinWidth) { // newWidth = width; // newX = Math.min(nodeDragMoveEvent.getX(), topLeft.getX()); // } // // setRubberband(newX, newY, newWidth, newHeight); // // redraw(); // } // }); // // dragBoxes[bot].addNodeDragMoveHandler(new NodeDragMoveHandler() { //public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { // Point2D topLeft = new Point2D(); // of the on screen shape // boundedShape.getLayer().getViewport().getTransform().transform(boundedShape.getDiagramElement().topLeft().asLienzoPoint2D(), topLeft); // // double newX = rubberband.getX(); // double newY = rubberband.getY(); // double newWidth = rubberband.getWidth(); // double newHeight = rubberband.getHeight(); // // double height = Math.max(nodeDragMoveEvent.getY(), topLeft.getY()) - Math.min(nodeDragMoveEvent.getY(), topLeft.getY()); // // if (height >= ConcreteDiagramElement.curveMinHeight) { // newHeight = height; // newY =<SUF> // } // // setRubberband(newX, newY, newWidth, newHeight); // // redraw(); // } // }); // // dragBoxes[left].addNodeDragMoveHandler(new NodeDragMoveHandler() { //public void onNodeDragMove(NodeDragMoveEvent nodeDragMoveEvent) { // // Point2D botRight = new Point2D(); // of the on screen shape // BoundingBox bbox = boundedShape.getBoundingBox(); // boundedShape.getLayer().getViewport().getTransform().transform( // new Point2D(boundedShape.getDiagramElement().topLeft().getX() + bbox.getWidth(), // boundedShape.getDiagramElement().topLeft().getY() + bbox.getHeight()), botRight); // // double newX = rubberband.getX(); // double newY = rubberband.getY(); // double newWidth = rubberband.getWidth(); // double newHeight = rubberband.getHeight(); // // double width = Math.max(nodeDragMoveEvent.getX(), botRight.getX()) - Math.min(nodeDragMoveEvent.getX(), botRight.getX()); // // if (width >= ConcreteDiagramElement.curveMinWidth) { // newWidth = width; // newX = Math.min(nodeDragMoveEvent.getX(), botRight.getX()); // } // // setRubberband(newX, newY, newWidth, newHeight); // // redraw(); // } // });
50699_14
package net.bzzt.ical.aggregator.model; import java.io.Serializable; import java.net.URL; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.ManyToOne; import net.bzzt.ical.aggregator.web.model.Identifiable; import net.fortuna.ical4j.model.Iso8601; import org.apache.wicket.util.time.Time; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class Event implements Serializable, Identifiable<Long>, Cloneable, Comparable<Event> { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue public Long id; @ManyToOne public Feed feed; @ManyToOne public Event duplicate_of; public String uid; public String summary; @Lob public String description; private Date start; /** false if 'start' is a date rather than a datetime */ private Boolean startHasTime = false; private Date ending; private Boolean endHasTime = false; @Lob public String rawEvent; public URL url; public String location; /** This event was added manually */ @Column(nullable=false) private Boolean manual = false; /** * Some manual events need to be verified before they show up. */ @Column(nullable=false) private Boolean hidden = true; /** * Hoe vaak komt een event met dezelfde titel en beschrijving voor in deze feed? */ private Integer aantalHerhalingen; public Event() { } public Event(Feed feed, Boolean hidden) { this.feed = feed; if (hidden == null) { this.hidden = feed.url == null; } else { this.hidden = hidden; } } public Event(boolean manual) { this.manual = manual; } public Date getStart() { return start; } public void setStart(Date start) { if (start instanceof Iso8601) { this.start = new Date(start.getTime()); } else { this.start = start; } } public Date getEnding() { return ending; } public void setEnding(Date ending) { if (ending instanceof Iso8601) { this.ending = new Date(ending.getTime()); } else { this.ending = ending; } } public Time getStartTime() { if (startHasTime == null || startHasTime) { return Time.valueOf(start); } else { return null; } } public Time getEndTime() { if (ending != null && (endHasTime == null || endHasTime)) { return Time.valueOf(ending); } else { return null; } } @Override public Long getId() { return id; } public Event clone() { if (duplicate_of != null) { throw new IllegalStateException(); } if (manual != null && manual) { throw new IllegalStateException(); } Event result; try { result = (Event) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } result.id = null; result.uid = null; result.setManual(true); return result; } /** * @return the manual */ public Boolean getManual() { return manual; } /** * @param manual the manual to set */ public void setManual(Boolean manual) { if (manual == null) { this.manual = false; } else { this.manual = manual; } } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "[" + feed.shortName + "] " + summary; } /** * @return the verified */ public Boolean getHidden() { return hidden != null && hidden; } /** * @param hidden the verified to set */ public void setHidden(Boolean hidden) { if (hidden == null) { this.hidden = true; } else { this.hidden = hidden; } } /** * @return the startHasTime */ public Boolean getStartHasTime() { return startHasTime; } /** * @param startHasTime the startHasTime to set */ public void setStartHasTime(Boolean startHasTime) { this.startHasTime = startHasTime; } /** * @return the endHasTime */ public Boolean getEndHasTime() { return endHasTime; } /** * @param endHasTime the endHasTime to set */ public void setEndHasTime(Boolean endHasTime) { this.endHasTime = endHasTime; } @Override public int compareTo(Event o) { int result = start.compareTo(o.start); if (result == 0) { return summary.compareTo(o.summary); } else { return result; } } /** * @return the aantalHerhalingen */ public Integer getAantalHerhalingen() { return aantalHerhalingen; } /** * @param aantalHerhalingen the aantalHerhalingen to set */ public void setAantalHerhalingen(Integer aantalHerhalingen) { this.aantalHerhalingen = aantalHerhalingen; } /** * @return the feed */ public Feed getFeed() { return feed; } /** * @param feed the feed to set */ public void setFeed(Feed feed) { this.feed = feed; } /** * @return the summary */ public String getSummary() { return summary; } /** * @param summary the summary to set */ public void setSummary(String summary) { this.summary = summary; } }
raboof/ical-aggregator
src/main/java/net/bzzt/ical/aggregator/model/Event.java
1,754
/** * @param aantalHerhalingen the aantalHerhalingen to set */
block_comment
nl
package net.bzzt.ical.aggregator.model; import java.io.Serializable; import java.net.URL; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.ManyToOne; import net.bzzt.ical.aggregator.web.model.Identifiable; import net.fortuna.ical4j.model.Iso8601; import org.apache.wicket.util.time.Time; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) public class Event implements Serializable, Identifiable<Long>, Cloneable, Comparable<Event> { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue public Long id; @ManyToOne public Feed feed; @ManyToOne public Event duplicate_of; public String uid; public String summary; @Lob public String description; private Date start; /** false if 'start' is a date rather than a datetime */ private Boolean startHasTime = false; private Date ending; private Boolean endHasTime = false; @Lob public String rawEvent; public URL url; public String location; /** This event was added manually */ @Column(nullable=false) private Boolean manual = false; /** * Some manual events need to be verified before they show up. */ @Column(nullable=false) private Boolean hidden = true; /** * Hoe vaak komt een event met dezelfde titel en beschrijving voor in deze feed? */ private Integer aantalHerhalingen; public Event() { } public Event(Feed feed, Boolean hidden) { this.feed = feed; if (hidden == null) { this.hidden = feed.url == null; } else { this.hidden = hidden; } } public Event(boolean manual) { this.manual = manual; } public Date getStart() { return start; } public void setStart(Date start) { if (start instanceof Iso8601) { this.start = new Date(start.getTime()); } else { this.start = start; } } public Date getEnding() { return ending; } public void setEnding(Date ending) { if (ending instanceof Iso8601) { this.ending = new Date(ending.getTime()); } else { this.ending = ending; } } public Time getStartTime() { if (startHasTime == null || startHasTime) { return Time.valueOf(start); } else { return null; } } public Time getEndTime() { if (ending != null && (endHasTime == null || endHasTime)) { return Time.valueOf(ending); } else { return null; } } @Override public Long getId() { return id; } public Event clone() { if (duplicate_of != null) { throw new IllegalStateException(); } if (manual != null && manual) { throw new IllegalStateException(); } Event result; try { result = (Event) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } result.id = null; result.uid = null; result.setManual(true); return result; } /** * @return the manual */ public Boolean getManual() { return manual; } /** * @param manual the manual to set */ public void setManual(Boolean manual) { if (manual == null) { this.manual = false; } else { this.manual = manual; } } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "[" + feed.shortName + "] " + summary; } /** * @return the verified */ public Boolean getHidden() { return hidden != null && hidden; } /** * @param hidden the verified to set */ public void setHidden(Boolean hidden) { if (hidden == null) { this.hidden = true; } else { this.hidden = hidden; } } /** * @return the startHasTime */ public Boolean getStartHasTime() { return startHasTime; } /** * @param startHasTime the startHasTime to set */ public void setStartHasTime(Boolean startHasTime) { this.startHasTime = startHasTime; } /** * @return the endHasTime */ public Boolean getEndHasTime() { return endHasTime; } /** * @param endHasTime the endHasTime to set */ public void setEndHasTime(Boolean endHasTime) { this.endHasTime = endHasTime; } @Override public int compareTo(Event o) { int result = start.compareTo(o.start); if (result == 0) { return summary.compareTo(o.summary); } else { return result; } } /** * @return the aantalHerhalingen */ public Integer getAantalHerhalingen() { return aantalHerhalingen; } /** * @param aantalHerhalingen the<SUF>*/ public void setAantalHerhalingen(Integer aantalHerhalingen) { this.aantalHerhalingen = aantalHerhalingen; } /** * @return the feed */ public Feed getFeed() { return feed; } /** * @param feed the feed to set */ public void setFeed(Feed feed) { this.feed = feed; } /** * @return the summary */ public String getSummary() { return summary; } /** * @param summary the summary to set */ public void setSummary(String summary) { this.summary = summary; } }
14037_0
package eu.theunitry.fabula.levels; import eu.theunitry.fabula.UNGameEngine.graphics.UNGameScreen; import eu.theunitry.fabula.UNGameEngine.graphics.UNColor; import eu.theunitry.fabula.UNGameEngine.graphics.UNLevel; import eu.theunitry.fabula.UNGameEngine.graphics.UNGraphicsObject; import eu.theunitry.fabula.UNGameEngine.launcher.UNLauncher; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Random; /** * Level 12 * Jeroen Bronkhorst */ public class Level12 extends UNLevel { private Timer timer; private UNGraphicsObject cage; private ArrayList<UNGraphicsObject> monkeys_white, monkeys_brown; private JButton button; private int need, touch; private UNColor color; private String lastHelp; /** * Level 12 * @param gameScreen * @param hudEnabled */ public Level12(UNGameScreen gameScreen, boolean hudEnabled) { super(gameScreen, hudEnabled); this.need = 3 + new Random().nextInt(5); this.setQuestion("Stop de aapjes in de kooi met een gewicht van " + need + " kilogram"); this.addHelp("Jammer! Je moet een totaal gewicht van " + need + " kilogram hebben"); this.addHelp("Helaas! Er moet een gewicht van " + need + " kilogram in de kooi zitten"); this.setHelp("Sleep de aapjes in de kooi"); this.setBackgroundImage(gameScreen.getBackgrounds().get("jungle")); this.setPlayerHasWon (false); this.lastHelp = getHelp(); this.monkeys_white = new ArrayList<UNGraphicsObject>(); this.monkeys_brown = new ArrayList<UNGraphicsObject>(); this.color = new UNColor(); this.cage = new UNGraphicsObject(gameScreen.getWindow().getFrame(), 35, 260, gameScreen.unResourceLoader.sprites.get("2:12:1"), false, 128, 128); for (int i = 0; i < 5; i++){ monkeys_white.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 150 + new Random().nextInt(360), 315 + new Random().nextInt(1), gameScreen.unResourceLoader.sprites.get("2:12:2:2"), true, 64, 64) ); } for (int i = 0; i < 5; i++){ monkeys_brown.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 150 + new Random().nextInt(360), 315 + new Random().nextInt(1), gameScreen.unResourceLoader.sprites.get("2:12:2:1"), true, 64, 64) ); } for (UNGraphicsObject monkey_white : monkeys_white) { addObject(monkey_white); } for (UNGraphicsObject monkey_brown : monkeys_brown) { addObject(monkey_brown); } this.addObject(cage); this.button = new JButton("Klaar"); this.setLayout(null); this.button.setBounds(618, 64, 150, 50); this.button.setBackground(new Color(51, 51, 51)); this.button.setFont(new Font("Minecraftia", Font.PLAIN, 15)); this.button.setForeground(Color.white); this.button.setOpaque(true); /** * Reset Default Styling */ this.button.setFocusPainted(false); this.button.setBorderPainted(false); button.addActionListener(e -> { if (button.getText().equals("Doorgaan")) { levelDone(12); } if (isHelperDoneTalking()) { if (hasPlayerWon()) { getHelper().setState(3); setHelp("Goed gedaan! Het past allemaal precies!"); for (UNGraphicsObject monkey_white : monkeys_white) { monkey_white.setClickable(false); } for (UNGraphicsObject monkey_brown : monkeys_brown) { monkey_brown.setClickable(false); } button.setText("Doorgaan"); } else { addMistake(); if (getMistakes() < 3) { getHelper().setState(4); while(lastHelp.equals(getHelp())) { setHelp(getHelpList().get(new Random().nextInt(getHelpList().size()))); } lastHelp = getHelp(); } else { getHelper().setState(4); if (touch < need) { setHelp("Jammer, je moest nog " + (need - touch) + " kilogram erbij doen. Want " + (need - touch) + " plus " + touch + " is " + need ); } else { setHelp("Jammer, je had er " + (touch - need) + " kilogram teveel bij gedaan. Want " + touch + " min " + (touch - need) + " is " + need ); } for (UNGraphicsObject monkey_white : monkeys_white) { monkey_white.setClickable(false); } for (UNGraphicsObject monkey_brown : monkeys_brown) { monkey_brown.setClickable(false); } button.setText("Doorgaan"); } } } }); this.getPanel().add(button); timer = new Timer(1, e -> { touch = 0; for (UNGraphicsObject monkey_white : monkeys_white) { if (monkey_white.getY() < 310 && !monkey_white.getMouseHold()) { monkey_white.setY(monkey_white.getY() + 1); } if(!monkey_white.getMouseHold() && cage.getHitbox().intersects(monkey_white.getHitbox())) { touch = touch + 2; } } for (UNGraphicsObject monkey_brown : monkeys_brown) { if (monkey_brown.getY() < 310 && !monkey_brown.getMouseHold()) { monkey_brown.setY(monkey_brown.getY() + 1); } if(!monkey_brown.getMouseHold() && cage.getHitbox().intersects(monkey_brown.getHitbox())) { touch = touch + 1; } } setPlayerHasWon(touch == need); }); timer.start(); } }
The-Unitry/fabula
Fabula/src/eu/theunitry/fabula/levels/Level12.java
1,662
/** * Level 12 * Jeroen Bronkhorst */
block_comment
nl
package eu.theunitry.fabula.levels; import eu.theunitry.fabula.UNGameEngine.graphics.UNGameScreen; import eu.theunitry.fabula.UNGameEngine.graphics.UNColor; import eu.theunitry.fabula.UNGameEngine.graphics.UNLevel; import eu.theunitry.fabula.UNGameEngine.graphics.UNGraphicsObject; import eu.theunitry.fabula.UNGameEngine.launcher.UNLauncher; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Random; /** * Level 12 <SUF>*/ public class Level12 extends UNLevel { private Timer timer; private UNGraphicsObject cage; private ArrayList<UNGraphicsObject> monkeys_white, monkeys_brown; private JButton button; private int need, touch; private UNColor color; private String lastHelp; /** * Level 12 * @param gameScreen * @param hudEnabled */ public Level12(UNGameScreen gameScreen, boolean hudEnabled) { super(gameScreen, hudEnabled); this.need = 3 + new Random().nextInt(5); this.setQuestion("Stop de aapjes in de kooi met een gewicht van " + need + " kilogram"); this.addHelp("Jammer! Je moet een totaal gewicht van " + need + " kilogram hebben"); this.addHelp("Helaas! Er moet een gewicht van " + need + " kilogram in de kooi zitten"); this.setHelp("Sleep de aapjes in de kooi"); this.setBackgroundImage(gameScreen.getBackgrounds().get("jungle")); this.setPlayerHasWon (false); this.lastHelp = getHelp(); this.monkeys_white = new ArrayList<UNGraphicsObject>(); this.monkeys_brown = new ArrayList<UNGraphicsObject>(); this.color = new UNColor(); this.cage = new UNGraphicsObject(gameScreen.getWindow().getFrame(), 35, 260, gameScreen.unResourceLoader.sprites.get("2:12:1"), false, 128, 128); for (int i = 0; i < 5; i++){ monkeys_white.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 150 + new Random().nextInt(360), 315 + new Random().nextInt(1), gameScreen.unResourceLoader.sprites.get("2:12:2:2"), true, 64, 64) ); } for (int i = 0; i < 5; i++){ monkeys_brown.add(new UNGraphicsObject(gameScreen.getWindow().getFrame(), 150 + new Random().nextInt(360), 315 + new Random().nextInt(1), gameScreen.unResourceLoader.sprites.get("2:12:2:1"), true, 64, 64) ); } for (UNGraphicsObject monkey_white : monkeys_white) { addObject(monkey_white); } for (UNGraphicsObject monkey_brown : monkeys_brown) { addObject(monkey_brown); } this.addObject(cage); this.button = new JButton("Klaar"); this.setLayout(null); this.button.setBounds(618, 64, 150, 50); this.button.setBackground(new Color(51, 51, 51)); this.button.setFont(new Font("Minecraftia", Font.PLAIN, 15)); this.button.setForeground(Color.white); this.button.setOpaque(true); /** * Reset Default Styling */ this.button.setFocusPainted(false); this.button.setBorderPainted(false); button.addActionListener(e -> { if (button.getText().equals("Doorgaan")) { levelDone(12); } if (isHelperDoneTalking()) { if (hasPlayerWon()) { getHelper().setState(3); setHelp("Goed gedaan! Het past allemaal precies!"); for (UNGraphicsObject monkey_white : monkeys_white) { monkey_white.setClickable(false); } for (UNGraphicsObject monkey_brown : monkeys_brown) { monkey_brown.setClickable(false); } button.setText("Doorgaan"); } else { addMistake(); if (getMistakes() < 3) { getHelper().setState(4); while(lastHelp.equals(getHelp())) { setHelp(getHelpList().get(new Random().nextInt(getHelpList().size()))); } lastHelp = getHelp(); } else { getHelper().setState(4); if (touch < need) { setHelp("Jammer, je moest nog " + (need - touch) + " kilogram erbij doen. Want " + (need - touch) + " plus " + touch + " is " + need ); } else { setHelp("Jammer, je had er " + (touch - need) + " kilogram teveel bij gedaan. Want " + touch + " min " + (touch - need) + " is " + need ); } for (UNGraphicsObject monkey_white : monkeys_white) { monkey_white.setClickable(false); } for (UNGraphicsObject monkey_brown : monkeys_brown) { monkey_brown.setClickable(false); } button.setText("Doorgaan"); } } } }); this.getPanel().add(button); timer = new Timer(1, e -> { touch = 0; for (UNGraphicsObject monkey_white : monkeys_white) { if (monkey_white.getY() < 310 && !monkey_white.getMouseHold()) { monkey_white.setY(monkey_white.getY() + 1); } if(!monkey_white.getMouseHold() && cage.getHitbox().intersects(monkey_white.getHitbox())) { touch = touch + 2; } } for (UNGraphicsObject monkey_brown : monkeys_brown) { if (monkey_brown.getY() < 310 && !monkey_brown.getMouseHold()) { monkey_brown.setY(monkey_brown.getY() + 1); } if(!monkey_brown.getMouseHold() && cage.getHitbox().intersects(monkey_brown.getHitbox())) { touch = touch + 1; } } setPlayerHasWon(touch == need); }); timer.start(); } }
128162_0
package nl.knaw.huc.di.tag.treegrammar; /* * Hier schetsen we eerst wat uit... * Ik wil een stukje code die stax parse events gooit en verwerkt. */ import nl.knaw.huc.di.tag.treegrammar.nodes.Node; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; class ValidationTest { private static final Logger LOG = LoggerFactory.getLogger(ValidationTest.class); @Test void testXMLParses() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(defaultTransitionRules()); validator.parse("<root><markup>tekst</markup></root>"); String expected = "root\n" + "| markup\n" + "| | \"tekst\""; assertTreeVisualisation(validator, expected); } @Test void testXMLDoesNotParse1() { XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(defaultTransitionRules()); try { validator.parse("<root><markup>tekst and <b>more</b> markup</markup></root>"); fail("Expected an exception"); } catch (Exception e) { assertThat(e).hasMessage("@1,27: Unexpected node: b"); } } @Test void testXMLDoesNotParse2() { XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(defaultTransitionRules()); try { validator.parse("<root>plain tekst and <markup>marked-up tekst</markup></root>"); fail("Expected an exception"); } catch (Exception e) { assertThat(e).hasMessage("@1,23: No match: expected markup, but got \"plain tekst and \""); } } private List<TransitionRule> defaultTransitionRules() { final List<TransitionRule> defaultTransitionRules = new ArrayList<>(); defaultTransitionRules.add(parseTransitionRule("# => root[MARKUP]")); defaultTransitionRules.add(parseTransitionRule("MARKUP => markup[_]")); return defaultTransitionRules; } @Test void testXMLParses2() throws XMLStreamException { String[] ruleStrings = { "# => person[NAME]", "NAME => name[FIRST LAST]", "FIRST => first[_]", "LAST => last[_]" }; final List<TransitionRule> transitionRules = stream(ruleStrings) .map(this::parseTransitionRule) .collect(toList()); XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(transitionRules); validator.parse("<person>" + "<name>" + "<first>John</first>" + "<last>Doe</last>" + "</name>" + "</person>"); String expected = "person\n" + "| name\n" + "| | first\n" + "| | | \"John\"\n" + "| | last\n" + "| | | \"Doe\""; assertTreeVisualisation(validator, expected); } private List<TransitionRule> getTransitionRulesWithChoice() { String[] ruleStrings = { "# => artist[NAME]", "NAME => name[({FIRST LAST}|ARTISTNAME)]", "FIRST => first[_]", "LAST => last[_]", "ARTISTNAME => artistname[_]" }; String tgsScript = String.join("\n", ruleStrings); List<TransitionRule> transitionRules = new TransitionRuleSetFactory().fromTGS(tgsScript); LOG.info("transitionrules={}", transitionRules); return transitionRules; } @Test void testChoiceForNonTerminal() throws XMLStreamException { List<TransitionRule> transitionRules = getTransitionRulesWithChoice(); XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(transitionRules); validator.parse("<artist>" + "<name>" + "<first>John</first>" + "<last>Doe</last>" + "</name>" + "</artist>"); String expected = "artist\n" + "| name\n" + "| | first\n" + "| | | \"John\"\n" + "| | last\n" + "| | | \"Doe\""; LOG.info("transitionrules={}", transitionRules); assertTreeVisualisation(validator, expected); } @Test void testChoiceForNonTerminal2() throws XMLStreamException { List<TransitionRule> transitionRules = getTransitionRulesWithChoice(); XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(transitionRules); validator.parse("<artist>" + "<name>" + "<artistname>The JohnDoes</artistname>" + "</name>" + "</artist>"); String expected2 = "artist\n" + "| name\n" + "| | artistname\n" + "| | | \"The JohnDoes\""; assertTreeVisualisation(validator, expected2); } private XMLValidatorUsingTreeGrammars zeroOrOneElementsValidator() { String[] ruleStrings = { "# => elements[ELEMENT?]", "ELEMENT => element[_]" }; return validator(ruleStrings); } @Test void testZeroOrOneRuleWithValidInput0() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrOneElementsValidator(); validator.parse("<elements></elements>"); String expected = "elements"; assertTreeVisualisation(validator, expected); } @Test void testZeroOrOneRuleWithValidInput1() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrOneElementsValidator(); validator.parse("<elements><element>Au</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\""; assertTreeVisualisation(validator, expected); } @Test void testZeroOrOneRuleWithInvalidInput() { XMLValidatorUsingTreeGrammars validator = zeroOrOneElementsValidator(); try { validator.parse("<elements><element>Au</element><element>Pt</element></elements>"); fail("Expected an exception"); } catch (Exception e) { assertThat(e).hasMessage("@1,40: Unexpected node: element"); } } private XMLValidatorUsingTreeGrammars zeroOrMoreElementsValidator() { String[] ruleStrings = { "# => elements[ELEMENT*]", "ELEMENT => element[_]" }; return validator(ruleStrings); } @Test void testZeroOrMoreRuleWithValidInput0() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrMoreElementsValidator(); validator.parse("<elements></elements>"); String expected = "elements"; assertTreeVisualisation(validator, expected); } @Test void testZeroOrMoreRuleWithValidInput1() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrMoreElementsValidator(); validator.parse("<elements><element>Au</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\""; assertTreeVisualisation(validator, expected); } @Test void testZeroOrMoreRuleWithValidInput2() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrMoreElementsValidator(); validator.parse("<elements><element>Au</element><element>Pt</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\"\n" + "| element\n" + "| | \"Pt\""; assertTreeVisualisation(validator, expected); } private XMLValidatorUsingTreeGrammars oneOrMoreElementsValidator() { String[] ruleStrings = { "# => elements[ELEMENT+]", "ELEMENT => element[_]" }; return validator(ruleStrings); } @Test void testOneOrMoreRuleWithValidInput1() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = oneOrMoreElementsValidator(); validator.parse("<elements><element>Au</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\""; assertTreeVisualisation(validator, expected); } @Test void testOneOrMoreRuleWithValidInput2() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = oneOrMoreElementsValidator(); validator.parse("<elements><element>Au</element><element>Pt</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\"\n" + "| element\n" + "| | \"Pt\""; assertTreeVisualisation(validator, expected); } @Test void testOneOrMoreRuleWithInvalidInput() { XMLValidatorUsingTreeGrammars validator = oneOrMoreElementsValidator(); try { validator.parse("<elements></elements>"); fail("Expected an exception"); } catch (Exception e) { assertThat(e).hasMessage("ELEMENT* should have at least one NonTerminal, but has none."); } } private void assertTreeVisualisation(final XMLValidatorUsingTreeGrammars validator, final String expected) { Tree<Node> tree = validator.getTree(); String asText = TreeVisualizer.asText(tree); LOG.info("\n{}", asText); assertThat(asText).isEqualTo(expected); String sExpression = TreeVisualizer.asSExpression(tree, false); LOG.info("\ns-expression={}", sExpression); } private TransitionRule parseTransitionRule(final String input) { return new TransitionRuleSetFactory().fromTGS(input).get(0); } private XMLValidatorUsingTreeGrammars validator(final String[] ruleStrings) { String tgsScript = String.join("\n", ruleStrings); List<TransitionRule> transitionRules = new TransitionRuleSetFactory().fromTGS(tgsScript); return new XMLValidatorUsingTreeGrammars(transitionRules); } }
HuygensING/treegrammar
src/test/java/nl/knaw/huc/di/tag/treegrammar/ValidationTest.java
2,586
/* * Hier schetsen we eerst wat uit... * Ik wil een stukje code die stax parse events gooit en verwerkt. */
block_comment
nl
package nl.knaw.huc.di.tag.treegrammar; /* * Hier schetsen we<SUF>*/ import nl.knaw.huc.di.tag.treegrammar.nodes.Node; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; class ValidationTest { private static final Logger LOG = LoggerFactory.getLogger(ValidationTest.class); @Test void testXMLParses() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(defaultTransitionRules()); validator.parse("<root><markup>tekst</markup></root>"); String expected = "root\n" + "| markup\n" + "| | \"tekst\""; assertTreeVisualisation(validator, expected); } @Test void testXMLDoesNotParse1() { XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(defaultTransitionRules()); try { validator.parse("<root><markup>tekst and <b>more</b> markup</markup></root>"); fail("Expected an exception"); } catch (Exception e) { assertThat(e).hasMessage("@1,27: Unexpected node: b"); } } @Test void testXMLDoesNotParse2() { XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(defaultTransitionRules()); try { validator.parse("<root>plain tekst and <markup>marked-up tekst</markup></root>"); fail("Expected an exception"); } catch (Exception e) { assertThat(e).hasMessage("@1,23: No match: expected markup, but got \"plain tekst and \""); } } private List<TransitionRule> defaultTransitionRules() { final List<TransitionRule> defaultTransitionRules = new ArrayList<>(); defaultTransitionRules.add(parseTransitionRule("# => root[MARKUP]")); defaultTransitionRules.add(parseTransitionRule("MARKUP => markup[_]")); return defaultTransitionRules; } @Test void testXMLParses2() throws XMLStreamException { String[] ruleStrings = { "# => person[NAME]", "NAME => name[FIRST LAST]", "FIRST => first[_]", "LAST => last[_]" }; final List<TransitionRule> transitionRules = stream(ruleStrings) .map(this::parseTransitionRule) .collect(toList()); XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(transitionRules); validator.parse("<person>" + "<name>" + "<first>John</first>" + "<last>Doe</last>" + "</name>" + "</person>"); String expected = "person\n" + "| name\n" + "| | first\n" + "| | | \"John\"\n" + "| | last\n" + "| | | \"Doe\""; assertTreeVisualisation(validator, expected); } private List<TransitionRule> getTransitionRulesWithChoice() { String[] ruleStrings = { "# => artist[NAME]", "NAME => name[({FIRST LAST}|ARTISTNAME)]", "FIRST => first[_]", "LAST => last[_]", "ARTISTNAME => artistname[_]" }; String tgsScript = String.join("\n", ruleStrings); List<TransitionRule> transitionRules = new TransitionRuleSetFactory().fromTGS(tgsScript); LOG.info("transitionrules={}", transitionRules); return transitionRules; } @Test void testChoiceForNonTerminal() throws XMLStreamException { List<TransitionRule> transitionRules = getTransitionRulesWithChoice(); XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(transitionRules); validator.parse("<artist>" + "<name>" + "<first>John</first>" + "<last>Doe</last>" + "</name>" + "</artist>"); String expected = "artist\n" + "| name\n" + "| | first\n" + "| | | \"John\"\n" + "| | last\n" + "| | | \"Doe\""; LOG.info("transitionrules={}", transitionRules); assertTreeVisualisation(validator, expected); } @Test void testChoiceForNonTerminal2() throws XMLStreamException { List<TransitionRule> transitionRules = getTransitionRulesWithChoice(); XMLValidatorUsingTreeGrammars validator = new XMLValidatorUsingTreeGrammars(transitionRules); validator.parse("<artist>" + "<name>" + "<artistname>The JohnDoes</artistname>" + "</name>" + "</artist>"); String expected2 = "artist\n" + "| name\n" + "| | artistname\n" + "| | | \"The JohnDoes\""; assertTreeVisualisation(validator, expected2); } private XMLValidatorUsingTreeGrammars zeroOrOneElementsValidator() { String[] ruleStrings = { "# => elements[ELEMENT?]", "ELEMENT => element[_]" }; return validator(ruleStrings); } @Test void testZeroOrOneRuleWithValidInput0() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrOneElementsValidator(); validator.parse("<elements></elements>"); String expected = "elements"; assertTreeVisualisation(validator, expected); } @Test void testZeroOrOneRuleWithValidInput1() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrOneElementsValidator(); validator.parse("<elements><element>Au</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\""; assertTreeVisualisation(validator, expected); } @Test void testZeroOrOneRuleWithInvalidInput() { XMLValidatorUsingTreeGrammars validator = zeroOrOneElementsValidator(); try { validator.parse("<elements><element>Au</element><element>Pt</element></elements>"); fail("Expected an exception"); } catch (Exception e) { assertThat(e).hasMessage("@1,40: Unexpected node: element"); } } private XMLValidatorUsingTreeGrammars zeroOrMoreElementsValidator() { String[] ruleStrings = { "# => elements[ELEMENT*]", "ELEMENT => element[_]" }; return validator(ruleStrings); } @Test void testZeroOrMoreRuleWithValidInput0() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrMoreElementsValidator(); validator.parse("<elements></elements>"); String expected = "elements"; assertTreeVisualisation(validator, expected); } @Test void testZeroOrMoreRuleWithValidInput1() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrMoreElementsValidator(); validator.parse("<elements><element>Au</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\""; assertTreeVisualisation(validator, expected); } @Test void testZeroOrMoreRuleWithValidInput2() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = zeroOrMoreElementsValidator(); validator.parse("<elements><element>Au</element><element>Pt</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\"\n" + "| element\n" + "| | \"Pt\""; assertTreeVisualisation(validator, expected); } private XMLValidatorUsingTreeGrammars oneOrMoreElementsValidator() { String[] ruleStrings = { "# => elements[ELEMENT+]", "ELEMENT => element[_]" }; return validator(ruleStrings); } @Test void testOneOrMoreRuleWithValidInput1() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = oneOrMoreElementsValidator(); validator.parse("<elements><element>Au</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\""; assertTreeVisualisation(validator, expected); } @Test void testOneOrMoreRuleWithValidInput2() throws XMLStreamException { XMLValidatorUsingTreeGrammars validator = oneOrMoreElementsValidator(); validator.parse("<elements><element>Au</element><element>Pt</element></elements>"); String expected = "elements\n" + "| element\n" + "| | \"Au\"\n" + "| element\n" + "| | \"Pt\""; assertTreeVisualisation(validator, expected); } @Test void testOneOrMoreRuleWithInvalidInput() { XMLValidatorUsingTreeGrammars validator = oneOrMoreElementsValidator(); try { validator.parse("<elements></elements>"); fail("Expected an exception"); } catch (Exception e) { assertThat(e).hasMessage("ELEMENT* should have at least one NonTerminal, but has none."); } } private void assertTreeVisualisation(final XMLValidatorUsingTreeGrammars validator, final String expected) { Tree<Node> tree = validator.getTree(); String asText = TreeVisualizer.asText(tree); LOG.info("\n{}", asText); assertThat(asText).isEqualTo(expected); String sExpression = TreeVisualizer.asSExpression(tree, false); LOG.info("\ns-expression={}", sExpression); } private TransitionRule parseTransitionRule(final String input) { return new TransitionRuleSetFactory().fromTGS(input).get(0); } private XMLValidatorUsingTreeGrammars validator(final String[] ruleStrings) { String tgsScript = String.join("\n", ruleStrings); List<TransitionRule> transitionRules = new TransitionRuleSetFactory().fromTGS(tgsScript); return new XMLValidatorUsingTreeGrammars(transitionRules); } }
31699_14
package ui.swing; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List; public class CelltPane extends JPanel { private Color defaultBackground; int row; int col; public boolean cliked; private static TestPane testPane; private CelltPane searchPane; public static boolean hasWinner = false; private static int counterVertical= 0 ; private static int counterHorizontal= 0 ; private static char role;// role 'v' or 'h' public static boolean vertical =true ; public static boolean horizontal =false; // public static List<LinkedHashMap<Position,Position>> possiblesMovesVerticale; // public static List<LinkedHashMap<Position,Position>> possiblesMovesHorizontal; public static List<CelltPane> possiblesMovesVerticale; public static List<CelltPane> possiblesMovesHorizontal; public CelltPane(TestPane testPane,int row , int col , boolean cliked){ possiblesMovesVerticale=new ArrayList<>(); possiblesMovesHorizontal = new ArrayList<>(); this.col = col; this.row = row; CelltPane.testPane =testPane; this.cliked=cliked; role='v'; game(); } // public void game(){ initializeMouseListener(); } public void initializeMouseListener() { addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); defaultBackground = getBackground(); //searchPane = searchAdj(row,col); System.out.println("row : "+row+" , col : "+col); if(role=='v'){ if(!isCliked() && !searchPane.isCliked()){ searchPane.cliked=true; setCliked(true); searchPane.setBackground(Color.blue); searchPane.cliked=true; setCliked(true); setBackground(Color.blue); role='h'; }else{ System.out.println("impossible de colorer"); } }else{ //min max if(!isCliked() && !searchPane.isCliked()){ searchPane.cliked=true; setCliked(true); searchPane.setBackground(Color.GREEN); searchPane.cliked=true; setCliked(true); setBackground(Color.GREEN); role='v'; }else{ System.out.println("impossible de colorer"); } } } // minmax(); @Override public void mouseEntered(MouseEvent e) { super.mouseEntered(e); defaultBackground = getBackground(); System.out.println(defaultBackground); if(counterVertical==0 || counterHorizontal==0){ checkWiner(); } if(role=='v'){ searchPane = searchAdjVertical(row,col); // chercher board adj vertical if(searchPane==null){ System.out.println("perdooonaaa is clicked"); }else{ if(!isCliked() && !searchPane.isCliked()){ searchPane.setBackground(Color.blue); setBackground(Color.blue); } else if (!isCliked() && searchPane.isCliked()) { System.out.println("impossible de colorer"); } else { System.out.println("impossible de colorer"); } } // int res = minmax(testPane,10,false); // System.out.println("resultttttttttttt : "+res); //minimaxMove(); }else { searchPane = searchAdjHorizontal(row,col); // chercher board adj horizontal if(searchPane==null){ System.out.println("perdooonaaa is clicked"); }else{ if(!isCliked() && !searchPane.isCliked()){ searchPane.setBackground(Color.GREEN); setBackground(Color.GREEN); }else{ System.out.println("impossible de colorer"); } } } } @Override public void mouseExited(MouseEvent e) { super.mouseExited(e); if(searchPane==null){ System.out.println("on ne peut pas exit car nous avons pas entred !"); }else{ if(!isCliked() && !searchPane.isCliked()){ searchPane.setBackground(defaultBackground); setBackground(defaultBackground); } } } }); } @Override public Dimension getPreferredSize(){ return new Dimension(100,100); } /** * searchAdjVertical * */ public static CelltPane searchAdjVertical(int row, int col){ Map<CelltPane,Position> map = TestPane.getMapCellPan(); // gestion Exceptions de manier statique : for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { // chercher la valeur adjacent vertical +1 if(entry.getValue().getX()==row+1 && entry.getValue().getY()==col){ if(!entry.getKey().isCliked()){ System.out.println("@@@@@ Valeur x: " + entry.getValue().getX()+" Valeur Y: "+entry.getValue().getY()); return entry.getKey(); } /** else { // si la cellul +1 isCliked on va verifier la cellul -1 for (Map.Entry<CelltPane, Position> item : map.entrySet()){ if(item.getValue().getX()==row-1 && item.getValue().getY()==col){ if(!item.getKey().isCliked()){ //counterVertical--; return item.getKey(); } } } }*/ } } return null; } public static CelltPane searchAdjHorizontal(int row, int col){ Map<CelltPane,Position> map = TestPane.getMapCellPan(); for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { if(entry.getValue().getX()==row && entry.getValue().getY()==col+1){ if(!entry.getKey().isCliked()){ System.out.println("@@@@@ Valeur x: " + entry.getValue().getX()+" Valeur Y: "+entry.getValue().getY()); return entry.getKey(); } /** else{ for (Map.Entry<CelltPane, Position> item : map.entrySet()){ if(item.getValue().getX()==row && item.getValue().getY()==col-1){ if(!item.getKey().isCliked()){ counterHorizontal--; return item.getKey(); } } } }*/ } } return null; } public static void getPossibleMouvesVertical(){ possiblesMovesVerticale.clear(); counterVertical=0; int c = 0; Map<CelltPane,Position> map = TestPane.getMapCellPan(); for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { if(!entry.getKey().cliked){ if(searchAdjVertical(entry.getValue().getX(),entry.getValue().getY())!=null){ c++; CelltPane adjacentVerticale = searchAdjVertical(entry.getValue().getX(),entry.getValue().getY()); System.out.println(entry.getValue().getX()+" , "+entry.getValue().getY()); System.out.println(adjacentVerticale.row+" , "+adjacentVerticale.col); possiblesMovesVerticale.add(entry.getKey()); //entry.getKey().setBackground(Color.red); //adjacentVerticale.setBackground(Color.yellow); System.out.println("=======================: "+c); counterVertical++; } } } } public static void getPossibleMouvesHorizontal(){ possiblesMovesHorizontal.clear(); counterHorizontal=0; Map<CelltPane,Position> map = TestPane.getMapCellPan(); for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { if(!entry.getKey().cliked){ if(searchAdjHorizontal(entry.getValue().getX(),entry.getValue().getY())!=null){ CelltPane adjacentHorizontal = searchAdjHorizontal(entry.getValue().getX(),entry.getValue().getY()); possiblesMovesHorizontal.add(entry.getKey()); counterHorizontal++; } } } } public static int checkWiner(){ int cellVide = 0; // 2 : v wen, -2 : h wen , 0 , Tie 1 Map<CelltPane,Position> map = TestPane.getMapCellPan(); if(counterHorizontal==0 && counterVertical==0){ for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { if(!entry.getKey().isCliked()){ cellVide++; } } if(cellVide==0){ System.out.println("il n'y a pas de gagnant"); return 0; }else{ if(role=='v'){ System.out.println("Horizontal gagnant !"); return 2; } else if (role=='h'){ System.out.println("Vertical gagnant !"); return -2; } } } else if (counterHorizontal!=0 && counterVertical==0) { System.out.println("Vertical gagnant !"); // h is wen return -2; } else if (counterHorizontal==0 && counterVertical!=0) { System.out.println("Vertical gagnant !"); // v is wen return 2; } return 0; } public void setCliked(boolean cliked) { this.cliked = cliked; getPossibleMouvesHorizontal(); getPossibleMouvesVertical(); System.out.println("counter horizontal -> ---- "+counterHorizontal); System.out.println("counter vertical -> ---- "+counterVertical); } public boolean isCliked() { return cliked; } // MINIMAX static int minmax(TestPane pane, int depth, boolean isMaximizing) { int result = checkWiner(); if (result != 1 || depth == 10) { return result; } if (isMaximizing) { int maxScore = Integer.MIN_VALUE; getPossibleMouvesVertical(); List<CelltPane> listVertical = possiblesMovesVerticale; Iterator<CelltPane> itr = listVertical.listIterator(); while (itr.hasNext()){ if(!itr.next().isCliked()){ CelltPane adjVertecal=searchAdjVertical(itr.next().row,itr.next().col); adjVertecal.setCliked(true); itr.next().setCliked(true); int score =minmax(pane,depth+1,false); itr.next().setCliked(false); adjVertecal.setCliked(false); maxScore = Math.max(score, maxScore); } } return maxScore; } else { int minScore = Integer.MAX_VALUE; getPossibleMouvesHorizontal(); List<CelltPane> listVertical = possiblesMovesHorizontal; Iterator<CelltPane> itr = listVertical.listIterator(); while (itr.hasNext()){ if(!itr.next().isCliked()){ CelltPane adjVertecal=searchAdjHorizontal(itr.next().row,itr.next().col); adjVertecal.setCliked(true); itr.next().setCliked(true); int score =minmax(pane,depth+1,true); itr.next().setCliked(false); adjVertecal.setCliked(false); minScore = Math.min(score, minScore); } } return minScore; } } static int[] findBestMove(TestPane pane) { int bestVal = Integer.MIN_VALUE; int[] bestMove = {-1, -1}; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // logique de max getPossibleMouvesVertical(); List<CelltPane> listVertical = possiblesMovesVerticale; Iterator<CelltPane> itr = listVertical.listIterator(); while (itr.hasNext()){ if(!itr.next().isCliked()){ CelltPane adjVertecal=searchAdjVertical(itr.next().row,itr.next().col); adjVertecal.setCliked(true); itr.next().setCliked(true); int moveVal =minmax(pane,0,false); itr.next().setCliked(false); adjVertecal.setCliked(false); if(moveVal > bestVal){ bestMove[0]=itr.next().row; bestMove[1]=itr.next().col; } } } //============= } } return bestMove; } }
mohammedelbakkali/Domineering
src/ui/swing/CelltPane.java
3,255
// h is wen
line_comment
nl
package ui.swing; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List; public class CelltPane extends JPanel { private Color defaultBackground; int row; int col; public boolean cliked; private static TestPane testPane; private CelltPane searchPane; public static boolean hasWinner = false; private static int counterVertical= 0 ; private static int counterHorizontal= 0 ; private static char role;// role 'v' or 'h' public static boolean vertical =true ; public static boolean horizontal =false; // public static List<LinkedHashMap<Position,Position>> possiblesMovesVerticale; // public static List<LinkedHashMap<Position,Position>> possiblesMovesHorizontal; public static List<CelltPane> possiblesMovesVerticale; public static List<CelltPane> possiblesMovesHorizontal; public CelltPane(TestPane testPane,int row , int col , boolean cliked){ possiblesMovesVerticale=new ArrayList<>(); possiblesMovesHorizontal = new ArrayList<>(); this.col = col; this.row = row; CelltPane.testPane =testPane; this.cliked=cliked; role='v'; game(); } // public void game(){ initializeMouseListener(); } public void initializeMouseListener() { addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); defaultBackground = getBackground(); //searchPane = searchAdj(row,col); System.out.println("row : "+row+" , col : "+col); if(role=='v'){ if(!isCliked() && !searchPane.isCliked()){ searchPane.cliked=true; setCliked(true); searchPane.setBackground(Color.blue); searchPane.cliked=true; setCliked(true); setBackground(Color.blue); role='h'; }else{ System.out.println("impossible de colorer"); } }else{ //min max if(!isCliked() && !searchPane.isCliked()){ searchPane.cliked=true; setCliked(true); searchPane.setBackground(Color.GREEN); searchPane.cliked=true; setCliked(true); setBackground(Color.GREEN); role='v'; }else{ System.out.println("impossible de colorer"); } } } // minmax(); @Override public void mouseEntered(MouseEvent e) { super.mouseEntered(e); defaultBackground = getBackground(); System.out.println(defaultBackground); if(counterVertical==0 || counterHorizontal==0){ checkWiner(); } if(role=='v'){ searchPane = searchAdjVertical(row,col); // chercher board adj vertical if(searchPane==null){ System.out.println("perdooonaaa is clicked"); }else{ if(!isCliked() && !searchPane.isCliked()){ searchPane.setBackground(Color.blue); setBackground(Color.blue); } else if (!isCliked() && searchPane.isCliked()) { System.out.println("impossible de colorer"); } else { System.out.println("impossible de colorer"); } } // int res = minmax(testPane,10,false); // System.out.println("resultttttttttttt : "+res); //minimaxMove(); }else { searchPane = searchAdjHorizontal(row,col); // chercher board adj horizontal if(searchPane==null){ System.out.println("perdooonaaa is clicked"); }else{ if(!isCliked() && !searchPane.isCliked()){ searchPane.setBackground(Color.GREEN); setBackground(Color.GREEN); }else{ System.out.println("impossible de colorer"); } } } } @Override public void mouseExited(MouseEvent e) { super.mouseExited(e); if(searchPane==null){ System.out.println("on ne peut pas exit car nous avons pas entred !"); }else{ if(!isCliked() && !searchPane.isCliked()){ searchPane.setBackground(defaultBackground); setBackground(defaultBackground); } } } }); } @Override public Dimension getPreferredSize(){ return new Dimension(100,100); } /** * searchAdjVertical * */ public static CelltPane searchAdjVertical(int row, int col){ Map<CelltPane,Position> map = TestPane.getMapCellPan(); // gestion Exceptions de manier statique : for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { // chercher la valeur adjacent vertical +1 if(entry.getValue().getX()==row+1 && entry.getValue().getY()==col){ if(!entry.getKey().isCliked()){ System.out.println("@@@@@ Valeur x: " + entry.getValue().getX()+" Valeur Y: "+entry.getValue().getY()); return entry.getKey(); } /** else { // si la cellul +1 isCliked on va verifier la cellul -1 for (Map.Entry<CelltPane, Position> item : map.entrySet()){ if(item.getValue().getX()==row-1 && item.getValue().getY()==col){ if(!item.getKey().isCliked()){ //counterVertical--; return item.getKey(); } } } }*/ } } return null; } public static CelltPane searchAdjHorizontal(int row, int col){ Map<CelltPane,Position> map = TestPane.getMapCellPan(); for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { if(entry.getValue().getX()==row && entry.getValue().getY()==col+1){ if(!entry.getKey().isCliked()){ System.out.println("@@@@@ Valeur x: " + entry.getValue().getX()+" Valeur Y: "+entry.getValue().getY()); return entry.getKey(); } /** else{ for (Map.Entry<CelltPane, Position> item : map.entrySet()){ if(item.getValue().getX()==row && item.getValue().getY()==col-1){ if(!item.getKey().isCliked()){ counterHorizontal--; return item.getKey(); } } } }*/ } } return null; } public static void getPossibleMouvesVertical(){ possiblesMovesVerticale.clear(); counterVertical=0; int c = 0; Map<CelltPane,Position> map = TestPane.getMapCellPan(); for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { if(!entry.getKey().cliked){ if(searchAdjVertical(entry.getValue().getX(),entry.getValue().getY())!=null){ c++; CelltPane adjacentVerticale = searchAdjVertical(entry.getValue().getX(),entry.getValue().getY()); System.out.println(entry.getValue().getX()+" , "+entry.getValue().getY()); System.out.println(adjacentVerticale.row+" , "+adjacentVerticale.col); possiblesMovesVerticale.add(entry.getKey()); //entry.getKey().setBackground(Color.red); //adjacentVerticale.setBackground(Color.yellow); System.out.println("=======================: "+c); counterVertical++; } } } } public static void getPossibleMouvesHorizontal(){ possiblesMovesHorizontal.clear(); counterHorizontal=0; Map<CelltPane,Position> map = TestPane.getMapCellPan(); for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { if(!entry.getKey().cliked){ if(searchAdjHorizontal(entry.getValue().getX(),entry.getValue().getY())!=null){ CelltPane adjacentHorizontal = searchAdjHorizontal(entry.getValue().getX(),entry.getValue().getY()); possiblesMovesHorizontal.add(entry.getKey()); counterHorizontal++; } } } } public static int checkWiner(){ int cellVide = 0; // 2 : v wen, -2 : h wen , 0 , Tie 1 Map<CelltPane,Position> map = TestPane.getMapCellPan(); if(counterHorizontal==0 && counterVertical==0){ for (Map.Entry<CelltPane, Position> entry : map.entrySet()) { if(!entry.getKey().isCliked()){ cellVide++; } } if(cellVide==0){ System.out.println("il n'y a pas de gagnant"); return 0; }else{ if(role=='v'){ System.out.println("Horizontal gagnant !"); return 2; } else if (role=='h'){ System.out.println("Vertical gagnant !"); return -2; } } } else if (counterHorizontal!=0 && counterVertical==0) { System.out.println("Vertical gagnant !"); // h is<SUF> return -2; } else if (counterHorizontal==0 && counterVertical!=0) { System.out.println("Vertical gagnant !"); // v is wen return 2; } return 0; } public void setCliked(boolean cliked) { this.cliked = cliked; getPossibleMouvesHorizontal(); getPossibleMouvesVertical(); System.out.println("counter horizontal -> ---- "+counterHorizontal); System.out.println("counter vertical -> ---- "+counterVertical); } public boolean isCliked() { return cliked; } // MINIMAX static int minmax(TestPane pane, int depth, boolean isMaximizing) { int result = checkWiner(); if (result != 1 || depth == 10) { return result; } if (isMaximizing) { int maxScore = Integer.MIN_VALUE; getPossibleMouvesVertical(); List<CelltPane> listVertical = possiblesMovesVerticale; Iterator<CelltPane> itr = listVertical.listIterator(); while (itr.hasNext()){ if(!itr.next().isCliked()){ CelltPane adjVertecal=searchAdjVertical(itr.next().row,itr.next().col); adjVertecal.setCliked(true); itr.next().setCliked(true); int score =minmax(pane,depth+1,false); itr.next().setCliked(false); adjVertecal.setCliked(false); maxScore = Math.max(score, maxScore); } } return maxScore; } else { int minScore = Integer.MAX_VALUE; getPossibleMouvesHorizontal(); List<CelltPane> listVertical = possiblesMovesHorizontal; Iterator<CelltPane> itr = listVertical.listIterator(); while (itr.hasNext()){ if(!itr.next().isCliked()){ CelltPane adjVertecal=searchAdjHorizontal(itr.next().row,itr.next().col); adjVertecal.setCliked(true); itr.next().setCliked(true); int score =minmax(pane,depth+1,true); itr.next().setCliked(false); adjVertecal.setCliked(false); minScore = Math.min(score, minScore); } } return minScore; } } static int[] findBestMove(TestPane pane) { int bestVal = Integer.MIN_VALUE; int[] bestMove = {-1, -1}; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // logique de max getPossibleMouvesVertical(); List<CelltPane> listVertical = possiblesMovesVerticale; Iterator<CelltPane> itr = listVertical.listIterator(); while (itr.hasNext()){ if(!itr.next().isCliked()){ CelltPane adjVertecal=searchAdjVertical(itr.next().row,itr.next().col); adjVertecal.setCliked(true); itr.next().setCliked(true); int moveVal =minmax(pane,0,false); itr.next().setCliked(false); adjVertecal.setCliked(false); if(moveVal > bestVal){ bestMove[0]=itr.next().row; bestMove[1]=itr.next().col; } } } //============= } } return bestMove; } }
96974_1
/* * This file is part of the SavaPage project <https://www.savapage.org>. * Copyright (c) 2011-2020 Datraverse B.V. * Author: Rijk Ravestein. * * SPDX-FileCopyrightText: 2011-2020 Datraverse B.V. <[email protected]> * SPDX-License-Identifier: AGPL-3.0-or-later * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * For more information, please contact Datraverse B.V. at this * address: [email protected] */ package org.savapage.core.dao; import java.util.List; import org.savapage.core.dao.enums.DeviceTypeEnum; import org.savapage.core.jpa.Device; /** * * @author Rijk Ravestein * */ public interface DeviceDao extends GenericDao<Device> { /** * Field identifiers used for select and sort. */ enum Field { /** * Device name. */ NAME } /** * */ class ListFilter { private String containingText; private Boolean disabled; private DeviceTypeEnum deviceType; public String getContainingText() { return containingText; } public void setContainingText(String containingText) { this.containingText = containingText; } public Boolean getDisabled() { return disabled; } public void setDisabled(Boolean disabled) { this.disabled = disabled; } public DeviceTypeEnum getDeviceType() { return deviceType; } public void setDeviceType(DeviceTypeEnum deviceType) { this.deviceType = deviceType; } } /** * Counts the number of devices according to filter. * * @param filter * The filter. * @return The count. */ long getListCount(ListFilter filter); /** * Gets a chunk of devices. * * @param filter * The filter. * @param startPosition * The zero-based start position of the chunk related to the * total number of rows. If {@code null} the chunk starts with * the first row. * @param maxResults * The maximum number of rows in the chunk. If {@code null}, then * ALL (remaining rows) are returned. * @param orderBy * The sort field. * @param sortAscending * {@code true} when sorted ascending. * @return The chunk. */ List<Device> getListChunk(ListFilter filter, Integer startPosition, Integer maxResults, Field orderBy, boolean sortAscending); /** * Finds the {@link Device} by name, when not found null is returned. * * @param deviceName * The unique name of the Device. * @return The instance, or {@code null} when not found. */ Device findByName(String deviceName); /** * Reads the row from database, when not found null is returned. * * @param deviceName * The unique name of the Device. * @return The instance, or {@code null} when not found. */ /** * Finds the {@link Device} by host name and {@link DeviceTypeEnum}, when * not found null is returned. * * @param hostname * The host name. * @param deviceType * The {@link DeviceTypeEnum}. * @return The instance, or {@code null} when not found. */ Device findByHostDeviceType(String hostname, DeviceTypeEnum deviceType); /** * Creates or updates the attribute value of a Device. * * @param device * The Device. * @param key * The attribute key. * @param value * The attribute value. */ void writeAttribute(Device device, String key, String value); /** * Checks if {@link Device} is a {@link DeviceTypeEnum#CARD_READER} (this is * a convenience method: no database access). * * @param device * The {@link Device}. * @return {@code true} a card reader. */ boolean isCardReader(Device device); /** * Checks if {@link Device} is a {@link DeviceTypeEnum#TERMINAL} (this is a * convenience method: no database access). * * @param device * The {@link Device}. * @return {@code true} when a terminal. */ boolean isTerminal(Device device); /** * Checks if printers are defined to be accessed via this terminal (this is * a convenience method: no database access). * * @param device * The {@link Device}. * @return {@code true} when a printer or printer group is associated with * this terminal. */ boolean hasPrinterRestriction(Device device); }
PLanB2008/savapage-core
src/main/java/org/savapage/core/dao/DeviceDao.java
1,390
/** * * @author Rijk Ravestein * */
block_comment
nl
/* * This file is part of the SavaPage project <https://www.savapage.org>. * Copyright (c) 2011-2020 Datraverse B.V. * Author: Rijk Ravestein. * * SPDX-FileCopyrightText: 2011-2020 Datraverse B.V. <[email protected]> * SPDX-License-Identifier: AGPL-3.0-or-later * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * For more information, please contact Datraverse B.V. at this * address: [email protected] */ package org.savapage.core.dao; import java.util.List; import org.savapage.core.dao.enums.DeviceTypeEnum; import org.savapage.core.jpa.Device; /** * * @author Rijk Ravestein<SUF>*/ public interface DeviceDao extends GenericDao<Device> { /** * Field identifiers used for select and sort. */ enum Field { /** * Device name. */ NAME } /** * */ class ListFilter { private String containingText; private Boolean disabled; private DeviceTypeEnum deviceType; public String getContainingText() { return containingText; } public void setContainingText(String containingText) { this.containingText = containingText; } public Boolean getDisabled() { return disabled; } public void setDisabled(Boolean disabled) { this.disabled = disabled; } public DeviceTypeEnum getDeviceType() { return deviceType; } public void setDeviceType(DeviceTypeEnum deviceType) { this.deviceType = deviceType; } } /** * Counts the number of devices according to filter. * * @param filter * The filter. * @return The count. */ long getListCount(ListFilter filter); /** * Gets a chunk of devices. * * @param filter * The filter. * @param startPosition * The zero-based start position of the chunk related to the * total number of rows. If {@code null} the chunk starts with * the first row. * @param maxResults * The maximum number of rows in the chunk. If {@code null}, then * ALL (remaining rows) are returned. * @param orderBy * The sort field. * @param sortAscending * {@code true} when sorted ascending. * @return The chunk. */ List<Device> getListChunk(ListFilter filter, Integer startPosition, Integer maxResults, Field orderBy, boolean sortAscending); /** * Finds the {@link Device} by name, when not found null is returned. * * @param deviceName * The unique name of the Device. * @return The instance, or {@code null} when not found. */ Device findByName(String deviceName); /** * Reads the row from database, when not found null is returned. * * @param deviceName * The unique name of the Device. * @return The instance, or {@code null} when not found. */ /** * Finds the {@link Device} by host name and {@link DeviceTypeEnum}, when * not found null is returned. * * @param hostname * The host name. * @param deviceType * The {@link DeviceTypeEnum}. * @return The instance, or {@code null} when not found. */ Device findByHostDeviceType(String hostname, DeviceTypeEnum deviceType); /** * Creates or updates the attribute value of a Device. * * @param device * The Device. * @param key * The attribute key. * @param value * The attribute value. */ void writeAttribute(Device device, String key, String value); /** * Checks if {@link Device} is a {@link DeviceTypeEnum#CARD_READER} (this is * a convenience method: no database access). * * @param device * The {@link Device}. * @return {@code true} a card reader. */ boolean isCardReader(Device device); /** * Checks if {@link Device} is a {@link DeviceTypeEnum#TERMINAL} (this is a * convenience method: no database access). * * @param device * The {@link Device}. * @return {@code true} when a terminal. */ boolean isTerminal(Device device); /** * Checks if printers are defined to be accessed via this terminal (this is * a convenience method: no database access). * * @param device * The {@link Device}. * @return {@code true} when a printer or printer group is associated with * this terminal. */ boolean hasPrinterRestriction(Device device); }
14146_12
class Voorbeeld { public static void main(String[] args) { System.out.println("Hallo"); System.out.println("Wereld!"); int getal1; // Declaratie van een variabele van het type int getal1 = 9; // Initialisatie int getal2 = 14; int getal3, getal4; int getal5 = 7, getal6; // System.out.println(getal3); --> compiler error omdat getal3 niet geïnitialiseerd is // in een array krijgen alle entries een default waarde (0 bij int) // primitive types vs reference/object types // String (en Wrapper) zitten hier een beetje tussenin maar vallen onder reference types // Primitives: // Gehele getallen: byte, short, int, long // Kommagetallen: float, double // char // boolean: true, false Auto car = null; Auto auto = new Auto(); // De signature van een method is: aantal, type en volgorde van de parameters // Parameter vs argument: geen synoniem. // Parameter is altijd de declaratie van een variabele bij de definitie van de method, argument is reeds gedeclareerd. Voorbeeld jojo = new Voorbeeld(); jojo.uitproberen(4); System.out.println(optellen() * optellen()); } // Als je aantal, type of volgorde van een method verschilt, kun je overloaden: static void uitproberen() { System.out.println("Hoppakee"); } void uitproberen(int a) { System.out.println("Hoppakee"); } void uitproberen(String a) { System.out.println("Hoppakee"); } // Wanneer het return type van een method anders is dan void, // dan kun je de aanroep van de methode vervangen door datgene wat deze teruggeeft. static int optellen() { return 6; } } class Auto { // Access modifiers: private, protected, public, DEFAULT (impliciet) // Non-access modifiers: static, abstract, final protected static int carsAmount; String brand; static int getAmountOfCars() { return carsAmount; } String getBrand() { return this.brand; } }
michielpauw/ycbootcamp
Voorbeeld.java
611
// Wanneer het return type van een method anders is dan void,
line_comment
nl
class Voorbeeld { public static void main(String[] args) { System.out.println("Hallo"); System.out.println("Wereld!"); int getal1; // Declaratie van een variabele van het type int getal1 = 9; // Initialisatie int getal2 = 14; int getal3, getal4; int getal5 = 7, getal6; // System.out.println(getal3); --> compiler error omdat getal3 niet geïnitialiseerd is // in een array krijgen alle entries een default waarde (0 bij int) // primitive types vs reference/object types // String (en Wrapper) zitten hier een beetje tussenin maar vallen onder reference types // Primitives: // Gehele getallen: byte, short, int, long // Kommagetallen: float, double // char // boolean: true, false Auto car = null; Auto auto = new Auto(); // De signature van een method is: aantal, type en volgorde van de parameters // Parameter vs argument: geen synoniem. // Parameter is altijd de declaratie van een variabele bij de definitie van de method, argument is reeds gedeclareerd. Voorbeeld jojo = new Voorbeeld(); jojo.uitproberen(4); System.out.println(optellen() * optellen()); } // Als je aantal, type of volgorde van een method verschilt, kun je overloaden: static void uitproberen() { System.out.println("Hoppakee"); } void uitproberen(int a) { System.out.println("Hoppakee"); } void uitproberen(String a) { System.out.println("Hoppakee"); } // Wanneer het<SUF> // dan kun je de aanroep van de methode vervangen door datgene wat deze teruggeeft. static int optellen() { return 6; } } class Auto { // Access modifiers: private, protected, public, DEFAULT (impliciet) // Non-access modifiers: static, abstract, final protected static int carsAmount; String brand; static int getAmountOfCars() { return carsAmount; } String getBrand() { return this.brand; } }
30848_6
/*----------------------------------------------------------------------- * Copyright (C) 2001 Green Light District Team, Utrecht University * Copyright of the TC1 algorithm (C) Marco Wiering, Utrecht University * * This program (Green Light District) is free software. * You may redistribute it and/or modify it under the terms * of the GNU General Public License as published by * the Free Software Foundation (version 2 or later). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * See the documentation of Green Light District for further information. * * Changed to use Sarsa(0) with random decision instead of DP - S. Louring *------------------------------------------------------------------------*/ package com.github.cc007.trafficlights.algo.tlc; import com.github.cc007.trafficlights.*; import com.github.cc007.trafficlights.algo.tlc.*; import com.github.cc007.trafficlights.infra.*; import com.github.cc007.trafficlights.xml.*; import java.io.IOException; import java.util.*; /** * * This controller will decide it's Q values for the traffic lights according to * the traffic situation on the lane connected to the TrafficLight. It will * learn how to alter it's outcome by reinforcement learning. * * @author Arne K, Jilles V, Søren Louring * @version 1.1 */ public class SL2TLC extends TCRL implements InstantiationAssistant { protected Infrastructure infrastructure; protected TrafficLight[][] tls; protected Node[] allnodes; protected int num_nodes; protected ArrayList<CountEntry> count; //, p_table; protected float[][][][] q_table; //sign, pos, des, color (red=0, green=1) protected static float gamma = 0.95f; //Discount Factor; used to decrease the influence of previous V values, that's why: 0 < gamma < 1 protected static float random_chance = 0.01f; //A random gain setting is chosen instead of the on the TLC dictates with this chance protected static float alpha = 0.7f; protected final static boolean red = false, green = true; protected final static int green_index = 0, red_index = 1; protected final static String shortXMLName = "tlc-sl2"; private Random random_number; protected float time_step = 0; /** * The constructor for TL controllers * * @param The model being used. */ public SL2TLC(Infrastructure infra) throws InfraException { super(infra); Node[] nodes = infra.getAllNodes(); //Moet Edge zijn eigenlijk, alleen testSimModel knalt er dan op int num_nodes = nodes.length; count = new ArrayList<>(); int numSigns = infra.getAllInboundLanes().size(); q_table = new float[numSigns + 1][][][]; int num_specialnodes = infra.getNumSpecialNodes(); for (int i = 0; i < nodes.length; i++) { Node n = nodes[i]; DriveLane[] dls = n.getInboundLanes(); for (int j = 0; j < dls.length; j++) { DriveLane d = dls[j]; Sign s = d.getSign(); int id = s.getId(); int num_pos_on_dl = d.getCompleteLength(); q_table[id] = new float[num_pos_on_dl][][]; for (int k = 0; k < num_pos_on_dl; k++) { q_table[id][k] = new float[num_specialnodes][]; for (int l = 0; l < q_table[id][k].length; l++) { q_table[id][k][l] = new float[2]; q_table[id][k][l][0] = 0.0f; q_table[id][k][l][1] = 0.0f; //v_table[id][k][l]=0.0f; } } } } System.out.println("tl = " + numSigns); System.out.println("des = " + num_specialnodes); System.out.println("Alpha = " + alpha); random_number = new Random(GLDSim.seriesSeed[GLDSim.seriesSeedIndex]); } @Override public void reset() { for (int j = 0; j < q_table.length; j++) { if (q_table[j] != null) { for (int k = 0; k < q_table[j].length; k++) { if (q_table[j][k] != null) { for (int l = 0; l < q_table[j][k].length; l++) { if (q_table[j][k][l] != null) { q_table[j][k][l][0] = 0.0f; q_table[j][k][l][1] = 0.0f; } } } } } } System.out.println("Q table nulstillet."); } //Reset slut /** * Calculates how every traffic light should be switched Per node, per sign * the waiting roadusers are passed and per each roaduser the gain is * calculated. * * @param The TLDecision is a tuple consisting of a traffic light and a * reward (Q) value, for it to be green * @see gld.algo.tlc.TLDecision */ @Override public TLDecision[][] decideTLs() { int num_dec; int num_tld = tld.length; //Determine wheter it should be random or not boolean do_this_random = false; time_step++; random_chance = (1.0f / ((float) Math.sqrt(time_step))); if (random_number.nextFloat() < random_chance) { do_this_random = true; } for (int i = 0; i < num_tld; i++) { num_dec = tld[i].length; for (int j = 0; j < num_dec; j++) { Sign currenttl = tld[i][j].getTL(); float gain = 0; DriveLane currentlane = currenttl.getLane(); int waitingsize = currentlane.getNumRoadusersWaiting(); Iterator<Roaduser> queue = currentlane.getQueue().iterator(); if (!do_this_random) { for (; waitingsize > 0; waitingsize--) { Roaduser ru = queue.next(); int pos = ru.getPosition(); Node destination = ru.getDestNode(); gain += q_table[currenttl.getId()][pos][destination.getId()][1] - q_table[currenttl.getId()][pos][destination.getId()][0]; //red - green // System.out.println(gain + " "); } float q = gain; } else { gain = random_number.nextFloat(); } tld[i][j].setGain(gain); } } return tld; } @Override public void updateRoaduserMove(Roaduser ru, DriveLane prevlane, Sign prevsign, int prevpos, DriveLane dlanenow, Sign signnow, int posnow, PosMov[] posMovs, DriveLane desired, int penalty) { //When a roaduser leaves the city; this will if (dlanenow == null || signnow == null) { dlanenow = prevlane; signnow = prevsign; posnow = -1; return; // ?? is recalculation is not necessary ?? } //This ordening is important for the execution of the algorithm! if (prevsign.getType() == Sign.TRAFFICLIGHT && (signnow.getType() == Sign.TRAFFICLIGHT || signnow.getType() == Sign.NO_SIGN)) { Node dest = ru.getDestNode(); recalcQ(prevsign, prevpos, dest, prevsign.mayDrive(), signnow, posnow, signnow.mayDrive(), posMovs, penalty); } } protected void recalcQ(Sign tl, int pos, Node destination, boolean light, Sign tl_new, int pos_new, boolean light_new, PosMov[] posMovs, int penalty) { /* Recalculate the Q values, only one PEntry has changed, meaning also only 1 QEntry has to change */ int R; float oldQvalue = 0; float Qmark = 0; float newQvalue = 0; R = penalty + rewardFunction(tl_new, pos_new, posMovs); try { oldQvalue = q_table[tl.getId()][pos][destination.getId()][light ? green_index : red_index]; Qmark = q_table[tl_new.getId()][pos_new][destination.getId()][light_new ? green_index : red_index];// Q( [ tl' , p' ] , L') } catch (Exception e) { System.out.println("ERROR"); System.out.println("tl: " + tl.getId()); System.out.println("pos:" + pos); System.out.println("des:" + destination.getId()); } newQvalue = oldQvalue + alpha * (R + gamma * Qmark - oldQvalue); q_table[tl.getId()][pos][destination.getId()][light ? green_index : red_index] = newQvalue; } /* ========================================================================== Additional methods, used by the recalc methods ========================================================================== */ protected int rewardFunction(Sign tl_new, int pos_new, PosMov[] posMovs) { //Ok, the reward function is actually very simple; it searches for the tuple (tl_new, pos_new) in the given set int size = posMovs.length; for (int i = 0; i < size; i++) { if (posMovs[i].tlId == tl_new.getId() && posMovs[i].pos == pos_new) { return 0; } } /*int size = possiblelanes.length; for(int i=0; i<size; i++) { if( possiblelanes[i].equals(tl_new.getLane()) ) { if(ranges[i].x < pos_new) { if(ranges[i].y > pos_new) { return 0; } } } }*/ return 1; } protected Target[] ownedTargets(Sign tl, int pos, Node des, boolean light) { //This method will determine to which destinations you can go starting at this source represented in this QEntry CountEntry dummy = new CountEntry(tl, pos, des, light, tl, pos); Target[] ownedtargets; ArrayList<Target> candidate_targets; candidate_targets = new ArrayList<>(); //Use the count table to sort this out, we need all Targets from //Only the elements in the count table are used, other just give a P Iterator<CountEntry> it = count.iterator(); while (it.hasNext()) { CountEntry current_entry = it.next(); if (current_entry.sameSource(dummy) != 0) { candidate_targets.add(new Target(current_entry.tl_new, current_entry.pos_new)); } } return candidate_targets.toArray(new Target[candidate_targets.size()]); } /* ========================================================================== Internal Classes to provide a way to put entries into the tables ========================================================================== */ public class CountEntry implements XMLSerializable, TwoStageLoader { Sign tl; int pos; Node destination; boolean light; Sign tl_new; int pos_new; int value; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; CountEntry(Sign _tl, int _pos, Node _destination, boolean _light, Sign _tl_new, int _pos_new) { tl = _tl; pos = _pos; destination = _destination; light = _light; tl_new = _tl_new; pos_new = _pos_new; value = 1; } CountEntry() { // Empty constructor for loading } public void incrementValue() { value++; } public int getValue() { return value; } @Override public boolean equals(Object other) { if (other != null && other instanceof CountEntry) { CountEntry countnew = (CountEntry) other; if (!countnew.tl.equals(tl)) { return false; } if (countnew.pos != pos) { return false; } if (!countnew.destination.equals(destination)) { return false; } if (countnew.light != light) { return false; } if (!countnew.tl_new.equals(tl_new)) { return false; } if (countnew.pos_new != pos_new) { return false; } return true; } return false; } public int sameSource(CountEntry other) { if (other.tl.equals(tl) && other.pos == pos && other.light == light && other.destination.equals(destination)) { return value; } else { return 0; } } // XMLSerializable implementation of CountEntry @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.oldTlId = myElement.getAttribute("tl-id").getIntValue(); loadData.destNodeId = myElement.getAttribute("destination").getIntValue(); light = myElement.getAttribute("light").getBoolValue(); loadData.newTlId = myElement.getAttribute("newtl-id").getIntValue(); pos_new = myElement.getAttribute("new-pos").getIntValue(); value = myElement.getAttribute("value").getIntValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("count"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); result.addAttribute(new XMLAttribute("destination", destination.getId())); result.addAttribute(new XMLAttribute("light", light)); result.addAttribute(new XMLAttribute("newtl-id", tl_new.getId())); result.addAttribute(new XMLAttribute("new-pos", pos_new)); result.addAttribute(new XMLAttribute("value", value)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A count entry has no child objects } @Override public String getXMLName() { return parentName + ".count"; } @Override public void setParentName(String parentName) { this.parentName = parentName; } // TwoStageLoader implementation of CountEntry class TwoStageLoaderData { int oldTlId, newTlId, destNodeId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) { Map laneMap = maps.get("lane"); Map nodeMap = maps.get("node"); tl = ((DriveLane) (laneMap.get(loadData.oldTlId))).getSign(); tl_new = ((DriveLane) (laneMap.get(loadData.newTlId))).getSign(); destination = (Node) (nodeMap.get(loadData.destNodeId)); } } public class PEntry implements XMLSerializable, TwoStageLoader { Sign tl; int pos; Node destination; boolean light; Sign tl_new; int pos_new; float value; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; PEntry(Sign _tl, int _pos, Node _destination, boolean _light, Sign _tl_new, int _pos_new) { tl = _tl; pos = _pos; destination = _destination; light = _light; tl_new = _tl_new; pos_new = _pos_new; value = 0; } PEntry() { // Empty constructor for loading } public void setValue(float v) { value = v; } public float getValue() { return value; } @Override public boolean equals(Object other) { if (other != null && other instanceof PEntry) { PEntry pnew = (PEntry) other; if (!pnew.tl.equals(tl)) { return false; } if (pnew.pos != pos) { return false; } if (!pnew.destination.equals(destination)) { return false; } if (pnew.light != light) { return false; } if (!pnew.tl_new.equals(tl_new)) { return false; } if (pnew.pos_new != pos_new) { return false; } return true; } return false; } public float sameSource(CountEntry other) { if (other.tl.equals(tl) && other.pos == pos && other.light == light && other.destination.equals(destination)) { return value; } else { return -1; } } // XMLSerializable implementation of PEntry @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.oldTlId = myElement.getAttribute("tl-id").getIntValue(); loadData.destNodeId = myElement.getAttribute("destination").getIntValue(); light = myElement.getAttribute("light").getBoolValue(); loadData.newTlId = myElement.getAttribute("newtl-id").getIntValue(); pos_new = myElement.getAttribute("new-pos").getIntValue(); value = myElement.getAttribute("value").getFloatValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("pval"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); result.addAttribute(new XMLAttribute("destination", destination.getId())); result.addAttribute(new XMLAttribute("light", light)); result.addAttribute(new XMLAttribute("newtl-id", tl_new.getId())); result.addAttribute(new XMLAttribute("new-pos", pos_new)); result.addAttribute(new XMLAttribute("value", value)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A PEntry has no child objects } @Override public void setParentName(String parentName) { this.parentName = parentName; } @Override public String getXMLName() { return parentName + ".pval"; } // TwoStageLoader implementation of PEntry class TwoStageLoaderData { int oldTlId, newTlId, destNodeId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) { Map laneMap = maps.get("lane"); Map nodeMap = maps.get("node"); tl = ((DriveLane) (laneMap.get(loadData.oldTlId))).getSign(); tl_new = ((DriveLane) (laneMap.get(loadData.newTlId))).getSign(); destination = (Node) (nodeMap.get(loadData.destNodeId)); } } protected class Target implements XMLSerializable, TwoStageLoader { Sign tl; int pos; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; Target(Sign _tl, int _pos) { tl = _tl; pos = _pos; } Target() { // Empty constructor for loading } public Sign getTL() { return tl; } public int getP() { return pos; } @Override public boolean equals(Object other) { if (other != null && other instanceof Target) { Target qnew = (Target) other; if (!qnew.tl.equals(tl)) { return false; } if (qnew.pos != pos) { return false; } return true; } return false; } // XMLSerializable implementation of Target @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.tlId = myElement.getAttribute("tl-id").getIntValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("target"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A Target has no child objects } @Override public String getXMLName() { return parentName + ".target"; } @Override public void setParentName(String parentName) { this.parentName = parentName; } // TwoStageLoader implementation of Target class TwoStageLoaderData { int tlId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) throws XMLInvalidInputException, XMLTreeException { Map laneMap = maps.get("lane"); tl = ((DriveLane) (laneMap.get(loadData.tlId))).getSign(); } } @Override public void showSettings(Controller c) { String[] descs = {"Gamma (discount factor)", "Random decision chance"}; float[] floats = {gamma, random_chance}; TLCSettings settings = new TLCSettings(descs, null, floats); settings = doSettingsDialog(c, settings); //OBS // Her burde laves et tjek p� om 0 < gamma < 1 og det samme med random chance gamma = settings.floats[0]; random_chance = settings.floats[1]; } // XMLSerializable, SecondStageLoader and InstantiationAssistant implementation @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { super.load(myElement, loader); gamma = myElement.getAttribute("gamma").getFloatValue(); random_chance = myElement.getAttribute("random-chance").getFloatValue(); q_table = (float[][][][]) XMLArray.loadArray(this, loader); //v_table=(float[][][])XMLArray.loadArray(this,loader); count = (ArrayList<CountEntry>) XMLArray.loadArray(this, loader, this); //p_table=(ArrayList<PEntry>)XMLArray.loadArray(this,loader,this); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = super.saveSelf(); result.setName(shortXMLName); result.addAttribute(new XMLAttribute("random-chance", random_chance)); result.addAttribute(new XMLAttribute("gamma", gamma)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { super.saveChilds(saver); XMLArray.saveArray(q_table, this, saver, "q-table"); //XMLArray.saveArray(v_table,this,saver,"v-table"); XMLArray.saveArray(count, this, saver, "counts"); //XMLArray.saveArray(p_table,this,saver,"p-table"); } @Override public String getXMLName() { return "model." + shortXMLName; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) throws XMLInvalidInputException, XMLTreeException { XMLUtils.loadSecondStage(count, maps); //XMLUtils.loadSecondStage(p_table.iterator(),maps); System.out.println("SL2 second stage load finished."); } @Override public boolean canCreateInstance(Class request) { return CountEntry.class.equals(request) || PEntry.class.equals(request); } @Override public Object createInstance(Class request) throws ClassNotFoundException, InstantiationException, IllegalAccessException { if (CountEntry.class.equals(request)) { return new CountEntry(); } else if (PEntry.class.equals(request)) { return new PEntry(); } else { throw new ClassNotFoundException("SL2 IntstantiationAssistant cannot make instances of " + request); } } }
CC007/TrafficLights
src/main/java/com/github/cc007/trafficlights/algo/tlc/SL2TLC.java
6,641
//Moet Edge zijn eigenlijk, alleen testSimModel knalt er dan op
line_comment
nl
/*----------------------------------------------------------------------- * Copyright (C) 2001 Green Light District Team, Utrecht University * Copyright of the TC1 algorithm (C) Marco Wiering, Utrecht University * * This program (Green Light District) is free software. * You may redistribute it and/or modify it under the terms * of the GNU General Public License as published by * the Free Software Foundation (version 2 or later). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * See the documentation of Green Light District for further information. * * Changed to use Sarsa(0) with random decision instead of DP - S. Louring *------------------------------------------------------------------------*/ package com.github.cc007.trafficlights.algo.tlc; import com.github.cc007.trafficlights.*; import com.github.cc007.trafficlights.algo.tlc.*; import com.github.cc007.trafficlights.infra.*; import com.github.cc007.trafficlights.xml.*; import java.io.IOException; import java.util.*; /** * * This controller will decide it's Q values for the traffic lights according to * the traffic situation on the lane connected to the TrafficLight. It will * learn how to alter it's outcome by reinforcement learning. * * @author Arne K, Jilles V, Søren Louring * @version 1.1 */ public class SL2TLC extends TCRL implements InstantiationAssistant { protected Infrastructure infrastructure; protected TrafficLight[][] tls; protected Node[] allnodes; protected int num_nodes; protected ArrayList<CountEntry> count; //, p_table; protected float[][][][] q_table; //sign, pos, des, color (red=0, green=1) protected static float gamma = 0.95f; //Discount Factor; used to decrease the influence of previous V values, that's why: 0 < gamma < 1 protected static float random_chance = 0.01f; //A random gain setting is chosen instead of the on the TLC dictates with this chance protected static float alpha = 0.7f; protected final static boolean red = false, green = true; protected final static int green_index = 0, red_index = 1; protected final static String shortXMLName = "tlc-sl2"; private Random random_number; protected float time_step = 0; /** * The constructor for TL controllers * * @param The model being used. */ public SL2TLC(Infrastructure infra) throws InfraException { super(infra); Node[] nodes = infra.getAllNodes(); //Moet Edge<SUF> int num_nodes = nodes.length; count = new ArrayList<>(); int numSigns = infra.getAllInboundLanes().size(); q_table = new float[numSigns + 1][][][]; int num_specialnodes = infra.getNumSpecialNodes(); for (int i = 0; i < nodes.length; i++) { Node n = nodes[i]; DriveLane[] dls = n.getInboundLanes(); for (int j = 0; j < dls.length; j++) { DriveLane d = dls[j]; Sign s = d.getSign(); int id = s.getId(); int num_pos_on_dl = d.getCompleteLength(); q_table[id] = new float[num_pos_on_dl][][]; for (int k = 0; k < num_pos_on_dl; k++) { q_table[id][k] = new float[num_specialnodes][]; for (int l = 0; l < q_table[id][k].length; l++) { q_table[id][k][l] = new float[2]; q_table[id][k][l][0] = 0.0f; q_table[id][k][l][1] = 0.0f; //v_table[id][k][l]=0.0f; } } } } System.out.println("tl = " + numSigns); System.out.println("des = " + num_specialnodes); System.out.println("Alpha = " + alpha); random_number = new Random(GLDSim.seriesSeed[GLDSim.seriesSeedIndex]); } @Override public void reset() { for (int j = 0; j < q_table.length; j++) { if (q_table[j] != null) { for (int k = 0; k < q_table[j].length; k++) { if (q_table[j][k] != null) { for (int l = 0; l < q_table[j][k].length; l++) { if (q_table[j][k][l] != null) { q_table[j][k][l][0] = 0.0f; q_table[j][k][l][1] = 0.0f; } } } } } } System.out.println("Q table nulstillet."); } //Reset slut /** * Calculates how every traffic light should be switched Per node, per sign * the waiting roadusers are passed and per each roaduser the gain is * calculated. * * @param The TLDecision is a tuple consisting of a traffic light and a * reward (Q) value, for it to be green * @see gld.algo.tlc.TLDecision */ @Override public TLDecision[][] decideTLs() { int num_dec; int num_tld = tld.length; //Determine wheter it should be random or not boolean do_this_random = false; time_step++; random_chance = (1.0f / ((float) Math.sqrt(time_step))); if (random_number.nextFloat() < random_chance) { do_this_random = true; } for (int i = 0; i < num_tld; i++) { num_dec = tld[i].length; for (int j = 0; j < num_dec; j++) { Sign currenttl = tld[i][j].getTL(); float gain = 0; DriveLane currentlane = currenttl.getLane(); int waitingsize = currentlane.getNumRoadusersWaiting(); Iterator<Roaduser> queue = currentlane.getQueue().iterator(); if (!do_this_random) { for (; waitingsize > 0; waitingsize--) { Roaduser ru = queue.next(); int pos = ru.getPosition(); Node destination = ru.getDestNode(); gain += q_table[currenttl.getId()][pos][destination.getId()][1] - q_table[currenttl.getId()][pos][destination.getId()][0]; //red - green // System.out.println(gain + " "); } float q = gain; } else { gain = random_number.nextFloat(); } tld[i][j].setGain(gain); } } return tld; } @Override public void updateRoaduserMove(Roaduser ru, DriveLane prevlane, Sign prevsign, int prevpos, DriveLane dlanenow, Sign signnow, int posnow, PosMov[] posMovs, DriveLane desired, int penalty) { //When a roaduser leaves the city; this will if (dlanenow == null || signnow == null) { dlanenow = prevlane; signnow = prevsign; posnow = -1; return; // ?? is recalculation is not necessary ?? } //This ordening is important for the execution of the algorithm! if (prevsign.getType() == Sign.TRAFFICLIGHT && (signnow.getType() == Sign.TRAFFICLIGHT || signnow.getType() == Sign.NO_SIGN)) { Node dest = ru.getDestNode(); recalcQ(prevsign, prevpos, dest, prevsign.mayDrive(), signnow, posnow, signnow.mayDrive(), posMovs, penalty); } } protected void recalcQ(Sign tl, int pos, Node destination, boolean light, Sign tl_new, int pos_new, boolean light_new, PosMov[] posMovs, int penalty) { /* Recalculate the Q values, only one PEntry has changed, meaning also only 1 QEntry has to change */ int R; float oldQvalue = 0; float Qmark = 0; float newQvalue = 0; R = penalty + rewardFunction(tl_new, pos_new, posMovs); try { oldQvalue = q_table[tl.getId()][pos][destination.getId()][light ? green_index : red_index]; Qmark = q_table[tl_new.getId()][pos_new][destination.getId()][light_new ? green_index : red_index];// Q( [ tl' , p' ] , L') } catch (Exception e) { System.out.println("ERROR"); System.out.println("tl: " + tl.getId()); System.out.println("pos:" + pos); System.out.println("des:" + destination.getId()); } newQvalue = oldQvalue + alpha * (R + gamma * Qmark - oldQvalue); q_table[tl.getId()][pos][destination.getId()][light ? green_index : red_index] = newQvalue; } /* ========================================================================== Additional methods, used by the recalc methods ========================================================================== */ protected int rewardFunction(Sign tl_new, int pos_new, PosMov[] posMovs) { //Ok, the reward function is actually very simple; it searches for the tuple (tl_new, pos_new) in the given set int size = posMovs.length; for (int i = 0; i < size; i++) { if (posMovs[i].tlId == tl_new.getId() && posMovs[i].pos == pos_new) { return 0; } } /*int size = possiblelanes.length; for(int i=0; i<size; i++) { if( possiblelanes[i].equals(tl_new.getLane()) ) { if(ranges[i].x < pos_new) { if(ranges[i].y > pos_new) { return 0; } } } }*/ return 1; } protected Target[] ownedTargets(Sign tl, int pos, Node des, boolean light) { //This method will determine to which destinations you can go starting at this source represented in this QEntry CountEntry dummy = new CountEntry(tl, pos, des, light, tl, pos); Target[] ownedtargets; ArrayList<Target> candidate_targets; candidate_targets = new ArrayList<>(); //Use the count table to sort this out, we need all Targets from //Only the elements in the count table are used, other just give a P Iterator<CountEntry> it = count.iterator(); while (it.hasNext()) { CountEntry current_entry = it.next(); if (current_entry.sameSource(dummy) != 0) { candidate_targets.add(new Target(current_entry.tl_new, current_entry.pos_new)); } } return candidate_targets.toArray(new Target[candidate_targets.size()]); } /* ========================================================================== Internal Classes to provide a way to put entries into the tables ========================================================================== */ public class CountEntry implements XMLSerializable, TwoStageLoader { Sign tl; int pos; Node destination; boolean light; Sign tl_new; int pos_new; int value; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; CountEntry(Sign _tl, int _pos, Node _destination, boolean _light, Sign _tl_new, int _pos_new) { tl = _tl; pos = _pos; destination = _destination; light = _light; tl_new = _tl_new; pos_new = _pos_new; value = 1; } CountEntry() { // Empty constructor for loading } public void incrementValue() { value++; } public int getValue() { return value; } @Override public boolean equals(Object other) { if (other != null && other instanceof CountEntry) { CountEntry countnew = (CountEntry) other; if (!countnew.tl.equals(tl)) { return false; } if (countnew.pos != pos) { return false; } if (!countnew.destination.equals(destination)) { return false; } if (countnew.light != light) { return false; } if (!countnew.tl_new.equals(tl_new)) { return false; } if (countnew.pos_new != pos_new) { return false; } return true; } return false; } public int sameSource(CountEntry other) { if (other.tl.equals(tl) && other.pos == pos && other.light == light && other.destination.equals(destination)) { return value; } else { return 0; } } // XMLSerializable implementation of CountEntry @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.oldTlId = myElement.getAttribute("tl-id").getIntValue(); loadData.destNodeId = myElement.getAttribute("destination").getIntValue(); light = myElement.getAttribute("light").getBoolValue(); loadData.newTlId = myElement.getAttribute("newtl-id").getIntValue(); pos_new = myElement.getAttribute("new-pos").getIntValue(); value = myElement.getAttribute("value").getIntValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("count"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); result.addAttribute(new XMLAttribute("destination", destination.getId())); result.addAttribute(new XMLAttribute("light", light)); result.addAttribute(new XMLAttribute("newtl-id", tl_new.getId())); result.addAttribute(new XMLAttribute("new-pos", pos_new)); result.addAttribute(new XMLAttribute("value", value)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A count entry has no child objects } @Override public String getXMLName() { return parentName + ".count"; } @Override public void setParentName(String parentName) { this.parentName = parentName; } // TwoStageLoader implementation of CountEntry class TwoStageLoaderData { int oldTlId, newTlId, destNodeId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) { Map laneMap = maps.get("lane"); Map nodeMap = maps.get("node"); tl = ((DriveLane) (laneMap.get(loadData.oldTlId))).getSign(); tl_new = ((DriveLane) (laneMap.get(loadData.newTlId))).getSign(); destination = (Node) (nodeMap.get(loadData.destNodeId)); } } public class PEntry implements XMLSerializable, TwoStageLoader { Sign tl; int pos; Node destination; boolean light; Sign tl_new; int pos_new; float value; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; PEntry(Sign _tl, int _pos, Node _destination, boolean _light, Sign _tl_new, int _pos_new) { tl = _tl; pos = _pos; destination = _destination; light = _light; tl_new = _tl_new; pos_new = _pos_new; value = 0; } PEntry() { // Empty constructor for loading } public void setValue(float v) { value = v; } public float getValue() { return value; } @Override public boolean equals(Object other) { if (other != null && other instanceof PEntry) { PEntry pnew = (PEntry) other; if (!pnew.tl.equals(tl)) { return false; } if (pnew.pos != pos) { return false; } if (!pnew.destination.equals(destination)) { return false; } if (pnew.light != light) { return false; } if (!pnew.tl_new.equals(tl_new)) { return false; } if (pnew.pos_new != pos_new) { return false; } return true; } return false; } public float sameSource(CountEntry other) { if (other.tl.equals(tl) && other.pos == pos && other.light == light && other.destination.equals(destination)) { return value; } else { return -1; } } // XMLSerializable implementation of PEntry @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.oldTlId = myElement.getAttribute("tl-id").getIntValue(); loadData.destNodeId = myElement.getAttribute("destination").getIntValue(); light = myElement.getAttribute("light").getBoolValue(); loadData.newTlId = myElement.getAttribute("newtl-id").getIntValue(); pos_new = myElement.getAttribute("new-pos").getIntValue(); value = myElement.getAttribute("value").getFloatValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("pval"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); result.addAttribute(new XMLAttribute("destination", destination.getId())); result.addAttribute(new XMLAttribute("light", light)); result.addAttribute(new XMLAttribute("newtl-id", tl_new.getId())); result.addAttribute(new XMLAttribute("new-pos", pos_new)); result.addAttribute(new XMLAttribute("value", value)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A PEntry has no child objects } @Override public void setParentName(String parentName) { this.parentName = parentName; } @Override public String getXMLName() { return parentName + ".pval"; } // TwoStageLoader implementation of PEntry class TwoStageLoaderData { int oldTlId, newTlId, destNodeId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) { Map laneMap = maps.get("lane"); Map nodeMap = maps.get("node"); tl = ((DriveLane) (laneMap.get(loadData.oldTlId))).getSign(); tl_new = ((DriveLane) (laneMap.get(loadData.newTlId))).getSign(); destination = (Node) (nodeMap.get(loadData.destNodeId)); } } protected class Target implements XMLSerializable, TwoStageLoader { Sign tl; int pos; TwoStageLoaderData loadData = new TwoStageLoaderData(); String parentName = "model.tlc"; Target(Sign _tl, int _pos) { tl = _tl; pos = _pos; } Target() { // Empty constructor for loading } public Sign getTL() { return tl; } public int getP() { return pos; } @Override public boolean equals(Object other) { if (other != null && other instanceof Target) { Target qnew = (Target) other; if (!qnew.tl.equals(tl)) { return false; } if (qnew.pos != pos) { return false; } return true; } return false; } // XMLSerializable implementation of Target @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { pos = myElement.getAttribute("pos").getIntValue(); loadData.tlId = myElement.getAttribute("tl-id").getIntValue(); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = new XMLElement("target"); result.addAttribute(new XMLAttribute("tl-id", tl.getId())); result.addAttribute(new XMLAttribute("pos", pos)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { // A Target has no child objects } @Override public String getXMLName() { return parentName + ".target"; } @Override public void setParentName(String parentName) { this.parentName = parentName; } // TwoStageLoader implementation of Target class TwoStageLoaderData { int tlId; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) throws XMLInvalidInputException, XMLTreeException { Map laneMap = maps.get("lane"); tl = ((DriveLane) (laneMap.get(loadData.tlId))).getSign(); } } @Override public void showSettings(Controller c) { String[] descs = {"Gamma (discount factor)", "Random decision chance"}; float[] floats = {gamma, random_chance}; TLCSettings settings = new TLCSettings(descs, null, floats); settings = doSettingsDialog(c, settings); //OBS // Her burde laves et tjek p� om 0 < gamma < 1 og det samme med random chance gamma = settings.floats[0]; random_chance = settings.floats[1]; } // XMLSerializable, SecondStageLoader and InstantiationAssistant implementation @Override public void load(XMLElement myElement, XMLLoader loader) throws XMLTreeException, IOException, XMLInvalidInputException { super.load(myElement, loader); gamma = myElement.getAttribute("gamma").getFloatValue(); random_chance = myElement.getAttribute("random-chance").getFloatValue(); q_table = (float[][][][]) XMLArray.loadArray(this, loader); //v_table=(float[][][])XMLArray.loadArray(this,loader); count = (ArrayList<CountEntry>) XMLArray.loadArray(this, loader, this); //p_table=(ArrayList<PEntry>)XMLArray.loadArray(this,loader,this); } @Override public XMLElement saveSelf() throws XMLCannotSaveException { XMLElement result = super.saveSelf(); result.setName(shortXMLName); result.addAttribute(new XMLAttribute("random-chance", random_chance)); result.addAttribute(new XMLAttribute("gamma", gamma)); return result; } @Override public void saveChilds(XMLSaver saver) throws XMLTreeException, IOException, XMLCannotSaveException { super.saveChilds(saver); XMLArray.saveArray(q_table, this, saver, "q-table"); //XMLArray.saveArray(v_table,this,saver,"v-table"); XMLArray.saveArray(count, this, saver, "counts"); //XMLArray.saveArray(p_table,this,saver,"p-table"); } @Override public String getXMLName() { return "model." + shortXMLName; } @Override public void loadSecondStage(Map<String, Map<Integer, TwoStageLoader>> maps) throws XMLInvalidInputException, XMLTreeException { XMLUtils.loadSecondStage(count, maps); //XMLUtils.loadSecondStage(p_table.iterator(),maps); System.out.println("SL2 second stage load finished."); } @Override public boolean canCreateInstance(Class request) { return CountEntry.class.equals(request) || PEntry.class.equals(request); } @Override public Object createInstance(Class request) throws ClassNotFoundException, InstantiationException, IllegalAccessException { if (CountEntry.class.equals(request)) { return new CountEntry(); } else if (PEntry.class.equals(request)) { return new PEntry(); } else { throw new ClassNotFoundException("SL2 IntstantiationAssistant cannot make instances of " + request); } } }
190005_12
package com.example.fabrice.joetz2.Controllers; import android.app.Activity; import android.os.Bundle; import android.app.Fragment; //import android.support.v4.app.Fragment; import android.support.annotation.NonNull; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.TextView; import android.widget.Toast; import com.example.fabrice.joetz2.Controllers.Adaptor.VacationListAdaptor; import com.example.fabrice.joetz2.MainActivity; import com.example.fabrice.joetz2.Models.Vacation; import com.example.fabrice.joetz2.R; import com.example.fabrice.joetz2.RestService.NetNico; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * A fragment representing a list of Items. * <p/> * Large screen devices (such as tablets) are supported by replacing the ListView * with a GridView. * <p/> * Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener} * interface. */ public class LijstFragment extends Fragment implements AbsListView.OnItemClickListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private static final String ARG_SECTION_NUMBER = "section_number"; private List<Vacation> controllerVacations = new ArrayList<Vacation>(); // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; /** * The fragment's ListView/GridView. */ private AbsListView mListView; /** * The Adapter which will be used to populate the ListView/GridView with * Views. */ private VacationListAdaptor mAdapter; // TODO: Rename and change types of parameters public static LijstFragment newInstance(String param1, String param2, int sectionNumber) { LijstFragment fragment = new LijstFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); //voorlopig ongebruikt, refactor args.putString(ARG_PARAM2, param2); //voorlopig ongebruikt, refactor args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public LijstFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } // TODO: Change Adapter to display your content // mAdapter = new ArrayAdapter<DummyContent.DummyItem>( // getActivity(), // android.R.layout.simple_list_item_1, // android.R.id.text1, // DummyContent.ITEMS); mAdapter = new VacationListAdaptor(getActivity(),R.layout.vacation_lijst_item,controllerVacations); //Demo Vacation voorbeeldVacation = new Vacation(); voorbeeldVacation.setTitel("Voorbeeldvakantie (Design)"); mAdapter.add(voorbeeldVacation); //Demo einde Callback <List<Vacation>> callback = new Callback<List<Vacation>>() { @Override public void success(List<Vacation> vacations, Response response) { if(response.getStatus()==200) { mAdapter.addAll(vacations); } } @Override public void failure(RetrofitError error) { Log.e("Retroapp",error.getMessage()); //Toast.makeText(getActivity(),"Server is niet beschikbaar",Toast.LENGTH_SHORT); } }; NetNico.getInstance().getService().getAllVacations(callback); //END TEST } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_lijstitem, container, false); // Set the adapter mListView = (AbsListView) view.findViewById(android.R.id.list); ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter); // Set OnItemClickListener so we can be notified on item clicks mListView.setOnItemClickListener(this); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } ((MainActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (null != mListener) { // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mListener.onFragmentInteraction(controllerVacations.get(position).getId(), "lijstFragment"); } } /** * The default content for this Fragment has a TextView that is shown when * the list is empty. If you would like to change the text, call this method * to supply the text it should use. */ public void setEmptyText(CharSequence emptyText) { View emptyView = mListView.getEmptyView(); if (emptyView instanceof TextView) { ((TextView) emptyView).setText(emptyText); } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Integer id, String source); } }
pspletinckx/AndroidZomer2015
app/src/main/java/com/example/fabrice/joetz2/Controllers/LijstFragment.java
1,675
//Toast.makeText(getActivity(),"Server is niet beschikbaar",Toast.LENGTH_SHORT);
line_comment
nl
package com.example.fabrice.joetz2.Controllers; import android.app.Activity; import android.os.Bundle; import android.app.Fragment; //import android.support.v4.app.Fragment; import android.support.annotation.NonNull; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.TextView; import android.widget.Toast; import com.example.fabrice.joetz2.Controllers.Adaptor.VacationListAdaptor; import com.example.fabrice.joetz2.MainActivity; import com.example.fabrice.joetz2.Models.Vacation; import com.example.fabrice.joetz2.R; import com.example.fabrice.joetz2.RestService.NetNico; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * A fragment representing a list of Items. * <p/> * Large screen devices (such as tablets) are supported by replacing the ListView * with a GridView. * <p/> * Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener} * interface. */ public class LijstFragment extends Fragment implements AbsListView.OnItemClickListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private static final String ARG_SECTION_NUMBER = "section_number"; private List<Vacation> controllerVacations = new ArrayList<Vacation>(); // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; /** * The fragment's ListView/GridView. */ private AbsListView mListView; /** * The Adapter which will be used to populate the ListView/GridView with * Views. */ private VacationListAdaptor mAdapter; // TODO: Rename and change types of parameters public static LijstFragment newInstance(String param1, String param2, int sectionNumber) { LijstFragment fragment = new LijstFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); //voorlopig ongebruikt, refactor args.putString(ARG_PARAM2, param2); //voorlopig ongebruikt, refactor args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public LijstFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } // TODO: Change Adapter to display your content // mAdapter = new ArrayAdapter<DummyContent.DummyItem>( // getActivity(), // android.R.layout.simple_list_item_1, // android.R.id.text1, // DummyContent.ITEMS); mAdapter = new VacationListAdaptor(getActivity(),R.layout.vacation_lijst_item,controllerVacations); //Demo Vacation voorbeeldVacation = new Vacation(); voorbeeldVacation.setTitel("Voorbeeldvakantie (Design)"); mAdapter.add(voorbeeldVacation); //Demo einde Callback <List<Vacation>> callback = new Callback<List<Vacation>>() { @Override public void success(List<Vacation> vacations, Response response) { if(response.getStatus()==200) { mAdapter.addAll(vacations); } } @Override public void failure(RetrofitError error) { Log.e("Retroapp",error.getMessage()); //Toast.makeText(getActivity(),"Server is<SUF> } }; NetNico.getInstance().getService().getAllVacations(callback); //END TEST } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_lijstitem, container, false); // Set the adapter mListView = (AbsListView) view.findViewById(android.R.id.list); ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter); // Set OnItemClickListener so we can be notified on item clicks mListView.setOnItemClickListener(this); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } ((MainActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (null != mListener) { // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mListener.onFragmentInteraction(controllerVacations.get(position).getId(), "lijstFragment"); } } /** * The default content for this Fragment has a TextView that is shown when * the list is empty. If you would like to change the text, call this method * to supply the text it should use. */ public void setEmptyText(CharSequence emptyText) { View emptyView = mListView.getEmptyView(); if (emptyView instanceof TextView) { ((TextView) emptyView).setText(emptyText); } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Integer id, String source); } }
23166_34
package novi.basics; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner playerInput = new Scanner(System.in); // -- vanaf hier gaan we het spel opnieuw spelen met andere spelers (nadat op het eind keuze 2 gekozen is) // de 1e speler om zijn naam vragen System.out.println("Player 1, what is your name?"); // de naam van de 1e speler opslaan String player1Name = playerInput.next(); Player player1 = new Player(player1Name,'x'); // de 2e speler om zijn naam vragen System.out.println("Player 2, what is your name?"); // de naam van de 2e speler opslaan String player2Name = playerInput.next(); Player player2 = new Player(player2Name,'o'); Game game = new Game(); game.play(); // opslaan hoeveel keer er gelijk spel is geweest int drawCount = 0; // -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is) // speelbord opslaan (1 - 9) // uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven // zie demo project code voor de andere manier met de for loop char[] board = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // maximale aantal rondes opslaan int maxRounds = board.length; // speelbord tonen printBoard(board); // token van de actieve speler opslaan //char activePlayerToken = player1.getToken(); Player activePlayer = player1; // starten met de beurt (maximaal 9 beurten) for (int round = 0; round < maxRounds; round++) { // naam van de actieve speler opslaan /*String activePlayerName; if(activePlayerToken == player1.getToken()) { activePlayerName = player1Name; } else { activePlayerName = player2Name; }*/ String activePlayerName = activePlayer.getName(); // actieve speler vragen om een veld te kiezen (1 - 9) System.out.println(activePlayerName + ", please choose a field"); // gekozen veld van de actieve speler opslaan int chosenField = playerInput.nextInt(); int chosenIndex = chosenField - 1; // als het veld bestaat if(chosenIndex < 9 && chosenIndex >= 0) { //als het veld leeg is, wanneer er geen token staat if(board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) { // wanneer de speler een token op het bord kan plaatsen // de token van de actieve speler op het gekozen veld plaatsen board[chosenIndex] = activePlayer.getToken(); //player.score += 10; // het nieuwe speelbord tonen printBoard(board); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we in de laatste beurt zijn en niemand gewonnen heeft // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: if(activePlayer == player1) { // maak de actieve speler, speler 2 activePlayer = player2; } // anders else { // maak de actieve speler weer speler 1 activePlayer = player1; } } //of al bezet is else { maxRounds++; System.out.println("this field is not available, choose another"); } //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ } // als het veld niet bestaat else { // het mamimale aantal beurten verhogen maxRounds++; // foutmelding tonen aan de speler System.out.println("the chosen field does not exist, try again"); } // -- terug naar het begin van de volgende beurt } // vragen of de spelers nog een keer willen spelen //1: nog een keer spelen //2: van spelers wisselen //3: afsluiten // speler keuze opslaan // bij keuze 1: terug naar het maken van het bord // bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen // bij keuze 3: het spel en de applicatie helemaal afsluiten } public static void printBoard(char[] board) { for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) { System.out.print(board[fieldIndex] + " "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if(fieldIndex == 2 || fieldIndex == 5) { System.out.println(); } } System.out.println(); } }
hogeschoolnovi/tic-tac-toe-elmarrekers
src/novi/basics/Main.java
1,344
// maak de actieve speler weer speler 1
line_comment
nl
package novi.basics; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner playerInput = new Scanner(System.in); // -- vanaf hier gaan we het spel opnieuw spelen met andere spelers (nadat op het eind keuze 2 gekozen is) // de 1e speler om zijn naam vragen System.out.println("Player 1, what is your name?"); // de naam van de 1e speler opslaan String player1Name = playerInput.next(); Player player1 = new Player(player1Name,'x'); // de 2e speler om zijn naam vragen System.out.println("Player 2, what is your name?"); // de naam van de 2e speler opslaan String player2Name = playerInput.next(); Player player2 = new Player(player2Name,'o'); Game game = new Game(); game.play(); // opslaan hoeveel keer er gelijk spel is geweest int drawCount = 0; // -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is) // speelbord opslaan (1 - 9) // uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven // zie demo project code voor de andere manier met de for loop char[] board = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; // maximale aantal rondes opslaan int maxRounds = board.length; // speelbord tonen printBoard(board); // token van de actieve speler opslaan //char activePlayerToken = player1.getToken(); Player activePlayer = player1; // starten met de beurt (maximaal 9 beurten) for (int round = 0; round < maxRounds; round++) { // naam van de actieve speler opslaan /*String activePlayerName; if(activePlayerToken == player1.getToken()) { activePlayerName = player1Name; } else { activePlayerName = player2Name; }*/ String activePlayerName = activePlayer.getName(); // actieve speler vragen om een veld te kiezen (1 - 9) System.out.println(activePlayerName + ", please choose a field"); // gekozen veld van de actieve speler opslaan int chosenField = playerInput.nextInt(); int chosenIndex = chosenField - 1; // als het veld bestaat if(chosenIndex < 9 && chosenIndex >= 0) { //als het veld leeg is, wanneer er geen token staat if(board[chosenIndex] != player1.getToken() && board[chosenIndex] != player2.getToken()) { // wanneer de speler een token op het bord kan plaatsen // de token van de actieve speler op het gekozen veld plaatsen board[chosenIndex] = activePlayer.getToken(); //player.score += 10; // het nieuwe speelbord tonen printBoard(board); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we in de laatste beurt zijn en niemand gewonnen heeft // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: if(activePlayer == player1) { // maak de actieve speler, speler 2 activePlayer = player2; } // anders else { // maak de<SUF> activePlayer = player1; } } //of al bezet is else { maxRounds++; System.out.println("this field is not available, choose another"); } //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ } // als het veld niet bestaat else { // het mamimale aantal beurten verhogen maxRounds++; // foutmelding tonen aan de speler System.out.println("the chosen field does not exist, try again"); } // -- terug naar het begin van de volgende beurt } // vragen of de spelers nog een keer willen spelen //1: nog een keer spelen //2: van spelers wisselen //3: afsluiten // speler keuze opslaan // bij keuze 1: terug naar het maken van het bord // bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen // bij keuze 3: het spel en de applicatie helemaal afsluiten } public static void printBoard(char[] board) { for (int fieldIndex = 0; fieldIndex < board.length; fieldIndex++) { System.out.print(board[fieldIndex] + " "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if(fieldIndex == 2 || fieldIndex == 5) { System.out.println(); } } System.out.println(); } }
94426_6
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class MyWorld extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("background4.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,212,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,77,-1,-1,-1,-1,194,-1,-1,212,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,-1,134,-1,197,-1,76,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,212,-1,-1,-1,-1,-1,140,47,47,47,47,47,42,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,-1,-1,-1,212,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,66,72,72,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,101,-1,-1,-1,-1,-1,-1,-1,101,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,66,67,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,89,95,15,15,15,15,15,15,15,95,91,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,66,67,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,89,90,80,155,155,155,155,155,155,155,80,92,91,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,66,67,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,89,90,80,80,153,153,153,153,153,153,153,80,80,92,91,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,55,-1,-1,-1,171,-1,-1,-1,33,-1,-1,-1,-1,78,-1,-1,-1,-1,-1,-1,-1,67,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {101,-1,-1,-1,-1,89,90,80,80,80,153,153,153,153,153,153,153,80,80,80,92,91,-1,-1,-1,-1,-1,-1,-1,210,210,210,-1,-1,-1,-1,-1,-1,-1,-1,-1,210,210,210,15,15,15,-1,-1,-1,-1,15,15,15,210,210,210,-1,-1,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {82,95,95,95,95,90,80,80,80,80,153,153,153,153,153,153,153,80,80,80,80,92,95,95,95,95,84,-1,-1,17,17,17,208,208,208,208,208,208,208,208,208,17,17,17,104,104,104,104,104,104,104,104,104,104,17,17,17,208,208,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,102,102,102,102,102,102,102,102,102,102,17,17,17,17,17,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,102,102,102,102,102,102,102,102,102,102,17,17,17,17,17,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,102,102,102,102,102,102,102,102,102,102,17,17,17,17,17,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 200, 1212); addObject(hero, 200, 1212); Slime slime = new Slime(); addObject(slime, 815, 1010); addObject(new Hartje(), 815, 1010); addObject(slime, 815, 1010); addObject(new slak(), 1466, 1247); addObject(new LetterB(), 300, 972); addObject(new LetterI(), 2053, 900); addObject(new LetterK(), 2951, 1000); addObject(new LetterC(), 2900, 1000); addObject(new LetterE(), 3568, 200); //addObject(new Enemy(), 1170, 410); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } public void resetStatic() { } }
ROCMondriaanTIN/project-greenfoot-game-302723805
MyWorld.java
5,184
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class MyWorld extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("background4.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,212,-1,-1,-1,-1,194,-1,-1,194,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,77,-1,-1,-1,-1,194,-1,-1,212,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1,-1,-1,-1,-1,134,-1,197,-1,76,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,212,-1,-1,-1,-1,-1,140,47,47,47,47,47,42,-1,-1,-1,-1,-1,-1,-1,-1,-1,194,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,-1,-1,-1,212,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,66,72,72,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,101,-1,-1,-1,-1,-1,-1,-1,101,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,66,67,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,89,95,15,15,15,15,15,15,15,95,91,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,66,67,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,89,90,80,155,155,155,155,155,155,155,80,92,91,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,66,67,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,89,90,80,80,153,153,153,153,153,153,153,80,80,92,91,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,55,-1,-1,-1,55,-1,-1,-1,171,-1,-1,-1,33,-1,-1,-1,-1,78,-1,-1,-1,-1,-1,-1,-1,67,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {101,-1,-1,-1,-1,89,90,80,80,80,153,153,153,153,153,153,153,80,80,80,92,91,-1,-1,-1,-1,-1,-1,-1,210,210,210,-1,-1,-1,-1,-1,-1,-1,-1,-1,210,210,210,15,15,15,-1,-1,-1,-1,15,15,15,210,210,210,-1,-1,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {82,95,95,95,95,90,80,80,80,80,153,153,153,153,153,153,153,80,80,80,80,92,95,95,95,95,84,-1,-1,17,17,17,208,208,208,208,208,208,208,208,208,17,17,17,104,104,104,104,104,104,104,104,104,104,17,17,17,208,208,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,102,102,102,102,102,102,102,102,102,102,17,17,17,17,17,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,102,102,102,102,102,102,102,102,102,102,17,17,17,17,17,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,153,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,102,102,102,102,102,102,102,102,102,102,17,17,17,17,17,50,50,50,50,50,50,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de<SUF> Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 200, 1212); addObject(hero, 200, 1212); Slime slime = new Slime(); addObject(slime, 815, 1010); addObject(new Hartje(), 815, 1010); addObject(slime, 815, 1010); addObject(new slak(), 1466, 1247); addObject(new LetterB(), 300, 972); addObject(new LetterI(), 2053, 900); addObject(new LetterK(), 2951, 1000); addObject(new LetterC(), 2900, 1000); addObject(new LetterE(), 3568, 200); //addObject(new Enemy(), 1170, 410); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } public void resetStatic() { } }
146081_7
/* * 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. */ package org.apache.commons.rng.sampling.distribution; import java.util.List; import java.util.ArrayList; import java.util.Collections; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; /** * List of samplers. */ public class ContinuousSamplersList { /** List of all RNGs implemented in the library. */ private static final List<ContinuousSamplerTestData[]> LIST = new ArrayList<ContinuousSamplerTestData[]>(); static { try { // The commons-math distributions are not used for sampling so use a null random generator org.apache.commons.math3.random.RandomGenerator rng = null; // List of distributions to test. // Gaussian ("inverse method"). final double meanNormal = -123.45; final double sigmaNormal = 6.789; add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), RandomSource.create(RandomSource.KISS)); // Gaussian (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), new BoxMullerGaussianSampler(RandomSource.create(RandomSource.MT), meanNormal, sigmaNormal)); // Gaussian ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), new GaussianSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), new GaussianSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), new GaussianSampler(new ZigguratNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Beta ("inverse method"). final double alphaBeta = 4.3; final double betaBeta = 2.1; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, alphaBeta, betaBeta), RandomSource.create(RandomSource.ISAAC)); // Beta ("Cheng"). add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, alphaBeta, betaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.MWC_256), alphaBeta, betaBeta)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, betaBeta, alphaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_A), betaBeta, alphaBeta)); // Beta ("Cheng", alternate algorithm). final double alphaBetaAlt = 0.5678; final double betaBetaAlt = 0.1234; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, alphaBetaAlt, betaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_512_A), alphaBetaAlt, betaBetaAlt)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, betaBetaAlt, alphaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_C), betaBetaAlt, alphaBetaAlt)); // Cauchy ("inverse method"). final double medianCauchy = 0.123; final double scaleCauchy = 4.5; add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(rng, medianCauchy, scaleCauchy), RandomSource.create(RandomSource.WELL_19937_C)); // Chi-square ("inverse method"). final int dofChi2 = 12; add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(rng, dofChi2), RandomSource.create(RandomSource.WELL_19937_A)); // Exponential ("inverse method"). final double meanExp = 3.45; add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(rng, meanExp), RandomSource.create(RandomSource.WELL_44497_A)); // Exponential. add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(rng, meanExp), new AhrensDieterExponentialSampler(RandomSource.create(RandomSource.MT), meanExp)); // F ("inverse method"). final int numDofF = 4; final int denomDofF = 7; add(LIST, new org.apache.commons.math3.distribution.FDistribution(rng, numDofF, denomDofF), RandomSource.create(RandomSource.MT_64)); // Gamma ("inverse method"). final double thetaGammaSmallerThanOne = 0.1234; final double thetaGammaLargerThanOne = 2.345; final double alphaGamma = 3.456; add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(rng, thetaGammaLargerThanOne, alphaGamma), RandomSource.create(RandomSource.SPLIT_MIX_64)); // Gamma (theta < 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(rng, thetaGammaSmallerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), alphaGamma, thetaGammaSmallerThanOne)); // Gamma (theta > 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(rng, thetaGammaLargerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.WELL_44497_B), alphaGamma, thetaGammaLargerThanOne)); // Gumbel ("inverse method"). final double muGumbel = -4.56; final double betaGumbel = 0.123; add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(rng, muGumbel, betaGumbel), RandomSource.create(RandomSource.WELL_1024_A)); // Laplace ("inverse method"). final double muLaplace = 12.3; final double betaLaplace = 5.6; add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(rng, muLaplace, betaLaplace), RandomSource.create(RandomSource.MWC_256)); // Levy ("inverse method"). final double muLevy = -1.098; final double cLevy = 0.76; add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(rng, muLevy, cLevy), RandomSource.create(RandomSource.TWO_CMRES)); // Log normal ("inverse method"). final double scaleLogNormal = 2.345; final double shapeLogNormal = 0.1234; add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), RandomSource.create(RandomSource.KISS)); // Log-normal (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), new BoxMullerLogNormalSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scaleLogNormal, shapeLogNormal)); // Log-normal ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S)), scaleLogNormal, shapeLogNormal)); // Log-normal ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT_64)), scaleLogNormal, shapeLogNormal)); // Log-normal ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new ZigguratNormalizedGaussianSampler(RandomSource.create(RandomSource.MWC_256)), scaleLogNormal, shapeLogNormal)); // Logistic ("inverse method"). final double muLogistic = -123.456; final double sLogistic = 7.89; add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(rng, muLogistic, sLogistic), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 2, 6)); // Nakagami ("inverse method"). final double muNakagami = 78.9; final double omegaNakagami = 23.4; final double inverseAbsoluteAccuracyNakagami = org.apache.commons.math3.distribution.NakagamiDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY; add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(rng, muNakagami, omegaNakagami, inverseAbsoluteAccuracyNakagami), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 5, 3)); // Pareto ("inverse method"). final double scalePareto = 23.45; final double shapePareto = 0.1234; add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(rng, scalePareto, shapePareto), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 9, 11)); // Pareto. add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(rng, scalePareto, shapePareto), new InverseTransformParetoSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scalePareto, shapePareto)); // T ("inverse method"). final double dofT = 0.76543; add(LIST, new org.apache.commons.math3.distribution.TDistribution(rng, dofT), RandomSource.create(RandomSource.ISAAC)); // Triangular ("inverse method"). final double aTriangle = -0.76543; final double cTriangle = -0.65432; final double bTriangle = -0.54321; add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(rng, aTriangle, cTriangle, bTriangle), RandomSource.create(RandomSource.MT)); // Uniform ("inverse method"). final double loUniform = -1.098; final double hiUniform = 0.76; add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(rng, loUniform, hiUniform), RandomSource.create(RandomSource.TWO_CMRES)); // Uniform. add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(rng, loUniform, hiUniform), new ContinuousUniformSampler(RandomSource.create(RandomSource.MT_64), loUniform, hiUniform)); // Weibull ("inverse method"). final double alphaWeibull = 678.9; final double betaWeibull = 98.76; add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(rng, alphaWeibull, betaWeibull), RandomSource.create(RandomSource.WELL_44497_B)); } catch (Exception e) { System.err.println("Unexpected exception while creating the list of samplers: " + e); e.printStackTrace(System.err); throw new RuntimeException(e); } } /** * Class contains only static methods. */ private ContinuousSamplersList() {} /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param rng Generator of uniformly distributed sequences. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, UniformRandomProvider rng) { final ContinuousSampler inverseMethodSampler = new InverseTransformContinuousSampler(rng, new ContinuousInverseCumulativeProbabilityFunction() { @Override public double inverseCumulativeProbability(double p) { return dist.inverseCumulativeProbability(p); } @Override public String toString() { return dist.toString(); } }); list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(inverseMethodSampler, getDeciles(dist)) }); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param sampler Sampler. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, final ContinuousSampler sampler) { list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(sampler, getDeciles(dist)) }); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of all generators. */ public static Iterable<ContinuousSamplerTestData[]> list() { return Collections.unmodifiableList(LIST); } /** * @param dist Distribution. * @return the deciles of the given distribution. */ private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) { final int last = 9; final double[] deciles = new double[last]; final double ten = 10; for (int i = 0; i < last; i++) { deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten); } return deciles; } }
aherbert/commons-rng
commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousSamplersList.java
3,853
// Beta ("inverse method").
line_comment
nl
/* * 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. */ package org.apache.commons.rng.sampling.distribution; import java.util.List; import java.util.ArrayList; import java.util.Collections; import org.apache.commons.rng.UniformRandomProvider; import org.apache.commons.rng.simple.RandomSource; /** * List of samplers. */ public class ContinuousSamplersList { /** List of all RNGs implemented in the library. */ private static final List<ContinuousSamplerTestData[]> LIST = new ArrayList<ContinuousSamplerTestData[]>(); static { try { // The commons-math distributions are not used for sampling so use a null random generator org.apache.commons.math3.random.RandomGenerator rng = null; // List of distributions to test. // Gaussian ("inverse method"). final double meanNormal = -123.45; final double sigmaNormal = 6.789; add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), RandomSource.create(RandomSource.KISS)); // Gaussian (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), new BoxMullerGaussianSampler(RandomSource.create(RandomSource.MT), meanNormal, sigmaNormal)); // Gaussian ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), new GaussianSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), new GaussianSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Gaussian ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(rng, meanNormal, sigmaNormal), new GaussianSampler(new ZigguratNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)), meanNormal, sigmaNormal)); // Beta ("inverse<SUF> final double alphaBeta = 4.3; final double betaBeta = 2.1; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, alphaBeta, betaBeta), RandomSource.create(RandomSource.ISAAC)); // Beta ("Cheng"). add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, alphaBeta, betaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.MWC_256), alphaBeta, betaBeta)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, betaBeta, alphaBeta), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_A), betaBeta, alphaBeta)); // Beta ("Cheng", alternate algorithm). final double alphaBetaAlt = 0.5678; final double betaBetaAlt = 0.1234; add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, alphaBetaAlt, betaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_512_A), alphaBetaAlt, betaBetaAlt)); add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(rng, betaBetaAlt, alphaBetaAlt), new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_C), betaBetaAlt, alphaBetaAlt)); // Cauchy ("inverse method"). final double medianCauchy = 0.123; final double scaleCauchy = 4.5; add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(rng, medianCauchy, scaleCauchy), RandomSource.create(RandomSource.WELL_19937_C)); // Chi-square ("inverse method"). final int dofChi2 = 12; add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(rng, dofChi2), RandomSource.create(RandomSource.WELL_19937_A)); // Exponential ("inverse method"). final double meanExp = 3.45; add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(rng, meanExp), RandomSource.create(RandomSource.WELL_44497_A)); // Exponential. add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(rng, meanExp), new AhrensDieterExponentialSampler(RandomSource.create(RandomSource.MT), meanExp)); // F ("inverse method"). final int numDofF = 4; final int denomDofF = 7; add(LIST, new org.apache.commons.math3.distribution.FDistribution(rng, numDofF, denomDofF), RandomSource.create(RandomSource.MT_64)); // Gamma ("inverse method"). final double thetaGammaSmallerThanOne = 0.1234; final double thetaGammaLargerThanOne = 2.345; final double alphaGamma = 3.456; add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(rng, thetaGammaLargerThanOne, alphaGamma), RandomSource.create(RandomSource.SPLIT_MIX_64)); // Gamma (theta < 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(rng, thetaGammaSmallerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), alphaGamma, thetaGammaSmallerThanOne)); // Gamma (theta > 1). add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(rng, thetaGammaLargerThanOne, alphaGamma), new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.WELL_44497_B), alphaGamma, thetaGammaLargerThanOne)); // Gumbel ("inverse method"). final double muGumbel = -4.56; final double betaGumbel = 0.123; add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(rng, muGumbel, betaGumbel), RandomSource.create(RandomSource.WELL_1024_A)); // Laplace ("inverse method"). final double muLaplace = 12.3; final double betaLaplace = 5.6; add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(rng, muLaplace, betaLaplace), RandomSource.create(RandomSource.MWC_256)); // Levy ("inverse method"). final double muLevy = -1.098; final double cLevy = 0.76; add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(rng, muLevy, cLevy), RandomSource.create(RandomSource.TWO_CMRES)); // Log normal ("inverse method"). final double scaleLogNormal = 2.345; final double shapeLogNormal = 0.1234; add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), RandomSource.create(RandomSource.KISS)); // Log-normal (DEPRECATED "Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), new BoxMullerLogNormalSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scaleLogNormal, shapeLogNormal)); // Log-normal ("Box-Muller"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S)), scaleLogNormal, shapeLogNormal)); // Log-normal ("Marsaglia"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new MarsagliaNormalizedGaussianSampler(RandomSource.create(RandomSource.MT_64)), scaleLogNormal, shapeLogNormal)); // Log-normal ("Ziggurat"). add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(rng, scaleLogNormal, shapeLogNormal), new LogNormalSampler(new ZigguratNormalizedGaussianSampler(RandomSource.create(RandomSource.MWC_256)), scaleLogNormal, shapeLogNormal)); // Logistic ("inverse method"). final double muLogistic = -123.456; final double sLogistic = 7.89; add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(rng, muLogistic, sLogistic), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 2, 6)); // Nakagami ("inverse method"). final double muNakagami = 78.9; final double omegaNakagami = 23.4; final double inverseAbsoluteAccuracyNakagami = org.apache.commons.math3.distribution.NakagamiDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY; add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(rng, muNakagami, omegaNakagami, inverseAbsoluteAccuracyNakagami), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 5, 3)); // Pareto ("inverse method"). final double scalePareto = 23.45; final double shapePareto = 0.1234; add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(rng, scalePareto, shapePareto), RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 9, 11)); // Pareto. add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(rng, scalePareto, shapePareto), new InverseTransformParetoSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scalePareto, shapePareto)); // T ("inverse method"). final double dofT = 0.76543; add(LIST, new org.apache.commons.math3.distribution.TDistribution(rng, dofT), RandomSource.create(RandomSource.ISAAC)); // Triangular ("inverse method"). final double aTriangle = -0.76543; final double cTriangle = -0.65432; final double bTriangle = -0.54321; add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(rng, aTriangle, cTriangle, bTriangle), RandomSource.create(RandomSource.MT)); // Uniform ("inverse method"). final double loUniform = -1.098; final double hiUniform = 0.76; add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(rng, loUniform, hiUniform), RandomSource.create(RandomSource.TWO_CMRES)); // Uniform. add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(rng, loUniform, hiUniform), new ContinuousUniformSampler(RandomSource.create(RandomSource.MT_64), loUniform, hiUniform)); // Weibull ("inverse method"). final double alphaWeibull = 678.9; final double betaWeibull = 98.76; add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(rng, alphaWeibull, betaWeibull), RandomSource.create(RandomSource.WELL_44497_B)); } catch (Exception e) { System.err.println("Unexpected exception while creating the list of samplers: " + e); e.printStackTrace(System.err); throw new RuntimeException(e); } } /** * Class contains only static methods. */ private ContinuousSamplersList() {} /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param rng Generator of uniformly distributed sequences. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, UniformRandomProvider rng) { final ContinuousSampler inverseMethodSampler = new InverseTransformContinuousSampler(rng, new ContinuousInverseCumulativeProbabilityFunction() { @Override public double inverseCumulativeProbability(double p) { return dist.inverseCumulativeProbability(p); } @Override public String toString() { return dist.toString(); } }); list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(inverseMethodSampler, getDeciles(dist)) }); } /** * @param list List of data (one the "parameters" tested by the Junit parametric test). * @param dist Distribution to which the samples are supposed to conform. * @param sampler Sampler. */ private static void add(List<ContinuousSamplerTestData[]> list, final org.apache.commons.math3.distribution.RealDistribution dist, final ContinuousSampler sampler) { list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(sampler, getDeciles(dist)) }); } /** * Subclasses that are "parametric" tests can forward the call to * the "@Parameters"-annotated method to this method. * * @return the list of all generators. */ public static Iterable<ContinuousSamplerTestData[]> list() { return Collections.unmodifiableList(LIST); } /** * @param dist Distribution. * @return the deciles of the given distribution. */ private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) { final int last = 9; final double[] deciles = new double[last]; final double ten = 10; for (int i = 0; i < last; i++) { deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten); } return deciles; } }
19825_1
package apps.myapplication; /** * Created by Boning on 21-8-2015. */ public class ThreeRow { private static int Block1; private static int Block2; public ThreeRow(int B1, int B2) { this.Block1 = B1; this.Block2 = B2; } public int[] calcOptions() { int[] res = new int[2]; int option1; int option2; // Block1 ligt rechts van block2 if((Block1 - Block2) == 1) { option1 = Block1 + 1; option2 = Block2 - 1; res[0] = option1; res[1] = option2; return res; } // Block1 ligt boven Block2 else if((Block1 - Block2) == 10) { option1 = Block1 + 10; option2 = Block2 - 10; res[0] = option1; res[1] = option2; return res; } // Block1 ligt rechtsonder Block2 else if((Block1 - Block2) == 11) { option1 = Block1 + 11; option2 = Block2 - 11; res[0] = option1; res[1] = option2; return res; } // Block1 ligt linksonder Block2 else if((Block1 - Block2) == 9) { option1 = Block1 + 9; option2 = Block2 - 9; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd naast elkaar met 1 block ertussen in else if((Block1 - Block2) == 2) { option1 = Block1 - 1; option2 = Block2 + 1; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd boven elkaar met 1 block ertussen in else if((Block1 - Block2 == 20)) { option1 = Block1 - 10; option2 = Block2 + 10; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd rechts schuinonder elkaar met 1 block ertussen in else if((Block1 - Block2 == 22)) { option1 = Block1 - 11; option2 = Block2 + 11; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd links schuinonder elkaar met 1 block ertussen in else if((Block1 - Block2 == 18)) { option1 = Block1 - 9; option2 = Block2 + 9; res[0] = option1; res[1] = option2; return res; } return null; } public int getBlock1() { return Block1; } public int getBlock2() { return Block2; } public void setBlock1(int B1) { Block1 = B1; } public void setBlock2(int B2) { Block2 = B2; } }
TimBuckers/AndroidApp
app/src/main/java/apps/myapplication/ThreeRow.java
913
// Block1 ligt rechts van block2
line_comment
nl
package apps.myapplication; /** * Created by Boning on 21-8-2015. */ public class ThreeRow { private static int Block1; private static int Block2; public ThreeRow(int B1, int B2) { this.Block1 = B1; this.Block2 = B2; } public int[] calcOptions() { int[] res = new int[2]; int option1; int option2; // Block1 ligt<SUF> if((Block1 - Block2) == 1) { option1 = Block1 + 1; option2 = Block2 - 1; res[0] = option1; res[1] = option2; return res; } // Block1 ligt boven Block2 else if((Block1 - Block2) == 10) { option1 = Block1 + 10; option2 = Block2 - 10; res[0] = option1; res[1] = option2; return res; } // Block1 ligt rechtsonder Block2 else if((Block1 - Block2) == 11) { option1 = Block1 + 11; option2 = Block2 - 11; res[0] = option1; res[1] = option2; return res; } // Block1 ligt linksonder Block2 else if((Block1 - Block2) == 9) { option1 = Block1 + 9; option2 = Block2 - 9; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd naast elkaar met 1 block ertussen in else if((Block1 - Block2) == 2) { option1 = Block1 - 1; option2 = Block2 + 1; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd boven elkaar met 1 block ertussen in else if((Block1 - Block2 == 20)) { option1 = Block1 - 10; option2 = Block2 + 10; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd rechts schuinonder elkaar met 1 block ertussen in else if((Block1 - Block2 == 22)) { option1 = Block1 - 11; option2 = Block2 + 11; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd links schuinonder elkaar met 1 block ertussen in else if((Block1 - Block2 == 18)) { option1 = Block1 - 9; option2 = Block2 + 9; res[0] = option1; res[1] = option2; return res; } return null; } public int getBlock1() { return Block1; } public int getBlock2() { return Block2; } public void setBlock1(int B1) { Block1 = B1; } public void setBlock2(int B2) { Block2 = B2; } }
144120_6
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.10.21 at 02:36:24 PM CEST // package nl.wetten.bwbng.toestand; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{}verdragspartij"/> * &lt;element ref="{}datum-ratificatie"/> * &lt;element ref="{}voorbehouden" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "verdragspartij", "datumRatificatie", "voorbehouden" }) @XmlRootElement(name = "partij-gegevens") public class PartijGegevens { @XmlElement(required = true) protected Verdragspartij verdragspartij; @XmlElement(name = "datum-ratificatie", required = true) protected DatumRatificatie datumRatificatie; protected Voorbehouden voorbehouden; /** * Gets the value of the verdragspartij property. * * @return * possible object is * {@link Verdragspartij } * */ public Verdragspartij getVerdragspartij() { return verdragspartij; } /** * Sets the value of the verdragspartij property. * * @param value * allowed object is * {@link Verdragspartij } * */ public void setVerdragspartij(Verdragspartij value) { this.verdragspartij = value; } /** * Gets the value of the datumRatificatie property. * * @return * possible object is * {@link DatumRatificatie } * */ public DatumRatificatie getDatumRatificatie() { return datumRatificatie; } /** * Sets the value of the datumRatificatie property. * * @param value * allowed object is * {@link DatumRatificatie } * */ public void setDatumRatificatie(DatumRatificatie value) { this.datumRatificatie = value; } /** * Gets the value of the voorbehouden property. * * @return * possible object is * {@link Voorbehouden } * */ public Voorbehouden getVoorbehouden() { return voorbehouden; } /** * Sets the value of the voorbehouden property. * * @param value * allowed object is * {@link Voorbehouden } * */ public void setVoorbehouden(Voorbehouden value) { this.voorbehouden = value; } }
digitalheir/java-wetten-nl-library
src/main/java/nl/wetten/bwbng/toestand/PartijGegevens.java
997
/** * Sets the value of the verdragspartij property. * * @param value * allowed object is * {@link Verdragspartij } * */
block_comment
nl
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.10.21 at 02:36:24 PM CEST // package nl.wetten.bwbng.toestand; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{}verdragspartij"/> * &lt;element ref="{}datum-ratificatie"/> * &lt;element ref="{}voorbehouden" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "verdragspartij", "datumRatificatie", "voorbehouden" }) @XmlRootElement(name = "partij-gegevens") public class PartijGegevens { @XmlElement(required = true) protected Verdragspartij verdragspartij; @XmlElement(name = "datum-ratificatie", required = true) protected DatumRatificatie datumRatificatie; protected Voorbehouden voorbehouden; /** * Gets the value of the verdragspartij property. * * @return * possible object is * {@link Verdragspartij } * */ public Verdragspartij getVerdragspartij() { return verdragspartij; } /** * Sets the value<SUF>*/ public void setVerdragspartij(Verdragspartij value) { this.verdragspartij = value; } /** * Gets the value of the datumRatificatie property. * * @return * possible object is * {@link DatumRatificatie } * */ public DatumRatificatie getDatumRatificatie() { return datumRatificatie; } /** * Sets the value of the datumRatificatie property. * * @param value * allowed object is * {@link DatumRatificatie } * */ public void setDatumRatificatie(DatumRatificatie value) { this.datumRatificatie = value; } /** * Gets the value of the voorbehouden property. * * @return * possible object is * {@link Voorbehouden } * */ public Voorbehouden getVoorbehouden() { return voorbehouden; } /** * Sets the value of the voorbehouden property. * * @param value * allowed object is * {@link Voorbehouden } * */ public void setVoorbehouden(Voorbehouden value) { this.voorbehouden = value; } }
34870_8
package reviewme; import java.util.*; public class ReviewMe { static Scanner scanner = new Scanner(System.in); static ArrayList <Gebruiker> gebruikers = new ArrayList<>(); static ArrayList <Item> items = new ArrayList<>(); static int gebruikerId = 2; static int uploadCount; private int keuze; private int itemId; //starten van de applicatie void start(){ laadGebruikers(); //inladen van gebruikers laadUploads(); //inladen van uploads laadDummies();//Inladen van gegeven cijfers (Dummies) titelBlok("Welkom bij ReviewMe!"); login(); } void login(){ boolean loginValidated = false; while(loginValidated == false){ titelBlok("LOGIN"); System.out.print("Gebruikersnaam: "); String gebruikersnaam = scanner.nextLine(); System.out.print("Password: "); String wachtwoord = scanner.nextLine(); boolean gelijkeGebruikersnaam = false; for(int i=0; i<gebruikers.size(); i++){ if(gebruikersnaam.equals(gebruikers.get(i).getGebruikersNaam())){ gelijkeGebruikersnaam = true; if(wachtwoord.equals(gebruikers.get(i).getWachtwoord())){ loginValidated = true; gebruikerId = i; } else { System.out.println("Combinatie gebruikersnaam en/of wachtwoord onbekend\nProbeer het opnieuw..."); scanner.nextLine(); } } } if(gelijkeGebruikersnaam == false){ System.out.println("Combinatie gebruikersnaam en/of wachtwoord onbekend\nProbeer het opnieuw..."); scanner.nextLine(); } } System.out.println(gebruikers.get(gebruikerId).getGebruikersNaam()+" het inloggen is gelukt!"); hoofdMenu(); } //Menu om items te reviewen void hoofdMenu(){ String categorie [] = {"Boeken","Muziek","Video's"}; boolean keuzeGemaakt = false; while (keuzeGemaakt == false){ titelBlok("Maak een keuze:"); for (int i = 0; i < categorie.length; i++) { System.out.println((i+1)+" : "+categorie[i]); } //optie voor afsluiten of in geval van uploader naar hoofdmenu gaan. if (gebruikers.get(gebruikerId) instanceof Uploader){ System.out.println("U : Upload item"); } System.out.println("I : Gebruikersinfo"); System.out.println("L : Log uit"); System.out.println("X : Sluit af"); System.out.println(); String keuze = scanner.nextLine().toUpperCase(); switch(keuze){ case "X": System.exit(1); break; case "1": keuzeGemaakt = true; boekenLijst(); break; case "2": keuzeGemaakt = true; songLijst(); break; case "3": keuzeGemaakt = true; videoLijst(); break; case "U": if(gebruikers.get(gebruikerId) instanceof Uploader){ System.out.println("uploadMenu"); keuzeGemaakt = true; break; } else { System.out.println("Deze keuze zit er niet tussen. Probeer opnieuw..."); keuzeGemaakt = false; break; } case "I": keuzeGemaakt = true; gebruikersInfoMenu(); break; case "L": keuzeGemaakt = true; System.out.println("U bent nu uitgelogd. \n====================\nDruk op een toets om door te gaan..."); scanner.nextLine(); login(); break; default: System.out.println("Deze keuze zit er niet tussen. Probeer opnieuw..."); keuzeGemaakt = false; break; } } while (keuzeGemaakt == false); } //invoer moet een int zijn anders moet er opnieuw ingevoerd worden void valideerInvoer(){ keuze = -1; try { keuze = scanner.nextInt(); } catch (InputMismatchException ime){ scanner.nextLine(); } } //Menu per categorie void boekenLijst(){ int aantalBoeken = 0; for(int i=0; i < items.size(); i++){ if(items.get(i) instanceof Boek){ aantalBoeken++; } } int boekKeuze = 0; int [] boekenlijst = new int[aantalBoeken]; boolean keuzeGemaakt = false; while(keuzeGemaakt == false){ titelBlok("Kies een boek:"); int index = 0; for (int i = 0; i < items.size(); i++) { if(items.get(i) instanceof Boek){ System.out.println((index+1)+" : "+ items.get(i).getTitel()); boekenlijst[index] = i; index++; } } System.out.println("0 : Terug naar vorig menu"); valideerInvoer(); boekKeuze = keuze; for (int i = 0; i < boekenlijst.length; i++) { if(boekKeuze == (i+1)){ keuzeGemaakt = true; boekKeuze--; } } if(keuze == 0){ hoofdMenu(); keuzeGemaakt = true; }else if (!keuzeGemaakt){ System.out.println("Verkeerde invoer. Probeer opnieuw..."); } } itemId = boekenlijst[boekKeuze]; itemMenu(); } void videoLijst(){ int aantalVideos = 0; for(int i=0; i < items.size(); i++){ if(items.get(i) instanceof Video){ aantalVideos++; } } int videoKeuze = 0; int [] videolijst = new int[aantalVideos]; boolean keuzeGemaakt = false; while(keuzeGemaakt == false){ titelBlok("Kies een video:"); int index = 0; for (int i = 0; i < items.size(); i++) { if(items.get(i) instanceof Video){ System.out.println((index+1)+" : "+ items.get(i).getTitel()); videolijst[index] = i; index++; } } System.out.println("0 : Terug naar vorig menu"); valideerInvoer(); videoKeuze = keuze; for (int i = 0; i < videolijst.length; i++) { if(videoKeuze == (i+1)){ keuzeGemaakt = true; videoKeuze--; } } if(keuze == 0){ hoofdMenu(); keuzeGemaakt = true; }else if (!keuzeGemaakt){ System.out.println("Verkeerde invoer. Probeer opnieuw..."); } } itemId = videolijst[videoKeuze]; itemMenu(); } void songLijst(){ int aantalSongs = 0; for(int i=0; i < items.size(); i++){ if(items.get(i) instanceof Song){ aantalSongs++; } } int songKeuze = 0; int [] songlijst = new int[aantalSongs]; boolean keuzeGemaakt = false; while(keuzeGemaakt == false){ titelBlok("Kies een lied:"); int index = 0; for (int i = 0; i < items.size(); i++) { if(items.get(i) instanceof Song){ System.out.println((index+1)+" : "+ items.get(i).getTitel()); songlijst[index] = i; index++; } } System.out.println("0 : Terug naar vorig menu"); valideerInvoer(); songKeuze = keuze; for (int i = 0; i < songlijst.length; i++) { if(songKeuze == (i+1)){ keuzeGemaakt = true; songKeuze--; } } if(keuze == 0){ hoofdMenu(); keuzeGemaakt = true; }else if (!keuzeGemaakt){ System.out.println("Verkeerde invoer. Probeer opnieuw..."); } } itemId = songlijst[songKeuze]; itemMenu(); } //menu van een item zelf void itemMenu(){ boolean keuzeGemaakt = false; while (keuzeGemaakt == false){ titelBlok("U heeft gekozen voor: "+ items.get(itemId).getTitel()); System.out.print("Gemiddelde cijfer: "); System.out.printf("%.1f", getGemiddeldeCijfer()); System.out.println("\n============================"); System.out.println("1 : Info over item"); System.out.println("2 : Geef een cijfer"); System.out.println("0 : Ga terug naar vorig menu"); valideerInvoer(); switch(keuze){ case 1: System.out.println("Infomenu"); keuzeGemaakt = true; break; case 2: cijferGeven(); keuzeGemaakt = true; break; case 0: if(items.get(itemId) instanceof Boek){ boekenLijst(); }else if(items.get(itemId) instanceof Song){ songLijst(); }else if(items.get(itemId) instanceof Video){ videoLijst(); } keuzeGemaakt = true; break; default: System.out.println("Verkeerde invoer. Probeer opnieuw..."); keuzeGemaakt = false; break; } } } //methode voor het geven van een cijfer void cijferGeven(){ int cijfer; //loop ter verificatie van een juiste invoer boolean keuzeGemaakt = false; while(keuzeGemaakt == false){ boolean cijferAlGegeven = false; int cijferIndexGebruiker = 0; int cijferIndexItem = 0; titelBlok(items.get(itemId).getTitel()); //Kijken of item al beoordeeld is door Gebruiker for(int i = 0; i < gebruikers.get(gebruikerId).getItemId().size(); i++){ if(itemId == (int) gebruikers.get(gebruikerId).getItemId().get(i)){ cijferIndexGebruiker = i; cijferIndexItem = items.get(itemId).getGebruikerId().indexOf(gebruikerId); cijferAlGegeven = true; System.out.println("U heeft eerder een "+ gebruikers.get(gebruikerId).getCijferlijst().get(i)+".0 gegeven."); } } //Geven van een cijfer System.out.println("Geef een cijfer van 0 t/m 10:"); valideerInvoer();//controle of het een geldige invoer is if(keuze >= 0 && keuze <11){ cijfer = keuze; System.out.println("U heeft een "+ cijfer + ".0 gegeven."); System.out.println("Druk op een toets om verder te gaan..."); System.out.println(); scanner.nextLine(); //cijfer toevoegen indien gebruiker nog niet eerder cijfer heeft gegeven //cijfer wijzigen indien gebruiker item al eerder een cijfer heeft gegeven if(cijferAlGegeven){ gebruikers.get(gebruikerId).changeCijfer(cijferIndexGebruiker, itemId, cijfer); items.get(itemId).changeCijfer(cijferIndexItem, gebruikerId, cijfer); }else{ gebruikers.get(gebruikerId).addCijfer(itemId, cijfer); items.get(itemId).addCijfer(gebruikerId, cijfer); } keuzeGemaakt = true; } else { System.out.println("Verkeerde invoer. Probeer opnieuw..."); keuzeGemaakt = false; } } itemMenu(); } //laden van vooraf ingevoerde gegevens (gebruikers en uploads) void laadGebruikers(){ gebruikers.add((Reviewer)new Reviewer("Manuel","123"));//0 gebruikers.add((Reviewer)new Reviewer("Bertho","123"));//1 gebruikers.add((Uploader)new Uploader("Jase","345"));//2 gebruikers.add((Uploader)new Uploader("Iwan","345"));//3 } void laadUploads(){ items.add((Boek)new Boek(0,"Wetten der Magie")); items.add((Boek)new Boek(1,"Yab Yum")); items.add((Boek)new Boek(2,"Het testament")); items.add((Song)new Song(3,"Brindis")); items.add((Song)new Song(4,"Hold up")); items.add((Song)new Song(5,"Bohemian Rhapsody")); items.add((Video)new Video(6,"Card flourishes")); items.add((Video)new Video(7,"Shawshank Redemption")); items.add((Video)new Video(8,"How to make cocktails")); items.add((Boek)new Boek(9,"Max Havelaar")); uploadCount = items.size(); } //menu voor het krijgen van gebruikersinfo void gebruikersInfoMenu(){ boolean keuzeGemaakt = false; while (keuzeGemaakt == false){ titelBlok("Ingelogde gebruiker: "+gebruikers.get(gebruikerId).getGebruikersNaam()); System.out.println("1 : Wijzig gegevens"); System.out.println("2 : Gegeven cijfers"); if(gebruikers.get(gebruikerId) instanceof Uploader){ System.out.println("3 : Bekijk je uploads"); } System.out.println("0 : Hoofdmenu"); valideerInvoer(); switch(keuze){ case 0: hoofdMenu(); keuzeGemaakt = true; break; case 1: System.out.println("Wijzig gegevens"); keuzeGemaakt = true; break; case 2: gegevenCijfers(); keuzeGemaakt = true; break; case 3: if(gebruikers.get(gebruikerId) instanceof Uploader){ System.out.println("Hier komt uploadMenu"); keuzeGemaakt = true; break; } else { System.out.println("Verkeerde invoer. Probeer opnieuw..."); keuzeGemaakt = false; break; } default: System.out.println("Verkeerde invoer. Probeer opnieuw..."); keuzeGemaakt = false; break; } } } void gegevenCijfers(){ titelBlok("U heeft de volgende cijfers gegeven:"); for (int i = 0; i < gebruikers.get(gebruikerId).getCijferlijst().size(); i++) { int idOfItem = (int) gebruikers.get(gebruikerId).getItemId().get(i); System.out.println(items.get(idOfItem).getClass().getSimpleName()); System.out.println(items.get(idOfItem).getTitel()); System.out.println("cijfer: " + gebruikers.get(gebruikerId).getCijferlijst().get(i)+".0"); System.out.println("------------------------------------"); } System.out.println("Druk op een toets om verder te gaan..."); scanner.nextLine(); scanner.nextLine(); gebruikersInfoMenu(); } double getGemiddeldeCijfer(){ int aantal = items.get(itemId).getCijferlijst().size(); double totaal = 0; for (int i = 0; i < aantal; i++) { totaal = totaal + (int)items.get(itemId).getCijferlijst().get(i); } return totaal/aantal; } void titelBlok(String titelBlokTitel){ String a = "*"; System.out.print("\n"+a+a); for (int i = 0; i < titelBlokTitel.length(); i++) { System.out.print(a); } System.out.print(a+a+"\n"); System.out.println(a+" "+titelBlokTitel+" "+a); System.out.print(a+a); for (int i = 0; i < titelBlokTitel.length(); i++) { System.out.print(a); } System.out.println(a+a+"\n"); } //////////////////// void laadDummies(){ //gebruiker 2 gebruikers.get(2).addCijfer(0, 8); items.get(0).addCijfer(2, 8); gebruikers.get(2).addCijfer(1, 7); items.get(1).addCijfer(2, 7); gebruikers.get(2).addCijfer(2, 6); items.get(2).addCijfer(2, 6); gebruikers.get(2).addCijfer(3, 5); items.get(3).addCijfer(2, 5); gebruikers.get(2).addCijfer(4, 6); items.get(4).addCijfer(2, 6); gebruikers.get(2).addCijfer(5, 8); items.get(5).addCijfer(2, 8); gebruikers.get(2).addCijfer(6, 9); items.get(6).addCijfer(2, 9); gebruikers.get(2).addCijfer(7, 4); items.get(7).addCijfer(2, 4); gebruikers.get(2).addCijfer(8, 3); items.get(8).addCijfer(2, 3); gebruikers.get(2).addCijfer(9, 3); items.get(9).addCijfer(2, 6); //gebruiker 0 gebruikers.get(0).addCijfer(0, 10); items.get(0).addCijfer(0, 10); gebruikers.get(0).addCijfer(1, 6); items.get(1).addCijfer(0, 6); gebruikers.get(0).addCijfer(2, 6); items.get(2).addCijfer(0, 6); gebruikers.get(0).addCijfer(3, 7); items.get(3).addCijfer(0, 7); gebruikers.get(0).addCijfer(4, 5); items.get(4).addCijfer(0, 5); gebruikers.get(0).addCijfer(5, 3); items.get(5).addCijfer(0, 3); gebruikers.get(0).addCijfer(6, 5); items.get(6).addCijfer(0, 5); gebruikers.get(0).addCijfer(7, 5); items.get(7).addCijfer(0, 5); gebruikers.get(0).addCijfer(8, 6); items.get(8).addCijfer(0, 6); gebruikers.get(0).addCijfer(9, 2); items.get(9).addCijfer(0, 2); //gebruiker 1 gebruikers.get(1).addCijfer(0, 7); items.get(0).addCijfer(1, 7); gebruikers.get(1).addCijfer(1, 7); items.get(1).addCijfer(1, 7); gebruikers.get(1).addCijfer(2, 6); items.get(2).addCijfer(1, 6); gebruikers.get(1).addCijfer(3, 7); items.get(3).addCijfer(1, 7); gebruikers.get(1).addCijfer(4, 5); items.get(4).addCijfer(1, 5); gebruikers.get(1).addCijfer(5, 6); items.get(5).addCijfer(1, 6); gebruikers.get(1).addCijfer(6, 7); items.get(6).addCijfer(1, 7); gebruikers.get(1).addCijfer(7, 5); items.get(7).addCijfer(1, 5); gebruikers.get(1).addCijfer(8, 8); items.get(8).addCijfer(1, 8); gebruikers.get(1).addCijfer(9, 5); items.get(9).addCijfer(1, 5); //gebruiker 3 gebruikers.get(3).addCijfer(0, 8); items.get(0).addCijfer(3, 8); gebruikers.get(3).addCijfer(1, 8); items.get(1).addCijfer(3, 8); gebruikers.get(3).addCijfer(2, 4); items.get(2).addCijfer(3, 4); gebruikers.get(3).addCijfer(3, 7); items.get(3).addCijfer(3, 7); gebruikers.get(3).addCijfer(4, 9); items.get(4).addCijfer(3, 9); gebruikers.get(3).addCijfer(5, 9); items.get(5).addCijfer(3, 9); gebruikers.get(3).addCijfer(6, 5); items.get(6).addCijfer(3, 5); gebruikers.get(3).addCijfer(7, 7); items.get(7).addCijfer(3, 7); gebruikers.get(3).addCijfer(8, 7); items.get(8).addCijfer(3, 7); gebruikers.get(3).addCijfer(9, 6); items.get(9).addCijfer(3, 6); } }
jaseterhaar/ReviewMe
src/reviewme/ReviewMe.java
5,829
//menu van een item zelf
line_comment
nl
package reviewme; import java.util.*; public class ReviewMe { static Scanner scanner = new Scanner(System.in); static ArrayList <Gebruiker> gebruikers = new ArrayList<>(); static ArrayList <Item> items = new ArrayList<>(); static int gebruikerId = 2; static int uploadCount; private int keuze; private int itemId; //starten van de applicatie void start(){ laadGebruikers(); //inladen van gebruikers laadUploads(); //inladen van uploads laadDummies();//Inladen van gegeven cijfers (Dummies) titelBlok("Welkom bij ReviewMe!"); login(); } void login(){ boolean loginValidated = false; while(loginValidated == false){ titelBlok("LOGIN"); System.out.print("Gebruikersnaam: "); String gebruikersnaam = scanner.nextLine(); System.out.print("Password: "); String wachtwoord = scanner.nextLine(); boolean gelijkeGebruikersnaam = false; for(int i=0; i<gebruikers.size(); i++){ if(gebruikersnaam.equals(gebruikers.get(i).getGebruikersNaam())){ gelijkeGebruikersnaam = true; if(wachtwoord.equals(gebruikers.get(i).getWachtwoord())){ loginValidated = true; gebruikerId = i; } else { System.out.println("Combinatie gebruikersnaam en/of wachtwoord onbekend\nProbeer het opnieuw..."); scanner.nextLine(); } } } if(gelijkeGebruikersnaam == false){ System.out.println("Combinatie gebruikersnaam en/of wachtwoord onbekend\nProbeer het opnieuw..."); scanner.nextLine(); } } System.out.println(gebruikers.get(gebruikerId).getGebruikersNaam()+" het inloggen is gelukt!"); hoofdMenu(); } //Menu om items te reviewen void hoofdMenu(){ String categorie [] = {"Boeken","Muziek","Video's"}; boolean keuzeGemaakt = false; while (keuzeGemaakt == false){ titelBlok("Maak een keuze:"); for (int i = 0; i < categorie.length; i++) { System.out.println((i+1)+" : "+categorie[i]); } //optie voor afsluiten of in geval van uploader naar hoofdmenu gaan. if (gebruikers.get(gebruikerId) instanceof Uploader){ System.out.println("U : Upload item"); } System.out.println("I : Gebruikersinfo"); System.out.println("L : Log uit"); System.out.println("X : Sluit af"); System.out.println(); String keuze = scanner.nextLine().toUpperCase(); switch(keuze){ case "X": System.exit(1); break; case "1": keuzeGemaakt = true; boekenLijst(); break; case "2": keuzeGemaakt = true; songLijst(); break; case "3": keuzeGemaakt = true; videoLijst(); break; case "U": if(gebruikers.get(gebruikerId) instanceof Uploader){ System.out.println("uploadMenu"); keuzeGemaakt = true; break; } else { System.out.println("Deze keuze zit er niet tussen. Probeer opnieuw..."); keuzeGemaakt = false; break; } case "I": keuzeGemaakt = true; gebruikersInfoMenu(); break; case "L": keuzeGemaakt = true; System.out.println("U bent nu uitgelogd. \n====================\nDruk op een toets om door te gaan..."); scanner.nextLine(); login(); break; default: System.out.println("Deze keuze zit er niet tussen. Probeer opnieuw..."); keuzeGemaakt = false; break; } } while (keuzeGemaakt == false); } //invoer moet een int zijn anders moet er opnieuw ingevoerd worden void valideerInvoer(){ keuze = -1; try { keuze = scanner.nextInt(); } catch (InputMismatchException ime){ scanner.nextLine(); } } //Menu per categorie void boekenLijst(){ int aantalBoeken = 0; for(int i=0; i < items.size(); i++){ if(items.get(i) instanceof Boek){ aantalBoeken++; } } int boekKeuze = 0; int [] boekenlijst = new int[aantalBoeken]; boolean keuzeGemaakt = false; while(keuzeGemaakt == false){ titelBlok("Kies een boek:"); int index = 0; for (int i = 0; i < items.size(); i++) { if(items.get(i) instanceof Boek){ System.out.println((index+1)+" : "+ items.get(i).getTitel()); boekenlijst[index] = i; index++; } } System.out.println("0 : Terug naar vorig menu"); valideerInvoer(); boekKeuze = keuze; for (int i = 0; i < boekenlijst.length; i++) { if(boekKeuze == (i+1)){ keuzeGemaakt = true; boekKeuze--; } } if(keuze == 0){ hoofdMenu(); keuzeGemaakt = true; }else if (!keuzeGemaakt){ System.out.println("Verkeerde invoer. Probeer opnieuw..."); } } itemId = boekenlijst[boekKeuze]; itemMenu(); } void videoLijst(){ int aantalVideos = 0; for(int i=0; i < items.size(); i++){ if(items.get(i) instanceof Video){ aantalVideos++; } } int videoKeuze = 0; int [] videolijst = new int[aantalVideos]; boolean keuzeGemaakt = false; while(keuzeGemaakt == false){ titelBlok("Kies een video:"); int index = 0; for (int i = 0; i < items.size(); i++) { if(items.get(i) instanceof Video){ System.out.println((index+1)+" : "+ items.get(i).getTitel()); videolijst[index] = i; index++; } } System.out.println("0 : Terug naar vorig menu"); valideerInvoer(); videoKeuze = keuze; for (int i = 0; i < videolijst.length; i++) { if(videoKeuze == (i+1)){ keuzeGemaakt = true; videoKeuze--; } } if(keuze == 0){ hoofdMenu(); keuzeGemaakt = true; }else if (!keuzeGemaakt){ System.out.println("Verkeerde invoer. Probeer opnieuw..."); } } itemId = videolijst[videoKeuze]; itemMenu(); } void songLijst(){ int aantalSongs = 0; for(int i=0; i < items.size(); i++){ if(items.get(i) instanceof Song){ aantalSongs++; } } int songKeuze = 0; int [] songlijst = new int[aantalSongs]; boolean keuzeGemaakt = false; while(keuzeGemaakt == false){ titelBlok("Kies een lied:"); int index = 0; for (int i = 0; i < items.size(); i++) { if(items.get(i) instanceof Song){ System.out.println((index+1)+" : "+ items.get(i).getTitel()); songlijst[index] = i; index++; } } System.out.println("0 : Terug naar vorig menu"); valideerInvoer(); songKeuze = keuze; for (int i = 0; i < songlijst.length; i++) { if(songKeuze == (i+1)){ keuzeGemaakt = true; songKeuze--; } } if(keuze == 0){ hoofdMenu(); keuzeGemaakt = true; }else if (!keuzeGemaakt){ System.out.println("Verkeerde invoer. Probeer opnieuw..."); } } itemId = songlijst[songKeuze]; itemMenu(); } //menu van<SUF> void itemMenu(){ boolean keuzeGemaakt = false; while (keuzeGemaakt == false){ titelBlok("U heeft gekozen voor: "+ items.get(itemId).getTitel()); System.out.print("Gemiddelde cijfer: "); System.out.printf("%.1f", getGemiddeldeCijfer()); System.out.println("\n============================"); System.out.println("1 : Info over item"); System.out.println("2 : Geef een cijfer"); System.out.println("0 : Ga terug naar vorig menu"); valideerInvoer(); switch(keuze){ case 1: System.out.println("Infomenu"); keuzeGemaakt = true; break; case 2: cijferGeven(); keuzeGemaakt = true; break; case 0: if(items.get(itemId) instanceof Boek){ boekenLijst(); }else if(items.get(itemId) instanceof Song){ songLijst(); }else if(items.get(itemId) instanceof Video){ videoLijst(); } keuzeGemaakt = true; break; default: System.out.println("Verkeerde invoer. Probeer opnieuw..."); keuzeGemaakt = false; break; } } } //methode voor het geven van een cijfer void cijferGeven(){ int cijfer; //loop ter verificatie van een juiste invoer boolean keuzeGemaakt = false; while(keuzeGemaakt == false){ boolean cijferAlGegeven = false; int cijferIndexGebruiker = 0; int cijferIndexItem = 0; titelBlok(items.get(itemId).getTitel()); //Kijken of item al beoordeeld is door Gebruiker for(int i = 0; i < gebruikers.get(gebruikerId).getItemId().size(); i++){ if(itemId == (int) gebruikers.get(gebruikerId).getItemId().get(i)){ cijferIndexGebruiker = i; cijferIndexItem = items.get(itemId).getGebruikerId().indexOf(gebruikerId); cijferAlGegeven = true; System.out.println("U heeft eerder een "+ gebruikers.get(gebruikerId).getCijferlijst().get(i)+".0 gegeven."); } } //Geven van een cijfer System.out.println("Geef een cijfer van 0 t/m 10:"); valideerInvoer();//controle of het een geldige invoer is if(keuze >= 0 && keuze <11){ cijfer = keuze; System.out.println("U heeft een "+ cijfer + ".0 gegeven."); System.out.println("Druk op een toets om verder te gaan..."); System.out.println(); scanner.nextLine(); //cijfer toevoegen indien gebruiker nog niet eerder cijfer heeft gegeven //cijfer wijzigen indien gebruiker item al eerder een cijfer heeft gegeven if(cijferAlGegeven){ gebruikers.get(gebruikerId).changeCijfer(cijferIndexGebruiker, itemId, cijfer); items.get(itemId).changeCijfer(cijferIndexItem, gebruikerId, cijfer); }else{ gebruikers.get(gebruikerId).addCijfer(itemId, cijfer); items.get(itemId).addCijfer(gebruikerId, cijfer); } keuzeGemaakt = true; } else { System.out.println("Verkeerde invoer. Probeer opnieuw..."); keuzeGemaakt = false; } } itemMenu(); } //laden van vooraf ingevoerde gegevens (gebruikers en uploads) void laadGebruikers(){ gebruikers.add((Reviewer)new Reviewer("Manuel","123"));//0 gebruikers.add((Reviewer)new Reviewer("Bertho","123"));//1 gebruikers.add((Uploader)new Uploader("Jase","345"));//2 gebruikers.add((Uploader)new Uploader("Iwan","345"));//3 } void laadUploads(){ items.add((Boek)new Boek(0,"Wetten der Magie")); items.add((Boek)new Boek(1,"Yab Yum")); items.add((Boek)new Boek(2,"Het testament")); items.add((Song)new Song(3,"Brindis")); items.add((Song)new Song(4,"Hold up")); items.add((Song)new Song(5,"Bohemian Rhapsody")); items.add((Video)new Video(6,"Card flourishes")); items.add((Video)new Video(7,"Shawshank Redemption")); items.add((Video)new Video(8,"How to make cocktails")); items.add((Boek)new Boek(9,"Max Havelaar")); uploadCount = items.size(); } //menu voor het krijgen van gebruikersinfo void gebruikersInfoMenu(){ boolean keuzeGemaakt = false; while (keuzeGemaakt == false){ titelBlok("Ingelogde gebruiker: "+gebruikers.get(gebruikerId).getGebruikersNaam()); System.out.println("1 : Wijzig gegevens"); System.out.println("2 : Gegeven cijfers"); if(gebruikers.get(gebruikerId) instanceof Uploader){ System.out.println("3 : Bekijk je uploads"); } System.out.println("0 : Hoofdmenu"); valideerInvoer(); switch(keuze){ case 0: hoofdMenu(); keuzeGemaakt = true; break; case 1: System.out.println("Wijzig gegevens"); keuzeGemaakt = true; break; case 2: gegevenCijfers(); keuzeGemaakt = true; break; case 3: if(gebruikers.get(gebruikerId) instanceof Uploader){ System.out.println("Hier komt uploadMenu"); keuzeGemaakt = true; break; } else { System.out.println("Verkeerde invoer. Probeer opnieuw..."); keuzeGemaakt = false; break; } default: System.out.println("Verkeerde invoer. Probeer opnieuw..."); keuzeGemaakt = false; break; } } } void gegevenCijfers(){ titelBlok("U heeft de volgende cijfers gegeven:"); for (int i = 0; i < gebruikers.get(gebruikerId).getCijferlijst().size(); i++) { int idOfItem = (int) gebruikers.get(gebruikerId).getItemId().get(i); System.out.println(items.get(idOfItem).getClass().getSimpleName()); System.out.println(items.get(idOfItem).getTitel()); System.out.println("cijfer: " + gebruikers.get(gebruikerId).getCijferlijst().get(i)+".0"); System.out.println("------------------------------------"); } System.out.println("Druk op een toets om verder te gaan..."); scanner.nextLine(); scanner.nextLine(); gebruikersInfoMenu(); } double getGemiddeldeCijfer(){ int aantal = items.get(itemId).getCijferlijst().size(); double totaal = 0; for (int i = 0; i < aantal; i++) { totaal = totaal + (int)items.get(itemId).getCijferlijst().get(i); } return totaal/aantal; } void titelBlok(String titelBlokTitel){ String a = "*"; System.out.print("\n"+a+a); for (int i = 0; i < titelBlokTitel.length(); i++) { System.out.print(a); } System.out.print(a+a+"\n"); System.out.println(a+" "+titelBlokTitel+" "+a); System.out.print(a+a); for (int i = 0; i < titelBlokTitel.length(); i++) { System.out.print(a); } System.out.println(a+a+"\n"); } //////////////////// void laadDummies(){ //gebruiker 2 gebruikers.get(2).addCijfer(0, 8); items.get(0).addCijfer(2, 8); gebruikers.get(2).addCijfer(1, 7); items.get(1).addCijfer(2, 7); gebruikers.get(2).addCijfer(2, 6); items.get(2).addCijfer(2, 6); gebruikers.get(2).addCijfer(3, 5); items.get(3).addCijfer(2, 5); gebruikers.get(2).addCijfer(4, 6); items.get(4).addCijfer(2, 6); gebruikers.get(2).addCijfer(5, 8); items.get(5).addCijfer(2, 8); gebruikers.get(2).addCijfer(6, 9); items.get(6).addCijfer(2, 9); gebruikers.get(2).addCijfer(7, 4); items.get(7).addCijfer(2, 4); gebruikers.get(2).addCijfer(8, 3); items.get(8).addCijfer(2, 3); gebruikers.get(2).addCijfer(9, 3); items.get(9).addCijfer(2, 6); //gebruiker 0 gebruikers.get(0).addCijfer(0, 10); items.get(0).addCijfer(0, 10); gebruikers.get(0).addCijfer(1, 6); items.get(1).addCijfer(0, 6); gebruikers.get(0).addCijfer(2, 6); items.get(2).addCijfer(0, 6); gebruikers.get(0).addCijfer(3, 7); items.get(3).addCijfer(0, 7); gebruikers.get(0).addCijfer(4, 5); items.get(4).addCijfer(0, 5); gebruikers.get(0).addCijfer(5, 3); items.get(5).addCijfer(0, 3); gebruikers.get(0).addCijfer(6, 5); items.get(6).addCijfer(0, 5); gebruikers.get(0).addCijfer(7, 5); items.get(7).addCijfer(0, 5); gebruikers.get(0).addCijfer(8, 6); items.get(8).addCijfer(0, 6); gebruikers.get(0).addCijfer(9, 2); items.get(9).addCijfer(0, 2); //gebruiker 1 gebruikers.get(1).addCijfer(0, 7); items.get(0).addCijfer(1, 7); gebruikers.get(1).addCijfer(1, 7); items.get(1).addCijfer(1, 7); gebruikers.get(1).addCijfer(2, 6); items.get(2).addCijfer(1, 6); gebruikers.get(1).addCijfer(3, 7); items.get(3).addCijfer(1, 7); gebruikers.get(1).addCijfer(4, 5); items.get(4).addCijfer(1, 5); gebruikers.get(1).addCijfer(5, 6); items.get(5).addCijfer(1, 6); gebruikers.get(1).addCijfer(6, 7); items.get(6).addCijfer(1, 7); gebruikers.get(1).addCijfer(7, 5); items.get(7).addCijfer(1, 5); gebruikers.get(1).addCijfer(8, 8); items.get(8).addCijfer(1, 8); gebruikers.get(1).addCijfer(9, 5); items.get(9).addCijfer(1, 5); //gebruiker 3 gebruikers.get(3).addCijfer(0, 8); items.get(0).addCijfer(3, 8); gebruikers.get(3).addCijfer(1, 8); items.get(1).addCijfer(3, 8); gebruikers.get(3).addCijfer(2, 4); items.get(2).addCijfer(3, 4); gebruikers.get(3).addCijfer(3, 7); items.get(3).addCijfer(3, 7); gebruikers.get(3).addCijfer(4, 9); items.get(4).addCijfer(3, 9); gebruikers.get(3).addCijfer(5, 9); items.get(5).addCijfer(3, 9); gebruikers.get(3).addCijfer(6, 5); items.get(6).addCijfer(3, 5); gebruikers.get(3).addCijfer(7, 7); items.get(7).addCijfer(3, 7); gebruikers.get(3).addCijfer(8, 7); items.get(8).addCijfer(3, 7); gebruikers.get(3).addCijfer(9, 6); items.get(9).addCijfer(3, 6); } }
165062_32
// Copyright 2021-present StarRocks, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // This file is based on code available under the Apache license here: // https://github.com/apache/incubator-doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/common/util/TimeUtils.java // 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. package com.starrocks.common.util; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.starrocks.catalog.PrimitiveType; import com.starrocks.catalog.Type; import com.starrocks.common.AnalysisException; import com.starrocks.common.DdlException; import com.starrocks.common.ErrorCode; import com.starrocks.common.ErrorReport; import com.starrocks.common.FeConstants; import com.starrocks.qe.ConnectContext; import com.starrocks.qe.VariableMgr; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.threeten.extra.PeriodDuration; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.time.Clock; import java.time.DateTimeException; import java.time.ZoneId; import java.time.format.DateTimeParseException; import java.util.Date; import java.util.SimpleTimeZone; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; // TODO(dhc) add nanosecond timer for coordinator's root profile public class TimeUtils { private static final Logger LOG = LogManager.getLogger(TimeUtils.class); public static final String DEFAULT_TIME_ZONE = "Asia/Shanghai"; private static final TimeZone TIME_ZONE; // set CST to +08:00 instead of America/Chicago public static final ImmutableMap<String, String> TIME_ZONE_ALIAS_MAP = ImmutableMap.of( "CST", DEFAULT_TIME_ZONE, "PRC", DEFAULT_TIME_ZONE); // NOTICE: Date formats are not synchronized. // it must be used as synchronized externally. private static final SimpleDateFormat DATE_FORMAT; private static final SimpleDateFormat DATETIME_FORMAT; private static final SimpleDateFormat TIME_FORMAT; private static final Pattern DATETIME_FORMAT_REG = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?" + "((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?" + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(" + "\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))" + "[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?" + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))" + "(\\s(((0?[0-9])|([1][0-9])|([2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$"); private static final Pattern TIMEZONE_OFFSET_FORMAT_REG = Pattern.compile("^[+-]{0,1}\\d{1,2}\\:\\d{2}$"); public static Date MIN_DATE = null; public static Date MAX_DATE = null; public static Date MIN_DATETIME = null; public static Date MAX_DATETIME = null; // It's really hard to define max unix timestamp because of timezone. // so this value is 253402329599(UTC 9999-12-31 23:59:59) - 24 * 3600(for all timezones) public static Long MAX_UNIX_TIMESTAMP = 253402243199L; static { TIME_ZONE = new SimpleTimeZone(8 * 3600 * 1000, ""); DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); DATE_FORMAT.setTimeZone(TIME_ZONE); DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DATETIME_FORMAT.setTimeZone(TIME_ZONE); TIME_FORMAT = new SimpleDateFormat("HH"); TIME_FORMAT.setTimeZone(TIME_ZONE); try { MIN_DATE = DATE_FORMAT.parse("0000-01-01"); MAX_DATE = DATE_FORMAT.parse("9999-12-31"); MIN_DATETIME = DATETIME_FORMAT.parse("0000-01-01 00:00:00"); MAX_DATETIME = DATETIME_FORMAT.parse("9999-12-31 23:59:59"); } catch (ParseException e) { LOG.error("invalid date format", e); System.exit(-1); } } public static long getStartTime() { return System.nanoTime(); } public static long getEstimatedTime(long startTime) { return System.nanoTime() - startTime; } public static synchronized String getCurrentFormatTime() { return DATETIME_FORMAT.format(new Date()); } public static TimeZone getTimeZone() { String timezone; if (ConnectContext.get() != null) { timezone = ConnectContext.get().getSessionVariable().getTimeZone(); } else { timezone = VariableMgr.getDefaultSessionVariable().getTimeZone(); } return TimeZone.getTimeZone(ZoneId.of(timezone, TIME_ZONE_ALIAS_MAP)); } // return the time zone of current system public static TimeZone getSystemTimeZone() { return TimeZone.getTimeZone(ZoneId.of(ZoneId.systemDefault().getId(), TIME_ZONE_ALIAS_MAP)); } // get time zone of given zone name, or return system time zone if name is null. public static TimeZone getOrSystemTimeZone(String timeZone) { if (timeZone == null) { return getSystemTimeZone(); } return TimeZone.getTimeZone(ZoneId.of(timeZone, TIME_ZONE_ALIAS_MAP)); } /** * Get UNIX timestamp/Epoch second at system timezone */ public static long getEpochSeconds() { return Clock.systemDefaultZone().instant().getEpochSecond(); } public static String longToTimeString(long timeStamp, SimpleDateFormat dateFormat) { if (timeStamp <= 0L) { return FeConstants.NULL_STRING; } return dateFormat.format(new Date(timeStamp)); } public static synchronized String longToTimeString(long timeStamp) { TimeZone timeZone = getTimeZone(); SimpleDateFormat dateFormatTimeZone = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormatTimeZone.setTimeZone(timeZone); return longToTimeString(timeStamp, dateFormatTimeZone); } public static synchronized Date getTimeAsDate(String timeString) { try { Date date = TIME_FORMAT.parse(timeString); return date; } catch (ParseException e) { LOG.warn("invalid time format: {}", timeString); return null; } } public static synchronized Date parseDate(String dateStr, PrimitiveType type) throws AnalysisException { Date date = null; Matcher matcher = DATETIME_FORMAT_REG.matcher(dateStr); if (!matcher.matches()) { throw new AnalysisException("Invalid date string: " + dateStr); } if (type == PrimitiveType.DATE) { ParsePosition pos = new ParsePosition(0); date = DATE_FORMAT.parse(dateStr, pos); if (pos.getIndex() != dateStr.length() || date == null) { throw new AnalysisException("Invalid date string: " + dateStr); } } else if (type == PrimitiveType.DATETIME) { try { date = DATETIME_FORMAT.parse(dateStr); } catch (ParseException e) { throw new AnalysisException("Invalid date string: " + dateStr); } } else { Preconditions.checkState(false, "error type: " + type); } return date; } public static synchronized Date parseDate(String dateStr, Type type) throws AnalysisException { return parseDate(dateStr, type.getPrimitiveType()); } public static synchronized String format(Date date, PrimitiveType type) { if (type == PrimitiveType.DATE) { return DATE_FORMAT.format(date); } else if (type == PrimitiveType.DATETIME) { return DATETIME_FORMAT.format(date); } else { return "INVALID"; } } public static synchronized String format(Date date, Type type) { return format(date, type.getPrimitiveType()); } public static long timeStringToLong(String timeStr) { Date d; try { d = DATETIME_FORMAT.parse(timeStr); } catch (ParseException e) { return -1; } return d.getTime(); } // Check if the time zone_value is valid public static String checkTimeZoneValidAndStandardize(String value) throws DdlException { try { if (value == null) { ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TIME_ZONE, "null"); } // match offset type, such as +08:00, -07:00 Matcher matcher = TIMEZONE_OFFSET_FORMAT_REG.matcher(value); // it supports offset and region timezone type, "CST" use here is compatibility purposes. boolean match = matcher.matches(); // match only check offset format timezone, // for others format like UTC the validation will be checked by ZoneId.of method if (match) { boolean postive = value.charAt(0) != '-'; value = (postive ? "+" : "-") + String.format("%02d:%02d", Integer.parseInt(value.replaceAll("[+-]", "").split(":")[0]), Integer.parseInt(value.replaceAll("[+-]", "").split(":")[1])); // timezone offsets around the world extended from -12:00 to +14:00 int tz = Integer.parseInt(value.substring(1, 3)) * 100 + Integer.parseInt(value.substring(4, 6)); if (value.charAt(0) == '-' && tz > 1200) { ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TIME_ZONE, value); } else if (value.charAt(0) == '+' && tz > 1400) { ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TIME_ZONE, value); } } ZoneId.of(value, TIME_ZONE_ALIAS_MAP); return value; } catch (DateTimeException ex) { ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TIME_ZONE, value); } throw new DdlException("Parse time zone " + value + " error"); } public static TimeUnit convertUnitIdentifierToTimeUnit(String unitIdentifierDescription) throws DdlException { switch (unitIdentifierDescription) { case "SECOND": return TimeUnit.SECONDS; case "MINUTE": return TimeUnit.MINUTES; case "HOUR": return TimeUnit.HOURS; case "DAY": return TimeUnit.DAYS; default: throw new DdlException( "Can not get TimeUnit from UnitIdentifier description: " + unitIdentifierDescription); } } public static long convertTimeUnitValueToSecond(long value, TimeUnit unit) { return TimeUnit.SECONDS.convert(value, unit); } /** * Based on the start seconds, get the seconds closest and greater than the target second by interval, * the interval use period and time unit to calculate. * * @param startTimeSecond start time second * @param targetTimeSecond target time second * @param period period * @param timeUnit time unit * @return next valid time second * @throws DdlException */ public static long getNextValidTimeSecond(long startTimeSecond, long targetTimeSecond, long period, TimeUnit timeUnit) throws DdlException { if (startTimeSecond > targetTimeSecond) { return startTimeSecond; } long intervalSecond = convertTimeUnitValueToSecond(period, timeUnit); if (intervalSecond < 1) { throw new DdlException("Can not get next valid time second," + "startTimeSecond:" + startTimeSecond + " period:" + period + " timeUnit:" + timeUnit); } long difference = targetTimeSecond - startTimeSecond; long step = difference / intervalSecond + 1; return startTimeSecond + step * intervalSecond; } public static PeriodDuration parseHumanReadablePeriodOrDuration(String text) { try { return PeriodDuration.of(PeriodStyle.LONG.parse(text)); } catch (DateTimeParseException ignored) { return PeriodDuration.of(DurationStyle.LONG.parse(text)); } } public static String toHumanReadableString(PeriodDuration periodDuration) { if (periodDuration.getPeriod().isZero()) { return DurationStyle.LONG.toString(periodDuration.getDuration()); } else if (periodDuration.getDuration().isZero()) { return PeriodStyle.LONG.toString(periodDuration.getPeriod()); } else { return PeriodStyle.LONG.toString(periodDuration.getPeriod()) + " " + DurationStyle.LONG.toString(periodDuration.getDuration()); } } public static String getSessionTimeZone() { String timezone; if (ConnectContext.get() != null) { timezone = ConnectContext.get().getSessionVariable().getTimeZone(); } else { timezone = VariableMgr.getDefaultSessionVariable().getTimeZone(); } return timezone; } }
StarRocks/starrocks
fe/fe-core/src/main/java/com/starrocks/common/util/TimeUtils.java
3,929
// Check if the time zone_value is valid
line_comment
nl
// Copyright 2021-present StarRocks, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // This file is based on code available under the Apache license here: // https://github.com/apache/incubator-doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/common/util/TimeUtils.java // 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. package com.starrocks.common.util; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.starrocks.catalog.PrimitiveType; import com.starrocks.catalog.Type; import com.starrocks.common.AnalysisException; import com.starrocks.common.DdlException; import com.starrocks.common.ErrorCode; import com.starrocks.common.ErrorReport; import com.starrocks.common.FeConstants; import com.starrocks.qe.ConnectContext; import com.starrocks.qe.VariableMgr; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.threeten.extra.PeriodDuration; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.time.Clock; import java.time.DateTimeException; import java.time.ZoneId; import java.time.format.DateTimeParseException; import java.util.Date; import java.util.SimpleTimeZone; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; // TODO(dhc) add nanosecond timer for coordinator's root profile public class TimeUtils { private static final Logger LOG = LogManager.getLogger(TimeUtils.class); public static final String DEFAULT_TIME_ZONE = "Asia/Shanghai"; private static final TimeZone TIME_ZONE; // set CST to +08:00 instead of America/Chicago public static final ImmutableMap<String, String> TIME_ZONE_ALIAS_MAP = ImmutableMap.of( "CST", DEFAULT_TIME_ZONE, "PRC", DEFAULT_TIME_ZONE); // NOTICE: Date formats are not synchronized. // it must be used as synchronized externally. private static final SimpleDateFormat DATE_FORMAT; private static final SimpleDateFormat DATETIME_FORMAT; private static final SimpleDateFormat TIME_FORMAT; private static final Pattern DATETIME_FORMAT_REG = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?" + "((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?" + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(" + "\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))" + "[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?" + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))" + "(\\s(((0?[0-9])|([1][0-9])|([2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$"); private static final Pattern TIMEZONE_OFFSET_FORMAT_REG = Pattern.compile("^[+-]{0,1}\\d{1,2}\\:\\d{2}$"); public static Date MIN_DATE = null; public static Date MAX_DATE = null; public static Date MIN_DATETIME = null; public static Date MAX_DATETIME = null; // It's really hard to define max unix timestamp because of timezone. // so this value is 253402329599(UTC 9999-12-31 23:59:59) - 24 * 3600(for all timezones) public static Long MAX_UNIX_TIMESTAMP = 253402243199L; static { TIME_ZONE = new SimpleTimeZone(8 * 3600 * 1000, ""); DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); DATE_FORMAT.setTimeZone(TIME_ZONE); DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DATETIME_FORMAT.setTimeZone(TIME_ZONE); TIME_FORMAT = new SimpleDateFormat("HH"); TIME_FORMAT.setTimeZone(TIME_ZONE); try { MIN_DATE = DATE_FORMAT.parse("0000-01-01"); MAX_DATE = DATE_FORMAT.parse("9999-12-31"); MIN_DATETIME = DATETIME_FORMAT.parse("0000-01-01 00:00:00"); MAX_DATETIME = DATETIME_FORMAT.parse("9999-12-31 23:59:59"); } catch (ParseException e) { LOG.error("invalid date format", e); System.exit(-1); } } public static long getStartTime() { return System.nanoTime(); } public static long getEstimatedTime(long startTime) { return System.nanoTime() - startTime; } public static synchronized String getCurrentFormatTime() { return DATETIME_FORMAT.format(new Date()); } public static TimeZone getTimeZone() { String timezone; if (ConnectContext.get() != null) { timezone = ConnectContext.get().getSessionVariable().getTimeZone(); } else { timezone = VariableMgr.getDefaultSessionVariable().getTimeZone(); } return TimeZone.getTimeZone(ZoneId.of(timezone, TIME_ZONE_ALIAS_MAP)); } // return the time zone of current system public static TimeZone getSystemTimeZone() { return TimeZone.getTimeZone(ZoneId.of(ZoneId.systemDefault().getId(), TIME_ZONE_ALIAS_MAP)); } // get time zone of given zone name, or return system time zone if name is null. public static TimeZone getOrSystemTimeZone(String timeZone) { if (timeZone == null) { return getSystemTimeZone(); } return TimeZone.getTimeZone(ZoneId.of(timeZone, TIME_ZONE_ALIAS_MAP)); } /** * Get UNIX timestamp/Epoch second at system timezone */ public static long getEpochSeconds() { return Clock.systemDefaultZone().instant().getEpochSecond(); } public static String longToTimeString(long timeStamp, SimpleDateFormat dateFormat) { if (timeStamp <= 0L) { return FeConstants.NULL_STRING; } return dateFormat.format(new Date(timeStamp)); } public static synchronized String longToTimeString(long timeStamp) { TimeZone timeZone = getTimeZone(); SimpleDateFormat dateFormatTimeZone = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormatTimeZone.setTimeZone(timeZone); return longToTimeString(timeStamp, dateFormatTimeZone); } public static synchronized Date getTimeAsDate(String timeString) { try { Date date = TIME_FORMAT.parse(timeString); return date; } catch (ParseException e) { LOG.warn("invalid time format: {}", timeString); return null; } } public static synchronized Date parseDate(String dateStr, PrimitiveType type) throws AnalysisException { Date date = null; Matcher matcher = DATETIME_FORMAT_REG.matcher(dateStr); if (!matcher.matches()) { throw new AnalysisException("Invalid date string: " + dateStr); } if (type == PrimitiveType.DATE) { ParsePosition pos = new ParsePosition(0); date = DATE_FORMAT.parse(dateStr, pos); if (pos.getIndex() != dateStr.length() || date == null) { throw new AnalysisException("Invalid date string: " + dateStr); } } else if (type == PrimitiveType.DATETIME) { try { date = DATETIME_FORMAT.parse(dateStr); } catch (ParseException e) { throw new AnalysisException("Invalid date string: " + dateStr); } } else { Preconditions.checkState(false, "error type: " + type); } return date; } public static synchronized Date parseDate(String dateStr, Type type) throws AnalysisException { return parseDate(dateStr, type.getPrimitiveType()); } public static synchronized String format(Date date, PrimitiveType type) { if (type == PrimitiveType.DATE) { return DATE_FORMAT.format(date); } else if (type == PrimitiveType.DATETIME) { return DATETIME_FORMAT.format(date); } else { return "INVALID"; } } public static synchronized String format(Date date, Type type) { return format(date, type.getPrimitiveType()); } public static long timeStringToLong(String timeStr) { Date d; try { d = DATETIME_FORMAT.parse(timeStr); } catch (ParseException e) { return -1; } return d.getTime(); } // Check if<SUF> public static String checkTimeZoneValidAndStandardize(String value) throws DdlException { try { if (value == null) { ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TIME_ZONE, "null"); } // match offset type, such as +08:00, -07:00 Matcher matcher = TIMEZONE_OFFSET_FORMAT_REG.matcher(value); // it supports offset and region timezone type, "CST" use here is compatibility purposes. boolean match = matcher.matches(); // match only check offset format timezone, // for others format like UTC the validation will be checked by ZoneId.of method if (match) { boolean postive = value.charAt(0) != '-'; value = (postive ? "+" : "-") + String.format("%02d:%02d", Integer.parseInt(value.replaceAll("[+-]", "").split(":")[0]), Integer.parseInt(value.replaceAll("[+-]", "").split(":")[1])); // timezone offsets around the world extended from -12:00 to +14:00 int tz = Integer.parseInt(value.substring(1, 3)) * 100 + Integer.parseInt(value.substring(4, 6)); if (value.charAt(0) == '-' && tz > 1200) { ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TIME_ZONE, value); } else if (value.charAt(0) == '+' && tz > 1400) { ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TIME_ZONE, value); } } ZoneId.of(value, TIME_ZONE_ALIAS_MAP); return value; } catch (DateTimeException ex) { ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TIME_ZONE, value); } throw new DdlException("Parse time zone " + value + " error"); } public static TimeUnit convertUnitIdentifierToTimeUnit(String unitIdentifierDescription) throws DdlException { switch (unitIdentifierDescription) { case "SECOND": return TimeUnit.SECONDS; case "MINUTE": return TimeUnit.MINUTES; case "HOUR": return TimeUnit.HOURS; case "DAY": return TimeUnit.DAYS; default: throw new DdlException( "Can not get TimeUnit from UnitIdentifier description: " + unitIdentifierDescription); } } public static long convertTimeUnitValueToSecond(long value, TimeUnit unit) { return TimeUnit.SECONDS.convert(value, unit); } /** * Based on the start seconds, get the seconds closest and greater than the target second by interval, * the interval use period and time unit to calculate. * * @param startTimeSecond start time second * @param targetTimeSecond target time second * @param period period * @param timeUnit time unit * @return next valid time second * @throws DdlException */ public static long getNextValidTimeSecond(long startTimeSecond, long targetTimeSecond, long period, TimeUnit timeUnit) throws DdlException { if (startTimeSecond > targetTimeSecond) { return startTimeSecond; } long intervalSecond = convertTimeUnitValueToSecond(period, timeUnit); if (intervalSecond < 1) { throw new DdlException("Can not get next valid time second," + "startTimeSecond:" + startTimeSecond + " period:" + period + " timeUnit:" + timeUnit); } long difference = targetTimeSecond - startTimeSecond; long step = difference / intervalSecond + 1; return startTimeSecond + step * intervalSecond; } public static PeriodDuration parseHumanReadablePeriodOrDuration(String text) { try { return PeriodDuration.of(PeriodStyle.LONG.parse(text)); } catch (DateTimeParseException ignored) { return PeriodDuration.of(DurationStyle.LONG.parse(text)); } } public static String toHumanReadableString(PeriodDuration periodDuration) { if (periodDuration.getPeriod().isZero()) { return DurationStyle.LONG.toString(periodDuration.getDuration()); } else if (periodDuration.getDuration().isZero()) { return PeriodStyle.LONG.toString(periodDuration.getPeriod()); } else { return PeriodStyle.LONG.toString(periodDuration.getPeriod()) + " " + DurationStyle.LONG.toString(periodDuration.getDuration()); } } public static String getSessionTimeZone() { String timezone; if (ConnectContext.get() != null) { timezone = ConnectContext.get().getSessionVariable().getTimeZone(); } else { timezone = VariableMgr.getDefaultSessionVariable().getTimeZone(); } return timezone; } }
56842_1
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import java.util.Locale; import butterknife.Bind; import butterknife.ButterKnife; /** * * @author marcolangebeeke */ public class AboutFragment extends Fragment { // bind layout elements @Bind(R.id.about_text) WebView mAboutWebView; /** * Constructor */ public AboutFragment() { } /** * Inflate the about_fragment layout containing the about text from strings resource * @param inflater LayoutInflater * @param container ViewGroup * @param savedInstanceState Bundle * @return View */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // get the about fragment View view = inflater.inflate(R.layout.about_fragment, container, false); // bind the elements to the view ButterKnife.bind(this, view); // load the about text from the assets depending on the locale String about_html = "about-nl.html"; Locale current = getResources().getConfiguration().locale; if (current.getISO3Language().equals("eng")) { about_html = "about-en.html"; } mAboutWebView.loadUrl("file:///android_asset/" + about_html); return view; } }
tiltshiftnl/makkelijkemarkt-androidapp
app/src/main/java/com/amsterdam/marktbureau/makkelijkemarkt/AboutFragment.java
470
/** * * @author marcolangebeeke */
block_comment
nl
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import java.util.Locale; import butterknife.Bind; import butterknife.ButterKnife; /** * * @author marcolangebeeke <SUF>*/ public class AboutFragment extends Fragment { // bind layout elements @Bind(R.id.about_text) WebView mAboutWebView; /** * Constructor */ public AboutFragment() { } /** * Inflate the about_fragment layout containing the about text from strings resource * @param inflater LayoutInflater * @param container ViewGroup * @param savedInstanceState Bundle * @return View */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // get the about fragment View view = inflater.inflate(R.layout.about_fragment, container, false); // bind the elements to the view ButterKnife.bind(this, view); // load the about text from the assets depending on the locale String about_html = "about-nl.html"; Locale current = getResources().getConfiguration().locale; if (current.getISO3Language().equals("eng")) { about_html = "about-en.html"; } mAboutWebView.loadUrl("file:///android_asset/" + about_html); return view; } }
103443_12
import greenfoot.*; import java.util.List; /** * * @author R. Springer */ public class TileEngine { public static int TILE_WIDTH; public static int TILE_HEIGHT; public static int SCREEN_HEIGHT; public static int SCREEN_WIDTH; public static int MAP_WIDTH; public static int MAP_HEIGHT; private World world; private int[][] map; private Tile[][] generateMap; private TileFactory tileFactory; /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations */ public TileEngine(World world, int tileWidth, int tileHeight) { this.world = world; TILE_WIDTH = tileWidth; TILE_HEIGHT = tileHeight; SCREEN_WIDTH = world.getWidth(); SCREEN_HEIGHT = world.getHeight(); this.tileFactory = new TileFactory(); } /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations * @param map A tilemap with numbers */ public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) { this(world, tileWidth, tileHeight); this.setMap(map); } /** * The setMap method used to set a map. This method also clears the previous * map and generates a new one. * * @param map */ public void setMap(int[][] map) { this.clearTilesWorld(); this.map = map; MAP_HEIGHT = this.map.length; MAP_WIDTH = this.map[0].length; this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH]; this.generateWorld(); } /** * The setTileFactory sets a tilefactory. You can use this if you want to * create you own tilefacory and use it in the class. * * @param tf A Tilefactory or extend of it. */ public void setTileFactory(TileFactory tf) { this.tileFactory = tf; } /** * Removes al the tiles from the world. */ public void clearTilesWorld() { List<Tile> removeObjects = this.world.getObjects(Tile.class); this.world.removeObjects(removeObjects); this.map = null; this.generateMap = null; MAP_HEIGHT = 0; MAP_WIDTH = 0; } /** * Creates the tile world based on the TileFactory and the map icons. */ public void generateWorld() { int mapID = 0; for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { // Nummer ophalen in de int array mapID++; int mapIcon = this.map[y][x]; if (mapIcon == -1) { continue; } // Als de mapIcon -1 is dan wordt de code hieronder overgeslagen // Dus er wordt geen tile aangemaakt. -1 is dus geen tile; Tile createdTile = this.tileFactory.createTile(mapIcon); createdTile.setMapID(mapID); createdTile.setMapIcon(mapIcon); addTileAt(createdTile, x, y); } } } /** * Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and * TILE_HEIGHT * * @param tile The Tile * @param colom The colom where the tile exist in the map * @param row The row where the tile exist in the map */ public void addTileAt(Tile tile, int colom, int row) { // De X en Y positie zitten het midden van de Actor. // De tilemap genereerd een wereld gebaseerd op dat de X en Y // positie links boven in zitten. Vandaar de we de helft van de // breedte en hoogte optellen zodat de X en Y links boven zit voor // het toevoegen van het object. this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2); // Toevoegen aan onze lokale array. Makkelijk om de tile op te halen // op basis van een x en y positie van de map this.generateMap[row][colom] = tile; tile.setColom(colom); tile.setRow(row); } /** * Retrieves a tile at the location based on colom and row in the map * * @param colom * @param row * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return null; } return this.generateMap[row][colom]; } /** * Retrieves a tile based on a x and y position in the world * * @param x X-position in the world * @param y Y-position in the world * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); Tile tile = getTileAt(col, row); return tile; } /** * Removes tile at the given colom and row * * @param colom * @param row * @return true if the tile has successfully been removed */ public boolean removeTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return false; } Tile tile = this.generateMap[row][colom]; if (tile != null) { this.world.removeObject(tile); this.generateMap[row][colom] = null; return true; } return false; } /** * Removes tile at the given x and y position * * @param x X-position in the world * @param y Y-position in the world * @return true if the tile has successfully been removed */ public boolean removeTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); return removeTileAt(col, row); } /** * Removes the tile based on a tile * * @param tile Tile from the tilemap * @return true if the tile has successfully been removed */ public boolean removeTile(Tile tile) { int colom = tile.getColom(); int row = tile.getRow(); if (colom != -1 && row != -1) { return this.removeTileAt(colom, row); } return false; } /** * This methode checks if a tile on a x and y position in the world is solid * or not. * * @param x X-position in the world * @param y Y-position in the world * @return Tile at location is solid */ public boolean checkTileSolid(int x, int y) { Tile tile = getTileAtXY(x, y); if (tile != null && tile.isSolid) { return true; } return false; } /** * This methode returns a colom based on a x position. * * @param x * @return the colom */ public int getColumn(int x) { return (int) Math.floor(x / TILE_WIDTH); } /** * This methode returns a row based on a y position. * * @param y * @return the row */ public int getRow(int y) { return (int) Math.floor(y / TILE_HEIGHT); } /** * This methode returns a x position based on the colom * * @param col * @return The x position */ public int getX(int col) { return col * TILE_WIDTH; } /** * This methode returns a y position based on the row * * @param row * @return The y position */ public int getY(int row) { return row * TILE_HEIGHT; } }
ROCMondriaanTIN/project-greenfoot-game-Xardas22
TileEngine.java
2,265
// De tilemap genereerd een wereld gebaseerd op dat de X en Y
line_comment
nl
import greenfoot.*; import java.util.List; /** * * @author R. Springer */ public class TileEngine { public static int TILE_WIDTH; public static int TILE_HEIGHT; public static int SCREEN_HEIGHT; public static int SCREEN_WIDTH; public static int MAP_WIDTH; public static int MAP_HEIGHT; private World world; private int[][] map; private Tile[][] generateMap; private TileFactory tileFactory; /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations */ public TileEngine(World world, int tileWidth, int tileHeight) { this.world = world; TILE_WIDTH = tileWidth; TILE_HEIGHT = tileHeight; SCREEN_WIDTH = world.getWidth(); SCREEN_HEIGHT = world.getHeight(); this.tileFactory = new TileFactory(); } /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations * @param map A tilemap with numbers */ public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) { this(world, tileWidth, tileHeight); this.setMap(map); } /** * The setMap method used to set a map. This method also clears the previous * map and generates a new one. * * @param map */ public void setMap(int[][] map) { this.clearTilesWorld(); this.map = map; MAP_HEIGHT = this.map.length; MAP_WIDTH = this.map[0].length; this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH]; this.generateWorld(); } /** * The setTileFactory sets a tilefactory. You can use this if you want to * create you own tilefacory and use it in the class. * * @param tf A Tilefactory or extend of it. */ public void setTileFactory(TileFactory tf) { this.tileFactory = tf; } /** * Removes al the tiles from the world. */ public void clearTilesWorld() { List<Tile> removeObjects = this.world.getObjects(Tile.class); this.world.removeObjects(removeObjects); this.map = null; this.generateMap = null; MAP_HEIGHT = 0; MAP_WIDTH = 0; } /** * Creates the tile world based on the TileFactory and the map icons. */ public void generateWorld() { int mapID = 0; for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { // Nummer ophalen in de int array mapID++; int mapIcon = this.map[y][x]; if (mapIcon == -1) { continue; } // Als de mapIcon -1 is dan wordt de code hieronder overgeslagen // Dus er wordt geen tile aangemaakt. -1 is dus geen tile; Tile createdTile = this.tileFactory.createTile(mapIcon); createdTile.setMapID(mapID); createdTile.setMapIcon(mapIcon); addTileAt(createdTile, x, y); } } } /** * Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and * TILE_HEIGHT * * @param tile The Tile * @param colom The colom where the tile exist in the map * @param row The row where the tile exist in the map */ public void addTileAt(Tile tile, int colom, int row) { // De X en Y positie zitten het midden van de Actor. // De tilemap<SUF> // positie links boven in zitten. Vandaar de we de helft van de // breedte en hoogte optellen zodat de X en Y links boven zit voor // het toevoegen van het object. this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2); // Toevoegen aan onze lokale array. Makkelijk om de tile op te halen // op basis van een x en y positie van de map this.generateMap[row][colom] = tile; tile.setColom(colom); tile.setRow(row); } /** * Retrieves a tile at the location based on colom and row in the map * * @param colom * @param row * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return null; } return this.generateMap[row][colom]; } /** * Retrieves a tile based on a x and y position in the world * * @param x X-position in the world * @param y Y-position in the world * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); Tile tile = getTileAt(col, row); return tile; } /** * Removes tile at the given colom and row * * @param colom * @param row * @return true if the tile has successfully been removed */ public boolean removeTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return false; } Tile tile = this.generateMap[row][colom]; if (tile != null) { this.world.removeObject(tile); this.generateMap[row][colom] = null; return true; } return false; } /** * Removes tile at the given x and y position * * @param x X-position in the world * @param y Y-position in the world * @return true if the tile has successfully been removed */ public boolean removeTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); return removeTileAt(col, row); } /** * Removes the tile based on a tile * * @param tile Tile from the tilemap * @return true if the tile has successfully been removed */ public boolean removeTile(Tile tile) { int colom = tile.getColom(); int row = tile.getRow(); if (colom != -1 && row != -1) { return this.removeTileAt(colom, row); } return false; } /** * This methode checks if a tile on a x and y position in the world is solid * or not. * * @param x X-position in the world * @param y Y-position in the world * @return Tile at location is solid */ public boolean checkTileSolid(int x, int y) { Tile tile = getTileAtXY(x, y); if (tile != null && tile.isSolid) { return true; } return false; } /** * This methode returns a colom based on a x position. * * @param x * @return the colom */ public int getColumn(int x) { return (int) Math.floor(x / TILE_WIDTH); } /** * This methode returns a row based on a y position. * * @param y * @return the row */ public int getRow(int y) { return (int) Math.floor(y / TILE_HEIGHT); } /** * This methode returns a x position based on the colom * * @param col * @return The x position */ public int getX(int col) { return col * TILE_WIDTH; } /** * This methode returns a y position based on the row * * @param row * @return The y position */ public int getY(int row) { return row * TILE_HEIGHT; } }
123935_5
package nl.han.ica.icss.checker; import nl.han.ica.datastructures.HANLinkedList; import nl.han.ica.datastructures.IHANLinkedList; import nl.han.ica.icss.ast.*; import nl.han.ica.icss.ast.types.ExpressionType; import java.util.ArrayList; import java.util.HashMap; import nl.han.ica.icss.ast.literals.*; import nl.han.ica.icss.ast.operations.*; /** * De Checker-klasse is verantwoordelijk voor het uitvoeren van diverse checks op een ICSS Abstract Syntax Tree (AST). * De volgende CH-vereisten worden gedekt: * - CH00: Minimaal vier van de onderstaande checks moeten zijn geïmplementeerd * - CH01: Controleer of er geen variabelen worden gebruikt die niet gedefinieerd zijn. * - CH02: Controleer of de operanden van de operaties plus en min van gelijk type zijn. * - CH03: Controleer of er geen kleuren worden gebruikt in operaties (plus, min en keer). * - CH04: Controleer of bij declaraties het type van de value klopt met de property. * - CH05: Controleer of de conditie bij een if-statement van het type boolean is. * - CH06: Controleer of variabelen enkel binnen hun scope gebruikt worden. */ public class Checker { private final IHANLinkedList<HashMap<String, ExpressionType>> variableTypes; public Checker() { this.variableTypes = new HANLinkedList<>(); } /** * Voert de checks uit op de gegeven AST. * * @param ast Het Abstract Syntax Tree-object dat moet worden gecontroleerd. */ public void check(AST ast) { checkStylesheet(ast.root); } /** * Voert checks uit op een Stylesheet-knooppunt in de AST. * * @param astNode Het Stylesheet-knooppunt dat moet worden gecontroleerd. */ private void checkStylesheet(ASTNode astNode) { Stylesheet stylesheet = (Stylesheet) astNode; variableTypes.addFirst(new HashMap<>()); for (ASTNode child : stylesheet.getChildren()) { if (child instanceof VariableAssignment) { checkVariableAssignment(child); } else if (child instanceof Stylerule) { variableTypes.addFirst(new HashMap<>()); checkStylerule(child); variableTypes.removeFirst(); } } variableTypes.clear(); } /** * Voert checks uit op een Stylerule-knooppunt in de AST. * * @param astNode Het Stylerule-knooppunt dat moet worden gecontroleerd. */ private void checkStylerule(ASTNode astNode) { Stylerule stylerule = (Stylerule) astNode; checkRuleBody(stylerule.body); } /** * Voert checks uit op de verzameling declaraties en if-clauses in een Stylerule. * * @param astNodes De lijst met declaraties en if-clauses die moeten worden gecontroleerd. */ private void checkRuleBody(ArrayList<ASTNode> astNodes) { for (ASTNode astNode : astNodes) { if (astNode instanceof Declaration) { checkDeclaration(astNode); } else if (astNode instanceof IfClause) { checkIfClause(astNode); } else if (astNode instanceof VariableAssignment) { checkVariableAssignment(astNode); } } } /** * Voert checks uit op een if-clause in de AST. * * @param astNode De if-clause die moet worden gecontroleerd. */ private void checkIfClause(ASTNode astNode) { IfClause ifClause = (IfClause) astNode; variableTypes.addFirst(new HashMap<>()); Expression conditionalExpression = ifClause.getConditionalExpression(); ExpressionType expressionType = checkExpressionType(conditionalExpression); if (expressionType != ExpressionType.BOOL) { ifClause.setError("Conditional expression moet een boolean literal type hebben."); } checkRuleBody(ifClause.body); variableTypes.removeFirst(); if (ifClause.getElseClause() != null) { variableTypes.addFirst(new HashMap<>()); checkElseClause(ifClause.getElseClause()); variableTypes.removeFirst(); } } /** * Voert checks uit op een else-clausule in de AST. * * @param astNode De else-clausule die moet worden gecontroleerd. */ private void checkElseClause(ASTNode astNode) { ElseClause elseClause = (ElseClause) astNode; checkRuleBody(elseClause.body); } /** * Voert checks uit op een declaratie in de AST. * * @param astNode De declaratie die moet worden gecontroleerd. */ private void checkDeclaration(ASTNode astNode) { Declaration declaration = (Declaration) astNode; ExpressionType expressionType = checkExpression(declaration.expression); switch (declaration.property.name) { case "color": if (expressionType != ExpressionType.COLOR) { astNode.setError("Color waarde kan alleen van type color literal zijn."); } break; case "background-color": if (expressionType != ExpressionType.COLOR) { astNode.setError("Background-color waarde kan alleen van color literal type zijn."); } break; case "width": if (expressionType != ExpressionType.PIXEL && expressionType != ExpressionType.PERCENTAGE) { astNode.setError("Width waarde kan alleen van type pixel, of percentage literal zijn."); } break; case "height": if (expressionType != ExpressionType.PIXEL && expressionType != ExpressionType.PERCENTAGE) { astNode.setError("Height waarde kan alleen van percentage of pixel literal type zijn."); } break; default: astNode.setError("De enige toegestane properties zijn: height, weight, color of background-color."); break; } } /** * Voert checks uit op een variabele-assignment in de AST. * * @param astNode De variabele-assignment die moet worden gecontroleerd. */ private void checkVariableAssignment(ASTNode astNode) { VariableAssignment variableAssignment = (VariableAssignment) astNode; VariableReference variableReference = variableAssignment.name; ExpressionType expressionType = checkExpression(variableAssignment.expression); if (expressionType == null || expressionType == ExpressionType.UNDEFINED) { astNode.setError("Variabele assignment lukt niet omdat de expression type undefined is."); return; } ExpressionType previousExpressionType = getVariableType(variableReference.name); if (variableTypeChanged(expressionType, previousExpressionType)) { astNode.setError("Een variabele kan niet veranderen van type: " + previousExpressionType + " ,naar type: " + expressionType); } putVariableType(variableReference.name, expressionType); } /** * Voert checks uit op een expressie in de AST, inclusief operaties. * * @param astNode De expressie die moet worden gecontroleerd. * @return Het type van de expressie na de controle. */ private ExpressionType checkExpression(ASTNode astNode) { Expression expression = (Expression) astNode; if (expression instanceof Operation) { return checkOperation((Operation) expression); } return checkExpressionType(expression); } /** * Voert checks uit op een operation-expressie in de AST. * * @param operation De operation-expressie die moet worden gecontroleerd. * @return Het type van de expressie na de controle. */ private ExpressionType checkOperation(Operation operation) { ExpressionType left; ExpressionType right; if (operation.lhs instanceof Operation) { left = checkOperation((Operation) operation.lhs); } else { left = checkExpressionType(operation.lhs); } if (operation.rhs instanceof Operation) { right = checkOperation((Operation) operation.rhs); } else { right = checkExpressionType(operation.rhs); } if (left == ExpressionType.COLOR || right == ExpressionType.COLOR || left == ExpressionType.BOOL || right == ExpressionType.BOOL) { operation.setError("Booleans en colors zijn niet toegestaan in een operation."); return ExpressionType.UNDEFINED; } if (operation instanceof MultiplyOperation) { if (left != ExpressionType.SCALAR && right != ExpressionType.SCALAR) { operation.setError("Multiply uitvoeren is alleen toegestaan met minimaal één scalar waarde."); return ExpressionType.UNDEFINED; } return right != ExpressionType.SCALAR ? right : left; } else if ((operation instanceof SubtractOperation || operation instanceof AddOperation) && left != right) { operation.setError("Add en subtract operations mogen alleen uitgevoerd worden met dezelfde type literal."); return ExpressionType.UNDEFINED; } return left; } /** * Controleert of een expressie van het juiste type is. * * @param expression De expressie die moet worden gecontroleerd. * @return Het type van de expressie na de controle. */ private ExpressionType checkExpressionType(Expression expression) { if (expression instanceof VariableReference) { return checkVariableReference((VariableReference) expression); } else if (expression instanceof PercentageLiteral) { return ExpressionType.PERCENTAGE; } else if (expression instanceof PixelLiteral) { return ExpressionType.PIXEL; } else if (expression instanceof ColorLiteral) { return ExpressionType.COLOR; } else if (expression instanceof ScalarLiteral) { return ExpressionType.SCALAR; } else if (expression instanceof BoolLiteral) { return ExpressionType.BOOL; } return ExpressionType.UNDEFINED; } /** * Controleert of een variabele-referentie geldig is. * * @param variableReference De variabele-referentie die moet worden gecontroleerd. * @return Het type van de variabele-referentie na de controle. */ private ExpressionType checkVariableReference(VariableReference variableReference) { ExpressionType expressionType = getVariableType(variableReference.name); if (expressionType == null) { variableReference.setError("Variabele is nog niet gedeclareerd of is niet in dezelfde scope."); return ExpressionType.UNDEFINED; } return expressionType; } /** * Slaat het type van een variabele op in de huidige scope. * * @param name De naam van de variabele. * @param type Het type van de variabele. */ private void putVariableType(String name, ExpressionType type) { variableTypes.getFirst().put(name, type); } /** * Haalt het type van een variabele op. * * @param name De naam van de variabele. * @return Het type van de variabele of null als deze niet is gedefinieerd. */ private ExpressionType getVariableType(String name) { for (HashMap<String, ExpressionType> scope : variableTypes) { ExpressionType type = scope.get(name); if (type != null) { return type; } } return null; } /** * Controleert of het type van een variabele is gewijzigd. * * @param currentType Het huidige type van de variabele. * @param previousType Het vorige type van de variabele. * @return true als het type is gewijzigd, anders false. */ private boolean variableTypeChanged(ExpressionType currentType, ExpressionType previousType) { return (previousType != null) && currentType != previousType; } }
daniel1890/icss2022-sep
startcode/src/main/java/nl/han/ica/icss/checker/Checker.java
2,886
/** * Voert checks uit op een if-clause in de AST. * * @param astNode De if-clause die moet worden gecontroleerd. */
block_comment
nl
package nl.han.ica.icss.checker; import nl.han.ica.datastructures.HANLinkedList; import nl.han.ica.datastructures.IHANLinkedList; import nl.han.ica.icss.ast.*; import nl.han.ica.icss.ast.types.ExpressionType; import java.util.ArrayList; import java.util.HashMap; import nl.han.ica.icss.ast.literals.*; import nl.han.ica.icss.ast.operations.*; /** * De Checker-klasse is verantwoordelijk voor het uitvoeren van diverse checks op een ICSS Abstract Syntax Tree (AST). * De volgende CH-vereisten worden gedekt: * - CH00: Minimaal vier van de onderstaande checks moeten zijn geïmplementeerd * - CH01: Controleer of er geen variabelen worden gebruikt die niet gedefinieerd zijn. * - CH02: Controleer of de operanden van de operaties plus en min van gelijk type zijn. * - CH03: Controleer of er geen kleuren worden gebruikt in operaties (plus, min en keer). * - CH04: Controleer of bij declaraties het type van de value klopt met de property. * - CH05: Controleer of de conditie bij een if-statement van het type boolean is. * - CH06: Controleer of variabelen enkel binnen hun scope gebruikt worden. */ public class Checker { private final IHANLinkedList<HashMap<String, ExpressionType>> variableTypes; public Checker() { this.variableTypes = new HANLinkedList<>(); } /** * Voert de checks uit op de gegeven AST. * * @param ast Het Abstract Syntax Tree-object dat moet worden gecontroleerd. */ public void check(AST ast) { checkStylesheet(ast.root); } /** * Voert checks uit op een Stylesheet-knooppunt in de AST. * * @param astNode Het Stylesheet-knooppunt dat moet worden gecontroleerd. */ private void checkStylesheet(ASTNode astNode) { Stylesheet stylesheet = (Stylesheet) astNode; variableTypes.addFirst(new HashMap<>()); for (ASTNode child : stylesheet.getChildren()) { if (child instanceof VariableAssignment) { checkVariableAssignment(child); } else if (child instanceof Stylerule) { variableTypes.addFirst(new HashMap<>()); checkStylerule(child); variableTypes.removeFirst(); } } variableTypes.clear(); } /** * Voert checks uit op een Stylerule-knooppunt in de AST. * * @param astNode Het Stylerule-knooppunt dat moet worden gecontroleerd. */ private void checkStylerule(ASTNode astNode) { Stylerule stylerule = (Stylerule) astNode; checkRuleBody(stylerule.body); } /** * Voert checks uit op de verzameling declaraties en if-clauses in een Stylerule. * * @param astNodes De lijst met declaraties en if-clauses die moeten worden gecontroleerd. */ private void checkRuleBody(ArrayList<ASTNode> astNodes) { for (ASTNode astNode : astNodes) { if (astNode instanceof Declaration) { checkDeclaration(astNode); } else if (astNode instanceof IfClause) { checkIfClause(astNode); } else if (astNode instanceof VariableAssignment) { checkVariableAssignment(astNode); } } } /** * Voert checks uit<SUF>*/ private void checkIfClause(ASTNode astNode) { IfClause ifClause = (IfClause) astNode; variableTypes.addFirst(new HashMap<>()); Expression conditionalExpression = ifClause.getConditionalExpression(); ExpressionType expressionType = checkExpressionType(conditionalExpression); if (expressionType != ExpressionType.BOOL) { ifClause.setError("Conditional expression moet een boolean literal type hebben."); } checkRuleBody(ifClause.body); variableTypes.removeFirst(); if (ifClause.getElseClause() != null) { variableTypes.addFirst(new HashMap<>()); checkElseClause(ifClause.getElseClause()); variableTypes.removeFirst(); } } /** * Voert checks uit op een else-clausule in de AST. * * @param astNode De else-clausule die moet worden gecontroleerd. */ private void checkElseClause(ASTNode astNode) { ElseClause elseClause = (ElseClause) astNode; checkRuleBody(elseClause.body); } /** * Voert checks uit op een declaratie in de AST. * * @param astNode De declaratie die moet worden gecontroleerd. */ private void checkDeclaration(ASTNode astNode) { Declaration declaration = (Declaration) astNode; ExpressionType expressionType = checkExpression(declaration.expression); switch (declaration.property.name) { case "color": if (expressionType != ExpressionType.COLOR) { astNode.setError("Color waarde kan alleen van type color literal zijn."); } break; case "background-color": if (expressionType != ExpressionType.COLOR) { astNode.setError("Background-color waarde kan alleen van color literal type zijn."); } break; case "width": if (expressionType != ExpressionType.PIXEL && expressionType != ExpressionType.PERCENTAGE) { astNode.setError("Width waarde kan alleen van type pixel, of percentage literal zijn."); } break; case "height": if (expressionType != ExpressionType.PIXEL && expressionType != ExpressionType.PERCENTAGE) { astNode.setError("Height waarde kan alleen van percentage of pixel literal type zijn."); } break; default: astNode.setError("De enige toegestane properties zijn: height, weight, color of background-color."); break; } } /** * Voert checks uit op een variabele-assignment in de AST. * * @param astNode De variabele-assignment die moet worden gecontroleerd. */ private void checkVariableAssignment(ASTNode astNode) { VariableAssignment variableAssignment = (VariableAssignment) astNode; VariableReference variableReference = variableAssignment.name; ExpressionType expressionType = checkExpression(variableAssignment.expression); if (expressionType == null || expressionType == ExpressionType.UNDEFINED) { astNode.setError("Variabele assignment lukt niet omdat de expression type undefined is."); return; } ExpressionType previousExpressionType = getVariableType(variableReference.name); if (variableTypeChanged(expressionType, previousExpressionType)) { astNode.setError("Een variabele kan niet veranderen van type: " + previousExpressionType + " ,naar type: " + expressionType); } putVariableType(variableReference.name, expressionType); } /** * Voert checks uit op een expressie in de AST, inclusief operaties. * * @param astNode De expressie die moet worden gecontroleerd. * @return Het type van de expressie na de controle. */ private ExpressionType checkExpression(ASTNode astNode) { Expression expression = (Expression) astNode; if (expression instanceof Operation) { return checkOperation((Operation) expression); } return checkExpressionType(expression); } /** * Voert checks uit op een operation-expressie in de AST. * * @param operation De operation-expressie die moet worden gecontroleerd. * @return Het type van de expressie na de controle. */ private ExpressionType checkOperation(Operation operation) { ExpressionType left; ExpressionType right; if (operation.lhs instanceof Operation) { left = checkOperation((Operation) operation.lhs); } else { left = checkExpressionType(operation.lhs); } if (operation.rhs instanceof Operation) { right = checkOperation((Operation) operation.rhs); } else { right = checkExpressionType(operation.rhs); } if (left == ExpressionType.COLOR || right == ExpressionType.COLOR || left == ExpressionType.BOOL || right == ExpressionType.BOOL) { operation.setError("Booleans en colors zijn niet toegestaan in een operation."); return ExpressionType.UNDEFINED; } if (operation instanceof MultiplyOperation) { if (left != ExpressionType.SCALAR && right != ExpressionType.SCALAR) { operation.setError("Multiply uitvoeren is alleen toegestaan met minimaal één scalar waarde."); return ExpressionType.UNDEFINED; } return right != ExpressionType.SCALAR ? right : left; } else if ((operation instanceof SubtractOperation || operation instanceof AddOperation) && left != right) { operation.setError("Add en subtract operations mogen alleen uitgevoerd worden met dezelfde type literal."); return ExpressionType.UNDEFINED; } return left; } /** * Controleert of een expressie van het juiste type is. * * @param expression De expressie die moet worden gecontroleerd. * @return Het type van de expressie na de controle. */ private ExpressionType checkExpressionType(Expression expression) { if (expression instanceof VariableReference) { return checkVariableReference((VariableReference) expression); } else if (expression instanceof PercentageLiteral) { return ExpressionType.PERCENTAGE; } else if (expression instanceof PixelLiteral) { return ExpressionType.PIXEL; } else if (expression instanceof ColorLiteral) { return ExpressionType.COLOR; } else if (expression instanceof ScalarLiteral) { return ExpressionType.SCALAR; } else if (expression instanceof BoolLiteral) { return ExpressionType.BOOL; } return ExpressionType.UNDEFINED; } /** * Controleert of een variabele-referentie geldig is. * * @param variableReference De variabele-referentie die moet worden gecontroleerd. * @return Het type van de variabele-referentie na de controle. */ private ExpressionType checkVariableReference(VariableReference variableReference) { ExpressionType expressionType = getVariableType(variableReference.name); if (expressionType == null) { variableReference.setError("Variabele is nog niet gedeclareerd of is niet in dezelfde scope."); return ExpressionType.UNDEFINED; } return expressionType; } /** * Slaat het type van een variabele op in de huidige scope. * * @param name De naam van de variabele. * @param type Het type van de variabele. */ private void putVariableType(String name, ExpressionType type) { variableTypes.getFirst().put(name, type); } /** * Haalt het type van een variabele op. * * @param name De naam van de variabele. * @return Het type van de variabele of null als deze niet is gedefinieerd. */ private ExpressionType getVariableType(String name) { for (HashMap<String, ExpressionType> scope : variableTypes) { ExpressionType type = scope.get(name); if (type != null) { return type; } } return null; } /** * Controleert of het type van een variabele is gewijzigd. * * @param currentType Het huidige type van de variabele. * @param previousType Het vorige type van de variabele. * @return true als het type is gewijzigd, anders false. */ private boolean variableTypeChanged(ExpressionType currentType, ExpressionType previousType) { return (previousType != null) && currentType != previousType; } }
200238_32
/** * Copyright (c) 2010-2013, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.novelanheatpump; import org.openhab.core.items.Item; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.StringItem; /** * Represents all valid commands which could be processed by this binding * * @author Jan-Philipp Bolle * @since 1.0.0 */ public enum HeatpumpCommandType { //in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE { { command = "temperature_outside"; itemClass = NumberItem.class; } }, //in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE_AVG { { command = "temperature_outside_avg"; itemClass = NumberItem.class; } }, //in german Rücklauf TYPE_TEMPERATURE_RETURN { { command = "temperature_return"; itemClass = NumberItem.class; } }, //in german Rücklauf Soll TYPE_TEMPERATURE_REFERENCE_RETURN { { command = "temperature_reference_return"; itemClass = NumberItem.class; } }, //in german Vorlauf TYPE_TEMPERATURE_SUPPLAY { { command = "temperature_supplay"; itemClass = NumberItem.class; } }, // in german Brauchwasser Soll TYPE_TEMPERATURE_SERVICEWATER_REFERENCE { { command = "temperature_servicewater_reference"; itemClass = NumberItem.class; } }, // in german Brauchwasser Ist TYPE_TEMPERATURE_SERVICEWATER { { command = "temperature_servicewater"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_STATE { { command = "state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_EXTENDED_STATE { { command = "extended_state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_SOLAR_COLLECTOR { { command = "temperature_solar_collector"; itemClass = NumberItem.class; } }, // in german Temperatur Heissgas TYPE_TEMPERATURE_HOT_GAS { { command = "temperature_hot_gas"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Eingang TYPE_TEMPERATURE_PROBE_IN { { command = "temperature_probe_in"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Ausgang TYPE_TEMPERATURE_PROBE_OUT { { command = "temperature_probe_out"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK1 { { command = "temperature_mk1"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK1_REFERENCE { { command = "temperature_mk1_reference"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK2 { { command = "temperature_mk2"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK2_REFERENCE { { command = "temperature_mk2_reference"; itemClass = NumberItem.class; } }, // in german Temperatur externe Energiequelle TYPE_TEMPERATURE_EXTERNAL_SOURCE { { command = "temperature_external_source"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter1 TYPE_HOURS_COMPRESSOR1 { { command = "hours_compressor1"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 1 TYPE_STARTS_COMPRESSOR1 { { command = "starts_compressor1"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter2 TYPE_HOURS_COMPRESSOR2 { { command = "hours_compressor2"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 2 TYPE_STARTS_COMPRESSOR2 { { command = "starts_compressor2"; itemClass = NumberItem.class; } }, // Temperatur_TRL_ext TYPE_TEMPERATURE_OUT_EXTERNAL { { command = "temperature_out_external"; itemClass = NumberItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE1 { { command = "hours_zwe1"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE2 { { command = "hours_zwe2"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE3 { { command = "hours_zwe3"; itemClass = StringItem.class; } }, // in german Betriebsstunden Wärmepumpe TYPE_HOURS_HETPUMP { { command = "hours_heatpump"; itemClass = StringItem.class; } }, // in german Betriebsstunden Heizung TYPE_HOURS_HEATING { { command = "hours_heating"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_WARMWATER { { command = "hours_warmwater"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_COOLING { { command = "hours_cooling"; itemClass = StringItem.class; } }, // in german Waermemenge Heizung TYPE_THERMALENERGY_HEATING { { command = "thermalenergy_heating"; itemClass = NumberItem.class; } }, // in german Waermemenge Brauchwasser TYPE_THERMALENERGY_WARMWATER { { command = "thermalenergy_warmwater"; itemClass = NumberItem.class; } }, // in german Waermemenge Schwimmbad TYPE_THERMALENERGY_POOL { { command = "thermalenergy_pool"; itemClass = NumberItem.class; } }, // in german Waermemenge gesamt seit Reset TYPE_THERMALENERGY_TOTAL { { command = "thermalenergy_total"; itemClass = NumberItem.class; } }, // in german Massentrom TYPE_MASSFLOW { { command = "massflow"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_SOLAR_STORAGE { { command = "temperature_solar_storage"; itemClass = NumberItem.class; } }; /** Represents the heatpump command as it will be used in *.items configuration */ String command; Class<? extends Item> itemClass; public String getCommand() { return command; } public Class<? extends Item> getItemClass() { return itemClass; } /** * * @param bindingConfig command string e.g. state, temperature_solar_storage,.. * @param itemClass class to validate * @return true if item class can bound to heatpumpCommand */ public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) { boolean ret = false; for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) { ret = true; break; } } return ret; } public static HeatpumpCommandType fromString(String heatpumpCommand) { if ("".equals(heatpumpCommand)) { return null; } for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(heatpumpCommand)) { return c; } } throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'"); } }
ANierbeck/openhab
bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java
2,279
// in german Massentrom
line_comment
nl
/** * Copyright (c) 2010-2013, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.novelanheatpump; import org.openhab.core.items.Item; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.StringItem; /** * Represents all valid commands which could be processed by this binding * * @author Jan-Philipp Bolle * @since 1.0.0 */ public enum HeatpumpCommandType { //in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE { { command = "temperature_outside"; itemClass = NumberItem.class; } }, //in german Außentemperatur TYPE_TEMPERATURE_OUTSIDE_AVG { { command = "temperature_outside_avg"; itemClass = NumberItem.class; } }, //in german Rücklauf TYPE_TEMPERATURE_RETURN { { command = "temperature_return"; itemClass = NumberItem.class; } }, //in german Rücklauf Soll TYPE_TEMPERATURE_REFERENCE_RETURN { { command = "temperature_reference_return"; itemClass = NumberItem.class; } }, //in german Vorlauf TYPE_TEMPERATURE_SUPPLAY { { command = "temperature_supplay"; itemClass = NumberItem.class; } }, // in german Brauchwasser Soll TYPE_TEMPERATURE_SERVICEWATER_REFERENCE { { command = "temperature_servicewater_reference"; itemClass = NumberItem.class; } }, // in german Brauchwasser Ist TYPE_TEMPERATURE_SERVICEWATER { { command = "temperature_servicewater"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_STATE { { command = "state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_EXTENDED_STATE { { command = "extended_state"; itemClass = StringItem.class; } }, TYPE_HEATPUMP_SOLAR_COLLECTOR { { command = "temperature_solar_collector"; itemClass = NumberItem.class; } }, // in german Temperatur Heissgas TYPE_TEMPERATURE_HOT_GAS { { command = "temperature_hot_gas"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Eingang TYPE_TEMPERATURE_PROBE_IN { { command = "temperature_probe_in"; itemClass = NumberItem.class; } }, // in german Sondentemperatur WP Ausgang TYPE_TEMPERATURE_PROBE_OUT { { command = "temperature_probe_out"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK1 { { command = "temperature_mk1"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK1_REFERENCE { { command = "temperature_mk1_reference"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 IST TYPE_TEMPERATURE_MK2 { { command = "temperature_mk2"; itemClass = NumberItem.class; } }, // in german Vorlauftemperatur MK1 SOLL TYPE_TEMPERATURE_MK2_REFERENCE { { command = "temperature_mk2_reference"; itemClass = NumberItem.class; } }, // in german Temperatur externe Energiequelle TYPE_TEMPERATURE_EXTERNAL_SOURCE { { command = "temperature_external_source"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter1 TYPE_HOURS_COMPRESSOR1 { { command = "hours_compressor1"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 1 TYPE_STARTS_COMPRESSOR1 { { command = "starts_compressor1"; itemClass = NumberItem.class; } }, // in german Betriebsstunden Verdichter2 TYPE_HOURS_COMPRESSOR2 { { command = "hours_compressor2"; itemClass = StringItem.class; } }, // in german Impulse (Starts) Verdichter 2 TYPE_STARTS_COMPRESSOR2 { { command = "starts_compressor2"; itemClass = NumberItem.class; } }, // Temperatur_TRL_ext TYPE_TEMPERATURE_OUT_EXTERNAL { { command = "temperature_out_external"; itemClass = NumberItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE1 { { command = "hours_zwe1"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE2 { { command = "hours_zwe2"; itemClass = StringItem.class; } }, // in german Betriebsstunden ZWE1 TYPE_HOURS_ZWE3 { { command = "hours_zwe3"; itemClass = StringItem.class; } }, // in german Betriebsstunden Wärmepumpe TYPE_HOURS_HETPUMP { { command = "hours_heatpump"; itemClass = StringItem.class; } }, // in german Betriebsstunden Heizung TYPE_HOURS_HEATING { { command = "hours_heating"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_WARMWATER { { command = "hours_warmwater"; itemClass = StringItem.class; } }, // in german Betriebsstunden Brauchwasser TYPE_HOURS_COOLING { { command = "hours_cooling"; itemClass = StringItem.class; } }, // in german Waermemenge Heizung TYPE_THERMALENERGY_HEATING { { command = "thermalenergy_heating"; itemClass = NumberItem.class; } }, // in german Waermemenge Brauchwasser TYPE_THERMALENERGY_WARMWATER { { command = "thermalenergy_warmwater"; itemClass = NumberItem.class; } }, // in german Waermemenge Schwimmbad TYPE_THERMALENERGY_POOL { { command = "thermalenergy_pool"; itemClass = NumberItem.class; } }, // in german Waermemenge gesamt seit Reset TYPE_THERMALENERGY_TOTAL { { command = "thermalenergy_total"; itemClass = NumberItem.class; } }, // in german<SUF> TYPE_MASSFLOW { { command = "massflow"; itemClass = NumberItem.class; } }, TYPE_HEATPUMP_SOLAR_STORAGE { { command = "temperature_solar_storage"; itemClass = NumberItem.class; } }; /** Represents the heatpump command as it will be used in *.items configuration */ String command; Class<? extends Item> itemClass; public String getCommand() { return command; } public Class<? extends Item> getItemClass() { return itemClass; } /** * * @param bindingConfig command string e.g. state, temperature_solar_storage,.. * @param itemClass class to validate * @return true if item class can bound to heatpumpCommand */ public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) { boolean ret = false; for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(bindingConfig.getCommand()) && c.getItemClass().equals(itemClass)) { ret = true; break; } } return ret; } public static HeatpumpCommandType fromString(String heatpumpCommand) { if ("".equals(heatpumpCommand)) { return null; } for (HeatpumpCommandType c : HeatpumpCommandType.values()) { if (c.getCommand().equals(heatpumpCommand)) { return c; } } throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '" + heatpumpCommand + "'"); } }
188962_34
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Ecosystem { public class Organism { public String name; //name of organism (either specified or auto-generated) public int level; public String type; //type of organism (plant, animal, etc.) public String lifestyle; //what types of organisms it eats (for animals) public ArrayList<String> preyList; //all the organisms it eats //each value in here is a trophic link, as the links are being designed //as predator ---> prey links (instead of double counting them or using both prey and predator links) public Organism(String name, int level, String type, String eating, ArrayList<String> preyList) { this.name = name; this.level = level; this.type = type; this.lifestyle = eating; this.preyList = preyList; } public Organism(String name) { this.name = name; this.preyList = new ArrayList<String>(); } public void assignLevel() { //assigns trophic level to organism int random = (int)(Math.random()*100 + 1); //number between 1 and 100 if (random <= 5) this.level = 4; //5% chance else if (random <= 20) this.level = 3; //15% chance (20 - 15) else if (random <= 50) this.level = 2; //30% chance else this.level = 1; //50% chance } public void assignType() { //assigns type of organism to organism //"plant", "animal" if (this.level == 1) this.type = "plant"; else if (this.level > 1 && this.level <= 4) this.type = "animal"; else System.out.print("assignType: Organism is not in a trophic level"); } public void assignLifestyle() { //assigns what the organism eats //"none", "carnivore", "herbivore", "omnivore" if (this.level == 1) { this.lifestyle = "none"; //basal species, so no prey } else if (this.level == 2) { this.lifestyle = "herbivore"; //get food from plants primarily } else if (this.level == 3) { //get food from plants or animals int random = (int)(Math.random()*100 + 1); if (random <= 40) this.lifestyle = "omnivore"; //40% chance else this.lifestyle = "carnivore"; //60% chance } else if (this.level == 4) { //mostly get food from animals (but can also get food from plants) int random = (int)(Math.random()*100 + 1); if (random <= 10) this.lifestyle = "omnivore"; //10% chance else this.lifestyle = "carnivore"; //90% chance } } public String preyString() { //preyList will be sorted by commas StringBuilder sb = new StringBuilder(); for (int i = 0; i < this.preyList.size(); i++) { if (i == this.preyList.size() - 1) sb.append(preyList.get(i)); else sb.append(preyList.get(i)+ ","); } return sb.toString(); } public String toString() { return this.name + " " + this.type + " " + this.lifestyle + " " + this.preyString(); } } public class DataPoint { //to hold data points in a better manner public int trophicLinks; public int speciesNum; public double connectance; public DataPoint(int trophicLinks, int speciesNum, double connectance) { this.trophicLinks = trophicLinks; this.speciesNum = speciesNum; this.connectance = connectance; } public String toString() { return "Links: " + this.trophicLinks + " Species: " + this.speciesNum + " Connectance: " + this.connectance; } } //final int[] foodChance = {0, 20, 40, 55, 65, 75, 80, 85, 90}; //(original) low chance //final int[] foodChance = {0, 10, 20, 35, 45, 50, 55, 60, 60}; //(original) high chance //final int[] foodChance = {0, 25, 45, 65, 75, 80, 85, 90, 90}; //low chance //final int[] foodChance = {0, 30, 55, 70, 80, 85, 90, 95, 95}; //lower chance final int[] foodChance = {0, 50, 65, 75, 85, 90, 90, 95, 95}; // absoluteLow chance //final int[] foodChance = {0, 15, 35, 45, 55, 65, 70, 75, 75}; //medium chance //final int[] foodChance = {0, 5, 20, 30, 40, 45, 50, 55, 60}; //high chance //inverse chances of getting another food source ( //makes it so the more food sources an organism has, the less likely it is to get another ArrayList<ArrayList<Organism>> trophicLevels; //each index is ArrayList for that trophic level ArrayList<DataPoint> data; //to hold all the data points for plotting (either in this or another file) ArrayList<String> carnivoreNames; ArrayList<String> herbivoreNames; ArrayList<String> omnivoreNames; ArrayList<String> plantNames; public Ecosystem () { trophicLevels = new ArrayList<ArrayList<Organism>>(); data = new ArrayList<DataPoint>(); for (int i = 0; i < 4; i++) { //adding each trophic level trophicLevels.add(new ArrayList<Organism>()); //IN ORDER (index 0 is trophic level 1) } } public ArrayList<Integer> getRandomIndex(ArrayList<Organism> trophic){ ArrayList<Integer> indexes = new ArrayList<Integer>(); while (indexes.size() != trophic.size()) { int random = (int)(Math.random()*trophic.size()); if (indexes.contains(random) == false) indexes.add(random); } for (int i = 0; i < indexes.size(); i++) { System.out.println(indexes.get(i)); } return indexes; } public void assignPredators(Organism o) { //assign all predators for given organism if (o.level == 4) return; //no predators for apex predator (4th level) else if (o.level > 0 && o.level < 4) { //between 1 and 3 int predatorLevel = o.level; // level above it (where the predators would be) (level is 1 more than index so it equals index + 1) ArrayList<Integer> randomIndex = getRandomIndex(trophicLevels.get(predatorLevel)); //gets indexes according to size but in random order for (int i = 0; i < randomIndex.size(); i++) { int random = (int)(Math.random()*100 + 1); //number between 1 and 100 int sizePrey = trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.size(); int chance = 0; //chance of becoming a predator for the given organism if (sizePrey >= foodChance.length) chance = foodChance[8]; //lowest chance else chance = foodChance[sizePrey]; //appropriate chance if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).lifestyle.equals("carnivore")) { if (o.type.equals("animal")) { if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.contains(o.name) == false) { //if carnivore eating animal that it doesn't already eat if (random <= 100 - chance) { trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.add(o.name); } } } } else if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).lifestyle.equals("herbivore")) { if (o.type.equals("plant")) { if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.contains(o.name) == false) { //if herbivore eating plant that it doesn't already eat if (random <= 100 - chance) { trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.add(o.name); } } } } else if (trophicLevels.get(predatorLevel).get(i).lifestyle.equals("omnivore")) { if (trophicLevels.get(predatorLevel).get(i).preyList.contains(o.name) == false) { //if omnivore eating something that it doesn't already eat if (random <= 100 - chance) { trophicLevels.get(predatorLevel).get(i).preyList.add(o.name); } } } } } } public void assignPrey(Organism o) { //assign all the prey for given organism if (o.level == 1) return; //no prey for basal species (1st level) else if (o.level > 1 && o.level <= 4) { //between 2 and 4 int preyLevel = o.level - 2; // level below it (where the prey would be) (since level = index + 1, level below is index - 2) ArrayList<Integer> randomIndex = getRandomIndex(trophicLevels.get(preyLevel)); //gets indexes according to size but in random order for (int i = 0; i < randomIndex.size(); i++) { int random = (int)(Math.random()*100 + 1); //number between 1 and 100 int sizePrey = o.preyList.size(); int chance = 0; //chance of the given organism getting more prey if (sizePrey >= foodChance.length) chance = foodChance[8]; //lowest chance else chance = foodChance[sizePrey]; //appropriate chance if (o.lifestyle.equals("carnivore")) { if (trophicLevels.get(preyLevel).get(i).type.equals("animal")) { if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if carnivore eating animal that it doesn't already eat if (random <= 100 - chance) { o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name); } } } } else if (o.lifestyle.equals("herbivore")) { if (trophicLevels.get(preyLevel).get(i).type.equals("plant")) { if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if herbivore eating plant that it doesn't already eat if (random <= 100 - chance) { o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name); } } } } else if (o.lifestyle.equals("omnivore")) { if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if omnivore eating something that it doesn't already eat if (random <= 100 - chance) { o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name); } } } } } } public void initializeNames() throws FileNotFoundException { //for adding names into the name arrays using files of words/names carnivoreNames = new ArrayList<String>(); herbivoreNames = new ArrayList<String>(); omnivoreNames = new ArrayList<String>(); plantNames = new ArrayList<String>(); Scanner fileContents = new Scanner(new File("names/randomCarnivore.txt")); while (fileContents.hasNext()) { String contents = fileContents.nextLine(); carnivoreNames.add(contents); } fileContents.close(); fileContents = new Scanner(new File("names/randomHerbivore.txt")); while (fileContents.hasNext()) { String contents = fileContents.nextLine(); herbivoreNames.add(contents); } fileContents.close(); fileContents = new Scanner(new File("names/randomOmnivore.txt")); while (fileContents.hasNext()) { String contents = fileContents.nextLine(); omnivoreNames.add(contents); } fileContents.close(); fileContents = new Scanner(new File("names/randomPlant.txt")); while (fileContents.hasNext()) { String contents = fileContents.nextLine(); plantNames.add(contents); } fileContents.close(); } public String randomName(ArrayList<String> nameList) { //corresponding ArrayList gets a name chosen and removed int random = (int)(Math.random()*nameList.size()); //between 0 and size of list (not including the actual size tho) String name = nameList.get(random); nameList.remove(random); //so repeat names can't show up return name; } public void addOrganism(String name, int level, String type, String lifestyle, ArrayList<String> preyList) { //in case any of it is already initialized Organism o = new Organism(name); //so organism functions can be used if (level == 0) { //if no data (besides maybe name) then find everything (will not trigger later if statements) o.assignLevel(); o.assignType(); o.assignLifestyle(); if (name.isEmpty() == true) { if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames); else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames); else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames); else if (o.type.equals("plant")) o.name = randomName(plantNames); } assignPrey(o); assignPredators(o); } //if level is there but type or anything else isn't (goes for other functions but allows to specify generals while randomizing details) if (type.isEmpty()) o.assignType(); if (lifestyle.isEmpty()) o.assignLifestyle(); if (name.isEmpty() == true) { if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames); else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames); else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames); else if (o.type.equals("plant")) o.name = randomName(plantNames); } if (preyList.isEmpty()) assignPrey(o); assignPredators(o); trophicLevels.get(o.level - 1).add(o); return; } public void addBeforeAssign(String name, int level, String type, String lifestyle) { //adding function where predator and prey are assigned later Organism o = new Organism(name); //so organism functions can be used if (level == 0) { //if no data (besides maybe name) then find everything (will not trigger later if statements) o.assignLevel(); o.assignType(); o.assignLifestyle(); if (name.isEmpty() == true) { if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames); else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames); else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames); else if (o.type.equals("plant")) o.name = randomName(plantNames); } } else o.level = level; //if level is there but type or anything else isn't (goes for other functions but allows to specify generals while randomizing details) if (type.isEmpty()) o.assignType(); else o.type = type; if (lifestyle.isEmpty()) o.assignLifestyle(); else o.lifestyle = lifestyle; if (name.isEmpty() == true) { if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames); else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames); else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames); else if (o.type.equals("plant")) o.name = randomName(plantNames); } else o.name = name; trophicLevels.get(o.level - 1).add(o); return; } public boolean removeOrganism(String name) { //removes a given organism (searches by name for it) int level = 0; //trophic level of organism for (int i = 0; i < trophicLevels.size(); i++) { for (int j = 0; j < trophicLevels.get(i).size(); j++) { if (trophicLevels.get(i).get(j).name.equals(name)) { level = i + 1; trophicLevels.get(i).remove(j); //removes organism at given index if (level != 4) { //not apex predator for (int k = 0; k < trophicLevels.get(level).size(); k++) { if (trophicLevels.get(level).get(k).preyList.contains(name)) { //if organism is prey of one of its potential predators trophicLevels.get(level).get(k).preyList.remove(name); //severs all trophic links to organisms (ones coming from organism get removed with it) } } } return true; } } } return false; } public boolean removeOrganism(String name, int level) { //removes a given organism (searches by name for it but uses level to make it faster) int levelUpdated = level - 1; for (int j = 0; j < trophicLevels.get(levelUpdated).size(); j++) { if (trophicLevels.get(levelUpdated).get(j).name.equals(name)) { trophicLevels.get(levelUpdated).remove(j); //removes organism at given index if (level != 4) { //not apex predator for (int k = 0; k < trophicLevels.get(levelUpdated).size(); k++) { if (trophicLevels.get(levelUpdated).get(k).preyList.contains(name)) { //if organism is prey of one of its potential predators trophicLevels.get(levelUpdated).get(k).preyList.remove(name); //severs all trophic links to organisms (ones coming from organism get removed with it) } } } return true; } } return false; } public int getTrophicLinks() { int trophicLinks = 0; for (int i = 0; i < trophicLevels.size(); i++) { //each trophic level for (int j = 0; j < trophicLevels.get(i).size(); j++) { //each organism in trophic level trophicLinks += trophicLevels.get(i).get(j).preyList.size(); //size of preyList (each being a link) } } return trophicLinks; } public int getSpeciesNumber() { int species = 0; for (int i = 0; i < trophicLevels.size(); i++) { //each trophic level species += trophicLevels.get(i).size(); //size of each trophic level (# of organisms in it) } return species; } public float getConnectance(int trophicLinks, int speciesNumber) { float links = (float) trophicLinks; float species = (float) speciesNumber; return (links / ((species * (species - 1)) / 2)); } public DataPoint getData(int links, int species, double connectance) { return new DataPoint(links, species, connectance); } public void addData(DataPoint dataPoint) { //may not need function but good to have just in case data.add(dataPoint); } public void saveEcosystem(String name) throws FileNotFoundException { File file = new File("ecostorage/" + name + "Eco.txt"); //make name same as ecosystem name for simplicity PrintWriter logger = new PrintWriter(file); for (int i = 3; i >= 0; i--) { int level = i + 1; logger.println("Trophic Level " + level + ": " + trophicLevels.get(i).size() + " Organisms"); ArrayList<Organism> currentLevel = trophicLevels.get(i); for (int j = 0; j < currentLevel.size(); j++) { logger.println(currentLevel.get(j).toString()); } logger.println(); } logger.close(); } public void saveData(String name) throws FileNotFoundException { File file = new File("datastorage/" + name + "Data.txt"); //make name same as ecosystem name for simplicity PrintWriter logger = new PrintWriter(file); for (int i = 0; i < data.size(); i++) { logger.println(data.get(i).toString()); } logger.close(); } /*public void testFunc() { //for testing features of subclasses Organism tests = new Organism("tests"); for (int i = 0; i < 10000; i++) { int chance = tests.assignLevel(); if (chance == 0) { break; } } }*/ public static void main(String[] args) throws FileNotFoundException { for (int k = 0; k < 20; k++) { Ecosystem test = new Ecosystem(); test.initializeNames(); ArrayList<String> a = new ArrayList<String>(); //so addOrganism works //initial species test.addBeforeAssign("a", 4, "animal", "carnivore"); test.addBeforeAssign("g", 3, "animal", "omnivore"); test.addBeforeAssign("p", 2, "animal", "herbivore"); test.addBeforeAssign("z", 1, "plant", "none"); for (int i = 0; i < 6; i++) { test.addBeforeAssign("", 0, "", ""); //default values so it randomizes them all } //assign predator and prey for them all for (int i = 0; i < test.trophicLevels.size(); i++) { for (int j = 0; j < test.trophicLevels.get(i).size(); j++) { test.assignPrey(test.trophicLevels.get(i).get(j)); } } //initial data point int links = test.getTrophicLinks(); int species = test.getSpeciesNumber(); double connectance = test.getConnectance(links, species); DataPoint data = test.getData(links, species, connectance); test.addData(data); //test.saveEcosystem("test1"); //test.saveData("test1"); //adding extra species for (int i = 0; i < 25; i++) { test.addOrganism("", 0, "", "", a); //default values so it randomizes them all links = test.getTrophicLinks(); species = test.getSpeciesNumber(); connectance = test.getConnectance(links, species); data = test.getData(links, species, connectance); test.addData(data); } //saving work String name = "rem" + k; //CHANGE name here for new data set test.saveEcosystem(name); test.saveData(name); //test.saveEcosystem("test"); } } }
npal312/ecosystem-simulator
EN-250/src/Ecosystem.java
6,349
//number between 1 and 100
line_comment
nl
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Ecosystem { public class Organism { public String name; //name of organism (either specified or auto-generated) public int level; public String type; //type of organism (plant, animal, etc.) public String lifestyle; //what types of organisms it eats (for animals) public ArrayList<String> preyList; //all the organisms it eats //each value in here is a trophic link, as the links are being designed //as predator ---> prey links (instead of double counting them or using both prey and predator links) public Organism(String name, int level, String type, String eating, ArrayList<String> preyList) { this.name = name; this.level = level; this.type = type; this.lifestyle = eating; this.preyList = preyList; } public Organism(String name) { this.name = name; this.preyList = new ArrayList<String>(); } public void assignLevel() { //assigns trophic level to organism int random = (int)(Math.random()*100 + 1); //number between 1 and 100 if (random <= 5) this.level = 4; //5% chance else if (random <= 20) this.level = 3; //15% chance (20 - 15) else if (random <= 50) this.level = 2; //30% chance else this.level = 1; //50% chance } public void assignType() { //assigns type of organism to organism //"plant", "animal" if (this.level == 1) this.type = "plant"; else if (this.level > 1 && this.level <= 4) this.type = "animal"; else System.out.print("assignType: Organism is not in a trophic level"); } public void assignLifestyle() { //assigns what the organism eats //"none", "carnivore", "herbivore", "omnivore" if (this.level == 1) { this.lifestyle = "none"; //basal species, so no prey } else if (this.level == 2) { this.lifestyle = "herbivore"; //get food from plants primarily } else if (this.level == 3) { //get food from plants or animals int random = (int)(Math.random()*100 + 1); if (random <= 40) this.lifestyle = "omnivore"; //40% chance else this.lifestyle = "carnivore"; //60% chance } else if (this.level == 4) { //mostly get food from animals (but can also get food from plants) int random = (int)(Math.random()*100 + 1); if (random <= 10) this.lifestyle = "omnivore"; //10% chance else this.lifestyle = "carnivore"; //90% chance } } public String preyString() { //preyList will be sorted by commas StringBuilder sb = new StringBuilder(); for (int i = 0; i < this.preyList.size(); i++) { if (i == this.preyList.size() - 1) sb.append(preyList.get(i)); else sb.append(preyList.get(i)+ ","); } return sb.toString(); } public String toString() { return this.name + " " + this.type + " " + this.lifestyle + " " + this.preyString(); } } public class DataPoint { //to hold data points in a better manner public int trophicLinks; public int speciesNum; public double connectance; public DataPoint(int trophicLinks, int speciesNum, double connectance) { this.trophicLinks = trophicLinks; this.speciesNum = speciesNum; this.connectance = connectance; } public String toString() { return "Links: " + this.trophicLinks + " Species: " + this.speciesNum + " Connectance: " + this.connectance; } } //final int[] foodChance = {0, 20, 40, 55, 65, 75, 80, 85, 90}; //(original) low chance //final int[] foodChance = {0, 10, 20, 35, 45, 50, 55, 60, 60}; //(original) high chance //final int[] foodChance = {0, 25, 45, 65, 75, 80, 85, 90, 90}; //low chance //final int[] foodChance = {0, 30, 55, 70, 80, 85, 90, 95, 95}; //lower chance final int[] foodChance = {0, 50, 65, 75, 85, 90, 90, 95, 95}; // absoluteLow chance //final int[] foodChance = {0, 15, 35, 45, 55, 65, 70, 75, 75}; //medium chance //final int[] foodChance = {0, 5, 20, 30, 40, 45, 50, 55, 60}; //high chance //inverse chances of getting another food source ( //makes it so the more food sources an organism has, the less likely it is to get another ArrayList<ArrayList<Organism>> trophicLevels; //each index is ArrayList for that trophic level ArrayList<DataPoint> data; //to hold all the data points for plotting (either in this or another file) ArrayList<String> carnivoreNames; ArrayList<String> herbivoreNames; ArrayList<String> omnivoreNames; ArrayList<String> plantNames; public Ecosystem () { trophicLevels = new ArrayList<ArrayList<Organism>>(); data = new ArrayList<DataPoint>(); for (int i = 0; i < 4; i++) { //adding each trophic level trophicLevels.add(new ArrayList<Organism>()); //IN ORDER (index 0 is trophic level 1) } } public ArrayList<Integer> getRandomIndex(ArrayList<Organism> trophic){ ArrayList<Integer> indexes = new ArrayList<Integer>(); while (indexes.size() != trophic.size()) { int random = (int)(Math.random()*trophic.size()); if (indexes.contains(random) == false) indexes.add(random); } for (int i = 0; i < indexes.size(); i++) { System.out.println(indexes.get(i)); } return indexes; } public void assignPredators(Organism o) { //assign all predators for given organism if (o.level == 4) return; //no predators for apex predator (4th level) else if (o.level > 0 && o.level < 4) { //between 1 and 3 int predatorLevel = o.level; // level above it (where the predators would be) (level is 1 more than index so it equals index + 1) ArrayList<Integer> randomIndex = getRandomIndex(trophicLevels.get(predatorLevel)); //gets indexes according to size but in random order for (int i = 0; i < randomIndex.size(); i++) { int random = (int)(Math.random()*100 + 1); //number between<SUF> int sizePrey = trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.size(); int chance = 0; //chance of becoming a predator for the given organism if (sizePrey >= foodChance.length) chance = foodChance[8]; //lowest chance else chance = foodChance[sizePrey]; //appropriate chance if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).lifestyle.equals("carnivore")) { if (o.type.equals("animal")) { if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.contains(o.name) == false) { //if carnivore eating animal that it doesn't already eat if (random <= 100 - chance) { trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.add(o.name); } } } } else if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).lifestyle.equals("herbivore")) { if (o.type.equals("plant")) { if (trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.contains(o.name) == false) { //if herbivore eating plant that it doesn't already eat if (random <= 100 - chance) { trophicLevels.get(predatorLevel).get(randomIndex.get(i)).preyList.add(o.name); } } } } else if (trophicLevels.get(predatorLevel).get(i).lifestyle.equals("omnivore")) { if (trophicLevels.get(predatorLevel).get(i).preyList.contains(o.name) == false) { //if omnivore eating something that it doesn't already eat if (random <= 100 - chance) { trophicLevels.get(predatorLevel).get(i).preyList.add(o.name); } } } } } } public void assignPrey(Organism o) { //assign all the prey for given organism if (o.level == 1) return; //no prey for basal species (1st level) else if (o.level > 1 && o.level <= 4) { //between 2 and 4 int preyLevel = o.level - 2; // level below it (where the prey would be) (since level = index + 1, level below is index - 2) ArrayList<Integer> randomIndex = getRandomIndex(trophicLevels.get(preyLevel)); //gets indexes according to size but in random order for (int i = 0; i < randomIndex.size(); i++) { int random = (int)(Math.random()*100 + 1); //number between 1 and 100 int sizePrey = o.preyList.size(); int chance = 0; //chance of the given organism getting more prey if (sizePrey >= foodChance.length) chance = foodChance[8]; //lowest chance else chance = foodChance[sizePrey]; //appropriate chance if (o.lifestyle.equals("carnivore")) { if (trophicLevels.get(preyLevel).get(i).type.equals("animal")) { if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if carnivore eating animal that it doesn't already eat if (random <= 100 - chance) { o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name); } } } } else if (o.lifestyle.equals("herbivore")) { if (trophicLevels.get(preyLevel).get(i).type.equals("plant")) { if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if herbivore eating plant that it doesn't already eat if (random <= 100 - chance) { o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name); } } } } else if (o.lifestyle.equals("omnivore")) { if (o.preyList.contains(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name) == false) { //if omnivore eating something that it doesn't already eat if (random <= 100 - chance) { o.preyList.add(trophicLevels.get(preyLevel).get(randomIndex.get(i)).name); } } } } } } public void initializeNames() throws FileNotFoundException { //for adding names into the name arrays using files of words/names carnivoreNames = new ArrayList<String>(); herbivoreNames = new ArrayList<String>(); omnivoreNames = new ArrayList<String>(); plantNames = new ArrayList<String>(); Scanner fileContents = new Scanner(new File("names/randomCarnivore.txt")); while (fileContents.hasNext()) { String contents = fileContents.nextLine(); carnivoreNames.add(contents); } fileContents.close(); fileContents = new Scanner(new File("names/randomHerbivore.txt")); while (fileContents.hasNext()) { String contents = fileContents.nextLine(); herbivoreNames.add(contents); } fileContents.close(); fileContents = new Scanner(new File("names/randomOmnivore.txt")); while (fileContents.hasNext()) { String contents = fileContents.nextLine(); omnivoreNames.add(contents); } fileContents.close(); fileContents = new Scanner(new File("names/randomPlant.txt")); while (fileContents.hasNext()) { String contents = fileContents.nextLine(); plantNames.add(contents); } fileContents.close(); } public String randomName(ArrayList<String> nameList) { //corresponding ArrayList gets a name chosen and removed int random = (int)(Math.random()*nameList.size()); //between 0 and size of list (not including the actual size tho) String name = nameList.get(random); nameList.remove(random); //so repeat names can't show up return name; } public void addOrganism(String name, int level, String type, String lifestyle, ArrayList<String> preyList) { //in case any of it is already initialized Organism o = new Organism(name); //so organism functions can be used if (level == 0) { //if no data (besides maybe name) then find everything (will not trigger later if statements) o.assignLevel(); o.assignType(); o.assignLifestyle(); if (name.isEmpty() == true) { if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames); else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames); else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames); else if (o.type.equals("plant")) o.name = randomName(plantNames); } assignPrey(o); assignPredators(o); } //if level is there but type or anything else isn't (goes for other functions but allows to specify generals while randomizing details) if (type.isEmpty()) o.assignType(); if (lifestyle.isEmpty()) o.assignLifestyle(); if (name.isEmpty() == true) { if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames); else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames); else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames); else if (o.type.equals("plant")) o.name = randomName(plantNames); } if (preyList.isEmpty()) assignPrey(o); assignPredators(o); trophicLevels.get(o.level - 1).add(o); return; } public void addBeforeAssign(String name, int level, String type, String lifestyle) { //adding function where predator and prey are assigned later Organism o = new Organism(name); //so organism functions can be used if (level == 0) { //if no data (besides maybe name) then find everything (will not trigger later if statements) o.assignLevel(); o.assignType(); o.assignLifestyle(); if (name.isEmpty() == true) { if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames); else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames); else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames); else if (o.type.equals("plant")) o.name = randomName(plantNames); } } else o.level = level; //if level is there but type or anything else isn't (goes for other functions but allows to specify generals while randomizing details) if (type.isEmpty()) o.assignType(); else o.type = type; if (lifestyle.isEmpty()) o.assignLifestyle(); else o.lifestyle = lifestyle; if (name.isEmpty() == true) { if (o.lifestyle.equals("carnivore")) o.name = randomName(carnivoreNames); else if (o.lifestyle.equals("herbivore")) o.name = randomName(herbivoreNames); else if (o.lifestyle.equals("omnivore")) o.name = randomName(omnivoreNames); else if (o.type.equals("plant")) o.name = randomName(plantNames); } else o.name = name; trophicLevels.get(o.level - 1).add(o); return; } public boolean removeOrganism(String name) { //removes a given organism (searches by name for it) int level = 0; //trophic level of organism for (int i = 0; i < trophicLevels.size(); i++) { for (int j = 0; j < trophicLevels.get(i).size(); j++) { if (trophicLevels.get(i).get(j).name.equals(name)) { level = i + 1; trophicLevels.get(i).remove(j); //removes organism at given index if (level != 4) { //not apex predator for (int k = 0; k < trophicLevels.get(level).size(); k++) { if (trophicLevels.get(level).get(k).preyList.contains(name)) { //if organism is prey of one of its potential predators trophicLevels.get(level).get(k).preyList.remove(name); //severs all trophic links to organisms (ones coming from organism get removed with it) } } } return true; } } } return false; } public boolean removeOrganism(String name, int level) { //removes a given organism (searches by name for it but uses level to make it faster) int levelUpdated = level - 1; for (int j = 0; j < trophicLevels.get(levelUpdated).size(); j++) { if (trophicLevels.get(levelUpdated).get(j).name.equals(name)) { trophicLevels.get(levelUpdated).remove(j); //removes organism at given index if (level != 4) { //not apex predator for (int k = 0; k < trophicLevels.get(levelUpdated).size(); k++) { if (trophicLevels.get(levelUpdated).get(k).preyList.contains(name)) { //if organism is prey of one of its potential predators trophicLevels.get(levelUpdated).get(k).preyList.remove(name); //severs all trophic links to organisms (ones coming from organism get removed with it) } } } return true; } } return false; } public int getTrophicLinks() { int trophicLinks = 0; for (int i = 0; i < trophicLevels.size(); i++) { //each trophic level for (int j = 0; j < trophicLevels.get(i).size(); j++) { //each organism in trophic level trophicLinks += trophicLevels.get(i).get(j).preyList.size(); //size of preyList (each being a link) } } return trophicLinks; } public int getSpeciesNumber() { int species = 0; for (int i = 0; i < trophicLevels.size(); i++) { //each trophic level species += trophicLevels.get(i).size(); //size of each trophic level (# of organisms in it) } return species; } public float getConnectance(int trophicLinks, int speciesNumber) { float links = (float) trophicLinks; float species = (float) speciesNumber; return (links / ((species * (species - 1)) / 2)); } public DataPoint getData(int links, int species, double connectance) { return new DataPoint(links, species, connectance); } public void addData(DataPoint dataPoint) { //may not need function but good to have just in case data.add(dataPoint); } public void saveEcosystem(String name) throws FileNotFoundException { File file = new File("ecostorage/" + name + "Eco.txt"); //make name same as ecosystem name for simplicity PrintWriter logger = new PrintWriter(file); for (int i = 3; i >= 0; i--) { int level = i + 1; logger.println("Trophic Level " + level + ": " + trophicLevels.get(i).size() + " Organisms"); ArrayList<Organism> currentLevel = trophicLevels.get(i); for (int j = 0; j < currentLevel.size(); j++) { logger.println(currentLevel.get(j).toString()); } logger.println(); } logger.close(); } public void saveData(String name) throws FileNotFoundException { File file = new File("datastorage/" + name + "Data.txt"); //make name same as ecosystem name for simplicity PrintWriter logger = new PrintWriter(file); for (int i = 0; i < data.size(); i++) { logger.println(data.get(i).toString()); } logger.close(); } /*public void testFunc() { //for testing features of subclasses Organism tests = new Organism("tests"); for (int i = 0; i < 10000; i++) { int chance = tests.assignLevel(); if (chance == 0) { break; } } }*/ public static void main(String[] args) throws FileNotFoundException { for (int k = 0; k < 20; k++) { Ecosystem test = new Ecosystem(); test.initializeNames(); ArrayList<String> a = new ArrayList<String>(); //so addOrganism works //initial species test.addBeforeAssign("a", 4, "animal", "carnivore"); test.addBeforeAssign("g", 3, "animal", "omnivore"); test.addBeforeAssign("p", 2, "animal", "herbivore"); test.addBeforeAssign("z", 1, "plant", "none"); for (int i = 0; i < 6; i++) { test.addBeforeAssign("", 0, "", ""); //default values so it randomizes them all } //assign predator and prey for them all for (int i = 0; i < test.trophicLevels.size(); i++) { for (int j = 0; j < test.trophicLevels.get(i).size(); j++) { test.assignPrey(test.trophicLevels.get(i).get(j)); } } //initial data point int links = test.getTrophicLinks(); int species = test.getSpeciesNumber(); double connectance = test.getConnectance(links, species); DataPoint data = test.getData(links, species, connectance); test.addData(data); //test.saveEcosystem("test1"); //test.saveData("test1"); //adding extra species for (int i = 0; i < 25; i++) { test.addOrganism("", 0, "", "", a); //default values so it randomizes them all links = test.getTrophicLinks(); species = test.getSpeciesNumber(); connectance = test.getConnectance(links, species); data = test.getData(links, species, connectance); test.addData(data); } //saving work String name = "rem" + k; //CHANGE name here for new data set test.saveEcosystem(name); test.saveData(name); //test.saveEcosystem("test"); } } }
10059_0
package org.ibs.application.service; import lombok.AllArgsConstructor; import org.ibs.application.ICategoryService; import org.ibs.application.dto.CategoryDTO; import org.ibs.data.CategoryRepository; import org.ibs.domain.Category; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; // tests nog niet gwschreven omdat ik niet zeker weet of we ook zo de try catch // willen uitvoeren. @Service @Transactional @AllArgsConstructor public class CategoryService implements ICategoryService { private final CategoryRepository categoryRepository; @Override public Category getById(long id) throws Exception { try { return categoryRepository.getById(id); } catch (Exception e) { // misschien een LOG library zoals log4j throw new Exception("Category could not be found due to an error", e); } } @Override public List<Category> getAll() throws Exception { try { return categoryRepository.findAll(); } catch (Exception e) { throw new Exception("Categories could not be found due to an error", e); } } @Override public Category persistCategory(CategoryDTO categoryDTO) throws Exception { try { // categoryDTO to category by builder // categoryRepository.save(category) return null; } catch (Exception e) { // misschien een Log library zoals log4j throw new Exception("Category was not persisted due to an error", e); } } @Override public boolean deleteCategory(long id) throws Exception { try { categoryRepository.delete(categoryRepository.getById(id)); return true; } catch (Exception e) { throw new Exception("Category could not be deleted due to an error", e); } } }
IBSInnovation/IBS-Fysiotherapy
src/main/java/org/ibs/application/service/CategoryService.java
448
// tests nog niet gwschreven omdat ik niet zeker weet of we ook zo de try catch
line_comment
nl
package org.ibs.application.service; import lombok.AllArgsConstructor; import org.ibs.application.ICategoryService; import org.ibs.application.dto.CategoryDTO; import org.ibs.data.CategoryRepository; import org.ibs.domain.Category; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; // tests nog<SUF> // willen uitvoeren. @Service @Transactional @AllArgsConstructor public class CategoryService implements ICategoryService { private final CategoryRepository categoryRepository; @Override public Category getById(long id) throws Exception { try { return categoryRepository.getById(id); } catch (Exception e) { // misschien een LOG library zoals log4j throw new Exception("Category could not be found due to an error", e); } } @Override public List<Category> getAll() throws Exception { try { return categoryRepository.findAll(); } catch (Exception e) { throw new Exception("Categories could not be found due to an error", e); } } @Override public Category persistCategory(CategoryDTO categoryDTO) throws Exception { try { // categoryDTO to category by builder // categoryRepository.save(category) return null; } catch (Exception e) { // misschien een Log library zoals log4j throw new Exception("Category was not persisted due to an error", e); } } @Override public boolean deleteCategory(long id) throws Exception { try { categoryRepository.delete(categoryRepository.getById(id)); return true; } catch (Exception e) { throw new Exception("Category could not be deleted due to an error", e); } } }
67248_0
package nl.overheid.stelsel.gba.reva.web.utils; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import nl.overheid.stelsel.gba.reva.web.locators.ProfileServiceLocator; /** * Zoekt het profiel / gemeentecode bij de ingelogde gebruiker. * */ public final class ProfileUtils { private static final Logger LOG = LoggerFactory.getLogger( ProfileUtils.class ); // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- private ProfileUtils() { // Private constructor. } /** * Geeft de gemeentecode van de ingelogde gebruiker terug. Eerst wordt er * gezocht in de lijst van principals die de gebruiker bij het inloggen heeft * gekregen. Als dat niks oplevert wordt de * {@link nl.overheid.stelsel.gba.reva.web.locators.ProfileServiceLocator} * geraadpleegd. * * @param subject * Het {@link org.apache.shiro.subject.Subject} van de ingelogde * gebruiker. * @return De gemeentecode waar de gebruiker toe behoort, of <code>null</code> * als voor de gebruiker geen gemeentecode kan worden gevonden. */ public static String getGemeentecode( Subject subject ) { String gemeentecode = null; for( String principal : subject.getPrincipals().byType( String.class ) ) { if( principal.startsWith( "gc=" ) ) { gemeentecode = principal.substring( principal.indexOf( '=' ) + 1 ); } } if( gemeentecode == null ) { String gebruiker = subject.getPrincipal().toString(); gemeentecode = ProfileServiceLocator.getService().getProfile( gebruiker ).getGemeenteCode(); } if( LOG.isDebugEnabled() ) { LOG.debug( "Gevonden gemeentecode: {}", gemeentecode ); } return gemeentecode; } }
MinBZK/REVA
huidig-productie-reva/reva/reva-web/src/main/java/nl/overheid/stelsel/gba/reva/web/utils/ProfileUtils.java
505
/** * Zoekt het profiel / gemeentecode bij de ingelogde gebruiker. * */
block_comment
nl
package nl.overheid.stelsel.gba.reva.web.utils; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import nl.overheid.stelsel.gba.reva.web.locators.ProfileServiceLocator; /** * Zoekt het profiel<SUF>*/ public final class ProfileUtils { private static final Logger LOG = LoggerFactory.getLogger( ProfileUtils.class ); // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- private ProfileUtils() { // Private constructor. } /** * Geeft de gemeentecode van de ingelogde gebruiker terug. Eerst wordt er * gezocht in de lijst van principals die de gebruiker bij het inloggen heeft * gekregen. Als dat niks oplevert wordt de * {@link nl.overheid.stelsel.gba.reva.web.locators.ProfileServiceLocator} * geraadpleegd. * * @param subject * Het {@link org.apache.shiro.subject.Subject} van de ingelogde * gebruiker. * @return De gemeentecode waar de gebruiker toe behoort, of <code>null</code> * als voor de gebruiker geen gemeentecode kan worden gevonden. */ public static String getGemeentecode( Subject subject ) { String gemeentecode = null; for( String principal : subject.getPrincipals().byType( String.class ) ) { if( principal.startsWith( "gc=" ) ) { gemeentecode = principal.substring( principal.indexOf( '=' ) + 1 ); } } if( gemeentecode == null ) { String gebruiker = subject.getPrincipal().toString(); gemeentecode = ProfileServiceLocator.getService().getProfile( gebruiker ).getGemeenteCode(); } if( LOG.isDebugEnabled() ) { LOG.debug( "Gevonden gemeentecode: {}", gemeentecode ); } return gemeentecode; } }
23373_1
package nl.b3p.geotools.data.dxf.entities; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import nl.b3p.geotools.data.dxf.parser.DXFLineNumberReader; import java.io.EOFException; import java.io.IOException; import java.text.MessageFormat; import java.util.regex.Pattern; import nl.b3p.geotools.data.GeometryType; import nl.b3p.geotools.data.dxf.parser.DXFUnivers; import nl.b3p.geotools.data.dxf.header.DXFLayer; import nl.b3p.geotools.data.dxf.header.DXFLineType; import nl.b3p.geotools.data.dxf.header.DXFTables; import nl.b3p.geotools.data.dxf.parser.DXFCodeValuePair; import nl.b3p.geotools.data.dxf.parser.DXFGroupCode; import nl.b3p.geotools.data.dxf.parser.DXFParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DXFText extends DXFEntity { private static final Log log = LogFactory.getLog(DXFText.class); private Double x = null, y = null; public DXFText(DXFText newText) { this(newText.getColor(), newText.getRefLayer(), 0, newText.getLineType(), 0.0); setStartingLineNumber(newText.getStartingLineNumber()); setType(newText.getType()); setUnivers(newText.getUnivers()); } public DXFText(int c, DXFLayer l, int visibility, DXFLineType lineType, double thickness) { super(c, l , visibility, lineType, thickness); } public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } public static DXFText read(DXFLineNumberReader br, DXFUnivers univers, boolean isMText) throws IOException { DXFText t = new DXFText(0, null, 0, null, DXFTables.defaultThickness); t.setUnivers(univers); t.setName(isMText ? "DXFMText" : "DXFText"); t.setTextrotation(0.0); t.setStartingLineNumber(br.getLineNumber()); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; // MTEXT direction vector Double directionX = null, directionY = null; String textposhor = "left"; String textposver = "bottom"; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: // geldt voor alle waarden van type br.reset(); doLoop = false; break; case X_1: //"10" t.setX(cvp.getDoubleValue()); break; case Y_1: //"20" t.setY(cvp.getDoubleValue()); break; case TEXT: //"1" t.setText(processOrStripTextCodes(cvp.getStringValue())); break; case ANGLE_1: //"50" t.setTextrotation(cvp.getDoubleValue()); break; case X_2: // 11, X-axis direction vector directionX = cvp.getDoubleValue(); break; case Y_2: // 21, Y-axis direction vector directionY = cvp.getDoubleValue(); break; case THICKNESS: //"39" t.setThickness(cvp.getDoubleValue()); break; case DOUBLE_1: //"40" t.setTextheight(cvp.getDoubleValue()); break; case INT_2: // 71: MTEXT attachment point switch(cvp.getShortValue()) { case 1: textposver = "top"; textposhor = "left"; break; case 2: textposver = "top"; textposhor = "center"; break; case 3: textposver = "top"; textposhor = "right"; break; case 4: textposver = "middle"; textposhor = "left"; break; case 5: textposver = "middle"; textposhor = "center"; break; case 6: textposver = "middle"; textposhor = "right"; break; case 7: textposver = "bottom"; textposhor = "left"; break; case 8: textposver = "bottom"; textposhor = "center"; break; case 9: textposver = "bottom"; textposhor = "right"; break; } break; case INT_3: // 72: TEXT horizontal text justification type // komen niet helemaal overeen, maar maak voor TEXT en MTEXT hetzelfde switch(cvp.getShortValue()) { case 0: textposhor = "left"; break; case 1: textposhor = "center"; break; case 2: textposhor = "right"; break; case 3: // aligned case 4: // middle case 5: // fit // negeer, maar hier "center" van textposhor = "center"; } break; case INT_4: switch(cvp.getShortValue()) { case 0: textposver = "bottom"; break; // eigenlijk baseline case 1: textposver = "bottom"; break; case 2: textposver = "middle"; break; case 3: textposver = "top"; break; } break; case LAYER_NAME: //"8" t._refLayer = univers.findLayer(cvp.getStringValue()); break; case COLOR: //"62" t.setColor(cvp.getShortValue()); break; case VISIBILITY: //"60" t.setVisible(cvp.getShortValue() == 0); break; default: break; } } t.setTextposvertical(textposver); t.setTextposhorizontal(textposhor); if(isMText && directionX != null && directionY != null) { t.setTextrotation(calculateRotationFromDirectionVector(directionX, directionY)); if(log.isDebugEnabled()) { log.debug(MessageFormat.format("MTEXT entity at line number %d: text pos (%.4f,%.4f), direction vector (%.4f,%.4f), calculated text rotation %.2f degrees", t.getStartingLineNumber(), t.getX(), t.getY(), directionX, directionY, t.getTextrotation())); } } t.setType(GeometryType.POINT); return t; } private static String processOrStripTextCodes(String text) { if(text == null) { return null; } // http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-63b9.htm,topicNumber=d0e123454 text = text.replaceAll("%%[cC]", "Ø"); text = text.replaceAll("\\\\[Pp]", "\r\n"); text = text.replaceAll("\\\\[Ll~]", ""); text = text.replaceAll(Pattern.quote("\\\\"), "\\"); text = text.replaceAll(Pattern.quote("\\{"), "{"); text = text.replaceAll(Pattern.quote("\\}"), "}"); text = text.replaceAll("\\\\[CcFfHhTtQqWwAa].*;", ""); return text; } private static double calculateRotationFromDirectionVector(double x, double y) { double rotation; // Hoek tussen vector (1,0) en de direction vector uit MText als theta: // arccos (theta) = inproduct(A,B) / lengte(A).lengte(B) // arccos (theta) = Bx / wortel(Bx^2 + By^2) // indien hoek in kwadrant III of IV, dan theta = -(theta-2PI) double length = Math.sqrt(x*x + y*y); if(length == 0) { rotation = 0; } else { double theta = Math.acos(x / length); if((x <= 0 && y <= 0) || (x >= 0 && y <= 0)) { theta = -(theta - 2*Math.PI); } // conversie van radialen naar graden rotation = theta * (180/Math.PI); if(Math.abs(360 - rotation) < 1e-4) { rotation = 0; } } return rotation; } @Override public Geometry getGeometry() { if (geometry == null) { updateGeometry(); } return geometry; } @Override public void updateGeometry() { if(x != null && y != null) { Coordinate c = rotateAndPlace(new Coordinate(x, y)); setGeometry(getUnivers().getGeometryFactory().createPoint(c)); } else { setGeometry(null); } } @Override public DXFEntity translate(double x, double y) { this.x += x; this.y += y; return this; } @Override public DXFEntity clone() { return new DXFText(this); //throw new UnsupportedOperationException(); } }
wscherphof/b3p-gt2-dxf
src/main/java/nl/b3p/geotools/data/dxf/entities/DXFText.java
2,561
// geldt voor alle waarden van type
line_comment
nl
package nl.b3p.geotools.data.dxf.entities; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import nl.b3p.geotools.data.dxf.parser.DXFLineNumberReader; import java.io.EOFException; import java.io.IOException; import java.text.MessageFormat; import java.util.regex.Pattern; import nl.b3p.geotools.data.GeometryType; import nl.b3p.geotools.data.dxf.parser.DXFUnivers; import nl.b3p.geotools.data.dxf.header.DXFLayer; import nl.b3p.geotools.data.dxf.header.DXFLineType; import nl.b3p.geotools.data.dxf.header.DXFTables; import nl.b3p.geotools.data.dxf.parser.DXFCodeValuePair; import nl.b3p.geotools.data.dxf.parser.DXFGroupCode; import nl.b3p.geotools.data.dxf.parser.DXFParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class DXFText extends DXFEntity { private static final Log log = LogFactory.getLog(DXFText.class); private Double x = null, y = null; public DXFText(DXFText newText) { this(newText.getColor(), newText.getRefLayer(), 0, newText.getLineType(), 0.0); setStartingLineNumber(newText.getStartingLineNumber()); setType(newText.getType()); setUnivers(newText.getUnivers()); } public DXFText(int c, DXFLayer l, int visibility, DXFLineType lineType, double thickness) { super(c, l , visibility, lineType, thickness); } public Double getX() { return x; } public void setX(Double x) { this.x = x; } public Double getY() { return y; } public void setY(Double y) { this.y = y; } public static DXFText read(DXFLineNumberReader br, DXFUnivers univers, boolean isMText) throws IOException { DXFText t = new DXFText(0, null, 0, null, DXFTables.defaultThickness); t.setUnivers(univers); t.setName(isMText ? "DXFMText" : "DXFText"); t.setTextrotation(0.0); t.setStartingLineNumber(br.getLineNumber()); DXFCodeValuePair cvp = null; DXFGroupCode gc = null; // MTEXT direction vector Double directionX = null, directionY = null; String textposhor = "left"; String textposver = "bottom"; boolean doLoop = true; while (doLoop) { cvp = new DXFCodeValuePair(); try { gc = cvp.read(br); } catch (DXFParseException ex) { throw new IOException("DXF parse error" + ex.getLocalizedMessage()); } catch (EOFException e) { doLoop = false; break; } switch (gc) { case TYPE: // geldt voor<SUF> br.reset(); doLoop = false; break; case X_1: //"10" t.setX(cvp.getDoubleValue()); break; case Y_1: //"20" t.setY(cvp.getDoubleValue()); break; case TEXT: //"1" t.setText(processOrStripTextCodes(cvp.getStringValue())); break; case ANGLE_1: //"50" t.setTextrotation(cvp.getDoubleValue()); break; case X_2: // 11, X-axis direction vector directionX = cvp.getDoubleValue(); break; case Y_2: // 21, Y-axis direction vector directionY = cvp.getDoubleValue(); break; case THICKNESS: //"39" t.setThickness(cvp.getDoubleValue()); break; case DOUBLE_1: //"40" t.setTextheight(cvp.getDoubleValue()); break; case INT_2: // 71: MTEXT attachment point switch(cvp.getShortValue()) { case 1: textposver = "top"; textposhor = "left"; break; case 2: textposver = "top"; textposhor = "center"; break; case 3: textposver = "top"; textposhor = "right"; break; case 4: textposver = "middle"; textposhor = "left"; break; case 5: textposver = "middle"; textposhor = "center"; break; case 6: textposver = "middle"; textposhor = "right"; break; case 7: textposver = "bottom"; textposhor = "left"; break; case 8: textposver = "bottom"; textposhor = "center"; break; case 9: textposver = "bottom"; textposhor = "right"; break; } break; case INT_3: // 72: TEXT horizontal text justification type // komen niet helemaal overeen, maar maak voor TEXT en MTEXT hetzelfde switch(cvp.getShortValue()) { case 0: textposhor = "left"; break; case 1: textposhor = "center"; break; case 2: textposhor = "right"; break; case 3: // aligned case 4: // middle case 5: // fit // negeer, maar hier "center" van textposhor = "center"; } break; case INT_4: switch(cvp.getShortValue()) { case 0: textposver = "bottom"; break; // eigenlijk baseline case 1: textposver = "bottom"; break; case 2: textposver = "middle"; break; case 3: textposver = "top"; break; } break; case LAYER_NAME: //"8" t._refLayer = univers.findLayer(cvp.getStringValue()); break; case COLOR: //"62" t.setColor(cvp.getShortValue()); break; case VISIBILITY: //"60" t.setVisible(cvp.getShortValue() == 0); break; default: break; } } t.setTextposvertical(textposver); t.setTextposhorizontal(textposhor); if(isMText && directionX != null && directionY != null) { t.setTextrotation(calculateRotationFromDirectionVector(directionX, directionY)); if(log.isDebugEnabled()) { log.debug(MessageFormat.format("MTEXT entity at line number %d: text pos (%.4f,%.4f), direction vector (%.4f,%.4f), calculated text rotation %.2f degrees", t.getStartingLineNumber(), t.getX(), t.getY(), directionX, directionY, t.getTextrotation())); } } t.setType(GeometryType.POINT); return t; } private static String processOrStripTextCodes(String text) { if(text == null) { return null; } // http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-63b9.htm,topicNumber=d0e123454 text = text.replaceAll("%%[cC]", "Ø"); text = text.replaceAll("\\\\[Pp]", "\r\n"); text = text.replaceAll("\\\\[Ll~]", ""); text = text.replaceAll(Pattern.quote("\\\\"), "\\"); text = text.replaceAll(Pattern.quote("\\{"), "{"); text = text.replaceAll(Pattern.quote("\\}"), "}"); text = text.replaceAll("\\\\[CcFfHhTtQqWwAa].*;", ""); return text; } private static double calculateRotationFromDirectionVector(double x, double y) { double rotation; // Hoek tussen vector (1,0) en de direction vector uit MText als theta: // arccos (theta) = inproduct(A,B) / lengte(A).lengte(B) // arccos (theta) = Bx / wortel(Bx^2 + By^2) // indien hoek in kwadrant III of IV, dan theta = -(theta-2PI) double length = Math.sqrt(x*x + y*y); if(length == 0) { rotation = 0; } else { double theta = Math.acos(x / length); if((x <= 0 && y <= 0) || (x >= 0 && y <= 0)) { theta = -(theta - 2*Math.PI); } // conversie van radialen naar graden rotation = theta * (180/Math.PI); if(Math.abs(360 - rotation) < 1e-4) { rotation = 0; } } return rotation; } @Override public Geometry getGeometry() { if (geometry == null) { updateGeometry(); } return geometry; } @Override public void updateGeometry() { if(x != null && y != null) { Coordinate c = rotateAndPlace(new Coordinate(x, y)); setGeometry(getUnivers().getGeometryFactory().createPoint(c)); } else { setGeometry(null); } } @Override public DXFEntity translate(double x, double y) { this.x += x; this.y += y; return this; } @Override public DXFEntity clone() { return new DXFText(this); //throw new UnsupportedOperationException(); } }
4787_11
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author N. Kuijper */ public class Level2 extends World { private CollisionEngine ce; public int levens = 0; public int coins = 0; /** * Constructor for objects of class Level2. * */ public Level2() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1280, 720, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,142,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,143,142,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,143,142,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,143,142,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,143,142,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,143,142,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,130,130,143,142,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,143,142,140,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,130,130,130,130,143,142}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,143,141,143,142,-1,-1,-1,-1,140,142,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,143}, {-1,-1,-1,-1,-1,-1,140,142,-1,-1,140,141,130,130,130,130,130,130,143,142,-1,-1,140,141,143,142,137,138,139,-1,140,141,130,130,130,130,130,130,130,130,130,130,147,130,130,130,130,130,130,130}, {128,-1,-1,-1,-1,140,141,143,142,140,141,130,130,130,130,130,130,130,130,143,142,140,141,130,147,143,142,-1,-1,140,141,130,130,130,130,130,130,130,130,130,147,130,130,130,147,130,130,130,130,130}, {137,138,138,139,140,141,147,147,143,141,130,130,130,130,130,130,130,130,130,147,143,141,147,130,130,130,143,142,140,141,130,130,130,130,130,130,130,130,147,130,130,130,130,130,130,130,147,130,130,130}, {-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,147,147,147,130,130,130,130,130,130,130,130,130,143,141,130,130,130,130,130,130,130,147,130,130,130,130,130,130,130,130,130,130,130,147,147}, {-1,-1,140,141,130,130,130,130,130,130,147,147,147,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,147,147,147,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130}, {-1,140,141,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130}, {93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(levens, coins); Boef boef = new Boef(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); //camera.follow(boef); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero,100, 910); addObject(boef ,190, 930); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); ce.addCollidingMover(boef); prepare(); } @Override public void act() { ce.update(); } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { } }
ROCMondriaanTIN/project-greenfoot-game-waffel130
Level2.java
3,602
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author N. Kuijper */ public class Level2 extends World { private CollisionEngine ce; public int levens = 0; public int coins = 0; /** * Constructor for objects of class Level2. * */ public Level2() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1280, 720, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,142,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,143,142,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,143,142,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,143,142,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,143,142,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,143,142,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,130,130,143,142,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,143,142,140,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,130,130,130,130,143,142}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,140,141,130,130,143,141,143,142,-1,-1,-1,-1,140,142,-1,-1,-1,-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,143}, {-1,-1,-1,-1,-1,-1,140,142,-1,-1,140,141,130,130,130,130,130,130,143,142,-1,-1,140,141,143,142,137,138,139,-1,140,141,130,130,130,130,130,130,130,130,130,130,147,130,130,130,130,130,130,130}, {128,-1,-1,-1,-1,140,141,143,142,140,141,130,130,130,130,130,130,130,130,143,142,140,141,130,147,143,142,-1,-1,140,141,130,130,130,130,130,130,130,130,130,147,130,130,130,147,130,130,130,130,130}, {137,138,138,139,140,141,147,147,143,141,130,130,130,130,130,130,130,130,130,147,143,141,147,130,130,130,143,142,140,141,130,130,130,130,130,130,130,130,147,130,130,130,130,130,130,130,147,130,130,130}, {-1,-1,-1,140,141,130,130,130,130,130,130,130,130,130,130,147,147,147,130,130,130,130,130,130,130,130,130,143,141,130,130,130,130,130,130,130,147,130,130,130,130,130,130,130,130,130,130,130,147,147}, {-1,-1,140,141,130,130,130,130,130,130,147,147,147,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,147,147,147,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130}, {-1,140,141,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130}, {93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93,93}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(levens, coins); Boef boef = new Boef(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); //camera.follow(boef); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero,100, 910); addObject(boef ,190, 930); // Initialiseren van<SUF> // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); ce.addCollidingMover(boef); prepare(); } @Override public void act() { ce.update(); } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { } }
135872_47
package slimeknights.tconstruct.tools.logic; import com.google.common.collect.Multiset; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.Projectile; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BeehiveBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.CampfireBlock; import net.minecraft.world.level.block.CarvedPumpkinBlock; import net.minecraft.world.level.block.entity.BeehiveBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; import net.minecraftforge.event.entity.ProjectileImpactEvent; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingDamageEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingTickEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingVisibilityEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.Event.Result; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import slimeknights.mantle.data.predicate.damage.DamageSourcePredicate; import slimeknights.tconstruct.TConstruct; import slimeknights.tconstruct.common.TinkerTags; import slimeknights.tconstruct.common.config.Config; import slimeknights.tconstruct.library.events.TinkerToolEvent.ToolHarvestEvent; import slimeknights.tconstruct.library.modifiers.Modifier; import slimeknights.tconstruct.library.modifiers.ModifierEntry; import slimeknights.tconstruct.library.modifiers.ModifierHooks; import slimeknights.tconstruct.library.modifiers.hook.armor.ModifyDamageModifierHook; import slimeknights.tconstruct.library.modifiers.hook.armor.OnAttackedModifierHook; import slimeknights.tconstruct.library.modifiers.hook.armor.ProtectionModifierHook; import slimeknights.tconstruct.library.modifiers.modules.armor.MobDisguiseModule; import slimeknights.tconstruct.library.modifiers.modules.technical.ArmorStatModule; import slimeknights.tconstruct.library.tools.capability.EntityModifierCapability; import slimeknights.tconstruct.library.tools.capability.PersistentDataCapability; import slimeknights.tconstruct.library.tools.capability.TinkerDataCapability; import slimeknights.tconstruct.library.tools.capability.TinkerDataKeys; import slimeknights.tconstruct.library.tools.context.EquipmentContext; import slimeknights.tconstruct.library.tools.definition.ModifiableArmorMaterial; import slimeknights.tconstruct.library.tools.helper.ArmorUtil; import slimeknights.tconstruct.library.tools.helper.ModifierUtil; import slimeknights.tconstruct.library.tools.helper.ToolAttackUtil; import slimeknights.tconstruct.library.tools.helper.ToolDamageUtil; import slimeknights.tconstruct.library.tools.nbt.IToolStackView; import slimeknights.tconstruct.library.tools.nbt.ModifierNBT; import slimeknights.tconstruct.library.tools.nbt.NamespacedNBT; import slimeknights.tconstruct.library.tools.nbt.ToolStack; import slimeknights.tconstruct.library.utils.BlockSideHitListener; import slimeknights.tconstruct.tools.TinkerModifiers; import java.util.List; import java.util.Objects; /** * Event subscriber for tool events */ @SuppressWarnings("unused") @EventBusSubscriber(modid = TConstruct.MOD_ID, bus = Bus.FORGE) public class ToolEvents { @SubscribeEvent static void onBreakSpeed(PlayerEvent.BreakSpeed event) { Player player = event.getEntity(); // tool break speed hook ItemStack stack = player.getMainHandItem(); if (stack.is(TinkerTags.Items.HARVEST)) { ToolStack tool = ToolStack.from(stack); if (!tool.isBroken()) { List<ModifierEntry> modifiers = tool.getModifierList(); if (!modifiers.isEmpty()) { // modifiers using additive boosts may want info on the original boosts provided float miningSpeedModifier = Modifier.getMiningModifier(player); boolean isEffective = stack.isCorrectToolForDrops(event.getState()); Direction direction = BlockSideHitListener.getSideHit(player); for (ModifierEntry entry : tool.getModifierList()) { entry.getHook(ModifierHooks.BREAK_SPEED).onBreakSpeed(tool, entry, event, direction, isEffective, miningSpeedModifier); // if any modifier cancels mining, stop right here if (event.isCanceled()) { return; } } } } } // next, add in armor haste float armorHaste = ArmorStatModule.getStat(player, TinkerDataKeys.MINING_SPEED); if (armorHaste > 0) { // adds in 10% per level event.setNewSpeed(event.getNewSpeed() * (1 + armorHaste)); } } @SubscribeEvent static void onHarvest(ToolHarvestEvent event) { // prevent processing if already processed if (event.getResult() != Result.DEFAULT) { return; } BlockState state = event.getState(); Block block = state.getBlock(); Level world = event.getWorld(); BlockPos pos = event.getPos(); // carve pumpkins if (block == Blocks.PUMPKIN) { Direction facing = event.getContext().getClickedFace(); if (facing.getAxis() == Direction.Axis.Y) { facing = event.getContext().getHorizontalDirection().getOpposite(); } // carve block world.playSound(null, pos, SoundEvents.PUMPKIN_CARVE, SoundSource.BLOCKS, 1.0F, 1.0F); world.setBlock(pos, Blocks.CARVED_PUMPKIN.defaultBlockState().setValue(CarvedPumpkinBlock.FACING, facing), 11); // spawn seeds ItemEntity itemEntity = new ItemEntity( world, pos.getX() + 0.5D + facing.getStepX() * 0.65D, pos.getY() + 0.1D, pos.getZ() + 0.5D + facing.getStepZ() * 0.65D, new ItemStack(Items.PUMPKIN_SEEDS, 4)); itemEntity.setDeltaMovement( 0.05D * facing.getStepX() + world.random.nextDouble() * 0.02D, 0.05D, 0.05D * facing.getStepZ() + world.random.nextDouble() * 0.02D); world.addFreshEntity(itemEntity); event.setResult(Result.ALLOW); } // hives: get the honey if (block instanceof BeehiveBlock beehive) { int level = state.getValue(BeehiveBlock.HONEY_LEVEL); if (level >= 5) { // first, spawn the honey world.playSound(null, pos, SoundEvents.BEEHIVE_SHEAR, SoundSource.NEUTRAL, 1.0F, 1.0F); Block.popResource(world, pos, new ItemStack(Items.HONEYCOMB, 3)); // if not smoking, make the bees angry if (!CampfireBlock.isSmokeyPos(world, pos)) { if (beehive.hiveContainsBees(world, pos)) { beehive.angerNearbyBees(world, pos); } beehive.releaseBeesAndResetHoneyLevel(world, state, pos, event.getPlayer(), BeehiveBlockEntity.BeeReleaseStatus.EMERGENCY); } else { beehive.resetHoneyLevel(world, state, pos); } event.setResult(Result.ALLOW); } else { event.setResult(Result.DENY); } } } @SubscribeEvent(priority = EventPriority.LOW) static void livingAttack(LivingAttackEvent event) { LivingEntity entity = event.getEntity(); // client side always returns false, so this should be fine? if (entity.level.isClientSide() || entity.isDeadOrDying()) { return; } // I cannot think of a reason to run when invulnerable DamageSource source = event.getSource(); if (entity.isInvulnerableTo(source)) { return; } // a lot of counterattack hooks want to detect direct attacks, so save time by calculating once boolean isDirectDamage = OnAttackedModifierHook.isDirectDamage(source); // determine if there is any modifiable armor, handles the target wearing modifiable armor EquipmentContext context = new EquipmentContext(entity); float amount = event.getAmount(); if (context.hasModifiableArmor()) { // first we need to determine if any of the four slots want to cancel the event for (EquipmentSlot slotType : EquipmentSlot.values()) { if (ModifierUtil.validArmorSlot(entity, slotType)) { IToolStackView toolStack = context.getToolInSlot(slotType); if (toolStack != null && !toolStack.isBroken()) { for (ModifierEntry entry : toolStack.getModifierList()) { if (entry.getHook(ModifierHooks.DAMAGE_BLOCK).isDamageBlocked(toolStack, entry, context, slotType, source, amount)) { event.setCanceled(true); return; } } } } } // then we need to determine if any want to respond assuming its not canceled OnAttackedModifierHook.handleAttack(ModifierHooks.ON_ATTACKED, context, source, amount, isDirectDamage); } // next, consider the attacker is wearing modifiable armor Entity attacker = source.getEntity(); if (attacker instanceof LivingEntity livingAttacker) { context = new EquipmentContext(livingAttacker); if (context.hasModifiableArmor()) { for (EquipmentSlot slotType : ModifiableArmorMaterial.ARMOR_SLOTS) { IToolStackView toolStack = context.getToolInSlot(slotType); if (toolStack != null && !toolStack.isBroken()) { for (ModifierEntry entry : toolStack.getModifierList()) { entry.getHook(ModifierHooks.DAMAGE_DEALT).onDamageDealt(toolStack, entry, context, slotType, entity, source, amount, isDirectDamage); } } } } } } /** * Determines how much to damage armor based on the given damage to the player * @param damage Amount to damage the player * @return Amount to damage the armor */ private static int getArmorDamage(float damage) { damage /= 4; if (damage < 1) { return 1; } return (int)damage; } // low priority to minimize conflict as we apply reduction as if we are the final change to damage before vanilla @SubscribeEvent(priority = EventPriority.LOW) static void livingHurt(LivingHurtEvent event) { LivingEntity entity = event.getEntity(); // determine if there is any modifiable armor, if not nothing to do DamageSource source = event.getSource(); EquipmentContext context = new EquipmentContext(entity); int vanillaModifier = 0; float modifierValue = 0; float originalDamage = event.getAmount(); // for our own armor, we have boosts from modifiers to consider if (context.hasModifiableArmor()) { // first, allow modifiers to change the damage being dealt and respond to it happening originalDamage = ModifyDamageModifierHook.modifyDamageTaken(ModifierHooks.MODIFY_HURT, context, source, originalDamage, OnAttackedModifierHook.isDirectDamage(source)); event.setAmount(originalDamage); if (originalDamage <= 0) { event.setCanceled(true); return; } // remaining logic is reducing damage like vanilla protection // fetch vanilla enchant level, assuming its not bypassed in vanilla if (DamageSourcePredicate.CAN_PROTECT.matches(source)) { modifierValue = vanillaModifier = EnchantmentHelper.getDamageProtection(entity.getArmorSlots(), source); } // next, determine how much tinkers armor wants to change it // note that armor modifiers can choose to block "absolute damage" if they wish, currently just starving damage I think for (EquipmentSlot slotType : EquipmentSlot.values()) { if (ModifierUtil.validArmorSlot(entity, slotType)) { IToolStackView tool = context.getToolInSlot(slotType); if (tool != null && !tool.isBroken()) { for (ModifierEntry entry : tool.getModifierList()) { modifierValue = entry.getHook(ModifierHooks.PROTECTION).getProtectionModifier(tool, entry, context, slotType, source, modifierValue); } } } } // give slimes a 4x armor boost if (entity.getType().is(TinkerTags.EntityTypes.SMALL_ARMOR)) { modifierValue *= 4; } } else if (DamageSourcePredicate.CAN_PROTECT.matches(source) && entity.getType().is(TinkerTags.EntityTypes.SMALL_ARMOR)) { vanillaModifier = EnchantmentHelper.getDamageProtection(entity.getArmorSlots(), source); modifierValue = vanillaModifier * 4; } // if we changed anything, run our logic. Changing the cap has 2 problematic cases where same value will work: // * increased cap and vanilla is over the vanilla cap // * decreased cap and vanilla is now under the cap // that said, don't actually care about cap unless we have some protection, can use vanilla to simplify logic float cap = 20f; if (modifierValue > 0) { cap = ProtectionModifierHook.getProtectionCap(context.getTinkerData()); } if (vanillaModifier != modifierValue || (cap > 20 && vanillaModifier > 20) || (cap < 20 && vanillaModifier > cap)) { // fetch armor and toughness if blockable, passing in 0 to the logic will skip the armor calculations float armor = 0, toughness = 0; if (!source.isBypassArmor()) { armor = entity.getArmorValue(); toughness = (float)entity.getAttributeValue(Attributes.ARMOR_TOUGHNESS); } // set the final dealt damage float finalDamage = ArmorUtil.getDamageForEvent(originalDamage, armor, toughness, vanillaModifier, modifierValue, cap); event.setAmount(finalDamage); // armor is damaged less as a result of our math, so damage the armor based on the difference if there is one if (!source.isBypassArmor()) { int damageMissed = getArmorDamage(originalDamage) - getArmorDamage(finalDamage); // TODO: is this check sufficient for whether the armor should be damaged? I partly wonder if I need to use reflection to call damageArmor if (damageMissed > 0 && entity instanceof Player) { for (EquipmentSlot slotType : ModifiableArmorMaterial.ARMOR_SLOTS) { // for our own armor, saves effort to damage directly with our utility IToolStackView tool = context.getToolInSlot(slotType); if (tool != null && (!source.isFire() || !tool.getItem().isFireResistant())) { // damaging the tool twice is generally not an issue, except for tanned where there is a difference between damaging by the sum and damaging twoce in pieces // so work around this by hardcoding a tanned check. Not making this a hook as this whole chunk of code should hopefully be unneeded in 1.21 if (tool.getModifierLevel(TinkerModifiers.tanned.getId()) == 0) { ToolDamageUtil.damageAnimated(tool, damageMissed, entity, slotType); } } else { // if not our armor, damage using vanilla like logic ItemStack armorStack = entity.getItemBySlot(slotType); if (!armorStack.isEmpty() && (!source.isFire() || !armorStack.getItem().isFireResistant()) && armorStack.getItem() instanceof ArmorItem) { armorStack.hurtAndBreak(damageMissed, entity, e -> e.broadcastBreakEvent(slotType)); } } } } } } } @SubscribeEvent static void livingDamage(LivingDamageEvent event) { LivingEntity entity = event.getEntity(); DamageSource source = event.getSource(); // give modifiers a chance to respond to damage happening EquipmentContext context = new EquipmentContext(entity); if (context.hasModifiableArmor()) { float amount = ModifyDamageModifierHook.modifyDamageTaken(ModifierHooks.MODIFY_DAMAGE, context, source, event.getAmount(), OnAttackedModifierHook.isDirectDamage(source)); event.setAmount(amount); if (amount <= 0) { event.setCanceled(true); return; } } // when damaging ender dragons, may drop scales - must be player caused explosion, end crystals and TNT are examples if (Config.COMMON.dropDragonScales.get() && entity.getType() == EntityType.ENDER_DRAGON && event.getAmount() > 0 && source.isExplosion() && source.getEntity() != null && source.getEntity().getType() == EntityType.PLAYER) { // drops 1 - 8 scales ModifierUtil.dropItem(entity, new ItemStack(TinkerModifiers.dragonScale, 1 + entity.level.random.nextInt(8))); } } /** Called the modifier hook when an entity's position changes */ @SubscribeEvent static void livingWalk(LivingTickEvent event) { LivingEntity living = event.getEntity(); // this event runs before vanilla updates prevBlockPos BlockPos pos = living.blockPosition(); if (!living.isSpectator() && !living.level.isClientSide() && living.isAlive() && !Objects.equals(living.lastPos, pos)) { ItemStack boots = living.getItemBySlot(EquipmentSlot.FEET); if (!boots.isEmpty() && boots.is(TinkerTags.Items.BOOTS)) { ToolStack tool = ToolStack.from(boots); for (ModifierEntry entry : tool.getModifierList()) { entry.getHook(ModifierHooks.BOOT_WALK).onWalk(tool, entry, living, living.lastPos, pos); } } } } /** Handles visibility effects of mob disguise and projectile protection */ @SubscribeEvent static void livingVisibility(LivingVisibilityEvent event) { // always nonnull in vanilla, not sure when it would be nullable but I dont see a need for either modifier Entity lookingEntity = event.getLookingEntity(); if (lookingEntity == null) { return; } LivingEntity living = event.getEntity(); living.getCapability(TinkerDataCapability.CAPABILITY).ifPresent(data -> { // mob disguise Multiset<EntityType<?>> disguises = data.get(MobDisguiseModule.DISGUISES); if (disguises != null && disguises.contains(lookingEntity.getType())) { // not as good as a real head event.modifyVisibility(0.65f); } }); } /** Implements projectile hit hook */ @SubscribeEvent static void projectileHit(ProjectileImpactEvent event) { Projectile projectile = event.getProjectile(); ModifierNBT modifiers = EntityModifierCapability.getOrEmpty(projectile); if (!modifiers.isEmpty()) { NamespacedNBT nbt = PersistentDataCapability.getOrWarn(projectile); HitResult hit = event.getRayTraceResult(); HitResult.Type type = hit.getType(); // extract a firing entity as that is a common need LivingEntity attacker = projectile.getOwner() instanceof LivingEntity l ? l : null; switch(type) { case ENTITY -> { EntityHitResult entityHit = (EntityHitResult)hit; // cancel all effects on endermen unless we have enderference, endermen like to teleport away // yes, hardcoded to enderference, if you need your own enderference for whatever reason, talk to us if (entityHit.getEntity().getType() != EntityType.ENDERMAN || modifiers.getLevel(TinkerModifiers.enderference.getId()) > 0) { // extract a living target as that is the most common need LivingEntity target = ToolAttackUtil.getLivingEntity(entityHit.getEntity()); for (ModifierEntry entry : modifiers.getModifiers()) { if (entry.getHook(ModifierHooks.PROJECTILE_HIT).onProjectileHitEntity(modifiers, nbt, entry, projectile, entityHit, attacker, target)) { event.setCanceled(true); } } } } case BLOCK -> { BlockHitResult blockHit = (BlockHitResult)hit; for (ModifierEntry entry : modifiers.getModifiers()) { if (entry.getHook(ModifierHooks.PROJECTILE_HIT).onProjectileHitBlock(modifiers, nbt, entry, projectile, blockHit, attacker)) { event.setCanceled(true); } } } } } } }
SlimeKnights/TinkersConstruct
src/main/java/slimeknights/tconstruct/tools/logic/ToolEvents.java
5,425
/** Implements projectile hit hook */
block_comment
nl
package slimeknights.tconstruct.tools.logic; import com.google.common.collect.Multiset; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.projectile.Projectile; import net.minecraft.world.item.ArmorItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BeehiveBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.CampfireBlock; import net.minecraft.world.level.block.CarvedPumpkinBlock; import net.minecraft.world.level.block.entity.BeehiveBlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; import net.minecraftforge.event.entity.ProjectileImpactEvent; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.event.entity.living.LivingDamageEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingTickEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingVisibilityEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.Event.Result; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import slimeknights.mantle.data.predicate.damage.DamageSourcePredicate; import slimeknights.tconstruct.TConstruct; import slimeknights.tconstruct.common.TinkerTags; import slimeknights.tconstruct.common.config.Config; import slimeknights.tconstruct.library.events.TinkerToolEvent.ToolHarvestEvent; import slimeknights.tconstruct.library.modifiers.Modifier; import slimeknights.tconstruct.library.modifiers.ModifierEntry; import slimeknights.tconstruct.library.modifiers.ModifierHooks; import slimeknights.tconstruct.library.modifiers.hook.armor.ModifyDamageModifierHook; import slimeknights.tconstruct.library.modifiers.hook.armor.OnAttackedModifierHook; import slimeknights.tconstruct.library.modifiers.hook.armor.ProtectionModifierHook; import slimeknights.tconstruct.library.modifiers.modules.armor.MobDisguiseModule; import slimeknights.tconstruct.library.modifiers.modules.technical.ArmorStatModule; import slimeknights.tconstruct.library.tools.capability.EntityModifierCapability; import slimeknights.tconstruct.library.tools.capability.PersistentDataCapability; import slimeknights.tconstruct.library.tools.capability.TinkerDataCapability; import slimeknights.tconstruct.library.tools.capability.TinkerDataKeys; import slimeknights.tconstruct.library.tools.context.EquipmentContext; import slimeknights.tconstruct.library.tools.definition.ModifiableArmorMaterial; import slimeknights.tconstruct.library.tools.helper.ArmorUtil; import slimeknights.tconstruct.library.tools.helper.ModifierUtil; import slimeknights.tconstruct.library.tools.helper.ToolAttackUtil; import slimeknights.tconstruct.library.tools.helper.ToolDamageUtil; import slimeknights.tconstruct.library.tools.nbt.IToolStackView; import slimeknights.tconstruct.library.tools.nbt.ModifierNBT; import slimeknights.tconstruct.library.tools.nbt.NamespacedNBT; import slimeknights.tconstruct.library.tools.nbt.ToolStack; import slimeknights.tconstruct.library.utils.BlockSideHitListener; import slimeknights.tconstruct.tools.TinkerModifiers; import java.util.List; import java.util.Objects; /** * Event subscriber for tool events */ @SuppressWarnings("unused") @EventBusSubscriber(modid = TConstruct.MOD_ID, bus = Bus.FORGE) public class ToolEvents { @SubscribeEvent static void onBreakSpeed(PlayerEvent.BreakSpeed event) { Player player = event.getEntity(); // tool break speed hook ItemStack stack = player.getMainHandItem(); if (stack.is(TinkerTags.Items.HARVEST)) { ToolStack tool = ToolStack.from(stack); if (!tool.isBroken()) { List<ModifierEntry> modifiers = tool.getModifierList(); if (!modifiers.isEmpty()) { // modifiers using additive boosts may want info on the original boosts provided float miningSpeedModifier = Modifier.getMiningModifier(player); boolean isEffective = stack.isCorrectToolForDrops(event.getState()); Direction direction = BlockSideHitListener.getSideHit(player); for (ModifierEntry entry : tool.getModifierList()) { entry.getHook(ModifierHooks.BREAK_SPEED).onBreakSpeed(tool, entry, event, direction, isEffective, miningSpeedModifier); // if any modifier cancels mining, stop right here if (event.isCanceled()) { return; } } } } } // next, add in armor haste float armorHaste = ArmorStatModule.getStat(player, TinkerDataKeys.MINING_SPEED); if (armorHaste > 0) { // adds in 10% per level event.setNewSpeed(event.getNewSpeed() * (1 + armorHaste)); } } @SubscribeEvent static void onHarvest(ToolHarvestEvent event) { // prevent processing if already processed if (event.getResult() != Result.DEFAULT) { return; } BlockState state = event.getState(); Block block = state.getBlock(); Level world = event.getWorld(); BlockPos pos = event.getPos(); // carve pumpkins if (block == Blocks.PUMPKIN) { Direction facing = event.getContext().getClickedFace(); if (facing.getAxis() == Direction.Axis.Y) { facing = event.getContext().getHorizontalDirection().getOpposite(); } // carve block world.playSound(null, pos, SoundEvents.PUMPKIN_CARVE, SoundSource.BLOCKS, 1.0F, 1.0F); world.setBlock(pos, Blocks.CARVED_PUMPKIN.defaultBlockState().setValue(CarvedPumpkinBlock.FACING, facing), 11); // spawn seeds ItemEntity itemEntity = new ItemEntity( world, pos.getX() + 0.5D + facing.getStepX() * 0.65D, pos.getY() + 0.1D, pos.getZ() + 0.5D + facing.getStepZ() * 0.65D, new ItemStack(Items.PUMPKIN_SEEDS, 4)); itemEntity.setDeltaMovement( 0.05D * facing.getStepX() + world.random.nextDouble() * 0.02D, 0.05D, 0.05D * facing.getStepZ() + world.random.nextDouble() * 0.02D); world.addFreshEntity(itemEntity); event.setResult(Result.ALLOW); } // hives: get the honey if (block instanceof BeehiveBlock beehive) { int level = state.getValue(BeehiveBlock.HONEY_LEVEL); if (level >= 5) { // first, spawn the honey world.playSound(null, pos, SoundEvents.BEEHIVE_SHEAR, SoundSource.NEUTRAL, 1.0F, 1.0F); Block.popResource(world, pos, new ItemStack(Items.HONEYCOMB, 3)); // if not smoking, make the bees angry if (!CampfireBlock.isSmokeyPos(world, pos)) { if (beehive.hiveContainsBees(world, pos)) { beehive.angerNearbyBees(world, pos); } beehive.releaseBeesAndResetHoneyLevel(world, state, pos, event.getPlayer(), BeehiveBlockEntity.BeeReleaseStatus.EMERGENCY); } else { beehive.resetHoneyLevel(world, state, pos); } event.setResult(Result.ALLOW); } else { event.setResult(Result.DENY); } } } @SubscribeEvent(priority = EventPriority.LOW) static void livingAttack(LivingAttackEvent event) { LivingEntity entity = event.getEntity(); // client side always returns false, so this should be fine? if (entity.level.isClientSide() || entity.isDeadOrDying()) { return; } // I cannot think of a reason to run when invulnerable DamageSource source = event.getSource(); if (entity.isInvulnerableTo(source)) { return; } // a lot of counterattack hooks want to detect direct attacks, so save time by calculating once boolean isDirectDamage = OnAttackedModifierHook.isDirectDamage(source); // determine if there is any modifiable armor, handles the target wearing modifiable armor EquipmentContext context = new EquipmentContext(entity); float amount = event.getAmount(); if (context.hasModifiableArmor()) { // first we need to determine if any of the four slots want to cancel the event for (EquipmentSlot slotType : EquipmentSlot.values()) { if (ModifierUtil.validArmorSlot(entity, slotType)) { IToolStackView toolStack = context.getToolInSlot(slotType); if (toolStack != null && !toolStack.isBroken()) { for (ModifierEntry entry : toolStack.getModifierList()) { if (entry.getHook(ModifierHooks.DAMAGE_BLOCK).isDamageBlocked(toolStack, entry, context, slotType, source, amount)) { event.setCanceled(true); return; } } } } } // then we need to determine if any want to respond assuming its not canceled OnAttackedModifierHook.handleAttack(ModifierHooks.ON_ATTACKED, context, source, amount, isDirectDamage); } // next, consider the attacker is wearing modifiable armor Entity attacker = source.getEntity(); if (attacker instanceof LivingEntity livingAttacker) { context = new EquipmentContext(livingAttacker); if (context.hasModifiableArmor()) { for (EquipmentSlot slotType : ModifiableArmorMaterial.ARMOR_SLOTS) { IToolStackView toolStack = context.getToolInSlot(slotType); if (toolStack != null && !toolStack.isBroken()) { for (ModifierEntry entry : toolStack.getModifierList()) { entry.getHook(ModifierHooks.DAMAGE_DEALT).onDamageDealt(toolStack, entry, context, slotType, entity, source, amount, isDirectDamage); } } } } } } /** * Determines how much to damage armor based on the given damage to the player * @param damage Amount to damage the player * @return Amount to damage the armor */ private static int getArmorDamage(float damage) { damage /= 4; if (damage < 1) { return 1; } return (int)damage; } // low priority to minimize conflict as we apply reduction as if we are the final change to damage before vanilla @SubscribeEvent(priority = EventPriority.LOW) static void livingHurt(LivingHurtEvent event) { LivingEntity entity = event.getEntity(); // determine if there is any modifiable armor, if not nothing to do DamageSource source = event.getSource(); EquipmentContext context = new EquipmentContext(entity); int vanillaModifier = 0; float modifierValue = 0; float originalDamage = event.getAmount(); // for our own armor, we have boosts from modifiers to consider if (context.hasModifiableArmor()) { // first, allow modifiers to change the damage being dealt and respond to it happening originalDamage = ModifyDamageModifierHook.modifyDamageTaken(ModifierHooks.MODIFY_HURT, context, source, originalDamage, OnAttackedModifierHook.isDirectDamage(source)); event.setAmount(originalDamage); if (originalDamage <= 0) { event.setCanceled(true); return; } // remaining logic is reducing damage like vanilla protection // fetch vanilla enchant level, assuming its not bypassed in vanilla if (DamageSourcePredicate.CAN_PROTECT.matches(source)) { modifierValue = vanillaModifier = EnchantmentHelper.getDamageProtection(entity.getArmorSlots(), source); } // next, determine how much tinkers armor wants to change it // note that armor modifiers can choose to block "absolute damage" if they wish, currently just starving damage I think for (EquipmentSlot slotType : EquipmentSlot.values()) { if (ModifierUtil.validArmorSlot(entity, slotType)) { IToolStackView tool = context.getToolInSlot(slotType); if (tool != null && !tool.isBroken()) { for (ModifierEntry entry : tool.getModifierList()) { modifierValue = entry.getHook(ModifierHooks.PROTECTION).getProtectionModifier(tool, entry, context, slotType, source, modifierValue); } } } } // give slimes a 4x armor boost if (entity.getType().is(TinkerTags.EntityTypes.SMALL_ARMOR)) { modifierValue *= 4; } } else if (DamageSourcePredicate.CAN_PROTECT.matches(source) && entity.getType().is(TinkerTags.EntityTypes.SMALL_ARMOR)) { vanillaModifier = EnchantmentHelper.getDamageProtection(entity.getArmorSlots(), source); modifierValue = vanillaModifier * 4; } // if we changed anything, run our logic. Changing the cap has 2 problematic cases where same value will work: // * increased cap and vanilla is over the vanilla cap // * decreased cap and vanilla is now under the cap // that said, don't actually care about cap unless we have some protection, can use vanilla to simplify logic float cap = 20f; if (modifierValue > 0) { cap = ProtectionModifierHook.getProtectionCap(context.getTinkerData()); } if (vanillaModifier != modifierValue || (cap > 20 && vanillaModifier > 20) || (cap < 20 && vanillaModifier > cap)) { // fetch armor and toughness if blockable, passing in 0 to the logic will skip the armor calculations float armor = 0, toughness = 0; if (!source.isBypassArmor()) { armor = entity.getArmorValue(); toughness = (float)entity.getAttributeValue(Attributes.ARMOR_TOUGHNESS); } // set the final dealt damage float finalDamage = ArmorUtil.getDamageForEvent(originalDamage, armor, toughness, vanillaModifier, modifierValue, cap); event.setAmount(finalDamage); // armor is damaged less as a result of our math, so damage the armor based on the difference if there is one if (!source.isBypassArmor()) { int damageMissed = getArmorDamage(originalDamage) - getArmorDamage(finalDamage); // TODO: is this check sufficient for whether the armor should be damaged? I partly wonder if I need to use reflection to call damageArmor if (damageMissed > 0 && entity instanceof Player) { for (EquipmentSlot slotType : ModifiableArmorMaterial.ARMOR_SLOTS) { // for our own armor, saves effort to damage directly with our utility IToolStackView tool = context.getToolInSlot(slotType); if (tool != null && (!source.isFire() || !tool.getItem().isFireResistant())) { // damaging the tool twice is generally not an issue, except for tanned where there is a difference between damaging by the sum and damaging twoce in pieces // so work around this by hardcoding a tanned check. Not making this a hook as this whole chunk of code should hopefully be unneeded in 1.21 if (tool.getModifierLevel(TinkerModifiers.tanned.getId()) == 0) { ToolDamageUtil.damageAnimated(tool, damageMissed, entity, slotType); } } else { // if not our armor, damage using vanilla like logic ItemStack armorStack = entity.getItemBySlot(slotType); if (!armorStack.isEmpty() && (!source.isFire() || !armorStack.getItem().isFireResistant()) && armorStack.getItem() instanceof ArmorItem) { armorStack.hurtAndBreak(damageMissed, entity, e -> e.broadcastBreakEvent(slotType)); } } } } } } } @SubscribeEvent static void livingDamage(LivingDamageEvent event) { LivingEntity entity = event.getEntity(); DamageSource source = event.getSource(); // give modifiers a chance to respond to damage happening EquipmentContext context = new EquipmentContext(entity); if (context.hasModifiableArmor()) { float amount = ModifyDamageModifierHook.modifyDamageTaken(ModifierHooks.MODIFY_DAMAGE, context, source, event.getAmount(), OnAttackedModifierHook.isDirectDamage(source)); event.setAmount(amount); if (amount <= 0) { event.setCanceled(true); return; } } // when damaging ender dragons, may drop scales - must be player caused explosion, end crystals and TNT are examples if (Config.COMMON.dropDragonScales.get() && entity.getType() == EntityType.ENDER_DRAGON && event.getAmount() > 0 && source.isExplosion() && source.getEntity() != null && source.getEntity().getType() == EntityType.PLAYER) { // drops 1 - 8 scales ModifierUtil.dropItem(entity, new ItemStack(TinkerModifiers.dragonScale, 1 + entity.level.random.nextInt(8))); } } /** Called the modifier hook when an entity's position changes */ @SubscribeEvent static void livingWalk(LivingTickEvent event) { LivingEntity living = event.getEntity(); // this event runs before vanilla updates prevBlockPos BlockPos pos = living.blockPosition(); if (!living.isSpectator() && !living.level.isClientSide() && living.isAlive() && !Objects.equals(living.lastPos, pos)) { ItemStack boots = living.getItemBySlot(EquipmentSlot.FEET); if (!boots.isEmpty() && boots.is(TinkerTags.Items.BOOTS)) { ToolStack tool = ToolStack.from(boots); for (ModifierEntry entry : tool.getModifierList()) { entry.getHook(ModifierHooks.BOOT_WALK).onWalk(tool, entry, living, living.lastPos, pos); } } } } /** Handles visibility effects of mob disguise and projectile protection */ @SubscribeEvent static void livingVisibility(LivingVisibilityEvent event) { // always nonnull in vanilla, not sure when it would be nullable but I dont see a need for either modifier Entity lookingEntity = event.getLookingEntity(); if (lookingEntity == null) { return; } LivingEntity living = event.getEntity(); living.getCapability(TinkerDataCapability.CAPABILITY).ifPresent(data -> { // mob disguise Multiset<EntityType<?>> disguises = data.get(MobDisguiseModule.DISGUISES); if (disguises != null && disguises.contains(lookingEntity.getType())) { // not as good as a real head event.modifyVisibility(0.65f); } }); } /** Implements projectile hit<SUF>*/ @SubscribeEvent static void projectileHit(ProjectileImpactEvent event) { Projectile projectile = event.getProjectile(); ModifierNBT modifiers = EntityModifierCapability.getOrEmpty(projectile); if (!modifiers.isEmpty()) { NamespacedNBT nbt = PersistentDataCapability.getOrWarn(projectile); HitResult hit = event.getRayTraceResult(); HitResult.Type type = hit.getType(); // extract a firing entity as that is a common need LivingEntity attacker = projectile.getOwner() instanceof LivingEntity l ? l : null; switch(type) { case ENTITY -> { EntityHitResult entityHit = (EntityHitResult)hit; // cancel all effects on endermen unless we have enderference, endermen like to teleport away // yes, hardcoded to enderference, if you need your own enderference for whatever reason, talk to us if (entityHit.getEntity().getType() != EntityType.ENDERMAN || modifiers.getLevel(TinkerModifiers.enderference.getId()) > 0) { // extract a living target as that is the most common need LivingEntity target = ToolAttackUtil.getLivingEntity(entityHit.getEntity()); for (ModifierEntry entry : modifiers.getModifiers()) { if (entry.getHook(ModifierHooks.PROJECTILE_HIT).onProjectileHitEntity(modifiers, nbt, entry, projectile, entityHit, attacker, target)) { event.setCanceled(true); } } } } case BLOCK -> { BlockHitResult blockHit = (BlockHitResult)hit; for (ModifierEntry entry : modifiers.getModifiers()) { if (entry.getHook(ModifierHooks.PROJECTILE_HIT).onProjectileHitBlock(modifiers, nbt, entry, projectile, blockHit, attacker)) { event.setCanceled(true); } } } } } } }
178843_41
/** * Copyright (c) 2024 DB InfraGO AG and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * https://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.set.model.planpro.Signale; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * <!-- begin-model-doc --> * HGx_gw=Ergänzung gewendete Streuscheiben (Information zunehmend von SBI gefordert) * <!-- end-model-doc --> * @see org.eclipse.set.model.planpro.Signale.SignalePackage#getENUMStreuscheibeBetriebsstellung() * @model extendedMetaData="name='ENUMStreuscheibe_Betriebsstellung'" * @generated */ public enum ENUMStreuscheibeBetriebsstellung implements Enumerator { /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG1</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1(0, "ENUMStreuscheibe_Betriebsstellung_HG1", "HG1"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG1 gw</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW(1, "ENUMStreuscheibe_Betriebsstellung_HG1_gw", "HG1_gw"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG2</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2(2, "ENUMStreuscheibe_Betriebsstellung_HG2", "HG2"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG2 gw</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW(3, "ENUMStreuscheibe_Betriebsstellung_HG2_gw", "HG2_gw"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG3</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3(4, "ENUMStreuscheibe_Betriebsstellung_HG3", "HG3"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG3 gw</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW(5, "ENUMStreuscheibe_Betriebsstellung_HG3_gw", "HG3_gw"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG4</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4(6, "ENUMStreuscheibe_Betriebsstellung_HG4", "HG4"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG4 gw</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW(7, "ENUMStreuscheibe_Betriebsstellung_HG4_gw", "HG4_gw"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL(8, "ENUMStreuscheibe_Betriebsstellung_HL", "HL"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HR</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR(9, "ENUMStreuscheibe_Betriebsstellung_HR", "HR"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung OL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL(10, "ENUMStreuscheibe_Betriebsstellung_OL", "OL"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung OR</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR(11, "ENUMStreuscheibe_Betriebsstellung_OR", "OR"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung sonstige</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE(12, "ENUMStreuscheibe_Betriebsstellung_sonstige", "sonstige"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung VL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL(13, "ENUMStreuscheibe_Betriebsstellung_VL", "VL"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung VR</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR(14, "ENUMStreuscheibe_Betriebsstellung_VR", "VR"); /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG1</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1 * @model name="ENUMStreuscheibe_Betriebsstellung_HG1" literal="HG1" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_VALUE = 0; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG1 gw</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW * @model name="ENUMStreuscheibe_Betriebsstellung_HG1_gw" literal="HG1_gw" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW_VALUE = 1; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG2</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2 * @model name="ENUMStreuscheibe_Betriebsstellung_HG2" literal="HG2" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_VALUE = 2; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG2 gw</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW * @model name="ENUMStreuscheibe_Betriebsstellung_HG2_gw" literal="HG2_gw" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW_VALUE = 3; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG3</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3 * @model name="ENUMStreuscheibe_Betriebsstellung_HG3" literal="HG3" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_VALUE = 4; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG3 gw</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW * @model name="ENUMStreuscheibe_Betriebsstellung_HG3_gw" literal="HG3_gw" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW_VALUE = 5; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG4</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4 * @model name="ENUMStreuscheibe_Betriebsstellung_HG4" literal="HG4" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_VALUE = 6; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG4 gw</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW * @model name="ENUMStreuscheibe_Betriebsstellung_HG4_gw" literal="HG4_gw" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW_VALUE = 7; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HL</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL * @model name="ENUMStreuscheibe_Betriebsstellung_HL" literal="HL" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL_VALUE = 8; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HR</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR * @model name="ENUMStreuscheibe_Betriebsstellung_HR" literal="HR" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR_VALUE = 9; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung OL</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL * @model name="ENUMStreuscheibe_Betriebsstellung_OL" literal="OL" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL_VALUE = 10; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung OR</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR * @model name="ENUMStreuscheibe_Betriebsstellung_OR" literal="OR" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR_VALUE = 11; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung sonstige</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE * @model name="ENUMStreuscheibe_Betriebsstellung_sonstige" literal="sonstige" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE_VALUE = 12; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung VL</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL * @model name="ENUMStreuscheibe_Betriebsstellung_VL" literal="VL" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL_VALUE = 13; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung VR</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR * @model name="ENUMStreuscheibe_Betriebsstellung_VR" literal="VR" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR_VALUE = 14; /** * An array of all the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final ENUMStreuscheibeBetriebsstellung[] VALUES_ARRAY = new ENUMStreuscheibeBetriebsstellung[] { ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR, }; /** * A public read-only list of all the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<ENUMStreuscheibeBetriebsstellung> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static ENUMStreuscheibeBetriebsstellung get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ENUMStreuscheibeBetriebsstellung result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static ENUMStreuscheibeBetriebsstellung getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ENUMStreuscheibeBetriebsstellung result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static ENUMStreuscheibeBetriebsstellung get(int value) { switch (value) { case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private ENUMStreuscheibeBetriebsstellung(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //ENUMStreuscheibeBetriebsstellung
eclipse-set/model
java/org.eclipse.set.model.planpro/src/org/eclipse/set/model/planpro/Signale/ENUMStreuscheibeBetriebsstellung.java
6,124
/** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
block_comment
nl
/** * Copyright (c) 2024 DB InfraGO AG and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * https://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.set.model.planpro.Signale; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * <!-- begin-model-doc --> * HGx_gw=Ergänzung gewendete Streuscheiben (Information zunehmend von SBI gefordert) * <!-- end-model-doc --> * @see org.eclipse.set.model.planpro.Signale.SignalePackage#getENUMStreuscheibeBetriebsstellung() * @model extendedMetaData="name='ENUMStreuscheibe_Betriebsstellung'" * @generated */ public enum ENUMStreuscheibeBetriebsstellung implements Enumerator { /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG1</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1(0, "ENUMStreuscheibe_Betriebsstellung_HG1", "HG1"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG1 gw</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW(1, "ENUMStreuscheibe_Betriebsstellung_HG1_gw", "HG1_gw"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG2</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2(2, "ENUMStreuscheibe_Betriebsstellung_HG2", "HG2"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG2 gw</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW(3, "ENUMStreuscheibe_Betriebsstellung_HG2_gw", "HG2_gw"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG3</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3(4, "ENUMStreuscheibe_Betriebsstellung_HG3", "HG3"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG3 gw</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW(5, "ENUMStreuscheibe_Betriebsstellung_HG3_gw", "HG3_gw"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG4</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4(6, "ENUMStreuscheibe_Betriebsstellung_HG4", "HG4"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG4 gw</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW(7, "ENUMStreuscheibe_Betriebsstellung_HG4_gw", "HG4_gw"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL(8, "ENUMStreuscheibe_Betriebsstellung_HL", "HL"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HR</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR(9, "ENUMStreuscheibe_Betriebsstellung_HR", "HR"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung OL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL(10, "ENUMStreuscheibe_Betriebsstellung_OL", "OL"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung OR</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR(11, "ENUMStreuscheibe_Betriebsstellung_OR", "OR"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung sonstige</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE(12, "ENUMStreuscheibe_Betriebsstellung_sonstige", "sonstige"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung VL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL(13, "ENUMStreuscheibe_Betriebsstellung_VL", "VL"), /** * The '<em><b>ENUM Streuscheibe Betriebsstellung VR</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR_VALUE * @generated * @ordered */ ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR(14, "ENUMStreuscheibe_Betriebsstellung_VR", "VR"); /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG1</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1 * @model name="ENUMStreuscheibe_Betriebsstellung_HG1" literal="HG1" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_VALUE = 0; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG1 gw</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW * @model name="ENUMStreuscheibe_Betriebsstellung_HG1_gw" literal="HG1_gw" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW_VALUE = 1; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG2</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2 * @model name="ENUMStreuscheibe_Betriebsstellung_HG2" literal="HG2" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_VALUE = 2; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG2 gw</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW * @model name="ENUMStreuscheibe_Betriebsstellung_HG2_gw" literal="HG2_gw" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW_VALUE = 3; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG3</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3 * @model name="ENUMStreuscheibe_Betriebsstellung_HG3" literal="HG3" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_VALUE = 4; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG3 gw</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW * @model name="ENUMStreuscheibe_Betriebsstellung_HG3_gw" literal="HG3_gw" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW_VALUE = 5; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG4</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4 * @model name="ENUMStreuscheibe_Betriebsstellung_HG4" literal="HG4" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_VALUE = 6; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HG4 gw</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW * @model name="ENUMStreuscheibe_Betriebsstellung_HG4_gw" literal="HG4_gw" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW_VALUE = 7; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HL</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL * @model name="ENUMStreuscheibe_Betriebsstellung_HL" literal="HL" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL_VALUE = 8; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung HR</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR * @model name="ENUMStreuscheibe_Betriebsstellung_HR" literal="HR" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR_VALUE = 9; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung OL</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL * @model name="ENUMStreuscheibe_Betriebsstellung_OL" literal="OL" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL_VALUE = 10; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung OR</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR * @model name="ENUMStreuscheibe_Betriebsstellung_OR" literal="OR" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR_VALUE = 11; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung sonstige</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE * @model name="ENUMStreuscheibe_Betriebsstellung_sonstige" literal="sonstige" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE_VALUE = 12; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung VL</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL * @model name="ENUMStreuscheibe_Betriebsstellung_VL" literal="VL" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL_VALUE = 13; /** * The '<em><b>ENUM Streuscheibe Betriebsstellung VR</b></em>' literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR * @model name="ENUMStreuscheibe_Betriebsstellung_VR" literal="VR" * @generated * @ordered */ public static final int ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR_VALUE = 14; /** * An array of all the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final ENUMStreuscheibeBetriebsstellung[] VALUES_ARRAY = new ENUMStreuscheibeBetriebsstellung[] { ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL, ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR, }; /** * A public read-only list of all the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<ENUMStreuscheibeBetriebsstellung> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static ENUMStreuscheibeBetriebsstellung get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ENUMStreuscheibeBetriebsstellung result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static ENUMStreuscheibeBetriebsstellung getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ENUMStreuscheibeBetriebsstellung result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>ENUM Streuscheibe Betriebsstellung</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static ENUMStreuscheibeBetriebsstellung get(int value) { switch (value) { case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG1_GW; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG2_GW; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG3_GW; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HG4_GW; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HL; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_HR; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OL; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_OR; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_SONSTIGE; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VL; case ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR_VALUE: return ENUM_STREUSCHEIBE_BETRIEBSSTELLUNG_VR; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private ENUMStreuscheibeBetriebsstellung(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --><SUF>*/ @Override public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //ENUMStreuscheibeBetriebsstellung
11542_19
// Main class. Alle methodes worden in deze klasse gedefinieerd. public class Main { // De main methode is gewoon een methode, maar wel verplicht als je je code wilt kunnen uitvoeren. Dit is de "voordeur" van je applicatie public static void main(String[] args) { // Variabele declaratie: [Type] [naam] = [waarde]; int number = 6; // type:int // naam:number // waarde:6 int number1 = 4; // type:int // naam:number1 // waarde:4 int number2 = 20; // type:int // naam:number2 // waarde:20 String name = "Kees"; // type:String // naam:name // waarde:"Kees" // Methode aanroepen: [naam][parameters tussen ()-haakjes]; hello(); positiveOrNegative(number); positiveOrNulOrNegative(number); sum(number1, number2); bartender(name); } // Methode declaratie: [Acces modifier] [optionele static] [return waarde] [naam] [parameters tussen ()-haakjes] [body tussen {}-accolades] public static void hello() { System.out.println("Hello, world"); } // Een methode declaratie met een parameter: [Type] [naam] public static void positiveOrNegative(int number) { // als het nummer in de parameter groter dan 0 is if (number > 0) { System.out.println("This number is positive!"); // alle andere gevallen, dus als het nummer in de parameter kleiner of gelijk aan 0 is } else { System.out.println("This number is negative!"); } } public static void positiveOrNulOrNegative(int number) { // als het nummer in de parameter groter dan 0 is if (number > 0) { System.out.println("This number is positive!"); // als het nummer in de parameter gelijk aan 0 is } else if (number == 0) { System.out.println("This number is zero!"); // alle andere gevallen, dus als het nummer in de parameter kleiner dan 0 is } else { System.out.println("This number is negative!"); } } public static void bartender(String name) { // We maken een switch die een beslissing maakt aan de hand van de waarde van de name parameter switch (name) { // als de waarde "Kees" is case "Kees": System.out.println("Kees wants a beer"); break; // als de waarde "Cassie" is case "Cassie": System.out.println("Cassie wants a withe wine"); // als de waarde "Jack" is case "Jack": System.out.println("Jack wants a coke"); // als de waarde "Nicky" is case "Nicky": System.out.println("Nicky wants a red wine"); } } // Een methode met 2 parameters, gescheiden door een komma. public static void sum(int number1, int number2) { // Let op hoe hier de String aan elkaar geknoopt is. Dat is concatenatie. Tip: let bij concatenatie altijd goed op de spaties. System.out.println(number1 + " summed with " + number2 + " = " + (number1 + number2)); } // Accolade sluit van de Main class }
hogeschoolnovi/backend-java-beslissingsstructuren-methodes-uitwerkingen
src/Main.java
845
// als de waarde "Nicky" is
line_comment
nl
// Main class. Alle methodes worden in deze klasse gedefinieerd. public class Main { // De main methode is gewoon een methode, maar wel verplicht als je je code wilt kunnen uitvoeren. Dit is de "voordeur" van je applicatie public static void main(String[] args) { // Variabele declaratie: [Type] [naam] = [waarde]; int number = 6; // type:int // naam:number // waarde:6 int number1 = 4; // type:int // naam:number1 // waarde:4 int number2 = 20; // type:int // naam:number2 // waarde:20 String name = "Kees"; // type:String // naam:name // waarde:"Kees" // Methode aanroepen: [naam][parameters tussen ()-haakjes]; hello(); positiveOrNegative(number); positiveOrNulOrNegative(number); sum(number1, number2); bartender(name); } // Methode declaratie: [Acces modifier] [optionele static] [return waarde] [naam] [parameters tussen ()-haakjes] [body tussen {}-accolades] public static void hello() { System.out.println("Hello, world"); } // Een methode declaratie met een parameter: [Type] [naam] public static void positiveOrNegative(int number) { // als het nummer in de parameter groter dan 0 is if (number > 0) { System.out.println("This number is positive!"); // alle andere gevallen, dus als het nummer in de parameter kleiner of gelijk aan 0 is } else { System.out.println("This number is negative!"); } } public static void positiveOrNulOrNegative(int number) { // als het nummer in de parameter groter dan 0 is if (number > 0) { System.out.println("This number is positive!"); // als het nummer in de parameter gelijk aan 0 is } else if (number == 0) { System.out.println("This number is zero!"); // alle andere gevallen, dus als het nummer in de parameter kleiner dan 0 is } else { System.out.println("This number is negative!"); } } public static void bartender(String name) { // We maken een switch die een beslissing maakt aan de hand van de waarde van de name parameter switch (name) { // als de waarde "Kees" is case "Kees": System.out.println("Kees wants a beer"); break; // als de waarde "Cassie" is case "Cassie": System.out.println("Cassie wants a withe wine"); // als de waarde "Jack" is case "Jack": System.out.println("Jack wants a coke"); // als de<SUF> case "Nicky": System.out.println("Nicky wants a red wine"); } } // Een methode met 2 parameters, gescheiden door een komma. public static void sum(int number1, int number2) { // Let op hoe hier de String aan elkaar geknoopt is. Dat is concatenatie. Tip: let bij concatenatie altijd goed op de spaties. System.out.println(number1 + " summed with " + number2 + " = " + (number1 + number2)); } // Accolade sluit van de Main class }
109960_21
package com.example.loginregister.ui.profile; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.text.InputType; import android.text.TextUtils; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import com.example.loginregister.MainActivity; import com.example.loginregister.R; import com.example.loginregister.login; import com.facebook.login.Login; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.Executor; import java.util.regex.Pattern; import io.grpc.Context; import jp.wasabeef.picasso.transformations.CropCircleTransformation; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import static android.app.Activity.RESULT_OK; import static com.google.firebase.storage.FirebaseStorage.getInstance; public class ProfileFragment extends Fragment { Button btnVeranderFoto; ImageButton mLogout; ImageView ProfielFoto; TextView naam, gsm, mail, amountBoxes, amountHarvests, mAddress; DatabaseReference reff; FirebaseUser muser; FirebaseAuth mAuth; FirebaseFirestore mStore; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; StorageReference storageReference; String userID; String storagePath = "Users_Profile_Imgs/"; Uri image_uri; ImageView mprofilePic; FloatingActionButton fab; ProgressDialog pd; FusedLocationProviderClient fusedLocationProviderClient; private static final int CAMERA_REQUEST_CODE = 100; private static final int STORAGE_REQUEST_CODE = 200; private static final int IMAGE_PICK_GALLERY_CODE = 300; private static final int IMAGE_PICK_CAMERA__CODE = 400; String cameraPermissions[]; String storagePermissions[]; public ProfileFragment() { } public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_profile, container, false); naam = view.findViewById(R.id.username_Textview); gsm = view.findViewById(R.id.phonenumber_Textview); mail = view.findViewById(R.id.userEmail_Textview); mprofilePic = view.findViewById(R.id.profilePic); fab = view.findViewById(R.id.EditProfile); amountBoxes = view.findViewById(R.id.txtAmountBoxes); amountHarvests = view.findViewById(R.id.txtAmountHarvests); mAddress = view.findViewById(R.id.adress_textView); mLogout = view.findViewById(R.id.logout_button); //init arrays of permissions cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; muser = FirebaseAuth.getInstance().getCurrentUser(); mAuth = FirebaseAuth.getInstance(); mStore = FirebaseFirestore.getInstance(); // databaseReference = firebaseDatabase.getReference("Users"); userID = mAuth.getCurrentUser().getUid(); storageReference = getInstance().getReference(); //fbase stor ref pd = new ProgressDialog(getActivity()); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity()); if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { getlocation(); } else { //no permission ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44); } //Code stef die reeds werkt --> betere optie mogelijk DocumentReference documentReference = mStore.collection("Users").document(userID); documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { String _naam = documentSnapshot.getString("uname"); String _gsm = documentSnapshot.getString("phone"); String _mail = documentSnapshot.getString("email"); String _foto = documentSnapshot.getString("image"); String _amountBoxes = documentSnapshot.getString("amountBoxes"); String _amountHarvests = documentSnapshot.getString("amountHarvests"); naam.setText(_naam); gsm.setText(_gsm); mail.setText(_mail); amountBoxes.setText(_amountBoxes); amountHarvests.setText((_amountHarvests)); try { Picasso.get().load(_foto).fit().transform(new CropCircleTransformation()).centerCrop().rotate(90).into(mprofilePic); // Picasso.get().load(_foto).into(mprofilePic); } catch (Exception a) { Picasso.get().load(R.drawable.ic_settings); } } }); mLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertsignout(); } }); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ShowEditProfileDialog(); } }); return view; } @SuppressLint("MissingPermission") private void getlocation() { fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() { @Override public void onComplete(@NonNull Task<Location> task) { Location location = task.getResult(); if (location != null){ try { Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation( location.getLatitude(), location.getLongitude(), 1 ); mAddress.setText(addresses.get(0).getLocality() +"," + addresses.get(0).getCountryName()); } catch (IOException e) { e.printStackTrace(); } } } }); } private boolean checkStoragePermission(){ boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } /* private void requestStoragePermission(){ ActivityCompat.requestPermissions(getActivity(), storagePermissions, STORAGE_REQUEST_CODE); } */ @RequiresApi(api = Build.VERSION_CODES.M) private void requestStoragePermission(){ //min api verhogen requestPermissions(storagePermissions ,STORAGE_REQUEST_CODE); } private boolean checkCameraPermission(){ boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } //min api verhogen private void requestCameraPermission(){ ActivityCompat.requestPermissions(getActivity(), cameraPermissions, CAMERA_REQUEST_CODE); } private void ShowEditProfileDialog(){ /* show dialog heeft volgende opties 1. foto kunnen bewerken --> zowel uit album als camera 2. naam, telefoon etc (user info dus) aanpassen. */ String options[] = {"Edit profile picture"," Edit name","Edit phone number","Edit e-mail"}; //alert dialog AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Choose action"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case 0: //edit profile picture pd.setMessage("updating profile picture"); showImagePicDialog(); break; case 1: // edit name pd.setMessage("updating name"); showNamePhoneUpdateDialog("uname"); break; case 2: //edit phone number pd.setMessage("updating phone number"); showNamePhoneUpdateDialog("phone"); break; case 3: //edit email pd.setMessage("updating mail"); showNamePhoneUpdateDialog("email"); break; default: break; } } }); builder.create().show(); } private void showNamePhoneUpdateDialog(final String key) { String emailRegEx = "^[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,4}$"; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("update "+ key); //set layout of dialog LinearLayout linearLayout = new LinearLayout(getActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(10,10,10,10); //add edit text final EditText editText = new EditText(getActivity()); if (key == "phone"){ editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); } editText.setHint("Enter"+key); //edit update name or photo linearLayout.addView(editText); builder.setView(linearLayout); builder.setPositiveButton("update", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //validation //input text from edit text String value = editText.getText().toString().trim(); if (!TextUtils.isEmpty(value)){ HashMap<String, Object> result = new HashMap<>(); result.put(key, value); DocumentReference documentReference = mStore.collection("Users").document(userID); documentReference.update(key, value); } else { Toast.makeText(getActivity(), "please enter"+key, Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); //create and show dialog builder.create(); builder.show(); } private void showImagePicDialog(){ /* show dialog heeft volgende opties 1. foto kunnen bewerken --> zowel uit album als camera */ String options[] = {"Camera"," Gallery"}; //alert dialog AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Pick Image From"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case 0: //camera if(!checkCameraPermission()){ requestCameraPermission(); } else { pickFromCamera(); } break; case 1: // gallery pd.setMessage("updating name"); if(!checkStoragePermission()){ requestStoragePermission(); } else { requestStoragePermission(); } break; default: break; } } }); builder.create().show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //deze methode wordt aangeroepen wanneer de user Allow of Deny kiest van de dialog //deze keuze wordt hier afgehandeld switch (requestCode){ case CAMERA_REQUEST_CODE:{ if (grantResults.length>0){ //checken of we toegang hebben tot camera boolean cameraAccepted =grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if(cameraAccepted && writeStorageAccepted){ pickFromCamera(); } } else { //toegang geweigerd Toast.makeText(getActivity(), "please enable camera & storage permission", Toast.LENGTH_SHORT).show(); } } break; case STORAGE_REQUEST_CODE:{ //van gallerij: eerst checkn of we hiervoor toestemming hebben if (grantResults.length>0){ boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if(writeStorageAccepted){ pickFromGallery(); } } else { //toegang geweigerd Toast.makeText(getActivity(), "please enalble storage permission", Toast.LENGTH_SHORT).show(); } } break; } } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { //deze methode wordt opgeroepne na het nemen van een foto van camera of gallerij if (resultCode == RESULT_OK) { if (requestCode == IMAGE_PICK_GALLERY_CODE) { //abeelding gekozen vanuit de gallerij --> verkrijgen van uri van de image image_uri = data.getData(); uploadProfileCoverphoto(image_uri); } if (requestCode == IMAGE_PICK_CAMERA__CODE) { //afbeelding gekozen met camera uploadProfileCoverphoto(image_uri); } } super.onActivityResult(requestCode, resultCode, data); } private void uploadProfileCoverphoto(final Uri uri) { //path and name of image t be stored in firebase storage String filePathandName = storagePath+ "" + "image" + "_"+ userID; StorageReference storageReference2 = storageReference.child(filePathandName); storageReference2.putFile(uri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl(); while (!uriTask.isSuccessful()); Uri downloadUti = uriTask.getResult(); //check if image is dowloaded or not if (uriTask.isSuccessful()){ //image upload //add/update url in users database HashMap<String, Object> results = new HashMap<>(); results.put("image", downloadUti.toString()); DocumentReference documentReference = mStore.collection("Users").document(userID); documentReference.update("image", downloadUti.toString()); } else { //error Toast.makeText(getContext(), "Some error occured", Toast.LENGTH_SHORT).show(); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void pickFromCamera() { //intent of picking image from device camera ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "Temp Pic"); values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description"); //put image uri image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); //intent to start camera Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri); startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA__CODE); } //check private void pickFromGallery(){ //pick from gallery Intent galleryIntent = new Intent(Intent.ACTION_PICK); galleryIntent.setType("image/*"); startActivityForResult(galleryIntent,IMAGE_PICK_GALLERY_CODE); } public void logout(View view) { FirebaseAuth.getInstance().signOut();//logout startActivity(new Intent(getActivity(), login.class)); } public void alertsignout() { AlertDialog.Builder alertDialog2 = new AlertDialog.Builder( getActivity()); // Setting Dialog Title alertDialog2.setTitle("Confirm SignOut"); // Setting Dialog Message alertDialog2.setMessage("Are you sure you want to Signout?"); // Setting Positive "Yes" Btn alertDialog2.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog FirebaseAuth.getInstance().signOut(); Intent i = new Intent(getActivity(), login.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); } }); // Setting Negative "NO" Btn alertDialog2.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog Toast.makeText(getContext(), "You clicked on NO", Toast.LENGTH_SHORT) .show(); dialog.cancel(); } }); // Showing Alert Dialog alertDialog2.show(); } }
AP-IT-GH/ap-valley-20-21-apv02
app/src/main/java/com/example/loginregister/ui/profile/ProfileFragment.java
4,646
//abeelding gekozen vanuit de gallerij --> verkrijgen van uri van de image
line_comment
nl
package com.example.loginregister.ui.profile; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.text.InputType; import android.text.TextUtils; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import com.example.loginregister.MainActivity; import com.example.loginregister.R; import com.example.loginregister.login; import com.facebook.login.Login; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.Executor; import java.util.regex.Pattern; import io.grpc.Context; import jp.wasabeef.picasso.transformations.CropCircleTransformation; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import static android.app.Activity.RESULT_OK; import static com.google.firebase.storage.FirebaseStorage.getInstance; public class ProfileFragment extends Fragment { Button btnVeranderFoto; ImageButton mLogout; ImageView ProfielFoto; TextView naam, gsm, mail, amountBoxes, amountHarvests, mAddress; DatabaseReference reff; FirebaseUser muser; FirebaseAuth mAuth; FirebaseFirestore mStore; FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; StorageReference storageReference; String userID; String storagePath = "Users_Profile_Imgs/"; Uri image_uri; ImageView mprofilePic; FloatingActionButton fab; ProgressDialog pd; FusedLocationProviderClient fusedLocationProviderClient; private static final int CAMERA_REQUEST_CODE = 100; private static final int STORAGE_REQUEST_CODE = 200; private static final int IMAGE_PICK_GALLERY_CODE = 300; private static final int IMAGE_PICK_CAMERA__CODE = 400; String cameraPermissions[]; String storagePermissions[]; public ProfileFragment() { } public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_profile, container, false); naam = view.findViewById(R.id.username_Textview); gsm = view.findViewById(R.id.phonenumber_Textview); mail = view.findViewById(R.id.userEmail_Textview); mprofilePic = view.findViewById(R.id.profilePic); fab = view.findViewById(R.id.EditProfile); amountBoxes = view.findViewById(R.id.txtAmountBoxes); amountHarvests = view.findViewById(R.id.txtAmountHarvests); mAddress = view.findViewById(R.id.adress_textView); mLogout = view.findViewById(R.id.logout_button); //init arrays of permissions cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; muser = FirebaseAuth.getInstance().getCurrentUser(); mAuth = FirebaseAuth.getInstance(); mStore = FirebaseFirestore.getInstance(); // databaseReference = firebaseDatabase.getReference("Users"); userID = mAuth.getCurrentUser().getUid(); storageReference = getInstance().getReference(); //fbase stor ref pd = new ProgressDialog(getActivity()); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity()); if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { getlocation(); } else { //no permission ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44); } //Code stef die reeds werkt --> betere optie mogelijk DocumentReference documentReference = mStore.collection("Users").document(userID); documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { String _naam = documentSnapshot.getString("uname"); String _gsm = documentSnapshot.getString("phone"); String _mail = documentSnapshot.getString("email"); String _foto = documentSnapshot.getString("image"); String _amountBoxes = documentSnapshot.getString("amountBoxes"); String _amountHarvests = documentSnapshot.getString("amountHarvests"); naam.setText(_naam); gsm.setText(_gsm); mail.setText(_mail); amountBoxes.setText(_amountBoxes); amountHarvests.setText((_amountHarvests)); try { Picasso.get().load(_foto).fit().transform(new CropCircleTransformation()).centerCrop().rotate(90).into(mprofilePic); // Picasso.get().load(_foto).into(mprofilePic); } catch (Exception a) { Picasso.get().load(R.drawable.ic_settings); } } }); mLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertsignout(); } }); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ShowEditProfileDialog(); } }); return view; } @SuppressLint("MissingPermission") private void getlocation() { fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() { @Override public void onComplete(@NonNull Task<Location> task) { Location location = task.getResult(); if (location != null){ try { Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation( location.getLatitude(), location.getLongitude(), 1 ); mAddress.setText(addresses.get(0).getLocality() +"," + addresses.get(0).getCountryName()); } catch (IOException e) { e.printStackTrace(); } } } }); } private boolean checkStoragePermission(){ boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result; } /* private void requestStoragePermission(){ ActivityCompat.requestPermissions(getActivity(), storagePermissions, STORAGE_REQUEST_CODE); } */ @RequiresApi(api = Build.VERSION_CODES.M) private void requestStoragePermission(){ //min api verhogen requestPermissions(storagePermissions ,STORAGE_REQUEST_CODE); } private boolean checkCameraPermission(){ boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED); boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED); return result && result1; } //min api verhogen private void requestCameraPermission(){ ActivityCompat.requestPermissions(getActivity(), cameraPermissions, CAMERA_REQUEST_CODE); } private void ShowEditProfileDialog(){ /* show dialog heeft volgende opties 1. foto kunnen bewerken --> zowel uit album als camera 2. naam, telefoon etc (user info dus) aanpassen. */ String options[] = {"Edit profile picture"," Edit name","Edit phone number","Edit e-mail"}; //alert dialog AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Choose action"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case 0: //edit profile picture pd.setMessage("updating profile picture"); showImagePicDialog(); break; case 1: // edit name pd.setMessage("updating name"); showNamePhoneUpdateDialog("uname"); break; case 2: //edit phone number pd.setMessage("updating phone number"); showNamePhoneUpdateDialog("phone"); break; case 3: //edit email pd.setMessage("updating mail"); showNamePhoneUpdateDialog("email"); break; default: break; } } }); builder.create().show(); } private void showNamePhoneUpdateDialog(final String key) { String emailRegEx = "^[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,4}$"; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("update "+ key); //set layout of dialog LinearLayout linearLayout = new LinearLayout(getActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(10,10,10,10); //add edit text final EditText editText = new EditText(getActivity()); if (key == "phone"){ editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); } editText.setHint("Enter"+key); //edit update name or photo linearLayout.addView(editText); builder.setView(linearLayout); builder.setPositiveButton("update", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //validation //input text from edit text String value = editText.getText().toString().trim(); if (!TextUtils.isEmpty(value)){ HashMap<String, Object> result = new HashMap<>(); result.put(key, value); DocumentReference documentReference = mStore.collection("Users").document(userID); documentReference.update(key, value); } else { Toast.makeText(getActivity(), "please enter"+key, Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); //create and show dialog builder.create(); builder.show(); } private void showImagePicDialog(){ /* show dialog heeft volgende opties 1. foto kunnen bewerken --> zowel uit album als camera */ String options[] = {"Camera"," Gallery"}; //alert dialog AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Pick Image From"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case 0: //camera if(!checkCameraPermission()){ requestCameraPermission(); } else { pickFromCamera(); } break; case 1: // gallery pd.setMessage("updating name"); if(!checkStoragePermission()){ requestStoragePermission(); } else { requestStoragePermission(); } break; default: break; } } }); builder.create().show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //deze methode wordt aangeroepen wanneer de user Allow of Deny kiest van de dialog //deze keuze wordt hier afgehandeld switch (requestCode){ case CAMERA_REQUEST_CODE:{ if (grantResults.length>0){ //checken of we toegang hebben tot camera boolean cameraAccepted =grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if(cameraAccepted && writeStorageAccepted){ pickFromCamera(); } } else { //toegang geweigerd Toast.makeText(getActivity(), "please enable camera & storage permission", Toast.LENGTH_SHORT).show(); } } break; case STORAGE_REQUEST_CODE:{ //van gallerij: eerst checkn of we hiervoor toestemming hebben if (grantResults.length>0){ boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED; if(writeStorageAccepted){ pickFromGallery(); } } else { //toegang geweigerd Toast.makeText(getActivity(), "please enalble storage permission", Toast.LENGTH_SHORT).show(); } } break; } } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { //deze methode wordt opgeroepne na het nemen van een foto van camera of gallerij if (resultCode == RESULT_OK) { if (requestCode == IMAGE_PICK_GALLERY_CODE) { //abeelding gekozen<SUF> image_uri = data.getData(); uploadProfileCoverphoto(image_uri); } if (requestCode == IMAGE_PICK_CAMERA__CODE) { //afbeelding gekozen met camera uploadProfileCoverphoto(image_uri); } } super.onActivityResult(requestCode, resultCode, data); } private void uploadProfileCoverphoto(final Uri uri) { //path and name of image t be stored in firebase storage String filePathandName = storagePath+ "" + "image" + "_"+ userID; StorageReference storageReference2 = storageReference.child(filePathandName); storageReference2.putFile(uri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl(); while (!uriTask.isSuccessful()); Uri downloadUti = uriTask.getResult(); //check if image is dowloaded or not if (uriTask.isSuccessful()){ //image upload //add/update url in users database HashMap<String, Object> results = new HashMap<>(); results.put("image", downloadUti.toString()); DocumentReference documentReference = mStore.collection("Users").document(userID); documentReference.update("image", downloadUti.toString()); } else { //error Toast.makeText(getContext(), "Some error occured", Toast.LENGTH_SHORT).show(); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { pd.dismiss(); Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void pickFromCamera() { //intent of picking image from device camera ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "Temp Pic"); values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description"); //put image uri image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); //intent to start camera Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri); startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA__CODE); } //check private void pickFromGallery(){ //pick from gallery Intent galleryIntent = new Intent(Intent.ACTION_PICK); galleryIntent.setType("image/*"); startActivityForResult(galleryIntent,IMAGE_PICK_GALLERY_CODE); } public void logout(View view) { FirebaseAuth.getInstance().signOut();//logout startActivity(new Intent(getActivity(), login.class)); } public void alertsignout() { AlertDialog.Builder alertDialog2 = new AlertDialog.Builder( getActivity()); // Setting Dialog Title alertDialog2.setTitle("Confirm SignOut"); // Setting Dialog Message alertDialog2.setMessage("Are you sure you want to Signout?"); // Setting Positive "Yes" Btn alertDialog2.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog FirebaseAuth.getInstance().signOut(); Intent i = new Intent(getActivity(), login.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); } }); // Setting Negative "NO" Btn alertDialog2.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog Toast.makeText(getContext(), "You clicked on NO", Toast.LENGTH_SHORT) .show(); dialog.cancel(); } }); // Showing Alert Dialog alertDialog2.show(); } }
144387_11
package nl.devoorkant.sbdr.ws.transfer; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.module.SimpleModule; import javax.ws.rs.WebApplicationException; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.IOException; import java.util.Map; @XmlRootElement public class UserAccount extends UserTransfer { //private String emailAdres = null; private String functie = null; private String naam = null; private String voornaam = null; //private Integer bedrijfId = null; private String wachtwoord = null; private boolean verantwoordelijkheidAkkoord = false; private String clientId; // API private String clientSecret; // API public UserAccount() { super(); } public UserAccount(Integer bedrijfId, String bedrijfNaam, Integer userId, String userName, String wachtwoord, String voornaam, String naam, String functie, String afdeling, String emailAdres, String gebruikerTelefoonNummer, String bedrijfTelefoonNummer, boolean isKlant, boolean isProspect, boolean isAdresOk, Map<String, Boolean> roles, boolean actionsPresent, Integer showHelp, String geslacht, boolean mobileUser, boolean isBedrijfManager) { super(userName, voornaam, naam, functie, afdeling, emailAdres, userId, bedrijfId, bedrijfNaam, gebruikerTelefoonNummer, bedrijfTelefoonNummer, isKlant, isProspect, isAdresOk, roles, actionsPresent, showHelp, geslacht, mobileUser, isBedrijfManager); //this.setBedrijfId(bedrijfId); this.wachtwoord = wachtwoord; this.voornaam = voornaam; this.naam = naam; //this.emailAdres = emailAdres; this.functie = functie; } /** * Deserializes an Object of class User from its JSON representation */ public static UserAccount fromString(String jsonRepresentation) { ObjectMapper mapper = new ObjectMapper(); // Jackson's JSON marshaller UserAccount o = null; SimpleModule module = new SimpleModule("UserAccountDeserializer", new Version(1, 0, 0, null)); //module.addDeserializer(UserTransfer.class, new UserDeserializer()); mapper.registerModule(module); try { o = mapper.readValue(jsonRepresentation, UserAccount.class); } catch(IOException e) { throw new WebApplicationException(); } return o; } @XmlElement public boolean isVerantwoordelijkheidAkkoord() { return verantwoordelijkheidAkkoord; } public void setVerantwoordelijkheidAkkoord(boolean verantwoordelijkheidAkkoord) { this.verantwoordelijkheidAkkoord = verantwoordelijkheidAkkoord; } @XmlElement public String getFunctie() { return functie; } public void setFunctie(String functie) { this.functie = functie; } @XmlElement public String getNaam() { return naam; } public void setNaam(String naam) { this.naam = naam; } @XmlElement public String getVoornaam() { return voornaam; } // @XmlElement // public String getEmailAdres() { // return emailAdres; // } // // public void setEmailAdres(String emailAdres) { // this.emailAdres = emailAdres; // } public void setVoornaam(String voornaam) { this.voornaam = voornaam; } @XmlElement public String getWachtwoord() { return wachtwoord; } // public Integer getBedrijfId() { // return bedrijfId; // } // // public void setBedrijfId(Integer bedrijfId) { // this.bedrijfId = bedrijfId; // } public void setWachtwoord(String wachtwoord) { this.wachtwoord = wachtwoord; } @XmlElement public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } @XmlElement public String getClientSecret() { return clientSecret; } public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } }
dangdanhhuu6292/company-search
sbdr-web/src/main/java/nl/devoorkant/sbdr/ws/transfer/UserAccount.java
1,077
// this.bedrijfId = bedrijfId;
line_comment
nl
package nl.devoorkant.sbdr.ws.transfer; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.module.SimpleModule; import javax.ws.rs.WebApplicationException; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.IOException; import java.util.Map; @XmlRootElement public class UserAccount extends UserTransfer { //private String emailAdres = null; private String functie = null; private String naam = null; private String voornaam = null; //private Integer bedrijfId = null; private String wachtwoord = null; private boolean verantwoordelijkheidAkkoord = false; private String clientId; // API private String clientSecret; // API public UserAccount() { super(); } public UserAccount(Integer bedrijfId, String bedrijfNaam, Integer userId, String userName, String wachtwoord, String voornaam, String naam, String functie, String afdeling, String emailAdres, String gebruikerTelefoonNummer, String bedrijfTelefoonNummer, boolean isKlant, boolean isProspect, boolean isAdresOk, Map<String, Boolean> roles, boolean actionsPresent, Integer showHelp, String geslacht, boolean mobileUser, boolean isBedrijfManager) { super(userName, voornaam, naam, functie, afdeling, emailAdres, userId, bedrijfId, bedrijfNaam, gebruikerTelefoonNummer, bedrijfTelefoonNummer, isKlant, isProspect, isAdresOk, roles, actionsPresent, showHelp, geslacht, mobileUser, isBedrijfManager); //this.setBedrijfId(bedrijfId); this.wachtwoord = wachtwoord; this.voornaam = voornaam; this.naam = naam; //this.emailAdres = emailAdres; this.functie = functie; } /** * Deserializes an Object of class User from its JSON representation */ public static UserAccount fromString(String jsonRepresentation) { ObjectMapper mapper = new ObjectMapper(); // Jackson's JSON marshaller UserAccount o = null; SimpleModule module = new SimpleModule("UserAccountDeserializer", new Version(1, 0, 0, null)); //module.addDeserializer(UserTransfer.class, new UserDeserializer()); mapper.registerModule(module); try { o = mapper.readValue(jsonRepresentation, UserAccount.class); } catch(IOException e) { throw new WebApplicationException(); } return o; } @XmlElement public boolean isVerantwoordelijkheidAkkoord() { return verantwoordelijkheidAkkoord; } public void setVerantwoordelijkheidAkkoord(boolean verantwoordelijkheidAkkoord) { this.verantwoordelijkheidAkkoord = verantwoordelijkheidAkkoord; } @XmlElement public String getFunctie() { return functie; } public void setFunctie(String functie) { this.functie = functie; } @XmlElement public String getNaam() { return naam; } public void setNaam(String naam) { this.naam = naam; } @XmlElement public String getVoornaam() { return voornaam; } // @XmlElement // public String getEmailAdres() { // return emailAdres; // } // // public void setEmailAdres(String emailAdres) { // this.emailAdres = emailAdres; // } public void setVoornaam(String voornaam) { this.voornaam = voornaam; } @XmlElement public String getWachtwoord() { return wachtwoord; } // public Integer getBedrijfId() { // return bedrijfId; // } // // public void setBedrijfId(Integer bedrijfId) { // this.bedrijfId =<SUF> // } public void setWachtwoord(String wachtwoord) { this.wachtwoord = wachtwoord; } @XmlElement public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } @XmlElement public String getClientSecret() { return clientSecret; } public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } }
13786_16
package gameapplication.model; import gameapplication.model.chess.Board; import gameapplication.model.chess.piece.Piece; import gameapplication.model.chess.piece.pieces.Pawn; import gameapplication.model.chess.piece.pieces.Piecetype; import gameapplication.model.chess.spot.Spot; import java.util.ArrayList; import java.util.List; /** * The MoveManager class is used to manage the moves of the pieces. It has a list of spots, which are used to store the * last spot clicked. It also has a list of moves, which are used to store the moves made */ /** * Given a string of the form "column.row:column.row", return a list of the two spots * * @param column the column of the spot that was clicked * @param row the row of the piece that was clicked on */ public class MoveManager { // This is creating a list of spots, which is used to store the last spot clicked. private List<Spot> spots = new ArrayList<>(); // This is creating a list of strings, which is used to store the moves made. private List<String> movesList; // Creating a reference to the board. private Board board; // This is creating a new MoveManager object, and initializing the board and movesList. public MoveManager(Board board) { this.board = board; movesList = new ArrayList<>(); } /** * If the first spot in the spots list is empty, add the current spot to the spots list. If the first spot in the spots * list is not empty, check if the current spot is a valid move for the piece in the first spot. If the current spot is * a valid move, add the current spot to the spots list. If the current spot is not a valid move, clear the spots list * * @param column the column of the spot that was clicked * @param row the row of the piece that was clicked on */ public void addMove(int column, int row) { // Getting the piece from the spot that was clicked on. Piece clickedOnPiece = board.getPieceFromSpot(column, row); // This is checking if the spots list is empty. If it is empty, it means that the first spot has not been clicked // yet. if (spots.isEmpty()) { // Kijk of er op niks geklicked werd, zoja doe niks if (clickedOnPiece == null) return; // als er op een andere piece gecklicked werd, doe ook niks. if (clickedOnPiece.getPieceColor() != board.getLastTurnColor()) return; // This is adding the spot that was clicked on to the spots list. spots.add(new Spot(column, row)); return; } // The above code is checking if the piece that was clicked on is the same color as the last piece that was moved. // If it is the same color, it will remove the first spot from the list of spots. If it is not the same color, it // will add the spot to the list of spots. if (spots.size() == 1) { Spot firstSpot = spots.get(0); Piece pieceFromSpot = board.getPieceFromSpot(firstSpot.getColumn(), firstSpot.getRow()); Piece currentPiece = board.getPieceFromSpot(column, row); if (board.getPieceFromSpot(column, row) != null && board.getPieceFromSpot(column, row).getPieceType() == Piecetype.KING) { return; } //Als huidige geklickde piece heeft dezelfde kleur als de vorige piece, if (currentPiece != null && currentPiece.getPieceColor() == board.getLastTurnColor()) { // verwijder de vorige spot, spots.remove(0); //en maak een recursieve oproep naar de addMove methode addMove(column, row); } else { //Als move niet mogelijk is try { if (!pieceFromSpot.moveTo(new Spot(column, row))) { spots.clear(); return; } } catch (NullPointerException npe) { pieceFromSpot.setBoard(getBoard()); if (!pieceFromSpot.moveTo(new Spot(column, row))) { spots.clear(); return; } } //^De else betekent dat er op een andere Spot met of zonder Piece geklicked werd. //Nu bekijken we als de 2de spot van de lijst, 1 van de valid moves van de eerste piece is. for (Spot[] validMove : pieceFromSpot.validMoves(board)) { for (Spot spot : validMove) { if (spot != null && spot.getColumn() == column && spot.getRow() == row) { //zoja, add de 2de spot naar de lijst, en roep de make move methode op. //Check if next move will cause check, or disable the check. if (testMove(new Spot(column, row), null)) { return; } //if not in a checked state, or testMove return true spots.add(new Spot(column, row)); //prepare next turn makeMove(); } } } } } } //move the piece and prepare next turn /** * This function moves a piece from one spot to another */ public void makeMove() { Piece piece = board.getPieceFromSpot(spots.get(0).getColumn(), spots.get(0).getRow()); // Actually move the piece piece.moveToSpot(board, spots.get(1)); // This is checking if the piece is a pawn. If it is, it will check if it is promotable. if (piece.getPieceType() == Piecetype.PAWN) { Pawn pawn = (Pawn) piece; pawn.checkIfPromotionAvailable(); } // This is clearing the list of spots, and switching the player. addMoveToList(); spots.clear(); board.switchPlayer(); // Checking if the current player is in check. If it is, it will check if the player is in checkmate. board.checkForCheck(); // Switching the player. board.nextTurn(); } //Method to check if the next move during check, will evade the check /** * This function checks if the move is valid by checking if the king is in check after the move * * @param secondSpot the spot where the piece is moving to * @param firstSpot the spot where the piece is currently located * @return A boolean value. */ public boolean testMove(Spot secondSpot, Spot firstSpot) { //second parameter to check for checkmate, only available if called from the board Spot newFirstSpot = firstSpot != null ? firstSpot : spots.get(0); //create a reference to the old board Board tempBoard = board; //create a copy of the old piece, in case there is one on the second spot Piece oldPiece = tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()]; // get the piece from the first spot Piece piece = board.getPieceFromSpot(newFirstSpot.getColumn(), newFirstSpot.getRow()); //if there was a piece on the second spot, remove it if (oldPiece != null) { tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null; } // remove the piece from the first spot tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = null; // set the piece from the first spot in the second spot tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = piece; //check if after doing this, the check is still there if (board.getKing(board.getCurrentPlayer().getColor()).isCheck(tempBoard)) { //if yes, put everything back in place tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null; tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece; if (oldPiece != null) { tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece; } return true; } //if not, also put everything back in place tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null; tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece; if (oldPiece != null) { tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece; } return false; } /** * Add the move to the list of moves */ public void addMoveToList() { movesList.add(String.format("%s:%s", spots.get(0).getLocationSpotName(), spots.get(1).getLocationSpotName())); } /** * Given a string of the form "column.row:column.row", return a list of the two spots * * @param spotString a string that represents a list of spots. * @return A list of spots. */ public List<Spot> getSpotFromString(String spotString) { String[] twoSpots = spotString.split(":"); List<Spot> spot = new ArrayList<>(); if (twoSpots.length == 0) { return null; } for (String singleSpot : twoSpots) { String[] columnAndRow = singleSpot.split("\\."); try { spot.add(new Spot(Integer.parseInt(columnAndRow[0]), Integer.parseInt(columnAndRow[1]))); } catch (Exception e) { return null; } } return spot; } /** * Returns the board * * @return The board object. */ public Board getBoard() { return board; } public List<String> getMovesList() { return movesList; } public List<Spot> getMoves() { return spots; } }
0xBienCuit/ChessGame
src/gameapplication/model/MoveManager.java
2,449
// verwijder de vorige spot,
line_comment
nl
package gameapplication.model; import gameapplication.model.chess.Board; import gameapplication.model.chess.piece.Piece; import gameapplication.model.chess.piece.pieces.Pawn; import gameapplication.model.chess.piece.pieces.Piecetype; import gameapplication.model.chess.spot.Spot; import java.util.ArrayList; import java.util.List; /** * The MoveManager class is used to manage the moves of the pieces. It has a list of spots, which are used to store the * last spot clicked. It also has a list of moves, which are used to store the moves made */ /** * Given a string of the form "column.row:column.row", return a list of the two spots * * @param column the column of the spot that was clicked * @param row the row of the piece that was clicked on */ public class MoveManager { // This is creating a list of spots, which is used to store the last spot clicked. private List<Spot> spots = new ArrayList<>(); // This is creating a list of strings, which is used to store the moves made. private List<String> movesList; // Creating a reference to the board. private Board board; // This is creating a new MoveManager object, and initializing the board and movesList. public MoveManager(Board board) { this.board = board; movesList = new ArrayList<>(); } /** * If the first spot in the spots list is empty, add the current spot to the spots list. If the first spot in the spots * list is not empty, check if the current spot is a valid move for the piece in the first spot. If the current spot is * a valid move, add the current spot to the spots list. If the current spot is not a valid move, clear the spots list * * @param column the column of the spot that was clicked * @param row the row of the piece that was clicked on */ public void addMove(int column, int row) { // Getting the piece from the spot that was clicked on. Piece clickedOnPiece = board.getPieceFromSpot(column, row); // This is checking if the spots list is empty. If it is empty, it means that the first spot has not been clicked // yet. if (spots.isEmpty()) { // Kijk of er op niks geklicked werd, zoja doe niks if (clickedOnPiece == null) return; // als er op een andere piece gecklicked werd, doe ook niks. if (clickedOnPiece.getPieceColor() != board.getLastTurnColor()) return; // This is adding the spot that was clicked on to the spots list. spots.add(new Spot(column, row)); return; } // The above code is checking if the piece that was clicked on is the same color as the last piece that was moved. // If it is the same color, it will remove the first spot from the list of spots. If it is not the same color, it // will add the spot to the list of spots. if (spots.size() == 1) { Spot firstSpot = spots.get(0); Piece pieceFromSpot = board.getPieceFromSpot(firstSpot.getColumn(), firstSpot.getRow()); Piece currentPiece = board.getPieceFromSpot(column, row); if (board.getPieceFromSpot(column, row) != null && board.getPieceFromSpot(column, row).getPieceType() == Piecetype.KING) { return; } //Als huidige geklickde piece heeft dezelfde kleur als de vorige piece, if (currentPiece != null && currentPiece.getPieceColor() == board.getLastTurnColor()) { // verwijder de<SUF> spots.remove(0); //en maak een recursieve oproep naar de addMove methode addMove(column, row); } else { //Als move niet mogelijk is try { if (!pieceFromSpot.moveTo(new Spot(column, row))) { spots.clear(); return; } } catch (NullPointerException npe) { pieceFromSpot.setBoard(getBoard()); if (!pieceFromSpot.moveTo(new Spot(column, row))) { spots.clear(); return; } } //^De else betekent dat er op een andere Spot met of zonder Piece geklicked werd. //Nu bekijken we als de 2de spot van de lijst, 1 van de valid moves van de eerste piece is. for (Spot[] validMove : pieceFromSpot.validMoves(board)) { for (Spot spot : validMove) { if (spot != null && spot.getColumn() == column && spot.getRow() == row) { //zoja, add de 2de spot naar de lijst, en roep de make move methode op. //Check if next move will cause check, or disable the check. if (testMove(new Spot(column, row), null)) { return; } //if not in a checked state, or testMove return true spots.add(new Spot(column, row)); //prepare next turn makeMove(); } } } } } } //move the piece and prepare next turn /** * This function moves a piece from one spot to another */ public void makeMove() { Piece piece = board.getPieceFromSpot(spots.get(0).getColumn(), spots.get(0).getRow()); // Actually move the piece piece.moveToSpot(board, spots.get(1)); // This is checking if the piece is a pawn. If it is, it will check if it is promotable. if (piece.getPieceType() == Piecetype.PAWN) { Pawn pawn = (Pawn) piece; pawn.checkIfPromotionAvailable(); } // This is clearing the list of spots, and switching the player. addMoveToList(); spots.clear(); board.switchPlayer(); // Checking if the current player is in check. If it is, it will check if the player is in checkmate. board.checkForCheck(); // Switching the player. board.nextTurn(); } //Method to check if the next move during check, will evade the check /** * This function checks if the move is valid by checking if the king is in check after the move * * @param secondSpot the spot where the piece is moving to * @param firstSpot the spot where the piece is currently located * @return A boolean value. */ public boolean testMove(Spot secondSpot, Spot firstSpot) { //second parameter to check for checkmate, only available if called from the board Spot newFirstSpot = firstSpot != null ? firstSpot : spots.get(0); //create a reference to the old board Board tempBoard = board; //create a copy of the old piece, in case there is one on the second spot Piece oldPiece = tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()]; // get the piece from the first spot Piece piece = board.getPieceFromSpot(newFirstSpot.getColumn(), newFirstSpot.getRow()); //if there was a piece on the second spot, remove it if (oldPiece != null) { tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null; } // remove the piece from the first spot tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = null; // set the piece from the first spot in the second spot tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = piece; //check if after doing this, the check is still there if (board.getKing(board.getCurrentPlayer().getColor()).isCheck(tempBoard)) { //if yes, put everything back in place tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null; tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece; if (oldPiece != null) { tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece; } return true; } //if not, also put everything back in place tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null; tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece; if (oldPiece != null) { tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece; } return false; } /** * Add the move to the list of moves */ public void addMoveToList() { movesList.add(String.format("%s:%s", spots.get(0).getLocationSpotName(), spots.get(1).getLocationSpotName())); } /** * Given a string of the form "column.row:column.row", return a list of the two spots * * @param spotString a string that represents a list of spots. * @return A list of spots. */ public List<Spot> getSpotFromString(String spotString) { String[] twoSpots = spotString.split(":"); List<Spot> spot = new ArrayList<>(); if (twoSpots.length == 0) { return null; } for (String singleSpot : twoSpots) { String[] columnAndRow = singleSpot.split("\\."); try { spot.add(new Spot(Integer.parseInt(columnAndRow[0]), Integer.parseInt(columnAndRow[1]))); } catch (Exception e) { return null; } } return spot; } /** * Returns the board * * @return The board object. */ public Board getBoard() { return board; } public List<String> getMovesList() { return movesList; } public List<Spot> getMoves() { return spots; } }
26232_4
package Jazzclub; import java.time.LocalDate; /** * De verantwoordelijkheid is hier het beheren van Lidmaatschapsinformatie * De sleutel om het terug de vinden is het e-mailadres * Een lidmaatschap is 1 jaar geldig. Daarna is het vervallen. * * REQ0005 - Het is bekend welk lid zich succesvol bekend gemaakt heeft * REQ0016 - Er kan nagegaan worden of het lidmaatschap geldig is op de datum van het geselecteerde concert - P * REQ0017 - De status (geldig of vervallen) van het lidmaatschap op concertdatum is bekend - I,O */ public class Lidmaatschap { private String eMailadres; private LocalDate laatsteDagGeldigheid; /** * Retourneert het e-mailadres * ten behoeve van REQ0005 * @return het e-mailadres */ public String getEMailadres() { return eMailadres; //TODO Juiste code later uit te werken } /** * Checkt of het lidmaatschap voor een gegeven checkdatum geldig is * ten behoeve van REQ0016 en REQ0017 * @param checkdatum de datum waarvoor het lidmaatschap gecheck wordt * @return true als het lidmaatschap nog geldig is, * false als het lidmaatschap vervallen is */ public boolean checkGeldigheid(LocalDate checkdatum) { return false; //TODO Juiste code later uit te werken } }
OdiseeSEF2324/Leerstof-klas-7-8
CodeskeletOplossing/Jazzclub/Lidmaatschap.java
378
//TODO Juiste code later uit te werken
line_comment
nl
package Jazzclub; import java.time.LocalDate; /** * De verantwoordelijkheid is hier het beheren van Lidmaatschapsinformatie * De sleutel om het terug de vinden is het e-mailadres * Een lidmaatschap is 1 jaar geldig. Daarna is het vervallen. * * REQ0005 - Het is bekend welk lid zich succesvol bekend gemaakt heeft * REQ0016 - Er kan nagegaan worden of het lidmaatschap geldig is op de datum van het geselecteerde concert - P * REQ0017 - De status (geldig of vervallen) van het lidmaatschap op concertdatum is bekend - I,O */ public class Lidmaatschap { private String eMailadres; private LocalDate laatsteDagGeldigheid; /** * Retourneert het e-mailadres * ten behoeve van REQ0005 * @return het e-mailadres */ public String getEMailadres() { return eMailadres; //TODO Juiste code later uit te werken } /** * Checkt of het lidmaatschap voor een gegeven checkdatum geldig is * ten behoeve van REQ0016 en REQ0017 * @param checkdatum de datum waarvoor het lidmaatschap gecheck wordt * @return true als het lidmaatschap nog geldig is, * false als het lidmaatschap vervallen is */ public boolean checkGeldigheid(LocalDate checkdatum) { return false; //TODO Juiste<SUF> } }
124027_12
package io.github.deechtezeeuw.kdframework.Rank; import io.github.deechtezeeuw.kdframework.KDFramework; import io.github.deechtezeeuw.kdframework.Land.Land; import io.github.deechtezeeuw.kdframework.Speler.Speler; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.UUID; public class DeleteRank { private KDFramework plugin; private CommandSender sender; private String label; private String[] args; public DeleteRank (KDFramework plugin, CommandSender sender, String label, String[] args) { this.plugin = plugin; this.sender = sender; this.label = label; this.args = args; this.checkArguments(); } private void checkArguments() { if (!(args.length > 2)) { if (sender.hasPermission("k.rank.delete.other")) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cFoutief: &4&l/" + label + " " + args[0] + " "+args[1]+" <rank/kingdom> <rank>")); return; } else { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cFoutief: &4&l/" + label + " " + args[0] + " "+args[1]+" <rank>")); return; } } // Check if user has permission to add ranks to all or only hes land if (sender.hasPermission("k.rank.delete.other") && args.length == 4) { // Check if arg 2 is an kingdom or an new rank if (!plugin.SQLSelect.land_exists(args[2])) { // Not an kingdom sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cWe kunnen de rank &4&l" + args[3] + " &cniet verwijderen, omdat &4&l" + args[2] + " &cgeen kingdom is!")); return; } // Land exists Land land = plugin.SQLSelect.land_get_by_name(args[2]); // Check if rank already exists Boolean found = false; Rank deleteRank = null; for (Rank rank : land.getRanks()) { if (rank.getName().equalsIgnoreCase(args[3])) { found = true; deleteRank = rank; } } if (!found) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[3]+" &cbestaat niet in het land &4&l"+land.getName()+"&c!")); return; } // Check if rank thats going to be deleted is the default rank if (land.get_defaultRank().equals(deleteRank)) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[3]+" &ckan niet worden verwijderd, omdat het de default rank is van &4&l"+land.getName()+"&c!")); return; } // Delete rank in land plugin.SQLDelete.rank_delete(deleteRank); sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&aDe rank &2&l"+args[3]+" &ais verwijderd voor het land &2&l"+land.getName()+"&a!")); return; } else { // user can only add rank to hes own kingdom if (!sender.hasPermission("k.rank.delete")) { plugin.Config.noPermission(sender); return; } // Check if user has all arguments good if (!(args.length == 3)) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cFoutief: &4&l/" + label + " " + args[0] + " "+args[1]+" "+args[2]+" &cen niet meer!")); return; } // Check if user is in an land Player CMDSender = (Player) sender; if (!plugin.SQLSelect.player_exists(CMDSender)) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cIn verband met veiligheids redenen kunnen wij niet toestaan dat u niet bestaat in onze database!")); return; } Speler speler = plugin.SQLSelect.player_get_by_name(CMDSender.getName()); if (speler == null || speler.getLand() == null) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cU kunt alleen een rol verwijderen als u lid bent van een land!")); return; } // Check if role already exists in land Land land = plugin.SQLSelect.land_get_by_player(speler); Boolean found = false; Rank deleteRank = null; for (Rank rank : land.getRanks()) { if (rank.getName().equalsIgnoreCase(args[2])) { found = true; deleteRank = rank; } } if (!found) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[2]+" &cbestaat niet in het land &4&l"+land.getName()+"&c!")); return; } // Check if rank thats going to be deleted is the default rank if (land.get_defaultRank().equals(deleteRank)) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[2]+" &ckan niet worden verwijderd, omdat het de default rank is van &4&l"+land.getName()+"&c!")); return; } // Check if the rank thats going to be deleted is equal or higher then player level Rank spelerRank = plugin.SQLSelect.get_rank(speler.getRank()); if (deleteRank.getLevel() >= spelerRank.getLevel()) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[2]+" &ckan niet worden verwijderd, omdat het level gelijk of hoger is dan die van jouw rank!")); return; } // Delete rank in land plugin.SQLDelete.rank_delete(deleteRank); sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&aDe rank &2&l"+args[2]+" &ais verwijderd voor het land &2&l"+land.getName()+"&a!")); return; } } }
RubenDalebout/KDFramework
src/main/java/io/github/deechtezeeuw/kdframework/Rank/DeleteRank.java
1,717
// Delete rank in land
line_comment
nl
package io.github.deechtezeeuw.kdframework.Rank; import io.github.deechtezeeuw.kdframework.KDFramework; import io.github.deechtezeeuw.kdframework.Land.Land; import io.github.deechtezeeuw.kdframework.Speler.Speler; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.UUID; public class DeleteRank { private KDFramework plugin; private CommandSender sender; private String label; private String[] args; public DeleteRank (KDFramework plugin, CommandSender sender, String label, String[] args) { this.plugin = plugin; this.sender = sender; this.label = label; this.args = args; this.checkArguments(); } private void checkArguments() { if (!(args.length > 2)) { if (sender.hasPermission("k.rank.delete.other")) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cFoutief: &4&l/" + label + " " + args[0] + " "+args[1]+" <rank/kingdom> <rank>")); return; } else { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cFoutief: &4&l/" + label + " " + args[0] + " "+args[1]+" <rank>")); return; } } // Check if user has permission to add ranks to all or only hes land if (sender.hasPermission("k.rank.delete.other") && args.length == 4) { // Check if arg 2 is an kingdom or an new rank if (!plugin.SQLSelect.land_exists(args[2])) { // Not an kingdom sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cWe kunnen de rank &4&l" + args[3] + " &cniet verwijderen, omdat &4&l" + args[2] + " &cgeen kingdom is!")); return; } // Land exists Land land = plugin.SQLSelect.land_get_by_name(args[2]); // Check if rank already exists Boolean found = false; Rank deleteRank = null; for (Rank rank : land.getRanks()) { if (rank.getName().equalsIgnoreCase(args[3])) { found = true; deleteRank = rank; } } if (!found) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[3]+" &cbestaat niet in het land &4&l"+land.getName()+"&c!")); return; } // Check if rank thats going to be deleted is the default rank if (land.get_defaultRank().equals(deleteRank)) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[3]+" &ckan niet worden verwijderd, omdat het de default rank is van &4&l"+land.getName()+"&c!")); return; } // Delete rank in land plugin.SQLDelete.rank_delete(deleteRank); sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&aDe rank &2&l"+args[3]+" &ais verwijderd voor het land &2&l"+land.getName()+"&a!")); return; } else { // user can only add rank to hes own kingdom if (!sender.hasPermission("k.rank.delete")) { plugin.Config.noPermission(sender); return; } // Check if user has all arguments good if (!(args.length == 3)) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cFoutief: &4&l/" + label + " " + args[0] + " "+args[1]+" "+args[2]+" &cen niet meer!")); return; } // Check if user is in an land Player CMDSender = (Player) sender; if (!plugin.SQLSelect.player_exists(CMDSender)) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cIn verband met veiligheids redenen kunnen wij niet toestaan dat u niet bestaat in onze database!")); return; } Speler speler = plugin.SQLSelect.player_get_by_name(CMDSender.getName()); if (speler == null || speler.getLand() == null) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cU kunt alleen een rol verwijderen als u lid bent van een land!")); return; } // Check if role already exists in land Land land = plugin.SQLSelect.land_get_by_player(speler); Boolean found = false; Rank deleteRank = null; for (Rank rank : land.getRanks()) { if (rank.getName().equalsIgnoreCase(args[2])) { found = true; deleteRank = rank; } } if (!found) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[2]+" &cbestaat niet in het land &4&l"+land.getName()+"&c!")); return; } // Check if rank thats going to be deleted is the default rank if (land.get_defaultRank().equals(deleteRank)) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[2]+" &ckan niet worden verwijderd, omdat het de default rank is van &4&l"+land.getName()+"&c!")); return; } // Check if the rank thats going to be deleted is equal or higher then player level Rank spelerRank = plugin.SQLSelect.get_rank(speler.getRank()); if (deleteRank.getLevel() >= spelerRank.getLevel()) { sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&cDe rank &4&l"+args[2]+" &ckan niet worden verwijderd, omdat het level gelijk of hoger is dan die van jouw rank!")); return; } // Delete rank<SUF> plugin.SQLDelete.rank_delete(deleteRank); sender.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.Config.getGeneralPrefix() + "&aDe rank &2&l"+args[2]+" &ais verwijderd voor het land &2&l"+land.getName()+"&a!")); return; } } }
132209_24
/** * Copyright 2014 Internet2 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author mchyzer * $Id: ChangeLogTypeBuiltin.java,v 1.9 2009-10-31 17:46:47 shilen Exp $ */ package edu.internet2.middleware.grouper.changeLog; import java.util.HashMap; import java.util.Map; import edu.internet2.middleware.grouperClient.collections.MultiKey; /** * */ public enum ChangeLogTypeBuiltin implements ChangeLogTypeIdentifier { /** * add group field */ GROUP_FIELD_ADD(new ChangeLogType("groupField", "addGroupField", ChangeLogLabels.GROUP_FIELD_ADD.id, ChangeLogLabels.GROUP_FIELD_ADD.name, ChangeLogLabels.GROUP_FIELD_ADD.groupTypeId, ChangeLogLabels.GROUP_FIELD_ADD.groupTypeName, ChangeLogLabels.GROUP_FIELD_ADD.type)), /** * update group field */ GROUP_FIELD_UPDATE(new ChangeLogType("groupField", "updateGroupField", ChangeLogLabels.GROUP_FIELD_UPDATE.id, ChangeLogLabels.GROUP_FIELD_UPDATE.name, ChangeLogLabels.GROUP_FIELD_UPDATE.groupTypeId, ChangeLogLabels.GROUP_FIELD_UPDATE.groupTypeName, ChangeLogLabels.GROUP_FIELD_UPDATE.type, ChangeLogLabels.GROUP_FIELD_UPDATE.propertyChanged, ChangeLogLabels.GROUP_FIELD_UPDATE.propertyOldValue, ChangeLogLabels.GROUP_FIELD_UPDATE.propertyNewValue)), /** * delete group field */ GROUP_FIELD_DELETE(new ChangeLogType("groupField", "deleteGroupField", ChangeLogLabels.GROUP_FIELD_DELETE.id, ChangeLogLabels.GROUP_FIELD_DELETE.name, ChangeLogLabels.GROUP_FIELD_DELETE.groupTypeId, ChangeLogLabels.GROUP_FIELD_DELETE.groupTypeName, ChangeLogLabels.GROUP_FIELD_DELETE.type)), /** * add group composite */ GROUP_COMPOSITE_ADD(new ChangeLogType("groupComposite", "addGroupComposite", "id", "ownerId", "ownerName", "leftFactorId", "leftFactorName", "rightFactorId", "rightFactorName", "type")), /** * update group composite */ GROUP_COMPOSITE_UPDATE(new ChangeLogType("groupComposite", "updateGroupComposite", "id", "ownerId", "ownerName", "leftFactorId", "leftFactorName", "rightFactorId", "rightFactorName", "type")), /** * delete group composite */ GROUP_COMPOSITE_DELETE(new ChangeLogType("groupComposite", "deleteGroupComposite", "id", "ownerId", "ownerName", "leftFactorId", "leftFactorName", "rightFactorId", "rightFactorName", "type")), /** * assign group type */ GROUP_TYPE_ASSIGN(new ChangeLogType("groupTypeAssignment", "assignGroupType", ChangeLogLabels.GROUP_TYPE_ASSIGN.id, ChangeLogLabels.GROUP_TYPE_ASSIGN.groupId, ChangeLogLabels.GROUP_TYPE_ASSIGN.groupName, ChangeLogLabels.GROUP_TYPE_ASSIGN.typeId, ChangeLogLabels.GROUP_TYPE_ASSIGN.typeName)), /** * unassign group type */ GROUP_TYPE_UNASSIGN(new ChangeLogType("groupTypeAssignment", "unassignGroupType", ChangeLogLabels.GROUP_TYPE_UNASSIGN.id, ChangeLogLabels.GROUP_TYPE_UNASSIGN.groupId, ChangeLogLabels.GROUP_TYPE_UNASSIGN.groupName, ChangeLogLabels.GROUP_TYPE_UNASSIGN.typeId, ChangeLogLabels.GROUP_TYPE_UNASSIGN.typeName)), /** * add membership */ MEMBERSHIP_ADD(new ChangeLogType("membership", "addMembership", ChangeLogLabels.MEMBERSHIP_ADD.id, ChangeLogLabels.MEMBERSHIP_ADD.fieldName, ChangeLogLabels.MEMBERSHIP_ADD.subjectId, ChangeLogLabels.MEMBERSHIP_ADD.sourceId, ChangeLogLabels.MEMBERSHIP_ADD.membershipType, ChangeLogLabels.MEMBERSHIP_ADD.groupId, ChangeLogLabels.MEMBERSHIP_ADD.groupName, ChangeLogLabels.MEMBERSHIP_ADD.memberId, ChangeLogLabels.MEMBERSHIP_ADD.fieldId, ChangeLogLabels.MEMBERSHIP_ADD.subjectIdentifier0)), /** * update membership */ MEMBERSHIP_UPDATE(new ChangeLogType("membership", "updateMembership", ChangeLogLabels.MEMBERSHIP_UPDATE.id, ChangeLogLabels.MEMBERSHIP_UPDATE.fieldName, ChangeLogLabels.MEMBERSHIP_UPDATE.subjectId, ChangeLogLabels.MEMBERSHIP_UPDATE.sourceId, ChangeLogLabels.MEMBERSHIP_UPDATE.membershipType, ChangeLogLabels.MEMBERSHIP_UPDATE.groupId, ChangeLogLabels.MEMBERSHIP_UPDATE.groupName, ChangeLogLabels.MEMBERSHIP_UPDATE.propertyChanged, ChangeLogLabels.MEMBERSHIP_UPDATE.propertyOldValue, ChangeLogLabels.MEMBERSHIP_UPDATE.propertyNewValue, ChangeLogLabels.MEMBERSHIP_UPDATE.memberId, ChangeLogLabels.MEMBERSHIP_UPDATE.fieldId)), /** * delete membership */ MEMBERSHIP_DELETE(new ChangeLogType("membership", "deleteMembership", ChangeLogLabels.MEMBERSHIP_DELETE.id, ChangeLogLabels.MEMBERSHIP_DELETE.fieldName, ChangeLogLabels.MEMBERSHIP_DELETE.subjectId, ChangeLogLabels.MEMBERSHIP_DELETE.sourceId, ChangeLogLabels.MEMBERSHIP_DELETE.membershipType, ChangeLogLabels.MEMBERSHIP_DELETE.groupId, ChangeLogLabels.MEMBERSHIP_DELETE.groupName, ChangeLogLabels.MEMBERSHIP_DELETE.memberId, ChangeLogLabels.MEMBERSHIP_DELETE.fieldId, ChangeLogLabels.MEMBERSHIP_DELETE.subjectName, ChangeLogLabels.MEMBERSHIP_DELETE.subjectIdentifier0)), /** * add privilege */ PRIVILEGE_ADD(new ChangeLogType("privilege", "addPrivilege", ChangeLogLabels.PRIVILEGE_ADD.id, ChangeLogLabels.PRIVILEGE_ADD.privilegeName, ChangeLogLabels.PRIVILEGE_ADD.subjectId, ChangeLogLabels.PRIVILEGE_ADD.sourceId, ChangeLogLabels.PRIVILEGE_ADD.privilegeType, ChangeLogLabels.PRIVILEGE_ADD.ownerType, ChangeLogLabels.PRIVILEGE_ADD.ownerId, ChangeLogLabels.PRIVILEGE_ADD.ownerName, ChangeLogLabels.PRIVILEGE_ADD.memberId, ChangeLogLabels.PRIVILEGE_ADD.fieldId, ChangeLogLabels.PRIVILEGE_ADD.membershipType)), /** * update privilege */ PRIVILEGE_UPDATE(new ChangeLogType("privilege", "updatePrivilege", ChangeLogLabels.PRIVILEGE_UPDATE.id, ChangeLogLabels.PRIVILEGE_UPDATE.privilegeName, ChangeLogLabels.PRIVILEGE_UPDATE.subjectId, ChangeLogLabels.PRIVILEGE_UPDATE.sourceId, ChangeLogLabels.PRIVILEGE_UPDATE.privilegeType, ChangeLogLabels.PRIVILEGE_UPDATE.ownerType, ChangeLogLabels.PRIVILEGE_UPDATE.ownerId, ChangeLogLabels.PRIVILEGE_UPDATE.ownerName, ChangeLogLabels.PRIVILEGE_UPDATE.membershipType)), /** * delete privilege */ PRIVILEGE_DELETE(new ChangeLogType("privilege", "deletePrivilege", ChangeLogLabels.PRIVILEGE_DELETE.id, ChangeLogLabels.PRIVILEGE_DELETE.privilegeName, ChangeLogLabels.PRIVILEGE_DELETE.subjectId, ChangeLogLabels.PRIVILEGE_DELETE.sourceId, ChangeLogLabels.PRIVILEGE_DELETE.privilegeType, ChangeLogLabels.PRIVILEGE_DELETE.ownerType, ChangeLogLabels.PRIVILEGE_DELETE.ownerId, ChangeLogLabels.PRIVILEGE_DELETE.ownerName, ChangeLogLabels.PRIVILEGE_DELETE.memberId, ChangeLogLabels.PRIVILEGE_DELETE.fieldId, ChangeLogLabels.PRIVILEGE_DELETE.membershipType)), /** * add group */ GROUP_ADD(new ChangeLogType("group", "addGroup", ChangeLogLabels.GROUP_ADD.id, ChangeLogLabels.GROUP_ADD.name, ChangeLogLabels.GROUP_ADD.parentStemId, ChangeLogLabels.GROUP_ADD.displayName, ChangeLogLabels.GROUP_ADD.description, ChangeLogLabels.GROUP_ADD.idIndex)), /** * update group */ GROUP_UPDATE(new ChangeLogType("group", "updateGroup", ChangeLogLabels.GROUP_UPDATE.id, ChangeLogLabels.GROUP_UPDATE.name, ChangeLogLabels.GROUP_UPDATE.parentStemId, ChangeLogLabels.GROUP_UPDATE.displayName, ChangeLogLabels.GROUP_UPDATE.description, ChangeLogLabels.GROUP_UPDATE.propertyChanged, ChangeLogLabels.GROUP_UPDATE.propertyOldValue, ChangeLogLabels.GROUP_UPDATE.propertyNewValue)), /** * delete group */ GROUP_DELETE(new ChangeLogType("group", "deleteGroup", ChangeLogLabels.GROUP_DELETE.id, ChangeLogLabels.GROUP_DELETE.name, ChangeLogLabels.GROUP_DELETE.parentStemId, ChangeLogLabels.GROUP_DELETE.displayName, ChangeLogLabels.GROUP_DELETE.description, ChangeLogLabels.GROUP_DELETE.idIndex)), /** * enable group */ GROUP_ENABLE(new ChangeLogType("group", "enableGroup", ChangeLogLabels.GROUP_ENABLE.id, ChangeLogLabels.GROUP_ENABLE.name, ChangeLogLabels.GROUP_ENABLE.parentStemId, ChangeLogLabels.GROUP_ENABLE.displayName, ChangeLogLabels.GROUP_ENABLE.description, ChangeLogLabels.GROUP_ENABLE.idIndex)), /** * disable group */ GROUP_DISABLE(new ChangeLogType("group", "disableGroup", ChangeLogLabels.GROUP_DISABLE.id, ChangeLogLabels.GROUP_DISABLE.name, ChangeLogLabels.GROUP_DISABLE.parentStemId, ChangeLogLabels.GROUP_DISABLE.displayName, ChangeLogLabels.GROUP_DISABLE.description, ChangeLogLabels.GROUP_DISABLE.idIndex)), /** * add entity */ ENTITY_ADD(new ChangeLogType("entity", "addEntity", ChangeLogLabels.ENTITY_ADD.id, ChangeLogLabels.ENTITY_ADD.name, ChangeLogLabels.ENTITY_ADD.parentStemId, ChangeLogLabels.ENTITY_ADD.displayName, ChangeLogLabels.ENTITY_ADD.description)), /** * enable entity */ ENTITY_ENABLE(new ChangeLogType("entity", "enableEntity", ChangeLogLabels.ENTITY_ENABLE.id, ChangeLogLabels.ENTITY_ENABLE.name, ChangeLogLabels.ENTITY_ENABLE.parentStemId, ChangeLogLabels.ENTITY_ENABLE.displayName, ChangeLogLabels.ENTITY_ENABLE.description)), /** * update entity */ ENTITY_UPDATE(new ChangeLogType("entity", "updateEntity", ChangeLogLabels.ENTITY_UPDATE.id, ChangeLogLabels.ENTITY_UPDATE.name, ChangeLogLabels.ENTITY_UPDATE.parentStemId, ChangeLogLabels.ENTITY_UPDATE.displayName, ChangeLogLabels.ENTITY_UPDATE.description, ChangeLogLabels.ENTITY_UPDATE.propertyChanged, ChangeLogLabels.ENTITY_UPDATE.propertyOldValue, ChangeLogLabels.ENTITY_UPDATE.propertyNewValue)), /** * delete entity */ ENTITY_DELETE(new ChangeLogType("entity", "deleteEntity", ChangeLogLabels.ENTITY_DELETE.id, ChangeLogLabels.ENTITY_DELETE.name, ChangeLogLabels.ENTITY_DELETE.parentStemId, ChangeLogLabels.ENTITY_DELETE.displayName, ChangeLogLabels.ENTITY_DELETE.description)), /** * disable entity */ ENTITY_DISABLE(new ChangeLogType("entity", "disableEntity", ChangeLogLabels.ENTITY_DISABLE.id, ChangeLogLabels.ENTITY_DISABLE.name, ChangeLogLabels.ENTITY_DISABLE.parentStemId, ChangeLogLabels.ENTITY_DISABLE.displayName, ChangeLogLabels.ENTITY_DISABLE.description)), /** * attribute def add */ ATTRIBUTE_DEF_ADD(new ChangeLogType("attributeDef", "addAttributeDef", ChangeLogLabels.ATTRIBUTE_DEF_ADD.id, ChangeLogLabels.ATTRIBUTE_DEF_ADD.name, ChangeLogLabels.ATTRIBUTE_DEF_ADD.stemId, ChangeLogLabels.ATTRIBUTE_DEF_ADD.description, ChangeLogLabels.ATTRIBUTE_DEF_ADD.attributeDefType)), /** * attribute def update */ ATTRIBUTE_DEF_UPDATE(new ChangeLogType("attributeDef", "updateAttributeDef", ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.id, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.name, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.stemId, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.description, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.attributeDefType, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.propertyChanged, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.propertyOldValue, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.propertyNewValue)), /** * attribute def delete */ ATTRIBUTE_DEF_DELETE(new ChangeLogType("attributeDef", "deleteAttributeDef", ChangeLogLabels.ATTRIBUTE_DEF_DELETE.id, ChangeLogLabels.ATTRIBUTE_DEF_DELETE.name, ChangeLogLabels.ATTRIBUTE_DEF_DELETE.stemId, ChangeLogLabels.ATTRIBUTE_DEF_DELETE.description, ChangeLogLabels.ATTRIBUTE_DEF_DELETE.attributeDefType)), /** * stem add */ STEM_ADD(new ChangeLogType("stem", "addStem", ChangeLogLabels.STEM_ADD.id, ChangeLogLabels.STEM_ADD.name, ChangeLogLabels.STEM_ADD.parentStemId, ChangeLogLabels.STEM_ADD.displayName, ChangeLogLabels.STEM_ADD.description)), /** * stem update */ STEM_UPDATE(new ChangeLogType("stem", "updateStem", ChangeLogLabels.STEM_UPDATE.id, ChangeLogLabels.STEM_UPDATE.name, ChangeLogLabels.STEM_UPDATE.parentStemId, ChangeLogLabels.STEM_UPDATE.displayName, ChangeLogLabels.STEM_UPDATE.description, ChangeLogLabels.STEM_UPDATE.propertyChanged, ChangeLogLabels.STEM_UPDATE.propertyOldValue, ChangeLogLabels.STEM_UPDATE.propertyNewValue)), /** * stem delete */ STEM_DELETE(new ChangeLogType("stem", "deleteStem", ChangeLogLabels.STEM_DELETE.id, ChangeLogLabels.STEM_DELETE.name, ChangeLogLabels.STEM_DELETE.parentStemId, ChangeLogLabels.STEM_DELETE.displayName, ChangeLogLabels.STEM_DELETE.description)), /** * member add */ MEMBER_ADD(new ChangeLogType("member", "addMember", ChangeLogLabels.MEMBER_ADD.id, ChangeLogLabels.MEMBER_ADD.subjectId, ChangeLogLabels.MEMBER_ADD.subjectSourceId, ChangeLogLabels.MEMBER_ADD.subjectTypeId, ChangeLogLabels.MEMBER_ADD.subjectIdentifier0)), /** * member add */ MEMBER_UPDATE(new ChangeLogType("member", "updateMember", ChangeLogLabels.MEMBER_UPDATE.id, ChangeLogLabels.MEMBER_UPDATE.subjectId, ChangeLogLabels.MEMBER_UPDATE.subjectSourceId, ChangeLogLabels.MEMBER_UPDATE.subjectTypeId, ChangeLogLabels.MEMBER_UPDATE.subjectIdentifier0, ChangeLogLabels.MEMBER_UPDATE.propertyChanged, ChangeLogLabels.MEMBER_UPDATE.propertyOldValue, ChangeLogLabels.MEMBER_UPDATE.propertyNewValue)), /** * member add */ MEMBER_DELETE(new ChangeLogType("member", "deleteMember", ChangeLogLabels.MEMBER_DELETE.id, ChangeLogLabels.MEMBER_DELETE.subjectId, ChangeLogLabels.MEMBER_DELETE.subjectSourceId, ChangeLogLabels.MEMBER_DELETE.subjectTypeId, ChangeLogLabels.MEMBER_DELETE.subjectIdentifier0)), /** * member change subject */ MEMBER_CHANGE_SUBJECT(new ChangeLogType("member", "changeSubject", "oldMemberId", "oldSubjectId", "oldSourceId", "newMemberId", "newSubjectId", "newSourceId", "deleteOldMember", "memberIdChanged")), /** * attribute assign action add */ ATTRIBUTE_ASSIGN_ACTION_ADD(new ChangeLogType("attributeAssignAction", "addAttributeAssignAction", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_ADD.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_ADD.name, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_ADD.attributeDefId)), /** * attribute assign action update */ ATTRIBUTE_ASSIGN_ACTION_UPDATE(new ChangeLogType("attributeAssignAction", "updateAttributeAssignAction", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.name, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.attributeDefId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.propertyChanged, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.propertyOldValue, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.propertyNewValue)), /** * attribute assign action delete */ ATTRIBUTE_ASSIGN_ACTION_DELETE(new ChangeLogType("attributeAssignAction", "deleteAttributeAssignAction", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_DELETE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_DELETE.name, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_DELETE.attributeDefId)), /** * attribute assign action set add */ ATTRIBUTE_ASSIGN_ACTION_SET_ADD(new ChangeLogType("attributeAssignActionSet", "addAttributeAssignActionSet", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.type, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.ifHasAttrAssnActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.thenHasAttrAssnActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.parentAttrAssignActionSetId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.depth)), /** * attribute assign action set delete */ ATTRIBUTE_ASSIGN_ACTION_SET_DELETE(new ChangeLogType("attributeAssignActionSet", "deleteAttributeAssignActionSet", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.type, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.ifHasAttrAssnActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.thenHasAttrAssnActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.parentAttrAssignActionSetId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.depth)), /** * attribute def name set add */ ATTRIBUTE_DEF_NAME_SET_ADD(new ChangeLogType("attributeDefNameSet", "addAttributeDefNameSet", ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.type, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.ifHasAttributeDefNameId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.thenHasAttributeDefNameId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.parentAttrDefNameSetId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.depth)), /** * attribute def name set delete */ ATTRIBUTE_DEF_NAME_SET_DELETE(new ChangeLogType("attributeDefNameSet", "deleteAttributeDefNameSet", ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.type, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.ifHasAttributeDefNameId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.thenHasAttributeDefNameId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.parentAttrDefNameSetId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.depth)), /** * role set add */ ROLE_SET_ADD(new ChangeLogType("roleSet", "addRoleSet", ChangeLogLabels.ROLE_SET_ADD.id, ChangeLogLabels.ROLE_SET_ADD.type, ChangeLogLabels.ROLE_SET_ADD.ifHasRoleId, ChangeLogLabels.ROLE_SET_ADD.thenHasRoleId, ChangeLogLabels.ROLE_SET_ADD.parentRoleSetId, ChangeLogLabels.ROLE_SET_ADD.depth)), /** * role set delete */ ROLE_SET_DELETE(new ChangeLogType("roleSet", "deleteRoleSet", ChangeLogLabels.ROLE_SET_DELETE.id, ChangeLogLabels.ROLE_SET_DELETE.type, ChangeLogLabels.ROLE_SET_DELETE.ifHasRoleId, ChangeLogLabels.ROLE_SET_DELETE.thenHasRoleId, ChangeLogLabels.ROLE_SET_DELETE.parentRoleSetId, ChangeLogLabels.ROLE_SET_DELETE.depth)), /** * attribute def name add */ ATTRIBUTE_DEF_NAME_ADD(new ChangeLogType("attributeDefName", "addAttributeDefName", ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.attributeDefId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.name, ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.stemId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.description)), /** * attribute def name update */ ATTRIBUTE_DEF_NAME_UPDATE(new ChangeLogType("attributeDefName", "updateAttributeDefName", ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.attributeDefId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.name, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.stemId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.description, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.propertyChanged, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.propertyOldValue, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.propertyNewValue)), /** * attribute def name delete */ ATTRIBUTE_DEF_NAME_DELETE(new ChangeLogType("attributeDefName", "deleteAttributeDefName", ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.attributeDefId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.name, ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.stemId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.description)), /** * attribute assign add */ ATTRIBUTE_ASSIGN_ADD(new ChangeLogType("attributeAssign", "addAttributeAssign", ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.attributeDefNameId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.attributeAssignActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.assignType, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.ownerId1, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.ownerId2, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.attributeDefNameName, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.action, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.disallowed)), /** * attribute assign delete */ ATTRIBUTE_ASSIGN_DELETE(new ChangeLogType("attributeAssign", "deleteAttributeAssign", ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.attributeDefNameId, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.attributeAssignActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.assignType, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.ownerId1, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.ownerId2, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.attributeDefNameName, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.action, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.disallowed)), /** * attribute assign value add */ ATTRIBUTE_ASSIGN_VALUE_ADD(new ChangeLogType("attributeAssignValue", "addAttributeAssignValue", ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.attributeAssignId, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.attributeDefNameId, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.attributeDefNameName, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.value, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.valueType)), /** * attribute assign value delete */ ATTRIBUTE_ASSIGN_VALUE_DELETE(new ChangeLogType("attributeAssignValue", "deleteAttributeAssignValue", ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.attributeAssignId, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.attributeDefNameId, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.attributeDefNameName, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.value, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.valueType)), /** * permission change on role */ PERMISSION_CHANGE_ON_ROLE(new ChangeLogType("permission", "permissionChangeOnRole", ChangeLogLabels.PERMISSION_CHANGE_ON_ROLE.roleId, ChangeLogLabels.PERMISSION_CHANGE_ON_ROLE.roleName)), /** * permission change on subject */ PERMISSION_CHANGE_ON_SUBJECT(new ChangeLogType("permission", "permissionChangeOnSubject", ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.subjectId, ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.subjectSourceId, ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.memberId, ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.roleId, ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.roleName)); /** * lookup change log type by category and action */ private static Map<MultiKey, ChangeLogTypeBuiltin> categoryAndActionLookup = null; /** * lookup a change log type by category and action * @param category * @param action * @return the builtin type */ public static ChangeLogTypeBuiltin retrieveChangeLogTypeByChangeLogEntry(ChangeLogEntry changeLogEntry) { ChangeLogType changeLogType = changeLogEntry.getChangeLogType(); if (changeLogType == null) { return null; } return retrieveChangeLogTypeByCategoryAndAction(changeLogType.getChangeLogCategory(), changeLogType.getActionName()); } /** * lookup a change log type by category and action * @param category * @param action * @return the builtin type */ public static ChangeLogTypeBuiltin retrieveChangeLogTypeByCategoryAndAction(String category, String action) { if (categoryAndActionLookup == null) { Map<MultiKey, ChangeLogTypeBuiltin> theCategoryAndActionLookup = new HashMap<MultiKey, ChangeLogTypeBuiltin>(); for (ChangeLogTypeBuiltin changeLogTypeBuiltin : ChangeLogTypeBuiltin.values()) { MultiKey multiKey = new MultiKey(changeLogTypeBuiltin.getChangeLogCategory(), changeLogTypeBuiltin.getActionName()); theCategoryAndActionLookup.put(multiKey, changeLogTypeBuiltin); } categoryAndActionLookup = theCategoryAndActionLookup; } return categoryAndActionLookup.get(new MultiKey(category, action)); } /** * defaults for changelog type, though doesn't hold the id */ private ChangeLogType internalChangeLogTypeDefault; /** * construct * @param theInternalChangeLogTypeDefault */ private ChangeLogTypeBuiltin(ChangeLogType theInternalChangeLogTypeDefault) { this.internalChangeLogTypeDefault = theInternalChangeLogTypeDefault; } /** * get the changelog type from the enum * @return the changelog type */ public ChangeLogType getChangeLogType() { return ChangeLogTypeFinder.find(this.internalChangeLogTypeDefault.getChangeLogCategory(), this.internalChangeLogTypeDefault.getActionName(), true); } /** * get the defaults, but not the id * @return the defaults */ public ChangeLogType internal_changeLogTypeDefault() { return this.internalChangeLogTypeDefault; } /** * * @see edu.internet2.middleware.grouper.changeLog.ChangeLogTypeIdentifier#getChangeLogCategory() */ public String getChangeLogCategory() { return this.getChangeLogType().getChangeLogCategory(); } /** * * @see edu.internet2.middleware.grouper.changeLog.ChangeLogTypeIdentifier#getActionName() */ public String getActionName() { return this.getChangeLogType().getActionName(); } /** * */ public static void internal_clearCache() { //set this to -1 so it will be an insert next time for (ChangeLogTypeBuiltin changeLogTypeBuiltin : ChangeLogTypeBuiltin.values()) { changeLogTypeBuiltin.internalChangeLogTypeDefault.setHibernateVersionNumber(-1l); } } }
Internet2/grouper
grouper/src/grouper/edu/internet2/middleware/grouper/changeLog/ChangeLogTypeBuiltin.java
7,725
/** * delete entity */
block_comment
nl
/** * Copyright 2014 Internet2 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author mchyzer * $Id: ChangeLogTypeBuiltin.java,v 1.9 2009-10-31 17:46:47 shilen Exp $ */ package edu.internet2.middleware.grouper.changeLog; import java.util.HashMap; import java.util.Map; import edu.internet2.middleware.grouperClient.collections.MultiKey; /** * */ public enum ChangeLogTypeBuiltin implements ChangeLogTypeIdentifier { /** * add group field */ GROUP_FIELD_ADD(new ChangeLogType("groupField", "addGroupField", ChangeLogLabels.GROUP_FIELD_ADD.id, ChangeLogLabels.GROUP_FIELD_ADD.name, ChangeLogLabels.GROUP_FIELD_ADD.groupTypeId, ChangeLogLabels.GROUP_FIELD_ADD.groupTypeName, ChangeLogLabels.GROUP_FIELD_ADD.type)), /** * update group field */ GROUP_FIELD_UPDATE(new ChangeLogType("groupField", "updateGroupField", ChangeLogLabels.GROUP_FIELD_UPDATE.id, ChangeLogLabels.GROUP_FIELD_UPDATE.name, ChangeLogLabels.GROUP_FIELD_UPDATE.groupTypeId, ChangeLogLabels.GROUP_FIELD_UPDATE.groupTypeName, ChangeLogLabels.GROUP_FIELD_UPDATE.type, ChangeLogLabels.GROUP_FIELD_UPDATE.propertyChanged, ChangeLogLabels.GROUP_FIELD_UPDATE.propertyOldValue, ChangeLogLabels.GROUP_FIELD_UPDATE.propertyNewValue)), /** * delete group field */ GROUP_FIELD_DELETE(new ChangeLogType("groupField", "deleteGroupField", ChangeLogLabels.GROUP_FIELD_DELETE.id, ChangeLogLabels.GROUP_FIELD_DELETE.name, ChangeLogLabels.GROUP_FIELD_DELETE.groupTypeId, ChangeLogLabels.GROUP_FIELD_DELETE.groupTypeName, ChangeLogLabels.GROUP_FIELD_DELETE.type)), /** * add group composite */ GROUP_COMPOSITE_ADD(new ChangeLogType("groupComposite", "addGroupComposite", "id", "ownerId", "ownerName", "leftFactorId", "leftFactorName", "rightFactorId", "rightFactorName", "type")), /** * update group composite */ GROUP_COMPOSITE_UPDATE(new ChangeLogType("groupComposite", "updateGroupComposite", "id", "ownerId", "ownerName", "leftFactorId", "leftFactorName", "rightFactorId", "rightFactorName", "type")), /** * delete group composite */ GROUP_COMPOSITE_DELETE(new ChangeLogType("groupComposite", "deleteGroupComposite", "id", "ownerId", "ownerName", "leftFactorId", "leftFactorName", "rightFactorId", "rightFactorName", "type")), /** * assign group type */ GROUP_TYPE_ASSIGN(new ChangeLogType("groupTypeAssignment", "assignGroupType", ChangeLogLabels.GROUP_TYPE_ASSIGN.id, ChangeLogLabels.GROUP_TYPE_ASSIGN.groupId, ChangeLogLabels.GROUP_TYPE_ASSIGN.groupName, ChangeLogLabels.GROUP_TYPE_ASSIGN.typeId, ChangeLogLabels.GROUP_TYPE_ASSIGN.typeName)), /** * unassign group type */ GROUP_TYPE_UNASSIGN(new ChangeLogType("groupTypeAssignment", "unassignGroupType", ChangeLogLabels.GROUP_TYPE_UNASSIGN.id, ChangeLogLabels.GROUP_TYPE_UNASSIGN.groupId, ChangeLogLabels.GROUP_TYPE_UNASSIGN.groupName, ChangeLogLabels.GROUP_TYPE_UNASSIGN.typeId, ChangeLogLabels.GROUP_TYPE_UNASSIGN.typeName)), /** * add membership */ MEMBERSHIP_ADD(new ChangeLogType("membership", "addMembership", ChangeLogLabels.MEMBERSHIP_ADD.id, ChangeLogLabels.MEMBERSHIP_ADD.fieldName, ChangeLogLabels.MEMBERSHIP_ADD.subjectId, ChangeLogLabels.MEMBERSHIP_ADD.sourceId, ChangeLogLabels.MEMBERSHIP_ADD.membershipType, ChangeLogLabels.MEMBERSHIP_ADD.groupId, ChangeLogLabels.MEMBERSHIP_ADD.groupName, ChangeLogLabels.MEMBERSHIP_ADD.memberId, ChangeLogLabels.MEMBERSHIP_ADD.fieldId, ChangeLogLabels.MEMBERSHIP_ADD.subjectIdentifier0)), /** * update membership */ MEMBERSHIP_UPDATE(new ChangeLogType("membership", "updateMembership", ChangeLogLabels.MEMBERSHIP_UPDATE.id, ChangeLogLabels.MEMBERSHIP_UPDATE.fieldName, ChangeLogLabels.MEMBERSHIP_UPDATE.subjectId, ChangeLogLabels.MEMBERSHIP_UPDATE.sourceId, ChangeLogLabels.MEMBERSHIP_UPDATE.membershipType, ChangeLogLabels.MEMBERSHIP_UPDATE.groupId, ChangeLogLabels.MEMBERSHIP_UPDATE.groupName, ChangeLogLabels.MEMBERSHIP_UPDATE.propertyChanged, ChangeLogLabels.MEMBERSHIP_UPDATE.propertyOldValue, ChangeLogLabels.MEMBERSHIP_UPDATE.propertyNewValue, ChangeLogLabels.MEMBERSHIP_UPDATE.memberId, ChangeLogLabels.MEMBERSHIP_UPDATE.fieldId)), /** * delete membership */ MEMBERSHIP_DELETE(new ChangeLogType("membership", "deleteMembership", ChangeLogLabels.MEMBERSHIP_DELETE.id, ChangeLogLabels.MEMBERSHIP_DELETE.fieldName, ChangeLogLabels.MEMBERSHIP_DELETE.subjectId, ChangeLogLabels.MEMBERSHIP_DELETE.sourceId, ChangeLogLabels.MEMBERSHIP_DELETE.membershipType, ChangeLogLabels.MEMBERSHIP_DELETE.groupId, ChangeLogLabels.MEMBERSHIP_DELETE.groupName, ChangeLogLabels.MEMBERSHIP_DELETE.memberId, ChangeLogLabels.MEMBERSHIP_DELETE.fieldId, ChangeLogLabels.MEMBERSHIP_DELETE.subjectName, ChangeLogLabels.MEMBERSHIP_DELETE.subjectIdentifier0)), /** * add privilege */ PRIVILEGE_ADD(new ChangeLogType("privilege", "addPrivilege", ChangeLogLabels.PRIVILEGE_ADD.id, ChangeLogLabels.PRIVILEGE_ADD.privilegeName, ChangeLogLabels.PRIVILEGE_ADD.subjectId, ChangeLogLabels.PRIVILEGE_ADD.sourceId, ChangeLogLabels.PRIVILEGE_ADD.privilegeType, ChangeLogLabels.PRIVILEGE_ADD.ownerType, ChangeLogLabels.PRIVILEGE_ADD.ownerId, ChangeLogLabels.PRIVILEGE_ADD.ownerName, ChangeLogLabels.PRIVILEGE_ADD.memberId, ChangeLogLabels.PRIVILEGE_ADD.fieldId, ChangeLogLabels.PRIVILEGE_ADD.membershipType)), /** * update privilege */ PRIVILEGE_UPDATE(new ChangeLogType("privilege", "updatePrivilege", ChangeLogLabels.PRIVILEGE_UPDATE.id, ChangeLogLabels.PRIVILEGE_UPDATE.privilegeName, ChangeLogLabels.PRIVILEGE_UPDATE.subjectId, ChangeLogLabels.PRIVILEGE_UPDATE.sourceId, ChangeLogLabels.PRIVILEGE_UPDATE.privilegeType, ChangeLogLabels.PRIVILEGE_UPDATE.ownerType, ChangeLogLabels.PRIVILEGE_UPDATE.ownerId, ChangeLogLabels.PRIVILEGE_UPDATE.ownerName, ChangeLogLabels.PRIVILEGE_UPDATE.membershipType)), /** * delete privilege */ PRIVILEGE_DELETE(new ChangeLogType("privilege", "deletePrivilege", ChangeLogLabels.PRIVILEGE_DELETE.id, ChangeLogLabels.PRIVILEGE_DELETE.privilegeName, ChangeLogLabels.PRIVILEGE_DELETE.subjectId, ChangeLogLabels.PRIVILEGE_DELETE.sourceId, ChangeLogLabels.PRIVILEGE_DELETE.privilegeType, ChangeLogLabels.PRIVILEGE_DELETE.ownerType, ChangeLogLabels.PRIVILEGE_DELETE.ownerId, ChangeLogLabels.PRIVILEGE_DELETE.ownerName, ChangeLogLabels.PRIVILEGE_DELETE.memberId, ChangeLogLabels.PRIVILEGE_DELETE.fieldId, ChangeLogLabels.PRIVILEGE_DELETE.membershipType)), /** * add group */ GROUP_ADD(new ChangeLogType("group", "addGroup", ChangeLogLabels.GROUP_ADD.id, ChangeLogLabels.GROUP_ADD.name, ChangeLogLabels.GROUP_ADD.parentStemId, ChangeLogLabels.GROUP_ADD.displayName, ChangeLogLabels.GROUP_ADD.description, ChangeLogLabels.GROUP_ADD.idIndex)), /** * update group */ GROUP_UPDATE(new ChangeLogType("group", "updateGroup", ChangeLogLabels.GROUP_UPDATE.id, ChangeLogLabels.GROUP_UPDATE.name, ChangeLogLabels.GROUP_UPDATE.parentStemId, ChangeLogLabels.GROUP_UPDATE.displayName, ChangeLogLabels.GROUP_UPDATE.description, ChangeLogLabels.GROUP_UPDATE.propertyChanged, ChangeLogLabels.GROUP_UPDATE.propertyOldValue, ChangeLogLabels.GROUP_UPDATE.propertyNewValue)), /** * delete group */ GROUP_DELETE(new ChangeLogType("group", "deleteGroup", ChangeLogLabels.GROUP_DELETE.id, ChangeLogLabels.GROUP_DELETE.name, ChangeLogLabels.GROUP_DELETE.parentStemId, ChangeLogLabels.GROUP_DELETE.displayName, ChangeLogLabels.GROUP_DELETE.description, ChangeLogLabels.GROUP_DELETE.idIndex)), /** * enable group */ GROUP_ENABLE(new ChangeLogType("group", "enableGroup", ChangeLogLabels.GROUP_ENABLE.id, ChangeLogLabels.GROUP_ENABLE.name, ChangeLogLabels.GROUP_ENABLE.parentStemId, ChangeLogLabels.GROUP_ENABLE.displayName, ChangeLogLabels.GROUP_ENABLE.description, ChangeLogLabels.GROUP_ENABLE.idIndex)), /** * disable group */ GROUP_DISABLE(new ChangeLogType("group", "disableGroup", ChangeLogLabels.GROUP_DISABLE.id, ChangeLogLabels.GROUP_DISABLE.name, ChangeLogLabels.GROUP_DISABLE.parentStemId, ChangeLogLabels.GROUP_DISABLE.displayName, ChangeLogLabels.GROUP_DISABLE.description, ChangeLogLabels.GROUP_DISABLE.idIndex)), /** * add entity */ ENTITY_ADD(new ChangeLogType("entity", "addEntity", ChangeLogLabels.ENTITY_ADD.id, ChangeLogLabels.ENTITY_ADD.name, ChangeLogLabels.ENTITY_ADD.parentStemId, ChangeLogLabels.ENTITY_ADD.displayName, ChangeLogLabels.ENTITY_ADD.description)), /** * enable entity */ ENTITY_ENABLE(new ChangeLogType("entity", "enableEntity", ChangeLogLabels.ENTITY_ENABLE.id, ChangeLogLabels.ENTITY_ENABLE.name, ChangeLogLabels.ENTITY_ENABLE.parentStemId, ChangeLogLabels.ENTITY_ENABLE.displayName, ChangeLogLabels.ENTITY_ENABLE.description)), /** * update entity */ ENTITY_UPDATE(new ChangeLogType("entity", "updateEntity", ChangeLogLabels.ENTITY_UPDATE.id, ChangeLogLabels.ENTITY_UPDATE.name, ChangeLogLabels.ENTITY_UPDATE.parentStemId, ChangeLogLabels.ENTITY_UPDATE.displayName, ChangeLogLabels.ENTITY_UPDATE.description, ChangeLogLabels.ENTITY_UPDATE.propertyChanged, ChangeLogLabels.ENTITY_UPDATE.propertyOldValue, ChangeLogLabels.ENTITY_UPDATE.propertyNewValue)), /** * delete entity <SUF>*/ ENTITY_DELETE(new ChangeLogType("entity", "deleteEntity", ChangeLogLabels.ENTITY_DELETE.id, ChangeLogLabels.ENTITY_DELETE.name, ChangeLogLabels.ENTITY_DELETE.parentStemId, ChangeLogLabels.ENTITY_DELETE.displayName, ChangeLogLabels.ENTITY_DELETE.description)), /** * disable entity */ ENTITY_DISABLE(new ChangeLogType("entity", "disableEntity", ChangeLogLabels.ENTITY_DISABLE.id, ChangeLogLabels.ENTITY_DISABLE.name, ChangeLogLabels.ENTITY_DISABLE.parentStemId, ChangeLogLabels.ENTITY_DISABLE.displayName, ChangeLogLabels.ENTITY_DISABLE.description)), /** * attribute def add */ ATTRIBUTE_DEF_ADD(new ChangeLogType("attributeDef", "addAttributeDef", ChangeLogLabels.ATTRIBUTE_DEF_ADD.id, ChangeLogLabels.ATTRIBUTE_DEF_ADD.name, ChangeLogLabels.ATTRIBUTE_DEF_ADD.stemId, ChangeLogLabels.ATTRIBUTE_DEF_ADD.description, ChangeLogLabels.ATTRIBUTE_DEF_ADD.attributeDefType)), /** * attribute def update */ ATTRIBUTE_DEF_UPDATE(new ChangeLogType("attributeDef", "updateAttributeDef", ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.id, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.name, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.stemId, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.description, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.attributeDefType, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.propertyChanged, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.propertyOldValue, ChangeLogLabels.ATTRIBUTE_DEF_UPDATE.propertyNewValue)), /** * attribute def delete */ ATTRIBUTE_DEF_DELETE(new ChangeLogType("attributeDef", "deleteAttributeDef", ChangeLogLabels.ATTRIBUTE_DEF_DELETE.id, ChangeLogLabels.ATTRIBUTE_DEF_DELETE.name, ChangeLogLabels.ATTRIBUTE_DEF_DELETE.stemId, ChangeLogLabels.ATTRIBUTE_DEF_DELETE.description, ChangeLogLabels.ATTRIBUTE_DEF_DELETE.attributeDefType)), /** * stem add */ STEM_ADD(new ChangeLogType("stem", "addStem", ChangeLogLabels.STEM_ADD.id, ChangeLogLabels.STEM_ADD.name, ChangeLogLabels.STEM_ADD.parentStemId, ChangeLogLabels.STEM_ADD.displayName, ChangeLogLabels.STEM_ADD.description)), /** * stem update */ STEM_UPDATE(new ChangeLogType("stem", "updateStem", ChangeLogLabels.STEM_UPDATE.id, ChangeLogLabels.STEM_UPDATE.name, ChangeLogLabels.STEM_UPDATE.parentStemId, ChangeLogLabels.STEM_UPDATE.displayName, ChangeLogLabels.STEM_UPDATE.description, ChangeLogLabels.STEM_UPDATE.propertyChanged, ChangeLogLabels.STEM_UPDATE.propertyOldValue, ChangeLogLabels.STEM_UPDATE.propertyNewValue)), /** * stem delete */ STEM_DELETE(new ChangeLogType("stem", "deleteStem", ChangeLogLabels.STEM_DELETE.id, ChangeLogLabels.STEM_DELETE.name, ChangeLogLabels.STEM_DELETE.parentStemId, ChangeLogLabels.STEM_DELETE.displayName, ChangeLogLabels.STEM_DELETE.description)), /** * member add */ MEMBER_ADD(new ChangeLogType("member", "addMember", ChangeLogLabels.MEMBER_ADD.id, ChangeLogLabels.MEMBER_ADD.subjectId, ChangeLogLabels.MEMBER_ADD.subjectSourceId, ChangeLogLabels.MEMBER_ADD.subjectTypeId, ChangeLogLabels.MEMBER_ADD.subjectIdentifier0)), /** * member add */ MEMBER_UPDATE(new ChangeLogType("member", "updateMember", ChangeLogLabels.MEMBER_UPDATE.id, ChangeLogLabels.MEMBER_UPDATE.subjectId, ChangeLogLabels.MEMBER_UPDATE.subjectSourceId, ChangeLogLabels.MEMBER_UPDATE.subjectTypeId, ChangeLogLabels.MEMBER_UPDATE.subjectIdentifier0, ChangeLogLabels.MEMBER_UPDATE.propertyChanged, ChangeLogLabels.MEMBER_UPDATE.propertyOldValue, ChangeLogLabels.MEMBER_UPDATE.propertyNewValue)), /** * member add */ MEMBER_DELETE(new ChangeLogType("member", "deleteMember", ChangeLogLabels.MEMBER_DELETE.id, ChangeLogLabels.MEMBER_DELETE.subjectId, ChangeLogLabels.MEMBER_DELETE.subjectSourceId, ChangeLogLabels.MEMBER_DELETE.subjectTypeId, ChangeLogLabels.MEMBER_DELETE.subjectIdentifier0)), /** * member change subject */ MEMBER_CHANGE_SUBJECT(new ChangeLogType("member", "changeSubject", "oldMemberId", "oldSubjectId", "oldSourceId", "newMemberId", "newSubjectId", "newSourceId", "deleteOldMember", "memberIdChanged")), /** * attribute assign action add */ ATTRIBUTE_ASSIGN_ACTION_ADD(new ChangeLogType("attributeAssignAction", "addAttributeAssignAction", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_ADD.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_ADD.name, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_ADD.attributeDefId)), /** * attribute assign action update */ ATTRIBUTE_ASSIGN_ACTION_UPDATE(new ChangeLogType("attributeAssignAction", "updateAttributeAssignAction", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.name, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.attributeDefId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.propertyChanged, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.propertyOldValue, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_UPDATE.propertyNewValue)), /** * attribute assign action delete */ ATTRIBUTE_ASSIGN_ACTION_DELETE(new ChangeLogType("attributeAssignAction", "deleteAttributeAssignAction", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_DELETE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_DELETE.name, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_DELETE.attributeDefId)), /** * attribute assign action set add */ ATTRIBUTE_ASSIGN_ACTION_SET_ADD(new ChangeLogType("attributeAssignActionSet", "addAttributeAssignActionSet", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.type, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.ifHasAttrAssnActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.thenHasAttrAssnActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.parentAttrAssignActionSetId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_ADD.depth)), /** * attribute assign action set delete */ ATTRIBUTE_ASSIGN_ACTION_SET_DELETE(new ChangeLogType("attributeAssignActionSet", "deleteAttributeAssignActionSet", ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.type, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.ifHasAttrAssnActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.thenHasAttrAssnActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.parentAttrAssignActionSetId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ACTION_SET_DELETE.depth)), /** * attribute def name set add */ ATTRIBUTE_DEF_NAME_SET_ADD(new ChangeLogType("attributeDefNameSet", "addAttributeDefNameSet", ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.type, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.ifHasAttributeDefNameId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.thenHasAttributeDefNameId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.parentAttrDefNameSetId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_ADD.depth)), /** * attribute def name set delete */ ATTRIBUTE_DEF_NAME_SET_DELETE(new ChangeLogType("attributeDefNameSet", "deleteAttributeDefNameSet", ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.type, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.ifHasAttributeDefNameId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.thenHasAttributeDefNameId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.parentAttrDefNameSetId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_SET_DELETE.depth)), /** * role set add */ ROLE_SET_ADD(new ChangeLogType("roleSet", "addRoleSet", ChangeLogLabels.ROLE_SET_ADD.id, ChangeLogLabels.ROLE_SET_ADD.type, ChangeLogLabels.ROLE_SET_ADD.ifHasRoleId, ChangeLogLabels.ROLE_SET_ADD.thenHasRoleId, ChangeLogLabels.ROLE_SET_ADD.parentRoleSetId, ChangeLogLabels.ROLE_SET_ADD.depth)), /** * role set delete */ ROLE_SET_DELETE(new ChangeLogType("roleSet", "deleteRoleSet", ChangeLogLabels.ROLE_SET_DELETE.id, ChangeLogLabels.ROLE_SET_DELETE.type, ChangeLogLabels.ROLE_SET_DELETE.ifHasRoleId, ChangeLogLabels.ROLE_SET_DELETE.thenHasRoleId, ChangeLogLabels.ROLE_SET_DELETE.parentRoleSetId, ChangeLogLabels.ROLE_SET_DELETE.depth)), /** * attribute def name add */ ATTRIBUTE_DEF_NAME_ADD(new ChangeLogType("attributeDefName", "addAttributeDefName", ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.attributeDefId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.name, ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.stemId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_ADD.description)), /** * attribute def name update */ ATTRIBUTE_DEF_NAME_UPDATE(new ChangeLogType("attributeDefName", "updateAttributeDefName", ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.attributeDefId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.name, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.stemId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.description, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.propertyChanged, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.propertyOldValue, ChangeLogLabels.ATTRIBUTE_DEF_NAME_UPDATE.propertyNewValue)), /** * attribute def name delete */ ATTRIBUTE_DEF_NAME_DELETE(new ChangeLogType("attributeDefName", "deleteAttributeDefName", ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.id, ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.attributeDefId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.name, ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.stemId, ChangeLogLabels.ATTRIBUTE_DEF_NAME_DELETE.description)), /** * attribute assign add */ ATTRIBUTE_ASSIGN_ADD(new ChangeLogType("attributeAssign", "addAttributeAssign", ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.attributeDefNameId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.attributeAssignActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.assignType, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.ownerId1, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.ownerId2, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.attributeDefNameName, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.action, ChangeLogLabels.ATTRIBUTE_ASSIGN_ADD.disallowed)), /** * attribute assign delete */ ATTRIBUTE_ASSIGN_DELETE(new ChangeLogType("attributeAssign", "deleteAttributeAssign", ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.attributeDefNameId, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.attributeAssignActionId, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.assignType, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.ownerId1, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.ownerId2, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.attributeDefNameName, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.action, ChangeLogLabels.ATTRIBUTE_ASSIGN_DELETE.disallowed)), /** * attribute assign value add */ ATTRIBUTE_ASSIGN_VALUE_ADD(new ChangeLogType("attributeAssignValue", "addAttributeAssignValue", ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.attributeAssignId, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.attributeDefNameId, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.attributeDefNameName, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.value, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_ADD.valueType)), /** * attribute assign value delete */ ATTRIBUTE_ASSIGN_VALUE_DELETE(new ChangeLogType("attributeAssignValue", "deleteAttributeAssignValue", ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.id, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.attributeAssignId, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.attributeDefNameId, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.attributeDefNameName, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.value, ChangeLogLabels.ATTRIBUTE_ASSIGN_VALUE_DELETE.valueType)), /** * permission change on role */ PERMISSION_CHANGE_ON_ROLE(new ChangeLogType("permission", "permissionChangeOnRole", ChangeLogLabels.PERMISSION_CHANGE_ON_ROLE.roleId, ChangeLogLabels.PERMISSION_CHANGE_ON_ROLE.roleName)), /** * permission change on subject */ PERMISSION_CHANGE_ON_SUBJECT(new ChangeLogType("permission", "permissionChangeOnSubject", ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.subjectId, ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.subjectSourceId, ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.memberId, ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.roleId, ChangeLogLabels.PERMISSION_CHANGE_ON_SUBJECT.roleName)); /** * lookup change log type by category and action */ private static Map<MultiKey, ChangeLogTypeBuiltin> categoryAndActionLookup = null; /** * lookup a change log type by category and action * @param category * @param action * @return the builtin type */ public static ChangeLogTypeBuiltin retrieveChangeLogTypeByChangeLogEntry(ChangeLogEntry changeLogEntry) { ChangeLogType changeLogType = changeLogEntry.getChangeLogType(); if (changeLogType == null) { return null; } return retrieveChangeLogTypeByCategoryAndAction(changeLogType.getChangeLogCategory(), changeLogType.getActionName()); } /** * lookup a change log type by category and action * @param category * @param action * @return the builtin type */ public static ChangeLogTypeBuiltin retrieveChangeLogTypeByCategoryAndAction(String category, String action) { if (categoryAndActionLookup == null) { Map<MultiKey, ChangeLogTypeBuiltin> theCategoryAndActionLookup = new HashMap<MultiKey, ChangeLogTypeBuiltin>(); for (ChangeLogTypeBuiltin changeLogTypeBuiltin : ChangeLogTypeBuiltin.values()) { MultiKey multiKey = new MultiKey(changeLogTypeBuiltin.getChangeLogCategory(), changeLogTypeBuiltin.getActionName()); theCategoryAndActionLookup.put(multiKey, changeLogTypeBuiltin); } categoryAndActionLookup = theCategoryAndActionLookup; } return categoryAndActionLookup.get(new MultiKey(category, action)); } /** * defaults for changelog type, though doesn't hold the id */ private ChangeLogType internalChangeLogTypeDefault; /** * construct * @param theInternalChangeLogTypeDefault */ private ChangeLogTypeBuiltin(ChangeLogType theInternalChangeLogTypeDefault) { this.internalChangeLogTypeDefault = theInternalChangeLogTypeDefault; } /** * get the changelog type from the enum * @return the changelog type */ public ChangeLogType getChangeLogType() { return ChangeLogTypeFinder.find(this.internalChangeLogTypeDefault.getChangeLogCategory(), this.internalChangeLogTypeDefault.getActionName(), true); } /** * get the defaults, but not the id * @return the defaults */ public ChangeLogType internal_changeLogTypeDefault() { return this.internalChangeLogTypeDefault; } /** * * @see edu.internet2.middleware.grouper.changeLog.ChangeLogTypeIdentifier#getChangeLogCategory() */ public String getChangeLogCategory() { return this.getChangeLogType().getChangeLogCategory(); } /** * * @see edu.internet2.middleware.grouper.changeLog.ChangeLogTypeIdentifier#getActionName() */ public String getActionName() { return this.getChangeLogType().getActionName(); } /** * */ public static void internal_clearCache() { //set this to -1 so it will be an insert next time for (ChangeLogTypeBuiltin changeLogTypeBuiltin : ChangeLogTypeBuiltin.values()) { changeLogTypeBuiltin.internalChangeLogTypeDefault.setHibernateVersionNumber(-1l); } } }
146328_2
/* * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.colorchooser.*; import javax.swing.plaf.ColorChooserUI; import javax.accessibility.*; import sun.swing.SwingUtilities2; /** * <code>JColorChooser</code> provides a pane of controls designed to allow * a user to manipulate and select a color. * For information about using color choosers, see * <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html">How to Use Color Choosers</a>, * a section in <em>The Java Tutorial</em>. * * <p> * * This class provides three levels of API: * <ol> * <li>A static convenience method which shows a modal color-chooser * dialog and returns the color selected by the user. * <li>A static convenience method for creating a color-chooser dialog * where <code>ActionListeners</code> can be specified to be invoked when * the user presses one of the dialog buttons. * <li>The ability to create instances of <code>JColorChooser</code> panes * directly (within any container). <code>PropertyChange</code> listeners * can be added to detect when the current "color" property changes. * </ol> * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * * @beaninfo * attribute: isContainer false * description: A component that supports selecting a Color. * * * @author James Gosling * @author Amy Fowler * @author Steve Wilson */ public class JColorChooser extends JComponent implements Accessible { /** * @see #getUIClassID * @see #readObject */ private static final String uiClassID = "ColorChooserUI"; private ColorSelectionModel selectionModel; private JComponent previewPanel = ColorChooserComponentFactory.getPreviewPanel(); private AbstractColorChooserPanel[] chooserPanels = new AbstractColorChooserPanel[0]; private boolean dragEnabled; /** * The selection model property name. */ public static final String SELECTION_MODEL_PROPERTY = "selectionModel"; /** * The preview panel property name. */ public static final String PREVIEW_PANEL_PROPERTY = "previewPanel"; /** * The chooserPanel array property name. */ public static final String CHOOSER_PANELS_PROPERTY = "chooserPanels"; /** * Shows a modal color-chooser dialog and blocks until the * dialog is hidden. If the user presses the "OK" button, then * this method hides/disposes the dialog and returns the selected color. * If the user presses the "Cancel" button or closes the dialog without * pressing "OK", then this method hides/disposes the dialog and returns * <code>null</code>. * * @param component the parent <code>Component</code> for the dialog * @param title the String containing the dialog's title * @param initialColor the initial Color set when the color-chooser is shown * @return the selected color or <code>null</code> if the user opted out * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ public static Color showDialog(Component component, String title, Color initialColor) throws HeadlessException { final JColorChooser pane = new JColorChooser(initialColor != null? initialColor : Color.white); ColorTracker ok = new ColorTracker(pane); JDialog dialog = createDialog(component, title, true, pane, ok, null); dialog.addComponentListener(new ColorChooserDialog.DisposeOnClose()); dialog.show(); // blocks until user brings dialog down... return ok.getColor(); } /** * Creates and returns a new dialog containing the specified * <code>ColorChooser</code> pane along with "OK", "Cancel", and "Reset" * buttons. If the "OK" or "Cancel" buttons are pressed, the dialog is * automatically hidden (but not disposed). If the "Reset" * button is pressed, the color-chooser's color will be reset to the * color which was set the last time <code>show</code> was invoked on the * dialog and the dialog will remain showing. * * @param c the parent component for the dialog * @param title the title for the dialog * @param modal a boolean. When true, the remainder of the program * is inactive until the dialog is closed. * @param chooserPane the color-chooser to be placed inside the dialog * @param okListener the ActionListener invoked when "OK" is pressed * @param cancelListener the ActionListener invoked when "Cancel" is pressed * @return a new dialog containing the color-chooser pane * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ public static JDialog createDialog(Component c, String title, boolean modal, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { Window window = JOptionPane.getWindowForComponent(c); ColorChooserDialog dialog; if (window instanceof Frame) { dialog = new ColorChooserDialog((Frame)window, title, modal, c, chooserPane, okListener, cancelListener); } else { dialog = new ColorChooserDialog((Dialog)window, title, modal, c, chooserPane, okListener, cancelListener); } dialog.getAccessibleContext().setAccessibleDescription(title); return dialog; } /** * Creates a color chooser pane with an initial color of white. */ public JColorChooser() { this(Color.white); } /** * Creates a color chooser pane with the specified initial color. * * @param initialColor the initial color set in the chooser */ public JColorChooser(Color initialColor) { this( new DefaultColorSelectionModel(initialColor) ); } /** * Creates a color chooser pane with the specified * <code>ColorSelectionModel</code>. * * @param model the <code>ColorSelectionModel</code> to be used */ public JColorChooser(ColorSelectionModel model) { selectionModel = model; updateUI(); dragEnabled = false; } /** * Returns the L&amp;F object that renders this component. * * @return the <code>ColorChooserUI</code> object that renders * this component */ public ColorChooserUI getUI() { return (ColorChooserUI)ui; } /** * Sets the L&amp;F object that renders this component. * * @param ui the <code>ColorChooserUI</code> L&amp;F object * @see UIDefaults#getUI * * @beaninfo * bound: true * hidden: true * description: The UI object that implements the color chooser's LookAndFeel. */ public void setUI(ColorChooserUI ui) { super.setUI(ui); } /** * Notification from the <code>UIManager</code> that the L&amp;F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see JComponent#updateUI */ public void updateUI() { setUI((ColorChooserUI)UIManager.getUI(this)); } /** * Returns the name of the L&amp;F class that renders this component. * * @return the string "ColorChooserUI" * @see JComponent#getUIClassID * @see UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Gets the current color value from the color chooser. * By default, this delegates to the model. * * @return the current color value of the color chooser */ public Color getColor() { return selectionModel.getSelectedColor(); } /** * Sets the current color of the color chooser to the specified color. * The <code>ColorSelectionModel</code> will fire a <code>ChangeEvent</code> * @param color the color to be set in the color chooser * @see JComponent#addPropertyChangeListener * * @beaninfo * bound: false * hidden: false * description: The current color the chooser is to display. */ public void setColor(Color color) { selectionModel.setSelectedColor(color); } /** * Sets the current color of the color chooser to the * specified RGB color. Note that the values of red, green, * and blue should be between the numbers 0 and 255, inclusive. * * @param r an int specifying the amount of Red * @param g an int specifying the amount of Green * @param b an int specifying the amount of Blue * @exception IllegalArgumentException if r,g,b values are out of range * @see java.awt.Color */ public void setColor(int r, int g, int b) { setColor(new Color(r,g,b)); } /** * Sets the current color of the color chooser to the * specified color. * * @param c an integer value that sets the current color in the chooser * where the low-order 8 bits specify the Blue value, * the next 8 bits specify the Green value, and the 8 bits * above that specify the Red value. */ public void setColor(int c) { setColor((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF); } /** * Sets the <code>dragEnabled</code> property, * which must be <code>true</code> to enable * automatic drag handling (the first part of drag and drop) * on this component. * The <code>transferHandler</code> property needs to be set * to a non-<code>null</code> value for the drag to do * anything. The default value of the <code>dragEnabled</code> * property * is <code>false</code>. * * <p> * * When automatic drag handling is enabled, * most look and feels begin a drag-and-drop operation * when the user presses the mouse button over the preview panel. * Some look and feels might not support automatic drag and drop; * they will ignore this property. You can work around such * look and feels by modifying the component * to directly call the <code>exportAsDrag</code> method of a * <code>TransferHandler</code>. * * @param b the value to set the <code>dragEnabled</code> property to * @exception HeadlessException if * <code>b</code> is <code>true</code> and * <code>GraphicsEnvironment.isHeadless()</code> * returns <code>true</code> * * @since 1.4 * * @see java.awt.GraphicsEnvironment#isHeadless * @see #getDragEnabled * @see #setTransferHandler * @see TransferHandler * * @beaninfo * description: Determines whether automatic drag handling is enabled. * bound: false */ public void setDragEnabled(boolean b) { if (b && GraphicsEnvironment.isHeadless()) { throw new HeadlessException(); } dragEnabled = b; } /** * Gets the value of the <code>dragEnabled</code> property. * * @return the value of the <code>dragEnabled</code> property * @see #setDragEnabled * @since 1.4 */ public boolean getDragEnabled() { return dragEnabled; } /** * Sets the current preview panel. * This will fire a <code>PropertyChangeEvent</code> for the property * named "previewPanel". * * @param preview the <code>JComponent</code> which displays the current color * @see JComponent#addPropertyChangeListener * * @beaninfo * bound: true * hidden: true * description: The UI component which displays the current color. */ public void setPreviewPanel(JComponent preview) { if (previewPanel != preview) { JComponent oldPreview = previewPanel; previewPanel = preview; firePropertyChange(JColorChooser.PREVIEW_PANEL_PROPERTY, oldPreview, preview); } } /** * Returns the preview panel that shows a chosen color. * * @return a <code>JComponent</code> object -- the preview panel */ public JComponent getPreviewPanel() { return previewPanel; } /** * Adds a color chooser panel to the color chooser. * * @param panel the <code>AbstractColorChooserPanel</code> to be added */ public void addChooserPanel( AbstractColorChooserPanel panel ) { AbstractColorChooserPanel[] oldPanels = getChooserPanels(); AbstractColorChooserPanel[] newPanels = new AbstractColorChooserPanel[oldPanels.length+1]; System.arraycopy(oldPanels, 0, newPanels, 0, oldPanels.length); newPanels[newPanels.length-1] = panel; setChooserPanels(newPanels); } /** * Removes the Color Panel specified. * * @param panel a string that specifies the panel to be removed * @return the color panel * @exception IllegalArgumentException if panel is not in list of * known chooser panels */ public AbstractColorChooserPanel removeChooserPanel( AbstractColorChooserPanel panel ) { int containedAt = -1; for (int i = 0; i < chooserPanels.length; i++) { if (chooserPanels[i] == panel) { containedAt = i; break; } } if (containedAt == -1) { throw new IllegalArgumentException("chooser panel not in this chooser"); } AbstractColorChooserPanel[] newArray = new AbstractColorChooserPanel[chooserPanels.length-1]; if (containedAt == chooserPanels.length-1) { // at end System.arraycopy(chooserPanels, 0, newArray, 0, newArray.length); } else if (containedAt == 0) { // at start System.arraycopy(chooserPanels, 1, newArray, 0, newArray.length); } else { // in middle System.arraycopy(chooserPanels, 0, newArray, 0, containedAt); System.arraycopy(chooserPanels, containedAt+1, newArray, containedAt, (chooserPanels.length - containedAt - 1)); } setChooserPanels(newArray); return panel; } /** * Specifies the Color Panels used to choose a color value. * * @param panels an array of <code>AbstractColorChooserPanel</code> * objects * * @beaninfo * bound: true * hidden: true * description: An array of different chooser types. */ public void setChooserPanels( AbstractColorChooserPanel[] panels) { AbstractColorChooserPanel[] oldValue = chooserPanels; chooserPanels = panels; firePropertyChange(CHOOSER_PANELS_PROPERTY, oldValue, panels); } /** * Returns the specified color panels. * * @return an array of <code>AbstractColorChooserPanel</code> objects */ public AbstractColorChooserPanel[] getChooserPanels() { return chooserPanels; } /** * Returns the data model that handles color selections. * * @return a <code>ColorSelectionModel</code> object */ public ColorSelectionModel getSelectionModel() { return selectionModel; } /** * Sets the model containing the selected color. * * @param newModel the new <code>ColorSelectionModel</code> object * * @beaninfo * bound: true * hidden: true * description: The model which contains the currently selected color. */ public void setSelectionModel(ColorSelectionModel newModel ) { ColorSelectionModel oldModel = selectionModel; selectionModel = newModel; firePropertyChange(JColorChooser.SELECTION_MODEL_PROPERTY, oldModel, newModel); } /** * See <code>readObject</code> and <code>writeObject</code> in * <code>JComponent</code> for more * information about serialization in Swing. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); if (getUIClassID().equals(uiClassID)) { byte count = JComponent.getWriteObjCounter(this); JComponent.setWriteObjCounter(this, --count); if (count == 0 && ui != null) { ui.installUI(this); } } } /** * Returns a string representation of this <code>JColorChooser</code>. * This method * is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not * be <code>null</code>. * * @return a string representation of this <code>JColorChooser</code> */ protected String paramString() { StringBuffer chooserPanelsString = new StringBuffer(""); for (int i=0; i<chooserPanels.length; i++) { chooserPanelsString.append("[" + chooserPanels[i].toString() + "]"); } String previewPanelString = (previewPanel != null ? previewPanel.toString() : ""); return super.paramString() + ",chooserPanels=" + chooserPanelsString.toString() + ",previewPanel=" + previewPanelString; } ///////////////// // Accessibility support //////////////// protected AccessibleContext accessibleContext = null; /** * Gets the AccessibleContext associated with this JColorChooser. * For color choosers, the AccessibleContext takes the form of an * AccessibleJColorChooser. * A new AccessibleJColorChooser instance is created if necessary. * * @return an AccessibleJColorChooser that serves as the * AccessibleContext of this JColorChooser */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJColorChooser(); } return accessibleContext; } /** * This class implements accessibility support for the * <code>JColorChooser</code> class. It provides an implementation of the * Java Accessibility API appropriate to color chooser user-interface * elements. */ protected class AccessibleJColorChooser extends AccessibleJComponent { /** * Get the role of this object. * * @return an instance of AccessibleRole describing the role of the * object * @see AccessibleRole */ public AccessibleRole getAccessibleRole() { return AccessibleRole.COLOR_CHOOSER; } } // inner class AccessibleJColorChooser } /* * Class which builds a color chooser dialog consisting of * a JColorChooser with "Ok", "Cancel", and "Reset" buttons. * * Note: This needs to be fixed to deal with localization! */ class ColorChooserDialog extends JDialog { private Color initialColor; private JColorChooser chooserPane; private JButton cancelButton; public ColorChooserDialog(Dialog owner, String title, boolean modal, Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { super(owner, title, modal); initColorChooserDialog(c, chooserPane, okListener, cancelListener); } public ColorChooserDialog(Frame owner, String title, boolean modal, Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { super(owner, title, modal); initColorChooserDialog(c, chooserPane, okListener, cancelListener); } protected void initColorChooserDialog(Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) { //setResizable(false); this.chooserPane = chooserPane; Locale locale = getLocale(); String okString = UIManager.getString("ColorChooser.okText", locale); String cancelString = UIManager.getString("ColorChooser.cancelText", locale); String resetString = UIManager.getString("ColorChooser.resetText", locale); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(chooserPane, BorderLayout.CENTER); /* * Create Lower button panel */ JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); JButton okButton = new JButton(okString); getRootPane().setDefaultButton(okButton); okButton.getAccessibleContext().setAccessibleDescription(okString); okButton.setActionCommand("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); if (okListener != null) { okButton.addActionListener(okListener); } buttonPane.add(okButton); cancelButton = new JButton(cancelString); cancelButton.getAccessibleContext().setAccessibleDescription(cancelString); // The following few lines are used to register esc to close the dialog Action cancelKeyAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { ((AbstractButton)e.getSource()).fireActionPerformed(e); } }; KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); InputMap inputMap = cancelButton.getInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW); ActionMap actionMap = cancelButton.getActionMap(); if (inputMap != null && actionMap != null) { inputMap.put(cancelKeyStroke, "cancel"); actionMap.put("cancel", cancelKeyAction); } // end esc handling cancelButton.setActionCommand("cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); if (cancelListener != null) { cancelButton.addActionListener(cancelListener); } buttonPane.add(cancelButton); JButton resetButton = new JButton(resetString); resetButton.getAccessibleContext().setAccessibleDescription(resetString); resetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { reset(); } }); int mnemonic = SwingUtilities2.getUIDefaultsInt("ColorChooser.resetMnemonic", locale, -1); if (mnemonic != -1) { resetButton.setMnemonic(mnemonic); } buttonPane.add(resetButton); contentPane.add(buttonPane, BorderLayout.SOUTH); if (JDialog.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = UIManager.getLookAndFeel().getSupportsWindowDecorations(); if (supportsWindowDecorations) { getRootPane().setWindowDecorationStyle(JRootPane.COLOR_CHOOSER_DIALOG); } } applyComponentOrientation(((c == null) ? getRootPane() : c).getComponentOrientation()); pack(); setLocationRelativeTo(c); this.addWindowListener(new Closer()); } public void show() { initialColor = chooserPane.getColor(); super.show(); } public void reset() { chooserPane.setColor(initialColor); } class Closer extends WindowAdapter implements Serializable{ public void windowClosing(WindowEvent e) { cancelButton.doClick(0); Window w = e.getWindow(); w.hide(); } } static class DisposeOnClose extends ComponentAdapter implements Serializable{ public void componentHidden(ComponentEvent e) { Window w = (Window)e.getComponent(); w.dispose(); } } } class ColorTracker implements ActionListener, Serializable { JColorChooser chooser; Color color; public ColorTracker(JColorChooser c) { chooser = c; } public void actionPerformed(ActionEvent e) { color = chooser.getColor(); } public Color getColor() { return color; } }
wupeixuan/JDKSourceCode1.8
src/javax/swing/JColorChooser.java
6,206
/** * @see #getUIClassID * @see #readObject */
block_comment
nl
/* * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.colorchooser.*; import javax.swing.plaf.ColorChooserUI; import javax.accessibility.*; import sun.swing.SwingUtilities2; /** * <code>JColorChooser</code> provides a pane of controls designed to allow * a user to manipulate and select a color. * For information about using color choosers, see * <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html">How to Use Color Choosers</a>, * a section in <em>The Java Tutorial</em>. * * <p> * * This class provides three levels of API: * <ol> * <li>A static convenience method which shows a modal color-chooser * dialog and returns the color selected by the user. * <li>A static convenience method for creating a color-chooser dialog * where <code>ActionListeners</code> can be specified to be invoked when * the user presses one of the dialog buttons. * <li>The ability to create instances of <code>JColorChooser</code> panes * directly (within any container). <code>PropertyChange</code> listeners * can be added to detect when the current "color" property changes. * </ol> * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * * @beaninfo * attribute: isContainer false * description: A component that supports selecting a Color. * * * @author James Gosling * @author Amy Fowler * @author Steve Wilson */ public class JColorChooser extends JComponent implements Accessible { /** * @see #getUIClassID <SUF>*/ private static final String uiClassID = "ColorChooserUI"; private ColorSelectionModel selectionModel; private JComponent previewPanel = ColorChooserComponentFactory.getPreviewPanel(); private AbstractColorChooserPanel[] chooserPanels = new AbstractColorChooserPanel[0]; private boolean dragEnabled; /** * The selection model property name. */ public static final String SELECTION_MODEL_PROPERTY = "selectionModel"; /** * The preview panel property name. */ public static final String PREVIEW_PANEL_PROPERTY = "previewPanel"; /** * The chooserPanel array property name. */ public static final String CHOOSER_PANELS_PROPERTY = "chooserPanels"; /** * Shows a modal color-chooser dialog and blocks until the * dialog is hidden. If the user presses the "OK" button, then * this method hides/disposes the dialog and returns the selected color. * If the user presses the "Cancel" button or closes the dialog without * pressing "OK", then this method hides/disposes the dialog and returns * <code>null</code>. * * @param component the parent <code>Component</code> for the dialog * @param title the String containing the dialog's title * @param initialColor the initial Color set when the color-chooser is shown * @return the selected color or <code>null</code> if the user opted out * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ public static Color showDialog(Component component, String title, Color initialColor) throws HeadlessException { final JColorChooser pane = new JColorChooser(initialColor != null? initialColor : Color.white); ColorTracker ok = new ColorTracker(pane); JDialog dialog = createDialog(component, title, true, pane, ok, null); dialog.addComponentListener(new ColorChooserDialog.DisposeOnClose()); dialog.show(); // blocks until user brings dialog down... return ok.getColor(); } /** * Creates and returns a new dialog containing the specified * <code>ColorChooser</code> pane along with "OK", "Cancel", and "Reset" * buttons. If the "OK" or "Cancel" buttons are pressed, the dialog is * automatically hidden (but not disposed). If the "Reset" * button is pressed, the color-chooser's color will be reset to the * color which was set the last time <code>show</code> was invoked on the * dialog and the dialog will remain showing. * * @param c the parent component for the dialog * @param title the title for the dialog * @param modal a boolean. When true, the remainder of the program * is inactive until the dialog is closed. * @param chooserPane the color-chooser to be placed inside the dialog * @param okListener the ActionListener invoked when "OK" is pressed * @param cancelListener the ActionListener invoked when "Cancel" is pressed * @return a new dialog containing the color-chooser pane * @exception HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ public static JDialog createDialog(Component c, String title, boolean modal, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { Window window = JOptionPane.getWindowForComponent(c); ColorChooserDialog dialog; if (window instanceof Frame) { dialog = new ColorChooserDialog((Frame)window, title, modal, c, chooserPane, okListener, cancelListener); } else { dialog = new ColorChooserDialog((Dialog)window, title, modal, c, chooserPane, okListener, cancelListener); } dialog.getAccessibleContext().setAccessibleDescription(title); return dialog; } /** * Creates a color chooser pane with an initial color of white. */ public JColorChooser() { this(Color.white); } /** * Creates a color chooser pane with the specified initial color. * * @param initialColor the initial color set in the chooser */ public JColorChooser(Color initialColor) { this( new DefaultColorSelectionModel(initialColor) ); } /** * Creates a color chooser pane with the specified * <code>ColorSelectionModel</code>. * * @param model the <code>ColorSelectionModel</code> to be used */ public JColorChooser(ColorSelectionModel model) { selectionModel = model; updateUI(); dragEnabled = false; } /** * Returns the L&amp;F object that renders this component. * * @return the <code>ColorChooserUI</code> object that renders * this component */ public ColorChooserUI getUI() { return (ColorChooserUI)ui; } /** * Sets the L&amp;F object that renders this component. * * @param ui the <code>ColorChooserUI</code> L&amp;F object * @see UIDefaults#getUI * * @beaninfo * bound: true * hidden: true * description: The UI object that implements the color chooser's LookAndFeel. */ public void setUI(ColorChooserUI ui) { super.setUI(ui); } /** * Notification from the <code>UIManager</code> that the L&amp;F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see JComponent#updateUI */ public void updateUI() { setUI((ColorChooserUI)UIManager.getUI(this)); } /** * Returns the name of the L&amp;F class that renders this component. * * @return the string "ColorChooserUI" * @see JComponent#getUIClassID * @see UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Gets the current color value from the color chooser. * By default, this delegates to the model. * * @return the current color value of the color chooser */ public Color getColor() { return selectionModel.getSelectedColor(); } /** * Sets the current color of the color chooser to the specified color. * The <code>ColorSelectionModel</code> will fire a <code>ChangeEvent</code> * @param color the color to be set in the color chooser * @see JComponent#addPropertyChangeListener * * @beaninfo * bound: false * hidden: false * description: The current color the chooser is to display. */ public void setColor(Color color) { selectionModel.setSelectedColor(color); } /** * Sets the current color of the color chooser to the * specified RGB color. Note that the values of red, green, * and blue should be between the numbers 0 and 255, inclusive. * * @param r an int specifying the amount of Red * @param g an int specifying the amount of Green * @param b an int specifying the amount of Blue * @exception IllegalArgumentException if r,g,b values are out of range * @see java.awt.Color */ public void setColor(int r, int g, int b) { setColor(new Color(r,g,b)); } /** * Sets the current color of the color chooser to the * specified color. * * @param c an integer value that sets the current color in the chooser * where the low-order 8 bits specify the Blue value, * the next 8 bits specify the Green value, and the 8 bits * above that specify the Red value. */ public void setColor(int c) { setColor((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF); } /** * Sets the <code>dragEnabled</code> property, * which must be <code>true</code> to enable * automatic drag handling (the first part of drag and drop) * on this component. * The <code>transferHandler</code> property needs to be set * to a non-<code>null</code> value for the drag to do * anything. The default value of the <code>dragEnabled</code> * property * is <code>false</code>. * * <p> * * When automatic drag handling is enabled, * most look and feels begin a drag-and-drop operation * when the user presses the mouse button over the preview panel. * Some look and feels might not support automatic drag and drop; * they will ignore this property. You can work around such * look and feels by modifying the component * to directly call the <code>exportAsDrag</code> method of a * <code>TransferHandler</code>. * * @param b the value to set the <code>dragEnabled</code> property to * @exception HeadlessException if * <code>b</code> is <code>true</code> and * <code>GraphicsEnvironment.isHeadless()</code> * returns <code>true</code> * * @since 1.4 * * @see java.awt.GraphicsEnvironment#isHeadless * @see #getDragEnabled * @see #setTransferHandler * @see TransferHandler * * @beaninfo * description: Determines whether automatic drag handling is enabled. * bound: false */ public void setDragEnabled(boolean b) { if (b && GraphicsEnvironment.isHeadless()) { throw new HeadlessException(); } dragEnabled = b; } /** * Gets the value of the <code>dragEnabled</code> property. * * @return the value of the <code>dragEnabled</code> property * @see #setDragEnabled * @since 1.4 */ public boolean getDragEnabled() { return dragEnabled; } /** * Sets the current preview panel. * This will fire a <code>PropertyChangeEvent</code> for the property * named "previewPanel". * * @param preview the <code>JComponent</code> which displays the current color * @see JComponent#addPropertyChangeListener * * @beaninfo * bound: true * hidden: true * description: The UI component which displays the current color. */ public void setPreviewPanel(JComponent preview) { if (previewPanel != preview) { JComponent oldPreview = previewPanel; previewPanel = preview; firePropertyChange(JColorChooser.PREVIEW_PANEL_PROPERTY, oldPreview, preview); } } /** * Returns the preview panel that shows a chosen color. * * @return a <code>JComponent</code> object -- the preview panel */ public JComponent getPreviewPanel() { return previewPanel; } /** * Adds a color chooser panel to the color chooser. * * @param panel the <code>AbstractColorChooserPanel</code> to be added */ public void addChooserPanel( AbstractColorChooserPanel panel ) { AbstractColorChooserPanel[] oldPanels = getChooserPanels(); AbstractColorChooserPanel[] newPanels = new AbstractColorChooserPanel[oldPanels.length+1]; System.arraycopy(oldPanels, 0, newPanels, 0, oldPanels.length); newPanels[newPanels.length-1] = panel; setChooserPanels(newPanels); } /** * Removes the Color Panel specified. * * @param panel a string that specifies the panel to be removed * @return the color panel * @exception IllegalArgumentException if panel is not in list of * known chooser panels */ public AbstractColorChooserPanel removeChooserPanel( AbstractColorChooserPanel panel ) { int containedAt = -1; for (int i = 0; i < chooserPanels.length; i++) { if (chooserPanels[i] == panel) { containedAt = i; break; } } if (containedAt == -1) { throw new IllegalArgumentException("chooser panel not in this chooser"); } AbstractColorChooserPanel[] newArray = new AbstractColorChooserPanel[chooserPanels.length-1]; if (containedAt == chooserPanels.length-1) { // at end System.arraycopy(chooserPanels, 0, newArray, 0, newArray.length); } else if (containedAt == 0) { // at start System.arraycopy(chooserPanels, 1, newArray, 0, newArray.length); } else { // in middle System.arraycopy(chooserPanels, 0, newArray, 0, containedAt); System.arraycopy(chooserPanels, containedAt+1, newArray, containedAt, (chooserPanels.length - containedAt - 1)); } setChooserPanels(newArray); return panel; } /** * Specifies the Color Panels used to choose a color value. * * @param panels an array of <code>AbstractColorChooserPanel</code> * objects * * @beaninfo * bound: true * hidden: true * description: An array of different chooser types. */ public void setChooserPanels( AbstractColorChooserPanel[] panels) { AbstractColorChooserPanel[] oldValue = chooserPanels; chooserPanels = panels; firePropertyChange(CHOOSER_PANELS_PROPERTY, oldValue, panels); } /** * Returns the specified color panels. * * @return an array of <code>AbstractColorChooserPanel</code> objects */ public AbstractColorChooserPanel[] getChooserPanels() { return chooserPanels; } /** * Returns the data model that handles color selections. * * @return a <code>ColorSelectionModel</code> object */ public ColorSelectionModel getSelectionModel() { return selectionModel; } /** * Sets the model containing the selected color. * * @param newModel the new <code>ColorSelectionModel</code> object * * @beaninfo * bound: true * hidden: true * description: The model which contains the currently selected color. */ public void setSelectionModel(ColorSelectionModel newModel ) { ColorSelectionModel oldModel = selectionModel; selectionModel = newModel; firePropertyChange(JColorChooser.SELECTION_MODEL_PROPERTY, oldModel, newModel); } /** * See <code>readObject</code> and <code>writeObject</code> in * <code>JComponent</code> for more * information about serialization in Swing. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); if (getUIClassID().equals(uiClassID)) { byte count = JComponent.getWriteObjCounter(this); JComponent.setWriteObjCounter(this, --count); if (count == 0 && ui != null) { ui.installUI(this); } } } /** * Returns a string representation of this <code>JColorChooser</code>. * This method * is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not * be <code>null</code>. * * @return a string representation of this <code>JColorChooser</code> */ protected String paramString() { StringBuffer chooserPanelsString = new StringBuffer(""); for (int i=0; i<chooserPanels.length; i++) { chooserPanelsString.append("[" + chooserPanels[i].toString() + "]"); } String previewPanelString = (previewPanel != null ? previewPanel.toString() : ""); return super.paramString() + ",chooserPanels=" + chooserPanelsString.toString() + ",previewPanel=" + previewPanelString; } ///////////////// // Accessibility support //////////////// protected AccessibleContext accessibleContext = null; /** * Gets the AccessibleContext associated with this JColorChooser. * For color choosers, the AccessibleContext takes the form of an * AccessibleJColorChooser. * A new AccessibleJColorChooser instance is created if necessary. * * @return an AccessibleJColorChooser that serves as the * AccessibleContext of this JColorChooser */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJColorChooser(); } return accessibleContext; } /** * This class implements accessibility support for the * <code>JColorChooser</code> class. It provides an implementation of the * Java Accessibility API appropriate to color chooser user-interface * elements. */ protected class AccessibleJColorChooser extends AccessibleJComponent { /** * Get the role of this object. * * @return an instance of AccessibleRole describing the role of the * object * @see AccessibleRole */ public AccessibleRole getAccessibleRole() { return AccessibleRole.COLOR_CHOOSER; } } // inner class AccessibleJColorChooser } /* * Class which builds a color chooser dialog consisting of * a JColorChooser with "Ok", "Cancel", and "Reset" buttons. * * Note: This needs to be fixed to deal with localization! */ class ColorChooserDialog extends JDialog { private Color initialColor; private JColorChooser chooserPane; private JButton cancelButton; public ColorChooserDialog(Dialog owner, String title, boolean modal, Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { super(owner, title, modal); initColorChooserDialog(c, chooserPane, okListener, cancelListener); } public ColorChooserDialog(Frame owner, String title, boolean modal, Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) throws HeadlessException { super(owner, title, modal); initColorChooserDialog(c, chooserPane, okListener, cancelListener); } protected void initColorChooserDialog(Component c, JColorChooser chooserPane, ActionListener okListener, ActionListener cancelListener) { //setResizable(false); this.chooserPane = chooserPane; Locale locale = getLocale(); String okString = UIManager.getString("ColorChooser.okText", locale); String cancelString = UIManager.getString("ColorChooser.cancelText", locale); String resetString = UIManager.getString("ColorChooser.resetText", locale); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(chooserPane, BorderLayout.CENTER); /* * Create Lower button panel */ JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); JButton okButton = new JButton(okString); getRootPane().setDefaultButton(okButton); okButton.getAccessibleContext().setAccessibleDescription(okString); okButton.setActionCommand("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); if (okListener != null) { okButton.addActionListener(okListener); } buttonPane.add(okButton); cancelButton = new JButton(cancelString); cancelButton.getAccessibleContext().setAccessibleDescription(cancelString); // The following few lines are used to register esc to close the dialog Action cancelKeyAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { ((AbstractButton)e.getSource()).fireActionPerformed(e); } }; KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); InputMap inputMap = cancelButton.getInputMap(JComponent. WHEN_IN_FOCUSED_WINDOW); ActionMap actionMap = cancelButton.getActionMap(); if (inputMap != null && actionMap != null) { inputMap.put(cancelKeyStroke, "cancel"); actionMap.put("cancel", cancelKeyAction); } // end esc handling cancelButton.setActionCommand("cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hide(); } }); if (cancelListener != null) { cancelButton.addActionListener(cancelListener); } buttonPane.add(cancelButton); JButton resetButton = new JButton(resetString); resetButton.getAccessibleContext().setAccessibleDescription(resetString); resetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { reset(); } }); int mnemonic = SwingUtilities2.getUIDefaultsInt("ColorChooser.resetMnemonic", locale, -1); if (mnemonic != -1) { resetButton.setMnemonic(mnemonic); } buttonPane.add(resetButton); contentPane.add(buttonPane, BorderLayout.SOUTH); if (JDialog.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = UIManager.getLookAndFeel().getSupportsWindowDecorations(); if (supportsWindowDecorations) { getRootPane().setWindowDecorationStyle(JRootPane.COLOR_CHOOSER_DIALOG); } } applyComponentOrientation(((c == null) ? getRootPane() : c).getComponentOrientation()); pack(); setLocationRelativeTo(c); this.addWindowListener(new Closer()); } public void show() { initialColor = chooserPane.getColor(); super.show(); } public void reset() { chooserPane.setColor(initialColor); } class Closer extends WindowAdapter implements Serializable{ public void windowClosing(WindowEvent e) { cancelButton.doClick(0); Window w = e.getWindow(); w.hide(); } } static class DisposeOnClose extends ComponentAdapter implements Serializable{ public void componentHidden(ComponentEvent e) { Window w = (Window)e.getComponent(); w.dispose(); } } } class ColorTracker implements ActionListener, Serializable { JColorChooser chooser; Color color; public ColorTracker(JColorChooser c) { chooser = c; } public void actionPerformed(ActionEvent e) { color = chooser.getColor(); } public Color getColor() { return color; } }
6387_11
import greenfoot.*; import java.util.*; /** * * @author R. Springer */ public class Hero extends Mover { private final double gravity; private final double acc; private final double drag; public int leven=3; public int gem=0; public int x= 159; public int y=913; private int frame =1; public String worldName=""; private double snelheid; private int springen; boolean inAir=true; boolean key=false; boolean level2=false; boolean schatkist=false; boolean isDood=false; boolean removedBadGuy=false; GreenfootSound gm =new GreenfootSound("gameSound.wav"); public Hero(String worldName) { super(); gravity = 9.8; acc = 0.6; drag = 0.8; setImage("p1.png"); this.worldName= worldName; } @Override public void act() { if(isDood)//controleert of je dood bent { isDood=false; //isDood = !isDood leven--;// haalt lven er af setLocation(getX(),getY() - 150);// haalt je weg van de tile die je hebt aangeraakt anders gaat leven -2 } music();//achtergrond muziek handleInput();//besturing veer();//jump veer levens();// controleert levens boostSnelheid();//code voor een boost die ervoor zorgt dat je sneller wordt boostSpringen();//code voor een boost die ervoor zorgt dat je hoger kan springen if(!Greenfoot.isKeyDown("k"))//cheat voor als je niet dood wil gaan { doodTile();//cactussen,spikes en lava waardoor je doodn kan gaan enemies();// de spin enemy waardoor je dood kan gaan } getGemBlue();// code voor gems verzamellen hart();// code voor het verzamellen van leven key();// code voor het pakken van de key touchingSchatkist();//code voor het open maken van de schatkist removeBadGuy();// code die de badguy verwijdert en de schatkist toevoegd levels();//code die je naar de volgende level brengt // getPositie();//code die je X en Y positie geeft checkpointVlag();// Code voot j checkpoint die je nieuwe x en y coordinaten geeft if(!removedBadGuy) { atTheEdge();//controleert of de BadGuy bij de edge of de wereld is } velocityX *= drag; velocityY += acc; if (velocityY > gravity) { velocityY = gravity; } applyVelocity(); } public void atTheEdge() { List<BadGuy> badList = this.getWorld().getObjects(BadGuy.class); BadGuy myBadGuy = badList.get(0); boolean atEdge= myBadGuy.atEdge(); if(atEdge==true) { setLocation(x,y); isDood=true; } } public void enemies() { for(Actor enemy:getIntersectingObjects(Enemy.class)) { setLocation(x,y); isDood=true; break; } } public void hart() { if(leven<3) { if(isTouching(Hart.class)) { removeTouching(Hart.class); leven++; } } } public void music() { if(!gm.isPlaying()) { gm.playLoop(); } } public int levens() { if(leven==0) { gm.stop(); Greenfoot.setWorld(new Gameover(worldName)); } return leven; } public double boostSnelheid() { if(isTouching(BoostSnelheid.class)) { removeTouching(BoostSnelheid.class); snelheid+=1.3; } return snelheid; } public int boostSpringen() { if(isTouching(BoostSpring.class)) { removeTouching(BoostSpring.class); springen+=2; } return springen; } public void doodTile() { for (Tile dodelijkeTile : getObjectsInRange(50, DodelijkeTile.class)) { if (dodelijkeTile != null && dodelijkeTile instanceof DodelijkeTile ) { setLocation(x,y); isDood=true; break; } } } public boolean touchingSchatkist() { if(key==true) { if(isTouching(Schatkist.class)) { removeTouching(Schatkist.class); schatkist=true; } } return schatkist; } public void removeBadGuy() { if(isTouching(BadGuy.class)) { removeTouching(BadGuy.class); removedBadGuy=true; if(worldName=="MyWorld1") { this.getWorld().addObject(new Schatkist(),5809,686); } if(worldName=="MyWorld2") { this.getWorld().addObject(new Schatkist(),5987,1285); } if(worldName=="MyWorld3") { this.getWorld().addObject(new Schatkist(),5705,1043); } if(worldName=="MyWorld4") { this.getWorld().addObject(new Schatkist(),5440,385); } return; } } public void levels() { //deur van level 1 naar level 2 for(Actor door:getIntersectingObjects(Door.class)) { if(key==true) { if(door!=null) { if(gem == 13) { if(BadGuy.class !=null) { if(schatkist==true) { Greenfoot.setWorld(new MyWorld2()); String actieveWereld="MyWorld2"; gm.stop(); return; } } } } } break; } //Deur van level2 naar Level 3 for(Actor door:getIntersectingObjects(Door.class)) { if(key==true) { if(door!=null) { if(gem == 22) { if(BadGuy.class !=null) { if(schatkist==true) { Greenfoot.setWorld(new MyWorld3()); String actieveWereld="MyWorld3"; gm.stop(); return; } } } } } break; } //deur van level 3 naar 4 for(Actor door:getIntersectingObjects(Door.class)) { if(key==true) { if(door!=null) { if(gem == 36) { if(BadGuy.class !=null) { if(schatkist==true) { Greenfoot.setWorld(new MyWorld4()); String actieveWereld="MyWorld4"; gm.stop(); return; } } } } } break; } // deur van level 4 naar EIND for(Actor door:getIntersectingObjects(Door.class)) { if(key==true) { if(door!=null) { if(gem == 16) { if(BadGuy.class !=null) { if(schatkist==true) { Greenfoot.setWorld(new EindScherm()); String actieveWereld="EindScherm"; gm.stop(); return; } } } } } break; } } public void checkpointVlag() { if(isTouching(Checkpoint.class)) { x=getX(); y=getY(); } } public String getPositie() { String positiexy= "X: "+this.getX() +" Y: "+this.getY(); return positiexy; } public int getGemBlue() { if(isTouching(GemBlueTile.class)) { removeTouching(GemBlueTile.class); Greenfoot.playSound("gemSound.wav"); gem++; } return gem; } public boolean key() { if(isTouching(Key.class)) { removeTouching(Key.class); key=true; } return key; } public void handleInput() { if (isTouching(MovingPlatform.class)) { velocityY = -1; if (Greenfoot.isKeyDown("UP")||Greenfoot.isKeyDown("Space")) { velocityY = -14; Greenfoot.playSound("jumpSound.wav"); } } for (Actor Hero: getIntersectingObjects(JumpTile.class)) { if (Greenfoot.isKeyDown("UP")||Greenfoot.isKeyDown("Space")) { inAir=true; velocityY = -15-springen; Greenfoot.playSound("jumpSound.wav"); setImage("p1_jump.png"); } else { inAir=false; } } if (Greenfoot.isKeyDown("Left")) { velocityX = -6.00-snelheid; framesLinks(); } else if (Greenfoot.isKeyDown("Right")) { velocityX = 6.00+snelheid; framesRechts(); } } public void veer() { for(Tile tile:getIntersectingObjects(SpringboardUpTile.class)) { if(tile!=null) { velocityY=-22; } } } public void framesRechts() { if(frame==1) { setImage("p1_walk01.png"); } if(frame==2) { setImage("p1_walk02.png"); } if(frame==3) { setImage("p1_walk03.png"); } if(frame==4) { setImage("p1_walk04.png"); } if(frame==5) { setImage("p1_walk05.png"); } if(frame==6) { setImage("p1_walk06.png"); } if(frame==7) { setImage("p1_walk07.png"); } if(frame==8) { setImage("p1_walk08.png"); } if(frame==9) { setImage("p1_walk09.png"); } if(frame==10) { setImage("p1_walk10.png"); } if(frame==11) { setImage("p1_walk11.png"); frame=1; return ; } frame++; } public void framesLinks() { if(frame==1) { setImage("p1_links_walk01.png"); } if(frame==2) { setImage("p1_links_walk02.png"); } if(frame==3) { setImage("p1_links_walk03.png"); } if(frame==4) { setImage("p1_links_walk04.png"); } if(frame==5) { setImage("p1_links_walk05.png"); } if(frame==6) { setImage("p1_links_walk06.png"); } if(frame==7) { setImage("p1_links_walk07.png"); } if(frame==8) { setImage("p1_links_walk08.png"); } if(frame==9) { setImage("p1_links_walk09.png"); } if(frame==10) { setImage("p1_links_walk10.png"); } if(frame==11) { setImage("p1_links_walk11.png"); frame=1; return ; } frame++; } public int getWidth() { return getImage().getWidth(); } public int getHeight() { return getImage().getHeight(); } }
ROCMondriaanTIN/project-greenfoot-game-ahmed-ben10
Hero.java
3,493
// code voor het verzamellen van leven
line_comment
nl
import greenfoot.*; import java.util.*; /** * * @author R. Springer */ public class Hero extends Mover { private final double gravity; private final double acc; private final double drag; public int leven=3; public int gem=0; public int x= 159; public int y=913; private int frame =1; public String worldName=""; private double snelheid; private int springen; boolean inAir=true; boolean key=false; boolean level2=false; boolean schatkist=false; boolean isDood=false; boolean removedBadGuy=false; GreenfootSound gm =new GreenfootSound("gameSound.wav"); public Hero(String worldName) { super(); gravity = 9.8; acc = 0.6; drag = 0.8; setImage("p1.png"); this.worldName= worldName; } @Override public void act() { if(isDood)//controleert of je dood bent { isDood=false; //isDood = !isDood leven--;// haalt lven er af setLocation(getX(),getY() - 150);// haalt je weg van de tile die je hebt aangeraakt anders gaat leven -2 } music();//achtergrond muziek handleInput();//besturing veer();//jump veer levens();// controleert levens boostSnelheid();//code voor een boost die ervoor zorgt dat je sneller wordt boostSpringen();//code voor een boost die ervoor zorgt dat je hoger kan springen if(!Greenfoot.isKeyDown("k"))//cheat voor als je niet dood wil gaan { doodTile();//cactussen,spikes en lava waardoor je doodn kan gaan enemies();// de spin enemy waardoor je dood kan gaan } getGemBlue();// code voor gems verzamellen hart();// code voor<SUF> key();// code voor het pakken van de key touchingSchatkist();//code voor het open maken van de schatkist removeBadGuy();// code die de badguy verwijdert en de schatkist toevoegd levels();//code die je naar de volgende level brengt // getPositie();//code die je X en Y positie geeft checkpointVlag();// Code voot j checkpoint die je nieuwe x en y coordinaten geeft if(!removedBadGuy) { atTheEdge();//controleert of de BadGuy bij de edge of de wereld is } velocityX *= drag; velocityY += acc; if (velocityY > gravity) { velocityY = gravity; } applyVelocity(); } public void atTheEdge() { List<BadGuy> badList = this.getWorld().getObjects(BadGuy.class); BadGuy myBadGuy = badList.get(0); boolean atEdge= myBadGuy.atEdge(); if(atEdge==true) { setLocation(x,y); isDood=true; } } public void enemies() { for(Actor enemy:getIntersectingObjects(Enemy.class)) { setLocation(x,y); isDood=true; break; } } public void hart() { if(leven<3) { if(isTouching(Hart.class)) { removeTouching(Hart.class); leven++; } } } public void music() { if(!gm.isPlaying()) { gm.playLoop(); } } public int levens() { if(leven==0) { gm.stop(); Greenfoot.setWorld(new Gameover(worldName)); } return leven; } public double boostSnelheid() { if(isTouching(BoostSnelheid.class)) { removeTouching(BoostSnelheid.class); snelheid+=1.3; } return snelheid; } public int boostSpringen() { if(isTouching(BoostSpring.class)) { removeTouching(BoostSpring.class); springen+=2; } return springen; } public void doodTile() { for (Tile dodelijkeTile : getObjectsInRange(50, DodelijkeTile.class)) { if (dodelijkeTile != null && dodelijkeTile instanceof DodelijkeTile ) { setLocation(x,y); isDood=true; break; } } } public boolean touchingSchatkist() { if(key==true) { if(isTouching(Schatkist.class)) { removeTouching(Schatkist.class); schatkist=true; } } return schatkist; } public void removeBadGuy() { if(isTouching(BadGuy.class)) { removeTouching(BadGuy.class); removedBadGuy=true; if(worldName=="MyWorld1") { this.getWorld().addObject(new Schatkist(),5809,686); } if(worldName=="MyWorld2") { this.getWorld().addObject(new Schatkist(),5987,1285); } if(worldName=="MyWorld3") { this.getWorld().addObject(new Schatkist(),5705,1043); } if(worldName=="MyWorld4") { this.getWorld().addObject(new Schatkist(),5440,385); } return; } } public void levels() { //deur van level 1 naar level 2 for(Actor door:getIntersectingObjects(Door.class)) { if(key==true) { if(door!=null) { if(gem == 13) { if(BadGuy.class !=null) { if(schatkist==true) { Greenfoot.setWorld(new MyWorld2()); String actieveWereld="MyWorld2"; gm.stop(); return; } } } } } break; } //Deur van level2 naar Level 3 for(Actor door:getIntersectingObjects(Door.class)) { if(key==true) { if(door!=null) { if(gem == 22) { if(BadGuy.class !=null) { if(schatkist==true) { Greenfoot.setWorld(new MyWorld3()); String actieveWereld="MyWorld3"; gm.stop(); return; } } } } } break; } //deur van level 3 naar 4 for(Actor door:getIntersectingObjects(Door.class)) { if(key==true) { if(door!=null) { if(gem == 36) { if(BadGuy.class !=null) { if(schatkist==true) { Greenfoot.setWorld(new MyWorld4()); String actieveWereld="MyWorld4"; gm.stop(); return; } } } } } break; } // deur van level 4 naar EIND for(Actor door:getIntersectingObjects(Door.class)) { if(key==true) { if(door!=null) { if(gem == 16) { if(BadGuy.class !=null) { if(schatkist==true) { Greenfoot.setWorld(new EindScherm()); String actieveWereld="EindScherm"; gm.stop(); return; } } } } } break; } } public void checkpointVlag() { if(isTouching(Checkpoint.class)) { x=getX(); y=getY(); } } public String getPositie() { String positiexy= "X: "+this.getX() +" Y: "+this.getY(); return positiexy; } public int getGemBlue() { if(isTouching(GemBlueTile.class)) { removeTouching(GemBlueTile.class); Greenfoot.playSound("gemSound.wav"); gem++; } return gem; } public boolean key() { if(isTouching(Key.class)) { removeTouching(Key.class); key=true; } return key; } public void handleInput() { if (isTouching(MovingPlatform.class)) { velocityY = -1; if (Greenfoot.isKeyDown("UP")||Greenfoot.isKeyDown("Space")) { velocityY = -14; Greenfoot.playSound("jumpSound.wav"); } } for (Actor Hero: getIntersectingObjects(JumpTile.class)) { if (Greenfoot.isKeyDown("UP")||Greenfoot.isKeyDown("Space")) { inAir=true; velocityY = -15-springen; Greenfoot.playSound("jumpSound.wav"); setImage("p1_jump.png"); } else { inAir=false; } } if (Greenfoot.isKeyDown("Left")) { velocityX = -6.00-snelheid; framesLinks(); } else if (Greenfoot.isKeyDown("Right")) { velocityX = 6.00+snelheid; framesRechts(); } } public void veer() { for(Tile tile:getIntersectingObjects(SpringboardUpTile.class)) { if(tile!=null) { velocityY=-22; } } } public void framesRechts() { if(frame==1) { setImage("p1_walk01.png"); } if(frame==2) { setImage("p1_walk02.png"); } if(frame==3) { setImage("p1_walk03.png"); } if(frame==4) { setImage("p1_walk04.png"); } if(frame==5) { setImage("p1_walk05.png"); } if(frame==6) { setImage("p1_walk06.png"); } if(frame==7) { setImage("p1_walk07.png"); } if(frame==8) { setImage("p1_walk08.png"); } if(frame==9) { setImage("p1_walk09.png"); } if(frame==10) { setImage("p1_walk10.png"); } if(frame==11) { setImage("p1_walk11.png"); frame=1; return ; } frame++; } public void framesLinks() { if(frame==1) { setImage("p1_links_walk01.png"); } if(frame==2) { setImage("p1_links_walk02.png"); } if(frame==3) { setImage("p1_links_walk03.png"); } if(frame==4) { setImage("p1_links_walk04.png"); } if(frame==5) { setImage("p1_links_walk05.png"); } if(frame==6) { setImage("p1_links_walk06.png"); } if(frame==7) { setImage("p1_links_walk07.png"); } if(frame==8) { setImage("p1_links_walk08.png"); } if(frame==9) { setImage("p1_links_walk09.png"); } if(frame==10) { setImage("p1_links_walk10.png"); } if(frame==11) { setImage("p1_links_walk11.png"); frame=1; return ; } frame++; } public int getWidth() { return getImage().getWidth(); } public int getHeight() { return getImage().getHeight(); } }
25518_4
import java.util.*; import java.util.concurrent.TimeUnit; // EXTREME DIFFICULTY: // 040000000000001803037060500060010000005306400000090020008050760906800000000000010 // input van de opdracht // 000820090500000000308040007100000040006402503000090010093004000004035200000700900 public class Sudoku { int boardSize; ArrayList<ArrayList<Cell>> board = new ArrayList<ArrayList<Cell>>(); Sudoku(String input) { this.boardSize = 9; this.board = this.initialize(input); } public ArrayList<ArrayList<Cell>> initialize(String input){ char[] inputArr = input.toCharArray(); // maak in het bord 9 ArrayLists<Cell> aan for(int i = 0; i < this.boardSize; i++){ this.board.add( new ArrayList<Cell>() ); } // loop dan door de input heen int index = 0; for(int i = 0; i < inputArr.length; i++){ /** beetje hacky maar 0 % 9 == ook 0, en we willen pas incrementen als ie daadwerkelijk een veelvoud van 9 is: */ if(i % boardSize == 0){ if(i != 0) { index+=1; } } // vul het grid met nieuwe cells Cell newCell = new Cell(); newCell.setXpos(index); // row newCell.setYpos(i % boardSize); // col newCell.setVal(Character.getNumericValue(inputArr[i])); this.board.get(index).add( newCell ); } this.display(); return this.board; } public boolean isLegalMove(Cell cell, int val) { // loop horizontal // {1,2,3,4,5,6,7,8,9} for (int i = 0; i < this.boardSize; i++) { if (this.board.get( cell.getXpos() ).get(i).getVal() == val) { return false; } } // loop vertical // {1} // {2} // {3} for (int j = 0; j < this.boardSize; j++) { if (this.board.get(j).get(cell.getYpos()).getVal() == val) { return false; } } // check unit van 3x3 // {1,2,3} // {1,2,3} // {1,2,3} int boxRow = cell.getXpos() - (cell.getXpos() % 3); int boxColumn = cell.getYpos() - (cell.getYpos() % 3); for (int j = 0; j < 3; j++) { for (int i = 0; i < 3; i++) { if (this.board.get(boxRow + j).get(boxColumn + i).getVal() == val) { return false; } } } return true; } public void solve() { // start de chain, als het false returned is het onmogelijk om te solven if (!backtrackSolve()) { System.out.println("impossible"); System.exit(0); } else { this.display(); System.out.println("yay :-)"); } } public boolean backtrackSolve() { Cell cell = new Cell(); // this.display(); // loop door alle cells, en begin bij de eerste lege cell die we vinden outerloop: for (int row = 0; row < this.boardSize; row++) { for (int col = 0; col < this.boardSize; col++) { cell = this.board.get(row).get(col); if ( cell.getIsEmpty() ) { // als deze cell leeg is, gaan we met deze cell werken // als we niet breaken gaat ie pas solven vanaf de laatste lege tile // wat opzich geen probleem zou moeten zijn break outerloop; } } } // als alle vals gevuld zijn, dan hebben we het einde gehaald // als de laatste cell NIET leeg is, zijn er dus geen lege cells meer if ( !cell.getIsEmpty() ) { return true; } // else, probeer values // loop 1-9 for (int val = 1; val < this.boardSize+1; val++) { // probeer alle mogelijkheden op deze cell en kijk of het legal is if ( this.isLegalMove(cell, val) ) { cell.setVal(val); // probeer de rest van het bord op te lossen met de huidige zet // als dat lukt, return true, lukt het niet, zet de val op 0 // dit is de bottleneck if ( this.backtrackSolve() ) { return true; } // als de move niet uitkomt op een goede oplossing, reset, try again cell.setVal(0); } } return false; //backtrack } public void display(){ System.out.println("\n-------------------"); for(int i = 0; i < this.board.size(); i++){ for(int j = 0; j < this.board.get(i).size(); j++){ String icon = this.board.get(i).get(j).getVal() == 0 ? " " : Integer.toString(this.board.get(i).get(j).getVal()); if(j == 8){ System.out.print("|" + icon + "|"); } else { System.out.print("|" + icon); } } System.out.println("\n-------------------"); } } }
thepassle/software-engineering-training
java-exercises/opdracht13-sudoku/Sudoku.java
1,571
// vul het grid met nieuwe cells
line_comment
nl
import java.util.*; import java.util.concurrent.TimeUnit; // EXTREME DIFFICULTY: // 040000000000001803037060500060010000005306400000090020008050760906800000000000010 // input van de opdracht // 000820090500000000308040007100000040006402503000090010093004000004035200000700900 public class Sudoku { int boardSize; ArrayList<ArrayList<Cell>> board = new ArrayList<ArrayList<Cell>>(); Sudoku(String input) { this.boardSize = 9; this.board = this.initialize(input); } public ArrayList<ArrayList<Cell>> initialize(String input){ char[] inputArr = input.toCharArray(); // maak in het bord 9 ArrayLists<Cell> aan for(int i = 0; i < this.boardSize; i++){ this.board.add( new ArrayList<Cell>() ); } // loop dan door de input heen int index = 0; for(int i = 0; i < inputArr.length; i++){ /** beetje hacky maar 0 % 9 == ook 0, en we willen pas incrementen als ie daadwerkelijk een veelvoud van 9 is: */ if(i % boardSize == 0){ if(i != 0) { index+=1; } } // vul het<SUF> Cell newCell = new Cell(); newCell.setXpos(index); // row newCell.setYpos(i % boardSize); // col newCell.setVal(Character.getNumericValue(inputArr[i])); this.board.get(index).add( newCell ); } this.display(); return this.board; } public boolean isLegalMove(Cell cell, int val) { // loop horizontal // {1,2,3,4,5,6,7,8,9} for (int i = 0; i < this.boardSize; i++) { if (this.board.get( cell.getXpos() ).get(i).getVal() == val) { return false; } } // loop vertical // {1} // {2} // {3} for (int j = 0; j < this.boardSize; j++) { if (this.board.get(j).get(cell.getYpos()).getVal() == val) { return false; } } // check unit van 3x3 // {1,2,3} // {1,2,3} // {1,2,3} int boxRow = cell.getXpos() - (cell.getXpos() % 3); int boxColumn = cell.getYpos() - (cell.getYpos() % 3); for (int j = 0; j < 3; j++) { for (int i = 0; i < 3; i++) { if (this.board.get(boxRow + j).get(boxColumn + i).getVal() == val) { return false; } } } return true; } public void solve() { // start de chain, als het false returned is het onmogelijk om te solven if (!backtrackSolve()) { System.out.println("impossible"); System.exit(0); } else { this.display(); System.out.println("yay :-)"); } } public boolean backtrackSolve() { Cell cell = new Cell(); // this.display(); // loop door alle cells, en begin bij de eerste lege cell die we vinden outerloop: for (int row = 0; row < this.boardSize; row++) { for (int col = 0; col < this.boardSize; col++) { cell = this.board.get(row).get(col); if ( cell.getIsEmpty() ) { // als deze cell leeg is, gaan we met deze cell werken // als we niet breaken gaat ie pas solven vanaf de laatste lege tile // wat opzich geen probleem zou moeten zijn break outerloop; } } } // als alle vals gevuld zijn, dan hebben we het einde gehaald // als de laatste cell NIET leeg is, zijn er dus geen lege cells meer if ( !cell.getIsEmpty() ) { return true; } // else, probeer values // loop 1-9 for (int val = 1; val < this.boardSize+1; val++) { // probeer alle mogelijkheden op deze cell en kijk of het legal is if ( this.isLegalMove(cell, val) ) { cell.setVal(val); // probeer de rest van het bord op te lossen met de huidige zet // als dat lukt, return true, lukt het niet, zet de val op 0 // dit is de bottleneck if ( this.backtrackSolve() ) { return true; } // als de move niet uitkomt op een goede oplossing, reset, try again cell.setVal(0); } } return false; //backtrack } public void display(){ System.out.println("\n-------------------"); for(int i = 0; i < this.board.size(); i++){ for(int j = 0; j < this.board.get(i).size(); j++){ String icon = this.board.get(i).get(j).getVal() == 0 ? " " : Integer.toString(this.board.get(i).get(j).getVal()); if(j == 8){ System.out.print("|" + icon + "|"); } else { System.out.print("|" + icon); } } System.out.println("\n-------------------"); } } }
32372_3
import SortingAlgorithms.SortingAlgorithm; public class ThreadManager { private Thread sortingThread; // private SortingAlgorithm sortingAlgorithm; public void setSortingAlgorithm(SortingAlgorithm sa) { // sortingAlgorithm = sa; } // TODO: if thread is started, start should be grayed out and reset should be clickable. Also when thread is done. Can we listen for thread finish event? public void startSorting(SortingAlgorithm sortingAlgorithm) { if (sortingThread == null && sortingAlgorithm != null) { sortingThread = new Thread(sortingAlgorithm::run); sortingThread.start(); } else { resumeSorting(); } } public void resumeSorting() { try { sortingThread.notify(); } catch (Exception ignored) { System.out.println("Could not resume thread"); } } // TODO: kan start of moet ik resume hierna doen? & hoe houdt ie state bij van de array??? // tuurlijk als ik continue gaat gwn die thread verder, duhh, nee dat is niet, die // sortingAlgorithm is dan tot een bepaald punt gesorteerd en daar gaat ie gwn op verder! // Met een nieuwe thread. public void pauseSorting() { try { sortingThread.suspend(); // sortingThread.wait(); // TODO: test better than suspend. } catch (Exception ignored) { System.out.println("Could not suspend thread"); } } public void stopSorting() { if (sortingThread != null) { // sortingThread.stop(); sortingThread.interrupt(); // TODO: test interrupt better than stop? this.sortingThread = null; } } }
JanBelterman/visualsort
src/ThreadManager.java
405
// TODO: kan start of moet ik resume hierna doen? & hoe houdt ie state bij van de array???
line_comment
nl
import SortingAlgorithms.SortingAlgorithm; public class ThreadManager { private Thread sortingThread; // private SortingAlgorithm sortingAlgorithm; public void setSortingAlgorithm(SortingAlgorithm sa) { // sortingAlgorithm = sa; } // TODO: if thread is started, start should be grayed out and reset should be clickable. Also when thread is done. Can we listen for thread finish event? public void startSorting(SortingAlgorithm sortingAlgorithm) { if (sortingThread == null && sortingAlgorithm != null) { sortingThread = new Thread(sortingAlgorithm::run); sortingThread.start(); } else { resumeSorting(); } } public void resumeSorting() { try { sortingThread.notify(); } catch (Exception ignored) { System.out.println("Could not resume thread"); } } // TODO: kan<SUF> // tuurlijk als ik continue gaat gwn die thread verder, duhh, nee dat is niet, die // sortingAlgorithm is dan tot een bepaald punt gesorteerd en daar gaat ie gwn op verder! // Met een nieuwe thread. public void pauseSorting() { try { sortingThread.suspend(); // sortingThread.wait(); // TODO: test better than suspend. } catch (Exception ignored) { System.out.println("Could not suspend thread"); } } public void stopSorting() { if (sortingThread != null) { // sortingThread.stop(); sortingThread.interrupt(); // TODO: test interrupt better than stop? this.sortingThread = null; } } }
57040_20
package woordenapplicatie.gui; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextArea; /** * FXML Controller class * * @author frankcoenen */ public class WoordenController implements Initializable { private static final String DEFAULT_TEXT = "Een, twee, drie, vier\n" + "Hoedje van, hoedje van\n" + "Een, twee, drie, vier\n" + "Hoedje van papier\n" + "\n" + "Heb je dan geen hoedje meer\n" + "Maak er één van bordpapier\n" + "Eén, twee, drie, vier\n" + "Hoedje van papier\n" + "\n" + "Een, twee, drie, vier\n" + "Hoedje van, hoedje van\n" + "Een, twee, drie, vier\n" + "Hoedje van papier\n" + "\n" + "En als het hoedje dan niet past\n" + "Zetten we 't in de glazenkas\n" + "Een, twee, drie, vier\n" + "Hoedje van papier"; @FXML private Button btAantal; @FXML private TextArea taInput; @FXML private Button btSorteer; @FXML private Button btFrequentie; @FXML private Button btConcordantie; @FXML private TextArea taOutput; @Override public void initialize(URL location, ResourceBundle resources) { taInput.setText(DEFAULT_TEXT); } @FXML private void aantalAction(ActionEvent event) { taOutput.setText(Aantal(taInput.getText())); } public static String Aantal(String tekst) { Collection henk = new ArrayList<>(); String text = tekst.toLowerCase().replace("\r", " ").replace(",", "").replace("\n", " "); // Weghalen van comma's en enters for (String s : text.split(" ")) { //Constant ( N ) henk.add(s.trim()); // weghalen onnodige spaties en toevoegen aan de lijst } Set hashhenk = new HashSet<>(henk); //omzetten naar HashSet om unieke resultaten te krijgen String out = "Totaal aantal woorden: " + henk.size() + "\n Aantal verschillende woorden: " + hashhenk.size(); return out; } @FXML private void sorteerAction(ActionEvent event) { taOutput.setText(Sorteer(taInput.getText())); } public static String Sorteer(String tekst) { Collection henk = new HashSet<>(); String text = tekst.toLowerCase().replace("\r", " ").replace(",", "").replace("\n", " "); // Weghalen van comma's en enters for (String s : text.split(" ")) { //Constant ( N ) henk.add(s.trim()); // weghalen onnodige spaties en toevoegen aan de lijst } Set hashhenk = new TreeSet<>(Collections.reverseOrder()); //Aanmaken van een gesorteerde treeset die DESC sorteert hashhenk.addAll(henk);// Het toevoegen van alle items. return hashhenk + ""; } @FXML private void frequentieAction(ActionEvent event) { taOutput.setText(Frequentie(taInput.getText())); } public static String Frequentie(String tekst) { Map henkmap = new HashMap(); //Unieke waarden voor frquentie analyse Collection henklist = new ArrayList<>(); //Houd index en maakt het mogelijk om doorheen te lopen. String text = tekst.toLowerCase().replace("\r", " ").replace(",", "").replace("\n", " "); // Weghalen van comma's en enters for (String s : text.split(" ")) { //Constant ( N ) if (henkmap.containsKey(s)) { henkmap.replace(s, (int) henkmap.get(s) + 1); //Aanpassen van de waarde van een element } else { henkmap.put(s, 1); //Ininteren van een element } } String output = ""; henkmap.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(entry -> henklist.add(entry.toString() + "\n")); //Sorteren map op value return henklist.toString(); } @FXML private void concordatieAction(ActionEvent event) { taOutput.setText(Concordantie(taInput.getText())); } public static String Concordantie(String tekst) { //Aanmaken van de map gekozen voor een treemap vanwege automatisch op volgorde zetten. Map henkmap = new TreeMap(); //aanmaken van een int voor de referentie. int i = 1; //lijn ophalen om te kijken waar de woorden staan. for (String line : tekst.split("\n")) { //Constant ( N ) //woord voor woord gaan kijken of dat het bestaat in de treemap. zo niet voeg het toe aan de map, anders updaten van de value for (String word : line.split(" ")) { //Constant ( N ) word = word.replaceAll(",| ", ""); if (henkmap.containsKey(word)) { henkmap.replace(word, henkmap.get(word) + " " + String.valueOf(i)); } else { henkmap.put(word, String.valueOf(i)); } } //naar de volgende regel i++; } //omzetten naar text voor de TextArea. String output = ""; for (Object s : henkmap.keySet()) { //Constant ( N ) output += s + ": " + henkmap.get(s) + "\n"; } return output; } }
94BasMulder/JCF4MitStijn
WoordenApplicatie/src/woordenapplicatie/gui/WoordenController.java
1,641
//lijn ophalen om te kijken waar de woorden staan.
line_comment
nl
package woordenapplicatie.gui; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextArea; /** * FXML Controller class * * @author frankcoenen */ public class WoordenController implements Initializable { private static final String DEFAULT_TEXT = "Een, twee, drie, vier\n" + "Hoedje van, hoedje van\n" + "Een, twee, drie, vier\n" + "Hoedje van papier\n" + "\n" + "Heb je dan geen hoedje meer\n" + "Maak er één van bordpapier\n" + "Eén, twee, drie, vier\n" + "Hoedje van papier\n" + "\n" + "Een, twee, drie, vier\n" + "Hoedje van, hoedje van\n" + "Een, twee, drie, vier\n" + "Hoedje van papier\n" + "\n" + "En als het hoedje dan niet past\n" + "Zetten we 't in de glazenkas\n" + "Een, twee, drie, vier\n" + "Hoedje van papier"; @FXML private Button btAantal; @FXML private TextArea taInput; @FXML private Button btSorteer; @FXML private Button btFrequentie; @FXML private Button btConcordantie; @FXML private TextArea taOutput; @Override public void initialize(URL location, ResourceBundle resources) { taInput.setText(DEFAULT_TEXT); } @FXML private void aantalAction(ActionEvent event) { taOutput.setText(Aantal(taInput.getText())); } public static String Aantal(String tekst) { Collection henk = new ArrayList<>(); String text = tekst.toLowerCase().replace("\r", " ").replace(",", "").replace("\n", " "); // Weghalen van comma's en enters for (String s : text.split(" ")) { //Constant ( N ) henk.add(s.trim()); // weghalen onnodige spaties en toevoegen aan de lijst } Set hashhenk = new HashSet<>(henk); //omzetten naar HashSet om unieke resultaten te krijgen String out = "Totaal aantal woorden: " + henk.size() + "\n Aantal verschillende woorden: " + hashhenk.size(); return out; } @FXML private void sorteerAction(ActionEvent event) { taOutput.setText(Sorteer(taInput.getText())); } public static String Sorteer(String tekst) { Collection henk = new HashSet<>(); String text = tekst.toLowerCase().replace("\r", " ").replace(",", "").replace("\n", " "); // Weghalen van comma's en enters for (String s : text.split(" ")) { //Constant ( N ) henk.add(s.trim()); // weghalen onnodige spaties en toevoegen aan de lijst } Set hashhenk = new TreeSet<>(Collections.reverseOrder()); //Aanmaken van een gesorteerde treeset die DESC sorteert hashhenk.addAll(henk);// Het toevoegen van alle items. return hashhenk + ""; } @FXML private void frequentieAction(ActionEvent event) { taOutput.setText(Frequentie(taInput.getText())); } public static String Frequentie(String tekst) { Map henkmap = new HashMap(); //Unieke waarden voor frquentie analyse Collection henklist = new ArrayList<>(); //Houd index en maakt het mogelijk om doorheen te lopen. String text = tekst.toLowerCase().replace("\r", " ").replace(",", "").replace("\n", " "); // Weghalen van comma's en enters for (String s : text.split(" ")) { //Constant ( N ) if (henkmap.containsKey(s)) { henkmap.replace(s, (int) henkmap.get(s) + 1); //Aanpassen van de waarde van een element } else { henkmap.put(s, 1); //Ininteren van een element } } String output = ""; henkmap.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(entry -> henklist.add(entry.toString() + "\n")); //Sorteren map op value return henklist.toString(); } @FXML private void concordatieAction(ActionEvent event) { taOutput.setText(Concordantie(taInput.getText())); } public static String Concordantie(String tekst) { //Aanmaken van de map gekozen voor een treemap vanwege automatisch op volgorde zetten. Map henkmap = new TreeMap(); //aanmaken van een int voor de referentie. int i = 1; //lijn ophalen<SUF> for (String line : tekst.split("\n")) { //Constant ( N ) //woord voor woord gaan kijken of dat het bestaat in de treemap. zo niet voeg het toe aan de map, anders updaten van de value for (String word : line.split(" ")) { //Constant ( N ) word = word.replaceAll(",| ", ""); if (henkmap.containsKey(word)) { henkmap.replace(word, henkmap.get(word) + " " + String.valueOf(i)); } else { henkmap.put(word, String.valueOf(i)); } } //naar de volgende regel i++; } //omzetten naar text voor de TextArea. String output = ""; for (Object s : henkmap.keySet()) { //Constant ( N ) output += s + ": " + henkmap.get(s) + "\n"; } return output; } }
17882_23
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.zorgvraagtypering.ZVTDecisionTree; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; /** * * @author Siree */ public interface DecisionTree { public static double calculateWeightedEntropy(ArrayList<PatientWithZVT> patientsLeft, ArrayList<PatientWithZVT> patientsRight) { double entropyLeft = entropy(patientsLeft); double entropyRight = entropy(patientsRight); int population = patientsLeft.size() + patientsRight.size(); return (entropyLeft * patientsLeft.size() + entropyRight * patientsRight.size()) / population; } public static double entropy(ArrayList<PatientWithZVT> patients) { assert !patients.isEmpty(); double totaal = 0; for (int nrOfPt : tel_PtperZVT(patients)) { double proportion = nrOfPt / (double) patients.size(); if (proportion != 0) { totaal -= proportion * Math.log(proportion); } } return totaal; } public static int berekenMeestvoorkomendeZVT(ArrayList<PatientWithZVT> trainingGroup) { //N is totaal aantal pt's in node int N = trainingGroup.size(); int[] ptperZVT = tel_PtperZVT(trainingGroup); int meestvoorkomendeZVT = 0; int max = 0; //bij equal gesplitste populatie maakt het voor de max niks uit, max behoudt dezelfde waarde for (int i = 0; i < ptperZVT.length; i++) { if (ptperZVT[i] > max) { max = ptperZVT[i]; meestvoorkomendeZVT = convertFromIndexToZVT(i); } } return meestvoorkomendeZVT; } public int typeer(Patient patient); public void print(String indent); /* interne infrastructuurklasse zodat createNode een decisiontree en diens errorvalue kan teruggeven */ class TreeAndE { DecisionTree decisiontree; double e; public TreeAndE(DecisionTree decisiontree, double e) { this.decisiontree = decisiontree; this.e = e; } } /* 1. loop over alle vragen en thresholds 1.a groepeer alle patiënten aan hun kant van de threshold 1.b meet hoe tevreden je bent met de split (meet entropy (https://towardsdatascience.com/entropy-and-information-gain-in-decision-trees-c7db67a3a293) en sla de split op als die beter is 2. maak the node met de gegevens van stap 1 3. doe the pruning Pruning perpectief van de nodeFork die mogelijk een nodeLeaf wordt stap 1: bereken de f en de e. De f is E/N (aantal pt's in node met een ander zvt dan het meerendeel van de pt's in die node zitten gedeeld door het aantal in de node (wat N is)). De e is de ophoging van f van je decision tree. F moet worden opgehoogd omdat de decision tree overgefit is op de data. De c is 0.25 standaard, z is dan 0.69. stap 2a:bereken de f en e van de linker node stap 2b:bereken de f en de e van de rechter node stap 3: combineer de f en de e van de linker en rechter node stap 4: vergelijk de gecombineerde e met je eigen e stap 5a:als hun gecombineerde e groter is, tranformeer tot een leaf node stap 5b:als hun gecombineerde e kleiner of gelijk is, herhaal de stappen voor zowel de linker child node als de rechter childe node */ public static TreeAndE createNode(ArrayList<PatientWithZVT> trainingGroup, double z) { //Kijk of alle patiënten dezelfde zorgvraagtypering hebben, zo ja dan return je een nodeleaf int zorgvraagtypering = trainingGroup.get(0).zorgvraagtype; //stap 3.1 pruning double e = calculateTrueErrorValue(trainingGroup, z); boolean oneZorgvraagtypering = true; for (var pt : trainingGroup) { //Je vergelijkt ieders zorgvraagtype met de zorgvraagtype van de eerste patiënt. Als niet iedereen hetzelfde is, moet je een split maken //en niet een node leaf. Anders eindigt hier de recursie. if (zorgvraagtypering != pt.zorgvraagtype) { oneZorgvraagtypering = false; } } if (oneZorgvraagtypering) { //iedereen heeft hetzelfde label return new TreeAndE(new NodeLeaf(zorgvraagtypering), e); } double bestValueOfSplit = Double.POSITIVE_INFINITY; //Double.Postitive_infinity is een extreem hoge waarde. Hoe schever de de verdeling over de //zorgvraagtyperingen, hoe lager de entropy(wat beter is) ArrayList<PatientWithZVT> goodSplitofPatientsLeft = null; // is null omdat bestValueOfSplit altijd het allerslechte is en dus goodSplitofPatiensLeft //altijd wordt gevuld ArrayList<PatientWithZVT> goodSplitofPatientsRight = null;// is null omdat bestValueOfSplit altijd het allerslechte is en dus goodSplitofPatiensRight //altijd wordt gevuld int nodeForkHonosVraag = 0; int nodeForkThreshold = 0; //zie stap 1 en 1.a for (int honosVraag = 0; honosVraag < 12; honosVraag++) { for (int threshold = 0; threshold < 5; threshold++) { ArrayList<PatientWithZVT> patientsLeft = new ArrayList<PatientWithZVT>(); ArrayList<PatientWithZVT> patientsRight = new ArrayList<PatientWithZVT>(); for (var patient : trainingGroup) { if (patient.patient.honosScore[honosVraag] < threshold) { patientsLeft.add(patient); } else { patientsRight.add(patient); } } if (patientsLeft.isEmpty()) { continue; } if (patientsRight.isEmpty()) { continue; } //zie stap 1.b double valueOfSplit = calculateWeightedEntropy(patientsLeft, patientsRight); if (valueOfSplit < bestValueOfSplit) { bestValueOfSplit = valueOfSplit; goodSplitofPatientsLeft = patientsLeft; goodSplitofPatientsRight = patientsRight; nodeForkHonosVraag = honosVraag; nodeForkThreshold = threshold; } } } int meestVoorkomendeZVTInGroep = berekenMeestvoorkomendeZVT(trainingGroup); //zie stap 2 //speciale situatie: dezelfde HONOS-antwoorden, toch andere ZVT -> geen splitsing mogelijk dus leafnode maken if (goodSplitofPatientsLeft == null) { return new TreeAndE(new NodeLeaf(meestVoorkomendeZVTInGroep), e); } TreeAndE leftChildNode = createNode(goodSplitofPatientsLeft, z); TreeAndE rightChildNode = createNode(goodSplitofPatientsRight, z); //zie stap 3.2a en 3.2b en 3.3 errorwaarde van de NodeFork (is het gewogen gemiddelde van de errorwaarden van de kinderen), niet te verwarren met e, //de errorwaarde van de LeafNode double eCombinedChildNodes = (leftChildNode.e * goodSplitofPatientsLeft.size() + rightChildNode.e * goodSplitofPatientsRight.size()) / trainingGroup.size(); //zie stap 3.4 if (e < eCombinedChildNodes) { //zie stap 3.5a return new TreeAndE(new NodeLeaf(meestVoorkomendeZVTInGroep), e); } else { //zie stap 3.5b NodeFork nodeFork = new NodeFork(nodeForkHonosVraag, nodeForkThreshold, leftChildNode.decisiontree, rightChildNode.decisiontree); return new TreeAndE(nodeFork, eCombinedChildNodes); } } public static int[] tel_PtperZVT(ArrayList<PatientWithZVT> patients) { int[] perZVTaantalPt = new int[20]; for (PatientWithZVT patient : patients) { //If statementchecks because ZVT 9 doesn't exist and ZVTtypes go up to ZVT21 (problem due to indexing) perZVTaantalPt[convertFromZVTToIndex(patient.zorgvraagtype)]++; } return perZVTaantalPt; } public static double calculateTrueErrorValue(ArrayList<PatientWithZVT> trainingGroup, double z) { //N is totaal aantal pt's in node int N = trainingGroup.size(); int[] ptperZVT = tel_PtperZVT(trainingGroup); int max = 0; //bij equal gesplitste populatie maakt het voor de max niks uit, max behoudt dezelfde waarde for (var nrPT : ptperZVT) { if (nrPT > max) { max = nrPT; } } // E is de errorwaarde van je eigen decisiontree die dus iets te goed is omdat je decisiontree overfitted op de data is int E = N - max; //integerdivision double f = E / N; //doubledivision double f = (double) E / N; //e is de ophoging van f naar een pessimistich geschatte echte errorwaarde, berekening is terug te vinden op //https://sorry.vse.cz/~berka/docs/4iz451/dm07-decision-tree-c45.pdf, z is 0,69 according to sorry but for tuning sake z is an parameter here. // double e = (f + ((z * z) / (2 * N)) + z * Math.sqrt((f / N) - ((f * f) / N) + ((z * z) / (4 * N * N)))) / (1 + (z * z) / N); return e; } public static int convertFromZVTToIndex(int zorgvraagtype) { assert zorgvraagtype < 22; assert zorgvraagtype > 0; assert zorgvraagtype != 9; if (zorgvraagtype < 9) { return zorgvraagtype - 1; } else { return zorgvraagtype - 2; } } public static int convertFromIndexToZVT(int index) { assert index < 20; assert index >= 0; if (index < 8) { return index + 1; } else { return index + 2; } } }
SireeKoolenWijkstra/Zorgvraagtypering
src/main/java/com/mycompany/zorgvraagtypering/ZVTDecisionTree/DecisionTree.java
2,739
//zie stap 3.4
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.zorgvraagtypering.ZVTDecisionTree; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; /** * * @author Siree */ public interface DecisionTree { public static double calculateWeightedEntropy(ArrayList<PatientWithZVT> patientsLeft, ArrayList<PatientWithZVT> patientsRight) { double entropyLeft = entropy(patientsLeft); double entropyRight = entropy(patientsRight); int population = patientsLeft.size() + patientsRight.size(); return (entropyLeft * patientsLeft.size() + entropyRight * patientsRight.size()) / population; } public static double entropy(ArrayList<PatientWithZVT> patients) { assert !patients.isEmpty(); double totaal = 0; for (int nrOfPt : tel_PtperZVT(patients)) { double proportion = nrOfPt / (double) patients.size(); if (proportion != 0) { totaal -= proportion * Math.log(proportion); } } return totaal; } public static int berekenMeestvoorkomendeZVT(ArrayList<PatientWithZVT> trainingGroup) { //N is totaal aantal pt's in node int N = trainingGroup.size(); int[] ptperZVT = tel_PtperZVT(trainingGroup); int meestvoorkomendeZVT = 0; int max = 0; //bij equal gesplitste populatie maakt het voor de max niks uit, max behoudt dezelfde waarde for (int i = 0; i < ptperZVT.length; i++) { if (ptperZVT[i] > max) { max = ptperZVT[i]; meestvoorkomendeZVT = convertFromIndexToZVT(i); } } return meestvoorkomendeZVT; } public int typeer(Patient patient); public void print(String indent); /* interne infrastructuurklasse zodat createNode een decisiontree en diens errorvalue kan teruggeven */ class TreeAndE { DecisionTree decisiontree; double e; public TreeAndE(DecisionTree decisiontree, double e) { this.decisiontree = decisiontree; this.e = e; } } /* 1. loop over alle vragen en thresholds 1.a groepeer alle patiënten aan hun kant van de threshold 1.b meet hoe tevreden je bent met de split (meet entropy (https://towardsdatascience.com/entropy-and-information-gain-in-decision-trees-c7db67a3a293) en sla de split op als die beter is 2. maak the node met de gegevens van stap 1 3. doe the pruning Pruning perpectief van de nodeFork die mogelijk een nodeLeaf wordt stap 1: bereken de f en de e. De f is E/N (aantal pt's in node met een ander zvt dan het meerendeel van de pt's in die node zitten gedeeld door het aantal in de node (wat N is)). De e is de ophoging van f van je decision tree. F moet worden opgehoogd omdat de decision tree overgefit is op de data. De c is 0.25 standaard, z is dan 0.69. stap 2a:bereken de f en e van de linker node stap 2b:bereken de f en de e van de rechter node stap 3: combineer de f en de e van de linker en rechter node stap 4: vergelijk de gecombineerde e met je eigen e stap 5a:als hun gecombineerde e groter is, tranformeer tot een leaf node stap 5b:als hun gecombineerde e kleiner of gelijk is, herhaal de stappen voor zowel de linker child node als de rechter childe node */ public static TreeAndE createNode(ArrayList<PatientWithZVT> trainingGroup, double z) { //Kijk of alle patiënten dezelfde zorgvraagtypering hebben, zo ja dan return je een nodeleaf int zorgvraagtypering = trainingGroup.get(0).zorgvraagtype; //stap 3.1 pruning double e = calculateTrueErrorValue(trainingGroup, z); boolean oneZorgvraagtypering = true; for (var pt : trainingGroup) { //Je vergelijkt ieders zorgvraagtype met de zorgvraagtype van de eerste patiënt. Als niet iedereen hetzelfde is, moet je een split maken //en niet een node leaf. Anders eindigt hier de recursie. if (zorgvraagtypering != pt.zorgvraagtype) { oneZorgvraagtypering = false; } } if (oneZorgvraagtypering) { //iedereen heeft hetzelfde label return new TreeAndE(new NodeLeaf(zorgvraagtypering), e); } double bestValueOfSplit = Double.POSITIVE_INFINITY; //Double.Postitive_infinity is een extreem hoge waarde. Hoe schever de de verdeling over de //zorgvraagtyperingen, hoe lager de entropy(wat beter is) ArrayList<PatientWithZVT> goodSplitofPatientsLeft = null; // is null omdat bestValueOfSplit altijd het allerslechte is en dus goodSplitofPatiensLeft //altijd wordt gevuld ArrayList<PatientWithZVT> goodSplitofPatientsRight = null;// is null omdat bestValueOfSplit altijd het allerslechte is en dus goodSplitofPatiensRight //altijd wordt gevuld int nodeForkHonosVraag = 0; int nodeForkThreshold = 0; //zie stap 1 en 1.a for (int honosVraag = 0; honosVraag < 12; honosVraag++) { for (int threshold = 0; threshold < 5; threshold++) { ArrayList<PatientWithZVT> patientsLeft = new ArrayList<PatientWithZVT>(); ArrayList<PatientWithZVT> patientsRight = new ArrayList<PatientWithZVT>(); for (var patient : trainingGroup) { if (patient.patient.honosScore[honosVraag] < threshold) { patientsLeft.add(patient); } else { patientsRight.add(patient); } } if (patientsLeft.isEmpty()) { continue; } if (patientsRight.isEmpty()) { continue; } //zie stap 1.b double valueOfSplit = calculateWeightedEntropy(patientsLeft, patientsRight); if (valueOfSplit < bestValueOfSplit) { bestValueOfSplit = valueOfSplit; goodSplitofPatientsLeft = patientsLeft; goodSplitofPatientsRight = patientsRight; nodeForkHonosVraag = honosVraag; nodeForkThreshold = threshold; } } } int meestVoorkomendeZVTInGroep = berekenMeestvoorkomendeZVT(trainingGroup); //zie stap 2 //speciale situatie: dezelfde HONOS-antwoorden, toch andere ZVT -> geen splitsing mogelijk dus leafnode maken if (goodSplitofPatientsLeft == null) { return new TreeAndE(new NodeLeaf(meestVoorkomendeZVTInGroep), e); } TreeAndE leftChildNode = createNode(goodSplitofPatientsLeft, z); TreeAndE rightChildNode = createNode(goodSplitofPatientsRight, z); //zie stap 3.2a en 3.2b en 3.3 errorwaarde van de NodeFork (is het gewogen gemiddelde van de errorwaarden van de kinderen), niet te verwarren met e, //de errorwaarde van de LeafNode double eCombinedChildNodes = (leftChildNode.e * goodSplitofPatientsLeft.size() + rightChildNode.e * goodSplitofPatientsRight.size()) / trainingGroup.size(); //zie stap<SUF> if (e < eCombinedChildNodes) { //zie stap 3.5a return new TreeAndE(new NodeLeaf(meestVoorkomendeZVTInGroep), e); } else { //zie stap 3.5b NodeFork nodeFork = new NodeFork(nodeForkHonosVraag, nodeForkThreshold, leftChildNode.decisiontree, rightChildNode.decisiontree); return new TreeAndE(nodeFork, eCombinedChildNodes); } } public static int[] tel_PtperZVT(ArrayList<PatientWithZVT> patients) { int[] perZVTaantalPt = new int[20]; for (PatientWithZVT patient : patients) { //If statementchecks because ZVT 9 doesn't exist and ZVTtypes go up to ZVT21 (problem due to indexing) perZVTaantalPt[convertFromZVTToIndex(patient.zorgvraagtype)]++; } return perZVTaantalPt; } public static double calculateTrueErrorValue(ArrayList<PatientWithZVT> trainingGroup, double z) { //N is totaal aantal pt's in node int N = trainingGroup.size(); int[] ptperZVT = tel_PtperZVT(trainingGroup); int max = 0; //bij equal gesplitste populatie maakt het voor de max niks uit, max behoudt dezelfde waarde for (var nrPT : ptperZVT) { if (nrPT > max) { max = nrPT; } } // E is de errorwaarde van je eigen decisiontree die dus iets te goed is omdat je decisiontree overfitted op de data is int E = N - max; //integerdivision double f = E / N; //doubledivision double f = (double) E / N; //e is de ophoging van f naar een pessimistich geschatte echte errorwaarde, berekening is terug te vinden op //https://sorry.vse.cz/~berka/docs/4iz451/dm07-decision-tree-c45.pdf, z is 0,69 according to sorry but for tuning sake z is an parameter here. // double e = (f + ((z * z) / (2 * N)) + z * Math.sqrt((f / N) - ((f * f) / N) + ((z * z) / (4 * N * N)))) / (1 + (z * z) / N); return e; } public static int convertFromZVTToIndex(int zorgvraagtype) { assert zorgvraagtype < 22; assert zorgvraagtype > 0; assert zorgvraagtype != 9; if (zorgvraagtype < 9) { return zorgvraagtype - 1; } else { return zorgvraagtype - 2; } } public static int convertFromIndexToZVT(int index) { assert index < 20; assert index >= 0; if (index < 8) { return index + 1; } else { return index + 2; } } }
10037_0
package com.hyxogen.authenticator.command; import org.bukkit.command.CommandSender; /** * * @author Daan Meijer * */ public interface ICommand { void onCommand(CommandSender sender, String[] args); public String getCommand(); public String getUsage(); public String getDescription(); /** * If the command requires a permission. <code>null</code> for no permission requirement * * @return list of permissions for which a CommandSender needs only one */ public String[] getPermissions(); public String[] getAliases(); public int getMinArguments(); public int getMaxArguments(); /** * TODO Misschien de basis hoofdcommand (nested) de helper functie laten zijn) * * @return If the command has sub {@link ICommand}s, if this is true, the body * of the current {@link ICommand} will not be executed. The * {@link CommandManager} will instead search for a child * {@link ICommand} with this as the parent. */ public boolean isNested(); }
Hyxogen/AuthenticatorPlugin
src/com/hyxogen/authenticator/command/ICommand.java
261
/** * * @author Daan Meijer * */
block_comment
nl
package com.hyxogen.authenticator.command; import org.bukkit.command.CommandSender; /** * * @author Daan Meijer<SUF>*/ public interface ICommand { void onCommand(CommandSender sender, String[] args); public String getCommand(); public String getUsage(); public String getDescription(); /** * If the command requires a permission. <code>null</code> for no permission requirement * * @return list of permissions for which a CommandSender needs only one */ public String[] getPermissions(); public String[] getAliases(); public int getMinArguments(); public int getMaxArguments(); /** * TODO Misschien de basis hoofdcommand (nested) de helper functie laten zijn) * * @return If the command has sub {@link ICommand}s, if this is true, the body * of the current {@link ICommand} will not be executed. The * {@link CommandManager} will instead search for a child * {@link ICommand} with this as the parent. */ public boolean isNested(); }
186150_4
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package brugerautorisation.server; import brugerautorisation.data.Diverse; import brugerautorisation.data.Bruger; import brugerautorisation.server.Serialisering; import java.io.IOException; import java.io.Serializable; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Scanner; /** * * @author j */ public class Brugerdatabase implements Serializable { // Vigtigt: Sæt versionsnummer så objekt kan læses selvom klassen er ændret! private static final long serialVersionUID = 12345; // bare et eller andet nr. private static Brugerdatabase instans; private static final String SERIALISERET_FIL = "brugere.ser"; private static final Path SIKKERHEDSKOPI = Paths.get("sikkerhedskopi"); private static long filSidstGemt; public ArrayList<Bruger> brugere = new ArrayList<>(); public transient HashMap<String,Bruger> brugernavnTilBruger = new HashMap<>(); public static Brugerdatabase getInstans() { if (instans!=null) return instans; try { instans = (Brugerdatabase) Serialisering.hent(SERIALISERET_FIL); instans.brugernavnTilBruger = new HashMap<>(); System.out.println("Indlæste serialiseret Brugerdatabase: "+instans); } catch (Exception e) { instans = new Brugerdatabase(); Path path = Paths.get("Deltagerliste.html"); Scanner scanner = new Scanner(System.in); try { String data = new String(Files.readAllBytes(path)); System.out.println("Det ser ud til at du ikke har en brugerdatabase endnu."); System.out.println("Jeg læser nu filen "+path+" og opretter en brugerdatabase fra den\n"); indlæsDeltagerlisteFraCampusnetHtml(data, instans.brugere); Bruger b = new Bruger(); b.campusnetId = "ukendt"; b.ekstraFelter.put("webside", "http://www.diplom.dtu.dk/"); b.fornavn = "Dennis"; b.efternavn = "Demostudent"; b.email = "[email protected]"; b.brugernavn = b.email.split("@")[0]; b.studeretning = "demobruger"; b.adgangskode = "kode1xyz"; instans.brugere.add(b); System.out.println("Demobruger tilføjet: "+Diverse.toString(b)); if (instans.brugere.size()==0) throw new IllegalStateException("Der blev ikke fundet nogen brugere i filen"); } catch (IOException e2) { e2.printStackTrace(); System.err.println("Deltagerlisten mangler vist. Du kan oprette den ved at hente\n" + "https://cn.inside.dtu.dk/cnnet/participants/default.aspx?ElementID=535237&sort=fname&order=ascending&pos=0&lastPos=0&lastDisplay=listWith&cache=false&display=listWith&groupby=rights&interval=10000&search=" + "\nog gemme indholdet i filen "+path.toAbsolutePath()); System.err.println("\nDer oprettes nu en enkelt bruger du kan teste med\n(tryk Ctrl-C for at annullere)"); Bruger b = new Bruger(); System.err.print("Brugernavn: "); b.brugernavn = scanner.nextLine(); System.err.print("Adgangskode: "); b.adgangskode = scanner.nextLine(); System.err.print("Fornavn: "); b.fornavn = scanner.nextLine(); System.err.print("Email: "); b.email = scanner.nextLine(); instans.brugere.add(b); System.err.println("Fortsætter, med Brugerdatabase med en enkelt bruger: "+Diverse.toString(b)); try { Thread.sleep(2000); } catch (InterruptedException ex) {} } } // Gendan de transiente felter for (Bruger b : instans.brugere) { instans.brugernavnTilBruger.put(b.brugernavn, b); } return instans; } public static void indlæsDeltagerlisteFraCampusnetHtml(String data, ArrayList<Bruger> brugere) { //System.out.println("data="+data); for (String tr : data.split("<tr")) { if (tr.contains("context_header")) continue; String td[] = tr.split("<td"); if (td.length!=6) continue; // Der er 6 kolonner i det, vi er interesserede i System.out.println("tr="+tr.replace('\n', ' ')); for (String tde : td) { System.out.println("td="+tde.replace('\n', ' ')); } System.out.flush(); /* 0 td= valign="top" class="context_alternating"> 1 td= height="76" valign="top" rowspan="2"><a href="/cnnet/participants/showperson.aspx?campusnetId=190186" class="link"><img src="/cnnet/UserPicture.ashx?x=56&amp;UserId=190186" style="border: 0; width: 56px" alt="" /></a></td> 2 td=><p><a href="/cnnet/participants/showperson.aspx?campusnetId=190186" class="link">Thor Jørgensen</a> <a href="/cnnet/participants/showperson.aspx?campusnetId=190186" class="link">Mortensen</a></p></td> 3 td=> </td> 4 td=><p><a href="mailto:[email protected]" class="link">[email protected]</a><br /><br /></p></td> 5 td=>STADS-tilmeldt<br /><br /><br />diploming. IT elektronik</td></tr> */ Bruger b = new Bruger(); b.campusnetId = td[1].split("id=")[1].split("\"")[0].split("&")[0]; b.ekstraFelter.put("webside", td[1].split("href=\"")[1].split("\"")[0]); b.fornavn = td[2].split("class=\"link\">")[1].split("<")[0]; b.efternavn = td[2].split("class=\"link\">")[2].split("<")[0]; b.email = td[4].split("mailto:")[1].split("\"")[0]; if (b.email.contains("[email protected]") || b.email.contains("[email protected]")) continue; // drom adm personale if (b.email.contains("[email protected]")) continue; // drom adm personale b.brugernavn = b.email.split("@")[0]; b.studeretning = td[5].substring(1).replaceAll("<[^>]+>", " ") .replace("STADS-tilmeldt","") .replace("Afdelingen for Uddannelse og Studerende", "") .replace("Center for Diplomingeniøruddannelse ", "") .replace("diploming. ","").replaceAll("[ \n]+", " ").trim(); if (b.studeretning.isEmpty()) b.studeretning = "IT-Økonomi"; // Hvorfor ITØ'ernes er tom ved jeg ikke.... b.adgangskode = "kode"+Integer.toString((int)(Math.random()*Integer.MAX_VALUE), Character.MAX_RADIX); System.out.println("Oprettet:" + Diverse.toString(b)); brugere.add(b); } } public static void indlæsDeltagerlisteFraCampusnetHtml2(String data, ArrayList<Bruger> brugere) { //System.out.println("data="+data); for (String tr : data.split("<div class=\"ui-participant\">")) { String td[] = tr.split("<div class=\"ui-participant-"); HashMap<String,String> map = new LinkedHashMap<>(); for (String lin : td) { int n = lin.indexOf('"'); if (n==-1) continue; String nøgle = lin.substring(0, n); String værdi = lin.substring(n+2).replaceAll("[\n\r ]+", " "); if (nøgle.equals("infobox")) { String[] x = værdi.split("</div>"); nøgle = x[0].replaceAll("<.+?>", " ").trim(); værdi = x[1]; } if (nøgle.equals("img")) { værdi = værdi.split("\"")[1]; } String værdi2 = værdi.replaceAll("<.+?>", " ").replaceAll("[ ]+", " ").trim(); map.put(nøgle, værdi2); } if (!map.containsKey("name")) continue; System.out.println("map="+map); System.out.flush(); /* <div class="ui-participant"> <div class="ui-participant-img"> <a href="https://www.inside.dtu.dk/da/dtuinside/generelt/telefonbog/person?id=87340&tab=0"> <img src="/cnnet/userpicture/userpicture.ashx?x=150&userId=179992" /> </a> </div> <div class="ui-participant-name"> <span>Sacha Nørskov Behrend</span> </div> <div class="ui-participant-email"> <span class="hiddenOnIcons"> <a href="mailto:[email protected]"> [email protected] </a> </span> <span class="shownOnIcons"> [email protected] </span> </div> <div class="ui-participants-arrow" id="participantarrow179992" onclick="ToggleAdditionalParticipantInformation(179992)"> </div> <div class="ui-participant-additional user-information"> <span>s132970</span> </div> </div> <div class="ui-participant-informationbox" id="participantinformation179992"> <div class="ui-participant-placeholder"> <div class="ui-participant-infobox"> <div class="info-header"> <span>Brugernavn</span> </div> <div> s132970 </div> </div> <div class="ui-participant-infobox"> <div class="info-header"> <span>Email</span> </div> <div> <a href="mailto:[email protected]"> [email protected] </a> </div> </div> <div class="ui-participant-infobox"> <div class="info-header"> <span>Uddannelse</span> </div> <div class="ui-participants-infolist"> <p>diploming. Softwaretek.</p> </div> </div> </div> </div> map={img=, name=Jacob Nordfalk, [email protected] [email protected], additional user-information=jacno, informationbox=id="participantinformation162858">, placeholder=, Brugernavn=jacno, [email protected], Institutter=Center for Diplomingeniøruddannelse} map={img=, name=Pia Holm Søeborg, [email protected] [email protected], additional user-information=phso, informationbox=id="participantinformation163058">, placeholder=, Brugernavn=phso, [email protected], Institutter=Center for Diplomingeniøruddannelse DIPL-Sekretariatet, categorybar=Forfattere (2), sortrow=Sortér efter Fornavn Efternavn Adresse Email} map={img=, name=Sune Thomas Bernth Nielsen, [email protected] [email protected], additional user-information=stbn, informationbox=id="participantinformation179622">, placeholder=, Brugernavn=stbn, [email protected], Adresse=Skodsborggade 17,4 th, 2200 København N, Uddannelse=diploming., Institutter=Center for Diplomingeniøruddannelse} map={img=, name=Bhupjit Singh, [email protected] [email protected], additional user-information=bhsi, informationbox=id="participantinformation89428">, placeholder=, Brugernavn=bhsi, [email protected], Institutter=Center for Diplomingeniøruddannelse, categorybar=Brugere (115), sortrow=Sortér efter Fornavn Efternavn Adresse Email} map={img=, name=Giuseppe Abbate, [email protected] [email protected], additional user-information=s153516, informationbox=id="participantinformation220426">, placeholder=, Brugernavn=s153516, [email protected], Uddannelse=diploming. Softwaretek.} map={img=, name=Burim Abdulahi, [email protected] [email protected], additional user-information=s143591, informationbox=id="participantinformation199640">, placeholder=, Brugernavn=s143591, [email protected], Uddannelse=diploming. Softwaretek.} map={img=, name=Ibrahim Al-Bacha, [email protected] [email protected], additional user-information=s118016, informationbox=id="participantinformation182196">, placeholder=, Brugernavn=s118016, [email protected], Uddannelse=diploming. Softwaretek.} map={img=, name=Amer Ali, [email protected] [email protected], additional user-information=s145224, informationbox=id="participantinformation203190">, placeholder=, Brugernavn=s145224, [email protected], Uddannelse=diploming. Softwaretek.} map={img=, name=Ahmad Mohammad Hassan Almajedi, [email protected] [email protected], additional user-information=s153317, informationbox=id="participantinformation220040">, placeholder=, Brugernavn=s153317, [email protected], Uddannelse=diploming. Softwaretek.} */ Bruger b = new Bruger(); b.fornavn = map.get("name"); int n = b.fornavn.indexOf(" "); b.efternavn = b.fornavn.substring(n+1); b.fornavn = b.fornavn.substring(0,n); b.email = map.get("Email"); if (b.email.contains("[email protected]") || b.email.contains("[email protected]")) continue; // drom adm personale b.brugernavn = b.email.split("@")[0]; b.studeretning = map.get("Uddannelse"); b.ekstraFelter.put("webside", map.get("img")); if (b.studeretning == null) b.studeretning = "Underviser"; else if (b.studeretning.isEmpty()) b.studeretning = "IT-Økonomi"; // Hvorfor ITØ'ernes er tom ved jeg ikke.... else b.studeretning = b.studeretning.replace("diploming. ","").replaceAll("[ \n]+", " ").trim(); b.adgangskode = "kode"+Integer.toString((int)(Math.random()*Integer.MAX_VALUE), Character.MAX_RADIX); System.out.println("Oprettet:" + Diverse.toString(b)); brugere.add(b); } } public void gemTilFil(boolean tvingSkrivning) { if (!tvingSkrivning && filSidstGemt>System.currentTimeMillis()-60000) return; // Gem højst 1 gang per minut // Lav en sikkerhedskopi - i fald der skal rulles tilbage eller filen blir beskadiget try { if (!Files.exists(SIKKERHEDSKOPI)) Files.createDirectories(SIKKERHEDSKOPI); if (Files.exists(Paths.get(SERIALISERET_FIL))) { Files.move(Paths.get(SERIALISERET_FIL), SIKKERHEDSKOPI.resolve(SERIALISERET_FIL+new Date())); } } catch (IOException e) { e.printStackTrace(); } try { Serialisering.gem(this, SERIALISERET_FIL); filSidstGemt = System.currentTimeMillis(); System.out.println("Gemt brugerne pr "+new Date()); } catch (IOException ex) { ex.printStackTrace(); } } public Bruger hentBruger(String brugernavn, String adgangskode) { Bruger b = brugernavnTilBruger.get(brugernavn); System.out.println("hentBruger "+brugernavn+" gav "+b); if (b!=null) { if (b.adgangskode.equals(adgangskode)) { b.sidstAktiv = System.currentTimeMillis(); return b; } System.out.println(" forkert kode: '"+adgangskode+"' - korrekt kode er '"+b.adgangskode+"'"); } // Forkert adgangskode - vent lidt for at imødegå brute force angreb try { Thread.sleep((int)(Math.random()*1000)); } catch (Exception ex) { } throw new IllegalArgumentException("Forkert brugernavn eller adgangskode"); } }
ghtali/distribuerede-systemer
src/brugerautorisation/server/Brugerdatabase.java
4,754
// Gendan de transiente felter
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package brugerautorisation.server; import brugerautorisation.data.Diverse; import brugerautorisation.data.Bruger; import brugerautorisation.server.Serialisering; import java.io.IOException; import java.io.Serializable; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Scanner; /** * * @author j */ public class Brugerdatabase implements Serializable { // Vigtigt: Sæt versionsnummer så objekt kan læses selvom klassen er ændret! private static final long serialVersionUID = 12345; // bare et eller andet nr. private static Brugerdatabase instans; private static final String SERIALISERET_FIL = "brugere.ser"; private static final Path SIKKERHEDSKOPI = Paths.get("sikkerhedskopi"); private static long filSidstGemt; public ArrayList<Bruger> brugere = new ArrayList<>(); public transient HashMap<String,Bruger> brugernavnTilBruger = new HashMap<>(); public static Brugerdatabase getInstans() { if (instans!=null) return instans; try { instans = (Brugerdatabase) Serialisering.hent(SERIALISERET_FIL); instans.brugernavnTilBruger = new HashMap<>(); System.out.println("Indlæste serialiseret Brugerdatabase: "+instans); } catch (Exception e) { instans = new Brugerdatabase(); Path path = Paths.get("Deltagerliste.html"); Scanner scanner = new Scanner(System.in); try { String data = new String(Files.readAllBytes(path)); System.out.println("Det ser ud til at du ikke har en brugerdatabase endnu."); System.out.println("Jeg læser nu filen "+path+" og opretter en brugerdatabase fra den\n"); indlæsDeltagerlisteFraCampusnetHtml(data, instans.brugere); Bruger b = new Bruger(); b.campusnetId = "ukendt"; b.ekstraFelter.put("webside", "http://www.diplom.dtu.dk/"); b.fornavn = "Dennis"; b.efternavn = "Demostudent"; b.email = "[email protected]"; b.brugernavn = b.email.split("@")[0]; b.studeretning = "demobruger"; b.adgangskode = "kode1xyz"; instans.brugere.add(b); System.out.println("Demobruger tilføjet: "+Diverse.toString(b)); if (instans.brugere.size()==0) throw new IllegalStateException("Der blev ikke fundet nogen brugere i filen"); } catch (IOException e2) { e2.printStackTrace(); System.err.println("Deltagerlisten mangler vist. Du kan oprette den ved at hente\n" + "https://cn.inside.dtu.dk/cnnet/participants/default.aspx?ElementID=535237&sort=fname&order=ascending&pos=0&lastPos=0&lastDisplay=listWith&cache=false&display=listWith&groupby=rights&interval=10000&search=" + "\nog gemme indholdet i filen "+path.toAbsolutePath()); System.err.println("\nDer oprettes nu en enkelt bruger du kan teste med\n(tryk Ctrl-C for at annullere)"); Bruger b = new Bruger(); System.err.print("Brugernavn: "); b.brugernavn = scanner.nextLine(); System.err.print("Adgangskode: "); b.adgangskode = scanner.nextLine(); System.err.print("Fornavn: "); b.fornavn = scanner.nextLine(); System.err.print("Email: "); b.email = scanner.nextLine(); instans.brugere.add(b); System.err.println("Fortsætter, med Brugerdatabase med en enkelt bruger: "+Diverse.toString(b)); try { Thread.sleep(2000); } catch (InterruptedException ex) {} } } // Gendan de<SUF> for (Bruger b : instans.brugere) { instans.brugernavnTilBruger.put(b.brugernavn, b); } return instans; } public static void indlæsDeltagerlisteFraCampusnetHtml(String data, ArrayList<Bruger> brugere) { //System.out.println("data="+data); for (String tr : data.split("<tr")) { if (tr.contains("context_header")) continue; String td[] = tr.split("<td"); if (td.length!=6) continue; // Der er 6 kolonner i det, vi er interesserede i System.out.println("tr="+tr.replace('\n', ' ')); for (String tde : td) { System.out.println("td="+tde.replace('\n', ' ')); } System.out.flush(); /* 0 td= valign="top" class="context_alternating"> 1 td= height="76" valign="top" rowspan="2"><a href="/cnnet/participants/showperson.aspx?campusnetId=190186" class="link"><img src="/cnnet/UserPicture.ashx?x=56&amp;UserId=190186" style="border: 0; width: 56px" alt="" /></a></td> 2 td=><p><a href="/cnnet/participants/showperson.aspx?campusnetId=190186" class="link">Thor Jørgensen</a> <a href="/cnnet/participants/showperson.aspx?campusnetId=190186" class="link">Mortensen</a></p></td> 3 td=> </td> 4 td=><p><a href="mailto:[email protected]" class="link">[email protected]</a><br /><br /></p></td> 5 td=>STADS-tilmeldt<br /><br /><br />diploming. IT elektronik</td></tr> */ Bruger b = new Bruger(); b.campusnetId = td[1].split("id=")[1].split("\"")[0].split("&")[0]; b.ekstraFelter.put("webside", td[1].split("href=\"")[1].split("\"")[0]); b.fornavn = td[2].split("class=\"link\">")[1].split("<")[0]; b.efternavn = td[2].split("class=\"link\">")[2].split("<")[0]; b.email = td[4].split("mailto:")[1].split("\"")[0]; if (b.email.contains("[email protected]") || b.email.contains("[email protected]")) continue; // drom adm personale if (b.email.contains("[email protected]")) continue; // drom adm personale b.brugernavn = b.email.split("@")[0]; b.studeretning = td[5].substring(1).replaceAll("<[^>]+>", " ") .replace("STADS-tilmeldt","") .replace("Afdelingen for Uddannelse og Studerende", "") .replace("Center for Diplomingeniøruddannelse ", "") .replace("diploming. ","").replaceAll("[ \n]+", " ").trim(); if (b.studeretning.isEmpty()) b.studeretning = "IT-Økonomi"; // Hvorfor ITØ'ernes er tom ved jeg ikke.... b.adgangskode = "kode"+Integer.toString((int)(Math.random()*Integer.MAX_VALUE), Character.MAX_RADIX); System.out.println("Oprettet:" + Diverse.toString(b)); brugere.add(b); } } public static void indlæsDeltagerlisteFraCampusnetHtml2(String data, ArrayList<Bruger> brugere) { //System.out.println("data="+data); for (String tr : data.split("<div class=\"ui-participant\">")) { String td[] = tr.split("<div class=\"ui-participant-"); HashMap<String,String> map = new LinkedHashMap<>(); for (String lin : td) { int n = lin.indexOf('"'); if (n==-1) continue; String nøgle = lin.substring(0, n); String værdi = lin.substring(n+2).replaceAll("[\n\r ]+", " "); if (nøgle.equals("infobox")) { String[] x = værdi.split("</div>"); nøgle = x[0].replaceAll("<.+?>", " ").trim(); værdi = x[1]; } if (nøgle.equals("img")) { værdi = værdi.split("\"")[1]; } String værdi2 = værdi.replaceAll("<.+?>", " ").replaceAll("[ ]+", " ").trim(); map.put(nøgle, værdi2); } if (!map.containsKey("name")) continue; System.out.println("map="+map); System.out.flush(); /* <div class="ui-participant"> <div class="ui-participant-img"> <a href="https://www.inside.dtu.dk/da/dtuinside/generelt/telefonbog/person?id=87340&tab=0"> <img src="/cnnet/userpicture/userpicture.ashx?x=150&userId=179992" /> </a> </div> <div class="ui-participant-name"> <span>Sacha Nørskov Behrend</span> </div> <div class="ui-participant-email"> <span class="hiddenOnIcons"> <a href="mailto:[email protected]"> [email protected] </a> </span> <span class="shownOnIcons"> [email protected] </span> </div> <div class="ui-participants-arrow" id="participantarrow179992" onclick="ToggleAdditionalParticipantInformation(179992)"> </div> <div class="ui-participant-additional user-information"> <span>s132970</span> </div> </div> <div class="ui-participant-informationbox" id="participantinformation179992"> <div class="ui-participant-placeholder"> <div class="ui-participant-infobox"> <div class="info-header"> <span>Brugernavn</span> </div> <div> s132970 </div> </div> <div class="ui-participant-infobox"> <div class="info-header"> <span>Email</span> </div> <div> <a href="mailto:[email protected]"> [email protected] </a> </div> </div> <div class="ui-participant-infobox"> <div class="info-header"> <span>Uddannelse</span> </div> <div class="ui-participants-infolist"> <p>diploming. Softwaretek.</p> </div> </div> </div> </div> map={img=, name=Jacob Nordfalk, [email protected] [email protected], additional user-information=jacno, informationbox=id="participantinformation162858">, placeholder=, Brugernavn=jacno, [email protected], Institutter=Center for Diplomingeniøruddannelse} map={img=, name=Pia Holm Søeborg, [email protected] [email protected], additional user-information=phso, informationbox=id="participantinformation163058">, placeholder=, Brugernavn=phso, [email protected], Institutter=Center for Diplomingeniøruddannelse DIPL-Sekretariatet, categorybar=Forfattere (2), sortrow=Sortér efter Fornavn Efternavn Adresse Email} map={img=, name=Sune Thomas Bernth Nielsen, [email protected] [email protected], additional user-information=stbn, informationbox=id="participantinformation179622">, placeholder=, Brugernavn=stbn, [email protected], Adresse=Skodsborggade 17,4 th, 2200 København N, Uddannelse=diploming., Institutter=Center for Diplomingeniøruddannelse} map={img=, name=Bhupjit Singh, [email protected] [email protected], additional user-information=bhsi, informationbox=id="participantinformation89428">, placeholder=, Brugernavn=bhsi, [email protected], Institutter=Center for Diplomingeniøruddannelse, categorybar=Brugere (115), sortrow=Sortér efter Fornavn Efternavn Adresse Email} map={img=, name=Giuseppe Abbate, [email protected] [email protected], additional user-information=s153516, informationbox=id="participantinformation220426">, placeholder=, Brugernavn=s153516, [email protected], Uddannelse=diploming. Softwaretek.} map={img=, name=Burim Abdulahi, [email protected] [email protected], additional user-information=s143591, informationbox=id="participantinformation199640">, placeholder=, Brugernavn=s143591, [email protected], Uddannelse=diploming. Softwaretek.} map={img=, name=Ibrahim Al-Bacha, [email protected] [email protected], additional user-information=s118016, informationbox=id="participantinformation182196">, placeholder=, Brugernavn=s118016, [email protected], Uddannelse=diploming. Softwaretek.} map={img=, name=Amer Ali, [email protected] [email protected], additional user-information=s145224, informationbox=id="participantinformation203190">, placeholder=, Brugernavn=s145224, [email protected], Uddannelse=diploming. Softwaretek.} map={img=, name=Ahmad Mohammad Hassan Almajedi, [email protected] [email protected], additional user-information=s153317, informationbox=id="participantinformation220040">, placeholder=, Brugernavn=s153317, [email protected], Uddannelse=diploming. Softwaretek.} */ Bruger b = new Bruger(); b.fornavn = map.get("name"); int n = b.fornavn.indexOf(" "); b.efternavn = b.fornavn.substring(n+1); b.fornavn = b.fornavn.substring(0,n); b.email = map.get("Email"); if (b.email.contains("[email protected]") || b.email.contains("[email protected]")) continue; // drom adm personale b.brugernavn = b.email.split("@")[0]; b.studeretning = map.get("Uddannelse"); b.ekstraFelter.put("webside", map.get("img")); if (b.studeretning == null) b.studeretning = "Underviser"; else if (b.studeretning.isEmpty()) b.studeretning = "IT-Økonomi"; // Hvorfor ITØ'ernes er tom ved jeg ikke.... else b.studeretning = b.studeretning.replace("diploming. ","").replaceAll("[ \n]+", " ").trim(); b.adgangskode = "kode"+Integer.toString((int)(Math.random()*Integer.MAX_VALUE), Character.MAX_RADIX); System.out.println("Oprettet:" + Diverse.toString(b)); brugere.add(b); } } public void gemTilFil(boolean tvingSkrivning) { if (!tvingSkrivning && filSidstGemt>System.currentTimeMillis()-60000) return; // Gem højst 1 gang per minut // Lav en sikkerhedskopi - i fald der skal rulles tilbage eller filen blir beskadiget try { if (!Files.exists(SIKKERHEDSKOPI)) Files.createDirectories(SIKKERHEDSKOPI); if (Files.exists(Paths.get(SERIALISERET_FIL))) { Files.move(Paths.get(SERIALISERET_FIL), SIKKERHEDSKOPI.resolve(SERIALISERET_FIL+new Date())); } } catch (IOException e) { e.printStackTrace(); } try { Serialisering.gem(this, SERIALISERET_FIL); filSidstGemt = System.currentTimeMillis(); System.out.println("Gemt brugerne pr "+new Date()); } catch (IOException ex) { ex.printStackTrace(); } } public Bruger hentBruger(String brugernavn, String adgangskode) { Bruger b = brugernavnTilBruger.get(brugernavn); System.out.println("hentBruger "+brugernavn+" gav "+b); if (b!=null) { if (b.adgangskode.equals(adgangskode)) { b.sidstAktiv = System.currentTimeMillis(); return b; } System.out.println(" forkert kode: '"+adgangskode+"' - korrekt kode er '"+b.adgangskode+"'"); } // Forkert adgangskode - vent lidt for at imødegå brute force angreb try { Thread.sleep((int)(Math.random()*1000)); } catch (Exception ex) { } throw new IllegalArgumentException("Forkert brugernavn eller adgangskode"); } }
11121_1
package students.nurley.tentamen; import java.util.Random; import java.util.Scanner; public class GetalRaden { public static void main(String[] args) { // STAP 1 System.out.println("Joris Roovers, Klas 1A, 12345"); System.out.println(); // STAP 3 int[] willekeurigeGetallen = new int[3]; Random getallenGenerator = new Random(); willekeurigeGetallen[0] = getallenGenerator.nextInt(7) + 1; willekeurigeGetallen[1] = getallenGenerator.nextInt(7) + 1; willekeurigeGetallen[2] = getallenGenerator.nextInt(7) + 1; // NOTA: Je kan de bovenstaande code ook met een for-loop doen. Dit is eingelijk beter, maar ik deed het zonder // om het eenvoudig te houden. // NOTA 2: Ik heb hier overal het getal 3 gebruikt in de onderstaande code om alles duidelijk te houden. Je kan // dit ook vervangen door een constante (= gebruik het final keyword) of door 'willekeurigeGetallen.length'. Scanner input = new Scanner(System.in); int aantalCorrecteGetallen = 0; int aantalKeerGeraden = 0; while (aantalCorrecteGetallen != 3) { // STAP 4 System.out.print("Geef 3 verschillende getallen tussen 1 en 8, gescheiden door spaties: "); int[] geradenGetallen = new int[3]; for (int i = 0; i < 3; i++) { int geradenGetal = input.nextInt(); geradenGetallen[i] = geradenGetal; } // STAP 5 aantalCorrecteGetallen = 0; for (int i = 0; i < willekeurigeGetallen.length; i++) { if (komtVoorIn(willekeurigeGetallen[i], geradenGetallen)) { aantalCorrecteGetallen++; } } System.out.println("Aantal correcte getallen = " + aantalCorrecteGetallen); aantalKeerGeraden++; // STAP 6 } System.out.println("U heeft " + aantalKeerGeraden + " keer geraden"); // STAP 7 System.out.println("De te raden getallen waren: "); for (int i = 0; i < willekeurigeGetallen.length; i++) { System.out.print(willekeurigeGetallen[i] + " "); } input.close(); } // STAP 2 public static boolean komtVoorIn(int zoekgetal, int[] lijst) { boolean getalGevonden = false; for (int i = 0; i < lijst.length; i++) { if (lijst[i] == zoekgetal) { getalGevonden = true; } } return getalGevonden; } }
jorisroovers/java-tutoring
exercises/students/nurley/tentamen/GetalRaden.java
760
// om het eenvoudig te houden.
line_comment
nl
package students.nurley.tentamen; import java.util.Random; import java.util.Scanner; public class GetalRaden { public static void main(String[] args) { // STAP 1 System.out.println("Joris Roovers, Klas 1A, 12345"); System.out.println(); // STAP 3 int[] willekeurigeGetallen = new int[3]; Random getallenGenerator = new Random(); willekeurigeGetallen[0] = getallenGenerator.nextInt(7) + 1; willekeurigeGetallen[1] = getallenGenerator.nextInt(7) + 1; willekeurigeGetallen[2] = getallenGenerator.nextInt(7) + 1; // NOTA: Je kan de bovenstaande code ook met een for-loop doen. Dit is eingelijk beter, maar ik deed het zonder // om het<SUF> // NOTA 2: Ik heb hier overal het getal 3 gebruikt in de onderstaande code om alles duidelijk te houden. Je kan // dit ook vervangen door een constante (= gebruik het final keyword) of door 'willekeurigeGetallen.length'. Scanner input = new Scanner(System.in); int aantalCorrecteGetallen = 0; int aantalKeerGeraden = 0; while (aantalCorrecteGetallen != 3) { // STAP 4 System.out.print("Geef 3 verschillende getallen tussen 1 en 8, gescheiden door spaties: "); int[] geradenGetallen = new int[3]; for (int i = 0; i < 3; i++) { int geradenGetal = input.nextInt(); geradenGetallen[i] = geradenGetal; } // STAP 5 aantalCorrecteGetallen = 0; for (int i = 0; i < willekeurigeGetallen.length; i++) { if (komtVoorIn(willekeurigeGetallen[i], geradenGetallen)) { aantalCorrecteGetallen++; } } System.out.println("Aantal correcte getallen = " + aantalCorrecteGetallen); aantalKeerGeraden++; // STAP 6 } System.out.println("U heeft " + aantalKeerGeraden + " keer geraden"); // STAP 7 System.out.println("De te raden getallen waren: "); for (int i = 0; i < willekeurigeGetallen.length; i++) { System.out.print(willekeurigeGetallen[i] + " "); } input.close(); } // STAP 2 public static boolean komtVoorIn(int zoekgetal, int[] lijst) { boolean getalGevonden = false; for (int i = 0; i < lijst.length; i++) { if (lijst[i] == zoekgetal) { getalGevonden = true; } } return getalGevonden; } }
4742_3
package oefening1_JUnit; import static org.junit.Assert.*; import org.junit.Test; import oefening1.Acteur; import oefening1.Egel; import oefening1.Konijn; public class ActeurTest { @Test public void testImplementatieBeweegbaar() { Acteur acteur = new Konijn(5, 10); // test stap boven acteur.stapBoven(); assertTrue("Verbeter implementatie van stapBoven() in klasse Acteur.", acteur.getX() == 5 && acteur.getY() == 11); // test stap links acteur.stapLinks(); assertTrue("Verbeter implementatie van stapLink() in klasse Acteur.", acteur.getX() == 4 && acteur.getY() == 11); // test stap onder acteur.stapOnder(); assertTrue("Verbeter implementatie van stapOnder() in klasse Acteur.", acteur.getX() == 4 && acteur.getY() == 10); // test stap rechts acteur.stapRechts(); assertTrue("Verbeter implementatie van stapRechts() in klasse Acteur.", acteur.getX() == 5 && acteur.getY() == 10); } @Test public void testEenEgelGroetEenEgelBinnenStraal20() { Egel egel = new Egel(0, 0); Egel andereEgel = new Egel(4, 4); String tekst = egel.interageer(andereEgel); assertTrue("egel moet egel binnen straal 20 groeten", tekst != null && tekst.equalsIgnoreCase("Dag egel")); } @Test public void testEenEgelGroetEenEgelBuitenStraal20Niet() { Egel egel = new Egel(0, 0); Egel andereEgel = new Egel(20, 20); assertEquals("egel kan egel buiten straal 20 niet groeten", egel.interageer(andereEgel), null); } @Test public void testEenEgelGroetEenKonijnBinnenStraal10() { Egel egel = new Egel(0, 0); Konijn konijn = new Konijn(4, 4); String tekst = egel.interageer(konijn); assertTrue("egel moet konijn binnen straal 10 groeten", tekst != null && tekst.equalsIgnoreCase("dag konijn")); } @Test public void testEenEgelGroetEenKonijnBuitenStraal10Niet() { Egel egel = new Egel(0, 0); Konijn konijn = new Konijn(14, 14); assertEquals("egel kan konijn buiten straal 10 niet groeten", egel.interageer(konijn), null); } @Test public void testEenKonijnGroetEenKonijnNiet() { Konijn konijn = new Konijn(0, 0); Konijn anderKonijn = new Konijn(1, 1); assertEquals("konijn mag een konijn niet groeten", konijn.interageer(anderKonijn), null); } @Test public void testEenKonijnGroetEenEgelNiet() { Egel egel = new Egel(1, 1); Konijn konijn = new Konijn(14, 14); assertEquals("konijn mag een egel niet groeten", konijn.interageer(egel), null); } }
JoachimVeulemans/PXL-DIGITAL
PXL_DIGITAL_JAAR_1/Java Essentials/Oplossingen/H13/oefening1_JUnit/ActeurTest.java
858
// test stap rechts
line_comment
nl
package oefening1_JUnit; import static org.junit.Assert.*; import org.junit.Test; import oefening1.Acteur; import oefening1.Egel; import oefening1.Konijn; public class ActeurTest { @Test public void testImplementatieBeweegbaar() { Acteur acteur = new Konijn(5, 10); // test stap boven acteur.stapBoven(); assertTrue("Verbeter implementatie van stapBoven() in klasse Acteur.", acteur.getX() == 5 && acteur.getY() == 11); // test stap links acteur.stapLinks(); assertTrue("Verbeter implementatie van stapLink() in klasse Acteur.", acteur.getX() == 4 && acteur.getY() == 11); // test stap onder acteur.stapOnder(); assertTrue("Verbeter implementatie van stapOnder() in klasse Acteur.", acteur.getX() == 4 && acteur.getY() == 10); // test stap<SUF> acteur.stapRechts(); assertTrue("Verbeter implementatie van stapRechts() in klasse Acteur.", acteur.getX() == 5 && acteur.getY() == 10); } @Test public void testEenEgelGroetEenEgelBinnenStraal20() { Egel egel = new Egel(0, 0); Egel andereEgel = new Egel(4, 4); String tekst = egel.interageer(andereEgel); assertTrue("egel moet egel binnen straal 20 groeten", tekst != null && tekst.equalsIgnoreCase("Dag egel")); } @Test public void testEenEgelGroetEenEgelBuitenStraal20Niet() { Egel egel = new Egel(0, 0); Egel andereEgel = new Egel(20, 20); assertEquals("egel kan egel buiten straal 20 niet groeten", egel.interageer(andereEgel), null); } @Test public void testEenEgelGroetEenKonijnBinnenStraal10() { Egel egel = new Egel(0, 0); Konijn konijn = new Konijn(4, 4); String tekst = egel.interageer(konijn); assertTrue("egel moet konijn binnen straal 10 groeten", tekst != null && tekst.equalsIgnoreCase("dag konijn")); } @Test public void testEenEgelGroetEenKonijnBuitenStraal10Niet() { Egel egel = new Egel(0, 0); Konijn konijn = new Konijn(14, 14); assertEquals("egel kan konijn buiten straal 10 niet groeten", egel.interageer(konijn), null); } @Test public void testEenKonijnGroetEenKonijnNiet() { Konijn konijn = new Konijn(0, 0); Konijn anderKonijn = new Konijn(1, 1); assertEquals("konijn mag een konijn niet groeten", konijn.interageer(anderKonijn), null); } @Test public void testEenKonijnGroetEenEgelNiet() { Egel egel = new Egel(1, 1); Konijn konijn = new Konijn(14, 14); assertEquals("konijn mag een egel niet groeten", konijn.interageer(egel), null); } }
6331_5
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.HashMap; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utilities { public static Pattern pattern = Pattern.compile("[\\-0-9]+"); public static SecureRandom random = new SecureRandom(); public static Random fastRandom = new Xoroshiro128PlusRandom(random.nextLong()); public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue"); public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue"); public static volatile DispatchQueue cacheClearQueue = new DispatchQueue("cacheClearQueue"); public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue"); public static volatile DispatchQueue phoneBookQueue = new DispatchQueue("phoneBookQueue"); public static volatile DispatchQueue themeQueue = new DispatchQueue("themeQueue"); public static volatile DispatchQueue externalNetworkQueue = new DispatchQueue("externalNetworkQueue"); private final static String RANDOM_STRING_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); static { try { File URANDOM_FILE = new File("/dev/urandom"); FileInputStream sUrandomIn = new FileInputStream(URANDOM_FILE); byte[] buffer = new byte[1024]; sUrandomIn.read(buffer); sUrandomIn.close(); random.setSeed(buffer); } catch (Exception e) { FileLog.e(e); } } public native static int pinBitmap(Bitmap bitmap); public native static void unpinBitmap(Bitmap bitmap); public native static void blurBitmap(Object bitmap, int radius, int unpin, int width, int height, int stride); public native static int needInvert(Object bitmap, int unpin, int width, int height, int stride); public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer, ByteBuffer calcBuffer); public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin); public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap); private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); private native static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length); public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, long length, int n); private native static void aesCbcEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt); public native static void aesCbcEncryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length, int encrypt); public native static String readlink(String path); public native static String readlinkFd(int fd); public native static long getDirSize(String path, int docType, boolean subdirs); public native static long getLastUsageFileTime(String path); public native static void clearDir(String path, int docType, long time, boolean subdirs); private native static int pbkdf2(byte[] password, byte[] salt, byte[] dst, int iterations); public static native void stackBlurBitmap(Bitmap bitmap, int radius); public static native void drawDitheredGradient(Bitmap bitmap, int[] colors, int startX, int startY, int endX, int endY); public static native int saveProgressiveJpeg(Bitmap bitmap, int width, int height, int stride, int quality, String path); public static native void generateGradient(Bitmap bitmap, boolean unpin, int phase, float progress, int width, int height, int stride, int[] colors); public static native void setupNativeCrashesListener(String path); public static Bitmap stackBlurBitmapMax(Bitmap bitmap) { int w = AndroidUtilities.dp(20); int h = (int) (AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth()); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap stackBlurBitmapWithScaleFactor(Bitmap bitmap, float scaleFactor) { int w = (int) Math.max(AndroidUtilities.dp(20), bitmap.getWidth() / scaleFactor); int h = (int) Math.max(AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth(), bitmap.getHeight() / scaleFactor); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap blurWallpaper(Bitmap src) { if (src == null) { return null; } Bitmap b; if (src.getHeight() > src.getWidth()) { b = Bitmap.createBitmap(Math.round(450f * src.getWidth() / src.getHeight()), 450, Bitmap.Config.ARGB_8888); } else { b = Bitmap.createBitmap(450, Math.round(450f * src.getHeight() / src.getWidth()), Bitmap.Config.ARGB_8888); } Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight()); new Canvas(b).drawBitmap(src, null, rect, paint); stackBlurBitmap(b, 12); return b; } public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryptionByteArray(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesCbcEncryptionByteArraySafe(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt) { aesCbcEncryptionByteArray(buffer, key, iv.clone(), offset, length, n, encrypt); } public static Integer parseInt(CharSequence value) { if (value == null) { return 0; } // if (BuildConfig.BUILD_HOST_IS_WINDOWS) { // Matcher matcher = pattern.matcher(value); // if (matcher.find()) { // return Integer.valueOf(matcher.group()); // } // } else { { int val = 0; try { int start = -1, end; for (end = 0; end < value.length(); ++end) { char character = value.charAt(end); boolean allowedChar = character == '-' || character >= '0' && character <= '9'; if (allowedChar && start < 0) { start = end; } else if (!allowedChar && start >= 0) { end++; break; } } if (start >= 0) { String str = value.subSequence(start, end).toString(); // val = parseInt(str); val = Integer.parseInt(str); } } catch (Exception ignore) {} return val; } // return 0; } private static int parseInt(final String s) { int num = 0; boolean negative = true; final int len = s.length(); final char ch = s.charAt(0); if (ch == '-') { negative = false; } else { num = '0' - ch; } int i = 1; while (i < len) { num = num * 10 + '0' - s.charAt(i++); } return negative ? -num : num; } public static Long parseLong(String value) { if (value == null) { return 0L; } long val = 0L; try { Matcher matcher = pattern.matcher(value); if (matcher.find()) { String num = matcher.group(0); val = Long.parseLong(num); } } catch (Exception ignore) { } return val; } public static String parseIntToString(String value) { Matcher matcher = pattern.matcher(value); if (matcher.find()) { return matcher.group(0); } return null; } public static String bytesToHex(byte[] bytes) { if (bytes == null) { return ""; } char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static byte[] hexToBytes(String hex) { if (hex == null) { return null; } int len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16)); } return data; } public static boolean isGoodPrime(byte[] prime, int g) { if (!(g >= 2 && g <= 7)) { return false; } if (prime.length != 256 || prime[0] >= 0) { return false; } BigInteger dhBI = new BigInteger(1, prime); if (g == 2) { // p mod 8 = 7 for g = 2; BigInteger res = dhBI.mod(BigInteger.valueOf(8)); if (res.intValue() != 7) { return false; } } else if (g == 3) { // p mod 3 = 2 for g = 3; BigInteger res = dhBI.mod(BigInteger.valueOf(3)); if (res.intValue() != 2) { return false; } } else if (g == 5) { // p mod 5 = 1 or 4 for g = 5; BigInteger res = dhBI.mod(BigInteger.valueOf(5)); int val = res.intValue(); if (val != 1 && val != 4) { return false; } } else if (g == 6) { // p mod 24 = 19 or 23 for g = 6; BigInteger res = dhBI.mod(BigInteger.valueOf(24)); int val = res.intValue(); if (val != 19 && val != 23) { return false; } } else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7. BigInteger res = dhBI.mod(BigInteger.valueOf(7)); int val = res.intValue(); if (val != 3 && val != 5 && val != 6) { return false; } } String hex = bytesToHex(prime); if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) { return true; } BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2)); return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30)); } public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) { return !(g_a.compareTo(BigInteger.valueOf(1)) <= 0 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) >= 0); } public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) { if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 > arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) { return false; } boolean result = true; for (int a = offset1; a < arr1.length; a++) { if (arr1[a + offset1] != arr2[a + offset2]) { result = false; } } return result; } public static byte[] computeSHA1(byte[] convertme, int offset, int len) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(convertme, offset, len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) { int oldp = convertme.position(); int oldl = convertme.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); convertme.position(offset); convertme.limit(len); md.update(convertme); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { convertme.limit(oldl); convertme.position(oldp); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme) { return computeSHA1(convertme, 0, convertme.limit()); } public static byte[] computeSHA1(byte[] convertme) { return computeSHA1(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme) { return computeSHA256(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme, int offset, long len) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(convertme, offset, (int) len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA256(byte[]... args) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); for (int a = 0; a < args.length; a++) { md.update(args[a], 0, args[a].length); } return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA512(byte[] convertme) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computePBKDF2(byte[] password, byte[] salt) { byte[] dst = new byte[64]; Utilities.pbkdf2(password, salt, dst, 100000); return dst; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2, byte[] convertme3) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); md.update(convertme3, 0, convertme3.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA256(byte[] b1, int o1, int l1, ByteBuffer b2, int o2, int l2) { int oldp = b2.position(); int oldl = b2.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(b1, o1, l1); b2.position(o2); b2.limit(l2); md.update(b2); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { b2.limit(oldl); b2.position(oldp); } return new byte[32]; } public static long bytesToLong(byte[] bytes) { return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32) + (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF); } public static int bytesToInt(byte[] bytes) { return (((int) bytes[3] & 0xFF) << 24) + (((int) bytes[2] & 0xFF) << 16) + (((int) bytes[1] & 0xFF) << 8) + ((int) bytes[0] & 0xFF); } public static byte[] intToBytes(int value) { return new byte[]{ (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; } public static String MD5(String md5) { if (md5 == null) { return null; } try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(AndroidUtilities.getStringBytes(md5)); StringBuilder sb = new StringBuilder(); for (int a = 0; a < array.length; a++) { sb.append(Integer.toHexString((array[a] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { FileLog.e(e); } return null; } public static int clamp(int value, int maxValue, int minValue) { return Math.max(Math.min(value, maxValue), minValue); } public static float clamp(float value, float maxValue, float minValue) { if (Float.isNaN(value)) { return minValue; } if (Float.isInfinite(value)) { return maxValue; } return Math.max(Math.min(value, maxValue), minValue); } public static String generateRandomString() { return generateRandomString(16); } public static String generateRandomString(int chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < chars; i++) { sb.append(RANDOM_STRING_CHARS.charAt(fastRandom.nextInt(RANDOM_STRING_CHARS.length()))); } return sb.toString(); } public static String getExtension(String fileName) { int idx = fileName.lastIndexOf('.'); String ext = null; if (idx != -1) { ext = fileName.substring(idx + 1); } if (ext == null) { return null; } ext = ext.toUpperCase(); return ext; } public static interface Callback<T> { public void run(T arg); } public static interface CallbackReturn<Arg, ReturnType> { public ReturnType run(Arg arg); } public static interface Callback2<T, T2> { public void run(T arg, T2 arg2); } public static interface Callback3<T, T2, T3> { public void run(T arg, T2 arg2, T3 arg3); } public static <Key, Value> Value getOrDefault(HashMap<Key, Value> map, Key key, Value defaultValue) { Value v = map.get(key); if (v == null) { return defaultValue; } return v; } public static void doCallbacks(Utilities.Callback<Runnable> ...actions) { doCallbacks(0, actions); } private static void doCallbacks(int i, Utilities.Callback<Runnable> ...actions) { if (actions != null && actions.length > i) { actions[i].run(() -> doCallbacks(i + 1, actions)); } } public static void raceCallbacks(Runnable onFinish, Utilities.Callback<Runnable> ...actions) { if (actions == null || actions.length == 0) { if (onFinish != null) { onFinish.run(); } return; } final int[] finished = new int[] { 0 }; Runnable checkFinish = () -> { finished[0]++; if (finished[0] == actions.length) { if (onFinish != null) { onFinish.run(); } } }; for (int i = 0; i < actions.length; ++i) { actions[i].run(checkFinish); } } }
NekoX-Dev/NekoX
TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java
6,517
// val = parseInt(str);
line_comment
nl
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.messenger; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import com.carrotsearch.randomizedtesting.Xoroshiro128PlusRandom; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.HashMap; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utilities { public static Pattern pattern = Pattern.compile("[\\-0-9]+"); public static SecureRandom random = new SecureRandom(); public static Random fastRandom = new Xoroshiro128PlusRandom(random.nextLong()); public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue"); public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue"); public static volatile DispatchQueue cacheClearQueue = new DispatchQueue("cacheClearQueue"); public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue"); public static volatile DispatchQueue phoneBookQueue = new DispatchQueue("phoneBookQueue"); public static volatile DispatchQueue themeQueue = new DispatchQueue("themeQueue"); public static volatile DispatchQueue externalNetworkQueue = new DispatchQueue("externalNetworkQueue"); private final static String RANDOM_STRING_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); static { try { File URANDOM_FILE = new File("/dev/urandom"); FileInputStream sUrandomIn = new FileInputStream(URANDOM_FILE); byte[] buffer = new byte[1024]; sUrandomIn.read(buffer); sUrandomIn.close(); random.setSeed(buffer); } catch (Exception e) { FileLog.e(e); } } public native static int pinBitmap(Bitmap bitmap); public native static void unpinBitmap(Bitmap bitmap); public native static void blurBitmap(Object bitmap, int radius, int unpin, int width, int height, int stride); public native static int needInvert(Object bitmap, int unpin, int width, int height, int stride); public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer, ByteBuffer calcBuffer); public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin); public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap); private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); private native static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); public native static void aesCtrDecryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length); public native static void aesCtrDecryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, long length, int n); private native static void aesCbcEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt); public native static void aesCbcEncryption(ByteBuffer buffer, byte[] key, byte[] iv, int offset, int length, int encrypt); public native static String readlink(String path); public native static String readlinkFd(int fd); public native static long getDirSize(String path, int docType, boolean subdirs); public native static long getLastUsageFileTime(String path); public native static void clearDir(String path, int docType, long time, boolean subdirs); private native static int pbkdf2(byte[] password, byte[] salt, byte[] dst, int iterations); public static native void stackBlurBitmap(Bitmap bitmap, int radius); public static native void drawDitheredGradient(Bitmap bitmap, int[] colors, int startX, int startY, int endX, int endY); public static native int saveProgressiveJpeg(Bitmap bitmap, int width, int height, int stride, int quality, String path); public static native void generateGradient(Bitmap bitmap, boolean unpin, int phase, float progress, int width, int height, int stride, int[] colors); public static native void setupNativeCrashesListener(String path); public static Bitmap stackBlurBitmapMax(Bitmap bitmap) { int w = AndroidUtilities.dp(20); int h = (int) (AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth()); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap stackBlurBitmapWithScaleFactor(Bitmap bitmap, float scaleFactor) { int w = (int) Math.max(AndroidUtilities.dp(20), bitmap.getWidth() / scaleFactor); int h = (int) Math.max(AndroidUtilities.dp(20) * (float) bitmap.getHeight() / bitmap.getWidth(), bitmap.getHeight() / scaleFactor); Bitmap scaledBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(scaledBitmap); canvas.save(); canvas.scale((float) scaledBitmap.getWidth() / bitmap.getWidth(), (float) scaledBitmap.getHeight() / bitmap.getHeight()); canvas.drawBitmap(bitmap, 0, 0, null); canvas.restore(); Utilities.stackBlurBitmap(scaledBitmap, Math.max(10, Math.max(w, h) / 150)); return scaledBitmap; } public static Bitmap blurWallpaper(Bitmap src) { if (src == null) { return null; } Bitmap b; if (src.getHeight() > src.getWidth()) { b = Bitmap.createBitmap(Math.round(450f * src.getWidth() / src.getHeight()), 450, Bitmap.Config.ARGB_8888); } else { b = Bitmap.createBitmap(450, Math.round(450f * src.getHeight() / src.getWidth()), Bitmap.Config.ARGB_8888); } Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight()); new Canvas(b).drawBitmap(src, null, rect, paint); stackBlurBitmap(b, 12); return b; } public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesIgeEncryptionByteArray(byte[] buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryptionByteArray(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } public static void aesCbcEncryptionByteArraySafe(byte[] buffer, byte[] key, byte[] iv, int offset, int length, int n, int encrypt) { aesCbcEncryptionByteArray(buffer, key, iv.clone(), offset, length, n, encrypt); } public static Integer parseInt(CharSequence value) { if (value == null) { return 0; } // if (BuildConfig.BUILD_HOST_IS_WINDOWS) { // Matcher matcher = pattern.matcher(value); // if (matcher.find()) { // return Integer.valueOf(matcher.group()); // } // } else { { int val = 0; try { int start = -1, end; for (end = 0; end < value.length(); ++end) { char character = value.charAt(end); boolean allowedChar = character == '-' || character >= '0' && character <= '9'; if (allowedChar && start < 0) { start = end; } else if (!allowedChar && start >= 0) { end++; break; } } if (start >= 0) { String str = value.subSequence(start, end).toString(); // val =<SUF> val = Integer.parseInt(str); } } catch (Exception ignore) {} return val; } // return 0; } private static int parseInt(final String s) { int num = 0; boolean negative = true; final int len = s.length(); final char ch = s.charAt(0); if (ch == '-') { negative = false; } else { num = '0' - ch; } int i = 1; while (i < len) { num = num * 10 + '0' - s.charAt(i++); } return negative ? -num : num; } public static Long parseLong(String value) { if (value == null) { return 0L; } long val = 0L; try { Matcher matcher = pattern.matcher(value); if (matcher.find()) { String num = matcher.group(0); val = Long.parseLong(num); } } catch (Exception ignore) { } return val; } public static String parseIntToString(String value) { Matcher matcher = pattern.matcher(value); if (matcher.find()) { return matcher.group(0); } return null; } public static String bytesToHex(byte[] bytes) { if (bytes == null) { return ""; } char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static byte[] hexToBytes(String hex) { if (hex == null) { return null; } int len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16)); } return data; } public static boolean isGoodPrime(byte[] prime, int g) { if (!(g >= 2 && g <= 7)) { return false; } if (prime.length != 256 || prime[0] >= 0) { return false; } BigInteger dhBI = new BigInteger(1, prime); if (g == 2) { // p mod 8 = 7 for g = 2; BigInteger res = dhBI.mod(BigInteger.valueOf(8)); if (res.intValue() != 7) { return false; } } else if (g == 3) { // p mod 3 = 2 for g = 3; BigInteger res = dhBI.mod(BigInteger.valueOf(3)); if (res.intValue() != 2) { return false; } } else if (g == 5) { // p mod 5 = 1 or 4 for g = 5; BigInteger res = dhBI.mod(BigInteger.valueOf(5)); int val = res.intValue(); if (val != 1 && val != 4) { return false; } } else if (g == 6) { // p mod 24 = 19 or 23 for g = 6; BigInteger res = dhBI.mod(BigInteger.valueOf(24)); int val = res.intValue(); if (val != 19 && val != 23) { return false; } } else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7. BigInteger res = dhBI.mod(BigInteger.valueOf(7)); int val = res.intValue(); if (val != 3 && val != 5 && val != 6) { return false; } } String hex = bytesToHex(prime); if (hex.equals("C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) { return true; } BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2)); return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30)); } public static boolean isGoodGaAndGb(BigInteger g_a, BigInteger p) { return !(g_a.compareTo(BigInteger.valueOf(1)) <= 0 || g_a.compareTo(p.subtract(BigInteger.valueOf(1))) >= 0); } public static boolean arraysEquals(byte[] arr1, int offset1, byte[] arr2, int offset2) { if (arr1 == null || arr2 == null || offset1 < 0 || offset2 < 0 || arr1.length - offset1 > arr2.length - offset2 || arr1.length - offset1 < 0 || arr2.length - offset2 < 0) { return false; } boolean result = true; for (int a = offset1; a < arr1.length; a++) { if (arr1[a + offset1] != arr2[a + offset2]) { result = false; } } return result; } public static byte[] computeSHA1(byte[] convertme, int offset, int len) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(convertme, offset, len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) { int oldp = convertme.position(); int oldl = convertme.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); convertme.position(offset); convertme.limit(len); md.update(convertme); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { convertme.limit(oldl); convertme.position(oldp); } return new byte[20]; } public static byte[] computeSHA1(ByteBuffer convertme) { return computeSHA1(convertme, 0, convertme.limit()); } public static byte[] computeSHA1(byte[] convertme) { return computeSHA1(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme) { return computeSHA256(convertme, 0, convertme.length); } public static byte[] computeSHA256(byte[] convertme, int offset, long len) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(convertme, offset, (int) len); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA256(byte[]... args) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); for (int a = 0; a < args.length; a++) { md.update(args[a], 0, args[a].length); } return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[32]; } public static byte[] computeSHA512(byte[] convertme) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computePBKDF2(byte[] password, byte[] salt) { byte[] dst = new byte[64]; Utilities.pbkdf2(password, salt, dst, 100000); return dst; } public static byte[] computeSHA512(byte[] convertme, byte[] convertme2, byte[] convertme3) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(convertme, 0, convertme.length); md.update(convertme2, 0, convertme2.length); md.update(convertme3, 0, convertme3.length); return md.digest(); } catch (Exception e) { FileLog.e(e); } return new byte[64]; } public static byte[] computeSHA256(byte[] b1, int o1, int l1, ByteBuffer b2, int o2, int l2) { int oldp = b2.position(); int oldl = b2.limit(); try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(b1, o1, l1); b2.position(o2); b2.limit(l2); md.update(b2); return md.digest(); } catch (Exception e) { FileLog.e(e); } finally { b2.limit(oldl); b2.position(oldp); } return new byte[32]; } public static long bytesToLong(byte[] bytes) { return ((long) bytes[7] << 56) + (((long) bytes[6] & 0xFF) << 48) + (((long) bytes[5] & 0xFF) << 40) + (((long) bytes[4] & 0xFF) << 32) + (((long) bytes[3] & 0xFF) << 24) + (((long) bytes[2] & 0xFF) << 16) + (((long) bytes[1] & 0xFF) << 8) + ((long) bytes[0] & 0xFF); } public static int bytesToInt(byte[] bytes) { return (((int) bytes[3] & 0xFF) << 24) + (((int) bytes[2] & 0xFF) << 16) + (((int) bytes[1] & 0xFF) << 8) + ((int) bytes[0] & 0xFF); } public static byte[] intToBytes(int value) { return new byte[]{ (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; } public static String MD5(String md5) { if (md5 == null) { return null; } try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(AndroidUtilities.getStringBytes(md5)); StringBuilder sb = new StringBuilder(); for (int a = 0; a < array.length; a++) { sb.append(Integer.toHexString((array[a] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { FileLog.e(e); } return null; } public static int clamp(int value, int maxValue, int minValue) { return Math.max(Math.min(value, maxValue), minValue); } public static float clamp(float value, float maxValue, float minValue) { if (Float.isNaN(value)) { return minValue; } if (Float.isInfinite(value)) { return maxValue; } return Math.max(Math.min(value, maxValue), minValue); } public static String generateRandomString() { return generateRandomString(16); } public static String generateRandomString(int chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < chars; i++) { sb.append(RANDOM_STRING_CHARS.charAt(fastRandom.nextInt(RANDOM_STRING_CHARS.length()))); } return sb.toString(); } public static String getExtension(String fileName) { int idx = fileName.lastIndexOf('.'); String ext = null; if (idx != -1) { ext = fileName.substring(idx + 1); } if (ext == null) { return null; } ext = ext.toUpperCase(); return ext; } public static interface Callback<T> { public void run(T arg); } public static interface CallbackReturn<Arg, ReturnType> { public ReturnType run(Arg arg); } public static interface Callback2<T, T2> { public void run(T arg, T2 arg2); } public static interface Callback3<T, T2, T3> { public void run(T arg, T2 arg2, T3 arg3); } public static <Key, Value> Value getOrDefault(HashMap<Key, Value> map, Key key, Value defaultValue) { Value v = map.get(key); if (v == null) { return defaultValue; } return v; } public static void doCallbacks(Utilities.Callback<Runnable> ...actions) { doCallbacks(0, actions); } private static void doCallbacks(int i, Utilities.Callback<Runnable> ...actions) { if (actions != null && actions.length > i) { actions[i].run(() -> doCallbacks(i + 1, actions)); } } public static void raceCallbacks(Runnable onFinish, Utilities.Callback<Runnable> ...actions) { if (actions == null || actions.length == 0) { if (onFinish != null) { onFinish.run(); } return; } final int[] finished = new int[] { 0 }; Runnable checkFinish = () -> { finished[0]++; if (finished[0] == actions.length) { if (onFinish != null) { onFinish.run(); } } }; for (int i = 0; i < actions.length; ++i) { actions[i].run(checkFinish); } } }
55966_2
package stroomnetwerk; import java.util.Objects; import java.util.Set; import logicalcollections.LogicalSet; /** * @invar | 0 < getDebiet() * @invar | (getBronknoop() == null) == (getDoelknoop() == null) * @invar | getBronknoop() == null || getBronknoop().getUitgaandeLeidingen().contains(this) * @invar | getDoelknoop() == null || getDoelknoop().getInkomendeLeidingen().contains(this) */ public class Leiding extends Onderdeel { /** * @invar | 0 < debiet * @invar | (bronknoop == null) == (doelknoop == null) * @invar | bronknoop == null || bronknoop.uitgaandeLeidingen.contains(this) * @invar | doelknoop == null || doelknoop.inkomendeLeidingen.contains(this) */ int debiet; /** * @peerObject */ Knoop bronknoop; /** * @peerObject */ Knoop doelknoop; public int getDebiet() { return debiet; } /** * @peerObject */ public Knoop getBronknoop() { return bronknoop; } /** * @peerObject */ public Knoop getDoelknoop() { return doelknoop; } /** * @throws IllegalArgumentException | debiet <= 0 * @post | getDebiet() == debiet * @post | getBronknoop() == null * @post | getDoelknoop() == null */ public Leiding(int debiet) { if (debiet <= 0) throw new IllegalArgumentException("`debiet` is not greater than zero"); this.debiet = debiet; } /** * @pre | getBronknoop() == null * @pre | bronknoop != null * @pre | doelknoop != null * @mutates_properties | getBronknoop(), getDoelknoop(), bronknoop.getUitgaandeLeidingen(), doelknoop.getInkomendeLeidingen() * @post | getBronknoop() == bronknoop * @post | getDoelknoop() == doelknoop * @post | getBronknoop().getUitgaandeLeidingen().equals(LogicalSet.plus(old(bronknoop.getUitgaandeLeidingen()), this)) * @post | getDoelknoop().getInkomendeLeidingen().equals(LogicalSet.plus(old(doelknoop.getInkomendeLeidingen()), this)) */ public void koppelAan(Knoop bronknoop, Knoop doelknoop) { this.bronknoop = bronknoop; this.doelknoop = doelknoop; bronknoop.uitgaandeLeidingen.add(this); doelknoop.inkomendeLeidingen.add(this); } /** * @pre | getBronknoop() != null * @mutates_properties | getBronknoop(), getDoelknoop(), getBronknoop().getUitgaandeLeidingen(), getDoelknoop().getInkomendeLeidingen() * @post | getBronknoop() == null * @post | getDoelknoop() == null * @post | old(getBronknoop()).getUitgaandeLeidingen().equals(LogicalSet.minus(old(getBronknoop().getUitgaandeLeidingen()), this)) * @post | old(getDoelknoop()).getInkomendeLeidingen().equals(LogicalSet.minus(old(getDoelknoop().getInkomendeLeidingen()), this)) */ public void ontkoppel() { bronknoop.uitgaandeLeidingen.remove(this); doelknoop.inkomendeLeidingen.remove(this); bronknoop = null; doelknoop = null; } /** * @creates | result * @post | Objects.equals(result, * | getBronknoop() == null * | ? * | Set.of() * | : * | Set.of(getBronknoop(), getDoelknoop()) * | ) */ @Override public Set<? extends Onderdeel> getGekoppeldeOnderdelen() { if (bronknoop == null) return Set.of(); return Set.of(bronknoop, doelknoop); } /** * @post | result == (onderdeel instanceof Leiding l && getDebiet() == l.getDebiet()) */ @Override public boolean isGelijkaardigAan(Onderdeel onderdeel) { return onderdeel instanceof Leiding l && debiet == l.debiet; } }
btj/stroomnetwerk
stroomnetwerk/src/stroomnetwerk/Leiding.java
1,239
/** * @peerObject */
block_comment
nl
package stroomnetwerk; import java.util.Objects; import java.util.Set; import logicalcollections.LogicalSet; /** * @invar | 0 < getDebiet() * @invar | (getBronknoop() == null) == (getDoelknoop() == null) * @invar | getBronknoop() == null || getBronknoop().getUitgaandeLeidingen().contains(this) * @invar | getDoelknoop() == null || getDoelknoop().getInkomendeLeidingen().contains(this) */ public class Leiding extends Onderdeel { /** * @invar | 0 < debiet * @invar | (bronknoop == null) == (doelknoop == null) * @invar | bronknoop == null || bronknoop.uitgaandeLeidingen.contains(this) * @invar | doelknoop == null || doelknoop.inkomendeLeidingen.contains(this) */ int debiet; /** * @peerObject <SUF>*/ Knoop bronknoop; /** * @peerObject */ Knoop doelknoop; public int getDebiet() { return debiet; } /** * @peerObject */ public Knoop getBronknoop() { return bronknoop; } /** * @peerObject */ public Knoop getDoelknoop() { return doelknoop; } /** * @throws IllegalArgumentException | debiet <= 0 * @post | getDebiet() == debiet * @post | getBronknoop() == null * @post | getDoelknoop() == null */ public Leiding(int debiet) { if (debiet <= 0) throw new IllegalArgumentException("`debiet` is not greater than zero"); this.debiet = debiet; } /** * @pre | getBronknoop() == null * @pre | bronknoop != null * @pre | doelknoop != null * @mutates_properties | getBronknoop(), getDoelknoop(), bronknoop.getUitgaandeLeidingen(), doelknoop.getInkomendeLeidingen() * @post | getBronknoop() == bronknoop * @post | getDoelknoop() == doelknoop * @post | getBronknoop().getUitgaandeLeidingen().equals(LogicalSet.plus(old(bronknoop.getUitgaandeLeidingen()), this)) * @post | getDoelknoop().getInkomendeLeidingen().equals(LogicalSet.plus(old(doelknoop.getInkomendeLeidingen()), this)) */ public void koppelAan(Knoop bronknoop, Knoop doelknoop) { this.bronknoop = bronknoop; this.doelknoop = doelknoop; bronknoop.uitgaandeLeidingen.add(this); doelknoop.inkomendeLeidingen.add(this); } /** * @pre | getBronknoop() != null * @mutates_properties | getBronknoop(), getDoelknoop(), getBronknoop().getUitgaandeLeidingen(), getDoelknoop().getInkomendeLeidingen() * @post | getBronknoop() == null * @post | getDoelknoop() == null * @post | old(getBronknoop()).getUitgaandeLeidingen().equals(LogicalSet.minus(old(getBronknoop().getUitgaandeLeidingen()), this)) * @post | old(getDoelknoop()).getInkomendeLeidingen().equals(LogicalSet.minus(old(getDoelknoop().getInkomendeLeidingen()), this)) */ public void ontkoppel() { bronknoop.uitgaandeLeidingen.remove(this); doelknoop.inkomendeLeidingen.remove(this); bronknoop = null; doelknoop = null; } /** * @creates | result * @post | Objects.equals(result, * | getBronknoop() == null * | ? * | Set.of() * | : * | Set.of(getBronknoop(), getDoelknoop()) * | ) */ @Override public Set<? extends Onderdeel> getGekoppeldeOnderdelen() { if (bronknoop == null) return Set.of(); return Set.of(bronknoop, doelknoop); } /** * @post | result == (onderdeel instanceof Leiding l && getDebiet() == l.getDebiet()) */ @Override public boolean isGelijkaardigAan(Onderdeel onderdeel) { return onderdeel instanceof Leiding l && debiet == l.debiet; } }
13744_8
package afvink3; /** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ /* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ /* (2) Declareer hier h1, h2, h3, h4 van het type Paard * Deze paarden instantieer je later in het programma */ /* (3) Declareer een button met de naam button van het type JButton */ int lengte = 250; Paard h1; Paard h2; Paard h3; Paard h4; JButton button; private JPanel panel; /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); /* (4) Geef het frame een breedte van 400 en hoogte van 140 */ frame.createGUI(); frame.setSize(400,140); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /** Tekenen van de finish streep */ /* (5) Geef de finish streep een rode kleur */ g.setColor(Color.red); g.fillRect(lengte, 0, 3, 100); /**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. */ h1 = new Paard("Lightning", Color.brown); h2 = new Paard("Storm", Color.black); h3 = new Paard("Wind", Color.white); h4 = new Paard("Rain", Color.gray); /** Loop tot een paard over de finish is*/ while (h1.getAfstand() < lengte && h2.getAfstand() < lengte && h3.getAfstand() < lengte && h4.getAfstand() < lengte) { h1.run(); h2.run(); h3.run(); h4.run(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ pauzeer(10); /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ tekenPaard(g, h1); tekenPaard(g, h2); tekenPaard(g, h3); tekenPaard(g, h4); } /** Kijk welk paard gewonnen heeft */ if (h1.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!"); } if (h2.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!"); } if (h3.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!"); } if (h4.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!"); } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new JPanel(); panel.setPreferredSize(new Dimension(300, 100)); panel.setBackground(Color.white); window.add(panel); button = new JButton("Run!"); /* (9) Zet hier de tekst Run! op de button */ window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { g.setColor(h.getKleur()); g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace (paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } }
itbc-bin/1819-owe5a-afvinkopdracht3-JanneKnuiman
afvink3/Race.java
1,553
/** Tekenen van de finish streep */
block_comment
nl
package afvink3; /** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ /* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ /* (2) Declareer hier h1, h2, h3, h4 van het type Paard * Deze paarden instantieer je later in het programma */ /* (3) Declareer een button met de naam button van het type JButton */ int lengte = 250; Paard h1; Paard h2; Paard h3; Paard h4; JButton button; private JPanel panel; /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); /* (4) Geef het frame een breedte van 400 en hoogte van 140 */ frame.createGUI(); frame.setSize(400,140); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /** Tekenen van de<SUF>*/ /* (5) Geef de finish streep een rode kleur */ g.setColor(Color.red); g.fillRect(lengte, 0, 3, 100); /**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. */ h1 = new Paard("Lightning", Color.brown); h2 = new Paard("Storm", Color.black); h3 = new Paard("Wind", Color.white); h4 = new Paard("Rain", Color.gray); /** Loop tot een paard over de finish is*/ while (h1.getAfstand() < lengte && h2.getAfstand() < lengte && h3.getAfstand() < lengte && h4.getAfstand() < lengte) { h1.run(); h2.run(); h3.run(); h4.run(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ pauzeer(10); /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ tekenPaard(g, h1); tekenPaard(g, h2); tekenPaard(g, h3); tekenPaard(g, h4); } /** Kijk welk paard gewonnen heeft */ if (h1.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!"); } if (h2.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!"); } if (h3.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!"); } if (h4.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!"); } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new JPanel(); panel.setPreferredSize(new Dimension(300, 100)); panel.setBackground(Color.white); window.add(panel); button = new JButton("Run!"); /* (9) Zet hier de tekst Run! op de button */ window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { g.setColor(h.getKleur()); g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace (paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } }
109730_37
package net.glowstone.block.blocktype; import lombok.Getter; import net.glowstone.EventFactory; import net.glowstone.block.GlowBlock; import net.glowstone.block.GlowSoundGroup; import net.glowstone.block.GlowBlockState; import net.glowstone.block.ItemTable; import net.glowstone.block.entity.BlockEntity; import net.glowstone.block.itemtype.ItemType; import net.glowstone.chunk.GlowChunk; import net.glowstone.entity.GlowPlayer; import net.glowstone.entity.physics.BlockBoundingBox; import net.glowstone.i18n.ConsoleMessages; import net.glowstone.i18n.GlowstoneMessages; import net.glowstone.util.SoundInfo; import net.glowstone.util.SoundUtil; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.Tag; import org.bukkit.block.BlockFace; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.event.block.BlockCanBuildEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Base class for specific types of blocks. */ public class BlockType extends ItemType { protected static final BlockFace[] SIDES = new BlockFace[] {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}; protected static final BlockFace[] ADJACENT = new BlockFace[] {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN}; protected List<ItemStack> drops; /** * Gets the sound that will be played when a player places the block. * * @return The sound to be played */ @Getter protected SoundInfo placeSound = new SoundInfo(Sound.BLOCK_WOOD_BREAK, 1F, 0.75F); @Getter protected GlowSoundGroup soundGroup; //////////////////////////////////////////////////////////////////////////// // Setters for subclass use /** * Gets the BlockFace opposite of the direction the location is facing. Usually used to set the * way container blocks face when being placed. * * @param location Location to get opposite of * @param inverted If up/down should be used * @return Opposite BlockFace or EAST if yaw is invalid */ protected static BlockFace getOppositeBlockFace(Location location, boolean inverted) { double rot = location.getYaw() % 360; if (inverted) { // todo: Check the 67.5 pitch in source. This is based off of WorldEdit's number for // this. double pitch = location.getPitch(); if (pitch < -67.5D) { return BlockFace.DOWN; } else if (pitch > 67.5D) { return BlockFace.UP; } } if (rot < 0) { rot += 360.0; } if (0 <= rot && rot < 45) { return BlockFace.NORTH; } else if (45 <= rot && rot < 135) { return BlockFace.EAST; } else if (135 <= rot && rot < 225) { return BlockFace.SOUTH; } else if (225 <= rot && rot < 315) { return BlockFace.WEST; } else if (315 <= rot && rot < 360.0) { return BlockFace.NORTH; } else { return BlockFace.EAST; } } //////////////////////////////////////////////////////////////////////////// // Public accessors protected final void setDrops(ItemStack... drops) { this.drops = Arrays.asList(drops); } /** * Get the items that will be dropped by digging the block. * * @param block The block being dug. * @param tool The tool used or {@code null} if fists or no tool was used. * @return The drops that should be returned. */ @NotNull public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) { if (!block.isValidTool(tool)) { return Collections.emptyList(); } if (drops == null) { // default calculation return Collections.singletonList(new ItemStack(block.getType(), 1, block.getData())); } else { return Collections.unmodifiableList(drops); } } /** * Sets the sound that will be played when a player places the block. * * @param sound The sound. */ public void setPlaceSound(Sound sound) { placeSound = new SoundInfo(sound, 1F, 0.75F); } //////////////////////////////////////////////////////////////////////////// // Actions /** * Get the items that would be dropped if the block was successfully mined. This is used f.e. to * calculate TNT drops. * * @param block The block. * @return The drops from that block. */ @NotNull public Collection<ItemStack> getMinedDrops(GlowBlock block) { return getDrops(block, null); } /** * Create a new block entity at the given location. * * @param chunk The chunk to create the block entity at. * @param cx The x coordinate in the chunk. * @param cy The y coordinate in the chunk. * @param cz The z coordinate in the chunk. * @return The new BlockEntity, or null if no block entity is used. */ public BlockEntity createBlockEntity(GlowChunk chunk, int cx, int cy, int cz) { return null; } /** * Check whether the block can be placed at the given location. * * @param player The player who placed the block. * @param block The location the block is being placed at. * @param against The face the block is being placed against. * @return Whether the placement is valid. */ public boolean canPlaceAt(@Nullable GlowPlayer player, GlowBlock block, BlockFace against) { return true; } /** * Called when a block is placed to calculate what the block will become. * * @param player the player who placed the block * @param state the BlockState to edit * @param holding the ItemStack that was being held * @param face the face off which the block is being placed * @param clickedLoc where in the block the click occurred */ public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { state.setType(holding.getType()); state.setData(holding.getData()); } /** * Called after a block has been placed by a player. * * @param player the player who placed the block * @param block the block that was placed * @param holding the the ItemStack that was being held * @param oldState The old block state before the block was placed. */ public void afterPlace(GlowPlayer player, GlowBlock block, ItemStack holding, GlowBlockState oldState) { block.applyPhysics(oldState.getType(), block.getType(), oldState.getRawData(), block.getData()); } /** * Called when a player attempts to interact with (right-click) a block of this type already in * the world. * * @param player the player interacting * @param block the block interacted with * @param face the clicked face * @param clickedLoc where in the block the click occurred * @return Whether the interaction occurred. */ public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face, Vector clickedLoc) { return false; } /** * Called when a player attempts to destroy a block. * * @param player The player interacting * @param block The block the player destroyed * @param face The block face */ public void blockDestroy(GlowPlayer player, GlowBlock block, BlockFace face) { // do nothing } /** * Called after a player successfully destroys a block. * * @param player The player interacting * @param block The block the player destroyed * @param face The block face * @param oldState The block state of the block the player destroyed. */ public void afterDestroy(GlowPlayer player, GlowBlock block, BlockFace face, GlowBlockState oldState) { block.applyPhysics(oldState.getType(), block.getType(), oldState.getRawData(), block.getData()); } /** * Called when the BlockType gets pulsed as requested. * * @param block The block that was pulsed */ public void receivePulse(GlowBlock block) { block.getWorld().cancelPulse(block); } /** * Called when a player attempts to place a block on an existing block of this type. Used to * determine if the placement should occur into the air adjacent to the block (normal behavior), * or absorbed into the block clicked on. * * @param block The block the player right-clicked * @param face The face on which the click occurred * @param holding The ItemStack the player was holding * @return Whether the place should occur into the block given. */ public boolean canAbsorb(GlowBlock block, BlockFace face, ItemStack holding) { return false; } /** * Called to check if this block can be overridden by a block place which would occur inside it. * * @param block The block being targeted by the placement * @param face The face on which the click occurred * @param holding The ItemStack the player was holding * @return Whether this block can be overridden. */ public boolean canOverride(GlowBlock block, BlockFace face, ItemStack holding) { return block.isLiquid(); } /** * Called when a neighboring block (within a 3x3x3 cube) has changed its type or data and * physics checks should occur. * * @param block The block to perform physics checks for * @param face The BlockFace to the changed block, or null if unavailable * @param changedBlock The neighboring block that has changed * @param oldType The old type of the changed block * @param oldData The old data of the changed block * @param newType The new type of the changed block * @param newData The new data of the changed block */ public void onNearBlockChanged(GlowBlock block, BlockFace face, GlowBlock changedBlock, Material oldType, byte oldData, Material newType, byte newData) { } /** * Called when this block has just changed to some other type. * * <p>This is called whenever {@link GlowBlock#setTypeIdAndData}, {@link GlowBlock#setType} * or {@link GlowBlock#setData} is called with physics enabled, and might * be called from plugins or other means of changing the block. * * @param block The block that was changed * @param oldType The old Material * @param oldData The old data * @param newType The new Material * @param data The new data */ public void onBlockChanged(GlowBlock block, Material oldType, byte oldData, Material newType, byte data) { // do nothing } /** * <p>Called when the BlockType should calculate the current physics.</p> * <p>Subclasses should override {@link #updatePhysicsAfterEvent(GlowBlock)} * if they need a custom handling of the physics calculation</p> * * @param block The block */ public final void updatePhysics(GlowBlock block) { if (!block.getWorld().isInitialized()) { return; } BlockPhysicsEvent event = EventFactory.getInstance() .callEvent(new BlockPhysicsEvent(block, block.getBlockData())); if (!event.isCancelled()) { updatePhysicsAfterEvent(block); } } public void updatePhysicsAfterEvent(GlowBlock block) { // do nothing } @Override public final void rightClickBlock(GlowPlayer player, GlowBlock against, BlockFace face, ItemStack holding, Vector clickedLoc, EquipmentSlot hand) { GlowBlock target = against.getRelative(face); final Material targetMat = ItemTable.instance().getBlock( target.getRelative(face.getOppositeFace()).getType()).getMaterial(); // prevent building above the height limit final int maxHeight = target.getWorld().getMaxHeight(); if (target.getLocation().getY() >= maxHeight) { GlowstoneMessages.Block.MAX_HEIGHT.send(player, maxHeight); return; } // check whether the block clicked against should absorb the placement BlockType againstType = ItemTable.instance().getBlock(against.getType()); if (againstType != null) { if (againstType.canAbsorb(against, face, holding)) { target = against; } else if (!target.isEmpty()) { // air can always be overridden BlockType targetType = ItemTable.instance().getBlock(target.getType()); if (targetType != null && !targetType.canOverride(target, face, holding)) { return; } } } if (getMaterial().isSolid()) { BlockBoundingBox box = new BlockBoundingBox(target); List<Entity> entities = target.getWorld().getEntityManager() .getEntitiesInside(box, null); for (Entity e : entities) { if (e instanceof LivingEntity) { return; } } } // call canBuild event boolean canBuild = true; if (Tag.SIGNS.isTagged(targetMat)) { if (player.isSneaking()) { canBuild = canPlaceAt(player, target, face); } else { return; } } else { canBuild = canPlaceAt(player, target, face); } BlockCanBuildEvent canBuildEvent = new BlockCanBuildEvent(target, against.getBlockData(), canBuild); if (!EventFactory.getInstance().callEvent(canBuildEvent).isBuildable()) { //revert(player, target); return; } // grab states and update block GlowBlockState oldState = target.getState(); GlowBlockState newState = target.getState(); ItemType itemType = ItemTable.instance().getItem(holding.getType()); if (itemType.getPlaceAs() == null) { placeBlock(player, newState, face, holding, clickedLoc); } else { placeBlock(player, newState, face, new ItemStack(itemType.getPlaceAs().getMaterial(), holding.getAmount(), holding.getDurability()), clickedLoc); } newState.update(true); // call blockPlace event BlockPlaceEvent event = new BlockPlaceEvent(target, oldState, against, holding, player, canBuild, hand); EventFactory.getInstance().callEvent(event); if (event.isCancelled() || !event.canBuild()) { oldState.update(true); return; } // play the placement sound, except for the current player (handled by the client) SoundUtil.playSoundAtLocationExcept(target.getLocation(), getPlaceSound().getSound(), (getPlaceSound().getVolume() + 1F) / 2F, getPlaceSound().getPitch() * 0.8F, player); // do any after-place actions afterPlace(player, target, holding, oldState); // deduct from stack if not in creative mode if (player.getGameMode() != GameMode.CREATIVE) { holding.setAmount(holding.getAmount() - 1); } } /** * Called to check if this block can perform random tick updates. * * @return Whether this block updates on tick. */ public boolean canTickRandomly() { return false; } /** * Called when this block needs to be updated. * * @param block The block that needs an update */ public void updateBlock(GlowBlock block) { // do nothing } //////////////////////////////////////////////////////////////////////////// // Helper methods /** * Called when a player left clicks a block. * * @param player the player who clicked the block * @param block the block that was clicked * @param holding the ItemStack that was being held */ public void leftClickBlock(GlowPlayer player, GlowBlock block, ItemStack holding) { // do nothing } /** * Display the warning for finding the wrong MaterialData subclass. * * @param clazz The expected subclass of MaterialData. * @param data The actual MaterialData found. * @deprecated MaterialData is no longer used (1.13). Use getCastedBlockData. */ @Deprecated protected void warnMaterialData(Class<?> clazz, MaterialData data) { ConsoleMessages.Warn.Block.WRONG_MATERIAL_DATA.log( getMaterial(), getClass().getSimpleName(), clazz.getSimpleName(), data); } /** * Assert that block data matches the expected BlockData class * * @param clazz The expected subclass of BlockData. * @param data The actual MaterialData found. * @return The casted block data. */ protected <T extends BlockData> T getCastedBlockData(Class<T> clazz, BlockData data) { if (clazz.isInstance(data)) { return clazz.cast(data); } throw new UnsupportedOperationException(ConsoleMessages.Warn.Block.WRONG_BLOCK_DATA.get( getMaterial(), getClass().getSimpleName(), clazz.getSimpleName(), data)); } public void onRedstoneUpdate(GlowBlock block) { // do nothing } /** * Called when an entity gets updated on top of the block. * * @param block the block that was stepped on * @param entity the entity */ public void onEntityStep(GlowBlock block, LivingEntity entity) { // do nothing } @Override public BlockType getPlaceAs() { return this; } public void requestPulse(GlowBlockState state) { // do nothing } /** * The rate at which the block should be pulsed. * * @param block the block * @return 0 if the block should not pulse, or a number of ticks between pulses. */ public int getPulseTickSpeed(GlowBlock block) { // Override if needs pulse return 0; } /** * Whether the block should only be pulsed once. * * @param block the block * @return true if the block should be pulsed once, false otherwise. */ public boolean isPulseOnce(GlowBlock block) { return true; } }
GlowstoneMC/Glowstone
src/main/java/net/glowstone/block/blocktype/BlockType.java
4,805
// Override if needs pulse
line_comment
nl
package net.glowstone.block.blocktype; import lombok.Getter; import net.glowstone.EventFactory; import net.glowstone.block.GlowBlock; import net.glowstone.block.GlowSoundGroup; import net.glowstone.block.GlowBlockState; import net.glowstone.block.ItemTable; import net.glowstone.block.entity.BlockEntity; import net.glowstone.block.itemtype.ItemType; import net.glowstone.chunk.GlowChunk; import net.glowstone.entity.GlowPlayer; import net.glowstone.entity.physics.BlockBoundingBox; import net.glowstone.i18n.ConsoleMessages; import net.glowstone.i18n.GlowstoneMessages; import net.glowstone.util.SoundInfo; import net.glowstone.util.SoundUtil; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.Tag; import org.bukkit.block.BlockFace; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.event.block.BlockCanBuildEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Base class for specific types of blocks. */ public class BlockType extends ItemType { protected static final BlockFace[] SIDES = new BlockFace[] {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}; protected static final BlockFace[] ADJACENT = new BlockFace[] {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN}; protected List<ItemStack> drops; /** * Gets the sound that will be played when a player places the block. * * @return The sound to be played */ @Getter protected SoundInfo placeSound = new SoundInfo(Sound.BLOCK_WOOD_BREAK, 1F, 0.75F); @Getter protected GlowSoundGroup soundGroup; //////////////////////////////////////////////////////////////////////////// // Setters for subclass use /** * Gets the BlockFace opposite of the direction the location is facing. Usually used to set the * way container blocks face when being placed. * * @param location Location to get opposite of * @param inverted If up/down should be used * @return Opposite BlockFace or EAST if yaw is invalid */ protected static BlockFace getOppositeBlockFace(Location location, boolean inverted) { double rot = location.getYaw() % 360; if (inverted) { // todo: Check the 67.5 pitch in source. This is based off of WorldEdit's number for // this. double pitch = location.getPitch(); if (pitch < -67.5D) { return BlockFace.DOWN; } else if (pitch > 67.5D) { return BlockFace.UP; } } if (rot < 0) { rot += 360.0; } if (0 <= rot && rot < 45) { return BlockFace.NORTH; } else if (45 <= rot && rot < 135) { return BlockFace.EAST; } else if (135 <= rot && rot < 225) { return BlockFace.SOUTH; } else if (225 <= rot && rot < 315) { return BlockFace.WEST; } else if (315 <= rot && rot < 360.0) { return BlockFace.NORTH; } else { return BlockFace.EAST; } } //////////////////////////////////////////////////////////////////////////// // Public accessors protected final void setDrops(ItemStack... drops) { this.drops = Arrays.asList(drops); } /** * Get the items that will be dropped by digging the block. * * @param block The block being dug. * @param tool The tool used or {@code null} if fists or no tool was used. * @return The drops that should be returned. */ @NotNull public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) { if (!block.isValidTool(tool)) { return Collections.emptyList(); } if (drops == null) { // default calculation return Collections.singletonList(new ItemStack(block.getType(), 1, block.getData())); } else { return Collections.unmodifiableList(drops); } } /** * Sets the sound that will be played when a player places the block. * * @param sound The sound. */ public void setPlaceSound(Sound sound) { placeSound = new SoundInfo(sound, 1F, 0.75F); } //////////////////////////////////////////////////////////////////////////// // Actions /** * Get the items that would be dropped if the block was successfully mined. This is used f.e. to * calculate TNT drops. * * @param block The block. * @return The drops from that block. */ @NotNull public Collection<ItemStack> getMinedDrops(GlowBlock block) { return getDrops(block, null); } /** * Create a new block entity at the given location. * * @param chunk The chunk to create the block entity at. * @param cx The x coordinate in the chunk. * @param cy The y coordinate in the chunk. * @param cz The z coordinate in the chunk. * @return The new BlockEntity, or null if no block entity is used. */ public BlockEntity createBlockEntity(GlowChunk chunk, int cx, int cy, int cz) { return null; } /** * Check whether the block can be placed at the given location. * * @param player The player who placed the block. * @param block The location the block is being placed at. * @param against The face the block is being placed against. * @return Whether the placement is valid. */ public boolean canPlaceAt(@Nullable GlowPlayer player, GlowBlock block, BlockFace against) { return true; } /** * Called when a block is placed to calculate what the block will become. * * @param player the player who placed the block * @param state the BlockState to edit * @param holding the ItemStack that was being held * @param face the face off which the block is being placed * @param clickedLoc where in the block the click occurred */ public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) { state.setType(holding.getType()); state.setData(holding.getData()); } /** * Called after a block has been placed by a player. * * @param player the player who placed the block * @param block the block that was placed * @param holding the the ItemStack that was being held * @param oldState The old block state before the block was placed. */ public void afterPlace(GlowPlayer player, GlowBlock block, ItemStack holding, GlowBlockState oldState) { block.applyPhysics(oldState.getType(), block.getType(), oldState.getRawData(), block.getData()); } /** * Called when a player attempts to interact with (right-click) a block of this type already in * the world. * * @param player the player interacting * @param block the block interacted with * @param face the clicked face * @param clickedLoc where in the block the click occurred * @return Whether the interaction occurred. */ public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face, Vector clickedLoc) { return false; } /** * Called when a player attempts to destroy a block. * * @param player The player interacting * @param block The block the player destroyed * @param face The block face */ public void blockDestroy(GlowPlayer player, GlowBlock block, BlockFace face) { // do nothing } /** * Called after a player successfully destroys a block. * * @param player The player interacting * @param block The block the player destroyed * @param face The block face * @param oldState The block state of the block the player destroyed. */ public void afterDestroy(GlowPlayer player, GlowBlock block, BlockFace face, GlowBlockState oldState) { block.applyPhysics(oldState.getType(), block.getType(), oldState.getRawData(), block.getData()); } /** * Called when the BlockType gets pulsed as requested. * * @param block The block that was pulsed */ public void receivePulse(GlowBlock block) { block.getWorld().cancelPulse(block); } /** * Called when a player attempts to place a block on an existing block of this type. Used to * determine if the placement should occur into the air adjacent to the block (normal behavior), * or absorbed into the block clicked on. * * @param block The block the player right-clicked * @param face The face on which the click occurred * @param holding The ItemStack the player was holding * @return Whether the place should occur into the block given. */ public boolean canAbsorb(GlowBlock block, BlockFace face, ItemStack holding) { return false; } /** * Called to check if this block can be overridden by a block place which would occur inside it. * * @param block The block being targeted by the placement * @param face The face on which the click occurred * @param holding The ItemStack the player was holding * @return Whether this block can be overridden. */ public boolean canOverride(GlowBlock block, BlockFace face, ItemStack holding) { return block.isLiquid(); } /** * Called when a neighboring block (within a 3x3x3 cube) has changed its type or data and * physics checks should occur. * * @param block The block to perform physics checks for * @param face The BlockFace to the changed block, or null if unavailable * @param changedBlock The neighboring block that has changed * @param oldType The old type of the changed block * @param oldData The old data of the changed block * @param newType The new type of the changed block * @param newData The new data of the changed block */ public void onNearBlockChanged(GlowBlock block, BlockFace face, GlowBlock changedBlock, Material oldType, byte oldData, Material newType, byte newData) { } /** * Called when this block has just changed to some other type. * * <p>This is called whenever {@link GlowBlock#setTypeIdAndData}, {@link GlowBlock#setType} * or {@link GlowBlock#setData} is called with physics enabled, and might * be called from plugins or other means of changing the block. * * @param block The block that was changed * @param oldType The old Material * @param oldData The old data * @param newType The new Material * @param data The new data */ public void onBlockChanged(GlowBlock block, Material oldType, byte oldData, Material newType, byte data) { // do nothing } /** * <p>Called when the BlockType should calculate the current physics.</p> * <p>Subclasses should override {@link #updatePhysicsAfterEvent(GlowBlock)} * if they need a custom handling of the physics calculation</p> * * @param block The block */ public final void updatePhysics(GlowBlock block) { if (!block.getWorld().isInitialized()) { return; } BlockPhysicsEvent event = EventFactory.getInstance() .callEvent(new BlockPhysicsEvent(block, block.getBlockData())); if (!event.isCancelled()) { updatePhysicsAfterEvent(block); } } public void updatePhysicsAfterEvent(GlowBlock block) { // do nothing } @Override public final void rightClickBlock(GlowPlayer player, GlowBlock against, BlockFace face, ItemStack holding, Vector clickedLoc, EquipmentSlot hand) { GlowBlock target = against.getRelative(face); final Material targetMat = ItemTable.instance().getBlock( target.getRelative(face.getOppositeFace()).getType()).getMaterial(); // prevent building above the height limit final int maxHeight = target.getWorld().getMaxHeight(); if (target.getLocation().getY() >= maxHeight) { GlowstoneMessages.Block.MAX_HEIGHT.send(player, maxHeight); return; } // check whether the block clicked against should absorb the placement BlockType againstType = ItemTable.instance().getBlock(against.getType()); if (againstType != null) { if (againstType.canAbsorb(against, face, holding)) { target = against; } else if (!target.isEmpty()) { // air can always be overridden BlockType targetType = ItemTable.instance().getBlock(target.getType()); if (targetType != null && !targetType.canOverride(target, face, holding)) { return; } } } if (getMaterial().isSolid()) { BlockBoundingBox box = new BlockBoundingBox(target); List<Entity> entities = target.getWorld().getEntityManager() .getEntitiesInside(box, null); for (Entity e : entities) { if (e instanceof LivingEntity) { return; } } } // call canBuild event boolean canBuild = true; if (Tag.SIGNS.isTagged(targetMat)) { if (player.isSneaking()) { canBuild = canPlaceAt(player, target, face); } else { return; } } else { canBuild = canPlaceAt(player, target, face); } BlockCanBuildEvent canBuildEvent = new BlockCanBuildEvent(target, against.getBlockData(), canBuild); if (!EventFactory.getInstance().callEvent(canBuildEvent).isBuildable()) { //revert(player, target); return; } // grab states and update block GlowBlockState oldState = target.getState(); GlowBlockState newState = target.getState(); ItemType itemType = ItemTable.instance().getItem(holding.getType()); if (itemType.getPlaceAs() == null) { placeBlock(player, newState, face, holding, clickedLoc); } else { placeBlock(player, newState, face, new ItemStack(itemType.getPlaceAs().getMaterial(), holding.getAmount(), holding.getDurability()), clickedLoc); } newState.update(true); // call blockPlace event BlockPlaceEvent event = new BlockPlaceEvent(target, oldState, against, holding, player, canBuild, hand); EventFactory.getInstance().callEvent(event); if (event.isCancelled() || !event.canBuild()) { oldState.update(true); return; } // play the placement sound, except for the current player (handled by the client) SoundUtil.playSoundAtLocationExcept(target.getLocation(), getPlaceSound().getSound(), (getPlaceSound().getVolume() + 1F) / 2F, getPlaceSound().getPitch() * 0.8F, player); // do any after-place actions afterPlace(player, target, holding, oldState); // deduct from stack if not in creative mode if (player.getGameMode() != GameMode.CREATIVE) { holding.setAmount(holding.getAmount() - 1); } } /** * Called to check if this block can perform random tick updates. * * @return Whether this block updates on tick. */ public boolean canTickRandomly() { return false; } /** * Called when this block needs to be updated. * * @param block The block that needs an update */ public void updateBlock(GlowBlock block) { // do nothing } //////////////////////////////////////////////////////////////////////////// // Helper methods /** * Called when a player left clicks a block. * * @param player the player who clicked the block * @param block the block that was clicked * @param holding the ItemStack that was being held */ public void leftClickBlock(GlowPlayer player, GlowBlock block, ItemStack holding) { // do nothing } /** * Display the warning for finding the wrong MaterialData subclass. * * @param clazz The expected subclass of MaterialData. * @param data The actual MaterialData found. * @deprecated MaterialData is no longer used (1.13). Use getCastedBlockData. */ @Deprecated protected void warnMaterialData(Class<?> clazz, MaterialData data) { ConsoleMessages.Warn.Block.WRONG_MATERIAL_DATA.log( getMaterial(), getClass().getSimpleName(), clazz.getSimpleName(), data); } /** * Assert that block data matches the expected BlockData class * * @param clazz The expected subclass of BlockData. * @param data The actual MaterialData found. * @return The casted block data. */ protected <T extends BlockData> T getCastedBlockData(Class<T> clazz, BlockData data) { if (clazz.isInstance(data)) { return clazz.cast(data); } throw new UnsupportedOperationException(ConsoleMessages.Warn.Block.WRONG_BLOCK_DATA.get( getMaterial(), getClass().getSimpleName(), clazz.getSimpleName(), data)); } public void onRedstoneUpdate(GlowBlock block) { // do nothing } /** * Called when an entity gets updated on top of the block. * * @param block the block that was stepped on * @param entity the entity */ public void onEntityStep(GlowBlock block, LivingEntity entity) { // do nothing } @Override public BlockType getPlaceAs() { return this; } public void requestPulse(GlowBlockState state) { // do nothing } /** * The rate at which the block should be pulsed. * * @param block the block * @return 0 if the block should not pulse, or a number of ticks between pulses. */ public int getPulseTickSpeed(GlowBlock block) { // Override if<SUF> return 0; } /** * Whether the block should only be pulsed once. * * @param block the block * @return true if the block should be pulsed once, false otherwise. */ public boolean isPulseOnce(GlowBlock block) { return true; } }
101416_1
package hu.adsd.projects; import hu.adsd.ClimateApp; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class ProductsConfigurationController implements Initializable { private ProductsConfiguration productsConfiguration; private int selectedConfiguration; @FXML private Label refEnergy; @FXML private Label totalEnergy; @FXML private Label differenceEnergy; @FXML private VBox buildingPartsBox; public ProductsConfigurationController( int selectedConfiguration ) { this.selectedConfiguration = selectedConfiguration; this.productsConfiguration = ClimateApp .getProject() .getConfigurations() .get( selectedConfiguration ); } @Override public void initialize( URL url, ResourceBundle resourceBundle ) { // Create BuildingParts with inner BuildingMaterials for ( BuildingPart buildingPart : productsConfiguration.getBuildingParts() ) { // Eerst nieuw vierkant maken // Create loader for loading productCardView VBOX FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource( "../../../projectBuildingPartView.fxml" ) ); // Use the ProductCardController Constructor with the current Product from the Loop fxmlLoader.setControllerFactory( controller -> new BuildingPartController( buildingPart ) ); // Load the VBox into the productsBox try { buildingPartsBox.getChildren().add( fxmlLoader.load() ); } catch ( IOException e ) { e.printStackTrace(); } } refEnergy.setText( "Lineair: " + productsConfiguration.getEmbodiedEnergy() ); totalEnergy.setText( "Huidig: " + productsConfiguration.getEmbodiedEnergy() ); differenceEnergy.setText( "Bespaard: " + productsConfiguration.getEmbodiedEnergy() ); } public void goToProject() throws IOException { ClimateApp.goToScreen( "projectView" ); } public void addProduct() throws IOException { ClimateApp.goToProductsScreen( selectedConfiguration ); } }
schonewillerf/ClimateApp
src/main/java/hu/adsd/projects/ProductsConfigurationController.java
532
// Eerst nieuw vierkant maken
line_comment
nl
package hu.adsd.projects; import hu.adsd.ClimateApp; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class ProductsConfigurationController implements Initializable { private ProductsConfiguration productsConfiguration; private int selectedConfiguration; @FXML private Label refEnergy; @FXML private Label totalEnergy; @FXML private Label differenceEnergy; @FXML private VBox buildingPartsBox; public ProductsConfigurationController( int selectedConfiguration ) { this.selectedConfiguration = selectedConfiguration; this.productsConfiguration = ClimateApp .getProject() .getConfigurations() .get( selectedConfiguration ); } @Override public void initialize( URL url, ResourceBundle resourceBundle ) { // Create BuildingParts with inner BuildingMaterials for ( BuildingPart buildingPart : productsConfiguration.getBuildingParts() ) { // Eerst nieuw<SUF> // Create loader for loading productCardView VBOX FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource( "../../../projectBuildingPartView.fxml" ) ); // Use the ProductCardController Constructor with the current Product from the Loop fxmlLoader.setControllerFactory( controller -> new BuildingPartController( buildingPart ) ); // Load the VBox into the productsBox try { buildingPartsBox.getChildren().add( fxmlLoader.load() ); } catch ( IOException e ) { e.printStackTrace(); } } refEnergy.setText( "Lineair: " + productsConfiguration.getEmbodiedEnergy() ); totalEnergy.setText( "Huidig: " + productsConfiguration.getEmbodiedEnergy() ); differenceEnergy.setText( "Bespaard: " + productsConfiguration.getEmbodiedEnergy() ); } public void goToProject() throws IOException { ClimateApp.goToScreen( "projectView" ); } public void addProduct() throws IOException { ClimateApp.goToProductsScreen( selectedConfiguration ); } }
13709_4
import greenfoot.*; /** * * @author R. Springer */ public class Hero extends Mover { private final double gravity; private final double acc; private final double drag; private final GreenfootImage staand= new GreenfootImage("staand.png"); private final GreenfootImage RMidle= new GreenfootImage("p123.png"); private final GreenfootImage RMjump= new GreenfootImage("p1_jump.png"); private final GreenfootImage RMwalk1= new GreenfootImage("p1_walk01.png"); private final GreenfootImage RMwalk2= new GreenfootImage("p1_walk02.png"); private final GreenfootImage RMwalk3= new GreenfootImage("p1_walk03.png"); private final GreenfootImage RMwalk4= new GreenfootImage("p1_walk04.png"); private final GreenfootImage RMwalk5= new GreenfootImage("p1_walk05.png"); private final GreenfootImage RMwalk6= new GreenfootImage("p1_walk06.png"); private final GreenfootImage RMwalk7= new GreenfootImage("p1_walk07.png"); private final GreenfootImage RMwalk8= new GreenfootImage("p1_walk08.png"); private final GreenfootImage RMwalk9= new GreenfootImage("p1_walk09.png"); private final GreenfootImage RMwalk10= new GreenfootImage("p1_walk10.png"); private final GreenfootImage RMwalk11= new GreenfootImage("p1_walk11.png"); private final GreenfootImage LMidle = new GreenfootImage("p123inv.png"); private final GreenfootImage LMjump = new GreenfootImage(RMjump); private final GreenfootImage LMwalk1 = new GreenfootImage("p1inv_walk01.png"); private final GreenfootImage LMwalk2 = new GreenfootImage("p1inv_walk02.png"); private final GreenfootImage LMwalk3 = new GreenfootImage("p1inv_walk03.png"); private final GreenfootImage LMwalk4 = new GreenfootImage("p1inv_walk04.png"); private final GreenfootImage LMwalk5 = new GreenfootImage("p1inv_walk05.png"); private final GreenfootImage LMwalk6 = new GreenfootImage("p1inv_walk06.png"); private final GreenfootImage LMwalk7 = new GreenfootImage("p1inv_walk07.png"); private final GreenfootImage LMwalk8 = new GreenfootImage("p1inv_walk08.png"); private final GreenfootImage LMwalk9 = new GreenfootImage("p1inv_walk09.png"); private final GreenfootImage LMwalk10 = new GreenfootImage("p1inv_walk10.png"); private final GreenfootImage LMwalk11 = new GreenfootImage("p1inv_walk11.png"); public int checkpoint = 0; private int speed = 3; private int frame; private boolean lopen; private boolean Kijkenrechts; private boolean isKeyPressed; public int x; public int y; public boolean key = false; public boolean door = false; public boolean openDeur1 = false; public boolean touchDeur1 = false; public double levens = 2; public static int munten; public boolean munten2; public String worldName; boolean isDood=false; boolean removedBadGuy=false; public String actieveWereld; public Hero() { super(); gravity = 9.8; acc = 0.6; drag = 0.8; setImage("p123.png"); this.worldName= worldName; setImage(RMidle); lopen = false; Kijkenrechts = true; RMidle.scale(70,100); RMjump.scale(70,100); RMwalk1.scale(70,100); RMwalk2.scale(70,100); RMwalk3.scale(70,100); RMwalk4.scale(70,100); RMwalk5.scale(70,100); RMwalk6.scale(70,100); RMwalk7.scale(70,100); RMwalk8.scale(70,100); RMwalk9.scale(70,100); RMwalk10.scale(70,100); RMwalk11.scale(70,100); LMidle.scale(70,100); LMjump.scale(70,100); LMwalk1.scale(70,100); LMwalk2.scale(70,100); LMwalk3.scale(70,100); LMwalk4.scale(70,100); LMwalk5.scale(70,100); LMwalk6.scale(70,100); LMwalk7.scale(70,100); LMwalk8.scale(70,100); LMwalk9.scale(70,100); LMwalk10.scale(70,100); LMwalk11.scale(70,100); } @Override public void act() { handleInput(); { checkKeys(); onGround(); } getWorld().showText(getX() + "," + getY(),500,50); velocityX *= drag; velocityY += acc; if (velocityY > gravity) { velocityY = gravity; } applyVelocity(); openDeur1(); eatCoins(); eatKeys(); //doodgaan door for (Actor enemy : getIntersectingObjects(Enemy.class)) { if (enemy != null) { //getWorld().removeObject(this); respawn(); break; } } for (Actor enemy : getIntersectingObjects(LavaTile.class)) { if (enemy != null) { //getWorld().removeObject(this); respawn(); return; } } for(Actor enemy : getIntersectingObjects(Water.class)){ if(enemy != null){ getWorld().removeObject(this); respawn(); return; } } for (Actor enemy : getIntersectingObjects(Death.class)) { if (enemy != null) { respawn(); break; } } for ( Actor enemy: getIntersectingObjects(Death.class)){ if(enemy != null){ respawn(); return; } } } //wereld naam aangeven public void wereld() { if(worldName == "MyWorld"){ String actieveWereld="MyWorld"; } else { String actieveWereld="Level2"; } } // respawn methode met gameover scherm en checkpoints public void respawn() { if (levens == 1 ) { Greenfoot.setWorld(new GameOver()); } if(checkpoint == 1){ setLocation(2785, 1990); levens --; } else if (checkpoint == 2){ setLocation(500, 500); levens --; } else if (checkpoint == 3){ setLocation(500, 500); levens --; } else if (checkpoint == 4){ setLocation(500, 500); levens --; } else { setLocation(87, 2890); levens --; } } //checkpoint waardes aangeven public void checkpoints() { if(isTouching(Checkpoint.class)) { checkpoint = 1; } if(isTouching(Checkpoint2.class)) { checkpoint = 2; } if(isTouching(Checkpoint3.class)) { checkpoint = 3; } if(isTouching(Checkpoint4.class)) { checkpoint = 4; } } //levens public double hearts(){ levens = levens; return levens; } //de death methode zodat alles onder 1 ding valt public void Death() { if (isTouching(LavaTile.class)) { respawn(); } if(isTouching(Water.class)) { respawn(); } } // positie methode voor informatie doorgeven public String positie() { String a= "X"+getX()+"Y"+getY(); return a; } //methode om coins weg te halen public int eatCoins() { Actor Coin = getOneIntersectingObject(Coin.class); if(isTouching(Coin.class)) { removeTouching(Coin.class); munten = munten + 1; } return munten; } public void eatKeys() { Actor Key = getOneIntersectingObject(Keys.class); if(isTouching(Keys.class)) { removeTouching(Keys.class); key = true; } } //methode om de knoppen van het toetsenboord te controleren public void checkKeys() { isKeyPressed = false; if (Greenfoot.isKeyDown("d") && Greenfoot.isKeyDown("a")) { stoplopen(); isKeyPressed = true; } else if (Greenfoot.isKeyDown("d")) { walkRight(); setLocation (getX()+speed, getY()); isKeyPressed = true; } else if (Greenfoot.isKeyDown("a")) { walkLeft(); setLocation (getX()-speed, getY()); isKeyPressed = true; } else if (Greenfoot.isKeyDown("space")) { respawn(); } if (!(isKeyPressed)) { stoplopen(); } } //de methode van de deuren public boolean openDeur1() { if (isTouching(Deur1.class) && (key = true)) { openDeur1 = true; Greenfoot.setWorld(new Level2()); } if ( isTouching(Deur2.class)) { Greenfoot.setWorld(new Einde()); } return openDeur1; } // de methode zodat je niet konstant kan springen public boolean onGround() { Actor under = getOneObjectAtOffset (0, getHeight ()/2, Tile.class); Tile tile = (Tile) under; return tile != null && tile.isSolid == true; } // de methode om de badguy weg te halen public void removeBadGuy() { if(isTouching(BadGuy.class)) { removeTouching(BadGuy.class); removedBadGuy=true; return; } } // de methode voor de jump public void handleInput() { if ((Greenfoot.isKeyDown("w") && onGround() == true ) ||(Greenfoot.isKeyDown("w") && isTouching(JumpTile.class))) { setImage("springen.png"); velocityY = -15; } if (velocityY != -5); { setImage("springen.png"); } if (Greenfoot.isKeyDown("a")) { velocityX = -4; } else if (Greenfoot.isKeyDown("d")) { velocityX = 4; } } public int getWidth() { return getImage().getWidth(); } public int getHeight() { return getImage().getHeight(); } // de methode voor de animatie public void walkRight() { lopen = true; Kijkenrechts = true; frame ++; if(frame==1) { setImage(RMidle); } else if(frame==2) { setImage(RMwalk1); } else if(frame==3) { setImage(RMwalk2); } else if(frame==4) { setImage(RMwalk3); } else if(frame==5) { setImage(RMwalk4); } else if(frame==6) { setImage(RMwalk5); } else if(frame==7) { setImage(RMwalk6); } else if(frame==8) { setImage(RMwalk7); } else if(frame==9) { setImage(RMwalk8); } else if(frame==10) { setImage(RMwalk9); } else if(frame==11) { setImage(RMwalk10); } else if (frame==12){ setImage(RMwalk11); frame = 1; return; } } // de andere methode voor de animatie public void walkLeft() { lopen = true; Kijkenrechts = false; frame ++; if(frame==1) { setImage(LMidle); } else if(frame==2) { setImage(LMwalk1); } else if(frame==3) { setImage(LMwalk2); } else if(frame==4) { setImage(LMwalk3); } else if(frame==5) { setImage(LMwalk4); } else if(frame==6) { setImage(LMwalk5); } else if(frame==7) { setImage(LMwalk6); } else if(frame==8) { setImage(LMwalk7); } else if(frame==9) { setImage(LMwalk8); } else if(frame==10) { setImage(LMwalk9); } else if(frame==11) { setImage(LMwalk10); } else if (frame==12) { setImage(LMwalk11); frame = 1; return; } } // een methode om te stoppen met lopen public void stoplopen() { lopen = false; if (Kijkenrechts) setImage (RMidle); else setImage (LMidle); } // een methode om achter je positie te komen public String position() { String a= "x" +getX()+"y"+getY(); return a; } }
ROCMondriaanTIN/project-greenfoot-game-302175742
Hero.java
3,806
//de death methode zodat alles onder 1 ding valt
line_comment
nl
import greenfoot.*; /** * * @author R. Springer */ public class Hero extends Mover { private final double gravity; private final double acc; private final double drag; private final GreenfootImage staand= new GreenfootImage("staand.png"); private final GreenfootImage RMidle= new GreenfootImage("p123.png"); private final GreenfootImage RMjump= new GreenfootImage("p1_jump.png"); private final GreenfootImage RMwalk1= new GreenfootImage("p1_walk01.png"); private final GreenfootImage RMwalk2= new GreenfootImage("p1_walk02.png"); private final GreenfootImage RMwalk3= new GreenfootImage("p1_walk03.png"); private final GreenfootImage RMwalk4= new GreenfootImage("p1_walk04.png"); private final GreenfootImage RMwalk5= new GreenfootImage("p1_walk05.png"); private final GreenfootImage RMwalk6= new GreenfootImage("p1_walk06.png"); private final GreenfootImage RMwalk7= new GreenfootImage("p1_walk07.png"); private final GreenfootImage RMwalk8= new GreenfootImage("p1_walk08.png"); private final GreenfootImage RMwalk9= new GreenfootImage("p1_walk09.png"); private final GreenfootImage RMwalk10= new GreenfootImage("p1_walk10.png"); private final GreenfootImage RMwalk11= new GreenfootImage("p1_walk11.png"); private final GreenfootImage LMidle = new GreenfootImage("p123inv.png"); private final GreenfootImage LMjump = new GreenfootImage(RMjump); private final GreenfootImage LMwalk1 = new GreenfootImage("p1inv_walk01.png"); private final GreenfootImage LMwalk2 = new GreenfootImage("p1inv_walk02.png"); private final GreenfootImage LMwalk3 = new GreenfootImage("p1inv_walk03.png"); private final GreenfootImage LMwalk4 = new GreenfootImage("p1inv_walk04.png"); private final GreenfootImage LMwalk5 = new GreenfootImage("p1inv_walk05.png"); private final GreenfootImage LMwalk6 = new GreenfootImage("p1inv_walk06.png"); private final GreenfootImage LMwalk7 = new GreenfootImage("p1inv_walk07.png"); private final GreenfootImage LMwalk8 = new GreenfootImage("p1inv_walk08.png"); private final GreenfootImage LMwalk9 = new GreenfootImage("p1inv_walk09.png"); private final GreenfootImage LMwalk10 = new GreenfootImage("p1inv_walk10.png"); private final GreenfootImage LMwalk11 = new GreenfootImage("p1inv_walk11.png"); public int checkpoint = 0; private int speed = 3; private int frame; private boolean lopen; private boolean Kijkenrechts; private boolean isKeyPressed; public int x; public int y; public boolean key = false; public boolean door = false; public boolean openDeur1 = false; public boolean touchDeur1 = false; public double levens = 2; public static int munten; public boolean munten2; public String worldName; boolean isDood=false; boolean removedBadGuy=false; public String actieveWereld; public Hero() { super(); gravity = 9.8; acc = 0.6; drag = 0.8; setImage("p123.png"); this.worldName= worldName; setImage(RMidle); lopen = false; Kijkenrechts = true; RMidle.scale(70,100); RMjump.scale(70,100); RMwalk1.scale(70,100); RMwalk2.scale(70,100); RMwalk3.scale(70,100); RMwalk4.scale(70,100); RMwalk5.scale(70,100); RMwalk6.scale(70,100); RMwalk7.scale(70,100); RMwalk8.scale(70,100); RMwalk9.scale(70,100); RMwalk10.scale(70,100); RMwalk11.scale(70,100); LMidle.scale(70,100); LMjump.scale(70,100); LMwalk1.scale(70,100); LMwalk2.scale(70,100); LMwalk3.scale(70,100); LMwalk4.scale(70,100); LMwalk5.scale(70,100); LMwalk6.scale(70,100); LMwalk7.scale(70,100); LMwalk8.scale(70,100); LMwalk9.scale(70,100); LMwalk10.scale(70,100); LMwalk11.scale(70,100); } @Override public void act() { handleInput(); { checkKeys(); onGround(); } getWorld().showText(getX() + "," + getY(),500,50); velocityX *= drag; velocityY += acc; if (velocityY > gravity) { velocityY = gravity; } applyVelocity(); openDeur1(); eatCoins(); eatKeys(); //doodgaan door for (Actor enemy : getIntersectingObjects(Enemy.class)) { if (enemy != null) { //getWorld().removeObject(this); respawn(); break; } } for (Actor enemy : getIntersectingObjects(LavaTile.class)) { if (enemy != null) { //getWorld().removeObject(this); respawn(); return; } } for(Actor enemy : getIntersectingObjects(Water.class)){ if(enemy != null){ getWorld().removeObject(this); respawn(); return; } } for (Actor enemy : getIntersectingObjects(Death.class)) { if (enemy != null) { respawn(); break; } } for ( Actor enemy: getIntersectingObjects(Death.class)){ if(enemy != null){ respawn(); return; } } } //wereld naam aangeven public void wereld() { if(worldName == "MyWorld"){ String actieveWereld="MyWorld"; } else { String actieveWereld="Level2"; } } // respawn methode met gameover scherm en checkpoints public void respawn() { if (levens == 1 ) { Greenfoot.setWorld(new GameOver()); } if(checkpoint == 1){ setLocation(2785, 1990); levens --; } else if (checkpoint == 2){ setLocation(500, 500); levens --; } else if (checkpoint == 3){ setLocation(500, 500); levens --; } else if (checkpoint == 4){ setLocation(500, 500); levens --; } else { setLocation(87, 2890); levens --; } } //checkpoint waardes aangeven public void checkpoints() { if(isTouching(Checkpoint.class)) { checkpoint = 1; } if(isTouching(Checkpoint2.class)) { checkpoint = 2; } if(isTouching(Checkpoint3.class)) { checkpoint = 3; } if(isTouching(Checkpoint4.class)) { checkpoint = 4; } } //levens public double hearts(){ levens = levens; return levens; } //de death<SUF> public void Death() { if (isTouching(LavaTile.class)) { respawn(); } if(isTouching(Water.class)) { respawn(); } } // positie methode voor informatie doorgeven public String positie() { String a= "X"+getX()+"Y"+getY(); return a; } //methode om coins weg te halen public int eatCoins() { Actor Coin = getOneIntersectingObject(Coin.class); if(isTouching(Coin.class)) { removeTouching(Coin.class); munten = munten + 1; } return munten; } public void eatKeys() { Actor Key = getOneIntersectingObject(Keys.class); if(isTouching(Keys.class)) { removeTouching(Keys.class); key = true; } } //methode om de knoppen van het toetsenboord te controleren public void checkKeys() { isKeyPressed = false; if (Greenfoot.isKeyDown("d") && Greenfoot.isKeyDown("a")) { stoplopen(); isKeyPressed = true; } else if (Greenfoot.isKeyDown("d")) { walkRight(); setLocation (getX()+speed, getY()); isKeyPressed = true; } else if (Greenfoot.isKeyDown("a")) { walkLeft(); setLocation (getX()-speed, getY()); isKeyPressed = true; } else if (Greenfoot.isKeyDown("space")) { respawn(); } if (!(isKeyPressed)) { stoplopen(); } } //de methode van de deuren public boolean openDeur1() { if (isTouching(Deur1.class) && (key = true)) { openDeur1 = true; Greenfoot.setWorld(new Level2()); } if ( isTouching(Deur2.class)) { Greenfoot.setWorld(new Einde()); } return openDeur1; } // de methode zodat je niet konstant kan springen public boolean onGround() { Actor under = getOneObjectAtOffset (0, getHeight ()/2, Tile.class); Tile tile = (Tile) under; return tile != null && tile.isSolid == true; } // de methode om de badguy weg te halen public void removeBadGuy() { if(isTouching(BadGuy.class)) { removeTouching(BadGuy.class); removedBadGuy=true; return; } } // de methode voor de jump public void handleInput() { if ((Greenfoot.isKeyDown("w") && onGround() == true ) ||(Greenfoot.isKeyDown("w") && isTouching(JumpTile.class))) { setImage("springen.png"); velocityY = -15; } if (velocityY != -5); { setImage("springen.png"); } if (Greenfoot.isKeyDown("a")) { velocityX = -4; } else if (Greenfoot.isKeyDown("d")) { velocityX = 4; } } public int getWidth() { return getImage().getWidth(); } public int getHeight() { return getImage().getHeight(); } // de methode voor de animatie public void walkRight() { lopen = true; Kijkenrechts = true; frame ++; if(frame==1) { setImage(RMidle); } else if(frame==2) { setImage(RMwalk1); } else if(frame==3) { setImage(RMwalk2); } else if(frame==4) { setImage(RMwalk3); } else if(frame==5) { setImage(RMwalk4); } else if(frame==6) { setImage(RMwalk5); } else if(frame==7) { setImage(RMwalk6); } else if(frame==8) { setImage(RMwalk7); } else if(frame==9) { setImage(RMwalk8); } else if(frame==10) { setImage(RMwalk9); } else if(frame==11) { setImage(RMwalk10); } else if (frame==12){ setImage(RMwalk11); frame = 1; return; } } // de andere methode voor de animatie public void walkLeft() { lopen = true; Kijkenrechts = false; frame ++; if(frame==1) { setImage(LMidle); } else if(frame==2) { setImage(LMwalk1); } else if(frame==3) { setImage(LMwalk2); } else if(frame==4) { setImage(LMwalk3); } else if(frame==5) { setImage(LMwalk4); } else if(frame==6) { setImage(LMwalk5); } else if(frame==7) { setImage(LMwalk6); } else if(frame==8) { setImage(LMwalk7); } else if(frame==9) { setImage(LMwalk8); } else if(frame==10) { setImage(LMwalk9); } else if(frame==11) { setImage(LMwalk10); } else if (frame==12) { setImage(LMwalk11); frame = 1; return; } } // een methode om te stoppen met lopen public void stoplopen() { lopen = false; if (Kijkenrechts) setImage (RMidle); else setImage (LMidle); } // een methode om achter je positie te komen public String position() { String a= "x" +getX()+"y"+getY(); return a; } }
191161_33
package com.blankj.utilcode.util; import android.content.ComponentName; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.provider.Settings; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresPermission; import androidx.core.content.FileProvider; import static android.Manifest.permission.CALL_PHONE; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/09/23 * desc : utils about intent * </pre> */ public final class IntentUtils { private IntentUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * Return whether the intent is available. * * @param intent The intent. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isIntentAvailable(final Intent intent) { return Utils.getApp() .getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .size() > 0; } /** * Return the intent of install app. * <p>Target APIs greater than 25 must hold * {@code <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />}</p> * * @param filePath The path of file. * @return the intent of install app */ public static Intent getInstallAppIntent(final String filePath) { return getInstallAppIntent(UtilsBridge.getFileByPath(filePath)); } /** * Return the intent of install app. * <p>Target APIs greater than 25 must hold * {@code <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />}</p> * * @param file The file. * @return the intent of install app */ public static Intent getInstallAppIntent(final File file) { if (!UtilsBridge.isFileExists(file)) return null; Uri uri; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { uri = Uri.fromFile(file); } else { String authority = Utils.getApp().getPackageName() + ".utilcode.fileprovider"; uri = FileProvider.getUriForFile(Utils.getApp(), authority, file); } return getInstallAppIntent(uri); } /** * Return the intent of install app. * <p>Target APIs greater than 25 must hold * {@code <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />}</p> * * @param uri The uri. * @return the intent of install app */ public static Intent getInstallAppIntent(final Uri uri) { if (uri == null) return null; Intent intent = new Intent(Intent.ACTION_VIEW); String type = "application/vnd.android.package-archive"; intent.setDataAndType(uri, type); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } /** * Return the intent of uninstall app. * <p>Target APIs greater than 25 must hold * Must hold {@code <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />}</p> * * @param pkgName The name of the package. * @return the intent of uninstall app */ public static Intent getUninstallAppIntent(final String pkgName) { Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + pkgName)); return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } /** * Return the intent of launch app. * * @param pkgName The name of the package. * @return the intent of launch app */ public static Intent getLaunchAppIntent(final String pkgName) { String launcherActivity = UtilsBridge.getLauncherActivity(pkgName); if (UtilsBridge.isSpace(launcherActivity)) return null; Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setClassName(pkgName, launcherActivity); return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } /** * Return the intent of launch app details settings. * * @param pkgName The name of the package. * @return the intent of launch app details settings */ public static Intent getLaunchAppDetailsSettingsIntent(final String pkgName) { return getLaunchAppDetailsSettingsIntent(pkgName, false); } /** * Return the intent of launch app details settings. * * @param pkgName The name of the package. * @return the intent of launch app details settings */ public static Intent getLaunchAppDetailsSettingsIntent(final String pkgName, final boolean isNewTask) { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + pkgName)); return getIntent(intent, isNewTask); } /** * Return the intent of share text. * * @param content The content. * @return the intent of share text */ public static Intent getShareTextIntent(final String content) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, content); intent = Intent.createChooser(intent, ""); return getIntent(intent, true); } /** * Return the intent of share image. * * @param imagePath The path of image. * @return the intent of share image */ public static Intent getShareImageIntent(final String imagePath) { return getShareTextImageIntent("", imagePath); } /** * Return the intent of share image. * * @param imageFile The file of image. * @return the intent of share image */ public static Intent getShareImageIntent(final File imageFile) { return getShareTextImageIntent("", imageFile); } /** * Return the intent of share image. * * @param imageUri The uri of image. * @return the intent of share image */ public static Intent getShareImageIntent(final Uri imageUri) { return getShareTextImageIntent("", imageUri); } /** * Return the intent of share image. * * @param content The content. * @param imagePath The path of image. * @return the intent of share image */ public static Intent getShareTextImageIntent(@Nullable final String content, final String imagePath) { return getShareTextImageIntent(content, UtilsBridge.getFileByPath(imagePath)); } /** * Return the intent of share image. * * @param content The content. * @param imageFile The file of image. * @return the intent of share image */ public static Intent getShareTextImageIntent(@Nullable final String content, final File imageFile) { return getShareTextImageIntent(content, UtilsBridge.file2Uri(imageFile)); } /** * Return the intent of share image. * * @param content The content. * @param imageUri The uri of image. * @return the intent of share image */ public static Intent getShareTextImageIntent(@Nullable final String content, final Uri imageUri) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_TEXT, content); intent.putExtra(Intent.EXTRA_STREAM, imageUri); intent.setType("image/*"); intent = Intent.createChooser(intent, ""); return getIntent(intent, true); } /** * Return the intent of share images. * * @param imagePaths The paths of images. * @return the intent of share images */ public static Intent getShareImageIntent(final LinkedList<String> imagePaths) { return getShareTextImageIntent("", imagePaths); } /** * Return the intent of share images. * * @param images The files of images. * @return the intent of share images */ public static Intent getShareImageIntent(final List<File> images) { return getShareTextImageIntent("", images); } /** * Return the intent of share images. * * @param uris The uris of image. * @return the intent of share image */ public static Intent getShareImageIntent(final ArrayList<Uri> uris) { return getShareTextImageIntent("", uris); } /** * Return the intent of share images. * * @param content The content. * @param imagePaths The paths of images. * @return the intent of share images */ public static Intent getShareTextImageIntent(@Nullable final String content, final LinkedList<String> imagePaths) { List<File> files = new ArrayList<>(); if (imagePaths != null) { for (String imagePath : imagePaths) { File file = UtilsBridge.getFileByPath(imagePath); if (file != null) { files.add(file); } } } return getShareTextImageIntent(content, files); } /** * Return the intent of share images. * * @param content The content. * @param images The files of images. * @return the intent of share images */ public static Intent getShareTextImageIntent(@Nullable final String content, final List<File> images) { ArrayList<Uri> uris = new ArrayList<>(); if (images != null) { for (File image : images) { Uri uri = UtilsBridge.file2Uri(image); if (uri != null) { uris.add(uri); } } } return getShareTextImageIntent(content, uris); } /** * Return the intent of share images. * * @param content The content. * @param uris The uris of image. * @return the intent of share image */ public static Intent getShareTextImageIntent(@Nullable final String content, final ArrayList<Uri> uris) { Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE); intent.putExtra(Intent.EXTRA_TEXT, content); intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); intent.setType("image/*"); intent = Intent.createChooser(intent, ""); return getIntent(intent, true); } /** * Return the intent of component. * * @param pkgName The name of the package. * @param className The name of class. * @return the intent of component */ public static Intent getComponentIntent(final String pkgName, final String className) { return getComponentIntent(pkgName, className, null, false); } /** * Return the intent of component. * * @param pkgName The name of the package. * @param className The name of class. * @param isNewTask True to add flag of new task, false otherwise. * @return the intent of component */ public static Intent getComponentIntent(final String pkgName, final String className, final boolean isNewTask) { return getComponentIntent(pkgName, className, null, isNewTask); } /** * Return the intent of component. * * @param pkgName The name of the package. * @param className The name of class. * @param bundle The Bundle of extras to add to this intent. * @return the intent of component */ public static Intent getComponentIntent(final String pkgName, final String className, final Bundle bundle) { return getComponentIntent(pkgName, className, bundle, false); } /** * Return the intent of component. * * @param pkgName The name of the package. * @param className The name of class. * @param bundle The Bundle of extras to add to this intent. * @param isNewTask True to add flag of new task, false otherwise. * @return the intent of component */ public static Intent getComponentIntent(final String pkgName, final String className, final Bundle bundle, final boolean isNewTask) { Intent intent = new Intent(); if (bundle != null) intent.putExtras(bundle); ComponentName cn = new ComponentName(pkgName, className); intent.setComponent(cn); return getIntent(intent, isNewTask); } /** * Return the intent of shutdown. * <p>Requires root permission * or hold {@code android:sharedUserId="android.uid.system"}, * {@code <uses-permission android:name="android.permission.SHUTDOWN" />} * in manifest.</p> * * @return the intent of shutdown */ public static Intent getShutdownIntent() { Intent intent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { intent = new Intent("com.android.internal.intent.action.REQUEST_SHUTDOWN"); } else { intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN"); } intent.putExtra("android.intent.extra.KEY_CONFIRM", false); return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } /** * Return the intent of dial. * * @param phoneNumber The phone number. * @return the intent of dial */ public static Intent getDialIntent(@NonNull final String phoneNumber) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(phoneNumber))); return getIntent(intent, true); } /** * Return the intent of call. * <p>Must hold {@code <uses-permission android:name="android.permission.CALL_PHONE" />}</p> * * @param phoneNumber The phone number. * @return the intent of call */ @RequiresPermission(CALL_PHONE) public static Intent getCallIntent(@NonNull final String phoneNumber) { Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + Uri.encode(phoneNumber))); return getIntent(intent, true); } /** * Return the intent of send SMS. * * @param phoneNumber The phone number. * @param content The content of SMS. * @return the intent of send SMS */ public static Intent getSendSmsIntent(@NonNull final String phoneNumber, final String content) { Uri uri = Uri.parse("smsto:" + Uri.encode(phoneNumber)); Intent intent = new Intent(Intent.ACTION_SENDTO, uri); intent.putExtra("sms_body", content); return getIntent(intent, true); } /** * Return the intent of capture. * * @param outUri The uri of output. * @return the intent of capture */ public static Intent getCaptureIntent(final Uri outUri) { return getCaptureIntent(outUri, false); } /** * Return the intent of capture. * * @param outUri The uri of output. * @param isNewTask True to add flag of new task, false otherwise. * @return the intent of capture */ public static Intent getCaptureIntent(final Uri outUri, final boolean isNewTask) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); return getIntent(intent, isNewTask); } private static Intent getIntent(final Intent intent, final boolean isNewTask) { return isNewTask ? intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) : intent; } // /** // * 获取选择照片的 Intent // * // * @return // */ // public static Intent getPickIntentWithGallery() { // Intent intent = new Intent(Intent.ACTION_PICK); // return intent.setType("image*//*"); // } // // /** // * 获取从文件中选择照片的 Intent // * // * @return // */ // public static Intent getPickIntentWithDocuments() { // Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // return intent.setType("image*//*"); // } // // // public static Intent buildImageGetIntent(final Uri saveTo, final int outputX, final int outputY, final boolean returnData) { // return buildImageGetIntent(saveTo, 1, 1, outputX, outputY, returnData); // } // // public static Intent buildImageGetIntent(Uri saveTo, int aspectX, int aspectY, // int outputX, int outputY, boolean returnData) { // Intent intent = new Intent(); // if (Build.VERSION.SDK_INT < 19) { // intent.setAction(Intent.ACTION_GET_CONTENT); // } else { // intent.setAction(Intent.ACTION_OPEN_DOCUMENT); // intent.addCategory(Intent.CATEGORY_OPENABLE); // } // intent.setType("image*//*"); // intent.putExtra("output", saveTo); // intent.putExtra("aspectX", aspectX); // intent.putExtra("aspectY", aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", true); // intent.putExtra("return-data", returnData); // intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); // return intent; // } // // public static Intent buildImageCropIntent(final Uri uriFrom, final Uri uriTo, final int outputX, final int outputY, final boolean returnData) { // return buildImageCropIntent(uriFrom, uriTo, 1, 1, outputX, outputY, returnData); // } // // public static Intent buildImageCropIntent(Uri uriFrom, Uri uriTo, int aspectX, int aspectY, // int outputX, int outputY, boolean returnData) { // Intent intent = new Intent("com.android.camera.action.CROP"); // intent.setDataAndType(uriFrom, "image*//*"); // intent.putExtra("crop", "true"); // intent.putExtra("output", uriTo); // intent.putExtra("aspectX", aspectX); // intent.putExtra("aspectY", aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", true); // intent.putExtra("return-data", returnData); // intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); // return intent; // } // // public static Intent buildImageCaptureIntent(final Uri uri) { // Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); // return intent; // } }
Blankj/AndroidUtilCode
lib/utilcode/src/main/java/com/blankj/utilcode/util/IntentUtils.java
4,923
// Intent intent = new Intent(Intent.ACTION_PICK);
line_comment
nl
package com.blankj.utilcode.util; import android.content.ComponentName; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.provider.Settings; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresPermission; import androidx.core.content.FileProvider; import static android.Manifest.permission.CALL_PHONE; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/09/23 * desc : utils about intent * </pre> */ public final class IntentUtils { private IntentUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * Return whether the intent is available. * * @param intent The intent. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isIntentAvailable(final Intent intent) { return Utils.getApp() .getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .size() > 0; } /** * Return the intent of install app. * <p>Target APIs greater than 25 must hold * {@code <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />}</p> * * @param filePath The path of file. * @return the intent of install app */ public static Intent getInstallAppIntent(final String filePath) { return getInstallAppIntent(UtilsBridge.getFileByPath(filePath)); } /** * Return the intent of install app. * <p>Target APIs greater than 25 must hold * {@code <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />}</p> * * @param file The file. * @return the intent of install app */ public static Intent getInstallAppIntent(final File file) { if (!UtilsBridge.isFileExists(file)) return null; Uri uri; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { uri = Uri.fromFile(file); } else { String authority = Utils.getApp().getPackageName() + ".utilcode.fileprovider"; uri = FileProvider.getUriForFile(Utils.getApp(), authority, file); } return getInstallAppIntent(uri); } /** * Return the intent of install app. * <p>Target APIs greater than 25 must hold * {@code <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />}</p> * * @param uri The uri. * @return the intent of install app */ public static Intent getInstallAppIntent(final Uri uri) { if (uri == null) return null; Intent intent = new Intent(Intent.ACTION_VIEW); String type = "application/vnd.android.package-archive"; intent.setDataAndType(uri, type); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } /** * Return the intent of uninstall app. * <p>Target APIs greater than 25 must hold * Must hold {@code <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />}</p> * * @param pkgName The name of the package. * @return the intent of uninstall app */ public static Intent getUninstallAppIntent(final String pkgName) { Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + pkgName)); return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } /** * Return the intent of launch app. * * @param pkgName The name of the package. * @return the intent of launch app */ public static Intent getLaunchAppIntent(final String pkgName) { String launcherActivity = UtilsBridge.getLauncherActivity(pkgName); if (UtilsBridge.isSpace(launcherActivity)) return null; Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setClassName(pkgName, launcherActivity); return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } /** * Return the intent of launch app details settings. * * @param pkgName The name of the package. * @return the intent of launch app details settings */ public static Intent getLaunchAppDetailsSettingsIntent(final String pkgName) { return getLaunchAppDetailsSettingsIntent(pkgName, false); } /** * Return the intent of launch app details settings. * * @param pkgName The name of the package. * @return the intent of launch app details settings */ public static Intent getLaunchAppDetailsSettingsIntent(final String pkgName, final boolean isNewTask) { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + pkgName)); return getIntent(intent, isNewTask); } /** * Return the intent of share text. * * @param content The content. * @return the intent of share text */ public static Intent getShareTextIntent(final String content) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, content); intent = Intent.createChooser(intent, ""); return getIntent(intent, true); } /** * Return the intent of share image. * * @param imagePath The path of image. * @return the intent of share image */ public static Intent getShareImageIntent(final String imagePath) { return getShareTextImageIntent("", imagePath); } /** * Return the intent of share image. * * @param imageFile The file of image. * @return the intent of share image */ public static Intent getShareImageIntent(final File imageFile) { return getShareTextImageIntent("", imageFile); } /** * Return the intent of share image. * * @param imageUri The uri of image. * @return the intent of share image */ public static Intent getShareImageIntent(final Uri imageUri) { return getShareTextImageIntent("", imageUri); } /** * Return the intent of share image. * * @param content The content. * @param imagePath The path of image. * @return the intent of share image */ public static Intent getShareTextImageIntent(@Nullable final String content, final String imagePath) { return getShareTextImageIntent(content, UtilsBridge.getFileByPath(imagePath)); } /** * Return the intent of share image. * * @param content The content. * @param imageFile The file of image. * @return the intent of share image */ public static Intent getShareTextImageIntent(@Nullable final String content, final File imageFile) { return getShareTextImageIntent(content, UtilsBridge.file2Uri(imageFile)); } /** * Return the intent of share image. * * @param content The content. * @param imageUri The uri of image. * @return the intent of share image */ public static Intent getShareTextImageIntent(@Nullable final String content, final Uri imageUri) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_TEXT, content); intent.putExtra(Intent.EXTRA_STREAM, imageUri); intent.setType("image/*"); intent = Intent.createChooser(intent, ""); return getIntent(intent, true); } /** * Return the intent of share images. * * @param imagePaths The paths of images. * @return the intent of share images */ public static Intent getShareImageIntent(final LinkedList<String> imagePaths) { return getShareTextImageIntent("", imagePaths); } /** * Return the intent of share images. * * @param images The files of images. * @return the intent of share images */ public static Intent getShareImageIntent(final List<File> images) { return getShareTextImageIntent("", images); } /** * Return the intent of share images. * * @param uris The uris of image. * @return the intent of share image */ public static Intent getShareImageIntent(final ArrayList<Uri> uris) { return getShareTextImageIntent("", uris); } /** * Return the intent of share images. * * @param content The content. * @param imagePaths The paths of images. * @return the intent of share images */ public static Intent getShareTextImageIntent(@Nullable final String content, final LinkedList<String> imagePaths) { List<File> files = new ArrayList<>(); if (imagePaths != null) { for (String imagePath : imagePaths) { File file = UtilsBridge.getFileByPath(imagePath); if (file != null) { files.add(file); } } } return getShareTextImageIntent(content, files); } /** * Return the intent of share images. * * @param content The content. * @param images The files of images. * @return the intent of share images */ public static Intent getShareTextImageIntent(@Nullable final String content, final List<File> images) { ArrayList<Uri> uris = new ArrayList<>(); if (images != null) { for (File image : images) { Uri uri = UtilsBridge.file2Uri(image); if (uri != null) { uris.add(uri); } } } return getShareTextImageIntent(content, uris); } /** * Return the intent of share images. * * @param content The content. * @param uris The uris of image. * @return the intent of share image */ public static Intent getShareTextImageIntent(@Nullable final String content, final ArrayList<Uri> uris) { Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE); intent.putExtra(Intent.EXTRA_TEXT, content); intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); intent.setType("image/*"); intent = Intent.createChooser(intent, ""); return getIntent(intent, true); } /** * Return the intent of component. * * @param pkgName The name of the package. * @param className The name of class. * @return the intent of component */ public static Intent getComponentIntent(final String pkgName, final String className) { return getComponentIntent(pkgName, className, null, false); } /** * Return the intent of component. * * @param pkgName The name of the package. * @param className The name of class. * @param isNewTask True to add flag of new task, false otherwise. * @return the intent of component */ public static Intent getComponentIntent(final String pkgName, final String className, final boolean isNewTask) { return getComponentIntent(pkgName, className, null, isNewTask); } /** * Return the intent of component. * * @param pkgName The name of the package. * @param className The name of class. * @param bundle The Bundle of extras to add to this intent. * @return the intent of component */ public static Intent getComponentIntent(final String pkgName, final String className, final Bundle bundle) { return getComponentIntent(pkgName, className, bundle, false); } /** * Return the intent of component. * * @param pkgName The name of the package. * @param className The name of class. * @param bundle The Bundle of extras to add to this intent. * @param isNewTask True to add flag of new task, false otherwise. * @return the intent of component */ public static Intent getComponentIntent(final String pkgName, final String className, final Bundle bundle, final boolean isNewTask) { Intent intent = new Intent(); if (bundle != null) intent.putExtras(bundle); ComponentName cn = new ComponentName(pkgName, className); intent.setComponent(cn); return getIntent(intent, isNewTask); } /** * Return the intent of shutdown. * <p>Requires root permission * or hold {@code android:sharedUserId="android.uid.system"}, * {@code <uses-permission android:name="android.permission.SHUTDOWN" />} * in manifest.</p> * * @return the intent of shutdown */ public static Intent getShutdownIntent() { Intent intent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { intent = new Intent("com.android.internal.intent.action.REQUEST_SHUTDOWN"); } else { intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN"); } intent.putExtra("android.intent.extra.KEY_CONFIRM", false); return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } /** * Return the intent of dial. * * @param phoneNumber The phone number. * @return the intent of dial */ public static Intent getDialIntent(@NonNull final String phoneNumber) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(phoneNumber))); return getIntent(intent, true); } /** * Return the intent of call. * <p>Must hold {@code <uses-permission android:name="android.permission.CALL_PHONE" />}</p> * * @param phoneNumber The phone number. * @return the intent of call */ @RequiresPermission(CALL_PHONE) public static Intent getCallIntent(@NonNull final String phoneNumber) { Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + Uri.encode(phoneNumber))); return getIntent(intent, true); } /** * Return the intent of send SMS. * * @param phoneNumber The phone number. * @param content The content of SMS. * @return the intent of send SMS */ public static Intent getSendSmsIntent(@NonNull final String phoneNumber, final String content) { Uri uri = Uri.parse("smsto:" + Uri.encode(phoneNumber)); Intent intent = new Intent(Intent.ACTION_SENDTO, uri); intent.putExtra("sms_body", content); return getIntent(intent, true); } /** * Return the intent of capture. * * @param outUri The uri of output. * @return the intent of capture */ public static Intent getCaptureIntent(final Uri outUri) { return getCaptureIntent(outUri, false); } /** * Return the intent of capture. * * @param outUri The uri of output. * @param isNewTask True to add flag of new task, false otherwise. * @return the intent of capture */ public static Intent getCaptureIntent(final Uri outUri, final boolean isNewTask) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); return getIntent(intent, isNewTask); } private static Intent getIntent(final Intent intent, final boolean isNewTask) { return isNewTask ? intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) : intent; } // /** // * 获取选择照片的 Intent // * // * @return // */ // public static Intent getPickIntentWithGallery() { // Intent intent<SUF> // return intent.setType("image*//*"); // } // // /** // * 获取从文件中选择照片的 Intent // * // * @return // */ // public static Intent getPickIntentWithDocuments() { // Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // return intent.setType("image*//*"); // } // // // public static Intent buildImageGetIntent(final Uri saveTo, final int outputX, final int outputY, final boolean returnData) { // return buildImageGetIntent(saveTo, 1, 1, outputX, outputY, returnData); // } // // public static Intent buildImageGetIntent(Uri saveTo, int aspectX, int aspectY, // int outputX, int outputY, boolean returnData) { // Intent intent = new Intent(); // if (Build.VERSION.SDK_INT < 19) { // intent.setAction(Intent.ACTION_GET_CONTENT); // } else { // intent.setAction(Intent.ACTION_OPEN_DOCUMENT); // intent.addCategory(Intent.CATEGORY_OPENABLE); // } // intent.setType("image*//*"); // intent.putExtra("output", saveTo); // intent.putExtra("aspectX", aspectX); // intent.putExtra("aspectY", aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", true); // intent.putExtra("return-data", returnData); // intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); // return intent; // } // // public static Intent buildImageCropIntent(final Uri uriFrom, final Uri uriTo, final int outputX, final int outputY, final boolean returnData) { // return buildImageCropIntent(uriFrom, uriTo, 1, 1, outputX, outputY, returnData); // } // // public static Intent buildImageCropIntent(Uri uriFrom, Uri uriTo, int aspectX, int aspectY, // int outputX, int outputY, boolean returnData) { // Intent intent = new Intent("com.android.camera.action.CROP"); // intent.setDataAndType(uriFrom, "image*//*"); // intent.putExtra("crop", "true"); // intent.putExtra("output", uriTo); // intent.putExtra("aspectX", aspectX); // intent.putExtra("aspectY", aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", true); // intent.putExtra("return-data", returnData); // intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); // return intent; // } // // public static Intent buildImageCaptureIntent(final Uri uri) { // Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); // return intent; // } }
10256_7
package semisplay; import java.util.*; /** * Een semisplay boom * * @param <E> Het type van de data */ public class SemiSplayTree<E extends Comparable<E>> implements SearchTree<E> { private final int k; private TreeNode<E> root; private int size; /* * Deze ArrayList zal hergebruikt worden doorheen method calls. * Het is iets efficiënter om de lijst te clearen dan een nieuwe aan te maken. * De keuze voor een ArrayList is om twee redenen: * 1) Bijna net zo snel als een gewone array om te accessen. * 2) Je kan geen array van generics maken zonder dat Java klaagt. * * Ik weet op voorhand hoe lang de ArrayList zal zijn, dus ik kan de capaciteit pre-allocaten. * Hierdoor gebeurt de add bewerking in constante tijd, want er zal nooit uitgebreid moeten worden. * Na enkele tests merk ik dat het performance verschil tussen arrays en pre-allocated ArrayList bijna niet merkbaar is. * Vandaar deze keuze. */ private final ArrayList<TreeNode<E>> outerTrees; private final ArrayList<TreeNode<E>> nodesOnPath; /** * Maakt een lege semisplay boom met splaypad lengte k aan * * @param k Lengte van het splaypad */ public SemiSplayTree(int k) { // Opgave: "minstens 3" if (k < 3) throw new IllegalArgumentException("k must be at least 3, k = " + k); this.k = k; outerTrees = new ArrayList<>(k + 1); nodesOnPath = new ArrayList<>(k); } @Override public boolean add(E e) { if (root == null) { root = new TreeNode<>(e); } else { TreeNode<E> current = root; TreeNode<E> parent = null; int comp = 0; while (current != null) { parent = current; comp = e.compareTo(current.getData()); if (comp == 0) { semiSplay(current); return false; } else if (comp < 0) current = current.getLeft(); else current = current.getRight(); } current = new TreeNode<>(e); if (comp < 0) parent.setLeft(current); else parent.setRight(current); semiSplay(current); } ++size; return true; } /** * Voer semisplay uit met semisplaypad eindpunt "current". * Vanaf daar wordt er k omhoog geteld, en dan heb je een pad van lengte k dat gesplayed wordt. * Dit wordt herhaald tot je niet meer verder omhoog kan. * * @param current Het eindpunt voor het semisplaypad. */ private void semiSplay(TreeNode<E> current) { TreeNode<E> pathEnd = current; while (current != null) { for (int count = 1; count < k && current != null; ++count) current = current.getParent(); if (current != null) { E end = pathEnd.getData(); TreeNode<E> grandparent = current.getParent(); TreeNode<E> result = semiSplaySingleStep(current, end); // Link herstellen in de boom. Indien null, dan was het de wortel. if (grandparent != null) { replaceParentLink(grandparent, current, result); // Blijven doorgaan met splayen pathEnd = current = result; } else { root = result; root.setParent(null); current = null; } } } } /** * Een enkele semisplay bewerking. * * @param node Startpunt van het splaypad * @param e Eindpunt data, nodig voor de richting te weten * @return Wortel van de geconstrueerde vervangboom */ private TreeNode<E> semiSplaySingleStep(TreeNode<E> node, E e) { // Al deze stappen zijn theta(k) fillPathAndOuterTrees(node, e); TreeNode<E> result = constructBinTree(0, k - 1); // Buitenbomen herkoppelen aan de nodes for (int i = 0, j = 0; i < k; ++i) { TreeNode<E> n = nodesOnPath.get(i); if (!n.hasLeft()) n.setLeft(outerTrees.get(j++)); if (!n.hasRight()) n.setRight(outerTrees.get(j++)); } outerTrees.clear(); nodesOnPath.clear(); return result; } /** * Construeert een zo goed mogelijk gebalanceerde binaire boom * * @param start Startindex van de deellijst * @param end Eindindex van de deellijst * @return Wortel van de (deel)boom */ private TreeNode<E> constructBinTree(int start, int end) { if (start > end) return null; int mid = (start + end) / 2; TreeNode<E> node = nodesOnPath.get(mid); node.setLeft(constructBinTree(start, mid - 1)); node.setRight(constructBinTree(mid + 1, end)); return node; } /** * Vult het pad gesorteerd op, en voegt de buitenbomen toe aan een lijst * * @param root Wortel van de deelboom om te vertrekken * @param data Data om te vinden */ private void fillPathAndOuterTrees(TreeNode<E> root, E data) { int comp = data.compareTo(root.getData()); if (comp < 0) fillPathAndOuterTrees(root.getLeft(), data); else outerTrees.add(root.getLeft()); nodesOnPath.add(root); if (comp > 0) fillPathAndOuterTrees(root.getRight(), data); else outerTrees.add(root.getRight()); } @Override public boolean contains(E e) { TreeNode<E> parent = null; TreeNode<E> current = root; while (current != null) { parent = current; int comp = e.compareTo(current.getData()); if (comp == 0) { semiSplay(current); return true; } else if (comp < 0) current = current.getLeft(); else // comp > 0 current = current.getRight(); } semiSplay(parent); return false; } @Override public boolean remove(E e) { TreeNode<E> parent = root; TreeNode<E> current = root; int comp; while (current != null && (comp = e.compareTo(current.getData())) != 0) { parent = current; if (comp < 0) current = current.getLeft(); else // comp > 0 current = current.getRight(); } // Zat er niet in if (current == null) { semiSplay(parent); return false; } semiSplay(removeNode(current)); --size; return true; } /** * Remove node * * @param current De node die verwijderd moet worden * @return De node die gesemisplayed moet worden */ private TreeNode<E> removeNode(TreeNode<E> current) { // Geval: blad if (current.isLeaf()) { // Geval: wortel if (current == root) { root = null; return null; } // Geval: heeft een ouder, dus we moeten kijken welke link we moeten verbreken else { TreeNode<E> parent = current.getParent(); replaceParentLink(parent, current, null); return parent; } } // Geval: enkel rechterkind => parent linken met rechterkind else if (!current.hasLeft()) { TreeNode<E> replacement = current.getRight(); current.setData(replacement.getData()); current.setLeft(replacement.getLeft()); current.setRight(replacement.getRight()); return current; } // Geval: enkel linkerkind => parent linken met linkerkind else if (!current.hasRight()) { TreeNode<E> replacement = current.getLeft(); current.setData(replacement.getData()); current.setLeft(replacement.getLeft()); current.setRight(replacement.getRight()); return current; } // Geval: twee kinderen else { TreeNode<E> replacement = minimum(current.getRight()); TreeNode<E> parent = replacement.getParent(); current.setData(replacement.getData()); removeNode(replacement); return parent; } } /** * Vervang een link in de parent naar het kind door een andere node * * @param parent De parent node * @param child De kind node * @param replacement De vervangende node */ private void replaceParentLink(TreeNode<E> parent, TreeNode<E> child, TreeNode<E> replacement) { if (parent.getLeft() == child) parent.setLeft(replacement); else parent.setRight(replacement); } /** * Zoekt de kleinste node in deze deelboom * * @param node De wortel van de deelboom * @return De kleinste node */ private TreeNode<E> minimum(TreeNode<E> node) { while (node.hasLeft()) node = node.getLeft(); return node; } @Override public int size() { return size; } /** * Diepte van de deelboom berekenen * * @param node De wortel van de deelboom * @return Diepte */ private int depth(TreeNode<E> node) { if (node == null) return -1; // Want gedefinieerd als aantal bogen, niet aantal toppen int l = depth(node.getLeft()); int r = depth(node.getRight()); return Math.max(l, r) + 1; } @Override public int depth() { return depth(root); } @Override public Iterator<E> iterator() { return new TreeIterator<>(root); } /** * Voor tests & debug: breedte eerst output in een lijst */ public List<E> bfs() { List<E> l = new ArrayList<>(size()); if (root == null) return l; LinkedList<TreeNode<E>> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode<E> n = queue.removeFirst(); l.add(n.getData()); if (n.hasLeft()) queue.add(n.getLeft()); if (n.hasRight()) queue.add(n.getRight()); } return l; } }
nielsdos/Semisplay-tree
src/semisplay/SemiSplayTree.java
2,836
/** * Een enkele semisplay bewerking. * * @param node Startpunt van het splaypad * @param e Eindpunt data, nodig voor de richting te weten * @return Wortel van de geconstrueerde vervangboom */
block_comment
nl
package semisplay; import java.util.*; /** * Een semisplay boom * * @param <E> Het type van de data */ public class SemiSplayTree<E extends Comparable<E>> implements SearchTree<E> { private final int k; private TreeNode<E> root; private int size; /* * Deze ArrayList zal hergebruikt worden doorheen method calls. * Het is iets efficiënter om de lijst te clearen dan een nieuwe aan te maken. * De keuze voor een ArrayList is om twee redenen: * 1) Bijna net zo snel als een gewone array om te accessen. * 2) Je kan geen array van generics maken zonder dat Java klaagt. * * Ik weet op voorhand hoe lang de ArrayList zal zijn, dus ik kan de capaciteit pre-allocaten. * Hierdoor gebeurt de add bewerking in constante tijd, want er zal nooit uitgebreid moeten worden. * Na enkele tests merk ik dat het performance verschil tussen arrays en pre-allocated ArrayList bijna niet merkbaar is. * Vandaar deze keuze. */ private final ArrayList<TreeNode<E>> outerTrees; private final ArrayList<TreeNode<E>> nodesOnPath; /** * Maakt een lege semisplay boom met splaypad lengte k aan * * @param k Lengte van het splaypad */ public SemiSplayTree(int k) { // Opgave: "minstens 3" if (k < 3) throw new IllegalArgumentException("k must be at least 3, k = " + k); this.k = k; outerTrees = new ArrayList<>(k + 1); nodesOnPath = new ArrayList<>(k); } @Override public boolean add(E e) { if (root == null) { root = new TreeNode<>(e); } else { TreeNode<E> current = root; TreeNode<E> parent = null; int comp = 0; while (current != null) { parent = current; comp = e.compareTo(current.getData()); if (comp == 0) { semiSplay(current); return false; } else if (comp < 0) current = current.getLeft(); else current = current.getRight(); } current = new TreeNode<>(e); if (comp < 0) parent.setLeft(current); else parent.setRight(current); semiSplay(current); } ++size; return true; } /** * Voer semisplay uit met semisplaypad eindpunt "current". * Vanaf daar wordt er k omhoog geteld, en dan heb je een pad van lengte k dat gesplayed wordt. * Dit wordt herhaald tot je niet meer verder omhoog kan. * * @param current Het eindpunt voor het semisplaypad. */ private void semiSplay(TreeNode<E> current) { TreeNode<E> pathEnd = current; while (current != null) { for (int count = 1; count < k && current != null; ++count) current = current.getParent(); if (current != null) { E end = pathEnd.getData(); TreeNode<E> grandparent = current.getParent(); TreeNode<E> result = semiSplaySingleStep(current, end); // Link herstellen in de boom. Indien null, dan was het de wortel. if (grandparent != null) { replaceParentLink(grandparent, current, result); // Blijven doorgaan met splayen pathEnd = current = result; } else { root = result; root.setParent(null); current = null; } } } } /** * Een enkele semisplay<SUF>*/ private TreeNode<E> semiSplaySingleStep(TreeNode<E> node, E e) { // Al deze stappen zijn theta(k) fillPathAndOuterTrees(node, e); TreeNode<E> result = constructBinTree(0, k - 1); // Buitenbomen herkoppelen aan de nodes for (int i = 0, j = 0; i < k; ++i) { TreeNode<E> n = nodesOnPath.get(i); if (!n.hasLeft()) n.setLeft(outerTrees.get(j++)); if (!n.hasRight()) n.setRight(outerTrees.get(j++)); } outerTrees.clear(); nodesOnPath.clear(); return result; } /** * Construeert een zo goed mogelijk gebalanceerde binaire boom * * @param start Startindex van de deellijst * @param end Eindindex van de deellijst * @return Wortel van de (deel)boom */ private TreeNode<E> constructBinTree(int start, int end) { if (start > end) return null; int mid = (start + end) / 2; TreeNode<E> node = nodesOnPath.get(mid); node.setLeft(constructBinTree(start, mid - 1)); node.setRight(constructBinTree(mid + 1, end)); return node; } /** * Vult het pad gesorteerd op, en voegt de buitenbomen toe aan een lijst * * @param root Wortel van de deelboom om te vertrekken * @param data Data om te vinden */ private void fillPathAndOuterTrees(TreeNode<E> root, E data) { int comp = data.compareTo(root.getData()); if (comp < 0) fillPathAndOuterTrees(root.getLeft(), data); else outerTrees.add(root.getLeft()); nodesOnPath.add(root); if (comp > 0) fillPathAndOuterTrees(root.getRight(), data); else outerTrees.add(root.getRight()); } @Override public boolean contains(E e) { TreeNode<E> parent = null; TreeNode<E> current = root; while (current != null) { parent = current; int comp = e.compareTo(current.getData()); if (comp == 0) { semiSplay(current); return true; } else if (comp < 0) current = current.getLeft(); else // comp > 0 current = current.getRight(); } semiSplay(parent); return false; } @Override public boolean remove(E e) { TreeNode<E> parent = root; TreeNode<E> current = root; int comp; while (current != null && (comp = e.compareTo(current.getData())) != 0) { parent = current; if (comp < 0) current = current.getLeft(); else // comp > 0 current = current.getRight(); } // Zat er niet in if (current == null) { semiSplay(parent); return false; } semiSplay(removeNode(current)); --size; return true; } /** * Remove node * * @param current De node die verwijderd moet worden * @return De node die gesemisplayed moet worden */ private TreeNode<E> removeNode(TreeNode<E> current) { // Geval: blad if (current.isLeaf()) { // Geval: wortel if (current == root) { root = null; return null; } // Geval: heeft een ouder, dus we moeten kijken welke link we moeten verbreken else { TreeNode<E> parent = current.getParent(); replaceParentLink(parent, current, null); return parent; } } // Geval: enkel rechterkind => parent linken met rechterkind else if (!current.hasLeft()) { TreeNode<E> replacement = current.getRight(); current.setData(replacement.getData()); current.setLeft(replacement.getLeft()); current.setRight(replacement.getRight()); return current; } // Geval: enkel linkerkind => parent linken met linkerkind else if (!current.hasRight()) { TreeNode<E> replacement = current.getLeft(); current.setData(replacement.getData()); current.setLeft(replacement.getLeft()); current.setRight(replacement.getRight()); return current; } // Geval: twee kinderen else { TreeNode<E> replacement = minimum(current.getRight()); TreeNode<E> parent = replacement.getParent(); current.setData(replacement.getData()); removeNode(replacement); return parent; } } /** * Vervang een link in de parent naar het kind door een andere node * * @param parent De parent node * @param child De kind node * @param replacement De vervangende node */ private void replaceParentLink(TreeNode<E> parent, TreeNode<E> child, TreeNode<E> replacement) { if (parent.getLeft() == child) parent.setLeft(replacement); else parent.setRight(replacement); } /** * Zoekt de kleinste node in deze deelboom * * @param node De wortel van de deelboom * @return De kleinste node */ private TreeNode<E> minimum(TreeNode<E> node) { while (node.hasLeft()) node = node.getLeft(); return node; } @Override public int size() { return size; } /** * Diepte van de deelboom berekenen * * @param node De wortel van de deelboom * @return Diepte */ private int depth(TreeNode<E> node) { if (node == null) return -1; // Want gedefinieerd als aantal bogen, niet aantal toppen int l = depth(node.getLeft()); int r = depth(node.getRight()); return Math.max(l, r) + 1; } @Override public int depth() { return depth(root); } @Override public Iterator<E> iterator() { return new TreeIterator<>(root); } /** * Voor tests & debug: breedte eerst output in een lijst */ public List<E> bfs() { List<E> l = new ArrayList<>(size()); if (root == null) return l; LinkedList<TreeNode<E>> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode<E> n = queue.removeFirst(); l.add(n.getData()); if (n.hasLeft()) queue.add(n.getLeft()); if (n.hasRight()) queue.add(n.getRight()); } return l; } }
58027_0
package Items; import Slide.SlideItem; import Style.Style; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.io.File; import java.io.IOException; /** <p>De klasse voor een Bitmap item</p> * <p>Bitmap items hebben de verantwoordelijkheid om zichzelf te tekenen.</p> * @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */ public class BitmapItem extends SlideItem { private BufferedImage bufferedImage; private final String imageName; protected static final String FILE = "Bestand "; protected static final String NOTFOUND = " Niet gevonden"; public BitmapItem(int level, String name) { super(level); this.imageName = name; try { this.bufferedImage = ImageIO.read(new File(this.imageName)); } catch (IOException e) { System.err.println(FILE + this.imageName + NOTFOUND) ; } } public String getName() { return this.imageName; } /** * Get the bounding box of an image * @param g The graphics context * @param observer The image observer that tracks changes * @param scale The scaling factor that's applied to the object * @param myStyle The style that is applied to the object * @return A rectangle which represents the bounding box */ public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) { return new Rectangle((int) (myStyle.getIndent() * scale), 0, (int) (this.bufferedImage.getWidth(observer) * scale), ((int) (myStyle.getLeading() * scale)) + (int) (this.bufferedImage.getHeight(observer) * scale)); } /** * Draw the image * @param x The x-coordinate * @param y The y-coordinate * @param scale The scaling factor that's applied to the object * @param g The graphics context * @param myStyle The style that is applied to the object * @param observer The image observer that tracks changes */ public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) { int width = x + (int) (myStyle.getIndent() * scale); int height = y + (int) (myStyle.getLeading() * scale); g.drawImage(this.bufferedImage, width, height,(int) (this.bufferedImage.getWidth(observer)*scale), (int) (this.bufferedImage.getHeight(observer)*scale), observer); } public String toString() { return "BitmapItem[" + getLevel() + "," + this.imageName + "]"; } }
Clibzz/OGO
src/Items/BitmapItem.java
824
/** <p>De klasse voor een Bitmap item</p> * <p>Bitmap items hebben de verantwoordelijkheid om zichzelf te tekenen.</p> * @author Ian F. Darwin, [email protected], Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */
block_comment
nl
package Items; import Slide.SlideItem; import Style.Style; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.io.File; import java.io.IOException; /** <p>De klasse voor<SUF>*/ public class BitmapItem extends SlideItem { private BufferedImage bufferedImage; private final String imageName; protected static final String FILE = "Bestand "; protected static final String NOTFOUND = " Niet gevonden"; public BitmapItem(int level, String name) { super(level); this.imageName = name; try { this.bufferedImage = ImageIO.read(new File(this.imageName)); } catch (IOException e) { System.err.println(FILE + this.imageName + NOTFOUND) ; } } public String getName() { return this.imageName; } /** * Get the bounding box of an image * @param g The graphics context * @param observer The image observer that tracks changes * @param scale The scaling factor that's applied to the object * @param myStyle The style that is applied to the object * @return A rectangle which represents the bounding box */ public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) { return new Rectangle((int) (myStyle.getIndent() * scale), 0, (int) (this.bufferedImage.getWidth(observer) * scale), ((int) (myStyle.getLeading() * scale)) + (int) (this.bufferedImage.getHeight(observer) * scale)); } /** * Draw the image * @param x The x-coordinate * @param y The y-coordinate * @param scale The scaling factor that's applied to the object * @param g The graphics context * @param myStyle The style that is applied to the object * @param observer The image observer that tracks changes */ public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) { int width = x + (int) (myStyle.getIndent() * scale); int height = y + (int) (myStyle.getLeading() * scale); g.drawImage(this.bufferedImage, width, height,(int) (this.bufferedImage.getWidth(observer)*scale), (int) (this.bufferedImage.getHeight(observer)*scale), observer); } public String toString() { return "BitmapItem[" + getLevel() + "," + this.imageName + "]"; } }
141795_6
/** * Author: Martin van Velsen <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package edu.cmu.cs.in.hoop.editor; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.geom.RoundRectangle2D; import java.awt.image.ImageObserver; import javax.swing.BorderFactory; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import com.mxgraph.model.mxCell; import com.mxgraph.model.mxGeometry; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.view.mxCellState; import edu.cmu.cs.in.base.HoopLink; import edu.cmu.cs.in.base.HoopProperties; import edu.cmu.cs.in.base.HoopRoot; import edu.cmu.cs.in.hoop.hoops.base.HoopBase; /** * */ public class HoopNodePanelRenderer extends HoopRoot implements ImageObserver { //protected CellRendererPane rendererPane = new CellRendererPane(); protected Border blackborder=null; protected Border redborder=null; protected Border raisedRed=null; private Border borderPainter=null; private mxGraphComponent graphComponent=null; private Paint gradient=null; /** * */ public HoopNodePanelRenderer (mxGraphComponent aComponent) { setClassName ("HoopNodePanelRenderer"); debug ("HoopNodePanelRenderer ()"); //GradientPaint redtowhite = new GradientPaint(5, 5, Color.red, 200, 5, Color.blue); gradient = new GradientPaint(0, 0, new Color(0xf3e2c7), 0, 50, new Color(0xc19e67), false); graphComponent=aComponent; borderPainter=BorderFactory.createBevelBorder(BevelBorder.RAISED); } /** * Ports are not used as terminals for edges, they are * only used to compute the graphical connection point */ public boolean isPort(Object cell) { mxGeometry geo =graphComponent.getGraph().getCellGeometry(cell); return (geo != null) ? geo.isRelative() : false; } /** * * @param state * @param label */ public void drawHoop (Graphics2D g, mxCellState state) { mxCell cell=(mxCell) state.getCell(); if (isPort (cell)) { g.setColor(new Color (217, 217, 217)); g.fillOval((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight()); g.setColor(new Color (100, 100, 100)); g.drawOval((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight()); } else { //HoopBase hoopTest=(HoopBase) cell.getValue(); // debug ("Check: " + hoopTest.getClass().getName()); /* g.setColor(HoopProperties.getHoopColor (null)); g.fillRect((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight()); */ gradient = new GradientPaint(0, 0, new Color(0xf3e2c7), 0, (int) state.getHeight(), new Color(0xc19e67), false); g.setPaint(gradient); g.fill(new RoundRectangle2D.Double((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight(), 10, 10)); if (borderPainter!=null) { borderPainter.paintBorder(graphComponent, g, (int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight()); } else { g.draw3DRect((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight(), true); } // Title area g.drawImage(HoopLink.getImageByName("led-yellow.png").getImage(), (int) state.getX()+4, (int) state.getY()+4, this); g.setColor(Color.black); /* g.drawString(hoopTest.getClassName(), (int) state.getX()+HoopLink.getImageByName("led-yellow.png").getIconWidth()+6, (int) state.getY()+16); */ g.drawString("HoopBase", (int) state.getX()+HoopLink.getImageByName("led-yellow.png").getIconWidth()+6, (int) state.getY()+16); g.drawImage(HoopLink.getImageByName("zoom.png").getImage(), (int) state.getX()+(int) state.getWidth()-(16*3)-4, (int) state.getY()+4, this); g.drawImage(HoopLink.getImageByName("gtk-execute.png").getImage(), (int) state.getX()+(int) state.getWidth()-(16*2)-4, (int) state.getY()+4, this); g.drawImage(HoopLink.getImageByName("help_icon.png").getImage(), (int) state.getX()+(int) state.getWidth()-(16*1)-4, (int) state.getY()+4, this); // Line markers g.setColor(Color.black); g.drawLine((int) state.getX()+4, (int) state.getY()+24, (int) state.getX()+(int) state.getWidth()-4, (int) state.getY()+24); g.setColor(Color.black); g.drawLine((int) state.getX()+4, (int) state.getY()+(int) state.getHeight()-24, (int) state.getX()+(int) state.getWidth()-4, (int) state.getY()+(int) state.getHeight()-24); // Footer area g.setColor(Color.black); g.drawString("Ex: 0, E: 1", (int) state.getX()+3, (int) state.getY()+(int) state.getHeight()-4); // Gripper g.drawImage(HoopLink.getImageByName("resize.png").getImage(), (int) state.getX()+(int) state.getWidth()-HoopLink.getImageByName("resize.png").getIconWidth()-2, (int) state.getY()+(int) state.getHeight()-HoopLink.getImageByName("resize.png").getIconHeight()-2, this); } } /** * No idea why we need this but the g.drawImage needs a pointer to some such interface */ @Override public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { return false; } }
Mindtoeye/Hoop
src/edu/cmu/cs/in/hoop/editor/HoopNodePanelRenderer.java
2,151
// debug ("Check: " + hoopTest.getClass().getName());
line_comment
nl
/** * Author: Martin van Velsen <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package edu.cmu.cs.in.hoop.editor; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.geom.RoundRectangle2D; import java.awt.image.ImageObserver; import javax.swing.BorderFactory; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import com.mxgraph.model.mxCell; import com.mxgraph.model.mxGeometry; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.view.mxCellState; import edu.cmu.cs.in.base.HoopLink; import edu.cmu.cs.in.base.HoopProperties; import edu.cmu.cs.in.base.HoopRoot; import edu.cmu.cs.in.hoop.hoops.base.HoopBase; /** * */ public class HoopNodePanelRenderer extends HoopRoot implements ImageObserver { //protected CellRendererPane rendererPane = new CellRendererPane(); protected Border blackborder=null; protected Border redborder=null; protected Border raisedRed=null; private Border borderPainter=null; private mxGraphComponent graphComponent=null; private Paint gradient=null; /** * */ public HoopNodePanelRenderer (mxGraphComponent aComponent) { setClassName ("HoopNodePanelRenderer"); debug ("HoopNodePanelRenderer ()"); //GradientPaint redtowhite = new GradientPaint(5, 5, Color.red, 200, 5, Color.blue); gradient = new GradientPaint(0, 0, new Color(0xf3e2c7), 0, 50, new Color(0xc19e67), false); graphComponent=aComponent; borderPainter=BorderFactory.createBevelBorder(BevelBorder.RAISED); } /** * Ports are not used as terminals for edges, they are * only used to compute the graphical connection point */ public boolean isPort(Object cell) { mxGeometry geo =graphComponent.getGraph().getCellGeometry(cell); return (geo != null) ? geo.isRelative() : false; } /** * * @param state * @param label */ public void drawHoop (Graphics2D g, mxCellState state) { mxCell cell=(mxCell) state.getCell(); if (isPort (cell)) { g.setColor(new Color (217, 217, 217)); g.fillOval((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight()); g.setColor(new Color (100, 100, 100)); g.drawOval((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight()); } else { //HoopBase hoopTest=(HoopBase) cell.getValue(); // debug ("Check:<SUF> /* g.setColor(HoopProperties.getHoopColor (null)); g.fillRect((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight()); */ gradient = new GradientPaint(0, 0, new Color(0xf3e2c7), 0, (int) state.getHeight(), new Color(0xc19e67), false); g.setPaint(gradient); g.fill(new RoundRectangle2D.Double((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight(), 10, 10)); if (borderPainter!=null) { borderPainter.paintBorder(graphComponent, g, (int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight()); } else { g.draw3DRect((int) state.getX(), (int) state.getY(), (int) state.getWidth(), (int) state.getHeight(), true); } // Title area g.drawImage(HoopLink.getImageByName("led-yellow.png").getImage(), (int) state.getX()+4, (int) state.getY()+4, this); g.setColor(Color.black); /* g.drawString(hoopTest.getClassName(), (int) state.getX()+HoopLink.getImageByName("led-yellow.png").getIconWidth()+6, (int) state.getY()+16); */ g.drawString("HoopBase", (int) state.getX()+HoopLink.getImageByName("led-yellow.png").getIconWidth()+6, (int) state.getY()+16); g.drawImage(HoopLink.getImageByName("zoom.png").getImage(), (int) state.getX()+(int) state.getWidth()-(16*3)-4, (int) state.getY()+4, this); g.drawImage(HoopLink.getImageByName("gtk-execute.png").getImage(), (int) state.getX()+(int) state.getWidth()-(16*2)-4, (int) state.getY()+4, this); g.drawImage(HoopLink.getImageByName("help_icon.png").getImage(), (int) state.getX()+(int) state.getWidth()-(16*1)-4, (int) state.getY()+4, this); // Line markers g.setColor(Color.black); g.drawLine((int) state.getX()+4, (int) state.getY()+24, (int) state.getX()+(int) state.getWidth()-4, (int) state.getY()+24); g.setColor(Color.black); g.drawLine((int) state.getX()+4, (int) state.getY()+(int) state.getHeight()-24, (int) state.getX()+(int) state.getWidth()-4, (int) state.getY()+(int) state.getHeight()-24); // Footer area g.setColor(Color.black); g.drawString("Ex: 0, E: 1", (int) state.getX()+3, (int) state.getY()+(int) state.getHeight()-4); // Gripper g.drawImage(HoopLink.getImageByName("resize.png").getImage(), (int) state.getX()+(int) state.getWidth()-HoopLink.getImageByName("resize.png").getIconWidth()-2, (int) state.getY()+(int) state.getHeight()-HoopLink.getImageByName("resize.png").getIconHeight()-2, this); } } /** * No idea why we need this but the g.drawImage needs a pointer to some such interface */ @Override public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { return false; } }
73550_8
package gui; import Game.GameStateEnum; import Game.Panel; import Game.PanelTypeEnum; import gui.panel.IPanel; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Vito Corleone on 6-10-2015. */ public class GameController implements Initializable { private static final Logger log = Logger.getLogger(GameController.class.getName()); @FXML private Button buttonStart; @FXML private Button buttonStartTimer; @FXML private ProgressBar progressBar = new ProgressBar(1); @FXML private Label timeLabel; @FXML private Label secondenLabel; @FXML private Label instructionLabel; private Timer timer; @FXML private GridPane gridPane = new GridPane(); @FXML private Label labelCorrectInstructions; @FXML private ImageView Team1Leven1; @FXML private ImageView Team1Leven2; @FXML private ImageView Team1Leven3; @FXML private ImageView Team2Leven1; @FXML private ImageView Team2Leven2; @FXML private ImageView Team2Leven3; @FXML private TextField lblTeamName1; @FXML private TextField lblTeamName2; private GameView view; private Runnable runnable; private PanelFactory panelFactory; private java.util.Timer timerRefresh; private TimerTask timerTask; private List<Panel> panelHolder; private boolean newPanels; private boolean panelPushed; private int levenTeam1 = 3; private int levenTeam2 = 3; private int levensTeam1 = 3; private int levensTeam2 = 3; /** * Called to initialize a controller after its root element has been * completely processed. * <p/> * start a timer for refreshView * * @param location The location used to resolve relative paths for the root object, or * <tt>null</tt> if the location is not known. * @param resources The resources used to localize the root object, or <tt>null</tt> if */ public void initialize(URL location, ResourceBundle resources) { log.log(Level.INFO, "Start initializing the gamecontroller"); panelFactory = new PanelFactory(); newPanels = true; timerRefresh = new java.util.Timer(); timerTask = new TimerTask() { @Override public void run() { refreshView(); } }; timerRefresh.schedule(timerTask, 0, 500); } /** * Call methods to refresh the View */ private void refreshView() { log.log(Level.FINER, "refreshView started"); while (view == null) Thread.yield(); while (view.stageController.clientGame.localGame.panels.isEmpty()) Thread.yield(); while (view.stageController.clientGame.localGame.getInstruction() == null) { Thread.yield(); } panelChecker(); checkForNewPanels(); showTeamLevens(); showTeamInstructionCount(); showPlayerInstruction(); checkDeath(); log.log(Level.FINER, "refreshView ended"); } /** * checks if teams has died. */ private void checkDeath() { if (view.stageController.clientGame.hasGameEnded()) { timerTask.cancel(); Platform.runLater(() -> { view.stageController.clientGame.setGameState(GameStateEnum.ScoreView); ScoreView scoreView = new ScoreView(view.stageController); view.pass(scoreView); }); } } /** * checks if grid with panels is filled */ private void panelChecker() { Platform.runLater(() -> { if (panelHolder == null || (view.stageController.clientGame.localGame.panels.size() != panelHolder.size())) { panelHolder = view.stageController.clientGame.localGame.panels; fillGridWithPanels(); //view.stageController.clientGame.localGame.setPanels(new ArrayList<Panel>()); log.log(Level.INFO, "Gridview filled with {0} panels", view.stageController.clientGame.localGame.panels.size()); } }); } /** * Sets the GameView * refreshes the View * * @param gameView the view where the game is played */ public void setView(GameView gameView) { log.log(Level.FINER, "setView started"); view = gameView; showTeamLevens(); setTeamNames(); buttonStartTimerOnClick(null); log.log(Level.FINER, "setView ended"); } /** * Fills the gridPane with panels in the right row and column * refreshes every Round */ public void fillGridWithPanels() { log.log(Level.INFO, "fillGridWithPanels started"); gridPane.getChildren().clear(); gridPane.setMinSize(0, 0); gridPane.setAlignment(Pos.CENTER); log.log(Level.INFO, "gridPane children cleared, minsize set and alignment set"); final ArrayList<Panel> panels = (ArrayList<Panel>) view.stageController.clientGame.localGame.panels; int column = 0; int row = 0; log.log(Level.INFO, "Add panels to the gridpane"); for (Panel panel : panels) { IPanel iPanel = PanelFactory.getPanel(panel, this); System.out.println(panel.getText()); if (row < 4) { gridPane.add((Node) iPanel, row, column); } else { row = 0; column++; gridPane.add((Node) iPanel, row, column); } log.log(Level.FINER, "Added panel with text {0}", panel.getText()); row++; } log.log(Level.INFO, "Loaded {0} panels in the gridPane", panels.size()); panelHolder = new ArrayList<>(); panelHolder.addAll(panels); newPanels = false; } /** * Author Kamil Wasylkiewicz * This method is uses to check whether a team has lost a life and the system needs to give new panels. */ private void checkForNewPanels() { // deze methode in de timer laten draaien // controleren hoeveel levens een team heeft // zodra deze wijzigen dan de fill grid with panels aanroepen int levensTeam1 = 0; int levensTeam2 = 0; if (view.stageController.clientGame.localGame.player != null) { levensTeam1 = view.stageController.clientGame.getTeams().get(0).getLives(); levensTeam2 = view.stageController.clientGame.getTeams().get(1).getLives(); } if (this.levensTeam1 != levensTeam1) { this.panelHolder.clear(); this.levensTeam1 = levensTeam1; view.stageController.clientGame.localGame.setPanels(new ArrayList<Panel>()); } if (this.levensTeam2 != levensTeam2) { this.panelHolder.clear(); this.levensTeam2 = levensTeam2; view.stageController.clientGame.localGame.setPanels(new ArrayList<Panel>()); } } /** * Shows the player Instruction in instructionLabel * refreshes ever 30 ms */ private void showPlayerInstruction() { Platform.runLater(() -> { while (view.stageController.clientGame.localGame.getInstruction() == null) { Thread.yield(); } if (view.stageController.clientGame.localGame.player != null) log.log(Level.FINE, "Retrieving instruction for player {0}", view.stageController.clientGame.localGame.player.getUsername()); if (view.stageController.clientGame.localGame.getInstruction().getPanel().getPanelType() == PanelTypeEnum.Button) { instructionLabel.setText("Press the " + view.stageController.clientGame.localGame.getInstruction().getPanel().getText() + " button"); //player.getActiveInstruction().getPanel().getText() + " button"); } else { instructionLabel.setText("Set " + view.stageController.clientGame.localGame.getInstruction().getPanel().getText() + " to: " + view.stageController.clientGame.localGame.getInstruction().getIntendedValue()); } }); } /** * Shows amount of teams correct instructions in labelCorrectInstructions * refreshes ever 30 ms */ private void showTeamInstructionCount() { Platform.runLater(() -> { if (view.stageController.clientGame.localGame.player != null) log.log(Level.FINE, "Retrieving score for player {0}", view.stageController.clientGame.localGame.player.getUsername()); labelCorrectInstructions.setText(view.stageController.clientGame.localGame.score + ""); }); } /** * Shows for every team the amount of lives left. represented in buldings that are still standing * refreshes ever 30 ms */ private void showTeamLevens() { Platform.runLater(() -> { int levensTeam1; int levensTeam2; if (view.stageController.clientGame.localGame.player != null) { levensTeam1 = view.stageController.clientGame.getTeams().get(0).getLives(); levensTeam2 = view.stageController.clientGame.getTeams().get(1).getLives(); switch (levensTeam1) { case 1: Team1Leven1.setVisible(false); Team1Leven2.setVisible(true); Team1Leven3.setVisible(true); this.levenTeam1 = 2; break; case 2: { Team1Leven1.setVisible(false); Team1Leven2.setVisible(false); Team1Leven3.setVisible(true); this.levenTeam1 = 1; break; } case 3: { Team1Leven3.setVisible(false); Team1Leven2.setVisible(false); Team1Leven1.setVisible(false); this.levenTeam1 = 3; break; } default: Team1Leven1.setVisible(true); Team1Leven2.setVisible(true); Team1Leven3.setVisible(true); this.levenTeam1 = 0; break; } switch (levensTeam2) { case 1: Team2Leven1.setVisible(false); Team2Leven2.setVisible(true); Team2Leven3.setVisible(true); this.levenTeam1 = 2; break; case 2: { Team2Leven2.setVisible(false); Team2Leven1.setVisible(false); Team2Leven3.setVisible(true); this.levenTeam1 = 1; break; } case 3: { Team2Leven3.setVisible(false); Team2Leven2.setVisible(false); Team2Leven1.setVisible(false); this.levenTeam1 = 3; break; } default: Team2Leven1.setVisible(true); Team2Leven2.setVisible(true); Team2Leven3.setVisible(true); this.levenTeam1 = 0; break; } } }); } /** * //TODO fix it so it works for multiple teams * Sets the name of the teams that are playing */ private void setTeamNames() { Platform.runLater(() -> { lblTeamName1.setText(view.stageController.clientGame.getTeams().get(1).getName()); lblTeamName2.setText(view.stageController.clientGame.getTeams().get(0).getName()); }); } /** * When button StartTimer is pressed start a timer which counts down the amount of time you have to fulfill a instruction * * @param mouseEvent starts the timer for the game */ private void buttonStartTimerOnClick(MouseEvent mouseEvent) { while (view.stageController.clientGame.localGame.team == null) Thread.yield(); buttonStartTimer.setVisible(false); timer = new Timer(1000, new ActionListener() { int counter = view.stageController.clientGame.localGame.team.getTime(); @Override public void actionPerformed(ActionEvent actionEvent) { while (view.stageController.clientGame.localGame.panels.isEmpty()) Thread.yield(); counter--; //check if counter must be reset because a button or slider was used if (correctIn()) { //counter = view.stageController.clientGame.localGame.team.getTime() System.out.println(view.stageController.clientGame.localGame.team.getTime()); counter = view.stageController.clientGame.localGame.team.getTime(); } Platform.runLater(() -> { progressBar.setProgress(counter * 0.1); timeLabel.setText(counter + ""); }); if (counter == 0) { view.stageController.clientGame.registerInvalidInstruction(view.stageController.clientGame.localGame.getInstruction()); view.stageController.clientGame.localGame.setInstruction(null); counter = view.stageController.clientGame.localGame.team.getTime(); Platform.runLater(() -> { try { instructionLabel.setText("Processing"); Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } }); } } }); timer.start(); } /** * Trigger for if a panel was pressed or a slider was used * sets panelPushed back to false after one time * * @return true if a panel was pressed or used */ private boolean correctIn() { if (panelPushed) { panelPushed = false; log.log(Level.FINE, "panel is pushed"); return true; } log.log(Level.FINE, "panel is not pushed"); return false; } /** * Check if instructions was correctly completed * sets panelPused to true * If lives of a team is 0 change to ScoreView * * @param panel pressed/used panel * @param sliderValue value of the panel */ public void checkInstruction(Panel panel, int sliderValue) { log.log(Level.INFO, "Processing the panel for {0}", panel.getText()); panelPushed = true; view.stageController.clientGame.localGame.setInstruction(null); panel.setValue(sliderValue); view.stageController.clientGame.processPanel(view.stageController.clientGame.localGame.player, panel); Platform.runLater(() -> { try { instructionLabel.setText("Processing"); Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } }); } }
Requinard/TeamTab
src/main/java/gui/GameController.java
3,947
// deze methode in de timer laten draaien
line_comment
nl
package gui; import Game.GameStateEnum; import Game.Panel; import Game.PanelTypeEnum; import gui.panel.IPanel; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Vito Corleone on 6-10-2015. */ public class GameController implements Initializable { private static final Logger log = Logger.getLogger(GameController.class.getName()); @FXML private Button buttonStart; @FXML private Button buttonStartTimer; @FXML private ProgressBar progressBar = new ProgressBar(1); @FXML private Label timeLabel; @FXML private Label secondenLabel; @FXML private Label instructionLabel; private Timer timer; @FXML private GridPane gridPane = new GridPane(); @FXML private Label labelCorrectInstructions; @FXML private ImageView Team1Leven1; @FXML private ImageView Team1Leven2; @FXML private ImageView Team1Leven3; @FXML private ImageView Team2Leven1; @FXML private ImageView Team2Leven2; @FXML private ImageView Team2Leven3; @FXML private TextField lblTeamName1; @FXML private TextField lblTeamName2; private GameView view; private Runnable runnable; private PanelFactory panelFactory; private java.util.Timer timerRefresh; private TimerTask timerTask; private List<Panel> panelHolder; private boolean newPanels; private boolean panelPushed; private int levenTeam1 = 3; private int levenTeam2 = 3; private int levensTeam1 = 3; private int levensTeam2 = 3; /** * Called to initialize a controller after its root element has been * completely processed. * <p/> * start a timer for refreshView * * @param location The location used to resolve relative paths for the root object, or * <tt>null</tt> if the location is not known. * @param resources The resources used to localize the root object, or <tt>null</tt> if */ public void initialize(URL location, ResourceBundle resources) { log.log(Level.INFO, "Start initializing the gamecontroller"); panelFactory = new PanelFactory(); newPanels = true; timerRefresh = new java.util.Timer(); timerTask = new TimerTask() { @Override public void run() { refreshView(); } }; timerRefresh.schedule(timerTask, 0, 500); } /** * Call methods to refresh the View */ private void refreshView() { log.log(Level.FINER, "refreshView started"); while (view == null) Thread.yield(); while (view.stageController.clientGame.localGame.panels.isEmpty()) Thread.yield(); while (view.stageController.clientGame.localGame.getInstruction() == null) { Thread.yield(); } panelChecker(); checkForNewPanels(); showTeamLevens(); showTeamInstructionCount(); showPlayerInstruction(); checkDeath(); log.log(Level.FINER, "refreshView ended"); } /** * checks if teams has died. */ private void checkDeath() { if (view.stageController.clientGame.hasGameEnded()) { timerTask.cancel(); Platform.runLater(() -> { view.stageController.clientGame.setGameState(GameStateEnum.ScoreView); ScoreView scoreView = new ScoreView(view.stageController); view.pass(scoreView); }); } } /** * checks if grid with panels is filled */ private void panelChecker() { Platform.runLater(() -> { if (panelHolder == null || (view.stageController.clientGame.localGame.panels.size() != panelHolder.size())) { panelHolder = view.stageController.clientGame.localGame.panels; fillGridWithPanels(); //view.stageController.clientGame.localGame.setPanels(new ArrayList<Panel>()); log.log(Level.INFO, "Gridview filled with {0} panels", view.stageController.clientGame.localGame.panels.size()); } }); } /** * Sets the GameView * refreshes the View * * @param gameView the view where the game is played */ public void setView(GameView gameView) { log.log(Level.FINER, "setView started"); view = gameView; showTeamLevens(); setTeamNames(); buttonStartTimerOnClick(null); log.log(Level.FINER, "setView ended"); } /** * Fills the gridPane with panels in the right row and column * refreshes every Round */ public void fillGridWithPanels() { log.log(Level.INFO, "fillGridWithPanels started"); gridPane.getChildren().clear(); gridPane.setMinSize(0, 0); gridPane.setAlignment(Pos.CENTER); log.log(Level.INFO, "gridPane children cleared, minsize set and alignment set"); final ArrayList<Panel> panels = (ArrayList<Panel>) view.stageController.clientGame.localGame.panels; int column = 0; int row = 0; log.log(Level.INFO, "Add panels to the gridpane"); for (Panel panel : panels) { IPanel iPanel = PanelFactory.getPanel(panel, this); System.out.println(panel.getText()); if (row < 4) { gridPane.add((Node) iPanel, row, column); } else { row = 0; column++; gridPane.add((Node) iPanel, row, column); } log.log(Level.FINER, "Added panel with text {0}", panel.getText()); row++; } log.log(Level.INFO, "Loaded {0} panels in the gridPane", panels.size()); panelHolder = new ArrayList<>(); panelHolder.addAll(panels); newPanels = false; } /** * Author Kamil Wasylkiewicz * This method is uses to check whether a team has lost a life and the system needs to give new panels. */ private void checkForNewPanels() { // deze methode<SUF> // controleren hoeveel levens een team heeft // zodra deze wijzigen dan de fill grid with panels aanroepen int levensTeam1 = 0; int levensTeam2 = 0; if (view.stageController.clientGame.localGame.player != null) { levensTeam1 = view.stageController.clientGame.getTeams().get(0).getLives(); levensTeam2 = view.stageController.clientGame.getTeams().get(1).getLives(); } if (this.levensTeam1 != levensTeam1) { this.panelHolder.clear(); this.levensTeam1 = levensTeam1; view.stageController.clientGame.localGame.setPanels(new ArrayList<Panel>()); } if (this.levensTeam2 != levensTeam2) { this.panelHolder.clear(); this.levensTeam2 = levensTeam2; view.stageController.clientGame.localGame.setPanels(new ArrayList<Panel>()); } } /** * Shows the player Instruction in instructionLabel * refreshes ever 30 ms */ private void showPlayerInstruction() { Platform.runLater(() -> { while (view.stageController.clientGame.localGame.getInstruction() == null) { Thread.yield(); } if (view.stageController.clientGame.localGame.player != null) log.log(Level.FINE, "Retrieving instruction for player {0}", view.stageController.clientGame.localGame.player.getUsername()); if (view.stageController.clientGame.localGame.getInstruction().getPanel().getPanelType() == PanelTypeEnum.Button) { instructionLabel.setText("Press the " + view.stageController.clientGame.localGame.getInstruction().getPanel().getText() + " button"); //player.getActiveInstruction().getPanel().getText() + " button"); } else { instructionLabel.setText("Set " + view.stageController.clientGame.localGame.getInstruction().getPanel().getText() + " to: " + view.stageController.clientGame.localGame.getInstruction().getIntendedValue()); } }); } /** * Shows amount of teams correct instructions in labelCorrectInstructions * refreshes ever 30 ms */ private void showTeamInstructionCount() { Platform.runLater(() -> { if (view.stageController.clientGame.localGame.player != null) log.log(Level.FINE, "Retrieving score for player {0}", view.stageController.clientGame.localGame.player.getUsername()); labelCorrectInstructions.setText(view.stageController.clientGame.localGame.score + ""); }); } /** * Shows for every team the amount of lives left. represented in buldings that are still standing * refreshes ever 30 ms */ private void showTeamLevens() { Platform.runLater(() -> { int levensTeam1; int levensTeam2; if (view.stageController.clientGame.localGame.player != null) { levensTeam1 = view.stageController.clientGame.getTeams().get(0).getLives(); levensTeam2 = view.stageController.clientGame.getTeams().get(1).getLives(); switch (levensTeam1) { case 1: Team1Leven1.setVisible(false); Team1Leven2.setVisible(true); Team1Leven3.setVisible(true); this.levenTeam1 = 2; break; case 2: { Team1Leven1.setVisible(false); Team1Leven2.setVisible(false); Team1Leven3.setVisible(true); this.levenTeam1 = 1; break; } case 3: { Team1Leven3.setVisible(false); Team1Leven2.setVisible(false); Team1Leven1.setVisible(false); this.levenTeam1 = 3; break; } default: Team1Leven1.setVisible(true); Team1Leven2.setVisible(true); Team1Leven3.setVisible(true); this.levenTeam1 = 0; break; } switch (levensTeam2) { case 1: Team2Leven1.setVisible(false); Team2Leven2.setVisible(true); Team2Leven3.setVisible(true); this.levenTeam1 = 2; break; case 2: { Team2Leven2.setVisible(false); Team2Leven1.setVisible(false); Team2Leven3.setVisible(true); this.levenTeam1 = 1; break; } case 3: { Team2Leven3.setVisible(false); Team2Leven2.setVisible(false); Team2Leven1.setVisible(false); this.levenTeam1 = 3; break; } default: Team2Leven1.setVisible(true); Team2Leven2.setVisible(true); Team2Leven3.setVisible(true); this.levenTeam1 = 0; break; } } }); } /** * //TODO fix it so it works for multiple teams * Sets the name of the teams that are playing */ private void setTeamNames() { Platform.runLater(() -> { lblTeamName1.setText(view.stageController.clientGame.getTeams().get(1).getName()); lblTeamName2.setText(view.stageController.clientGame.getTeams().get(0).getName()); }); } /** * When button StartTimer is pressed start a timer which counts down the amount of time you have to fulfill a instruction * * @param mouseEvent starts the timer for the game */ private void buttonStartTimerOnClick(MouseEvent mouseEvent) { while (view.stageController.clientGame.localGame.team == null) Thread.yield(); buttonStartTimer.setVisible(false); timer = new Timer(1000, new ActionListener() { int counter = view.stageController.clientGame.localGame.team.getTime(); @Override public void actionPerformed(ActionEvent actionEvent) { while (view.stageController.clientGame.localGame.panels.isEmpty()) Thread.yield(); counter--; //check if counter must be reset because a button or slider was used if (correctIn()) { //counter = view.stageController.clientGame.localGame.team.getTime() System.out.println(view.stageController.clientGame.localGame.team.getTime()); counter = view.stageController.clientGame.localGame.team.getTime(); } Platform.runLater(() -> { progressBar.setProgress(counter * 0.1); timeLabel.setText(counter + ""); }); if (counter == 0) { view.stageController.clientGame.registerInvalidInstruction(view.stageController.clientGame.localGame.getInstruction()); view.stageController.clientGame.localGame.setInstruction(null); counter = view.stageController.clientGame.localGame.team.getTime(); Platform.runLater(() -> { try { instructionLabel.setText("Processing"); Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } }); } } }); timer.start(); } /** * Trigger for if a panel was pressed or a slider was used * sets panelPushed back to false after one time * * @return true if a panel was pressed or used */ private boolean correctIn() { if (panelPushed) { panelPushed = false; log.log(Level.FINE, "panel is pushed"); return true; } log.log(Level.FINE, "panel is not pushed"); return false; } /** * Check if instructions was correctly completed * sets panelPused to true * If lives of a team is 0 change to ScoreView * * @param panel pressed/used panel * @param sliderValue value of the panel */ public void checkInstruction(Panel panel, int sliderValue) { log.log(Level.INFO, "Processing the panel for {0}", panel.getText()); panelPushed = true; view.stageController.clientGame.localGame.setInstruction(null); panel.setValue(sliderValue); view.stageController.clientGame.processPanel(view.stageController.clientGame.localGame.player, panel); Platform.runLater(() -> { try { instructionLabel.setText("Processing"); Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } }); } }
60051_2
package com.catehuston.imagefilter.app; import java.io.File; import processing.core.PApplet; import com.catehuston.imagefilter.color.ColorHelper; import com.catehuston.imagefilter.color.PixelColorHelper; import com.catehuston.imagefilter.model.ImageState; @SuppressWarnings("serial") public class ImageFilterApp extends PApplet { static final String INSTRUCTIONS = "R: increase red filter\nE: reduce red filter\n" + "G: increase green filter\nF: reduce green filter\nB: increase blue filter\n" + "V: reduce blue filter\nI: increase hue tolerance\nU: reduce hue tolerance\n" + "S: show dominant hue\nH: hide dominant hue\nP: process image\n" + "C: choose a new file\nW: save file\nSPACE: reset image"; static final int FILTER_HEIGHT = 2; static final int FILTER_INCREMENT = 5; static final int HUE_INCREMENT = 2; static final int HUE_RANGE = 100; static final int IMAGE_MAX = 640; static final int RGB_COLOR_RANGE = 100; static final int SIDE_BAR_PADDING = 10; static final int SIDE_BAR_WIDTH = RGB_COLOR_RANGE + 2 * SIDE_BAR_PADDING + 50; private ImageState imageState; boolean redrawImage = true; @Override public void setup() { noLoop(); imageState = new ImageState(new ColorHelper(new PixelColorHelper())); // Set up the view. size(IMAGE_MAX + SIDE_BAR_WIDTH, IMAGE_MAX); background(0); chooseFile(); } @Override public void draw() { // Draw image. if (imageState.image().image() != null && redrawImage) { background(0); drawImage(); } colorMode(RGB, RGB_COLOR_RANGE); fill(0); rect(IMAGE_MAX, 0, SIDE_BAR_WIDTH, IMAGE_MAX); stroke(RGB_COLOR_RANGE); line(IMAGE_MAX, 0, IMAGE_MAX, IMAGE_MAX); // Draw red line int x = IMAGE_MAX + SIDE_BAR_PADDING; int y = 2 * SIDE_BAR_PADDING; stroke(RGB_COLOR_RANGE, 0, 0); line(x, y, x + RGB_COLOR_RANGE, y); line(x + imageState.redFilter(), y - FILTER_HEIGHT, x + imageState.redFilter(), y + FILTER_HEIGHT); // Draw green line y += 2 * SIDE_BAR_PADDING; stroke(0, RGB_COLOR_RANGE, 0); line(x, y, x + RGB_COLOR_RANGE, y); line(x + imageState.greenFilter(), y - FILTER_HEIGHT, x + imageState.greenFilter(), y + FILTER_HEIGHT); // Draw blue line y += 2 * SIDE_BAR_PADDING; stroke(0, 0, RGB_COLOR_RANGE); line(x, y, x + RGB_COLOR_RANGE, y); line(x + imageState.blueFilter(), y - FILTER_HEIGHT, x + imageState.blueFilter(), y + FILTER_HEIGHT); // Draw white line. y += 2 * SIDE_BAR_PADDING; stroke(HUE_RANGE); line(x, y, x + 100, y); line(x + imageState.hueTolerance(), y - FILTER_HEIGHT, x + imageState.hueTolerance(), y + FILTER_HEIGHT); y += 4 * SIDE_BAR_PADDING; fill(RGB_COLOR_RANGE); text(INSTRUCTIONS, x, y); updatePixels(); } // Callback for selectInput(), has to be public to be found. public void fileSelected(File file) { if (file == null) { println("User hit cancel."); } else { imageState.setFilepath(file.getAbsolutePath()); imageState.setUpImage(this, IMAGE_MAX); redrawImage = true; redraw(); } } private void drawImage() { imageMode(CENTER); imageState.updateImage(this, HUE_RANGE, RGB_COLOR_RANGE, IMAGE_MAX); image(imageState.image().image(), IMAGE_MAX/2, IMAGE_MAX/2, imageState.image().getWidth(), imageState.image().getHeight()); redrawImage = false; } @Override public void keyPressed() { switch(key) { case 'c': chooseFile(); break; case 'p': redrawImage = true; break; case ' ': imageState.resetImage(this, IMAGE_MAX); redrawImage = true; break; } imageState.processKeyPress(key, FILTER_INCREMENT, RGB_COLOR_RANGE, HUE_INCREMENT, HUE_RANGE); redraw(); } private void chooseFile() { // Choose the file. selectInput("Select a file to process:", "fileSelected"); } }
aosabook/500lines
image-filters/code/com/catehuston/imagefilter/app/ImageFilterApp.java
1,283
// Draw green line
line_comment
nl
package com.catehuston.imagefilter.app; import java.io.File; import processing.core.PApplet; import com.catehuston.imagefilter.color.ColorHelper; import com.catehuston.imagefilter.color.PixelColorHelper; import com.catehuston.imagefilter.model.ImageState; @SuppressWarnings("serial") public class ImageFilterApp extends PApplet { static final String INSTRUCTIONS = "R: increase red filter\nE: reduce red filter\n" + "G: increase green filter\nF: reduce green filter\nB: increase blue filter\n" + "V: reduce blue filter\nI: increase hue tolerance\nU: reduce hue tolerance\n" + "S: show dominant hue\nH: hide dominant hue\nP: process image\n" + "C: choose a new file\nW: save file\nSPACE: reset image"; static final int FILTER_HEIGHT = 2; static final int FILTER_INCREMENT = 5; static final int HUE_INCREMENT = 2; static final int HUE_RANGE = 100; static final int IMAGE_MAX = 640; static final int RGB_COLOR_RANGE = 100; static final int SIDE_BAR_PADDING = 10; static final int SIDE_BAR_WIDTH = RGB_COLOR_RANGE + 2 * SIDE_BAR_PADDING + 50; private ImageState imageState; boolean redrawImage = true; @Override public void setup() { noLoop(); imageState = new ImageState(new ColorHelper(new PixelColorHelper())); // Set up the view. size(IMAGE_MAX + SIDE_BAR_WIDTH, IMAGE_MAX); background(0); chooseFile(); } @Override public void draw() { // Draw image. if (imageState.image().image() != null && redrawImage) { background(0); drawImage(); } colorMode(RGB, RGB_COLOR_RANGE); fill(0); rect(IMAGE_MAX, 0, SIDE_BAR_WIDTH, IMAGE_MAX); stroke(RGB_COLOR_RANGE); line(IMAGE_MAX, 0, IMAGE_MAX, IMAGE_MAX); // Draw red line int x = IMAGE_MAX + SIDE_BAR_PADDING; int y = 2 * SIDE_BAR_PADDING; stroke(RGB_COLOR_RANGE, 0, 0); line(x, y, x + RGB_COLOR_RANGE, y); line(x + imageState.redFilter(), y - FILTER_HEIGHT, x + imageState.redFilter(), y + FILTER_HEIGHT); // Draw green<SUF> y += 2 * SIDE_BAR_PADDING; stroke(0, RGB_COLOR_RANGE, 0); line(x, y, x + RGB_COLOR_RANGE, y); line(x + imageState.greenFilter(), y - FILTER_HEIGHT, x + imageState.greenFilter(), y + FILTER_HEIGHT); // Draw blue line y += 2 * SIDE_BAR_PADDING; stroke(0, 0, RGB_COLOR_RANGE); line(x, y, x + RGB_COLOR_RANGE, y); line(x + imageState.blueFilter(), y - FILTER_HEIGHT, x + imageState.blueFilter(), y + FILTER_HEIGHT); // Draw white line. y += 2 * SIDE_BAR_PADDING; stroke(HUE_RANGE); line(x, y, x + 100, y); line(x + imageState.hueTolerance(), y - FILTER_HEIGHT, x + imageState.hueTolerance(), y + FILTER_HEIGHT); y += 4 * SIDE_BAR_PADDING; fill(RGB_COLOR_RANGE); text(INSTRUCTIONS, x, y); updatePixels(); } // Callback for selectInput(), has to be public to be found. public void fileSelected(File file) { if (file == null) { println("User hit cancel."); } else { imageState.setFilepath(file.getAbsolutePath()); imageState.setUpImage(this, IMAGE_MAX); redrawImage = true; redraw(); } } private void drawImage() { imageMode(CENTER); imageState.updateImage(this, HUE_RANGE, RGB_COLOR_RANGE, IMAGE_MAX); image(imageState.image().image(), IMAGE_MAX/2, IMAGE_MAX/2, imageState.image().getWidth(), imageState.image().getHeight()); redrawImage = false; } @Override public void keyPressed() { switch(key) { case 'c': chooseFile(); break; case 'p': redrawImage = true; break; case ' ': imageState.resetImage(this, IMAGE_MAX); redrawImage = true; break; } imageState.processKeyPress(key, FILTER_INCREMENT, RGB_COLOR_RANGE, HUE_INCREMENT, HUE_RANGE); redraw(); } private void chooseFile() { // Choose the file. selectInput("Select a file to process:", "fileSelected"); } }
173628_0
package mprog.nl.findmystuff; //Jochem van Dooren //[email protected] //10572929 import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.InputType; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { List<String> objectList; ArrayAdapter<String> adapter; String selected; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //create arrayadapter and list for objects objectList = new ArrayList<String>(); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, objectList); ListView listView = (ListView) findViewById(R.id.listView); listView.setAdapter(adapter); //retrieve objects based on currentuser ParseQuery<ParseObject> query = ParseQuery.getQuery("ObjectList"); query.whereEqualTo("user", ParseUser.getCurrentUser().getUsername()); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> results, ParseException e) { if (e == null) { for (ParseObject result : results) { //add all the objects to the list objectList.add(result.getString("object")); } //update the listview adapter.notifyDataSetChanged(); } else { Toast.makeText(getApplicationContext(), "There seems to be a problem loading your objects...", Toast.LENGTH_LONG).show(); } } }); //click on list item and go to map activity listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, MapsActivity.class); String selected = (String)parent.getItemAtPosition(position); //remember selected object in next activity intent.putExtra("object", selected); startActivity(intent); } }); //removing objects from the list listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { selected = (String)parent.getItemAtPosition(position); //confirmation dialog AlertDialog.Builder alert = new AlertDialog.Builder( MainActivity.this); alert.setTitle("Alert!"); alert.setMessage("Are you sure to delete this object?"); //remove object from Parse and list alert.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { objectList.remove(selected); ParseQuery<ParseObject> query = ParseQuery.getQuery("ObjectList"); query.whereEqualTo("user", ParseUser.getCurrentUser().getUsername()); query.whereEqualTo("object", selected); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> results, ParseException e) { if (e == null) { for (ParseObject result : results) { try { result.delete(); } catch (ParseException e1) { e1.printStackTrace(); } result.saveInBackground(); } } else { Toast.makeText(getApplicationContext(), "Trouble deleting your object in Parse...", Toast.LENGTH_LONG).show(); } } }); //update the listview adapter.notifyDataSetChanged(); dialog.dismiss(); } }); alert.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); return true; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } public void gotoMap(View view) { Intent intent = new Intent(MainActivity.this, MapsActivity.class); startActivity(intent); finish(); } public void logOut(View view) { Intent intent = new Intent(MainActivity.this, LoginActivity.class); ParseUser.getCurrentUser().logOut(); Toast.makeText(getApplicationContext(), "You signed out!", Toast.LENGTH_LONG).show(); startActivity(intent); finish(); } public void addObject(View view){ //create dialog AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("What object do you want to track?"); alert.setMessage("You can add an object by filling in the form and pressing OK."); // Set an EditText view to get user input final EditText input = new EditText(this); alert.setView(input); //Click OK in alert dialog alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //convert input to string and upload to Parse/add to array String object = input.getText().toString().toLowerCase(); //check if object meets requirements if (objectList.contains(object)) { Toast.makeText(getApplicationContext(), "There already is an object named " + object, Toast.LENGTH_LONG).show(); } else if (object.contains(" ")) { Toast.makeText(getApplicationContext(), "Your object cannot contain whitespace!", Toast.LENGTH_LONG).show(); } else if (object.contentEquals("")){ Toast.makeText(getApplicationContext(), "Your object cannot be nothing.", Toast.LENGTH_LONG).show(); } else { //add the object to the list and Parse ParseObject dataObject = new ParseObject("ObjectList"); dataObject.put("user", ParseUser.getCurrentUser().getUsername()); dataObject.put("object", object); dataObject.saveInBackground(); objectList.add(object); } } }); //cancel alert dialog alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
jochemvandooren/Programmeerproject
FindMyStuff/app/src/main/java/mprog/nl/findmystuff/MainActivity.java
1,887
//Jochem van Dooren
line_comment
nl
package mprog.nl.findmystuff; //Jochem van<SUF> //[email protected] //10572929 import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.InputType; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { List<String> objectList; ArrayAdapter<String> adapter; String selected; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //create arrayadapter and list for objects objectList = new ArrayList<String>(); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, objectList); ListView listView = (ListView) findViewById(R.id.listView); listView.setAdapter(adapter); //retrieve objects based on currentuser ParseQuery<ParseObject> query = ParseQuery.getQuery("ObjectList"); query.whereEqualTo("user", ParseUser.getCurrentUser().getUsername()); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> results, ParseException e) { if (e == null) { for (ParseObject result : results) { //add all the objects to the list objectList.add(result.getString("object")); } //update the listview adapter.notifyDataSetChanged(); } else { Toast.makeText(getApplicationContext(), "There seems to be a problem loading your objects...", Toast.LENGTH_LONG).show(); } } }); //click on list item and go to map activity listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, MapsActivity.class); String selected = (String)parent.getItemAtPosition(position); //remember selected object in next activity intent.putExtra("object", selected); startActivity(intent); } }); //removing objects from the list listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { selected = (String)parent.getItemAtPosition(position); //confirmation dialog AlertDialog.Builder alert = new AlertDialog.Builder( MainActivity.this); alert.setTitle("Alert!"); alert.setMessage("Are you sure to delete this object?"); //remove object from Parse and list alert.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { objectList.remove(selected); ParseQuery<ParseObject> query = ParseQuery.getQuery("ObjectList"); query.whereEqualTo("user", ParseUser.getCurrentUser().getUsername()); query.whereEqualTo("object", selected); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> results, ParseException e) { if (e == null) { for (ParseObject result : results) { try { result.delete(); } catch (ParseException e1) { e1.printStackTrace(); } result.saveInBackground(); } } else { Toast.makeText(getApplicationContext(), "Trouble deleting your object in Parse...", Toast.LENGTH_LONG).show(); } } }); //update the listview adapter.notifyDataSetChanged(); dialog.dismiss(); } }); alert.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); return true; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } public void gotoMap(View view) { Intent intent = new Intent(MainActivity.this, MapsActivity.class); startActivity(intent); finish(); } public void logOut(View view) { Intent intent = new Intent(MainActivity.this, LoginActivity.class); ParseUser.getCurrentUser().logOut(); Toast.makeText(getApplicationContext(), "You signed out!", Toast.LENGTH_LONG).show(); startActivity(intent); finish(); } public void addObject(View view){ //create dialog AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("What object do you want to track?"); alert.setMessage("You can add an object by filling in the form and pressing OK."); // Set an EditText view to get user input final EditText input = new EditText(this); alert.setView(input); //Click OK in alert dialog alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //convert input to string and upload to Parse/add to array String object = input.getText().toString().toLowerCase(); //check if object meets requirements if (objectList.contains(object)) { Toast.makeText(getApplicationContext(), "There already is an object named " + object, Toast.LENGTH_LONG).show(); } else if (object.contains(" ")) { Toast.makeText(getApplicationContext(), "Your object cannot contain whitespace!", Toast.LENGTH_LONG).show(); } else if (object.contentEquals("")){ Toast.makeText(getApplicationContext(), "Your object cannot be nothing.", Toast.LENGTH_LONG).show(); } else { //add the object to the list and Parse ParseObject dataObject = new ParseObject("ObjectList"); dataObject.put("user", ParseUser.getCurrentUser().getUsername()); dataObject.put("object", object); dataObject.saveInBackground(); objectList.add(object); } } }); //cancel alert dialog alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
150998_9
// Importeer de Scanner klasse import java.util.Scanner; public class DayOfWeek { /** * @param args */ public static void main(String[] args) { // Instantieer een nieuw Scanner object Scanner input = new Scanner(System.in); // Vraag gebruiker het jaar, de maand en de dag van de maand in te voeren: jaar, maand en dag. System.out.print("Voer het jaartal in, bijvoorbeeld '1978': "); int jaar = input.nextInt(); System.out.print("Voer de maand in, 1 voor januari, 4 voor april, etc.: "); int maand = input.nextInt(); System.out.print("Voer de dag van de maand in (1-31): "); int dag = input.nextInt(); // Bereken q: = dag int q = dag; // Bereken m: = maand als de maand niet januari of februari is, anders m = maand+12 en jaar = jaar-1 int m = maand; if (m < 3) { m = m + 12; jaar = jaar - 1; } // bereken j, de eeuw = jaar / 100 int j = jaar / 100; // bereken k, het jaar van de eeuw: = jaar % 100 int k = jaar % 100; // bereken h, de numerieke waarde van de dag van de week: h = (q + (26*(m + 1))/10 + k + k/4 + j/4 + 5*j)%7 int h = (q + (26 * (m + 1)) / 10 + k + (k / 4) + (j / 4) + (5 * j)) % 7; // Geef de naam van de dag met een switch statement switch (h) { case 0: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zaterdag."); break; case 1: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zondag."); break; case 2: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een maandag."); break; case 3: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een dinsdag."); break; case 4: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een woensdag."); break; case 5: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een donderdag."); break; case 6: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een vrijdag."); break; } } }
JobSarneel/java
h1-3/DayOfWeek.java
727
// Geef de naam van de dag met een switch statement
line_comment
nl
// Importeer de Scanner klasse import java.util.Scanner; public class DayOfWeek { /** * @param args */ public static void main(String[] args) { // Instantieer een nieuw Scanner object Scanner input = new Scanner(System.in); // Vraag gebruiker het jaar, de maand en de dag van de maand in te voeren: jaar, maand en dag. System.out.print("Voer het jaartal in, bijvoorbeeld '1978': "); int jaar = input.nextInt(); System.out.print("Voer de maand in, 1 voor januari, 4 voor april, etc.: "); int maand = input.nextInt(); System.out.print("Voer de dag van de maand in (1-31): "); int dag = input.nextInt(); // Bereken q: = dag int q = dag; // Bereken m: = maand als de maand niet januari of februari is, anders m = maand+12 en jaar = jaar-1 int m = maand; if (m < 3) { m = m + 12; jaar = jaar - 1; } // bereken j, de eeuw = jaar / 100 int j = jaar / 100; // bereken k, het jaar van de eeuw: = jaar % 100 int k = jaar % 100; // bereken h, de numerieke waarde van de dag van de week: h = (q + (26*(m + 1))/10 + k + k/4 + j/4 + 5*j)%7 int h = (q + (26 * (m + 1)) / 10 + k + (k / 4) + (j / 4) + (5 * j)) % 7; // Geef de<SUF> switch (h) { case 0: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zaterdag."); break; case 1: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een zondag."); break; case 2: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een maandag."); break; case 3: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een dinsdag."); break; case 4: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een woensdag."); break; case 5: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een donderdag."); break; case 6: System.out.println(dag + "-" + maand + "-" + jaar + " valt op een vrijdag."); break; } } }
19808_8
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // Type casting is wanneer je een waarde toewijst van een primitieve datatype naar een ander datatype. //We kennen 2 manieren om een type casting te doen: System.out.println(" ---- Widening casting ---- "); // Widening Casting - omzetten van een kleinere type naar een grotere type. int myInt = 9; // Automatische casting: int naar double double myDouble = myInt; System.out.println("Integer = " + myInt); System.out.println("Double = " + myDouble); // De conversie tussen numeriek datatype naar char of Boolean gebeurt niet automatisch. // Ook zijn de gegevenstypen char en Boolean niet compatibel met elkaar. char myChar = 'q'; // compileer fout "incompatible types: char cannot be converted to boolean" // boolean myBoolean = myChar; // System.out.println(myChar); // System.out.println(myBoolean); System.out.println(" ---- Narrowing casting ---- "); // Narrowing Casting (handmatig) - een groter type omzetten naar een kleiner formaat type. double Double = 9.78d; // Manueel casting: double naar int int myInteger = (int) Double; System.out.println("Double = " + Double); System.out.println("Integer = " + myInteger); } }
Gabe-Alvess/Typecasting
src/be/intecbrussel/MainApp.java
360
// Narrowing Casting (handmatig) - een groter type omzetten naar een kleiner formaat type.
line_comment
nl
package be.intecbrussel; public class MainApp { public static void main(String[] args) { // Type casting is wanneer je een waarde toewijst van een primitieve datatype naar een ander datatype. //We kennen 2 manieren om een type casting te doen: System.out.println(" ---- Widening casting ---- "); // Widening Casting - omzetten van een kleinere type naar een grotere type. int myInt = 9; // Automatische casting: int naar double double myDouble = myInt; System.out.println("Integer = " + myInt); System.out.println("Double = " + myDouble); // De conversie tussen numeriek datatype naar char of Boolean gebeurt niet automatisch. // Ook zijn de gegevenstypen char en Boolean niet compatibel met elkaar. char myChar = 'q'; // compileer fout "incompatible types: char cannot be converted to boolean" // boolean myBoolean = myChar; // System.out.println(myChar); // System.out.println(myBoolean); System.out.println(" ---- Narrowing casting ---- "); // Narrowing Casting<SUF> double Double = 9.78d; // Manueel casting: double naar int int myInteger = (int) Double; System.out.println("Double = " + Double); System.out.println("Integer = " + myInteger); } }
1643_0
package main.application; /** * Vraag 6 - Pascal Triangle * Pascals driehoek is een bekende piramide waarbij het bovenste getal 1 is en de opvolgende rijen de som zijn * van de 2 bovenliggende aangrenzende getallen. Zie hieronder een voorbeeld : * * 1 * 1 1 * 1 2 1 * 1 3 3 1 * 1 4 6 4 1 * 1 5 10 10 5 1 * * Bereken de som van de onderste rij van een Pascal-driehoek met duizend rijen. De top van de driehoek telt niet mee als rij. * Gebruik in je antwoord de wetenschappelijke notatie, rond af op 4 cijfers achter de komma, bijvoorbeeld: 1.0903E+23 */ public class VraagSei { public static void main(String[] args) { //Antwoord is: 1.0715E+301 Excel } }
Igoranze/Martyrs-mega-project-list
tweakers-devv-contest/src/main/application/VraagSei.java
252
/** * Vraag 6 - Pascal Triangle * Pascals driehoek is een bekende piramide waarbij het bovenste getal 1 is en de opvolgende rijen de som zijn * van de 2 bovenliggende aangrenzende getallen. Zie hieronder een voorbeeld : * * 1 * 1 1 * 1 2 1 * 1 3 3 1 * 1 4 6 4 1 * 1 5 10 10 5 1 * * Bereken de som van de onderste rij van een Pascal-driehoek met duizend rijen. De top van de driehoek telt niet mee als rij. * Gebruik in je antwoord de wetenschappelijke notatie, rond af op 4 cijfers achter de komma, bijvoorbeeld: 1.0903E+23 */
block_comment
nl
package main.application; /** * Vraag 6 -<SUF>*/ public class VraagSei { public static void main(String[] args) { //Antwoord is: 1.0715E+301 Excel } }
22658_9
package game.reversi; import framework.GameClient; import framework.GameSelectMenu; import framework.LobbyController; import framework.MessageBus; import framework.interfaces.Controller; import framework.interfaces.Networkable; import game.abstraction.AbstractServerController; import java.awt.Point; import java.net.URL; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Line; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.collections.ObservableList; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.text.Text; import javafx.util.Duration; import org.json.simple.*; import org.json.simple.parser.*; /** * Created by markshizzle on 4-4-2017. */ public class ServerController extends AbstractServerController implements Networkable,Initializable{ @FXML Label timer; @FXML GridPane winLoseGrid; @FXML private Label scoreB; @FXML private Label scoreW; @FXML Label turn; @FXML Button playAgainBtn; private final String game = "Reversi"; private boolean isTournament = false; private int turns = 0; private char our_colour = ' '; private char their_colour = ' '; private boolean can_move = false; private Text text; private Model model; private char currentTurn; private boolean[][] legalMovesW; private boolean[][] legalMovesB; private final int STARTTIME = 10; private int remainSec = STARTTIME; private boolean endGame; private String winner; private int totalW = 0; private int totalB = 0; private int amountLegalMovesB; private int amountLegalMovesW; private Timeline timeline; private String our_name; @FXML private GridPane grid; @FXML private Label turnLabel; public ServerController(){ LobbyController lc = new LobbyController(game); GameClient.load(lc,"CENTER"); MessageBus mb = MessageBus.getBus(); mb.register("LOBBY", lc); mb.call("MENU", "tournament mode on", null); lc.init(); initHandlers(); } private void newGame(){ model = new Model(); turns = 0; legalMovesW = new boolean[8][8]; legalMovesB = new boolean[8][8]; currentTurn = 'b'; drawBoard(); } public void registerGame() { } @Override public void initialize(URL location, ResourceBundle resources){ String loc = location.toString(); System.out.println(loc); if(loc.endsWith("SidebarGameMenuFXML.fxml")){ turnLabel.setText("Our colour is"); String colour = (our_colour == 'w') ? "white" : "black"; turn.setText(colour); } } private void initHandlers() { super.registerHandler("SVR GAME CHALLENGE", this::handleChallenge); super.registerHandler("SVR GAME MATCH", this::handleMatchStarted); super.registerHandler("SVR GAME MOVE", this::handleMove); super.registerHandler("SVR GAME YOURTURN", this::turnStart); super.registerHandler("GAME CHALLENGE ACCEPT", this::handleChallengeAccept); super.registerHandler("GAME SUBSCRIBE", this::handleSubscribe); super.registerHandler("tournament mode toggle", this::setTournamentMode); } @Override public void putData(ArrayList<String> messages) { for(String m : messages){ String[] parts = m.split("\\s+"); switch(parts[0]){ case "name": this.our_name = m.replace("name ", ""); break; } } } private void turnStart(String message, Object[] args){ can_move = true; if(isTournament){ calcPoints(); // Berekent de volgende legale zetten getLegalMoves(); System.out.println("I think my colour is " + our_colour); Point m = new AI(model, our_colour, 0.075).nextMove(); System.out.println("Next:" + m.x + ", " + m.y); MessageBus.getBus().call("NETWORK", "move " + (m.y * 8 + m.x), null); } } private void setTournamentMode(String message, Object[] args){ isTournament = !isTournament; } void drawBoard() { int countBlack = 0; int countWhite = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (model.getSymbol(i,j) == 'b') { drawO('b', i, j); countBlack++; } if (model.getSymbol(i,j) == 'w') { drawO('w', i, j); countWhite++; } } } String whiteString = countWhite+""; String blackString = countBlack+""; Platform.runLater(()->{ scoreW.setText(whiteString); scoreB.setText(blackString); }); } private void drawO(char colour, int column, int row) { Platform.runLater(()->{ Circle c1 = new Circle(0, 0, 38); c1.setStroke(Color.BLACK); if(colour == 'b') { c1.setFill(Color.BLACK); } if(colour == 'w') { c1.setFill(Color.WHITE); } c1.setStrokeWidth(3); grid.add(c1,column,row); }); } private void handleChallenge(String message, Object[] args) { // Since the server string isn't valid JSON, we'll have to pry out our answers. String toParse = message.substring(19); Pattern p = Pattern.compile("\\{CHALLENGER: \"(.*?)\", CHALLENGENUMBER: \"(\\d*?)\", GAMETYPE: \"(.*?)\"\\}"); Matcher m = p.matcher(toParse); if (m.find()) { if (m.group(3).equals(game)) { System.out.println("Incoming challenge from " + m.group(1)); MessageBus.getBus().call("LOBBY", "CHALLENGE", new String[] { m.group(1), m.group(2), m.group(3)}); } } } private void handleMatchStarted(String message, Object[] args) { MessageBus mb = MessageBus.getBus(); Object[] args_to_send = new Object[1]; args_to_send[0] = this; mb.call("NETWORK", "get name", args_to_send); String parsedMessage = message.substring(15) .replace("PLAYERTOMOVE","\"PLAYERTOMOVE\"") .replace("GAMETYPE", "\"GAMETYPE\"") .replace("OPPONENT:", "\"OPPONENT\""); Object o; try { JSONParser parser = new JSONParser(); o = parser.parse(parsedMessage); JSONObject playerJSON = (JSONObject) o; String player_to_move = (String) playerJSON.get("PLAYERTOMOVE"); System.out.println(player_to_move + " " + our_name); if(player_to_move.equals(our_name)){ our_colour = 'b'; their_colour = 'w'; } else{ our_colour = 'w'; their_colour = 'b'; } GameClient.load(this, "CENTER"); GameClient.load(this, "LEFT", "../game/reversi/SidebarGameMenuFXML.fxml"); newGame(); } catch (ParseException ex) { Logger.getLogger(ServerController.class.getName()).log(Level.SEVERE, null, ex); } } private void handleMove(String message, Object[] args) { String parsedMessage = message.substring(14) .replace("PLAYER","\"PLAYER\"") .replace("MOVE", "\"MOVE\"") .replace("DETAILS", "\"DETAILS\""); Object o; try { JSONParser parser = new JSONParser(); o = parser.parse(parsedMessage); JSONObject playerJSON = (JSONObject) o; int position = Integer.parseInt((String) playerJSON.get("MOVE")); int row = (position - (position % 8)) / 8; int col = position - row*8; turns++; char to_move; if(( (String) playerJSON.get("PLAYER") ).equals(our_name)) to_move = our_colour; else to_move = their_colour; legalMove(col, row, to_move, true); model.setSymbol(col, row, to_move); drawBoard(); } catch (ParseException ex) { Logger.getLogger(ServerController.class.getName()).log(Level.SEVERE, null, ex); } } private void handleChallengeAccept(String message, Object[] args) { System.out.println("Accepting challenge " + args[0]); MessageBus mb = MessageBus.getBus(); mb.call("NETWORK", "challenge accept " + args[0], null); } private void handleSubscribe(String message, Object[] args) { MessageBus.getBus().call("NETWORK", "subscribe " + this.game, null); } @Override public String getLocation() { return "../game/reversi/ReversiBoard.fxml"; } @FXML public void squareClicked(MouseEvent event) { if(can_move){ Label l = (Label) event.getSource(); MessageBus.getBus().call("NETWORK", "move " + (GridPane.getRowIndex(l) * 8 + GridPane.getColumnIndex(l)), null); can_move = false; } } public void doMove(int column, int row) { if(legalMove(column, row, our_colour, false)) { remainSec = STARTTIME; model.setSymbol(column, row, our_colour); } else { createDialog("Invalid move", "This is an invalid move."); return; } calcPoints(); drawBoard(); // Berekent de volgende legale zetten } private boolean checkIfLegalMove(char currentTurn) { if(currentTurn == 'b') { if(amountLegalMovesB == 0) { return false; } } if(currentTurn == 'w') { if (amountLegalMovesW == 0) { return false; } } return true; } private void setTimer() { timeline = new Timeline(new KeyFrame( Duration.millis(1000), ae -> countDown())); timeline.setCycleCount(Animation.INDEFINITE); timeline.play(); } private void countDown() { remainSec--; if(endGame) { timeline.stop(); } if(remainSec == 0 || remainSec < 0) { createDialog("Game over", "You ran out of time!"); endGame = true; if(currentTurn == 'b') winner = "White"; else winner = "Black"; timeline.stop(); } timer.setText("00:0" + remainSec); } private void calcPoints() { totalW = 0; totalB = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (model.getSymbol(i, j) == 'w') { totalW++; } else if(model.getSymbol(i,j) == 'b') { totalB++; } } } //scoreB.setText("" + totalB); //scoreW.setText("" + totalW); } public void createDialog(String title, String content) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle(title); alert.setHeaderText(null); alert.setContentText(content); alert.show(); } public void getLegalMoves() { amountLegalMovesB = 0; amountLegalMovesW = 0; for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { legalMovesW[i][j] = legalMove(i,j,currentTurn,false); if(legalMove(i,j,'w',false)) { amountLegalMovesW++; } legalMovesB[i][j] = legalMove(i,j,currentTurn,false); if(legalMove(i,j,'b',false)) { amountLegalMovesB++; } } } } public boolean legalMove(int r, int c, char color, boolean flip) { boolean legal = false; char oppSymbol; // Als de cel leeg is begin met zoeken // Als de cel niet leeg is wordt het afgebroken if (model.getSymbol(r,c) != 'w' && model.getSymbol(r,c) != 'b') { // Initialize variables int posX; int posY; boolean found; char current; // Zoekt in elke richting // x en y beschrijven alle richtingen for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { //Variabelen om de positie bij te houden en of het een valid zet is. posX = c + x; posY = r + y; found = false; if (posX > -1 && posX < 8 && posY > -1 && posY < 8) { current = model.getSymbol(posY,posX); oppSymbol = color == 'b' ? 'w' : 'b'; if (current != oppSymbol) { continue; } while (!found) { posX += x; posY += y; if (posX < 0 || posX > 7 || posY < 0 || posY > 7) { found = true; } else { current = model.getSymbol(posY, posX); oppSymbol = currentTurn == 'b' ? 'w' : 'b'; if (current == color) { found = true; legal = true; // Als flip op true staat mag er omgedraaid worden. // De algoritme draait dan om een gaat alles omdraaien // tot de oorspronkelijke positie bereikt is. if (flip) { posX -= x; posY -= y; if (posX > -1 && posX < 8 && posY > -1 && posY < 8) { current = model.getSymbol(posY, posX); oppSymbol = color == 'b' ? 'w' : 'b'; while (current == oppSymbol) { model.setSymbol(posY, posX, color); posX -= x; posY -= y; current = model.getSymbol(posY, posX); } } } } // Als het algoritme een cel vind dat leeg is // wordt de loop afgebroken en op zoek gegaan naar een andere plek else if (current != 'w' && current != 'b') { found = true; } } } } } } } return legal; } @FXML public void handlePlayAgainButton(){ } @FXML public void handleQuitButton(){ Controller ctrl = new GameSelectMenu(); GameClient.load(ctrl, "LEFT", ctrl.getLocation()); MessageBus.getBus().call("CLIENT", "display home", null); } @FXML public void handleForfeitButton(){ handleQuitButton(); } public void showWinLoseGrid(){ ObservableList<Node> children = winLoseGrid.getChildren(); for(Node n : children){ if(n instanceof Label){ ((Label) n).setText(winner + " won!"); } } children.remove(playAgainBtn); winLoseGrid.setVisible(true); } }
HanzehogeschoolSICT/GameClient
src/game/reversi/ServerController.java
4,317
// x en y beschrijven alle richtingen
line_comment
nl
package game.reversi; import framework.GameClient; import framework.GameSelectMenu; import framework.LobbyController; import framework.MessageBus; import framework.interfaces.Controller; import framework.interfaces.Networkable; import game.abstraction.AbstractServerController; import java.awt.Point; import java.net.URL; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Line; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.collections.ObservableList; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.text.Text; import javafx.util.Duration; import org.json.simple.*; import org.json.simple.parser.*; /** * Created by markshizzle on 4-4-2017. */ public class ServerController extends AbstractServerController implements Networkable,Initializable{ @FXML Label timer; @FXML GridPane winLoseGrid; @FXML private Label scoreB; @FXML private Label scoreW; @FXML Label turn; @FXML Button playAgainBtn; private final String game = "Reversi"; private boolean isTournament = false; private int turns = 0; private char our_colour = ' '; private char their_colour = ' '; private boolean can_move = false; private Text text; private Model model; private char currentTurn; private boolean[][] legalMovesW; private boolean[][] legalMovesB; private final int STARTTIME = 10; private int remainSec = STARTTIME; private boolean endGame; private String winner; private int totalW = 0; private int totalB = 0; private int amountLegalMovesB; private int amountLegalMovesW; private Timeline timeline; private String our_name; @FXML private GridPane grid; @FXML private Label turnLabel; public ServerController(){ LobbyController lc = new LobbyController(game); GameClient.load(lc,"CENTER"); MessageBus mb = MessageBus.getBus(); mb.register("LOBBY", lc); mb.call("MENU", "tournament mode on", null); lc.init(); initHandlers(); } private void newGame(){ model = new Model(); turns = 0; legalMovesW = new boolean[8][8]; legalMovesB = new boolean[8][8]; currentTurn = 'b'; drawBoard(); } public void registerGame() { } @Override public void initialize(URL location, ResourceBundle resources){ String loc = location.toString(); System.out.println(loc); if(loc.endsWith("SidebarGameMenuFXML.fxml")){ turnLabel.setText("Our colour is"); String colour = (our_colour == 'w') ? "white" : "black"; turn.setText(colour); } } private void initHandlers() { super.registerHandler("SVR GAME CHALLENGE", this::handleChallenge); super.registerHandler("SVR GAME MATCH", this::handleMatchStarted); super.registerHandler("SVR GAME MOVE", this::handleMove); super.registerHandler("SVR GAME YOURTURN", this::turnStart); super.registerHandler("GAME CHALLENGE ACCEPT", this::handleChallengeAccept); super.registerHandler("GAME SUBSCRIBE", this::handleSubscribe); super.registerHandler("tournament mode toggle", this::setTournamentMode); } @Override public void putData(ArrayList<String> messages) { for(String m : messages){ String[] parts = m.split("\\s+"); switch(parts[0]){ case "name": this.our_name = m.replace("name ", ""); break; } } } private void turnStart(String message, Object[] args){ can_move = true; if(isTournament){ calcPoints(); // Berekent de volgende legale zetten getLegalMoves(); System.out.println("I think my colour is " + our_colour); Point m = new AI(model, our_colour, 0.075).nextMove(); System.out.println("Next:" + m.x + ", " + m.y); MessageBus.getBus().call("NETWORK", "move " + (m.y * 8 + m.x), null); } } private void setTournamentMode(String message, Object[] args){ isTournament = !isTournament; } void drawBoard() { int countBlack = 0; int countWhite = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (model.getSymbol(i,j) == 'b') { drawO('b', i, j); countBlack++; } if (model.getSymbol(i,j) == 'w') { drawO('w', i, j); countWhite++; } } } String whiteString = countWhite+""; String blackString = countBlack+""; Platform.runLater(()->{ scoreW.setText(whiteString); scoreB.setText(blackString); }); } private void drawO(char colour, int column, int row) { Platform.runLater(()->{ Circle c1 = new Circle(0, 0, 38); c1.setStroke(Color.BLACK); if(colour == 'b') { c1.setFill(Color.BLACK); } if(colour == 'w') { c1.setFill(Color.WHITE); } c1.setStrokeWidth(3); grid.add(c1,column,row); }); } private void handleChallenge(String message, Object[] args) { // Since the server string isn't valid JSON, we'll have to pry out our answers. String toParse = message.substring(19); Pattern p = Pattern.compile("\\{CHALLENGER: \"(.*?)\", CHALLENGENUMBER: \"(\\d*?)\", GAMETYPE: \"(.*?)\"\\}"); Matcher m = p.matcher(toParse); if (m.find()) { if (m.group(3).equals(game)) { System.out.println("Incoming challenge from " + m.group(1)); MessageBus.getBus().call("LOBBY", "CHALLENGE", new String[] { m.group(1), m.group(2), m.group(3)}); } } } private void handleMatchStarted(String message, Object[] args) { MessageBus mb = MessageBus.getBus(); Object[] args_to_send = new Object[1]; args_to_send[0] = this; mb.call("NETWORK", "get name", args_to_send); String parsedMessage = message.substring(15) .replace("PLAYERTOMOVE","\"PLAYERTOMOVE\"") .replace("GAMETYPE", "\"GAMETYPE\"") .replace("OPPONENT:", "\"OPPONENT\""); Object o; try { JSONParser parser = new JSONParser(); o = parser.parse(parsedMessage); JSONObject playerJSON = (JSONObject) o; String player_to_move = (String) playerJSON.get("PLAYERTOMOVE"); System.out.println(player_to_move + " " + our_name); if(player_to_move.equals(our_name)){ our_colour = 'b'; their_colour = 'w'; } else{ our_colour = 'w'; their_colour = 'b'; } GameClient.load(this, "CENTER"); GameClient.load(this, "LEFT", "../game/reversi/SidebarGameMenuFXML.fxml"); newGame(); } catch (ParseException ex) { Logger.getLogger(ServerController.class.getName()).log(Level.SEVERE, null, ex); } } private void handleMove(String message, Object[] args) { String parsedMessage = message.substring(14) .replace("PLAYER","\"PLAYER\"") .replace("MOVE", "\"MOVE\"") .replace("DETAILS", "\"DETAILS\""); Object o; try { JSONParser parser = new JSONParser(); o = parser.parse(parsedMessage); JSONObject playerJSON = (JSONObject) o; int position = Integer.parseInt((String) playerJSON.get("MOVE")); int row = (position - (position % 8)) / 8; int col = position - row*8; turns++; char to_move; if(( (String) playerJSON.get("PLAYER") ).equals(our_name)) to_move = our_colour; else to_move = their_colour; legalMove(col, row, to_move, true); model.setSymbol(col, row, to_move); drawBoard(); } catch (ParseException ex) { Logger.getLogger(ServerController.class.getName()).log(Level.SEVERE, null, ex); } } private void handleChallengeAccept(String message, Object[] args) { System.out.println("Accepting challenge " + args[0]); MessageBus mb = MessageBus.getBus(); mb.call("NETWORK", "challenge accept " + args[0], null); } private void handleSubscribe(String message, Object[] args) { MessageBus.getBus().call("NETWORK", "subscribe " + this.game, null); } @Override public String getLocation() { return "../game/reversi/ReversiBoard.fxml"; } @FXML public void squareClicked(MouseEvent event) { if(can_move){ Label l = (Label) event.getSource(); MessageBus.getBus().call("NETWORK", "move " + (GridPane.getRowIndex(l) * 8 + GridPane.getColumnIndex(l)), null); can_move = false; } } public void doMove(int column, int row) { if(legalMove(column, row, our_colour, false)) { remainSec = STARTTIME; model.setSymbol(column, row, our_colour); } else { createDialog("Invalid move", "This is an invalid move."); return; } calcPoints(); drawBoard(); // Berekent de volgende legale zetten } private boolean checkIfLegalMove(char currentTurn) { if(currentTurn == 'b') { if(amountLegalMovesB == 0) { return false; } } if(currentTurn == 'w') { if (amountLegalMovesW == 0) { return false; } } return true; } private void setTimer() { timeline = new Timeline(new KeyFrame( Duration.millis(1000), ae -> countDown())); timeline.setCycleCount(Animation.INDEFINITE); timeline.play(); } private void countDown() { remainSec--; if(endGame) { timeline.stop(); } if(remainSec == 0 || remainSec < 0) { createDialog("Game over", "You ran out of time!"); endGame = true; if(currentTurn == 'b') winner = "White"; else winner = "Black"; timeline.stop(); } timer.setText("00:0" + remainSec); } private void calcPoints() { totalW = 0; totalB = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (model.getSymbol(i, j) == 'w') { totalW++; } else if(model.getSymbol(i,j) == 'b') { totalB++; } } } //scoreB.setText("" + totalB); //scoreW.setText("" + totalW); } public void createDialog(String title, String content) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle(title); alert.setHeaderText(null); alert.setContentText(content); alert.show(); } public void getLegalMoves() { amountLegalMovesB = 0; amountLegalMovesW = 0; for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { legalMovesW[i][j] = legalMove(i,j,currentTurn,false); if(legalMove(i,j,'w',false)) { amountLegalMovesW++; } legalMovesB[i][j] = legalMove(i,j,currentTurn,false); if(legalMove(i,j,'b',false)) { amountLegalMovesB++; } } } } public boolean legalMove(int r, int c, char color, boolean flip) { boolean legal = false; char oppSymbol; // Als de cel leeg is begin met zoeken // Als de cel niet leeg is wordt het afgebroken if (model.getSymbol(r,c) != 'w' && model.getSymbol(r,c) != 'b') { // Initialize variables int posX; int posY; boolean found; char current; // Zoekt in elke richting // x en<SUF> for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { //Variabelen om de positie bij te houden en of het een valid zet is. posX = c + x; posY = r + y; found = false; if (posX > -1 && posX < 8 && posY > -1 && posY < 8) { current = model.getSymbol(posY,posX); oppSymbol = color == 'b' ? 'w' : 'b'; if (current != oppSymbol) { continue; } while (!found) { posX += x; posY += y; if (posX < 0 || posX > 7 || posY < 0 || posY > 7) { found = true; } else { current = model.getSymbol(posY, posX); oppSymbol = currentTurn == 'b' ? 'w' : 'b'; if (current == color) { found = true; legal = true; // Als flip op true staat mag er omgedraaid worden. // De algoritme draait dan om een gaat alles omdraaien // tot de oorspronkelijke positie bereikt is. if (flip) { posX -= x; posY -= y; if (posX > -1 && posX < 8 && posY > -1 && posY < 8) { current = model.getSymbol(posY, posX); oppSymbol = color == 'b' ? 'w' : 'b'; while (current == oppSymbol) { model.setSymbol(posY, posX, color); posX -= x; posY -= y; current = model.getSymbol(posY, posX); } } } } // Als het algoritme een cel vind dat leeg is // wordt de loop afgebroken en op zoek gegaan naar een andere plek else if (current != 'w' && current != 'b') { found = true; } } } } } } } return legal; } @FXML public void handlePlayAgainButton(){ } @FXML public void handleQuitButton(){ Controller ctrl = new GameSelectMenu(); GameClient.load(ctrl, "LEFT", ctrl.getLocation()); MessageBus.getBus().call("CLIENT", "display home", null); } @FXML public void handleForfeitButton(){ handleQuitButton(); } public void showWinLoseGrid(){ ObservableList<Node> children = winLoseGrid.getChildren(); for(Node n : children){ if(n instanceof Label){ ((Label) n).setText(winner + " won!"); } } children.remove(playAgainBtn); winLoseGrid.setVisible(true); } }
6334_5
package novi.basics; import static novi.basics.Main.PLAYERINPUT; public class Game { private Field[] board; private int maxRounds; private Player player1; private Player player2; private int drawCount; private Player activePlayer; public Game(Player player1, Player player2){ // speelbord opslaan (1 - 9) // uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven // zie demo project code voor de andere manier met de for loop //board= new char[]{'1','2','3','4','5','6','7','8','9'}; board = new Field[9]; for (int fieldIndex = 0; fieldIndex <9; fieldIndex++) { board[fieldIndex] = new Field(fieldIndex + 1); } // maximale aantal rondes opslaan maxRounds=board.length; this.player1 = player1; this.player2 = player2; } public void play(){ // opslaan hoeveel keer er gelijk spel is geweest int drawCount = 0; // -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is) { // speelbord tonen printBoard(); // token van de actieve speler opslaan //char activePlayerToken = player1.getToken(); // starten met de beurt (maximaal 9 beurten) for(int round=0;round<maxRounds; round++){ /* // naam van de actieve speler opslaan String activePlayerName; if(activePlayerToken == player1.getToken()) { activePlayerName = player1.getName(); } else { activePlayerName = player2.getName(); }*/ String activePlayerName=activePlayer.getName(); // actieve speler vragen om een veld te kiezen (1 - 9) System.out.println(activePlayerName+", please choose a field"); //setField(); // gekozen veld van de actieve speler opslaan int chosenField=PLAYERINPUT.nextInt(); int chosenIndex=chosenField-1; // als het veld bestaat if(chosenIndex< 9 && chosenIndex>=0){ //als het veld leeg is, wanneer er geen token staat if(board[chosenIndex].isEmpty()) { // wanneer de speler een token op het bord kan plaatsen // de token van de actieve speler op het gekozen veld plaatsen board[chosenIndex].setToken(activePlayer.getToken()); //player.score += 10; // het nieuwe speelbord tonen printBoard(); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we in de laatste beurt zijn en niemand gewonnen heeft // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: // changePlayer(); if(activePlayer==player1){ // maak de actieve speler, speler 2 activePlayer=player2; } // anders else{ // maak de actieve speler weer speler 1 activePlayer=player1; } } //of al bezet is else{ maxRounds++; System.out.println("this field is not available, choose another"); } //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ } // als het veld niet bestaat else{ // het mamimale aantal beurten verhogen maxRounds++; // foutmelding tonen aan de speler System.out.println("the chosen field does not exist, try again"); } // -- terug naar het begin van de volgende beurt } // vragen of de spelers nog een keer willen spelen //1: nog een keer spelen //2: van spelers wisselen //3: afsluiten // speler keuze opslaan // bij keuze 1: terug naar het maken van het bord // bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen // bij keuze 3: het spel en de applicatie helemaal afsluiten } } public void printBoard(){ for(int fieldIndex=0;fieldIndex<board.length;fieldIndex++){ System.out.print(board[fieldIndex].getToken()+" "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if(fieldIndex==2||fieldIndex==5){ System.out.println(); } } System.out.println(); } }
hogeschoolnovi/tic-tac-toe-Daaniy
src/novi/basics/Game.java
1,240
// opslaan hoeveel keer er gelijk spel is geweest
line_comment
nl
package novi.basics; import static novi.basics.Main.PLAYERINPUT; public class Game { private Field[] board; private int maxRounds; private Player player1; private Player player2; private int drawCount; private Player activePlayer; public Game(Player player1, Player player2){ // speelbord opslaan (1 - 9) // uitleg: omdat we altijd met een bord starten met 9 getallen, kunnen we het Tic Tac Toe bord ook direct een waarde geven // zie demo project code voor de andere manier met de for loop //board= new char[]{'1','2','3','4','5','6','7','8','9'}; board = new Field[9]; for (int fieldIndex = 0; fieldIndex <9; fieldIndex++) { board[fieldIndex] = new Field(fieldIndex + 1); } // maximale aantal rondes opslaan maxRounds=board.length; this.player1 = player1; this.player2 = player2; } public void play(){ // opslaan hoeveel<SUF> int drawCount = 0; // -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is) { // speelbord tonen printBoard(); // token van de actieve speler opslaan //char activePlayerToken = player1.getToken(); // starten met de beurt (maximaal 9 beurten) for(int round=0;round<maxRounds; round++){ /* // naam van de actieve speler opslaan String activePlayerName; if(activePlayerToken == player1.getToken()) { activePlayerName = player1.getName(); } else { activePlayerName = player2.getName(); }*/ String activePlayerName=activePlayer.getName(); // actieve speler vragen om een veld te kiezen (1 - 9) System.out.println(activePlayerName+", please choose a field"); //setField(); // gekozen veld van de actieve speler opslaan int chosenField=PLAYERINPUT.nextInt(); int chosenIndex=chosenField-1; // als het veld bestaat if(chosenIndex< 9 && chosenIndex>=0){ //als het veld leeg is, wanneer er geen token staat if(board[chosenIndex].isEmpty()) { // wanneer de speler een token op het bord kan plaatsen // de token van de actieve speler op het gekozen veld plaatsen board[chosenIndex].setToken(activePlayer.getToken()); //player.score += 10; // het nieuwe speelbord tonen printBoard(); // als het spel gewonnen is // tonen wie er gewonnen heeft (de actieve speler) // de actieve speler krijgt een punt // de scores van de spelers tonen // wanneer we in de laatste beurt zijn en niemand gewonnen heeft // aantal keer gelijk spel ophogen // aantal keer gelijk spel tonen // de beurt doorgeven aan de volgende speler (van speler wisselen) // als de actieve speler, speler 1 is: // changePlayer(); if(activePlayer==player1){ // maak de actieve speler, speler 2 activePlayer=player2; } // anders else{ // maak de actieve speler weer speler 1 activePlayer=player1; } } //of al bezet is else{ maxRounds++; System.out.println("this field is not available, choose another"); } //versie 2: als het veld leeg is, wanneer de waarde gelijk is aan chosenField /*if(board[chosenIndex] != '1' + chosenIndex) { board[chosenIndex] = activePlayerToken; }*/ } // als het veld niet bestaat else{ // het mamimale aantal beurten verhogen maxRounds++; // foutmelding tonen aan de speler System.out.println("the chosen field does not exist, try again"); } // -- terug naar het begin van de volgende beurt } // vragen of de spelers nog een keer willen spelen //1: nog een keer spelen //2: van spelers wisselen //3: afsluiten // speler keuze opslaan // bij keuze 1: terug naar het maken van het bord // bij keuze 2: terug naar de start van de applicatie en het vragen van spelernamen // bij keuze 3: het spel en de applicatie helemaal afsluiten } } public void printBoard(){ for(int fieldIndex=0;fieldIndex<board.length;fieldIndex++){ System.out.print(board[fieldIndex].getToken()+" "); // als we het tweede veld geprint hebben of het vijfde veld geprint hebben // dan gaan we naar de volgende regel if(fieldIndex==2||fieldIndex==5){ System.out.println(); } } System.out.println(); } }
160417_2
package nl.hva.hvacrawler.communication.controller; import nl.hva.hvacrawler.business.domain.Potion; import nl.hva.hvacrawler.business.service.PotionService; import nl.hva.hvacrawler.communication.controller.PotionController; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.util.Optional; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* * In de onderstaande code gebruik ik Mockito om de PotionService na te bootsen. * Verder geef ik aan hoe deze zich moet gedragen wanneer de methoden ervan worden * aangeroepen. Vervolgens gebruik ik MockMvc om HTTP GET request uit te voeren * naar de controller enspoints en de verwachte statuscodes te checken. */ @WebMvcTest(PotionController.class) public class PotionControllerTest { @MockBean private PotionService potionService; private MockMvc mockMvc; @BeforeEach void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(new PotionController(potionService)).build(); } @Test void testGetPotionById() throws Exception { int potionId = 1; Potion testPotion = new Potion(); // Mockt een potion // Mockt de PotionService om getPotionById te testen. Mockito.when(potionService.getPotionById(potionId)).thenReturn(Optional.of(testPotion)); // Doet een GET request /potion/{id} en verwacht status code 200 System.out.println("Stap 1: Mocking PotionService."); ResultActions resultActions = mockMvc.perform(get("/potion/{id}", potionId) .contentType(MediaType.APPLICATION_JSON)); System.out.println("Stap 2: GET request gedaan naar /potion/{id}."); resultActions.andExpect(status().isOk()); System.out.println("Stap 3: Verwachtte statuscode gecontroleerd."); System.out.println("Test 'testGetPotionById' is voltooid."); } @Test void testGetRandomPotion() throws Exception { Potion testPotion = new Potion(); Mockito.when(potionService.getRandomPotion()).thenReturn(Optional.of(testPotion)); // Doet een GET request /random-potion en verwacht status code 200 System.out.println("Stap 1: Mocking PotionService voor getRandomPotion."); ResultActions resultActions = mockMvc.perform(get("/random-potion") .contentType(MediaType.APPLICATION_JSON)); System.out.println("Stap 2: GET request gedaan naar /random-potion."); resultActions.andExpect(status().isOk()); System.out.println("Stap 3: Verwachtte statuscode gecontroleerd."); System.out.println("Test 'testGetRandomPotion' is voltooid."); } }
PetyaKatsarova/my_dungeon_crawler2
dungeonCrawlerGithub - Copy/webapp/src/test/java/nl/hva/hvacrawler/communication/controller/PotionControllerTest.java
842
// Mockt de PotionService om getPotionById te testen.
line_comment
nl
package nl.hva.hvacrawler.communication.controller; import nl.hva.hvacrawler.business.domain.Potion; import nl.hva.hvacrawler.business.service.PotionService; import nl.hva.hvacrawler.communication.controller.PotionController; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.util.Optional; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /* * In de onderstaande code gebruik ik Mockito om de PotionService na te bootsen. * Verder geef ik aan hoe deze zich moet gedragen wanneer de methoden ervan worden * aangeroepen. Vervolgens gebruik ik MockMvc om HTTP GET request uit te voeren * naar de controller enspoints en de verwachte statuscodes te checken. */ @WebMvcTest(PotionController.class) public class PotionControllerTest { @MockBean private PotionService potionService; private MockMvc mockMvc; @BeforeEach void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(new PotionController(potionService)).build(); } @Test void testGetPotionById() throws Exception { int potionId = 1; Potion testPotion = new Potion(); // Mockt een potion // Mockt de<SUF> Mockito.when(potionService.getPotionById(potionId)).thenReturn(Optional.of(testPotion)); // Doet een GET request /potion/{id} en verwacht status code 200 System.out.println("Stap 1: Mocking PotionService."); ResultActions resultActions = mockMvc.perform(get("/potion/{id}", potionId) .contentType(MediaType.APPLICATION_JSON)); System.out.println("Stap 2: GET request gedaan naar /potion/{id}."); resultActions.andExpect(status().isOk()); System.out.println("Stap 3: Verwachtte statuscode gecontroleerd."); System.out.println("Test 'testGetPotionById' is voltooid."); } @Test void testGetRandomPotion() throws Exception { Potion testPotion = new Potion(); Mockito.when(potionService.getRandomPotion()).thenReturn(Optional.of(testPotion)); // Doet een GET request /random-potion en verwacht status code 200 System.out.println("Stap 1: Mocking PotionService voor getRandomPotion."); ResultActions resultActions = mockMvc.perform(get("/random-potion") .contentType(MediaType.APPLICATION_JSON)); System.out.println("Stap 2: GET request gedaan naar /random-potion."); resultActions.andExpect(status().isOk()); System.out.println("Stap 3: Verwachtte statuscode gecontroleerd."); System.out.println("Test 'testGetRandomPotion' is voltooid."); } }
15386_6
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class World1 extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public World1() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {61,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {60,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {6,6,6,6,128,-1,-1,-1,-1,-1,-1,177,175,177,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {6,2,2,6,128,-1,-1,-1,-1,-1,-1,64,64,64,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {6,2,2,6,128,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,102,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {6,6,6,6,128,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,104,-1,-1,-1,-1,-1,102,-1,-1,-1,-1,-1,102,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {91,91,91,91,64,64,64,64,64,64,64,64,64,64,64,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,104,-1,-1,-1,-1,-1,104,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,91,91,91,91,91,91,91,91,91,91,91,1,1,17,17,17,17,17,17,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,6,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,6,6,6,1,1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,-1,-1,-1,-1,-1,-1,-1,-1,6,102,102,102,102,102,102,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,104,104,104,104,104,104,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,178,-1}, {-1,-1,75,76,64,17,17,17,17,17,17,64,77,-1,-1,-1,-1,64,64,64,64,64,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,1,-1}, {64,64,64,64,64,94,94,94,94,94,94,65,78,77,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,24,26,26,26,26,26,26,26,26,26,26,26,26,22,-1,-1,-1,-1,-1,-1}, {93,93,93,93,93,93,93,93,93,93,93,65,65,78,77,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,17,-1,-1,17,-1,-1,17,-1,-1,17,64,64,64,64,64,16,-1,-1,16,-1,-1,16,-1,16,-1,20,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92}, {93,93,93,93,93,93,93,93,93,93,93,65,65,65,78,77,-1,-1,-1,-1,-1,-1,-1,75,76,94,94,94,94,94,94,94,94,94,94,15,15,15,15,15,92,92,92,92,92,92,92,92,92,92,20,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90}, {93,93,93,93,93,93,93,93,93,93,93,65,65,65,65,78,77,-1,-1,-1,-1,-1,75,76,65,93,93,93,93,93,93,93,93,93,93,15,15,15,15,15,90,90,90,90,90,90,90,90,90,90,20,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90}, {93,93,93,93,93,93,93,93,93,93,93,65,65,65,65,65,65,64,64,64,64,64,65,65,65,93,93,93,93,93,93,93,93,93,93,15,15,15,15,15,90,90,90,90,90,90,90,90,90,90,20,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(4); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 84, 973); addObject(new Enemy(), 1170, 410); showText("Level 1", 100, 120); addObject(new HUD(), 0, 0); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } }
ROCMondriaanTIN/project-greenfoot-game-skiffa070
World1.java
4,141
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class World1 extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public World1() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {61,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {60,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {6,6,6,6,128,-1,-1,-1,-1,-1,-1,177,175,177,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {6,2,2,6,128,-1,-1,-1,-1,-1,-1,64,64,64,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {6,2,2,6,128,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,102,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {6,6,6,6,128,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,104,-1,-1,-1,-1,-1,102,-1,-1,-1,-1,-1,102,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {91,91,91,91,64,64,64,64,64,64,64,64,64,64,64,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,104,-1,-1,-1,-1,-1,104,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,91,91,91,91,91,91,91,91,91,91,91,1,1,17,17,17,17,17,17,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,6,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {90,90,90,90,90,90,90,90,90,90,90,90,90,90,19,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,6,6,6,6,6,1,1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,-1,-1,-1,-1,-1,-1,-1,-1,6,102,102,102,102,102,102,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,104,104,104,104,104,104,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,178,-1}, {-1,-1,75,76,64,17,17,17,17,17,17,64,77,-1,-1,-1,-1,64,64,64,64,64,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,1,-1}, {64,64,64,64,64,94,94,94,94,94,94,65,78,77,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,24,26,26,26,26,26,26,26,26,26,26,26,26,22,-1,-1,-1,-1,-1,-1}, {93,93,93,93,93,93,93,93,93,93,93,65,65,78,77,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,17,-1,-1,17,-1,-1,17,-1,-1,17,64,64,64,64,64,16,-1,-1,16,-1,-1,16,-1,16,-1,20,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92,92}, {93,93,93,93,93,93,93,93,93,93,93,65,65,65,78,77,-1,-1,-1,-1,-1,-1,-1,75,76,94,94,94,94,94,94,94,94,94,94,15,15,15,15,15,92,92,92,92,92,92,92,92,92,92,20,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90}, {93,93,93,93,93,93,93,93,93,93,93,65,65,65,65,78,77,-1,-1,-1,-1,-1,75,76,65,93,93,93,93,93,93,93,93,93,93,15,15,15,15,15,90,90,90,90,90,90,90,90,90,90,20,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90}, {93,93,93,93,93,93,93,93,93,93,93,65,65,65,65,65,65,64,64,64,64,64,65,65,65,93,93,93,93,93,93,93,93,93,93,15,15,15,15,15,90,90,90,90,90,90,90,90,90,90,20,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de<SUF> Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(4); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 84, 973); addObject(new Enemy(), 1170, 410); showText("Level 1", 100, 120); addObject(new HUD(), 0, 0); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } }
10819_0
import ........ // Bestudeer de code. Raadpleeg daar waar nodig is de API. // Beantwoord de vragen .. zie commentaar bij de code. public class DataView extends JPanel implements ............................................... { private Bal bal; private final int MINHOOGTE = 17; // minmale hoogte van dit view private int hoogte; // actuele hoogte van dit view private int x, y; private boolean dragged = false; private int dragX, dragY; public DataView (................) { // zet de achtergrondkleur van dit view op oranje // voeg verschillende MouseListeners toe aan dit view Border titelrand = // view met een rand en titel "bal-data" // zie (bv in de API) de klasse BorderFactory en // de methode createTitledBorder this.setBorder (titelrand); setBounds (0, 0, 180, hoogte); // wat doet dit statement? } public void paintComponent (Graphics g) { super.paintComponent(g); if ((x != 0) && (y != 0)) setLocation (x, y); String st_t = String.format ("%.2f", bal.getT() / 1000.0); // wat doet dit statement precies? // waarom wordt er door 1000.0 gedeeld? String st_y = // idem, maar nu met de actuele, afgelegde afstand van de bal String st_vy = // idem, maar nu met de actuele snelheid van de bal // zet de schrijfkleur op blauw // druk tijd (in sec), afgelegde weg (in meter) en snelheid (in meter/sec) netjes // onder elkaar af in deze view } // MouseWheelListener-method public void mouseWheelMoved (MouseWheelEvent ev) { int ticks = ev.getWheelRotation(); // pas de hoogte van deze view aan mbv de waarde 'ticks' // De minmale hoogte moet MINHOOGTE zijn } // MouseListener-methods public void mouseClicked (MouseEvent me) {} public void mouseEntered (MouseEvent me) {} public void mouseExited (MouseEvent me) {} // waarom staan deze methoden hier? // als ze niets doen dan kan je ze toch beter gewoon weglaten? public void mouseReleased (MouseEvent me) { .... // zie ook mouseDragged } public void mousePressed (MouseEvent me) // wat moet deze methode hier? {} // MouseMotionListener-methods public void mouseDragged (MouseEvent me) { // zie aan de hand van het Vierkanten-voorbeeld // hoe je de view kan verplaatsen (tweede werkcollege, week 1) // maak gebruik van de eigenschappen 'dragX', 'dragY' en 'dragged' } public void mouseMoved (MouseEvent me) // wat moet deze methode hier? {} }
reshadf/Oefeningen
src/DataView.java
780
// Bestudeer de code. Raadpleeg daar waar nodig is de API.
line_comment
nl
import ........ // Bestudeer de<SUF> // Beantwoord de vragen .. zie commentaar bij de code. public class DataView extends JPanel implements ............................................... { private Bal bal; private final int MINHOOGTE = 17; // minmale hoogte van dit view private int hoogte; // actuele hoogte van dit view private int x, y; private boolean dragged = false; private int dragX, dragY; public DataView (................) { // zet de achtergrondkleur van dit view op oranje // voeg verschillende MouseListeners toe aan dit view Border titelrand = // view met een rand en titel "bal-data" // zie (bv in de API) de klasse BorderFactory en // de methode createTitledBorder this.setBorder (titelrand); setBounds (0, 0, 180, hoogte); // wat doet dit statement? } public void paintComponent (Graphics g) { super.paintComponent(g); if ((x != 0) && (y != 0)) setLocation (x, y); String st_t = String.format ("%.2f", bal.getT() / 1000.0); // wat doet dit statement precies? // waarom wordt er door 1000.0 gedeeld? String st_y = // idem, maar nu met de actuele, afgelegde afstand van de bal String st_vy = // idem, maar nu met de actuele snelheid van de bal // zet de schrijfkleur op blauw // druk tijd (in sec), afgelegde weg (in meter) en snelheid (in meter/sec) netjes // onder elkaar af in deze view } // MouseWheelListener-method public void mouseWheelMoved (MouseWheelEvent ev) { int ticks = ev.getWheelRotation(); // pas de hoogte van deze view aan mbv de waarde 'ticks' // De minmale hoogte moet MINHOOGTE zijn } // MouseListener-methods public void mouseClicked (MouseEvent me) {} public void mouseEntered (MouseEvent me) {} public void mouseExited (MouseEvent me) {} // waarom staan deze methoden hier? // als ze niets doen dan kan je ze toch beter gewoon weglaten? public void mouseReleased (MouseEvent me) { .... // zie ook mouseDragged } public void mousePressed (MouseEvent me) // wat moet deze methode hier? {} // MouseMotionListener-methods public void mouseDragged (MouseEvent me) { // zie aan de hand van het Vierkanten-voorbeeld // hoe je de view kan verplaatsen (tweede werkcollege, week 1) // maak gebruik van de eigenschappen 'dragX', 'dragY' en 'dragged' } public void mouseMoved (MouseEvent me) // wat moet deze methode hier? {} }
78594_4
package cloudapplications.citycheck.Activities; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.media.MediaPlayer; import android.os.Bundle; import android.os.CountDownTimer; import android.provider.Settings; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import java.util.ArrayList; import java.util.List; import java.util.Objects; import cloudapplications.citycheck.APIService.NetworkManager; import cloudapplications.citycheck.APIService.NetworkResponseListener; import cloudapplications.citycheck.Goals; import cloudapplications.citycheck.IntersectCalculator; import cloudapplications.citycheck.Models.Antwoord; import cloudapplications.citycheck.Models.GameDoel; import cloudapplications.citycheck.Models.Locatie; import cloudapplications.citycheck.Models.StringReturn; import cloudapplications.citycheck.Models.Team; import cloudapplications.citycheck.Models.Vraag; import cloudapplications.citycheck.MyTeam; import cloudapplications.citycheck.OtherTeams; import cloudapplications.citycheck.R; public class GameActivity extends FragmentActivity implements OnMapReadyCallback { // Kaart vars private GoogleMap kaart; private MyTeam myTeam; private OtherTeams otherTeams; private Goals goals; private NetworkManager service; private IntersectCalculator calc; private FloatingActionButton myLocation; // Variabelen om teams private TextView teamNameTextView; private TextView scoreTextView; private String teamNaam; private int gamecode; private int score; // Vragen beantwoorden private String[] antwoorden; private String vraag; private int correctAntwoordIndex; private int gekozenAntwoordIndex; private boolean isClaiming; // Timer vars private TextView timerTextView; private ProgressBar timerProgressBar; private int progress; //screen time out private int defTimeOut=0; // Afstand private float[] afstandResult; private float treshHoldAfstand = 50; //(meter) // Geluiden private MediaPlayer mpTrace; private MediaPlayer mpClaimed; private MediaPlayer mpBonusCorrect; private MediaPlayer mpBonusWrong; private MediaPlayer mpGameStarted; // Callbacks @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); Objects.requireNonNull(mapFragment).getMapAsync(this); calc = new IntersectCalculator(); service = NetworkManager.getInstance(); gamecode = Integer.parseInt(Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras()).getString("gameCode"))); // AfstandTreshold treshHoldAfstand = 15; //(meter) // Claiming naar false isClaiming = false; //myLocation myLocation = findViewById(R.id.myLoc); //txt views teamNameTextView = findViewById(R.id.text_view_team_name); timerTextView = findViewById(R.id.text_view_timer); timerProgressBar = findViewById(R.id.progress_bar_timer); teamNaam = getIntent().getExtras().getString("teamNaam"); teamNameTextView.setText(teamNaam); gameTimer(); // Een vraag stellen als ik op de naam klik (Dit is tijdelijk om een vraag toch te kunnen tonen) teamNameTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { claimLocatie(1, 1); } }); myLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(myTeam.newLocation != null){ LatLng positie = new LatLng(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude()); kaart.moveCamera(CameraUpdateFactory.newLatLng(positie)); } } }); // Score scoreTextView = findViewById(R.id.text_view_points); score = 0; setScore(30); // Geluiden mpTrace = MediaPlayer.create(this, R.raw.trace_crossed); mpClaimed = MediaPlayer.create(this, R.raw.claimed); mpBonusCorrect = MediaPlayer.create(this, R.raw.bonus_correct); mpBonusWrong = MediaPlayer.create(this, R.raw.bonus_wrong); mpGameStarted = MediaPlayer.create(this, R.raw.game_started); mpGameStarted.start(); ImageView pointsImageView = findViewById(R.id.image_view_points); pointsImageView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { endGame(); return false; } }); } @Override protected void onResume() { super.onResume(); if (myTeam != null) myTeam.StartConnection(); } @Override public void onMapReady(GoogleMap googleMap) { kaart = googleMap; kaart.getUiSettings().setMapToolbarEnabled(false); // Alles ivm locatie van het eigen team myTeam = new MyTeam(this, kaart, gamecode, teamNaam); myTeam.StartConnection(); // Move the camera to Antwerp LatLng Antwerpen = new LatLng(51.2194, 4.4025); kaart.moveCamera(CameraUpdateFactory.newLatLngZoom(Antwerpen, 15)); // Locaties van andere teams otherTeams = new OtherTeams(gamecode, teamNaam, kaart, GameActivity.this); otherTeams.GetTeamsOnMap(); // Alles ivm doellocaties goals = new Goals(gamecode, kaart, GameActivity.this); } @Override public void onBackPressed() { } // Private helper methoden /* private void showDoelLocaties(List<DoelLocation> newDoelLocaties) { // Place a marker on the locations for (int i = 0; i < newDoelLocaties.size(); i++) { DoelLocation doellocatie = newDoelLocaties.get(i); LatLng Locatie = new LatLng(doellocatie.getLocatie().getLat(), doellocatie.getLocatie().getLong()); kaart.addMarker(new MarkerOptions().position(Locatie).title("Naam locatie").snippet("500").icon(BitmapDescriptorFactory.fromResource(R.drawable.coin_small))); } } */ private void everythingThatNeedsToHappenEvery3s(long verstrekentijd) { int tijd = (int) (verstrekentijd / 1000); if (tijd % 3 == 0) { goals.RemoveCaimedLocations(); if (myTeam.newLocation != null) { myTeam.HandleNewLocation(new Locatie(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude()), tijd); calculateIntersect(); } otherTeams.GetTeamsOnMap(); } // Controleren op doellocatie triggers om te kunnen claimen // Huidige locaties van de doelen ophalen if (goals.currentGoals != null && myTeam.Traces.size() > 0 && !isClaiming) { Locatie loc1 = goals.currentGoals.get(0).getDoel().getLocatie(); Locatie loc2 = goals.currentGoals.get(1).getDoel().getLocatie(); Locatie loc3 = goals.currentGoals.get(2).getDoel().getLocatie(); Locatie[] locs = {loc1, loc2, loc3}; // Mijn huidige locatie ophalen int tempTraceSize = myTeam.Traces.size(); double tempLat = myTeam.Traces.get(tempTraceSize - 1).getLat(); double tempLong = myTeam.Traces.get(tempTraceSize - 1).getLong(); // Kijken of er een hit is met een locatie int tempIndex = 0; for (Locatie loc : locs) { berekenAfstand(loc, tempLat, tempLong, goals.currentGoals.get(tempIndex)); tempIndex++; } } } private void berekenAfstand(Locatie doelLoc, double tempLat, double tempLong, GameDoel goal) { afstandResult = new float[1]; Location.distanceBetween(doelLoc.getLat(), doelLoc.getLong(), tempLat, tempLong, afstandResult); if (afstandResult[0] < treshHoldAfstand && !goal.getClaimed()) { // GameDoelID en doellocID ophalen int GD = goal.getId(); int LC = goal.getDoel().getId(); // Locatie claim triggeren claimLocatie(GD, LC); goal.setClaimed(true); // Claimen instellen zolang we bezig zijn met claimen isClaiming = true; //Claim medelen via toast Toast.makeText(GameActivity.this, "Locatie Geclaimed: " + goal.getDoel().getTitel(), Toast.LENGTH_LONG).show(); } } private void setMultiChoice(final String[] antwoorden, int CorrectIndex, String vraag) { // Alertdialog aanmaken AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this); // Single choice dialog met de antwoorden builder.setSingleChoiceItems(antwoorden, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // Notify the current action Toast.makeText(GameActivity.this, "Antwoord: " + antwoorden[i], Toast.LENGTH_LONG).show(); gekozenAntwoordIndex = i; } }); // Specify the dialog is not cancelable builder.setCancelable(true); // Set a title for alert dialog builder.setTitle(vraag); // Set the positive/yes button click listener builder.setPositiveButton("Kies!", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do something when click positive button // Toast.makeText(GameActivity.this, "data: "+gekozenAntwoordIndex, Toast.LENGTH_LONG).show(); // Antwoord controleren checkAnswer(gekozenAntwoordIndex, correctAntwoordIndex); } }); AlertDialog dialog = builder.create(); // Display the alert dialog on interface dialog.show(); } private void checkAnswer(int gekozenInd, int correctInd) { // Klopt de gekozen index met het correcte antwoord index if (gekozenInd == correctInd) { mpBonusCorrect.start(); Toast.makeText(GameActivity.this, "Correct!", Toast.LENGTH_LONG).show(); // X aantal punten toevoegen bij de gebruiker // Nieuwe score tonen en doorpushen naar de db setScore(20); isClaiming = false; } else { mpBonusWrong.start(); Toast.makeText(GameActivity.this, "Helaas!", Toast.LENGTH_LONG).show(); setScore(5); isClaiming = false; } } private void setScore(int newScore) { score += newScore; scoreTextView.setText(String.valueOf(score)); service.setTeamScore(gamecode, teamNaam, score, new NetworkResponseListener<Integer>() { @Override public void onResponseReceived(Integer score) { // Score ok } @Override public void onError() { Toast.makeText(GameActivity.this, "Error while trying to set the new score", Toast.LENGTH_SHORT).show(); } }); } private void claimLocatie(final int locId, final int doellocID) { mpClaimed.start(); // locid => gamelocaties ID, doellocID => id van de daadwerkelijke doellocatie // Een team een locatie laten claimen als ze op deze plek zijn. service.claimDoelLocatie(gamecode, locId, new NetworkResponseListener<StringReturn>() { @Override public void onResponseReceived(StringReturn rtrn) { //response verwerken try { String waarde = rtrn.getWaarde(); Toast.makeText(GameActivity.this, waarde, Toast.LENGTH_SHORT).show(); } catch (Throwable err) { Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show(); } } @Override public void onError() { Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show(); } }); // Dialog tonen met de vraag claim of bonus vraag AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Claimen of bonus vraag(risico) oplossen?") // Niet cancel-baar .setCancelable(false) .setPositiveButton("Claim", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mpBonusCorrect.start(); // De location alleen claimen zonder bonusvraag setScore(10); isClaiming = false; } }) .setNegativeButton("Bonus vraag", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Random vraag bij deze locatie ophalen uit de backend service.getDoelLocatieVraag(doellocID, new NetworkResponseListener<Vraag>() { @Override public void onResponseReceived(Vraag newVraag) { // Response verwerken // Vraagtitel bewaren vraag = newVraag.getVraagZin(); //3 Antwoorden bewaren ArrayList<Antwoord> allAnswers = newVraag.getAntwoorden(); antwoorden = new String[3]; for (int i = 0; i < 3; i++) { antwoorden[i] = allAnswers.get(i).getAntwoordzin(); if (allAnswers.get(i).isCorrectBool()) { correctAntwoordIndex = i; } } //Vraag stellen askQuestion(); } @Override public void onError() { Toast.makeText(GameActivity.this, "Error while trying to get the question", Toast.LENGTH_SHORT).show(); } }); } }); AlertDialog alert = builder.create(); alert.show(); } private void askQuestion() { // Instellen van een vraag en deze stellen + controleren // Vraag tonen setMultiChoice(antwoorden, correctAntwoordIndex, vraag); } private void gameTimer() { String chosenGameTime = Objects.requireNonNull(getIntent().getExtras()).getString("gameTime"); long millisStarted = Long.parseLong(Objects.requireNonNull(getIntent().getExtras().getString("millisStarted"))); int gameTimeInMillis = Integer.parseInt(Objects.requireNonNull(chosenGameTime)) * 3600000; // Het verschil tussen de tijd van nu en de tijd van wanneer de game is gestart long differenceFromMillisStarted = System.currentTimeMillis() - millisStarted; // Hoe lang dat de timer moet doorlopen long timerMillis = gameTimeInMillis - differenceFromMillisStarted; //screen time out try{ if(Settings.System.canWrite(this)){ defTimeOut = Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 0); android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, (int)timerMillis); } } catch (NoSuchMethodError err){ err.printStackTrace(); } // De progress begint op de juiste plek, dus niet altijd vanaf 0 progress = (int) ((gameTimeInMillis - timerMillis) / 1000); timerProgressBar.setProgress(progress); if (timerMillis > 0) { final int finalGameTimeInMillis = gameTimeInMillis; new CountDownTimer(timerMillis, 1000) { public void onTick(long millisUntilFinished) { int seconds = (int) (millisUntilFinished / 1000) % 60; int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60); int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24); timerTextView.setText("Time remaining: " + hours + ":" + minutes + ":" + seconds); everythingThatNeedsToHappenEvery3s(finalGameTimeInMillis - millisUntilFinished); getNewGoalsAfterInterval((finalGameTimeInMillis - millisUntilFinished), 900); progress++; timerProgressBar.setProgress(progress * 100 / (finalGameTimeInMillis / 1000)); } public void onFinish() { progress++; timerProgressBar.setProgress(100); endGame(); } }.start(); } else { endGame(); } } private void endGame() { try{ if(Settings.System.canWrite(this)) { Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut); } } catch (NoSuchMethodError err) { err.printStackTrace(); } Intent i = new Intent(GameActivity.this, EndGameActivity.class); if (myTeam != null) myTeam.StopConnection(); if (Objects.requireNonNull(getIntent().getExtras()).getBoolean("gameCreator")) i.putExtra("gameCreator", true); else i.putExtra("gameCreator", false); i.putExtra("gameCode", Integer.toString(gamecode)); startActivity(i); } private void calculateIntersect() { if (myTeam.Traces.size() > 2) { service.getAllTeamTraces(gamecode, new NetworkResponseListener<List<Team>>() { @Override public void onResponseReceived(List<Team> teams) { if(myTeam.Traces.size() > 2) { Locatie start = myTeam.Traces.get(myTeam.Traces.size() - 2); Locatie einde = myTeam.Traces.get(myTeam.Traces.size() - 1); for (Team team : teams) { if (!team.getTeamNaam().equals(teamNaam)) { Log.d("intersect", "size: " + team.getTeamTrace().size()); for (int i = 0; i < team.getTeamTrace().size(); i++) { if ((i + 1) < team.getTeamTrace().size()) { if (calc.doLineSegmentsIntersect(start, einde, team.getTeamTrace().get(i).getLocatie(), team.getTeamTrace().get(i + 1).getLocatie())) { mpTrace.start(); Log.d("intersect", team.getTeamNaam() + " kruist"); setScore(-5); Toast.makeText(GameActivity.this, "Oh oohw you crossed another team's path, bye bye 5 points", Toast.LENGTH_SHORT).show(); } } } } } } } @Override public void onError() { Toast.makeText(GameActivity.this, "Er ging iets mis bij het opvragen van de teamtraces", Toast.LENGTH_SHORT); } }); } } private void getNewGoalsAfterInterval(Long verstrekenTijd, int interval) { int tijd = (int) (verstrekenTijd / 1000); // interval meegeven in seconden goals.GetNewGoals(tijd, interval); //traces op map clearen bij elk interval if (tijd % interval == 0) { service.deleteTeamtraces(gamecode, new NetworkResponseListener<Boolean>() { @Override public void onResponseReceived(Boolean cleared) { Log.d("clearTraces", "cleared: " +cleared); myTeam.ClearTraces(); otherTeams.ClearTraces(); } @Override public void onError() { } }); } } }
AP-IT-GH/CA1819-CityCheck
src/CityCheckApp/app/src/main/java/cloudapplications/citycheck/Activities/GameActivity.java
5,094
// Een vraag stellen als ik op de naam klik (Dit is tijdelijk om een vraag toch te kunnen tonen)
line_comment
nl
package cloudapplications.citycheck.Activities; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.media.MediaPlayer; import android.os.Bundle; import android.os.CountDownTimer; import android.provider.Settings; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import java.util.ArrayList; import java.util.List; import java.util.Objects; import cloudapplications.citycheck.APIService.NetworkManager; import cloudapplications.citycheck.APIService.NetworkResponseListener; import cloudapplications.citycheck.Goals; import cloudapplications.citycheck.IntersectCalculator; import cloudapplications.citycheck.Models.Antwoord; import cloudapplications.citycheck.Models.GameDoel; import cloudapplications.citycheck.Models.Locatie; import cloudapplications.citycheck.Models.StringReturn; import cloudapplications.citycheck.Models.Team; import cloudapplications.citycheck.Models.Vraag; import cloudapplications.citycheck.MyTeam; import cloudapplications.citycheck.OtherTeams; import cloudapplications.citycheck.R; public class GameActivity extends FragmentActivity implements OnMapReadyCallback { // Kaart vars private GoogleMap kaart; private MyTeam myTeam; private OtherTeams otherTeams; private Goals goals; private NetworkManager service; private IntersectCalculator calc; private FloatingActionButton myLocation; // Variabelen om teams private TextView teamNameTextView; private TextView scoreTextView; private String teamNaam; private int gamecode; private int score; // Vragen beantwoorden private String[] antwoorden; private String vraag; private int correctAntwoordIndex; private int gekozenAntwoordIndex; private boolean isClaiming; // Timer vars private TextView timerTextView; private ProgressBar timerProgressBar; private int progress; //screen time out private int defTimeOut=0; // Afstand private float[] afstandResult; private float treshHoldAfstand = 50; //(meter) // Geluiden private MediaPlayer mpTrace; private MediaPlayer mpClaimed; private MediaPlayer mpBonusCorrect; private MediaPlayer mpBonusWrong; private MediaPlayer mpGameStarted; // Callbacks @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); Objects.requireNonNull(mapFragment).getMapAsync(this); calc = new IntersectCalculator(); service = NetworkManager.getInstance(); gamecode = Integer.parseInt(Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras()).getString("gameCode"))); // AfstandTreshold treshHoldAfstand = 15; //(meter) // Claiming naar false isClaiming = false; //myLocation myLocation = findViewById(R.id.myLoc); //txt views teamNameTextView = findViewById(R.id.text_view_team_name); timerTextView = findViewById(R.id.text_view_timer); timerProgressBar = findViewById(R.id.progress_bar_timer); teamNaam = getIntent().getExtras().getString("teamNaam"); teamNameTextView.setText(teamNaam); gameTimer(); // Een vraag<SUF> teamNameTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { claimLocatie(1, 1); } }); myLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(myTeam.newLocation != null){ LatLng positie = new LatLng(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude()); kaart.moveCamera(CameraUpdateFactory.newLatLng(positie)); } } }); // Score scoreTextView = findViewById(R.id.text_view_points); score = 0; setScore(30); // Geluiden mpTrace = MediaPlayer.create(this, R.raw.trace_crossed); mpClaimed = MediaPlayer.create(this, R.raw.claimed); mpBonusCorrect = MediaPlayer.create(this, R.raw.bonus_correct); mpBonusWrong = MediaPlayer.create(this, R.raw.bonus_wrong); mpGameStarted = MediaPlayer.create(this, R.raw.game_started); mpGameStarted.start(); ImageView pointsImageView = findViewById(R.id.image_view_points); pointsImageView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { endGame(); return false; } }); } @Override protected void onResume() { super.onResume(); if (myTeam != null) myTeam.StartConnection(); } @Override public void onMapReady(GoogleMap googleMap) { kaart = googleMap; kaart.getUiSettings().setMapToolbarEnabled(false); // Alles ivm locatie van het eigen team myTeam = new MyTeam(this, kaart, gamecode, teamNaam); myTeam.StartConnection(); // Move the camera to Antwerp LatLng Antwerpen = new LatLng(51.2194, 4.4025); kaart.moveCamera(CameraUpdateFactory.newLatLngZoom(Antwerpen, 15)); // Locaties van andere teams otherTeams = new OtherTeams(gamecode, teamNaam, kaart, GameActivity.this); otherTeams.GetTeamsOnMap(); // Alles ivm doellocaties goals = new Goals(gamecode, kaart, GameActivity.this); } @Override public void onBackPressed() { } // Private helper methoden /* private void showDoelLocaties(List<DoelLocation> newDoelLocaties) { // Place a marker on the locations for (int i = 0; i < newDoelLocaties.size(); i++) { DoelLocation doellocatie = newDoelLocaties.get(i); LatLng Locatie = new LatLng(doellocatie.getLocatie().getLat(), doellocatie.getLocatie().getLong()); kaart.addMarker(new MarkerOptions().position(Locatie).title("Naam locatie").snippet("500").icon(BitmapDescriptorFactory.fromResource(R.drawable.coin_small))); } } */ private void everythingThatNeedsToHappenEvery3s(long verstrekentijd) { int tijd = (int) (verstrekentijd / 1000); if (tijd % 3 == 0) { goals.RemoveCaimedLocations(); if (myTeam.newLocation != null) { myTeam.HandleNewLocation(new Locatie(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude()), tijd); calculateIntersect(); } otherTeams.GetTeamsOnMap(); } // Controleren op doellocatie triggers om te kunnen claimen // Huidige locaties van de doelen ophalen if (goals.currentGoals != null && myTeam.Traces.size() > 0 && !isClaiming) { Locatie loc1 = goals.currentGoals.get(0).getDoel().getLocatie(); Locatie loc2 = goals.currentGoals.get(1).getDoel().getLocatie(); Locatie loc3 = goals.currentGoals.get(2).getDoel().getLocatie(); Locatie[] locs = {loc1, loc2, loc3}; // Mijn huidige locatie ophalen int tempTraceSize = myTeam.Traces.size(); double tempLat = myTeam.Traces.get(tempTraceSize - 1).getLat(); double tempLong = myTeam.Traces.get(tempTraceSize - 1).getLong(); // Kijken of er een hit is met een locatie int tempIndex = 0; for (Locatie loc : locs) { berekenAfstand(loc, tempLat, tempLong, goals.currentGoals.get(tempIndex)); tempIndex++; } } } private void berekenAfstand(Locatie doelLoc, double tempLat, double tempLong, GameDoel goal) { afstandResult = new float[1]; Location.distanceBetween(doelLoc.getLat(), doelLoc.getLong(), tempLat, tempLong, afstandResult); if (afstandResult[0] < treshHoldAfstand && !goal.getClaimed()) { // GameDoelID en doellocID ophalen int GD = goal.getId(); int LC = goal.getDoel().getId(); // Locatie claim triggeren claimLocatie(GD, LC); goal.setClaimed(true); // Claimen instellen zolang we bezig zijn met claimen isClaiming = true; //Claim medelen via toast Toast.makeText(GameActivity.this, "Locatie Geclaimed: " + goal.getDoel().getTitel(), Toast.LENGTH_LONG).show(); } } private void setMultiChoice(final String[] antwoorden, int CorrectIndex, String vraag) { // Alertdialog aanmaken AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this); // Single choice dialog met de antwoorden builder.setSingleChoiceItems(antwoorden, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // Notify the current action Toast.makeText(GameActivity.this, "Antwoord: " + antwoorden[i], Toast.LENGTH_LONG).show(); gekozenAntwoordIndex = i; } }); // Specify the dialog is not cancelable builder.setCancelable(true); // Set a title for alert dialog builder.setTitle(vraag); // Set the positive/yes button click listener builder.setPositiveButton("Kies!", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do something when click positive button // Toast.makeText(GameActivity.this, "data: "+gekozenAntwoordIndex, Toast.LENGTH_LONG).show(); // Antwoord controleren checkAnswer(gekozenAntwoordIndex, correctAntwoordIndex); } }); AlertDialog dialog = builder.create(); // Display the alert dialog on interface dialog.show(); } private void checkAnswer(int gekozenInd, int correctInd) { // Klopt de gekozen index met het correcte antwoord index if (gekozenInd == correctInd) { mpBonusCorrect.start(); Toast.makeText(GameActivity.this, "Correct!", Toast.LENGTH_LONG).show(); // X aantal punten toevoegen bij de gebruiker // Nieuwe score tonen en doorpushen naar de db setScore(20); isClaiming = false; } else { mpBonusWrong.start(); Toast.makeText(GameActivity.this, "Helaas!", Toast.LENGTH_LONG).show(); setScore(5); isClaiming = false; } } private void setScore(int newScore) { score += newScore; scoreTextView.setText(String.valueOf(score)); service.setTeamScore(gamecode, teamNaam, score, new NetworkResponseListener<Integer>() { @Override public void onResponseReceived(Integer score) { // Score ok } @Override public void onError() { Toast.makeText(GameActivity.this, "Error while trying to set the new score", Toast.LENGTH_SHORT).show(); } }); } private void claimLocatie(final int locId, final int doellocID) { mpClaimed.start(); // locid => gamelocaties ID, doellocID => id van de daadwerkelijke doellocatie // Een team een locatie laten claimen als ze op deze plek zijn. service.claimDoelLocatie(gamecode, locId, new NetworkResponseListener<StringReturn>() { @Override public void onResponseReceived(StringReturn rtrn) { //response verwerken try { String waarde = rtrn.getWaarde(); Toast.makeText(GameActivity.this, waarde, Toast.LENGTH_SHORT).show(); } catch (Throwable err) { Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show(); } } @Override public void onError() { Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show(); } }); // Dialog tonen met de vraag claim of bonus vraag AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Claimen of bonus vraag(risico) oplossen?") // Niet cancel-baar .setCancelable(false) .setPositiveButton("Claim", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mpBonusCorrect.start(); // De location alleen claimen zonder bonusvraag setScore(10); isClaiming = false; } }) .setNegativeButton("Bonus vraag", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Random vraag bij deze locatie ophalen uit de backend service.getDoelLocatieVraag(doellocID, new NetworkResponseListener<Vraag>() { @Override public void onResponseReceived(Vraag newVraag) { // Response verwerken // Vraagtitel bewaren vraag = newVraag.getVraagZin(); //3 Antwoorden bewaren ArrayList<Antwoord> allAnswers = newVraag.getAntwoorden(); antwoorden = new String[3]; for (int i = 0; i < 3; i++) { antwoorden[i] = allAnswers.get(i).getAntwoordzin(); if (allAnswers.get(i).isCorrectBool()) { correctAntwoordIndex = i; } } //Vraag stellen askQuestion(); } @Override public void onError() { Toast.makeText(GameActivity.this, "Error while trying to get the question", Toast.LENGTH_SHORT).show(); } }); } }); AlertDialog alert = builder.create(); alert.show(); } private void askQuestion() { // Instellen van een vraag en deze stellen + controleren // Vraag tonen setMultiChoice(antwoorden, correctAntwoordIndex, vraag); } private void gameTimer() { String chosenGameTime = Objects.requireNonNull(getIntent().getExtras()).getString("gameTime"); long millisStarted = Long.parseLong(Objects.requireNonNull(getIntent().getExtras().getString("millisStarted"))); int gameTimeInMillis = Integer.parseInt(Objects.requireNonNull(chosenGameTime)) * 3600000; // Het verschil tussen de tijd van nu en de tijd van wanneer de game is gestart long differenceFromMillisStarted = System.currentTimeMillis() - millisStarted; // Hoe lang dat de timer moet doorlopen long timerMillis = gameTimeInMillis - differenceFromMillisStarted; //screen time out try{ if(Settings.System.canWrite(this)){ defTimeOut = Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 0); android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, (int)timerMillis); } } catch (NoSuchMethodError err){ err.printStackTrace(); } // De progress begint op de juiste plek, dus niet altijd vanaf 0 progress = (int) ((gameTimeInMillis - timerMillis) / 1000); timerProgressBar.setProgress(progress); if (timerMillis > 0) { final int finalGameTimeInMillis = gameTimeInMillis; new CountDownTimer(timerMillis, 1000) { public void onTick(long millisUntilFinished) { int seconds = (int) (millisUntilFinished / 1000) % 60; int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60); int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24); timerTextView.setText("Time remaining: " + hours + ":" + minutes + ":" + seconds); everythingThatNeedsToHappenEvery3s(finalGameTimeInMillis - millisUntilFinished); getNewGoalsAfterInterval((finalGameTimeInMillis - millisUntilFinished), 900); progress++; timerProgressBar.setProgress(progress * 100 / (finalGameTimeInMillis / 1000)); } public void onFinish() { progress++; timerProgressBar.setProgress(100); endGame(); } }.start(); } else { endGame(); } } private void endGame() { try{ if(Settings.System.canWrite(this)) { Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut); } } catch (NoSuchMethodError err) { err.printStackTrace(); } Intent i = new Intent(GameActivity.this, EndGameActivity.class); if (myTeam != null) myTeam.StopConnection(); if (Objects.requireNonNull(getIntent().getExtras()).getBoolean("gameCreator")) i.putExtra("gameCreator", true); else i.putExtra("gameCreator", false); i.putExtra("gameCode", Integer.toString(gamecode)); startActivity(i); } private void calculateIntersect() { if (myTeam.Traces.size() > 2) { service.getAllTeamTraces(gamecode, new NetworkResponseListener<List<Team>>() { @Override public void onResponseReceived(List<Team> teams) { if(myTeam.Traces.size() > 2) { Locatie start = myTeam.Traces.get(myTeam.Traces.size() - 2); Locatie einde = myTeam.Traces.get(myTeam.Traces.size() - 1); for (Team team : teams) { if (!team.getTeamNaam().equals(teamNaam)) { Log.d("intersect", "size: " + team.getTeamTrace().size()); for (int i = 0; i < team.getTeamTrace().size(); i++) { if ((i + 1) < team.getTeamTrace().size()) { if (calc.doLineSegmentsIntersect(start, einde, team.getTeamTrace().get(i).getLocatie(), team.getTeamTrace().get(i + 1).getLocatie())) { mpTrace.start(); Log.d("intersect", team.getTeamNaam() + " kruist"); setScore(-5); Toast.makeText(GameActivity.this, "Oh oohw you crossed another team's path, bye bye 5 points", Toast.LENGTH_SHORT).show(); } } } } } } } @Override public void onError() { Toast.makeText(GameActivity.this, "Er ging iets mis bij het opvragen van de teamtraces", Toast.LENGTH_SHORT); } }); } } private void getNewGoalsAfterInterval(Long verstrekenTijd, int interval) { int tijd = (int) (verstrekenTijd / 1000); // interval meegeven in seconden goals.GetNewGoals(tijd, interval); //traces op map clearen bij elk interval if (tijd % interval == 0) { service.deleteTeamtraces(gamecode, new NetworkResponseListener<Boolean>() { @Override public void onResponseReceived(Boolean cleared) { Log.d("clearTraces", "cleared: " +cleared); myTeam.ClearTraces(); otherTeams.ClearTraces(); } @Override public void onError() { } }); } } }
181129_12
/* * Copyright (c) 2024, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ package com.tangosol.util.asm; import com.oracle.coherence.common.base.Logger; import java.io.IOException; import java.io.InputStream; /** * Base class for internal wrappers of ASM's ClassReader. * * @param <RT> the ClassReader type * @param <CVT> the ClassVisitor type * * @since 15.1.1.0 */ public abstract class BaseClassReaderInternal<RT, CVT> { // ----- constructors --------------------------------------------------- /** * @see org.objectweb.asm.ClassReader#ClassReader(InputStream) */ public BaseClassReaderInternal(InputStream streamIn) throws IOException { this(streamIn.readAllBytes()); } /** * @see org.objectweb.asm.ClassReader#ClassReader(byte[]) */ public BaseClassReaderInternal(byte[] abBytes) { m_abBytes = abBytes; } // ----- abstract methods ----------------------------------------------- /** * Create the module-specific ClassReader. * * @param abBytes the class bytes * * @return the module-specific ClassReader */ protected abstract RT createReader(byte[] abBytes); /** * Perform the accept operation on the module-specific ClassReader * * @param classReader the module-specific ClassReader * @param classVisitor the module-specific ClassVisitor * @param nParsingOptions the parsing options */ protected abstract void accept(RT classReader, CVT classVisitor, int nParsingOptions); // ----- api methods ---------------------------------------------------- /** * Makes the given visitor visit the Java Virtual Machine's class file * structure passed to the constructor of this {@code ClassReader}. * * @param classVisitor the visitor that must visit this class * @param nParsingOptions the options to use to parse this class * * @see org.objectweb.asm.ClassReader#accept(org.objectweb.asm.ClassVisitor, int) */ @SuppressWarnings("DuplicatedCode") public void accept(CVT classVisitor, int nParsingOptions) { byte[] abBytes = m_abBytes; int nOriginalVersion = getMajorVersion(abBytes); boolean fRevertVersion = false; if (nOriginalVersion > MAX_MAJOR_VERSION) { // temporarily downgrade version to bypass check in ASM setMajorVersion(MAX_MAJOR_VERSION, abBytes); fRevertVersion = true; Logger.warn(() -> String.format("Unsupported class file major version " + nOriginalVersion)); } RT classReader = createReader(abBytes); if (fRevertVersion) { // set version back setMajorVersion(nOriginalVersion, abBytes); } accept(classReader, classVisitor, nParsingOptions); } // ----- helper methods ------------------------------------------------- /** * Sets the major version number in given class bytes. * * @param nMajorVersion major version of bytecode to set * @param abBytes class bytes * * @see #getMajorVersion(byte[]) */ protected static void setMajorVersion(final int nMajorVersion, final byte[] abBytes) { abBytes[6] = (byte) (nMajorVersion >>> 8); abBytes[7] = (byte) nMajorVersion; } /** * Gets major version number from the given class bytes. * * @param abBytes class bytes * * @return the major version of bytecode */ protected static int getMajorVersion(final byte[] abBytes) { return ((abBytes[6] & 0xFF) << 8) | (abBytes[7] & 0xFF); } // ----- constants ------------------------------------------------------ /** * The max major version supported by the shaded ASM. */ /* * Implementation Note: This doesn't reference the constant to avoid * strange issues with moditect */ private static final int MAX_MAJOR_VERSION = 66; // Opcodes.V22 // ----- data members --------------------------------------------------- /** * The class bytes. */ protected byte[] m_abBytes; }
oracle/coherence
prj/coherence-core/src/main/java/com/tangosol/util/asm/BaseClassReaderInternal.java
1,122
// ----- helper methods -------------------------------------------------
line_comment
nl
/* * Copyright (c) 2024, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ package com.tangosol.util.asm; import com.oracle.coherence.common.base.Logger; import java.io.IOException; import java.io.InputStream; /** * Base class for internal wrappers of ASM's ClassReader. * * @param <RT> the ClassReader type * @param <CVT> the ClassVisitor type * * @since 15.1.1.0 */ public abstract class BaseClassReaderInternal<RT, CVT> { // ----- constructors --------------------------------------------------- /** * @see org.objectweb.asm.ClassReader#ClassReader(InputStream) */ public BaseClassReaderInternal(InputStream streamIn) throws IOException { this(streamIn.readAllBytes()); } /** * @see org.objectweb.asm.ClassReader#ClassReader(byte[]) */ public BaseClassReaderInternal(byte[] abBytes) { m_abBytes = abBytes; } // ----- abstract methods ----------------------------------------------- /** * Create the module-specific ClassReader. * * @param abBytes the class bytes * * @return the module-specific ClassReader */ protected abstract RT createReader(byte[] abBytes); /** * Perform the accept operation on the module-specific ClassReader * * @param classReader the module-specific ClassReader * @param classVisitor the module-specific ClassVisitor * @param nParsingOptions the parsing options */ protected abstract void accept(RT classReader, CVT classVisitor, int nParsingOptions); // ----- api methods ---------------------------------------------------- /** * Makes the given visitor visit the Java Virtual Machine's class file * structure passed to the constructor of this {@code ClassReader}. * * @param classVisitor the visitor that must visit this class * @param nParsingOptions the options to use to parse this class * * @see org.objectweb.asm.ClassReader#accept(org.objectweb.asm.ClassVisitor, int) */ @SuppressWarnings("DuplicatedCode") public void accept(CVT classVisitor, int nParsingOptions) { byte[] abBytes = m_abBytes; int nOriginalVersion = getMajorVersion(abBytes); boolean fRevertVersion = false; if (nOriginalVersion > MAX_MAJOR_VERSION) { // temporarily downgrade version to bypass check in ASM setMajorVersion(MAX_MAJOR_VERSION, abBytes); fRevertVersion = true; Logger.warn(() -> String.format("Unsupported class file major version " + nOriginalVersion)); } RT classReader = createReader(abBytes); if (fRevertVersion) { // set version back setMajorVersion(nOriginalVersion, abBytes); } accept(classReader, classVisitor, nParsingOptions); } // ----- helper<SUF> /** * Sets the major version number in given class bytes. * * @param nMajorVersion major version of bytecode to set * @param abBytes class bytes * * @see #getMajorVersion(byte[]) */ protected static void setMajorVersion(final int nMajorVersion, final byte[] abBytes) { abBytes[6] = (byte) (nMajorVersion >>> 8); abBytes[7] = (byte) nMajorVersion; } /** * Gets major version number from the given class bytes. * * @param abBytes class bytes * * @return the major version of bytecode */ protected static int getMajorVersion(final byte[] abBytes) { return ((abBytes[6] & 0xFF) << 8) | (abBytes[7] & 0xFF); } // ----- constants ------------------------------------------------------ /** * The max major version supported by the shaded ASM. */ /* * Implementation Note: This doesn't reference the constant to avoid * strange issues with moditect */ private static final int MAX_MAJOR_VERSION = 66; // Opcodes.V22 // ----- data members --------------------------------------------------- /** * The class bytes. */ protected byte[] m_abBytes; }
40180_16
package de.kekru.struktogrammeditor.control; import java.awt.Color; import java.awt.Font; import java.io.File; import java.io.IOException; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import de.kekru.struktogrammeditor.struktogrammelemente.Fallauswahl; import de.kekru.struktogrammeditor.struktogrammelemente.Schleife; import de.kekru.struktogrammeditor.struktogrammelemente.StruktogrammElement; import de.kekru.struktogrammeditor.struktogrammelemente.StruktogrammElementListe; //XML erstellen: http://www.ibm.com/developerworks/java/library/j-jdom/ //XML auslesen: http://www.javabeginners.de/XML/XML-Datei_lesen.php public class XMLLeser { private Struktogramm struktogramm; public XMLLeser(){ } public void ladeXLM(String pfad, Struktogramm struktogramm){ ladeXML(pfad, null, struktogramm); } public void ladeXLM(Document document, Struktogramm struktogramm){ ladeXML(null, document, struktogramm); } //Rekursive Erstellung der StruktogrammElemente (Rekursiver Aufruf dieser Methode passiert dabei erst in listenelementeErstellen(...)) //http://www.jdom.org/docs/oracle/jdom-part1.pdf //http://www.jdom.org/docs/apidocs/org/jdom/Element.html private void erstelleElementeRek(Element elem, StruktogrammElement tmp){//elem ist der strelem-Tag zu tmp List<?> alleTextzeilen = (List<?>)elem.getChildren("text"); //alle text-Tags auslesen String[] textzeilen = new String[alleTextzeilen.size()]; // String s; for(int i=0; i < alleTextzeilen.size(); i++){ //eine Textzeile besteht aus Zahlen mit ";" getrennt, eine Zahl steht für das entsprechende Unicode-Zeichen textzeilen[i] = decodeS(((Element)alleTextzeilen.get(i)).getText());//Zahlen wieder in Zeichen umwandeln } tmp.setzeText(textzeilen); //alle Textzeilen im StruktogrammElement speichern if (tmp instanceof Schleife){ //wenn das StruktogrammElement eine Schleife ist, müssen ihre Unterelemente generiert werden listenelementeErstellen(elem.getChild("schleifeninhalt"),((Schleife)tmp).gibListe()); //Unterelemente sind im schleifeninhalt-Tag }else if(tmp instanceof Fallauswahl){ //Fallauswahl oder Verzweigung List<?> alleFaelle = (List<?>)elem.getChildren("fall"); Fallauswahl fallauswahl = ((Fallauswahl)tmp); fallauswahl.erstelleNeueListen(alleFaelle.size());//so viele Fall-Listen, wie fall-Tags vorhanden sind, werden erstellt for (int i=0; i < alleFaelle.size(); i++){ fallauswahl.gibListe(i).setzeBeschreibung(decodeS(((Element)alleFaelle.get(i)).getAttributeValue("fallname"))); //Beschreibung wird aus dem fall-Tag gelesen und in der Liste gesetzt listenelementeErstellen((Element)alleFaelle.get(i), fallauswahl.gibListe(i)); //die Liste i der Fallauswahl erhält den entsprechenden fall-Tag und erstellt ihre Unterelemente } } } /*erstellt aus einem Element ein StruktogrammElement mit Unterelementen und gibt es zurück, wird gebraucht für die Kopier-Funktion*/ private StruktogrammElementListe wurzelStruktogrammElementErstellen(Element elem){ StruktogrammElementListe liste = new StruktogrammElementListe(null); listenelementeErstellen(elem, liste); return liste; // Element wurzelElement = elem.getChildren("strelem"); // int typ = Integer.parseInt(wurzelElement.getAttributeValue("typ")); // StruktogrammElement neues = struktogramm.neuesStruktogrammElement(typ); // // setAttribute(neues,wurzelElement); // // erstelleElementeRek(wurzelElement,neues); // // return neues; } private void listenelementeErstellen(Element elem, StruktogrammElementListe liste){ List<?> alleUnterelemente = (List<?>)elem.getChildren("strelem"); //alle strelem-Tags ermitteln int typ; Element tmp; for(int i=0; i < alleUnterelemente.size(); i++){ tmp = (Element)alleUnterelemente.get(i); typ = Integer.parseInt(tmp.getAttributeValue("typ")); StruktogrammElement neues = struktogramm.neuesStruktogrammElement(typ); //neues StruktogrammElement anhand des gespeicherten Typs erzeugen... setAttribute(neues,tmp); liste.hinzufuegen(neues); //...und der übergebenen Liste anhängen erstelleElementeRek((Element)alleUnterelemente.get(i),neues); //Text und Unterelemente des StruktogrammElementes setzen, entsprechender strelem-Tag wird übergeben } } private void setAttribute(StruktogrammElement struktogrammelement, Element zugehoerigesKopfelement){ String s = zugehoerigesKopfelement.getAttributeValue("zx"); if(s != null){ struktogrammelement.setXVergroesserung(Integer.parseInt(s)); } s = zugehoerigesKopfelement.getAttributeValue("zy"); if(s != null){ struktogrammelement.setYVergroesserung(Integer.parseInt(s)); } s = zugehoerigesKopfelement.getAttributeValue("textcolor"); if(s != null){ struktogrammelement.setFarbeSchrift(Color.decode(s)); } s = zugehoerigesKopfelement.getAttributeValue("bgcolor"); if(s != null){ struktogrammelement.setFarbeHintergrund(Color.decode(s)); } } private void ladeXML(String pfad, Document document, Struktogramm struktogramm){ Document doc = null; try{//http://www.javabeginners.de/XML/XML-Datei_lesen.php if (document != null){ doc = document; }else{ //Das Document erstellen, aus einer Datei SAXBuilder builder = new SAXBuilder(); doc = builder.build(new File(pfad)); } Element element = doc.getRootElement(); //WurzelElement ermitteln this.struktogramm = struktogramm; //Schriftart für dieses Struktgramm einlesen String fontFamily, fontSize, fontStyle; fontFamily = element.getAttributeValue("fontfamily"); fontSize = element.getAttributeValue("fontsize"); fontStyle = element.getAttributeValue("fontstyle"); String struktogrammBeschreibung = element.getAttributeValue("caption"); if(fontFamily != null && fontSize != null && fontStyle != null){ struktogramm.setFontStr(new Font(decodeS(fontFamily),Integer.parseInt(fontStyle),Integer.parseInt(fontSize))); } if(struktogrammBeschreibung != null){ struktogramm.setStruktogrammBeschreibung(decodeS(struktogrammBeschreibung)); } struktogramm.gibListe().alleEntfernen(); //Liste des Struktogramms leeren listenelementeErstellen(element,struktogramm.gibListe()); //Struktogramm mit neuen Elementen füllen, Ausgangspunkt ist das Wurzelelement der XML-Datei if(struktogramm.gibGraphics() != null){ struktogramm.zeichenbereichAktualisieren(); struktogramm.zeichne(); } }catch(JDOMException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } } //Für Kopier-Funktion: erstellt aus dem Document ein StruktogrammElement mit Unterelementen public StruktogrammElementListe erstelleStruktogrammElementListe(Document document, Struktogramm struktogramm){ if(document != null){ this.struktogramm = struktogramm; //StruktogrammElement neues = return wurzelStruktogrammElementErstellen(document.getRootElement()); // if(struktogramm.gibGraphics() != null){ // struktogramm.zeichenbereichAktualisieren(); // struktogramm.zeichne(); // } // // return neues; }else{ return null; } } //wandelt die Zeichen eines Strings in entsprechende Unicode-Zahlen um, mit ";" getrennt, weil es beim Laden von XML-Dateien mit Sonderzeichen und Umlauten zu Problemen kommt public static String encodeS(String s){ String ausgabe = ""; if (s.equals("")){ ausgabe = "-1;"; //-1 markiert eine leere Zeile }else{ for (int i=0; i < s.length(); i++){ ausgabe += (int)s.charAt(i) +";"; } } return ausgabe; } //Zahlen wieder in Zeichen umwandeln private static String decodeS(String codiert){ String[] textzeileAlsZahlen = codiert.split(";"); //an allen ; splitten String s = ""; int zeichenNummer; for (int i=0; i < textzeileAlsZahlen.length; i++){ zeichenNummer = Integer.parseInt(textzeileAlsZahlen[i]);//einzelne Arrayeinträge beinhalten die Unicode-Zahlen if (zeichenNummer == -1){ s = ""; //zeichenNummer ist -1, also eine leere Zeile -> s wird zum leeren String }else{ s += (char)zeichenNummer;//Zahl wird zu Unicode-Zeichen umgewandelt } } return s; } }
kekru/struktogrammeditor
src/main/java/de/kekru/struktogrammeditor/control/XMLLeser.java
2,643
// int typ = Integer.parseInt(wurzelElement.getAttributeValue("typ"));
line_comment
nl
package de.kekru.struktogrammeditor.control; import java.awt.Color; import java.awt.Font; import java.io.File; import java.io.IOException; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import de.kekru.struktogrammeditor.struktogrammelemente.Fallauswahl; import de.kekru.struktogrammeditor.struktogrammelemente.Schleife; import de.kekru.struktogrammeditor.struktogrammelemente.StruktogrammElement; import de.kekru.struktogrammeditor.struktogrammelemente.StruktogrammElementListe; //XML erstellen: http://www.ibm.com/developerworks/java/library/j-jdom/ //XML auslesen: http://www.javabeginners.de/XML/XML-Datei_lesen.php public class XMLLeser { private Struktogramm struktogramm; public XMLLeser(){ } public void ladeXLM(String pfad, Struktogramm struktogramm){ ladeXML(pfad, null, struktogramm); } public void ladeXLM(Document document, Struktogramm struktogramm){ ladeXML(null, document, struktogramm); } //Rekursive Erstellung der StruktogrammElemente (Rekursiver Aufruf dieser Methode passiert dabei erst in listenelementeErstellen(...)) //http://www.jdom.org/docs/oracle/jdom-part1.pdf //http://www.jdom.org/docs/apidocs/org/jdom/Element.html private void erstelleElementeRek(Element elem, StruktogrammElement tmp){//elem ist der strelem-Tag zu tmp List<?> alleTextzeilen = (List<?>)elem.getChildren("text"); //alle text-Tags auslesen String[] textzeilen = new String[alleTextzeilen.size()]; // String s; for(int i=0; i < alleTextzeilen.size(); i++){ //eine Textzeile besteht aus Zahlen mit ";" getrennt, eine Zahl steht für das entsprechende Unicode-Zeichen textzeilen[i] = decodeS(((Element)alleTextzeilen.get(i)).getText());//Zahlen wieder in Zeichen umwandeln } tmp.setzeText(textzeilen); //alle Textzeilen im StruktogrammElement speichern if (tmp instanceof Schleife){ //wenn das StruktogrammElement eine Schleife ist, müssen ihre Unterelemente generiert werden listenelementeErstellen(elem.getChild("schleifeninhalt"),((Schleife)tmp).gibListe()); //Unterelemente sind im schleifeninhalt-Tag }else if(tmp instanceof Fallauswahl){ //Fallauswahl oder Verzweigung List<?> alleFaelle = (List<?>)elem.getChildren("fall"); Fallauswahl fallauswahl = ((Fallauswahl)tmp); fallauswahl.erstelleNeueListen(alleFaelle.size());//so viele Fall-Listen, wie fall-Tags vorhanden sind, werden erstellt for (int i=0; i < alleFaelle.size(); i++){ fallauswahl.gibListe(i).setzeBeschreibung(decodeS(((Element)alleFaelle.get(i)).getAttributeValue("fallname"))); //Beschreibung wird aus dem fall-Tag gelesen und in der Liste gesetzt listenelementeErstellen((Element)alleFaelle.get(i), fallauswahl.gibListe(i)); //die Liste i der Fallauswahl erhält den entsprechenden fall-Tag und erstellt ihre Unterelemente } } } /*erstellt aus einem Element ein StruktogrammElement mit Unterelementen und gibt es zurück, wird gebraucht für die Kopier-Funktion*/ private StruktogrammElementListe wurzelStruktogrammElementErstellen(Element elem){ StruktogrammElementListe liste = new StruktogrammElementListe(null); listenelementeErstellen(elem, liste); return liste; // Element wurzelElement = elem.getChildren("strelem"); // int typ<SUF> // StruktogrammElement neues = struktogramm.neuesStruktogrammElement(typ); // // setAttribute(neues,wurzelElement); // // erstelleElementeRek(wurzelElement,neues); // // return neues; } private void listenelementeErstellen(Element elem, StruktogrammElementListe liste){ List<?> alleUnterelemente = (List<?>)elem.getChildren("strelem"); //alle strelem-Tags ermitteln int typ; Element tmp; for(int i=0; i < alleUnterelemente.size(); i++){ tmp = (Element)alleUnterelemente.get(i); typ = Integer.parseInt(tmp.getAttributeValue("typ")); StruktogrammElement neues = struktogramm.neuesStruktogrammElement(typ); //neues StruktogrammElement anhand des gespeicherten Typs erzeugen... setAttribute(neues,tmp); liste.hinzufuegen(neues); //...und der übergebenen Liste anhängen erstelleElementeRek((Element)alleUnterelemente.get(i),neues); //Text und Unterelemente des StruktogrammElementes setzen, entsprechender strelem-Tag wird übergeben } } private void setAttribute(StruktogrammElement struktogrammelement, Element zugehoerigesKopfelement){ String s = zugehoerigesKopfelement.getAttributeValue("zx"); if(s != null){ struktogrammelement.setXVergroesserung(Integer.parseInt(s)); } s = zugehoerigesKopfelement.getAttributeValue("zy"); if(s != null){ struktogrammelement.setYVergroesserung(Integer.parseInt(s)); } s = zugehoerigesKopfelement.getAttributeValue("textcolor"); if(s != null){ struktogrammelement.setFarbeSchrift(Color.decode(s)); } s = zugehoerigesKopfelement.getAttributeValue("bgcolor"); if(s != null){ struktogrammelement.setFarbeHintergrund(Color.decode(s)); } } private void ladeXML(String pfad, Document document, Struktogramm struktogramm){ Document doc = null; try{//http://www.javabeginners.de/XML/XML-Datei_lesen.php if (document != null){ doc = document; }else{ //Das Document erstellen, aus einer Datei SAXBuilder builder = new SAXBuilder(); doc = builder.build(new File(pfad)); } Element element = doc.getRootElement(); //WurzelElement ermitteln this.struktogramm = struktogramm; //Schriftart für dieses Struktgramm einlesen String fontFamily, fontSize, fontStyle; fontFamily = element.getAttributeValue("fontfamily"); fontSize = element.getAttributeValue("fontsize"); fontStyle = element.getAttributeValue("fontstyle"); String struktogrammBeschreibung = element.getAttributeValue("caption"); if(fontFamily != null && fontSize != null && fontStyle != null){ struktogramm.setFontStr(new Font(decodeS(fontFamily),Integer.parseInt(fontStyle),Integer.parseInt(fontSize))); } if(struktogrammBeschreibung != null){ struktogramm.setStruktogrammBeschreibung(decodeS(struktogrammBeschreibung)); } struktogramm.gibListe().alleEntfernen(); //Liste des Struktogramms leeren listenelementeErstellen(element,struktogramm.gibListe()); //Struktogramm mit neuen Elementen füllen, Ausgangspunkt ist das Wurzelelement der XML-Datei if(struktogramm.gibGraphics() != null){ struktogramm.zeichenbereichAktualisieren(); struktogramm.zeichne(); } }catch(JDOMException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } } //Für Kopier-Funktion: erstellt aus dem Document ein StruktogrammElement mit Unterelementen public StruktogrammElementListe erstelleStruktogrammElementListe(Document document, Struktogramm struktogramm){ if(document != null){ this.struktogramm = struktogramm; //StruktogrammElement neues = return wurzelStruktogrammElementErstellen(document.getRootElement()); // if(struktogramm.gibGraphics() != null){ // struktogramm.zeichenbereichAktualisieren(); // struktogramm.zeichne(); // } // // return neues; }else{ return null; } } //wandelt die Zeichen eines Strings in entsprechende Unicode-Zahlen um, mit ";" getrennt, weil es beim Laden von XML-Dateien mit Sonderzeichen und Umlauten zu Problemen kommt public static String encodeS(String s){ String ausgabe = ""; if (s.equals("")){ ausgabe = "-1;"; //-1 markiert eine leere Zeile }else{ for (int i=0; i < s.length(); i++){ ausgabe += (int)s.charAt(i) +";"; } } return ausgabe; } //Zahlen wieder in Zeichen umwandeln private static String decodeS(String codiert){ String[] textzeileAlsZahlen = codiert.split(";"); //an allen ; splitten String s = ""; int zeichenNummer; for (int i=0; i < textzeileAlsZahlen.length; i++){ zeichenNummer = Integer.parseInt(textzeileAlsZahlen[i]);//einzelne Arrayeinträge beinhalten die Unicode-Zahlen if (zeichenNummer == -1){ s = ""; //zeichenNummer ist -1, also eine leere Zeile -> s wird zum leeren String }else{ s += (char)zeichenNummer;//Zahl wird zu Unicode-Zeichen umgewandelt } } return s; } }
30177_4
package nl.hu.sd.inno.basicboot.shop.application; import nl.hu.sd.inno.basicboot.shop.data.DeliveryRepository; import nl.hu.sd.inno.basicboot.shop.data.ProductRepository; import nl.hu.sd.inno.basicboot.shop.domain.Delivery; import nl.hu.sd.inno.basicboot.shop.domain.Product; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; import java.util.Optional; //Tsja, wat voor Delivery is dit? Van onze winkel naar onze klant? Of vanuit onze leveranciers naar ons? // //Dit soort dingen zijn verwarrend in een nieuwe code-base, maar elk bedrijf bouwt vrij snel z'n eigen 'dialect' op. //Zou zouden we bijv. het woord Delivery voor leveringen aan ons kunnen gebruiken, maar Shipment voor een levering aan //een klant? Kan, en is arbitrair. Dit soort termen worden uiteindelijk het 'domein' waar we in week 6 & 7 verder op in //gaan. @Service @Transactional public class DeliveryService { private final DeliveryRepository deliveries; private final ProductRepository products; public DeliveryService(DeliveryRepository deliveries, ProductRepository products) { this.deliveries = deliveries; this.products = products; } public List<Delivery> getDeliveries() { return this.deliveries.findAll(); } public Optional<Delivery> getDeliveryById(Long id) { return this.deliveries.findById(id); } public Optional<Product> getProductById(Long id){ return this.products.findById(id); } public void processDelivery(Delivery newDelivery) { newDelivery.process(); this.deliveries.save(newDelivery); //this.products.save(newDelivery.getProduct()); Let op: dit staat er niet, zou dit nodig zijn? Waarom/wanneer wel/niet? } }
HU-Inno-SD/demos
basicboot/src/main/java/nl/hu/sd/inno/basicboot/shop/application/DeliveryService.java
471
//this.products.save(newDelivery.getProduct()); Let op: dit staat er niet, zou dit nodig zijn? Waarom/wanneer wel/niet?
line_comment
nl
package nl.hu.sd.inno.basicboot.shop.application; import nl.hu.sd.inno.basicboot.shop.data.DeliveryRepository; import nl.hu.sd.inno.basicboot.shop.data.ProductRepository; import nl.hu.sd.inno.basicboot.shop.domain.Delivery; import nl.hu.sd.inno.basicboot.shop.domain.Product; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; import java.util.Optional; //Tsja, wat voor Delivery is dit? Van onze winkel naar onze klant? Of vanuit onze leveranciers naar ons? // //Dit soort dingen zijn verwarrend in een nieuwe code-base, maar elk bedrijf bouwt vrij snel z'n eigen 'dialect' op. //Zou zouden we bijv. het woord Delivery voor leveringen aan ons kunnen gebruiken, maar Shipment voor een levering aan //een klant? Kan, en is arbitrair. Dit soort termen worden uiteindelijk het 'domein' waar we in week 6 & 7 verder op in //gaan. @Service @Transactional public class DeliveryService { private final DeliveryRepository deliveries; private final ProductRepository products; public DeliveryService(DeliveryRepository deliveries, ProductRepository products) { this.deliveries = deliveries; this.products = products; } public List<Delivery> getDeliveries() { return this.deliveries.findAll(); } public Optional<Delivery> getDeliveryById(Long id) { return this.deliveries.findById(id); } public Optional<Product> getProductById(Long id){ return this.products.findById(id); } public void processDelivery(Delivery newDelivery) { newDelivery.process(); this.deliveries.save(newDelivery); //this.products.save(newDelivery.getProduct()); Let<SUF> } }
19816_1
package TVH.Entities.Truck; import TVH.Entities.Machine.Machine; import TVH.Entities.Node.Location; import java.util.LinkedList; import java.util.Objects; /** * Elke Route bevat een lijst van Stops. Deze bepalen waar de truck passeert en wat hij doet op die locatie. */ public class Stop { private final Location location; private final LinkedList<Machine> collect; private final LinkedList<Machine> drop; private int timespend = 0; private int deltaFillRate = 0; //Hoeveelheid waarmee de fillrate van de truck verandert na deze stop public Stop(Location location) { this.location = location; this.collect = new LinkedList<>(); this.drop = new LinkedList<>(); } //Copy constructor public Stop(Stop s) { this.location = s.location; this.collect = new LinkedList<>(s.collect); this.drop = new LinkedList<>(s.drop); this.timespend = s.timespend; this.deltaFillRate = s.deltaFillRate; } /** * Merge 2 stops met elkaar * @param s Stop die in deze stop gemerged moet worden */ public void merge(Stop s){ collect.addAll(s.getCollect()); drop.addAll(s.getDrop()); timespend += s.getTimeSpend(); deltaFillRate += s.getDeltaFillRate(); } /** * Checkt als er iets gebeurt op deze stop * @return true als er niets wordt uitgevoerd */ public boolean isEmpty() { return collect.isEmpty() && drop.isEmpty(); } public void addToCollect(Machine m) { collect.add(m); timespend += m.getType().getServiceTime(); deltaFillRate += m.getType().getVolume(); } public void addToDrop(Machine m) { drop.add(m); timespend += m.getType().getServiceTime(); deltaFillRate -= m.getType().getVolume(); } public boolean removeFromCollect(Machine m) { if(collect.remove(m)) { timespend -= m.getType().getServiceTime(); deltaFillRate -= m.getType().getVolume(); return true; } return false; } public boolean removeFromDrop(Machine m) { if(drop.remove(m)) { timespend -= m.getType().getServiceTime(); deltaFillRate += m.getType().getVolume(); return true; } return false; } public int getTimeSpend() { return timespend; } public int getDeltaFillRate(){ return deltaFillRate; } public Location getLocation() { return location; } public LinkedList<Machine> getCollect() { return collect; } public LinkedList<Machine> getDrop() { return drop; } public String toString() { return location.toString(); } }
aaronhallaert/OPT_ProjectTVH
src/TVH/Entities/Truck/Stop.java
731
//Hoeveelheid waarmee de fillrate van de truck verandert na deze stop
line_comment
nl
package TVH.Entities.Truck; import TVH.Entities.Machine.Machine; import TVH.Entities.Node.Location; import java.util.LinkedList; import java.util.Objects; /** * Elke Route bevat een lijst van Stops. Deze bepalen waar de truck passeert en wat hij doet op die locatie. */ public class Stop { private final Location location; private final LinkedList<Machine> collect; private final LinkedList<Machine> drop; private int timespend = 0; private int deltaFillRate = 0; //Hoeveelheid waarmee<SUF> public Stop(Location location) { this.location = location; this.collect = new LinkedList<>(); this.drop = new LinkedList<>(); } //Copy constructor public Stop(Stop s) { this.location = s.location; this.collect = new LinkedList<>(s.collect); this.drop = new LinkedList<>(s.drop); this.timespend = s.timespend; this.deltaFillRate = s.deltaFillRate; } /** * Merge 2 stops met elkaar * @param s Stop die in deze stop gemerged moet worden */ public void merge(Stop s){ collect.addAll(s.getCollect()); drop.addAll(s.getDrop()); timespend += s.getTimeSpend(); deltaFillRate += s.getDeltaFillRate(); } /** * Checkt als er iets gebeurt op deze stop * @return true als er niets wordt uitgevoerd */ public boolean isEmpty() { return collect.isEmpty() && drop.isEmpty(); } public void addToCollect(Machine m) { collect.add(m); timespend += m.getType().getServiceTime(); deltaFillRate += m.getType().getVolume(); } public void addToDrop(Machine m) { drop.add(m); timespend += m.getType().getServiceTime(); deltaFillRate -= m.getType().getVolume(); } public boolean removeFromCollect(Machine m) { if(collect.remove(m)) { timespend -= m.getType().getServiceTime(); deltaFillRate -= m.getType().getVolume(); return true; } return false; } public boolean removeFromDrop(Machine m) { if(drop.remove(m)) { timespend -= m.getType().getServiceTime(); deltaFillRate += m.getType().getVolume(); return true; } return false; } public int getTimeSpend() { return timespend; } public int getDeltaFillRate(){ return deltaFillRate; } public Location getLocation() { return location; } public LinkedList<Machine> getCollect() { return collect; } public LinkedList<Machine> getDrop() { return drop; } public String toString() { return location.toString(); } }
162424_0
/* * Copyright 2021 De Staat der Nederlanden, Ministerie van Volksgezondheid, Welzijn en Sport. * Licensed under the EUROPEAN UNION PUBLIC LICENCE v. 1.2 * SPDX-License-Identifier: EUPL-1.2 */ package nl.minvws.encoding; import java.nio.charset.StandardCharsets; import java.util.Arrays; public class Base45 { private static final int BaseSize = 45; private static final int ChunkSize = 2; private static final int EncodedChunkSize = 3; private static final int SmallEncodedChunkSize = 2; private static final int ByteSize = 256; private Base45() { } /** * Returns a {@link Encoder} that encodes using the type Base45 encoding scheme. * @return A Base45 encoder. */ public static Encoder getEncoder() { return Encoder.ENCODER; } /** * Returns a {@link Decoder} that decodes using the type Base45 encoding scheme. * @return A Base45 decoder. */ public static Decoder getDecoder() { return Decoder.DECODER; } /** * This class implements an encoder for encoding byte data using the Base45 encoding scheme * Instances of {@link Encoder} class are safe for use by multiple concurrent threads. */ public static class Encoder { /** * This array is a lookup table that translates integer * index values into their "Base45 Alphabet" equivalents as specified. */ private static final byte[] toBase45 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' }; static final Encoder ENCODER = new Encoder(); /** * Encodes all bytes from the specified byte array into a newly-allocated * byte array using the {@link Base45} encoding scheme. The returned byte * array is of the length of the resulting bytes. * * @param src the byte array to encode * @return A newly-allocated byte array containing the resulting encoded bytes. */ public byte[] encode(byte[] src) { int wholeChunkCount = src.length / ChunkSize; byte[] result = new byte[wholeChunkCount * EncodedChunkSize + (src.length % ChunkSize == 1 ? SmallEncodedChunkSize : 0)]; int resultIndex = 0; int wholeChunkLength = wholeChunkCount * ChunkSize; for (int i = 0; i < wholeChunkLength;) { int value = (src[i++] & 0xff) * ByteSize + (src[i++] & 0xff); result[resultIndex++] = toBase45[value % BaseSize]; result[resultIndex++] = toBase45[(value / BaseSize) % BaseSize]; result[resultIndex++] = toBase45[(value / (BaseSize * BaseSize)) % BaseSize]; } if (src.length % ChunkSize != 0) { result[result.length - 2] = toBase45[(src[src.length - 1] & 0xff) % BaseSize]; result[result.length - 1] = (src[src.length - 1] & 0xff) < BaseSize ? toBase45[0] : toBase45[(src[src.length - 1] & 0xff) / BaseSize % BaseSize]; } return result; } /** * Encodes the specified byte array into a String using the {@link Base45} encoding scheme. * * An invocation of this method has exactly the same * effect as invoking {@code new String(encode(src), StandardCharsets.ISO_8859_1)}. * Even though it's deprecated it's added to be similar to Base64 in java. * * @param src the byte array to encode * @return A String containing the resulting Base45 encoded characters */ @SuppressWarnings("deprecation") public String encodeToString(byte[] src) { byte[] encoded = encode(src); return new String(encoded, 0, 0, encoded.length); } } /** * This class implements a decoder for decoding byte data using the * Base45 encoding scheme * * <p> Instances of {@link Decoder} class are safe for use by * multiple concurrent threads. */ public static class Decoder { private Decoder() { } /** * Lookup table for decoding unicode characters drawn from the * "Base45 Alphabet". */ private static final int[] fromBase45 = new int[256]; static { Arrays.fill(fromBase45, -1); for (int i = 0; i < Encoder.toBase45.length; i++) { fromBase45[Encoder.toBase45[i]] = i; } } static final Decoder DECODER = new Decoder(); /** * Decodes all bytes from the input byte array using the {@link Base45} * encoding scheme, writing the results into a newly-allocated output * byte array. The returned byte array is of the length of the resulting * bytes. * * @param src the byte array to decode * @return A newly-allocated byte array containing the decoded bytes. * @throws IllegalArgumentException if {@code src} is not in valid Base45 scheme */ public byte[] decode(byte[] src) { int remainderSize = src.length % EncodedChunkSize; int[] buffer = new int[src.length]; for (int i = 0; i < src.length; ++i) { buffer[i] = fromBase45[Byte.toUnsignedInt(src[i])]; if (buffer[i] == -1) { throw new IllegalArgumentException(); } } int wholeChunkCount = buffer.length / EncodedChunkSize; byte[] result = new byte[wholeChunkCount * ChunkSize + (remainderSize == ChunkSize ? 1 : 0)]; int resultIndex = 0; int wholeChunkLength = wholeChunkCount * EncodedChunkSize; for (int i = 0; i < wholeChunkLength; ) { int val = buffer[i++] + BaseSize * buffer[i++] + BaseSize * BaseSize * buffer[i++]; if (val > 0xFFFF) { throw new IllegalArgumentException(); } result[resultIndex++] = (byte)(val / ByteSize); result[resultIndex++] = (byte)(val % ByteSize); } if (remainderSize != 0) { result[resultIndex] = (byte) (buffer[buffer.length - 2] + BaseSize * buffer[buffer.length - 1]); } return result; } public byte[] decode(String src) { return decode(src.getBytes(StandardCharsets.ISO_8859_1)); } } }
albertus82/acodec
src/main/java/nl/minvws/encoding/Base45.java
1,811
/* * Copyright 2021 De Staat der Nederlanden, Ministerie van Volksgezondheid, Welzijn en Sport. * Licensed under the EUROPEAN UNION PUBLIC LICENCE v. 1.2 * SPDX-License-Identifier: EUPL-1.2 */
block_comment
nl
/* * Copyright 2021 De<SUF>*/ package nl.minvws.encoding; import java.nio.charset.StandardCharsets; import java.util.Arrays; public class Base45 { private static final int BaseSize = 45; private static final int ChunkSize = 2; private static final int EncodedChunkSize = 3; private static final int SmallEncodedChunkSize = 2; private static final int ByteSize = 256; private Base45() { } /** * Returns a {@link Encoder} that encodes using the type Base45 encoding scheme. * @return A Base45 encoder. */ public static Encoder getEncoder() { return Encoder.ENCODER; } /** * Returns a {@link Decoder} that decodes using the type Base45 encoding scheme. * @return A Base45 decoder. */ public static Decoder getDecoder() { return Decoder.DECODER; } /** * This class implements an encoder for encoding byte data using the Base45 encoding scheme * Instances of {@link Encoder} class are safe for use by multiple concurrent threads. */ public static class Encoder { /** * This array is a lookup table that translates integer * index values into their "Base45 Alphabet" equivalents as specified. */ private static final byte[] toBase45 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' }; static final Encoder ENCODER = new Encoder(); /** * Encodes all bytes from the specified byte array into a newly-allocated * byte array using the {@link Base45} encoding scheme. The returned byte * array is of the length of the resulting bytes. * * @param src the byte array to encode * @return A newly-allocated byte array containing the resulting encoded bytes. */ public byte[] encode(byte[] src) { int wholeChunkCount = src.length / ChunkSize; byte[] result = new byte[wholeChunkCount * EncodedChunkSize + (src.length % ChunkSize == 1 ? SmallEncodedChunkSize : 0)]; int resultIndex = 0; int wholeChunkLength = wholeChunkCount * ChunkSize; for (int i = 0; i < wholeChunkLength;) { int value = (src[i++] & 0xff) * ByteSize + (src[i++] & 0xff); result[resultIndex++] = toBase45[value % BaseSize]; result[resultIndex++] = toBase45[(value / BaseSize) % BaseSize]; result[resultIndex++] = toBase45[(value / (BaseSize * BaseSize)) % BaseSize]; } if (src.length % ChunkSize != 0) { result[result.length - 2] = toBase45[(src[src.length - 1] & 0xff) % BaseSize]; result[result.length - 1] = (src[src.length - 1] & 0xff) < BaseSize ? toBase45[0] : toBase45[(src[src.length - 1] & 0xff) / BaseSize % BaseSize]; } return result; } /** * Encodes the specified byte array into a String using the {@link Base45} encoding scheme. * * An invocation of this method has exactly the same * effect as invoking {@code new String(encode(src), StandardCharsets.ISO_8859_1)}. * Even though it's deprecated it's added to be similar to Base64 in java. * * @param src the byte array to encode * @return A String containing the resulting Base45 encoded characters */ @SuppressWarnings("deprecation") public String encodeToString(byte[] src) { byte[] encoded = encode(src); return new String(encoded, 0, 0, encoded.length); } } /** * This class implements a decoder for decoding byte data using the * Base45 encoding scheme * * <p> Instances of {@link Decoder} class are safe for use by * multiple concurrent threads. */ public static class Decoder { private Decoder() { } /** * Lookup table for decoding unicode characters drawn from the * "Base45 Alphabet". */ private static final int[] fromBase45 = new int[256]; static { Arrays.fill(fromBase45, -1); for (int i = 0; i < Encoder.toBase45.length; i++) { fromBase45[Encoder.toBase45[i]] = i; } } static final Decoder DECODER = new Decoder(); /** * Decodes all bytes from the input byte array using the {@link Base45} * encoding scheme, writing the results into a newly-allocated output * byte array. The returned byte array is of the length of the resulting * bytes. * * @param src the byte array to decode * @return A newly-allocated byte array containing the decoded bytes. * @throws IllegalArgumentException if {@code src} is not in valid Base45 scheme */ public byte[] decode(byte[] src) { int remainderSize = src.length % EncodedChunkSize; int[] buffer = new int[src.length]; for (int i = 0; i < src.length; ++i) { buffer[i] = fromBase45[Byte.toUnsignedInt(src[i])]; if (buffer[i] == -1) { throw new IllegalArgumentException(); } } int wholeChunkCount = buffer.length / EncodedChunkSize; byte[] result = new byte[wholeChunkCount * ChunkSize + (remainderSize == ChunkSize ? 1 : 0)]; int resultIndex = 0; int wholeChunkLength = wholeChunkCount * EncodedChunkSize; for (int i = 0; i < wholeChunkLength; ) { int val = buffer[i++] + BaseSize * buffer[i++] + BaseSize * BaseSize * buffer[i++]; if (val > 0xFFFF) { throw new IllegalArgumentException(); } result[resultIndex++] = (byte)(val / ByteSize); result[resultIndex++] = (byte)(val % ByteSize); } if (remainderSize != 0) { result[resultIndex] = (byte) (buffer[buffer.length - 2] + BaseSize * buffer[buffer.length - 1]); } return result; } public byte[] decode(String src) { return decode(src.getBytes(StandardCharsets.ISO_8859_1)); } } }
114404_57
import java.sql.Array; import java.util.*; import java.time.LocalDate; import javax.persistence.Persistence; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; public class KantineSimulatie2 { // Create an EntityManagerFactory when you start the application. private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory("KantineSimulatie"); private EntityManager manager; // kantine private Kantine kantine; // kantineaanbod private KantineAanbod kantineAanbod; // random generator private Random random; // aantal artikelen private static final int AANTAL_ARTIKELEN = 4; // artikelen private static final String[] artikelnamen = new String[] { "Koffie", "Broodje pindakaas", "Broodje kaas", "Appelsap" }; // prijzen private static double[] artikelprijzen = new double[] { 1.50, 2.10, 1.65, 1.65 }; // minimum en maximum aantal artikelen per soort private static final int MIN_ARTIKELEN_PER_SOORT = 1; private static final int MAX_ARTIKELEN_PER_SOORT = 1; // minimum en maximum aantal personen per dag private static final int MIN_PERSONEN_PER_DAG = 5; private static final int MAX_PERSONEN_PER_DAG = 20; // minimum en maximum artikelen per persoon private static final int MIN_ARTIKELEN_PER_PERSOON = 2; private static final int MAX_ARTIKELEN_PER_PERSOON = 4; // totaalomzet private int[] gemiddeldeArtikelen; private double[] dagOmzet; /** * Constructor */ public KantineSimulatie2() { // Create the manager manager = ENTITY_MANAGER_FACTORY.createEntityManager(); // Maak een nieuwe kantine aan, de "hoofd" klasse. kantine = new Kantine(manager); // Zet een randomizer klaar. random = new Random(); // Bepaal het aantal hoeveelheden van elk aspect. // Gebruikt de nieuwe getRandomArray();. int[] hoeveelheden = getRandomArray(AANTAL_ARTIKELEN, MIN_ARTIKELEN_PER_SOORT, MAX_ARTIKELEN_PER_SOORT); // Maak een nieuw kantineaanbod aan. kantineAanbod = new KantineAanbod(artikelnamen, artikelprijzen, hoeveelheden); // Verwerk het kantineaanbod in de kantine. kantine.setKantineAanbod(kantineAanbod); } /** * Methode om een array van random getallen te genereren. De getallen liggen * tussen min en max (inclusief). * * @param lengte De gegeven lengte van de array. * @param min Minimale waarde die in de array mag. * @param max Maximale waarde die in de array mag. * @return De array met random getallen. */ private int[] getRandomArray(int lengte, int min, int max) { int[] temp = new int[lengte]; for (int i = 0; i < lengte; i++) { temp[i] = getRandomValue(min, max); } return temp; } /** * Methode om een random getal tussen min(incl) en max(incl) te genereren. * * @param min De minimumwaarde. * @param max De maximumwaarde. * @return Het random gegenereerde getal. */ private int getRandomValue(int min, int max) { // Omdat er misschien "0" klanten kunnen zijn, doen we +1. return random.nextInt(max - min + 1) + min; } /** * Methode om op basis van een gegeven array van indexen voor de array * artikelnamen de bijhorende array van artikelnamen te maken. * * @param indexen De array met gegeven indexen. * @return De array met artikelnamen. */ private String[] geefArtikelNamen(int[] indexen) { String[] artikelen = new String[indexen.length]; for (int i = 0; i < indexen.length; i++) { artikelen[i] = artikelnamen[indexen[i]]; } return artikelen; } /** * Deze methode simuleert een aantal dagen in het verloop van de kantine. * * @param dagen De hoeveelheid dagen die je wil simuleren. */ public void simuleer(int dagen) { // Zet de variabele voor administratie. gemiddeldeArtikelen = new int[dagen+1]; dagOmzet = new double[dagen+1]; // counters voor totaalstatistieken int totaalAantalStudenten = 0; int totaalAantalDocenten = 0; int totaalAantalKantineMedewerkers = 0; // een BSN die mee gegeven wordt met elk persoon. (9 cijfers) int bsn = 100000000; // Voor leerlingen: studentnummer int studentnummer = 10000; // For lus voor dagen. for (int i = 1; i < dagen + 1; i++) { System.out.println("-------------------------"); System.out.println("Dag: " + i); // Nieuwe aantallen en dagaanbiedingen // Bepaal het aantal hoeveelheden van elk aspect. // Gebruikt de nieuwe getRandomArray();. int[] hoeveelheden = getRandomArray(AANTAL_ARTIKELEN, MIN_ARTIKELEN_PER_SOORT, MAX_ARTIKELEN_PER_SOORT); // Maak een nieuw kantineaanbod aan. kantineAanbod = new KantineAanbod(artikelnamen, artikelprijzen, hoeveelheden); // Bedenk hoeveel personen vandaag binnen lopen. int aantalPersonen = getRandomValue(MIN_PERSONEN_PER_DAG, MAX_PERSONEN_PER_DAG); // maak wat counters voor statistieken : int aantalStudenten = 0; int aantalDocenten = 0; int aantalKantineMedewerkers = 0; // Laat de personen maar komen... for (int j = 0; j < aantalPersonen; j++) { // Nieuw persoon, nieuw BSN! bsn++; // Maak een geboortedatum // While loop to make sure we have a valid datum Boolean datumAangemaakt = false; // Maak een "fake" datum aan om een echte te kunnen checken. Datum datum = new Datum(); // while loop todat er een echte datum gevonden is while(datumAangemaakt == false) { // Max 31 dagen int randomdag = random.nextInt(31); // Max 12 maanden int randommaand = random.nextInt(12); // Min 10 jaar oud, max 60+10 int randomjaar = (2020-((random.nextInt(60))+10)); // Kijk of de 3 gegevens samen een echte datum maken if (datum.bestaatDatum(randomdag, randommaand, randomjaar)) { // datum bestaat, overwrite de fake datum! datum = new Datum(randomdag, randommaand, randomjaar); // exit loop! datumAangemaakt = true; } else { // datum bestaat niet. Try again datumAangemaakt = false; } } // Get random geslacht (1 op 2) int randomgetal = random.nextInt(2); char geslacht = 'O'; if (randomgetal == 1) { // 1 op 2: Man geslacht = 'M'; } else { // 1 op 2: Vrouw geslacht = 'V'; } // Bepaal wat voor klant dit is // maak een fake klant Persoon klantInWinkel = new Persoon(); // Overwrite random getal en maak een 1 - 100 randomgetal = random.nextInt(100); randomgetal++; // maak getal 1-100 i.p.v 0-99. String[] voornamen = { "Stefan", "Teun", "Stijn", "Romano", "Maurice", "Jan-Wiepke", "Henkie", "Jessica"}; String[] achternamen = { "de Jong","Hoogezand","Braxhoofden","Pater","Wolthuis","Highsand-Juicylake","Timmermans","Willemse","Jansen","Kramer","Kuppen","Jilderda"}; int randomVoornaam = random.nextInt(voornamen.length); int randomAchternaam = random.nextInt(achternamen.length); String voornaam = voornamen[randomVoornaam]; String achternaam = achternamen[randomAchternaam]; if (randomgetal == 100) { // 1 op 100: kantinemedewerker klantInWinkel = new KantineMedewerker(bsn, voornaam, achternaam, datum, geslacht); klantInWinkel.setKortingsKaartHouder(true); aantalKantineMedewerkers++; } else if(randomgetal <= 89) { // 89 op 100: Student studentnummer++; String studierichting = "ICT"; // TODO random afdeling klantInWinkel = new Student(bsn, voornaam, achternaam, datum, geslacht, studentnummer, studierichting); aantalStudenten++; } else if (randomgetal >= 90 && randomgetal < 100 ) { // 10 op 100: Docent String vierlettercode = "ABCD"; // TODO random vierlettercode String afdeling = "ICT"; // TODO random afdeling klantInWinkel = new Docent(bsn, voornaam, achternaam, datum, geslacht, vierlettercode, afdeling); klantInWinkel.setKortingsKaartHouder(true); aantalDocenten++; } // Get random geslacht (1 op 2) randomgetal = random.nextInt(2); if (randomgetal == 1) { // 1 op 2: Contant Contant betaalwijze; klantInWinkel.setBetaalwijze(betaalwijze = new Contant()); betaalwijze.setSaldo(7.50); } else { // 1 op 2: Pinpas Pinpas betaalwijze; klantInWinkel.setBetaalwijze(betaalwijze = new Pinpas()); betaalwijze.setKredietLimiet(7.0); betaalwijze.setSaldo(7.50); } // Maak persoon en dienblad aan, koppel ze aan elkaar. Dienblad dienbladVanKlant = new Dienblad(klantInWinkel); dienbladVanKlant.setKlant(klantInWinkel); // Bedenk hoeveel artikelen worden gepakt. int aantalArtikelen = getRandomValue(MIN_ARTIKELEN_PER_PERSOON, MAX_ARTIKELEN_PER_PERSOON); // Genereer de "artikelnummers", dit zijn indexen van de artikelnamen. int[] tePakken = getRandomArray(aantalArtikelen, 0, AANTAL_ARTIKELEN - 1); // Vind de artikelnamen op basis van de indexen hierboven. String[] artikelen = geefArtikelNamen(tePakken); // Loop de kantine binnen, pak de gewenste artikelen en sluit aan. kantine.loopPakSluitAan(dienbladVanKlant, artikelen); // Vul artikelen aan als ze onder het minimum komen. 3.1 for(int p = 0; p < aantalArtikelen; p++) { kantineAanbod.vulVoorraadAan(artikelen[p]); } // Spam for week 3 opgave 4b //System.out.println(klantInWinkel.toString()); } // Verwerk rij voor de kassa. kantine.verwerkRijVoorKassa(i); // druk de dagtotalen af en hoeveel personen binnen zijn gekomen. System.out.println("Aantal klanten: " + aantalPersonen); System.out.println("Studenten: " + aantalStudenten + " Docenten: " + aantalDocenten + " Kantinemedewerkers: " + aantalKantineMedewerkers); System.out.println("Aantal artikelen: " + kantine.getAantalArtikelen()); System.out.printf("Totaalbedrag: " + "%.2f%n",kantine.getTotaalbedrag()); System.out.println(""); // sla de waarden van die dag op. gemiddeldeArtikelen[i] = kantine.getAantalArtikelen(); dagOmzet[i] = kantine.getTotaalbedrag(); // vul statistieken aan totaalAantalStudenten += aantalStudenten; totaalAantalDocenten += aantalDocenten; totaalAantalKantineMedewerkers += aantalKantineMedewerkers; // reset de kassa voor de volgende dag. kantine.resetKassa(); } System.out.println("--- Klanten --- "); System.out.println("Totaal aantal klanten: " + (totaalAantalStudenten + totaalAantalDocenten + totaalAantalKantineMedewerkers)); System.out.println("Studenten: " + totaalAantalStudenten + " Docenten: " + totaalAantalDocenten + " Kantinemedewerkers: " + totaalAantalKantineMedewerkers); System.out.println("--- Gemiddelden --- "); System.out.printf("Gemiddelde omzet: " + "%.2f%n",Administratie.berekenGemiddeldeOmzet(dagOmzet)); System.out.printf("Gemiddelde verkochte artikelen: " + "%.2f%n",Administratie.berekenGemiddeldAantal(gemiddeldeArtikelen)); double[] dagTotalen = Administratie.berekenDagOmzet(dagOmzet); System.out.println("--- Totalen per dag --- "); System.out.printf("Maandag: " + "%.2f%n",dagTotalen[0]); System.out.printf("Dinsdag: " + "%.2f%n",dagTotalen[1]); System.out.printf("Woensdag: " + "%.2f%n",dagTotalen[2]); System.out.printf("Donderdag: " + "%.2f%n",dagTotalen[3]); System.out.printf("Vrijdag: " + "%.2f%n",dagTotalen[4]); System.out.printf("Zaterdag: " + "%.2f%n",dagTotalen[5]); System.out.printf("Zondag: " + "%.2f%n",dagTotalen[6]); // NOW STOP - > Querytime // single query System.out.println("~Now stop. Querytime~"); // 3.a Query query = manager.createQuery("SELECT SUM(totaal) AS totaal, SUM(korting) AS korting FROM Factuur"); List<Object[]> resultList = query.getResultList(); /* System.out.println("3A: Totale omzetten"); for (Object[] r : resultList) { System.out.println("Totaal Omzet: " + r[0]); System.out.println("Totaal Korting: " + r[1]); } */ resultList.forEach(r -> System.out.println(Arrays.toString(r))); // 3.b query = manager.createQuery("SELECT AVG(totaal) AS totaal, AVG(korting) AS korting FROM Factuur"); resultList = query.getResultList(); System.out.println("3B: Gemiddelde omzetten"); resultList.forEach(r -> System.out.println(Arrays.toString(r))); /*for (Object[] r : resultList) { System.out.println("Gemiddelde omzet per factuur: " + r[0]); System.out.println("Gemiddelde korting per factuur: " + r[1]); }*/ // 3.c query = manager.createQuery("SELECT totaal FROM Factuur ORDER BY totaal DESC"); query.setMaxResults(3); resultList = query.getResultList(); System.out.println("3C: Top 3 hoogste facturen"); Object[] g = resultList.toArray(); System.out.println("#1: " + g[0]); System.out.println("#2: " + g[1]); System.out.println("#3: " + g[2]); System.out.println("~Now stop. Querytime V2~"); // 5.a System.out.println("5a: Gemiddelde omzetten"); OmzetKortingArtikel("Broodje kaas"); OmzetKortingArtikel("Koffie"); OmzetKortingArtikel("Broodje pindakaas"); OmzetKortingArtikel("Appelsap"); // 5.b queryTotaalPerDag(dagen); // 5.c System.out.println("5c: top 3 meest populaire artikelen"); query = manager .createQuery("SELECT artikel.naam, COUNT(artikel.naam) FROM FactuurRegel GROUP BY artikel.naam ORDER BY COUNT(artikel.naam) DESC"); query.setMaxResults(3); resultList = query.getResultList(); resultList.forEach(r -> System.out.println(Arrays.toString(r))); // 5.d System.out.println("5d: top 3 hoogste omzet artikelen"); query = manager .createQuery("SELECT artikel.naam, SUM(artikel.prijs - artikel.korting) FROM FactuurRegel GROUP BY artikel.naam ORDER BY SUM(artikel.prijs - artikel.korting) DESC"); query.setMaxResults(3); resultList = query.getResultList(); resultList.forEach(r -> System.out.println(Arrays.toString(r))); System.out.println("~Close DB~"); // Close manager and database :) manager.close(); ENTITY_MANAGER_FACTORY.close(); } public void OmzetKortingArtikel(String artikel) { Query query = manager.createQuery("SELECT id FROM FactuurRegel where naam = '"+ artikel + "' and korting > 0"); List<FactuurRegel> resultList = query.getResultList(); double korting = resultList.size() * (kantineAanbod.getArtikel(artikel).getPrijs() * 0.2); System.out.println("Korting op " + artikel + ": €" + korting); query = manager.createQuery("SELECT id FROM FactuurRegel where naam = '"+ artikel + "'"); resultList = query.getResultList(); System.out.println("Totaal verdiend met " + artikel + ": €" + resultList.size() * kantineAanbod.getArtikel(artikel).getPrijs()); } public void queryTotaalPerDag(int dagen) { for (int i = 0; i < dagen; i++) { System.out.println("Dag: " + LocalDate.now().plusDays(i)); Query query = manager .createQuery("SELECT fr.artikel.naam, sum(fr.artikel.prijs), sum(fr.artikel.korting) FROM FactuurRegel fr JOIN fr.factuur f WHERE f.datum = '"+ LocalDate.now().plusDays(i)+ "'GROUP BY fr.artikel.naam "); query.setMaxResults(3); List<Object[]> resultList = query.getResultList(); resultList.forEach(r -> System.out.println(Arrays.toString(r))); } }; }
RedFirebreak/ProjectKantine
src/main/java/KantineSimulatie2.java
4,826
// Bedenk hoeveel artikelen worden gepakt.
line_comment
nl
import java.sql.Array; import java.util.*; import java.time.LocalDate; import javax.persistence.Persistence; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; public class KantineSimulatie2 { // Create an EntityManagerFactory when you start the application. private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory("KantineSimulatie"); private EntityManager manager; // kantine private Kantine kantine; // kantineaanbod private KantineAanbod kantineAanbod; // random generator private Random random; // aantal artikelen private static final int AANTAL_ARTIKELEN = 4; // artikelen private static final String[] artikelnamen = new String[] { "Koffie", "Broodje pindakaas", "Broodje kaas", "Appelsap" }; // prijzen private static double[] artikelprijzen = new double[] { 1.50, 2.10, 1.65, 1.65 }; // minimum en maximum aantal artikelen per soort private static final int MIN_ARTIKELEN_PER_SOORT = 1; private static final int MAX_ARTIKELEN_PER_SOORT = 1; // minimum en maximum aantal personen per dag private static final int MIN_PERSONEN_PER_DAG = 5; private static final int MAX_PERSONEN_PER_DAG = 20; // minimum en maximum artikelen per persoon private static final int MIN_ARTIKELEN_PER_PERSOON = 2; private static final int MAX_ARTIKELEN_PER_PERSOON = 4; // totaalomzet private int[] gemiddeldeArtikelen; private double[] dagOmzet; /** * Constructor */ public KantineSimulatie2() { // Create the manager manager = ENTITY_MANAGER_FACTORY.createEntityManager(); // Maak een nieuwe kantine aan, de "hoofd" klasse. kantine = new Kantine(manager); // Zet een randomizer klaar. random = new Random(); // Bepaal het aantal hoeveelheden van elk aspect. // Gebruikt de nieuwe getRandomArray();. int[] hoeveelheden = getRandomArray(AANTAL_ARTIKELEN, MIN_ARTIKELEN_PER_SOORT, MAX_ARTIKELEN_PER_SOORT); // Maak een nieuw kantineaanbod aan. kantineAanbod = new KantineAanbod(artikelnamen, artikelprijzen, hoeveelheden); // Verwerk het kantineaanbod in de kantine. kantine.setKantineAanbod(kantineAanbod); } /** * Methode om een array van random getallen te genereren. De getallen liggen * tussen min en max (inclusief). * * @param lengte De gegeven lengte van de array. * @param min Minimale waarde die in de array mag. * @param max Maximale waarde die in de array mag. * @return De array met random getallen. */ private int[] getRandomArray(int lengte, int min, int max) { int[] temp = new int[lengte]; for (int i = 0; i < lengte; i++) { temp[i] = getRandomValue(min, max); } return temp; } /** * Methode om een random getal tussen min(incl) en max(incl) te genereren. * * @param min De minimumwaarde. * @param max De maximumwaarde. * @return Het random gegenereerde getal. */ private int getRandomValue(int min, int max) { // Omdat er misschien "0" klanten kunnen zijn, doen we +1. return random.nextInt(max - min + 1) + min; } /** * Methode om op basis van een gegeven array van indexen voor de array * artikelnamen de bijhorende array van artikelnamen te maken. * * @param indexen De array met gegeven indexen. * @return De array met artikelnamen. */ private String[] geefArtikelNamen(int[] indexen) { String[] artikelen = new String[indexen.length]; for (int i = 0; i < indexen.length; i++) { artikelen[i] = artikelnamen[indexen[i]]; } return artikelen; } /** * Deze methode simuleert een aantal dagen in het verloop van de kantine. * * @param dagen De hoeveelheid dagen die je wil simuleren. */ public void simuleer(int dagen) { // Zet de variabele voor administratie. gemiddeldeArtikelen = new int[dagen+1]; dagOmzet = new double[dagen+1]; // counters voor totaalstatistieken int totaalAantalStudenten = 0; int totaalAantalDocenten = 0; int totaalAantalKantineMedewerkers = 0; // een BSN die mee gegeven wordt met elk persoon. (9 cijfers) int bsn = 100000000; // Voor leerlingen: studentnummer int studentnummer = 10000; // For lus voor dagen. for (int i = 1; i < dagen + 1; i++) { System.out.println("-------------------------"); System.out.println("Dag: " + i); // Nieuwe aantallen en dagaanbiedingen // Bepaal het aantal hoeveelheden van elk aspect. // Gebruikt de nieuwe getRandomArray();. int[] hoeveelheden = getRandomArray(AANTAL_ARTIKELEN, MIN_ARTIKELEN_PER_SOORT, MAX_ARTIKELEN_PER_SOORT); // Maak een nieuw kantineaanbod aan. kantineAanbod = new KantineAanbod(artikelnamen, artikelprijzen, hoeveelheden); // Bedenk hoeveel personen vandaag binnen lopen. int aantalPersonen = getRandomValue(MIN_PERSONEN_PER_DAG, MAX_PERSONEN_PER_DAG); // maak wat counters voor statistieken : int aantalStudenten = 0; int aantalDocenten = 0; int aantalKantineMedewerkers = 0; // Laat de personen maar komen... for (int j = 0; j < aantalPersonen; j++) { // Nieuw persoon, nieuw BSN! bsn++; // Maak een geboortedatum // While loop to make sure we have a valid datum Boolean datumAangemaakt = false; // Maak een "fake" datum aan om een echte te kunnen checken. Datum datum = new Datum(); // while loop todat er een echte datum gevonden is while(datumAangemaakt == false) { // Max 31 dagen int randomdag = random.nextInt(31); // Max 12 maanden int randommaand = random.nextInt(12); // Min 10 jaar oud, max 60+10 int randomjaar = (2020-((random.nextInt(60))+10)); // Kijk of de 3 gegevens samen een echte datum maken if (datum.bestaatDatum(randomdag, randommaand, randomjaar)) { // datum bestaat, overwrite de fake datum! datum = new Datum(randomdag, randommaand, randomjaar); // exit loop! datumAangemaakt = true; } else { // datum bestaat niet. Try again datumAangemaakt = false; } } // Get random geslacht (1 op 2) int randomgetal = random.nextInt(2); char geslacht = 'O'; if (randomgetal == 1) { // 1 op 2: Man geslacht = 'M'; } else { // 1 op 2: Vrouw geslacht = 'V'; } // Bepaal wat voor klant dit is // maak een fake klant Persoon klantInWinkel = new Persoon(); // Overwrite random getal en maak een 1 - 100 randomgetal = random.nextInt(100); randomgetal++; // maak getal 1-100 i.p.v 0-99. String[] voornamen = { "Stefan", "Teun", "Stijn", "Romano", "Maurice", "Jan-Wiepke", "Henkie", "Jessica"}; String[] achternamen = { "de Jong","Hoogezand","Braxhoofden","Pater","Wolthuis","Highsand-Juicylake","Timmermans","Willemse","Jansen","Kramer","Kuppen","Jilderda"}; int randomVoornaam = random.nextInt(voornamen.length); int randomAchternaam = random.nextInt(achternamen.length); String voornaam = voornamen[randomVoornaam]; String achternaam = achternamen[randomAchternaam]; if (randomgetal == 100) { // 1 op 100: kantinemedewerker klantInWinkel = new KantineMedewerker(bsn, voornaam, achternaam, datum, geslacht); klantInWinkel.setKortingsKaartHouder(true); aantalKantineMedewerkers++; } else if(randomgetal <= 89) { // 89 op 100: Student studentnummer++; String studierichting = "ICT"; // TODO random afdeling klantInWinkel = new Student(bsn, voornaam, achternaam, datum, geslacht, studentnummer, studierichting); aantalStudenten++; } else if (randomgetal >= 90 && randomgetal < 100 ) { // 10 op 100: Docent String vierlettercode = "ABCD"; // TODO random vierlettercode String afdeling = "ICT"; // TODO random afdeling klantInWinkel = new Docent(bsn, voornaam, achternaam, datum, geslacht, vierlettercode, afdeling); klantInWinkel.setKortingsKaartHouder(true); aantalDocenten++; } // Get random geslacht (1 op 2) randomgetal = random.nextInt(2); if (randomgetal == 1) { // 1 op 2: Contant Contant betaalwijze; klantInWinkel.setBetaalwijze(betaalwijze = new Contant()); betaalwijze.setSaldo(7.50); } else { // 1 op 2: Pinpas Pinpas betaalwijze; klantInWinkel.setBetaalwijze(betaalwijze = new Pinpas()); betaalwijze.setKredietLimiet(7.0); betaalwijze.setSaldo(7.50); } // Maak persoon en dienblad aan, koppel ze aan elkaar. Dienblad dienbladVanKlant = new Dienblad(klantInWinkel); dienbladVanKlant.setKlant(klantInWinkel); // Bedenk hoeveel<SUF> int aantalArtikelen = getRandomValue(MIN_ARTIKELEN_PER_PERSOON, MAX_ARTIKELEN_PER_PERSOON); // Genereer de "artikelnummers", dit zijn indexen van de artikelnamen. int[] tePakken = getRandomArray(aantalArtikelen, 0, AANTAL_ARTIKELEN - 1); // Vind de artikelnamen op basis van de indexen hierboven. String[] artikelen = geefArtikelNamen(tePakken); // Loop de kantine binnen, pak de gewenste artikelen en sluit aan. kantine.loopPakSluitAan(dienbladVanKlant, artikelen); // Vul artikelen aan als ze onder het minimum komen. 3.1 for(int p = 0; p < aantalArtikelen; p++) { kantineAanbod.vulVoorraadAan(artikelen[p]); } // Spam for week 3 opgave 4b //System.out.println(klantInWinkel.toString()); } // Verwerk rij voor de kassa. kantine.verwerkRijVoorKassa(i); // druk de dagtotalen af en hoeveel personen binnen zijn gekomen. System.out.println("Aantal klanten: " + aantalPersonen); System.out.println("Studenten: " + aantalStudenten + " Docenten: " + aantalDocenten + " Kantinemedewerkers: " + aantalKantineMedewerkers); System.out.println("Aantal artikelen: " + kantine.getAantalArtikelen()); System.out.printf("Totaalbedrag: " + "%.2f%n",kantine.getTotaalbedrag()); System.out.println(""); // sla de waarden van die dag op. gemiddeldeArtikelen[i] = kantine.getAantalArtikelen(); dagOmzet[i] = kantine.getTotaalbedrag(); // vul statistieken aan totaalAantalStudenten += aantalStudenten; totaalAantalDocenten += aantalDocenten; totaalAantalKantineMedewerkers += aantalKantineMedewerkers; // reset de kassa voor de volgende dag. kantine.resetKassa(); } System.out.println("--- Klanten --- "); System.out.println("Totaal aantal klanten: " + (totaalAantalStudenten + totaalAantalDocenten + totaalAantalKantineMedewerkers)); System.out.println("Studenten: " + totaalAantalStudenten + " Docenten: " + totaalAantalDocenten + " Kantinemedewerkers: " + totaalAantalKantineMedewerkers); System.out.println("--- Gemiddelden --- "); System.out.printf("Gemiddelde omzet: " + "%.2f%n",Administratie.berekenGemiddeldeOmzet(dagOmzet)); System.out.printf("Gemiddelde verkochte artikelen: " + "%.2f%n",Administratie.berekenGemiddeldAantal(gemiddeldeArtikelen)); double[] dagTotalen = Administratie.berekenDagOmzet(dagOmzet); System.out.println("--- Totalen per dag --- "); System.out.printf("Maandag: " + "%.2f%n",dagTotalen[0]); System.out.printf("Dinsdag: " + "%.2f%n",dagTotalen[1]); System.out.printf("Woensdag: " + "%.2f%n",dagTotalen[2]); System.out.printf("Donderdag: " + "%.2f%n",dagTotalen[3]); System.out.printf("Vrijdag: " + "%.2f%n",dagTotalen[4]); System.out.printf("Zaterdag: " + "%.2f%n",dagTotalen[5]); System.out.printf("Zondag: " + "%.2f%n",dagTotalen[6]); // NOW STOP - > Querytime // single query System.out.println("~Now stop. Querytime~"); // 3.a Query query = manager.createQuery("SELECT SUM(totaal) AS totaal, SUM(korting) AS korting FROM Factuur"); List<Object[]> resultList = query.getResultList(); /* System.out.println("3A: Totale omzetten"); for (Object[] r : resultList) { System.out.println("Totaal Omzet: " + r[0]); System.out.println("Totaal Korting: " + r[1]); } */ resultList.forEach(r -> System.out.println(Arrays.toString(r))); // 3.b query = manager.createQuery("SELECT AVG(totaal) AS totaal, AVG(korting) AS korting FROM Factuur"); resultList = query.getResultList(); System.out.println("3B: Gemiddelde omzetten"); resultList.forEach(r -> System.out.println(Arrays.toString(r))); /*for (Object[] r : resultList) { System.out.println("Gemiddelde omzet per factuur: " + r[0]); System.out.println("Gemiddelde korting per factuur: " + r[1]); }*/ // 3.c query = manager.createQuery("SELECT totaal FROM Factuur ORDER BY totaal DESC"); query.setMaxResults(3); resultList = query.getResultList(); System.out.println("3C: Top 3 hoogste facturen"); Object[] g = resultList.toArray(); System.out.println("#1: " + g[0]); System.out.println("#2: " + g[1]); System.out.println("#3: " + g[2]); System.out.println("~Now stop. Querytime V2~"); // 5.a System.out.println("5a: Gemiddelde omzetten"); OmzetKortingArtikel("Broodje kaas"); OmzetKortingArtikel("Koffie"); OmzetKortingArtikel("Broodje pindakaas"); OmzetKortingArtikel("Appelsap"); // 5.b queryTotaalPerDag(dagen); // 5.c System.out.println("5c: top 3 meest populaire artikelen"); query = manager .createQuery("SELECT artikel.naam, COUNT(artikel.naam) FROM FactuurRegel GROUP BY artikel.naam ORDER BY COUNT(artikel.naam) DESC"); query.setMaxResults(3); resultList = query.getResultList(); resultList.forEach(r -> System.out.println(Arrays.toString(r))); // 5.d System.out.println("5d: top 3 hoogste omzet artikelen"); query = manager .createQuery("SELECT artikel.naam, SUM(artikel.prijs - artikel.korting) FROM FactuurRegel GROUP BY artikel.naam ORDER BY SUM(artikel.prijs - artikel.korting) DESC"); query.setMaxResults(3); resultList = query.getResultList(); resultList.forEach(r -> System.out.println(Arrays.toString(r))); System.out.println("~Close DB~"); // Close manager and database :) manager.close(); ENTITY_MANAGER_FACTORY.close(); } public void OmzetKortingArtikel(String artikel) { Query query = manager.createQuery("SELECT id FROM FactuurRegel where naam = '"+ artikel + "' and korting > 0"); List<FactuurRegel> resultList = query.getResultList(); double korting = resultList.size() * (kantineAanbod.getArtikel(artikel).getPrijs() * 0.2); System.out.println("Korting op " + artikel + ": €" + korting); query = manager.createQuery("SELECT id FROM FactuurRegel where naam = '"+ artikel + "'"); resultList = query.getResultList(); System.out.println("Totaal verdiend met " + artikel + ": €" + resultList.size() * kantineAanbod.getArtikel(artikel).getPrijs()); } public void queryTotaalPerDag(int dagen) { for (int i = 0; i < dagen; i++) { System.out.println("Dag: " + LocalDate.now().plusDays(i)); Query query = manager .createQuery("SELECT fr.artikel.naam, sum(fr.artikel.prijs), sum(fr.artikel.korting) FROM FactuurRegel fr JOIN fr.factuur f WHERE f.datum = '"+ LocalDate.now().plusDays(i)+ "'GROUP BY fr.artikel.naam "); query.setMaxResults(3); List<Object[]> resultList = query.getResultList(); resultList.forEach(r -> System.out.println(Arrays.toString(r))); } }; }
58650_9
/** * Copyright 2002 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * This file is part of MARY TTS. * * MARY TTS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package marytts.language.de.postlex; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * The rules for the postlexical phonological processes module. * * @author Marc Schr&ouml;der */ public class PhonologicalRules { // Rules as regular expressions with substitution patterns: // The first string is a regular expression pattern, the three others are // substitution patterns for PRECISE, NORMAL and SLOPPY pronunciation // respectively. They may contain bracket references $1, $2, ... // as in the example below: // {"([bdg])@(n)", "$1@$2", "$1@$2", "$1@$2"} private static final String[][] _rules = { // @-Elision mit -en, -el, -em { "([dlrszSt])@n", "$1@n", "$1@n", "$1@n" }, // warning: mbrola de1/2 don't have Z-n diphone // @Elision mit -en, -el, -em; Assimilation { "f@n", "f@n", "f@n", "f@n" }, { "g@n", "g@n", "g@n", "g@n" }, // warning: mbrola de1 doesn't have g-N diphone { "k@n", "k@n", "k@n", "k@n" },// warning: mbrola de1 doesn't have k-N diphone { "p@n", "p@n", "p@n", "p@n" }, { "x@n", "x@n", "x@n", "x@n" },// warning: mbrola de1/2 don't have x-N diphone // @-Elision mit -en, -el, -em; Assimilation und Geminatenreduktion { "b@n", "b@n", "b@n", "b@n" },// warning: mbrola de1 doesn't have b-m diphone { "m@n", "m@n", "m@n", "m@n" }, { "n@n", "n@n", "n@n", "n@n" }, // bei Geminatenreduktion wird der uebrigbleibende Laut eigentlich gelaengt. // Da es jedoch noch kein Symbol und keine Semantik fuer Laengung gibt, // soll an dieser Stelle nur darauf hingewiesen werden. // Assimilation der Artikulationsart { "g-n", "g-n", "g-n", "g-n" }, // Assimilation und Geminatenreduktion { "m-b", "m-b", "m-b", "m-b" }, { "t-t", "t-t", "t-t", "t-t" }, // bei Geminatenreduktion wird der uebrigbleibende Laut eigentlich gelaengt. // Da es jedoch noch kein Symbol und keine Semantik fuer Laengung gibt, // soll an dieser Stelle nur darauf hingewiesen werden. // glottal stop removal: { "\\?(aI|OY|aU|[iIyYe\\{E29uUoOaA])", "?$1", "?$1", "?$1" }, // Reduce E6 -> 6 in unstressed syllables only: // {"^([^'-]*)E6", "$16", "$16", "$16"}, // {"-([^'-]*)E6", "-$16", "-$16", "-$16"}, // be more specific: reduce fE6 -> f6 in unstressed syllables only { "^([^'-]*)fE6", "$1f6", "$1f6", "$1f6" }, { "-([^'-]*)fE6", "-$1f6", "-$1f6", "-$1f6" }, // Replace ?6 with ?E6 wordinitial { "\\?6", "\\?E6", "\\?E6", "\\?E6" }, // !! Translate the old MARY SAMPA to the new MARY SAMPA: { "O~:", "a~", "a~", "a~" }, { "o~:", "o~", "o~", "o~" }, { "9~:", "9~", "9~", "9~" }, { "E~:", "e~", "e~", "e~" }, { "O~", "a~", "a~", "a~" }, { "o~", "o~", "o~", "o~" }, { "9~", "9~", "9~", "9~" }, { "E~", "e~", "e~", "e~" }, { "\\{", "E", "E", "E" }, // {"r", "R", "R", "R"} }; private static final List<PhonologicalRules> rules = initialiseRules(); private static List<PhonologicalRules> initialiseRules() { List<PhonologicalRules> r = new ArrayList<PhonologicalRules>(); for (int i = 0; i < _rules.length; i++) { r.add(new PhonologicalRules(_rules[i])); } return r; } public static List<PhonologicalRules> getRules() { return rules; } public static final int PRECISE = 1; public static final int NORMAL = 2; public static final int SLOPPY = 3; private Pattern key; private String precise; private String normal; private String sloppy; public PhonologicalRules(String[] data) { try { key = Pattern.compile(data[0]); } catch (PatternSyntaxException e) { System.err.println("Cannot compile regular expression `" + data[0] + "':"); e.printStackTrace(); } precise = data[1]; normal = data[2]; sloppy = data[3]; } public boolean matches(String input) { return key.matcher(input).find(); } public String apply(String input, int precision) { String repl = normal; if (precision == PRECISE) repl = precise; else if (precision == SLOPPY) repl = sloppy; return key.matcher(input).replaceAll(repl); } }
marytts/marytts
marytts-languages/marytts-lang-de/src/main/java/marytts/language/de/postlex/PhonologicalRules.java
1,741
// warning: mbrola de1/2 don't have Z-n diphone
line_comment
nl
/** * Copyright 2002 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * This file is part of MARY TTS. * * MARY TTS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package marytts.language.de.postlex; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * The rules for the postlexical phonological processes module. * * @author Marc Schr&ouml;der */ public class PhonologicalRules { // Rules as regular expressions with substitution patterns: // The first string is a regular expression pattern, the three others are // substitution patterns for PRECISE, NORMAL and SLOPPY pronunciation // respectively. They may contain bracket references $1, $2, ... // as in the example below: // {"([bdg])@(n)", "$1@$2", "$1@$2", "$1@$2"} private static final String[][] _rules = { // @-Elision mit -en, -el, -em { "([dlrszSt])@n", "$1@n", "$1@n", "$1@n" }, // warning: mbrola<SUF> // @Elision mit -en, -el, -em; Assimilation { "f@n", "f@n", "f@n", "f@n" }, { "g@n", "g@n", "g@n", "g@n" }, // warning: mbrola de1 doesn't have g-N diphone { "k@n", "k@n", "k@n", "k@n" },// warning: mbrola de1 doesn't have k-N diphone { "p@n", "p@n", "p@n", "p@n" }, { "x@n", "x@n", "x@n", "x@n" },// warning: mbrola de1/2 don't have x-N diphone // @-Elision mit -en, -el, -em; Assimilation und Geminatenreduktion { "b@n", "b@n", "b@n", "b@n" },// warning: mbrola de1 doesn't have b-m diphone { "m@n", "m@n", "m@n", "m@n" }, { "n@n", "n@n", "n@n", "n@n" }, // bei Geminatenreduktion wird der uebrigbleibende Laut eigentlich gelaengt. // Da es jedoch noch kein Symbol und keine Semantik fuer Laengung gibt, // soll an dieser Stelle nur darauf hingewiesen werden. // Assimilation der Artikulationsart { "g-n", "g-n", "g-n", "g-n" }, // Assimilation und Geminatenreduktion { "m-b", "m-b", "m-b", "m-b" }, { "t-t", "t-t", "t-t", "t-t" }, // bei Geminatenreduktion wird der uebrigbleibende Laut eigentlich gelaengt. // Da es jedoch noch kein Symbol und keine Semantik fuer Laengung gibt, // soll an dieser Stelle nur darauf hingewiesen werden. // glottal stop removal: { "\\?(aI|OY|aU|[iIyYe\\{E29uUoOaA])", "?$1", "?$1", "?$1" }, // Reduce E6 -> 6 in unstressed syllables only: // {"^([^'-]*)E6", "$16", "$16", "$16"}, // {"-([^'-]*)E6", "-$16", "-$16", "-$16"}, // be more specific: reduce fE6 -> f6 in unstressed syllables only { "^([^'-]*)fE6", "$1f6", "$1f6", "$1f6" }, { "-([^'-]*)fE6", "-$1f6", "-$1f6", "-$1f6" }, // Replace ?6 with ?E6 wordinitial { "\\?6", "\\?E6", "\\?E6", "\\?E6" }, // !! Translate the old MARY SAMPA to the new MARY SAMPA: { "O~:", "a~", "a~", "a~" }, { "o~:", "o~", "o~", "o~" }, { "9~:", "9~", "9~", "9~" }, { "E~:", "e~", "e~", "e~" }, { "O~", "a~", "a~", "a~" }, { "o~", "o~", "o~", "o~" }, { "9~", "9~", "9~", "9~" }, { "E~", "e~", "e~", "e~" }, { "\\{", "E", "E", "E" }, // {"r", "R", "R", "R"} }; private static final List<PhonologicalRules> rules = initialiseRules(); private static List<PhonologicalRules> initialiseRules() { List<PhonologicalRules> r = new ArrayList<PhonologicalRules>(); for (int i = 0; i < _rules.length; i++) { r.add(new PhonologicalRules(_rules[i])); } return r; } public static List<PhonologicalRules> getRules() { return rules; } public static final int PRECISE = 1; public static final int NORMAL = 2; public static final int SLOPPY = 3; private Pattern key; private String precise; private String normal; private String sloppy; public PhonologicalRules(String[] data) { try { key = Pattern.compile(data[0]); } catch (PatternSyntaxException e) { System.err.println("Cannot compile regular expression `" + data[0] + "':"); e.printStackTrace(); } precise = data[1]; normal = data[2]; sloppy = data[3]; } public boolean matches(String input) { return key.matcher(input).find(); } public String apply(String input, int precision) { String repl = normal; if (precision == PRECISE) repl = precise; else if (precision == SLOPPY) repl = sloppy; return key.matcher(input).replaceAll(repl); } }
90893_13
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tsp.simulatie; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.GridLayout; import java.util.ArrayList; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.FontMetrics; /** * * @author Johan */ public class Grid extends JPanel{ private JLabel[][] myLabels; private Color myColor; private int size; Vak[][] alleVakken; ArrayList<Vak> vakken; int vakSize; boolean lijntjes = false; @Override public void paintComponent(Graphics g)// bteken akke vakken met een bepaalde kleur als die wel of niet is geslecteerd { int pointX = 0; int pointY = 0; // teken de achtergrond super.paintComponent(g); // maak de achtergrond wit setBackground(Color.WHITE); Font font =new Font("Consolas", Font.PLAIN, 11); g.setFont(font); // tekenen.. g.setColor(Color.black); for (int row = 0; row < alleVakken.length; row++) { for (int col = 0; col < alleVakken[row].length; col++) { if(alleVakken[row][col].getIsGeselecteerd()) { g.setColor(Color.green); }else { g.setColor(Color.blue); } //System.out.println("x: " + pointX); // alleVakken[row][col] g.fillRect(pointX, pointY, pointX + vakSize, pointY + vakSize); g.setColor(Color.black); g.drawRect(pointX, pointY, pointX + vakSize, pointY + vakSize); if(alleVakken[row][col].getIsGeselecteerd()) { g.setColor(Color.black); }else { g.setColor(Color.white); } g.drawString(alleVakken[row][col].getLocatie().toString(), pointX+1, pointY+vakSize-1); pointX += vakSize; //System.out.println("x1: " + pointX + " |y1: " + pointY + " |x2: " + (pointX + 720/alleVakken.length) + " |y2: " + (pointY + 720/alleVakken.length) + " |size: " + 720/alleVakken.length); } // System.out.println("y " + pointY); pointY += vakSize; pointX = 0; } if(lijntjes) { Vak[] lijnCords = new Vak[vakken.size()]; g.setColor(Color.red); int i = 0; for(Vak v : vakken) { lijnCords[i] = v; i++; } for(int j = 1; j < lijnCords.length; j++) { if(j == 1) { g.drawLine(0, 720, lijnCords[j-1].getX()*(vakSize)+(vakSize/2), lijnCords[j-1].getY()*(vakSize)+(vakSize/2)); } g.drawLine(lijnCords[j-1].getX()*(vakSize)+(vakSize/2), lijnCords[j-1].getY()*(vakSize)+(vakSize/2), lijnCords[j].getX()*(vakSize)+(vakSize/2), lijnCords[j].getY()*(vakSize)+(vakSize/2)); } lijntjes = false; } } public void drawLijnjes(ArrayList<Vak> vakken)// tekend de route aan het eind van een berekening { Locatie loc = new Locatie(0, 20); this.vakken = vakken; for (int a = 0; a < vakken.size(); a++) { if (vakken.get(a).getLocatie().toString().equals(loc.toString())) { vakken.remove(vakken.get(a)); } } lijntjes = true; repaint(); } public Grid(int rows, int cols, int cellWidth, int Lineborder) { //myLabels = new JLabel[rows][cols]; MouseListener myListener = new MouseListener(this); Dimension labelPrefSize = new Dimension(cellWidth, cellWidth); //setLayout(new GridLayout(rows, cols, Lineborder, Lineborder)); setBackground(Color.BLACK); generateVakken(rows); vakSize = 720/alleVakken.length; this.addMouseListener(myListener); /*for (int row = 0; row < myLabels.length; row++) { for (int col = 0; col < myLabels[row].length; col++) { JLabel myLabel = new JLabel(); myLabel = new JLabel(); myLabel.setOpaque(true); myColor = Color.BLUE; myLabel.setBackground(myColor); myLabel. myLabel.setPreferredSize(labelPrefSize); add(myLabel); myLabels[row][col] = myLabel; } }*/ } private void generateVakken(int s)//genereerd vakken gebaseerd op de dimensies { alleVakken = new Vak[s][s]; for (int row = 0; row < alleVakken.length; row++) { for (int col = 0; col < alleVakken[row].length; col++) { Vak myVak = new Vak(col, row); alleVakken[row][col] = myVak; } } } public void labelPressed(Vak v) {// select of deselect een vak for (int row = 0; row < alleVakken.length; row++) { for (int col = 0; col < alleVakken[row].length; col++) { if (v == alleVakken[row][col]) { alleVakken[row][col].isGeselecteerd(); } } } } public void berekenVak(int x, int y)//berken welke vak gebaseerd op de x en y cordinaat die uit de mouse listener worden gehaald { if(x%vakSize != 0) { x -= x%vakSize; } if(y%vakSize != 0) { y -= y%vakSize; } int row = y/vakSize; int col = x/vakSize; Vak vk = alleVakken[row][col]; labelPressed(vk); repaint(); } public Vak[][] getAlleVakken() { return alleVakken; } }
jurrianf/TSP
TSP-simulatie/src/tsp/simulatie/Grid.java
1,808
// select of deselect een vak
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tsp.simulatie; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.GridLayout; import java.util.ArrayList; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.FontMetrics; /** * * @author Johan */ public class Grid extends JPanel{ private JLabel[][] myLabels; private Color myColor; private int size; Vak[][] alleVakken; ArrayList<Vak> vakken; int vakSize; boolean lijntjes = false; @Override public void paintComponent(Graphics g)// bteken akke vakken met een bepaalde kleur als die wel of niet is geslecteerd { int pointX = 0; int pointY = 0; // teken de achtergrond super.paintComponent(g); // maak de achtergrond wit setBackground(Color.WHITE); Font font =new Font("Consolas", Font.PLAIN, 11); g.setFont(font); // tekenen.. g.setColor(Color.black); for (int row = 0; row < alleVakken.length; row++) { for (int col = 0; col < alleVakken[row].length; col++) { if(alleVakken[row][col].getIsGeselecteerd()) { g.setColor(Color.green); }else { g.setColor(Color.blue); } //System.out.println("x: " + pointX); // alleVakken[row][col] g.fillRect(pointX, pointY, pointX + vakSize, pointY + vakSize); g.setColor(Color.black); g.drawRect(pointX, pointY, pointX + vakSize, pointY + vakSize); if(alleVakken[row][col].getIsGeselecteerd()) { g.setColor(Color.black); }else { g.setColor(Color.white); } g.drawString(alleVakken[row][col].getLocatie().toString(), pointX+1, pointY+vakSize-1); pointX += vakSize; //System.out.println("x1: " + pointX + " |y1: " + pointY + " |x2: " + (pointX + 720/alleVakken.length) + " |y2: " + (pointY + 720/alleVakken.length) + " |size: " + 720/alleVakken.length); } // System.out.println("y " + pointY); pointY += vakSize; pointX = 0; } if(lijntjes) { Vak[] lijnCords = new Vak[vakken.size()]; g.setColor(Color.red); int i = 0; for(Vak v : vakken) { lijnCords[i] = v; i++; } for(int j = 1; j < lijnCords.length; j++) { if(j == 1) { g.drawLine(0, 720, lijnCords[j-1].getX()*(vakSize)+(vakSize/2), lijnCords[j-1].getY()*(vakSize)+(vakSize/2)); } g.drawLine(lijnCords[j-1].getX()*(vakSize)+(vakSize/2), lijnCords[j-1].getY()*(vakSize)+(vakSize/2), lijnCords[j].getX()*(vakSize)+(vakSize/2), lijnCords[j].getY()*(vakSize)+(vakSize/2)); } lijntjes = false; } } public void drawLijnjes(ArrayList<Vak> vakken)// tekend de route aan het eind van een berekening { Locatie loc = new Locatie(0, 20); this.vakken = vakken; for (int a = 0; a < vakken.size(); a++) { if (vakken.get(a).getLocatie().toString().equals(loc.toString())) { vakken.remove(vakken.get(a)); } } lijntjes = true; repaint(); } public Grid(int rows, int cols, int cellWidth, int Lineborder) { //myLabels = new JLabel[rows][cols]; MouseListener myListener = new MouseListener(this); Dimension labelPrefSize = new Dimension(cellWidth, cellWidth); //setLayout(new GridLayout(rows, cols, Lineborder, Lineborder)); setBackground(Color.BLACK); generateVakken(rows); vakSize = 720/alleVakken.length; this.addMouseListener(myListener); /*for (int row = 0; row < myLabels.length; row++) { for (int col = 0; col < myLabels[row].length; col++) { JLabel myLabel = new JLabel(); myLabel = new JLabel(); myLabel.setOpaque(true); myColor = Color.BLUE; myLabel.setBackground(myColor); myLabel. myLabel.setPreferredSize(labelPrefSize); add(myLabel); myLabels[row][col] = myLabel; } }*/ } private void generateVakken(int s)//genereerd vakken gebaseerd op de dimensies { alleVakken = new Vak[s][s]; for (int row = 0; row < alleVakken.length; row++) { for (int col = 0; col < alleVakken[row].length; col++) { Vak myVak = new Vak(col, row); alleVakken[row][col] = myVak; } } } public void labelPressed(Vak v) {// select of<SUF> for (int row = 0; row < alleVakken.length; row++) { for (int col = 0; col < alleVakken[row].length; col++) { if (v == alleVakken[row][col]) { alleVakken[row][col].isGeselecteerd(); } } } } public void berekenVak(int x, int y)//berken welke vak gebaseerd op de x en y cordinaat die uit de mouse listener worden gehaald { if(x%vakSize != 0) { x -= x%vakSize; } if(y%vakSize != 0) { y -= y%vakSize; } int row = y/vakSize; int col = x/vakSize; Vak vk = alleVakken[row][col]; labelPressed(vk); repaint(); } public Vak[][] getAlleVakken() { return alleVakken; } }
2220_3
/* * Copyright 2007 Pieter De Rycke * * This file is part of JMTP. * * JTMP is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or any later version. * * JMTP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU LesserGeneral Public * License along with JMTP. If not, see <http://www.gnu.org/licenses/>. */ package be.derycke.pieter.com; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Set; /** * * @author Pieter De Rycke */ public class COMReference { private static Set<WeakReference<COMReference>> references; private static Object lock; static { lock = new Object(); references = new HashSet<WeakReference<COMReference>>(); //dit wordt nog voor de finalizers aangeroepen als finalizen //bij exit aan staat //dit is voor de objecten die niet of nog niet door de gc //gefinalized werden //http://en.allexperts.com/q/Java-1046/Constructor-destructor.htm Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { synchronized(lock) { for(WeakReference<COMReference> reference : references) { try { reference.get().release(); } catch(NullPointerException e) {} } } } }); } private WeakReference<COMReference> reference; private long pIUnknown; public COMReference(long pIUnkown) { this.pIUnknown = pIUnkown; reference = new WeakReference<COMReference>(this); synchronized(lock) { references.add(reference); } } public long getMemoryAddress() { return pIUnknown; } native long release(); native long addRef(); @Override protected void finalize() { synchronized(lock) { references.remove(reference); release(); } } }
reindahl/jmtp
java/src/be/derycke/pieter/com/COMReference.java
630
//bij exit aan staat
line_comment
nl
/* * Copyright 2007 Pieter De Rycke * * This file is part of JMTP. * * JTMP is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or any later version. * * JMTP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU LesserGeneral Public * License along with JMTP. If not, see <http://www.gnu.org/licenses/>. */ package be.derycke.pieter.com; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.Set; /** * * @author Pieter De Rycke */ public class COMReference { private static Set<WeakReference<COMReference>> references; private static Object lock; static { lock = new Object(); references = new HashSet<WeakReference<COMReference>>(); //dit wordt nog voor de finalizers aangeroepen als finalizen //bij exit<SUF> //dit is voor de objecten die niet of nog niet door de gc //gefinalized werden //http://en.allexperts.com/q/Java-1046/Constructor-destructor.htm Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { synchronized(lock) { for(WeakReference<COMReference> reference : references) { try { reference.get().release(); } catch(NullPointerException e) {} } } } }); } private WeakReference<COMReference> reference; private long pIUnknown; public COMReference(long pIUnkown) { this.pIUnknown = pIUnkown; reference = new WeakReference<COMReference>(this); synchronized(lock) { references.add(reference); } } public long getMemoryAddress() { return pIUnknown; } native long release(); native long addRef(); @Override protected void finalize() { synchronized(lock) { references.remove(reference); release(); } } }
76936_2
package com.protomaps.basemap.layers; import com.onthegomap.planetiler.FeatureCollector; import com.onthegomap.planetiler.ForwardingProfile; import com.onthegomap.planetiler.VectorTile; import com.onthegomap.planetiler.reader.SourceFeature; import com.onthegomap.planetiler.util.Parse; import com.protomaps.basemap.feature.FeatureId; import com.protomaps.basemap.names.OsmNames; import java.util.List; public class Transit implements ForwardingProfile.FeatureProcessor, ForwardingProfile.FeaturePostProcessor { @Override public String name() { return "transit"; } @Override public void processFeature(SourceFeature sf, FeatureCollector features) { // todo: exclude railway stations, levels if (sf.canBeLine() && (sf.hasTag("railway") || sf.hasTag("aerialway", "cable_car") || sf.hasTag("man_made", "pier") || sf.hasTag("route", "ferry") || sf.hasTag("aeroway", "runway", "taxiway")) && (!sf.hasTag("railway", "abandoned", "razed", "demolished", "removed", "construction", "platform", "proposed"))) { int minZoom = 11; if (sf.hasTag("aeroway", "runway")) { minZoom = 9; } else if (sf.hasTag("aeroway", "taxiway")) { minZoom = 10; } else if (sf.hasTag("service", "yard", "siding", "crossover")) { minZoom = 13; } else if (sf.hasTag("man_made", "pier")) { minZoom = 13; } String kind = "other"; String kindDetail = ""; if (sf.hasTag("aeroway")) { kind = "aeroway"; kindDetail = sf.getString("aeroway"); } else if (sf.hasTag("railway", "disused", "funicular", "light_rail", "miniature", "monorail", "narrow_gauge", "preserved", "subway", "tram")) { kind = "rail"; kindDetail = sf.getString("railway"); minZoom = 14; if (sf.hasTag("railway", "disused")) { minZoom = 15; } } else if (sf.hasTag("railway")) { kind = "rail"; kindDetail = sf.getString("railway"); if (kindDetail.equals("service")) { minZoom = 13; // eg a rail yard if (sf.hasTag("service")) { minZoom = 14; } } } else if (sf.hasTag("ferry")) { kind = "ferry"; kindDetail = sf.getString("ferry"); } else if (sf.hasTag("man_made", "pier")) { kind = "pier"; } else if (sf.hasTag("aerialway")) { kind = "aerialway"; kindDetail = sf.getString("aerialway"); } var feature = features.line(this.name()) .setId(FeatureId.create(sf)) // Core Tilezen schema properties .setAttr("pmap:kind", kind) // Used for client-side label collisions .setAttr("pmap:min_zoom", minZoom + 1) // Core OSM tags for different kinds of places .setAttr("layer", Parse.parseIntOrNull(sf.getString("layer"))) .setAttr("network", sf.getString("network")) .setAttr("ref", sf.getString("ref")) .setAttr("route", sf.getString("route")) .setAttr("service", sf.getString("service")) // DEPRECATION WARNING: Marked for deprecation in v4 schema, do not use these for styling // If an explicate value is needed it should bea kind, or included in kind_detail .setAttr("aerialway", sf.getString("aerialway")) .setAttr("aeroway", sf.getString("aeroway")) .setAttr("highspeed", sf.getString("highspeed")) .setAttr("man_made", sf.getString("pier")) .setAttr("railway", sf.getString("railway")) .setZoomRange(minZoom, 15); // Core Tilezen schema properties if (!kindDetail.isEmpty()) { feature.setAttr("pmap:kind_detail", kindDetail); } // Set "brunnel" (bridge / tunnel) property where "level" = 1 is a bridge, 0 is ground level, and -1 is a tunnel // Because of MapLibre performance and draw order limitations, generally the boolean is sufficent // See also: "layer" for more complicated ±6 layering for more sophisticated graphics libraries if (sf.hasTag("bridge") && !sf.hasTag("bridge", "no")) { feature.setAttr("pmap:level", 1); } else if (sf.hasTag("tunnel") && !sf.hasTag("tunnel", "no")) { feature.setAttr("pmap:level", -1); } else { feature.setAttr("pmap:level", 0); } // Too many small pier lines otherwise if (kind.equals("pier")) { feature.setMinPixelSize(2); } // Server sort features so client label collisions are pre-sorted feature.setSortKey(minZoom); // TODO: (nvkelso 20230623) This should be variable, but 12 is better than 0 for line merging OsmNames.setOsmNames(feature, sf, 12); } } @Override public List<VectorTile.Feature> postProcess(int zoom, List<VectorTile.Feature> items) { return items; } }
protomaps/basemaps
tiles/src/main/java/com/protomaps/basemap/layers/Transit.java
1,456
// Core Tilezen schema properties
line_comment
nl
package com.protomaps.basemap.layers; import com.onthegomap.planetiler.FeatureCollector; import com.onthegomap.planetiler.ForwardingProfile; import com.onthegomap.planetiler.VectorTile; import com.onthegomap.planetiler.reader.SourceFeature; import com.onthegomap.planetiler.util.Parse; import com.protomaps.basemap.feature.FeatureId; import com.protomaps.basemap.names.OsmNames; import java.util.List; public class Transit implements ForwardingProfile.FeatureProcessor, ForwardingProfile.FeaturePostProcessor { @Override public String name() { return "transit"; } @Override public void processFeature(SourceFeature sf, FeatureCollector features) { // todo: exclude railway stations, levels if (sf.canBeLine() && (sf.hasTag("railway") || sf.hasTag("aerialway", "cable_car") || sf.hasTag("man_made", "pier") || sf.hasTag("route", "ferry") || sf.hasTag("aeroway", "runway", "taxiway")) && (!sf.hasTag("railway", "abandoned", "razed", "demolished", "removed", "construction", "platform", "proposed"))) { int minZoom = 11; if (sf.hasTag("aeroway", "runway")) { minZoom = 9; } else if (sf.hasTag("aeroway", "taxiway")) { minZoom = 10; } else if (sf.hasTag("service", "yard", "siding", "crossover")) { minZoom = 13; } else if (sf.hasTag("man_made", "pier")) { minZoom = 13; } String kind = "other"; String kindDetail = ""; if (sf.hasTag("aeroway")) { kind = "aeroway"; kindDetail = sf.getString("aeroway"); } else if (sf.hasTag("railway", "disused", "funicular", "light_rail", "miniature", "monorail", "narrow_gauge", "preserved", "subway", "tram")) { kind = "rail"; kindDetail = sf.getString("railway"); minZoom = 14; if (sf.hasTag("railway", "disused")) { minZoom = 15; } } else if (sf.hasTag("railway")) { kind = "rail"; kindDetail = sf.getString("railway"); if (kindDetail.equals("service")) { minZoom = 13; // eg a rail yard if (sf.hasTag("service")) { minZoom = 14; } } } else if (sf.hasTag("ferry")) { kind = "ferry"; kindDetail = sf.getString("ferry"); } else if (sf.hasTag("man_made", "pier")) { kind = "pier"; } else if (sf.hasTag("aerialway")) { kind = "aerialway"; kindDetail = sf.getString("aerialway"); } var feature = features.line(this.name()) .setId(FeatureId.create(sf)) // Core Tilezen<SUF> .setAttr("pmap:kind", kind) // Used for client-side label collisions .setAttr("pmap:min_zoom", minZoom + 1) // Core OSM tags for different kinds of places .setAttr("layer", Parse.parseIntOrNull(sf.getString("layer"))) .setAttr("network", sf.getString("network")) .setAttr("ref", sf.getString("ref")) .setAttr("route", sf.getString("route")) .setAttr("service", sf.getString("service")) // DEPRECATION WARNING: Marked for deprecation in v4 schema, do not use these for styling // If an explicate value is needed it should bea kind, or included in kind_detail .setAttr("aerialway", sf.getString("aerialway")) .setAttr("aeroway", sf.getString("aeroway")) .setAttr("highspeed", sf.getString("highspeed")) .setAttr("man_made", sf.getString("pier")) .setAttr("railway", sf.getString("railway")) .setZoomRange(minZoom, 15); // Core Tilezen schema properties if (!kindDetail.isEmpty()) { feature.setAttr("pmap:kind_detail", kindDetail); } // Set "brunnel" (bridge / tunnel) property where "level" = 1 is a bridge, 0 is ground level, and -1 is a tunnel // Because of MapLibre performance and draw order limitations, generally the boolean is sufficent // See also: "layer" for more complicated ±6 layering for more sophisticated graphics libraries if (sf.hasTag("bridge") && !sf.hasTag("bridge", "no")) { feature.setAttr("pmap:level", 1); } else if (sf.hasTag("tunnel") && !sf.hasTag("tunnel", "no")) { feature.setAttr("pmap:level", -1); } else { feature.setAttr("pmap:level", 0); } // Too many small pier lines otherwise if (kind.equals("pier")) { feature.setMinPixelSize(2); } // Server sort features so client label collisions are pre-sorted feature.setSortKey(minZoom); // TODO: (nvkelso 20230623) This should be variable, but 12 is better than 0 for line merging OsmNames.setOsmNames(feature, sf, 12); } } @Override public List<VectorTile.Feature> postProcess(int zoom, List<VectorTile.Feature> items) { return items; } }
55474_3
package de.Hero.clickgui.elements.menu; import java.awt.Color; import net.minecraft.client.gui.Gui; import net.minecraft.util.MathHelper; import de.Hero.clickgui.elements.Element; import de.Hero.clickgui.elements.ModuleButton; import de.Hero.clickgui.util.ColorUtil; import de.Hero.clickgui.util.FontUtil; import de.Hero.settings.Setting; /** * Made by HeroCode * it's free to use * but you have to credit me * * @author HeroCode */ public class ElementSlider extends Element { public boolean dragging; /* * Konstrukor */ public ElementSlider(ModuleButton iparent, Setting iset) { parent = iparent; set = iset; dragging = false; super.setup(); } /* * Rendern des Elements */ public void drawScreen(int mouseX, int mouseY, float partialTicks) { String displayval = "" + Math.round(set.getValDouble() * 100D)/ 100D; boolean hoveredORdragged = isSliderHovered(mouseX, mouseY) || dragging; Color temp = ColorUtil.getClickGUIColor(); int color = new Color(temp.getRed(), temp.getGreen(), temp.getBlue(), hoveredORdragged ? 250 : 200).getRGB(); int color2 = new Color(temp.getRed(), temp.getGreen(), temp.getBlue(), hoveredORdragged ? 255 : 230).getRGB(); //selected = iset.getValDouble() / iset.getMax(); double percentBar = (set.getValDouble() - set.getMin())/(set.getMax() - set.getMin()); /* * Die Box und Umrandung rendern */ Gui.drawRect(x, y, x + width, y + height, 0xff1a1a1a); /* * Den Text rendern */ FontUtil.drawString(setstrg, x + 1, y + 2, 0xffffffff); FontUtil.drawString(displayval, x + width - FontUtil.getStringWidth(displayval), y + 2, 0xffffffff); /* * Den Slider rendern */ Gui.drawRect(x, y + 12, x + width, y + 13.5, 0xff101010); Gui.drawRect(x, y + 12, x + (percentBar * width), y + 13.5, color); if(percentBar > 0 && percentBar < 1) Gui.drawRect(x + (percentBar * width)-1, y + 12, x + Math.min((percentBar * width), width), y + 13.5, color2); /* * Neue Value berechnen, wenn dragging */ if (this.dragging) { double diff = set.getMax() - set.getMin(); double val = set.getMin() + (MathHelper.clamp_double((mouseX - x) / width, 0, 1)) * diff; set.setValDouble(val); //Die Value im Setting updaten } } /* * 'true' oder 'false' bedeutet hat der Nutzer damit interagiert und * sollen alle anderen Versuche der Interaktion abgebrochen werden? */ public boolean mouseClicked(int mouseX, int mouseY, int mouseButton) { if (mouseButton == 0 && isSliderHovered(mouseX, mouseY)) { this.dragging = true; return true; } return super.mouseClicked(mouseX, mouseY, mouseButton); } /* * Wenn die Maus losgelassen wird soll aufgehrt werden die Slidervalue zu verndern */ public void mouseReleased(int mouseX, int mouseY, int state) { this.dragging = false; } /* * Einfacher HoverCheck, bentigt damit dragging auf true gesetzt werden kann */ public boolean isSliderHovered(int mouseX, int mouseY) { return mouseX >= x && mouseX <= x + width && mouseY >= y + 11 && mouseY <= y + 14; } }
minty-codes/TutorialClient1.8.8
de/Hero/clickgui/elements/menu/ElementSlider.java
1,099
//selected = iset.getValDouble() / iset.getMax();
line_comment
nl
package de.Hero.clickgui.elements.menu; import java.awt.Color; import net.minecraft.client.gui.Gui; import net.minecraft.util.MathHelper; import de.Hero.clickgui.elements.Element; import de.Hero.clickgui.elements.ModuleButton; import de.Hero.clickgui.util.ColorUtil; import de.Hero.clickgui.util.FontUtil; import de.Hero.settings.Setting; /** * Made by HeroCode * it's free to use * but you have to credit me * * @author HeroCode */ public class ElementSlider extends Element { public boolean dragging; /* * Konstrukor */ public ElementSlider(ModuleButton iparent, Setting iset) { parent = iparent; set = iset; dragging = false; super.setup(); } /* * Rendern des Elements */ public void drawScreen(int mouseX, int mouseY, float partialTicks) { String displayval = "" + Math.round(set.getValDouble() * 100D)/ 100D; boolean hoveredORdragged = isSliderHovered(mouseX, mouseY) || dragging; Color temp = ColorUtil.getClickGUIColor(); int color = new Color(temp.getRed(), temp.getGreen(), temp.getBlue(), hoveredORdragged ? 250 : 200).getRGB(); int color2 = new Color(temp.getRed(), temp.getGreen(), temp.getBlue(), hoveredORdragged ? 255 : 230).getRGB(); //selected =<SUF> double percentBar = (set.getValDouble() - set.getMin())/(set.getMax() - set.getMin()); /* * Die Box und Umrandung rendern */ Gui.drawRect(x, y, x + width, y + height, 0xff1a1a1a); /* * Den Text rendern */ FontUtil.drawString(setstrg, x + 1, y + 2, 0xffffffff); FontUtil.drawString(displayval, x + width - FontUtil.getStringWidth(displayval), y + 2, 0xffffffff); /* * Den Slider rendern */ Gui.drawRect(x, y + 12, x + width, y + 13.5, 0xff101010); Gui.drawRect(x, y + 12, x + (percentBar * width), y + 13.5, color); if(percentBar > 0 && percentBar < 1) Gui.drawRect(x + (percentBar * width)-1, y + 12, x + Math.min((percentBar * width), width), y + 13.5, color2); /* * Neue Value berechnen, wenn dragging */ if (this.dragging) { double diff = set.getMax() - set.getMin(); double val = set.getMin() + (MathHelper.clamp_double((mouseX - x) / width, 0, 1)) * diff; set.setValDouble(val); //Die Value im Setting updaten } } /* * 'true' oder 'false' bedeutet hat der Nutzer damit interagiert und * sollen alle anderen Versuche der Interaktion abgebrochen werden? */ public boolean mouseClicked(int mouseX, int mouseY, int mouseButton) { if (mouseButton == 0 && isSliderHovered(mouseX, mouseY)) { this.dragging = true; return true; } return super.mouseClicked(mouseX, mouseY, mouseButton); } /* * Wenn die Maus losgelassen wird soll aufgehrt werden die Slidervalue zu verndern */ public void mouseReleased(int mouseX, int mouseY, int state) { this.dragging = false; } /* * Einfacher HoverCheck, bentigt damit dragging auf true gesetzt werden kann */ public boolean isSliderHovered(int mouseX, int mouseY) { return mouseX >= x && mouseX <= x + width && mouseY >= y + 11 && mouseY <= y + 14; } }
131421_59
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.qrcode.encoder; import com.google.zxing.WriterException; import com.google.zxing.common.BitArray; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.google.zxing.qrcode.decoder.Version; /** * @author [email protected] (Satoru Takabayashi) - creator * @author [email protected] (Daniel Switkin) - ported from C++ */ final class MatrixUtil { private static final int[][] POSITION_DETECTION_PATTERN = { {1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 1}, {1, 0, 1, 1, 1, 0, 1}, {1, 0, 1, 1, 1, 0, 1}, {1, 0, 1, 1, 1, 0, 1}, {1, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1}, }; private static final int[][] POSITION_ADJUSTMENT_PATTERN = { {1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 1, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 1}, }; // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu. private static final int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = { {-1, -1, -1, -1, -1, -1, -1}, // Version 1 { 6, 18, -1, -1, -1, -1, -1}, // Version 2 { 6, 22, -1, -1, -1, -1, -1}, // Version 3 { 6, 26, -1, -1, -1, -1, -1}, // Version 4 { 6, 30, -1, -1, -1, -1, -1}, // Version 5 { 6, 34, -1, -1, -1, -1, -1}, // Version 6 { 6, 22, 38, -1, -1, -1, -1}, // Version 7 { 6, 24, 42, -1, -1, -1, -1}, // Version 8 { 6, 26, 46, -1, -1, -1, -1}, // Version 9 { 6, 28, 50, -1, -1, -1, -1}, // Version 10 { 6, 30, 54, -1, -1, -1, -1}, // Version 11 { 6, 32, 58, -1, -1, -1, -1}, // Version 12 { 6, 34, 62, -1, -1, -1, -1}, // Version 13 { 6, 26, 46, 66, -1, -1, -1}, // Version 14 { 6, 26, 48, 70, -1, -1, -1}, // Version 15 { 6, 26, 50, 74, -1, -1, -1}, // Version 16 { 6, 30, 54, 78, -1, -1, -1}, // Version 17 { 6, 30, 56, 82, -1, -1, -1}, // Version 18 { 6, 30, 58, 86, -1, -1, -1}, // Version 19 { 6, 34, 62, 90, -1, -1, -1}, // Version 20 { 6, 28, 50, 72, 94, -1, -1}, // Version 21 { 6, 26, 50, 74, 98, -1, -1}, // Version 22 { 6, 30, 54, 78, 102, -1, -1}, // Version 23 { 6, 28, 54, 80, 106, -1, -1}, // Version 24 { 6, 32, 58, 84, 110, -1, -1}, // Version 25 { 6, 30, 58, 86, 114, -1, -1}, // Version 26 { 6, 34, 62, 90, 118, -1, -1}, // Version 27 { 6, 26, 50, 74, 98, 122, -1}, // Version 28 { 6, 30, 54, 78, 102, 126, -1}, // Version 29 { 6, 26, 52, 78, 104, 130, -1}, // Version 30 { 6, 30, 56, 82, 108, 134, -1}, // Version 31 { 6, 34, 60, 86, 112, 138, -1}, // Version 32 { 6, 30, 58, 86, 114, 142, -1}, // Version 33 { 6, 34, 62, 90, 118, 146, -1}, // Version 34 { 6, 30, 54, 78, 102, 126, 150}, // Version 35 { 6, 24, 50, 76, 102, 128, 154}, // Version 36 { 6, 28, 54, 80, 106, 132, 158}, // Version 37 { 6, 32, 58, 84, 110, 136, 162}, // Version 38 { 6, 26, 54, 82, 110, 138, 166}, // Version 39 { 6, 30, 58, 86, 114, 142, 170}, // Version 40 }; // Type info cells at the left top corner. private static final int[][] TYPE_INFO_COORDINATES = { {8, 0}, {8, 1}, {8, 2}, {8, 3}, {8, 4}, {8, 5}, {8, 7}, {8, 8}, {7, 8}, {5, 8}, {4, 8}, {3, 8}, {2, 8}, {1, 8}, {0, 8}, }; // From Appendix D in JISX0510:2004 (p. 67) private static final int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101 // From Appendix C in JISX0510:2004 (p.65). private static final int TYPE_INFO_POLY = 0x537; private static final int TYPE_INFO_MASK_PATTERN = 0x5412; private MatrixUtil() { // do nothing } // Set all cells to -1. -1 means that the cell is empty (not set yet). // // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding // with the ByteMatrix initialized all to zero. static void clearMatrix(ByteMatrix matrix) { matrix.clear((byte) -1); } // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On // success, store the result in "matrix" and return true. static void buildMatrix(BitArray dataBits, ErrorCorrectionLevel ecLevel, Version version, int maskPattern, ByteMatrix matrix) throws WriterException { clearMatrix(matrix); embedBasicPatterns(version, matrix); // Type information appear with any version. embedTypeInfo(ecLevel, maskPattern, matrix); // Version info appear if version >= 7. maybeEmbedVersionInfo(version, matrix); // Data should be embedded at end. embedDataBits(dataBits, maskPattern, matrix); } // Embed basic patterns. On success, modify the matrix and return true. // The basic patterns are: // - Position detection patterns // - Timing patterns // - Dark dot at the left bottom corner // - Position adjustment patterns, if need be static void embedBasicPatterns(Version version, ByteMatrix matrix) throws WriterException { // Let's get started with embedding big squares at corners. embedPositionDetectionPatternsAndSeparators(matrix); // Then, embed the dark dot at the left bottom corner. embedDarkDotAtLeftBottomCorner(matrix); // Position adjustment patterns appear if version >= 2. maybeEmbedPositionAdjustmentPatterns(version, matrix); // Timing patterns should be embedded after position adj. patterns. embedTimingPatterns(matrix); } // Embed type information. On success, modify the matrix. static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) throws WriterException { BitArray typeInfoBits = new BitArray(); makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); for (int i = 0; i < typeInfoBits.getSize(); ++i) { // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in // "typeInfoBits". boolean bit = typeInfoBits.get(typeInfoBits.getSize() - 1 - i); // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). int[] coordinates = TYPE_INFO_COORDINATES[i]; int x1 = coordinates[0]; int y1 = coordinates[1]; matrix.set(x1, y1, bit); int x2; int y2; if (i < 8) { // Right top corner. x2 = matrix.getWidth() - i - 1; y2 = 8; } else { // Left bottom corner. x2 = 8; y2 = matrix.getHeight() - 7 + (i - 8); } matrix.set(x2, y2, bit); } } // Embed version information if need be. On success, modify the matrix and return true. // See 8.10 of JISX0510:2004 (p.47) for how to embed version information. static void maybeEmbedVersionInfo(Version version, ByteMatrix matrix) throws WriterException { if (version.getVersionNumber() < 7) { // Version info is necessary if version >= 7. return; // Don't need version info. } BitArray versionInfoBits = new BitArray(); makeVersionInfoBits(version, versionInfoBits); int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. for (int i = 0; i < 6; ++i) { for (int j = 0; j < 3; ++j) { // Place bits in LSB (least significant bit) to MSB order. boolean bit = versionInfoBits.get(bitIndex); bitIndex--; // Left bottom corner. matrix.set(i, matrix.getHeight() - 11 + j, bit); // Right bottom corner. matrix.set(matrix.getHeight() - 11 + j, i, bit); } } } // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. // For debugging purposes, it skips masking process if "getMaskPattern" is -1. // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. static void embedDataBits(BitArray dataBits, int maskPattern, ByteMatrix matrix) throws WriterException { int bitIndex = 0; int direction = -1; // Start from the right bottom cell. int x = matrix.getWidth() - 1; int y = matrix.getHeight() - 1; while (x > 0) { // Skip the vertical timing pattern. if (x == 6) { x -= 1; } while (y >= 0 && y < matrix.getHeight()) { for (int i = 0; i < 2; ++i) { int xx = x - i; // Skip the cell if it's not empty. if (!isEmpty(matrix.get(xx, y))) { continue; } boolean bit; if (bitIndex < dataBits.getSize()) { bit = dataBits.get(bitIndex); ++bitIndex; } else { // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described // in 8.4.9 of JISX0510:2004 (p. 24). bit = false; } // Skip masking if mask_pattern is -1. if (maskPattern != -1 && MaskUtil.getDataMaskBit(maskPattern, xx, y)) { bit = !bit; } matrix.set(xx, y, bit); } y += direction; } direction = -direction; // Reverse the direction. y += direction; x -= 2; // Move to the left. } // All bits should be consumed. if (bitIndex != dataBits.getSize()) { throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.getSize()); } } // Return the position of the most significant bit set (to one) in the "value". The most // significant bit is position 32. If there is no bit set, return 0. Examples: // - findMSBSet(0) => 0 // - findMSBSet(1) => 1 // - findMSBSet(255) => 8 static int findMSBSet(int value) { return 32 - Integer.numberOfLeadingZeros(value); } // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH // code is used for encoding type information and version information. // Example: Calculation of version information of 7. // f(x) is created from 7. // - 7 = 000111 in 6 bits // - f(x) = x^2 + x^1 + x^0 // g(x) is given by the standard (p. 67) // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 // Multiply f(x) by x^(18 - 6) // - f'(x) = f(x) * x^(18 - 6) // - f'(x) = x^14 + x^13 + x^12 // Calculate the remainder of f'(x) / g(x) // x^2 // __________________________________________________ // g(x) )x^14 + x^13 + x^12 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2 // -------------------------------------------------- // x^11 + x^10 + x^7 + x^4 + x^2 // // The remainder is x^11 + x^10 + x^7 + x^4 + x^2 // Encode it in binary: 110010010100 // The return value is 0xc94 (1100 1001 0100) // // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit // operations. We don't care if coefficients are positive or negative. static int calculateBCHCode(int value, int poly) { if (poly == 0) { throw new IllegalArgumentException("0 polynomial"); } // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 // from 13 to make it 12. int msbSetInPoly = findMSBSet(poly); value <<= msbSetInPoly - 1; // Do the division business using exclusive-or operations. while (findMSBSet(value) >= msbSetInPoly) { value ^= poly << (findMSBSet(value) - msbSetInPoly); } // Now the "value" is the remainder (i.e. the BCH code) return value; } // Make bit vector of type information. On success, store the result in "bits" and return true. // Encode error correction level and mask pattern. See 8.9 of // JISX0510:2004 (p.45) for details. static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits) throws WriterException { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new WriterException("Invalid mask pattern"); } int typeInfo = (ecLevel.getBits() << 3) | maskPattern; bits.appendBits(typeInfo, 5); int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); bits.appendBits(bchCode, 10); BitArray maskBits = new BitArray(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.getSize() != 15) { // Just in case. throw new WriterException("should not happen but we got: " + bits.getSize()); } } // Make bit vector of version information. On success, store the result in "bits" and return true. // See 8.10 of JISX0510:2004 (p.45) for details. static void makeVersionInfoBits(Version version, BitArray bits) throws WriterException { bits.appendBits(version.getVersionNumber(), 6); int bchCode = calculateBCHCode(version.getVersionNumber(), VERSION_INFO_POLY); bits.appendBits(bchCode, 12); if (bits.getSize() != 18) { // Just in case. throw new WriterException("should not happen but we got: " + bits.getSize()); } } // Check if "value" is empty. private static boolean isEmpty(int value) { return value == -1; } private static void embedTimingPatterns(ByteMatrix matrix) { // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical // separation patterns (size 1). Thus, 8 = 7 + 1. for (int i = 8; i < matrix.getWidth() - 8; ++i) { int bit = (i + 1) % 2; // Horizontal line. if (isEmpty(matrix.get(i, 6))) { matrix.set(i, 6, bit); } // Vertical line. if (isEmpty(matrix.get(6, i))) { matrix.set(6, i, bit); } } } // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException { if (matrix.get(8, matrix.getHeight() - 8) == 0) { throw new WriterException(); } matrix.set(8, matrix.getHeight() - 8, 1); } private static void embedHorizontalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { for (int x = 0; x < 8; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart))) { throw new WriterException(); } matrix.set(xStart + x, yStart, 0); } } private static void embedVerticalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { for (int y = 0; y < 7; ++y) { if (!isEmpty(matrix.get(xStart, yStart + y))) { throw new WriterException(); } matrix.set(xStart, yStart + y, 0); } } private static void embedPositionAdjustmentPattern(int xStart, int yStart, ByteMatrix matrix) { for (int y = 0; y < 5; ++y) { int[] patternY = POSITION_ADJUSTMENT_PATTERN[y]; for (int x = 0; x < 5; ++x) { matrix.set(xStart + x, yStart + y, patternY[x]); } } } private static void embedPositionDetectionPattern(int xStart, int yStart, ByteMatrix matrix) { for (int y = 0; y < 7; ++y) { int[] patternY = POSITION_DETECTION_PATTERN[y]; for (int x = 0; x < 7; ++x) { matrix.set(xStart + x, yStart + y, patternY[x]); } } } // Embed position detection patterns and surrounding vertical/horizontal separators. private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException { // Embed three big squares at corners. int pdpWidth = POSITION_DETECTION_PATTERN[0].length; // Left top corner. embedPositionDetectionPattern(0, 0, matrix); // Right top corner. embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix); // Left bottom corner. embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix); // Embed horizontal separation patterns around the squares. int hspWidth = 8; // Left top corner. embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); // Right top corner. embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth, hspWidth - 1, matrix); // Left bottom corner. embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix); // Embed vertical separation patterns around the squares. int vspSize = 7; // Left top corner. embedVerticalSeparationPattern(vspSize, 0, matrix); // Right top corner. embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix); // Left bottom corner. embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize, matrix); } // Embed position adjustment patterns if need be. private static void maybeEmbedPositionAdjustmentPatterns(Version version, ByteMatrix matrix) { if (version.getVersionNumber() < 2) { // The patterns appear if version >= 2 return; } int index = version.getVersionNumber() - 1; int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; for (int y : coordinates) { if (y >= 0) { for (int x : coordinates) { if (x >= 0 && isEmpty(matrix.get(x, y))) { // If the cell is unset, we embed the position adjustment pattern here. // -2 is necessary since the x/y coordinates point to the center of the pattern, not the // left top corner. embedPositionAdjustmentPattern(x - 2, y - 2, matrix); } } } } } }
daisuke-nomura/zxing
core/src/main/java/com/google/zxing/qrcode/encoder/MatrixUtil.java
6,596
// - 7 = 000111 in 6 bits
line_comment
nl
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.qrcode.encoder; import com.google.zxing.WriterException; import com.google.zxing.common.BitArray; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.google.zxing.qrcode.decoder.Version; /** * @author [email protected] (Satoru Takabayashi) - creator * @author [email protected] (Daniel Switkin) - ported from C++ */ final class MatrixUtil { private static final int[][] POSITION_DETECTION_PATTERN = { {1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 1}, {1, 0, 1, 1, 1, 0, 1}, {1, 0, 1, 1, 1, 0, 1}, {1, 0, 1, 1, 1, 0, 1}, {1, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1}, }; private static final int[][] POSITION_ADJUSTMENT_PATTERN = { {1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 1, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 1}, }; // From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu. private static final int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = { {-1, -1, -1, -1, -1, -1, -1}, // Version 1 { 6, 18, -1, -1, -1, -1, -1}, // Version 2 { 6, 22, -1, -1, -1, -1, -1}, // Version 3 { 6, 26, -1, -1, -1, -1, -1}, // Version 4 { 6, 30, -1, -1, -1, -1, -1}, // Version 5 { 6, 34, -1, -1, -1, -1, -1}, // Version 6 { 6, 22, 38, -1, -1, -1, -1}, // Version 7 { 6, 24, 42, -1, -1, -1, -1}, // Version 8 { 6, 26, 46, -1, -1, -1, -1}, // Version 9 { 6, 28, 50, -1, -1, -1, -1}, // Version 10 { 6, 30, 54, -1, -1, -1, -1}, // Version 11 { 6, 32, 58, -1, -1, -1, -1}, // Version 12 { 6, 34, 62, -1, -1, -1, -1}, // Version 13 { 6, 26, 46, 66, -1, -1, -1}, // Version 14 { 6, 26, 48, 70, -1, -1, -1}, // Version 15 { 6, 26, 50, 74, -1, -1, -1}, // Version 16 { 6, 30, 54, 78, -1, -1, -1}, // Version 17 { 6, 30, 56, 82, -1, -1, -1}, // Version 18 { 6, 30, 58, 86, -1, -1, -1}, // Version 19 { 6, 34, 62, 90, -1, -1, -1}, // Version 20 { 6, 28, 50, 72, 94, -1, -1}, // Version 21 { 6, 26, 50, 74, 98, -1, -1}, // Version 22 { 6, 30, 54, 78, 102, -1, -1}, // Version 23 { 6, 28, 54, 80, 106, -1, -1}, // Version 24 { 6, 32, 58, 84, 110, -1, -1}, // Version 25 { 6, 30, 58, 86, 114, -1, -1}, // Version 26 { 6, 34, 62, 90, 118, -1, -1}, // Version 27 { 6, 26, 50, 74, 98, 122, -1}, // Version 28 { 6, 30, 54, 78, 102, 126, -1}, // Version 29 { 6, 26, 52, 78, 104, 130, -1}, // Version 30 { 6, 30, 56, 82, 108, 134, -1}, // Version 31 { 6, 34, 60, 86, 112, 138, -1}, // Version 32 { 6, 30, 58, 86, 114, 142, -1}, // Version 33 { 6, 34, 62, 90, 118, 146, -1}, // Version 34 { 6, 30, 54, 78, 102, 126, 150}, // Version 35 { 6, 24, 50, 76, 102, 128, 154}, // Version 36 { 6, 28, 54, 80, 106, 132, 158}, // Version 37 { 6, 32, 58, 84, 110, 136, 162}, // Version 38 { 6, 26, 54, 82, 110, 138, 166}, // Version 39 { 6, 30, 58, 86, 114, 142, 170}, // Version 40 }; // Type info cells at the left top corner. private static final int[][] TYPE_INFO_COORDINATES = { {8, 0}, {8, 1}, {8, 2}, {8, 3}, {8, 4}, {8, 5}, {8, 7}, {8, 8}, {7, 8}, {5, 8}, {4, 8}, {3, 8}, {2, 8}, {1, 8}, {0, 8}, }; // From Appendix D in JISX0510:2004 (p. 67) private static final int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101 // From Appendix C in JISX0510:2004 (p.65). private static final int TYPE_INFO_POLY = 0x537; private static final int TYPE_INFO_MASK_PATTERN = 0x5412; private MatrixUtil() { // do nothing } // Set all cells to -1. -1 means that the cell is empty (not set yet). // // JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding // with the ByteMatrix initialized all to zero. static void clearMatrix(ByteMatrix matrix) { matrix.clear((byte) -1); } // Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On // success, store the result in "matrix" and return true. static void buildMatrix(BitArray dataBits, ErrorCorrectionLevel ecLevel, Version version, int maskPattern, ByteMatrix matrix) throws WriterException { clearMatrix(matrix); embedBasicPatterns(version, matrix); // Type information appear with any version. embedTypeInfo(ecLevel, maskPattern, matrix); // Version info appear if version >= 7. maybeEmbedVersionInfo(version, matrix); // Data should be embedded at end. embedDataBits(dataBits, maskPattern, matrix); } // Embed basic patterns. On success, modify the matrix and return true. // The basic patterns are: // - Position detection patterns // - Timing patterns // - Dark dot at the left bottom corner // - Position adjustment patterns, if need be static void embedBasicPatterns(Version version, ByteMatrix matrix) throws WriterException { // Let's get started with embedding big squares at corners. embedPositionDetectionPatternsAndSeparators(matrix); // Then, embed the dark dot at the left bottom corner. embedDarkDotAtLeftBottomCorner(matrix); // Position adjustment patterns appear if version >= 2. maybeEmbedPositionAdjustmentPatterns(version, matrix); // Timing patterns should be embedded after position adj. patterns. embedTimingPatterns(matrix); } // Embed type information. On success, modify the matrix. static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) throws WriterException { BitArray typeInfoBits = new BitArray(); makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); for (int i = 0; i < typeInfoBits.getSize(); ++i) { // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in // "typeInfoBits". boolean bit = typeInfoBits.get(typeInfoBits.getSize() - 1 - i); // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). int[] coordinates = TYPE_INFO_COORDINATES[i]; int x1 = coordinates[0]; int y1 = coordinates[1]; matrix.set(x1, y1, bit); int x2; int y2; if (i < 8) { // Right top corner. x2 = matrix.getWidth() - i - 1; y2 = 8; } else { // Left bottom corner. x2 = 8; y2 = matrix.getHeight() - 7 + (i - 8); } matrix.set(x2, y2, bit); } } // Embed version information if need be. On success, modify the matrix and return true. // See 8.10 of JISX0510:2004 (p.47) for how to embed version information. static void maybeEmbedVersionInfo(Version version, ByteMatrix matrix) throws WriterException { if (version.getVersionNumber() < 7) { // Version info is necessary if version >= 7. return; // Don't need version info. } BitArray versionInfoBits = new BitArray(); makeVersionInfoBits(version, versionInfoBits); int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. for (int i = 0; i < 6; ++i) { for (int j = 0; j < 3; ++j) { // Place bits in LSB (least significant bit) to MSB order. boolean bit = versionInfoBits.get(bitIndex); bitIndex--; // Left bottom corner. matrix.set(i, matrix.getHeight() - 11 + j, bit); // Right bottom corner. matrix.set(matrix.getHeight() - 11 + j, i, bit); } } } // Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true. // For debugging purposes, it skips masking process if "getMaskPattern" is -1. // See 8.7 of JISX0510:2004 (p.38) for how to embed data bits. static void embedDataBits(BitArray dataBits, int maskPattern, ByteMatrix matrix) throws WriterException { int bitIndex = 0; int direction = -1; // Start from the right bottom cell. int x = matrix.getWidth() - 1; int y = matrix.getHeight() - 1; while (x > 0) { // Skip the vertical timing pattern. if (x == 6) { x -= 1; } while (y >= 0 && y < matrix.getHeight()) { for (int i = 0; i < 2; ++i) { int xx = x - i; // Skip the cell if it's not empty. if (!isEmpty(matrix.get(xx, y))) { continue; } boolean bit; if (bitIndex < dataBits.getSize()) { bit = dataBits.get(bitIndex); ++bitIndex; } else { // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described // in 8.4.9 of JISX0510:2004 (p. 24). bit = false; } // Skip masking if mask_pattern is -1. if (maskPattern != -1 && MaskUtil.getDataMaskBit(maskPattern, xx, y)) { bit = !bit; } matrix.set(xx, y, bit); } y += direction; } direction = -direction; // Reverse the direction. y += direction; x -= 2; // Move to the left. } // All bits should be consumed. if (bitIndex != dataBits.getSize()) { throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.getSize()); } } // Return the position of the most significant bit set (to one) in the "value". The most // significant bit is position 32. If there is no bit set, return 0. Examples: // - findMSBSet(0) => 0 // - findMSBSet(1) => 1 // - findMSBSet(255) => 8 static int findMSBSet(int value) { return 32 - Integer.numberOfLeadingZeros(value); } // Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH // code is used for encoding type information and version information. // Example: Calculation of version information of 7. // f(x) is created from 7. // - 7<SUF> // - f(x) = x^2 + x^1 + x^0 // g(x) is given by the standard (p. 67) // - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1 // Multiply f(x) by x^(18 - 6) // - f'(x) = f(x) * x^(18 - 6) // - f'(x) = x^14 + x^13 + x^12 // Calculate the remainder of f'(x) / g(x) // x^2 // __________________________________________________ // g(x) )x^14 + x^13 + x^12 // x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2 // -------------------------------------------------- // x^11 + x^10 + x^7 + x^4 + x^2 // // The remainder is x^11 + x^10 + x^7 + x^4 + x^2 // Encode it in binary: 110010010100 // The return value is 0xc94 (1100 1001 0100) // // Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit // operations. We don't care if coefficients are positive or negative. static int calculateBCHCode(int value, int poly) { if (poly == 0) { throw new IllegalArgumentException("0 polynomial"); } // If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1 // from 13 to make it 12. int msbSetInPoly = findMSBSet(poly); value <<= msbSetInPoly - 1; // Do the division business using exclusive-or operations. while (findMSBSet(value) >= msbSetInPoly) { value ^= poly << (findMSBSet(value) - msbSetInPoly); } // Now the "value" is the remainder (i.e. the BCH code) return value; } // Make bit vector of type information. On success, store the result in "bits" and return true. // Encode error correction level and mask pattern. See 8.9 of // JISX0510:2004 (p.45) for details. static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits) throws WriterException { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new WriterException("Invalid mask pattern"); } int typeInfo = (ecLevel.getBits() << 3) | maskPattern; bits.appendBits(typeInfo, 5); int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); bits.appendBits(bchCode, 10); BitArray maskBits = new BitArray(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.getSize() != 15) { // Just in case. throw new WriterException("should not happen but we got: " + bits.getSize()); } } // Make bit vector of version information. On success, store the result in "bits" and return true. // See 8.10 of JISX0510:2004 (p.45) for details. static void makeVersionInfoBits(Version version, BitArray bits) throws WriterException { bits.appendBits(version.getVersionNumber(), 6); int bchCode = calculateBCHCode(version.getVersionNumber(), VERSION_INFO_POLY); bits.appendBits(bchCode, 12); if (bits.getSize() != 18) { // Just in case. throw new WriterException("should not happen but we got: " + bits.getSize()); } } // Check if "value" is empty. private static boolean isEmpty(int value) { return value == -1; } private static void embedTimingPatterns(ByteMatrix matrix) { // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical // separation patterns (size 1). Thus, 8 = 7 + 1. for (int i = 8; i < matrix.getWidth() - 8; ++i) { int bit = (i + 1) % 2; // Horizontal line. if (isEmpty(matrix.get(i, 6))) { matrix.set(i, 6, bit); } // Vertical line. if (isEmpty(matrix.get(6, i))) { matrix.set(6, i, bit); } } } // Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46) private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException { if (matrix.get(8, matrix.getHeight() - 8) == 0) { throw new WriterException(); } matrix.set(8, matrix.getHeight() - 8, 1); } private static void embedHorizontalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { for (int x = 0; x < 8; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart))) { throw new WriterException(); } matrix.set(xStart + x, yStart, 0); } } private static void embedVerticalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { for (int y = 0; y < 7; ++y) { if (!isEmpty(matrix.get(xStart, yStart + y))) { throw new WriterException(); } matrix.set(xStart, yStart + y, 0); } } private static void embedPositionAdjustmentPattern(int xStart, int yStart, ByteMatrix matrix) { for (int y = 0; y < 5; ++y) { int[] patternY = POSITION_ADJUSTMENT_PATTERN[y]; for (int x = 0; x < 5; ++x) { matrix.set(xStart + x, yStart + y, patternY[x]); } } } private static void embedPositionDetectionPattern(int xStart, int yStart, ByteMatrix matrix) { for (int y = 0; y < 7; ++y) { int[] patternY = POSITION_DETECTION_PATTERN[y]; for (int x = 0; x < 7; ++x) { matrix.set(xStart + x, yStart + y, patternY[x]); } } } // Embed position detection patterns and surrounding vertical/horizontal separators. private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException { // Embed three big squares at corners. int pdpWidth = POSITION_DETECTION_PATTERN[0].length; // Left top corner. embedPositionDetectionPattern(0, 0, matrix); // Right top corner. embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix); // Left bottom corner. embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix); // Embed horizontal separation patterns around the squares. int hspWidth = 8; // Left top corner. embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); // Right top corner. embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth, hspWidth - 1, matrix); // Left bottom corner. embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix); // Embed vertical separation patterns around the squares. int vspSize = 7; // Left top corner. embedVerticalSeparationPattern(vspSize, 0, matrix); // Right top corner. embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix); // Left bottom corner. embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize, matrix); } // Embed position adjustment patterns if need be. private static void maybeEmbedPositionAdjustmentPatterns(Version version, ByteMatrix matrix) { if (version.getVersionNumber() < 2) { // The patterns appear if version >= 2 return; } int index = version.getVersionNumber() - 1; int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; for (int y : coordinates) { if (y >= 0) { for (int x : coordinates) { if (x >= 0 && isEmpty(matrix.get(x, y))) { // If the cell is unset, we embed the position adjustment pattern here. // -2 is necessary since the x/y coordinates point to the center of the pattern, not the // left top corner. embedPositionAdjustmentPattern(x - 2, y - 2, matrix); } } } } } }
174363_0
package nl.novi.les16jwt.security; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.lang.NonNull; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; // https://edhub.novi.nl/study/courses/319/content/12903 // Het verifiëren van een JWT-token dient ook in de filter chain te worden opgenomen. // Dat kan door een RequestFilter te implementeren en die aan de filter chain toe te voegen. // Tenslotte moet deze RequestFilter worden toegevoegd aan de filter chain in SecurityConfig.java @Component public class JwtRequestFilter extends OncePerRequestFilter { private final UserDetailsService userDetailsService; private final JwtService jwtService; public JwtRequestFilter(JwtService jwtService, UserDetailsService udService) { this.jwtService = jwtService; this.userDetailsService = udService; } @Override protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { final String authorizationHeader = request.getHeader("Authorization"); String username = null; String jwt = null; if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) { jwt = authorizationHeader.substring(7); username = jwtService.extractUsername(jwt); } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); if (jwtService.validateToken(jwt, userDetails)) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities() ); usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } } filterChain.doFilter(request, response); } }
Aphelion-im/Les-16-uitwerking-opdracht-jwt
src/main/java/nl/novi/les16jwt/security/JwtRequestFilter.java
611
// Het verifiëren van een JWT-token dient ook in de filter chain te worden opgenomen.
line_comment
nl
package nl.novi.les16jwt.security; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.lang.NonNull; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; // https://edhub.novi.nl/study/courses/319/content/12903 // Het verifiëren<SUF> // Dat kan door een RequestFilter te implementeren en die aan de filter chain toe te voegen. // Tenslotte moet deze RequestFilter worden toegevoegd aan de filter chain in SecurityConfig.java @Component public class JwtRequestFilter extends OncePerRequestFilter { private final UserDetailsService userDetailsService; private final JwtService jwtService; public JwtRequestFilter(JwtService jwtService, UserDetailsService udService) { this.jwtService = jwtService; this.userDetailsService = udService; } @Override protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException { final String authorizationHeader = request.getHeader("Authorization"); String username = null; String jwt = null; if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) { jwt = authorizationHeader.substring(7); username = jwtService.extractUsername(jwt); } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); if (jwtService.validateToken(jwt, userDetails)) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities() ); usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } } filterChain.doFilter(request, response); } }
2248_29
package nl.irp.sepa.sdd; import static com.google.common.base.Preconditions.checkArgument; import static nl.irp.sepa.sdd.Utils.createAccount; import static nl.irp.sepa.sdd.Utils.createAmount; import static nl.irp.sepa.sdd.Utils.createFinInstnId; import static nl.irp.sepa.sdd.Utils.createIdParty; import static nl.irp.sepa.sdd.Utils.createParty; import static nl.irp.sepa.sdd.Utils.createPaymentIdentification; import static nl.irp.sepa.sdd.Utils.createRmtInf; import static nl.irp.sepa.sdd.Utils.createXMLGregorianCalendar; import static nl.irp.sepa.sdd.Utils.createXMLGregorianCalendarDate; import iso.std.iso._20022.tech.xsd.pain_008_001.ChargeBearerType1Code; import iso.std.iso._20022.tech.xsd.pain_008_001.CustomerDirectDebitInitiationV02; import iso.std.iso._20022.tech.xsd.pain_008_001.DirectDebitTransaction6; import iso.std.iso._20022.tech.xsd.pain_008_001.DirectDebitTransactionInformation9; import iso.std.iso._20022.tech.xsd.pain_008_001.Document; import iso.std.iso._20022.tech.xsd.pain_008_001.GroupHeader39; import iso.std.iso._20022.tech.xsd.pain_008_001.LocalInstrument2Choice; import iso.std.iso._20022.tech.xsd.pain_008_001.MandateRelatedInformation6; import iso.std.iso._20022.tech.xsd.pain_008_001.ObjectFactory; import iso.std.iso._20022.tech.xsd.pain_008_001.PaymentInstructionInformation4; import iso.std.iso._20022.tech.xsd.pain_008_001.PaymentMethod2Code; import iso.std.iso._20022.tech.xsd.pain_008_001.PaymentTypeInformation20; import iso.std.iso._20022.tech.xsd.pain_008_001.Purpose2Choice; import iso.std.iso._20022.tech.xsd.pain_008_001.SequenceType1Code; import iso.std.iso._20022.tech.xsd.pain_008_001.ServiceLevel8Choice; import java.io.OutputStream; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.UUID; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.joda.time.LocalDate; /** * This document describes the Implementation Guidelines for the XML SEPA Direct Debit Initiation message * UNIFI (ISO20022) - “pain.008.001.02” in the Netherlands. * @author "Jasper Krijgsman <[email protected]>" * */ public class DirectDebitInitiation { private Document document = new Document(); private CustomerDirectDebitInitiationV02 customerDirectDebitInitiationV02; private GroupHeader39 groupHeader; public DirectDebitInitiation() { customerDirectDebitInitiationV02 = new CustomerDirectDebitInitiationV02(); document.setCstmrDrctDbtInitn(customerDirectDebitInitiationV02); } /** * Set of characteristics shared by all individual transactions included in the message. * @param msgId Point to point reference, assigned by the instructing party and sent to * the next party in the chain, to unambiguously identify the message. * @param name * @param date */ public void buildGroupHeader(String msgId, String name, Date date) { groupHeader = new GroupHeader39(); // if no msgId is given create one if(msgId==null) msgId = UUID.randomUUID().toString().replaceAll("-", ""); checkArgument(msgId.length()<=35, "length of setMsgId is more than 35"); checkArgument(msgId.length()>1, "length of setMsgId is less than 1"); groupHeader.setMsgId(msgId); // Date and time at which the message was created. groupHeader.setCreDtTm( createXMLGregorianCalendar(date)); // Number of individual transactions contained in the message. groupHeader.setNbOfTxs("0"); //Total of all individual amounts included in the message. groupHeader.setCtrlSum(BigDecimal.ZERO); // Party that initiates the payment. groupHeader.setInitgPty( createParty(name) ); customerDirectDebitInitiationV02.setGrpHdr(groupHeader); } public void write(OutputStream os) throws JAXBException { JAXBContext jc = JAXBContext.newInstance(Document.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // The UTF-8 character encoding standard must be used in the UNIFI messages. marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.marshal(new ObjectFactory().createDocument(document), os); } public PaymentInstruction paymentInstruction( String pmtInfId, Date reqdColltnDt, String creditor, SequenceType1Code type, String creditorCountry, List<String> addressLines, String creditorAccount, String creditorBic) { PaymentInstruction paymentInstruction = new PaymentInstruction( pmtInfId, reqdColltnDt, creditor, type, creditorCountry, addressLines, creditorAccount, creditorBic); this.customerDirectDebitInitiationV02.getPmtInf().add(paymentInstruction.getPaymentInstructionInformation()); return paymentInstruction; } public class PaymentInstruction { private PaymentInstructionInformation4 paymentInstructionInformation; /** * * @param pmtInfId * @param reqdColltnDt Date and time at which the creditor requests that the amount of money is to be * collected from the debtor. */ public PaymentInstruction( String pmtInfId, Date reqdColltnDt, String creditor, SequenceType1Code type, String creditorCountry, List<String> addressLines, String creditorAccount, String creditorBic) { paymentInstructionInformation = new PaymentInstructionInformation4(); // Unique identification, as assigned by a sending party, to // unambiguously identify the payment information group within the message. checkArgument(pmtInfId.length()<=35, "length of pmtInfId is more than 35"); checkArgument(pmtInfId.length()>1, "length of pmtInfId is less than 1"); paymentInstructionInformation.setPmtInfId(pmtInfId); // Specifies the means of payment that will be used to move the amount of money. // DD=DirectDebit paymentInstructionInformation.setPmtMtd(PaymentMethod2Code.DD); // TODO paymentInstructionInformation.setNbOfTxs("0"); // TODO paymentInstructionInformation.setCtrlSum(BigDecimal.ZERO); // TODO paymentInstructionInformation.setPmtTpInf(makePaymentTypeInformation(type)); // Date and time at which the creditor requests that the amount of money is to be // collected from the debtor. paymentInstructionInformation.setReqdColltnDt( createXMLGregorianCalendarDate(reqdColltnDt) ); // Party to which an amount of money is due. paymentInstructionInformation.setCdtr( createParty(creditor, creditorCountry, addressLines) ); // Unambiguous identification of the account of the creditor to which a credit entry will // be posted as a result of the payment transaction. Only IBAN is allowed. paymentInstructionInformation.setCdtrAcct( createAccount(creditorAccount) ); paymentInstructionInformation.setCdtrAgt( createFinInstnId(creditorBic) ); paymentInstructionInformation.setChrgBr(ChargeBearerType1Code.SLEV); } public DirectDebitTransactionInformation9 addTransaction( String instructionIdentification, String endToEndIdentification, BigDecimal amount, String mandateId, LocalDate dateOfSignature, String cdtrSchmeId, String debtor, String debtorIban, String debtorBic, String debtorCtry, List<String> debtorAdrLine, String remittanceInformation) { DirectDebitTransactionInformation9 directDebitTransactionInformation = new DirectDebitTransactionInformation9(); // Set of elements used to reference a payment instruction. directDebitTransactionInformation.setPmtId( createPaymentIdentification(instructionIdentification, endToEndIdentification)); // Amount of money to be moved between the debtor and creditor, before deduction // of charges, expressed in the currency as ordered by the initiating party. directDebitTransactionInformation.setInstdAmt( createAmount(amount) ); //TODO: directDebitTransactionInformation.setDrctDbtTx(t(mandateId, dateOfSignature, cdtrSchmeId)); // Financial institution servicing an account for the debtor. directDebitTransactionInformation.setDbtrAgt( createFinInstnId(debtorBic) ); // Party that owes an amount of money to the (ultimate) creditor. directDebitTransactionInformation.setDbtr( createParty(debtor) ); directDebitTransactionInformation.setDbtrAcct( createAccount(debtorIban) ); //TODO: Purpose2Choice purpose = new Purpose2Choice(); purpose.setCd("OTHR"); directDebitTransactionInformation.setPurp(purpose); directDebitTransactionInformation.setRmtInf( createRmtInf(remittanceInformation) ); paymentInstructionInformation.getDrctDbtTxInf().add(directDebitTransactionInformation); // TODO: BigDecimal ctrlSum = groupHeader.getCtrlSum(); ctrlSum = ctrlSum.add(amount); groupHeader.setCtrlSum(ctrlSum); int nbOfTxs = Integer.parseInt(groupHeader.getNbOfTxs()); nbOfTxs = nbOfTxs+1; groupHeader.setNbOfTxs(String.valueOf(nbOfTxs)); // TODO: BigDecimal ictrlSum = paymentInstructionInformation.getCtrlSum(); ictrlSum = ictrlSum.add(amount); paymentInstructionInformation.setCtrlSum(ictrlSum); int inbOfTxs = Integer.parseInt(paymentInstructionInformation.getNbOfTxs()); inbOfTxs = inbOfTxs+1; paymentInstructionInformation.setNbOfTxs(String.valueOf(inbOfTxs)); return directDebitTransactionInformation; } public PaymentInstructionInformation4 getPaymentInstructionInformation() { return paymentInstructionInformation; } private PaymentTypeInformation20 makePaymentTypeInformation(SequenceType1Code type) { // Payment Type Information PaymentTypeInformation20 paymentTypeInformation = new PaymentTypeInformation20(); ServiceLevel8Choice serviceLevel8Choice = new ServiceLevel8Choice(); serviceLevel8Choice.setCd("SEPA");//Vaste waarde 'SEPA' paymentTypeInformation.setSvcLvl(serviceLevel8Choice); LocalInstrument2Choice localInstrument = new LocalInstrument2Choice(); localInstrument.setCd("CORE"); // "CORE" voor incasso's van particulieren paymentTypeInformation.setLclInstrm(localInstrument); //FRST eerste incasso binnen een serie op hetzelfde mandaat //RCUR vervolgincasso binnen hetzelfde mandaat //FNAL laatste incasso binnen hetzelfde mandaat //OOFF enkelvoudige incasso zonder repetering // Als de "Amendment indicator" (veld 2.50) op 'true' staat en de // "Original Debtor Agent"(veld 2.58) is "SMNDA" dan moet "FRST" gekozen worden // Na een afwijzing van een "FRST" of "OOFF" moet een herhaling als "FRST" aangegeven worden // Als een "FRST" gestorneerd of geretourneerd wordt (alleen bij type "CORE") moet deze als "RCUR" ingestuurd worden // Als een "OOFF" gestorneerd of geretourneerd wordt (alleen bij type "CORE") kan deze alleen met een nieuw mandaat ingestuurd worden paymentTypeInformation.setSeqTp(type); return paymentTypeInformation; } private DirectDebitTransaction6 t(String mandateId, LocalDate dtOfSgntr, String cdtrSchmeId ) { DirectDebitTransaction6 transaction = new DirectDebitTransaction6(); MandateRelatedInformation6 mandateInf = new MandateRelatedInformation6(); mandateInf.setMndtId(mandateId); mandateInf.setDtOfSgntr( createXMLGregorianCalendarDate(dtOfSgntr.toDate())); mandateInf.setAmdmntInd(false); transaction.setMndtRltdInf(mandateInf); //// transaction.setCdtrSchmeId(createIdParty(cdtrSchmeId)); return transaction; } } }
jasperkrijgsman/dutch-sepa-iso20022
src/main/java/nl/irp/sepa/sdd/DirectDebitInitiation.java
3,358
// Als de "Amendment indicator" (veld 2.50) op 'true' staat en de
line_comment
nl
package nl.irp.sepa.sdd; import static com.google.common.base.Preconditions.checkArgument; import static nl.irp.sepa.sdd.Utils.createAccount; import static nl.irp.sepa.sdd.Utils.createAmount; import static nl.irp.sepa.sdd.Utils.createFinInstnId; import static nl.irp.sepa.sdd.Utils.createIdParty; import static nl.irp.sepa.sdd.Utils.createParty; import static nl.irp.sepa.sdd.Utils.createPaymentIdentification; import static nl.irp.sepa.sdd.Utils.createRmtInf; import static nl.irp.sepa.sdd.Utils.createXMLGregorianCalendar; import static nl.irp.sepa.sdd.Utils.createXMLGregorianCalendarDate; import iso.std.iso._20022.tech.xsd.pain_008_001.ChargeBearerType1Code; import iso.std.iso._20022.tech.xsd.pain_008_001.CustomerDirectDebitInitiationV02; import iso.std.iso._20022.tech.xsd.pain_008_001.DirectDebitTransaction6; import iso.std.iso._20022.tech.xsd.pain_008_001.DirectDebitTransactionInformation9; import iso.std.iso._20022.tech.xsd.pain_008_001.Document; import iso.std.iso._20022.tech.xsd.pain_008_001.GroupHeader39; import iso.std.iso._20022.tech.xsd.pain_008_001.LocalInstrument2Choice; import iso.std.iso._20022.tech.xsd.pain_008_001.MandateRelatedInformation6; import iso.std.iso._20022.tech.xsd.pain_008_001.ObjectFactory; import iso.std.iso._20022.tech.xsd.pain_008_001.PaymentInstructionInformation4; import iso.std.iso._20022.tech.xsd.pain_008_001.PaymentMethod2Code; import iso.std.iso._20022.tech.xsd.pain_008_001.PaymentTypeInformation20; import iso.std.iso._20022.tech.xsd.pain_008_001.Purpose2Choice; import iso.std.iso._20022.tech.xsd.pain_008_001.SequenceType1Code; import iso.std.iso._20022.tech.xsd.pain_008_001.ServiceLevel8Choice; import java.io.OutputStream; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.UUID; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.joda.time.LocalDate; /** * This document describes the Implementation Guidelines for the XML SEPA Direct Debit Initiation message * UNIFI (ISO20022) - “pain.008.001.02” in the Netherlands. * @author "Jasper Krijgsman <[email protected]>" * */ public class DirectDebitInitiation { private Document document = new Document(); private CustomerDirectDebitInitiationV02 customerDirectDebitInitiationV02; private GroupHeader39 groupHeader; public DirectDebitInitiation() { customerDirectDebitInitiationV02 = new CustomerDirectDebitInitiationV02(); document.setCstmrDrctDbtInitn(customerDirectDebitInitiationV02); } /** * Set of characteristics shared by all individual transactions included in the message. * @param msgId Point to point reference, assigned by the instructing party and sent to * the next party in the chain, to unambiguously identify the message. * @param name * @param date */ public void buildGroupHeader(String msgId, String name, Date date) { groupHeader = new GroupHeader39(); // if no msgId is given create one if(msgId==null) msgId = UUID.randomUUID().toString().replaceAll("-", ""); checkArgument(msgId.length()<=35, "length of setMsgId is more than 35"); checkArgument(msgId.length()>1, "length of setMsgId is less than 1"); groupHeader.setMsgId(msgId); // Date and time at which the message was created. groupHeader.setCreDtTm( createXMLGregorianCalendar(date)); // Number of individual transactions contained in the message. groupHeader.setNbOfTxs("0"); //Total of all individual amounts included in the message. groupHeader.setCtrlSum(BigDecimal.ZERO); // Party that initiates the payment. groupHeader.setInitgPty( createParty(name) ); customerDirectDebitInitiationV02.setGrpHdr(groupHeader); } public void write(OutputStream os) throws JAXBException { JAXBContext jc = JAXBContext.newInstance(Document.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // The UTF-8 character encoding standard must be used in the UNIFI messages. marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.marshal(new ObjectFactory().createDocument(document), os); } public PaymentInstruction paymentInstruction( String pmtInfId, Date reqdColltnDt, String creditor, SequenceType1Code type, String creditorCountry, List<String> addressLines, String creditorAccount, String creditorBic) { PaymentInstruction paymentInstruction = new PaymentInstruction( pmtInfId, reqdColltnDt, creditor, type, creditorCountry, addressLines, creditorAccount, creditorBic); this.customerDirectDebitInitiationV02.getPmtInf().add(paymentInstruction.getPaymentInstructionInformation()); return paymentInstruction; } public class PaymentInstruction { private PaymentInstructionInformation4 paymentInstructionInformation; /** * * @param pmtInfId * @param reqdColltnDt Date and time at which the creditor requests that the amount of money is to be * collected from the debtor. */ public PaymentInstruction( String pmtInfId, Date reqdColltnDt, String creditor, SequenceType1Code type, String creditorCountry, List<String> addressLines, String creditorAccount, String creditorBic) { paymentInstructionInformation = new PaymentInstructionInformation4(); // Unique identification, as assigned by a sending party, to // unambiguously identify the payment information group within the message. checkArgument(pmtInfId.length()<=35, "length of pmtInfId is more than 35"); checkArgument(pmtInfId.length()>1, "length of pmtInfId is less than 1"); paymentInstructionInformation.setPmtInfId(pmtInfId); // Specifies the means of payment that will be used to move the amount of money. // DD=DirectDebit paymentInstructionInformation.setPmtMtd(PaymentMethod2Code.DD); // TODO paymentInstructionInformation.setNbOfTxs("0"); // TODO paymentInstructionInformation.setCtrlSum(BigDecimal.ZERO); // TODO paymentInstructionInformation.setPmtTpInf(makePaymentTypeInformation(type)); // Date and time at which the creditor requests that the amount of money is to be // collected from the debtor. paymentInstructionInformation.setReqdColltnDt( createXMLGregorianCalendarDate(reqdColltnDt) ); // Party to which an amount of money is due. paymentInstructionInformation.setCdtr( createParty(creditor, creditorCountry, addressLines) ); // Unambiguous identification of the account of the creditor to which a credit entry will // be posted as a result of the payment transaction. Only IBAN is allowed. paymentInstructionInformation.setCdtrAcct( createAccount(creditorAccount) ); paymentInstructionInformation.setCdtrAgt( createFinInstnId(creditorBic) ); paymentInstructionInformation.setChrgBr(ChargeBearerType1Code.SLEV); } public DirectDebitTransactionInformation9 addTransaction( String instructionIdentification, String endToEndIdentification, BigDecimal amount, String mandateId, LocalDate dateOfSignature, String cdtrSchmeId, String debtor, String debtorIban, String debtorBic, String debtorCtry, List<String> debtorAdrLine, String remittanceInformation) { DirectDebitTransactionInformation9 directDebitTransactionInformation = new DirectDebitTransactionInformation9(); // Set of elements used to reference a payment instruction. directDebitTransactionInformation.setPmtId( createPaymentIdentification(instructionIdentification, endToEndIdentification)); // Amount of money to be moved between the debtor and creditor, before deduction // of charges, expressed in the currency as ordered by the initiating party. directDebitTransactionInformation.setInstdAmt( createAmount(amount) ); //TODO: directDebitTransactionInformation.setDrctDbtTx(t(mandateId, dateOfSignature, cdtrSchmeId)); // Financial institution servicing an account for the debtor. directDebitTransactionInformation.setDbtrAgt( createFinInstnId(debtorBic) ); // Party that owes an amount of money to the (ultimate) creditor. directDebitTransactionInformation.setDbtr( createParty(debtor) ); directDebitTransactionInformation.setDbtrAcct( createAccount(debtorIban) ); //TODO: Purpose2Choice purpose = new Purpose2Choice(); purpose.setCd("OTHR"); directDebitTransactionInformation.setPurp(purpose); directDebitTransactionInformation.setRmtInf( createRmtInf(remittanceInformation) ); paymentInstructionInformation.getDrctDbtTxInf().add(directDebitTransactionInformation); // TODO: BigDecimal ctrlSum = groupHeader.getCtrlSum(); ctrlSum = ctrlSum.add(amount); groupHeader.setCtrlSum(ctrlSum); int nbOfTxs = Integer.parseInt(groupHeader.getNbOfTxs()); nbOfTxs = nbOfTxs+1; groupHeader.setNbOfTxs(String.valueOf(nbOfTxs)); // TODO: BigDecimal ictrlSum = paymentInstructionInformation.getCtrlSum(); ictrlSum = ictrlSum.add(amount); paymentInstructionInformation.setCtrlSum(ictrlSum); int inbOfTxs = Integer.parseInt(paymentInstructionInformation.getNbOfTxs()); inbOfTxs = inbOfTxs+1; paymentInstructionInformation.setNbOfTxs(String.valueOf(inbOfTxs)); return directDebitTransactionInformation; } public PaymentInstructionInformation4 getPaymentInstructionInformation() { return paymentInstructionInformation; } private PaymentTypeInformation20 makePaymentTypeInformation(SequenceType1Code type) { // Payment Type Information PaymentTypeInformation20 paymentTypeInformation = new PaymentTypeInformation20(); ServiceLevel8Choice serviceLevel8Choice = new ServiceLevel8Choice(); serviceLevel8Choice.setCd("SEPA");//Vaste waarde 'SEPA' paymentTypeInformation.setSvcLvl(serviceLevel8Choice); LocalInstrument2Choice localInstrument = new LocalInstrument2Choice(); localInstrument.setCd("CORE"); // "CORE" voor incasso's van particulieren paymentTypeInformation.setLclInstrm(localInstrument); //FRST eerste incasso binnen een serie op hetzelfde mandaat //RCUR vervolgincasso binnen hetzelfde mandaat //FNAL laatste incasso binnen hetzelfde mandaat //OOFF enkelvoudige incasso zonder repetering // Als de<SUF> // "Original Debtor Agent"(veld 2.58) is "SMNDA" dan moet "FRST" gekozen worden // Na een afwijzing van een "FRST" of "OOFF" moet een herhaling als "FRST" aangegeven worden // Als een "FRST" gestorneerd of geretourneerd wordt (alleen bij type "CORE") moet deze als "RCUR" ingestuurd worden // Als een "OOFF" gestorneerd of geretourneerd wordt (alleen bij type "CORE") kan deze alleen met een nieuw mandaat ingestuurd worden paymentTypeInformation.setSeqTp(type); return paymentTypeInformation; } private DirectDebitTransaction6 t(String mandateId, LocalDate dtOfSgntr, String cdtrSchmeId ) { DirectDebitTransaction6 transaction = new DirectDebitTransaction6(); MandateRelatedInformation6 mandateInf = new MandateRelatedInformation6(); mandateInf.setMndtId(mandateId); mandateInf.setDtOfSgntr( createXMLGregorianCalendarDate(dtOfSgntr.toDate())); mandateInf.setAmdmntInd(false); transaction.setMndtRltdInf(mandateInf); //// transaction.setCdtrSchmeId(createIdParty(cdtrSchmeId)); return transaction; } } }