index
int64 1
4.83k
| file_id
stringlengths 5
9
| content
stringlengths 167
16.5k
| repo
stringlengths 7
82
| path
stringlengths 8
164
| token_length
int64 72
4.23k
| original_comment
stringlengths 11
2.7k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 142
16.5k
| Inclusion
stringclasses 4
values | file-tokens-Qwen/Qwen2-7B
int64 64
3.93k
| comment-tokens-Qwen/Qwen2-7B
int64 4
972
| file-tokens-bigcode/starcoder2-7b
int64 74
3.98k
| comment-tokens-bigcode/starcoder2-7b
int64 4
959
| file-tokens-google/codegemma-7b
int64 56
3.99k
| comment-tokens-google/codegemma-7b
int64 3
953
| file-tokens-ibm-granite/granite-8b-code-base
int64 74
3.98k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 4
959
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 77
4.12k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
1.11k
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,188 | 73378_4 | package staticfactory;
import java.util.ArrayList;
import java.util.Iterator;
// instance controlled class
public class ManagedResource {
static ArrayList<ManagedResource> instances = new ArrayList<>();
static final int MAX_POOL_SIZE = 10;
private ManagedResource () {
System.out.println("Creating managed resource number " +instances.size());
}
private boolean isReady() {
System.out.println("Checking whether this resource is ready.");
if (Math.random() < .5) {
System.out.println("Resource busy; try again later.");
return false;
} else {
System.out.println("Resource ready to be used again.");
return true;
}
}
static ManagedResource getInstance() {
// eerst kun je bijvoorbeeld kijken of er nog slots te vergeven zijn.
if (instances.size()<=MAX_POOL_SIZE) {
ManagedResource foo = new ManagedResource();
instances.add(foo);
return foo;
}
// in het andere geval zou je iets moeten doen met
// lock and wait; en geef je de eerste instantie terug die niets te doen heeft
// (dit is uiteraard een slechts realisatie, alleen voor de demonstratie)
boolean found = false;
ManagedResource tmp=null;;
while (!found) {
Iterator<ManagedResource> itr = instances.iterator();
while(itr.hasNext()) {
tmp = itr.next();
if (tmp.isReady()) {
found = true;
break;
}
}
}
return tmp;
}
}
| bart314/practicum.2.3 | week4/staticfactory/ManagedResource.java | 433 | // (dit is uiteraard een slechts realisatie, alleen voor de demonstratie) | line_comment | nl | package staticfactory;
import java.util.ArrayList;
import java.util.Iterator;
// instance controlled class
public class ManagedResource {
static ArrayList<ManagedResource> instances = new ArrayList<>();
static final int MAX_POOL_SIZE = 10;
private ManagedResource () {
System.out.println("Creating managed resource number " +instances.size());
}
private boolean isReady() {
System.out.println("Checking whether this resource is ready.");
if (Math.random() < .5) {
System.out.println("Resource busy; try again later.");
return false;
} else {
System.out.println("Resource ready to be used again.");
return true;
}
}
static ManagedResource getInstance() {
// eerst kun je bijvoorbeeld kijken of er nog slots te vergeven zijn.
if (instances.size()<=MAX_POOL_SIZE) {
ManagedResource foo = new ManagedResource();
instances.add(foo);
return foo;
}
// in het andere geval zou je iets moeten doen met
// lock and wait; en geef je de eerste instantie terug die niets te doen heeft
// (dit is<SUF>
boolean found = false;
ManagedResource tmp=null;;
while (!found) {
Iterator<ManagedResource> itr = instances.iterator();
while(itr.hasNext()) {
tmp = itr.next();
if (tmp.isReady()) {
found = true;
break;
}
}
}
return tmp;
}
}
| False | 338 | 21 | 414 | 23 | 395 | 17 | 414 | 23 | 487 | 22 | false | false | false | false | false | true |
1,030 | 172967_3 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import org.havi.ui.*;
import java.awt.*;
import org.dvb.ui.*;
/**
*
* @author student
*/
public class Sprite extends HComponent {
private Image spaceship;
private MediaTracker mtrack;
//plaats en lovatie instellen in de constructor
public Sprite(String file, int x, int y)
{
spaceship = this.getToolkit().getImage(file);
mtrack = new MediaTracker(this);
mtrack.addImage(spaceship, 0);
try
{
mtrack.waitForAll(); // wacht tot alle bitmaps geladen zijn
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap
}
//paint methode overschrijven
public void paint(Graphics g)
{
g.drawImage(spaceship, 0, 0, null);
}
public void Verplaats(int x, int y)
{
this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this));
}
}
| MTA-Digital-Broadcast-2/K-De-Maeyer-Didier-Schuddinck-Sam-Project-MHP | Didier De Maeyer/blz47/Oef1/HelloTVXlet/src/hellotvxlet/Sprite.java | 367 | // wacht tot alle bitmaps geladen zijn | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import org.havi.ui.*;
import java.awt.*;
import org.dvb.ui.*;
/**
*
* @author student
*/
public class Sprite extends HComponent {
private Image spaceship;
private MediaTracker mtrack;
//plaats en lovatie instellen in de constructor
public Sprite(String file, int x, int y)
{
spaceship = this.getToolkit().getImage(file);
mtrack = new MediaTracker(this);
mtrack.addImage(spaceship, 0);
try
{
mtrack.waitForAll(); // wacht tot<SUF>
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap
}
//paint methode overschrijven
public void paint(Graphics g)
{
g.drawImage(spaceship, 0, 0, null);
}
public void Verplaats(int x, int y)
{
this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this));
}
}
| True | 271 | 10 | 313 | 11 | 330 | 8 | 313 | 11 | 369 | 10 | false | false | false | false | false | true |
600 | 11641_4 | import java.util.ArrayList;_x000D_
_x000D_
/**_x000D_
* Presentation houdt de slides in de presentatie bij._x000D_
* <p>_x000D_
* In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_
* This program is distributed under the terms of the accompanying_x000D_
* COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_
* Please read it. Your use of the software constitutes acceptance_x000D_
* of the terms in the COPYRIGHT.txt file._x000D_
* @author Ian F. Darwin, [email protected]_x000D_
* @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_
* @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_
* @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_
* @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_
*/_x000D_
_x000D_
// Verandering: Presentation wordt een Observable_x000D_
public class Presentation {_x000D_
private String showTitle; // de titel van de presentatie_x000D_
private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_
private int currentSlideNumber = 0; // het slidenummer van de huidige Slide_x000D_
// Verandering: we kennen slideViewComponent niet meer direct_x000D_
// private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_
_x000D_
public Presentation() {_x000D_
// Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_
//slideViewComponent = null;_x000D_
clear();_x000D_
}_x000D_
_x000D_
// Methode die wordt gebruikt door de Controller_x000D_
// om te bepalen wat er getoond wordt._x000D_
public int getSize() {_x000D_
return showList.size();_x000D_
}_x000D_
_x000D_
public String getTitle() {_x000D_
return showTitle;_x000D_
}_x000D_
_x000D_
public void setTitle(String nt) {_x000D_
showTitle = nt;_x000D_
}_x000D_
_x000D_
// Verandering: deze methode hebben we niet meer nodig_x000D_
// public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_
// this.slideViewComponent = slideViewerComponent;_x000D_
// }_x000D_
_x000D_
// geef het nummer van de huidige slide_x000D_
public int getSlideNumber() {_x000D_
return currentSlideNumber;_x000D_
}_x000D_
_x000D_
// verander het huidige-slide-nummer en laat het aan het window weten._x000D_
public void setSlideNumber(int number) {_x000D_
currentSlideNumber = number;_x000D_
// Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_
//if (slideViewComponent != null) {_x000D_
// slideViewComponent.update(this, getCurrentSlide());_x000D_
//}_x000D_
}_x000D_
_x000D_
// Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_
void clear() {_x000D_
showList = new ArrayList<Slide>();_x000D_
setTitle("New presentation");_x000D_
setSlideNumber(-1);_x000D_
}_x000D_
_x000D_
// Voeg een slide toe aan de presentatie_x000D_
public void append(Slide slide) {_x000D_
showList.add(slide);_x000D_
}_x000D_
_x000D_
// Geef een slide met een bepaald slidenummer_x000D_
public Slide getSlide(int number) {_x000D_
if (number < 0 || number >= getSize()){_x000D_
return null;_x000D_
}_x000D_
return (Slide)showList.get(number);_x000D_
}_x000D_
_x000D_
// Geef de huidige Slide_x000D_
public Slide getCurrentSlide() {_x000D_
return getSlide(currentSlideNumber);_x000D_
}_x000D_
}_x000D_
| GertSallaerts/jabbertest | Presentation.java | 935 | // het slidenummer van de huidige Slide_x000D_ | line_comment | nl | import java.util.ArrayList;_x000D_
_x000D_
/**_x000D_
* Presentation houdt de slides in de presentatie bij._x000D_
* <p>_x000D_
* In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_
* This program is distributed under the terms of the accompanying_x000D_
* COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_
* Please read it. Your use of the software constitutes acceptance_x000D_
* of the terms in the COPYRIGHT.txt file._x000D_
* @author Ian F. Darwin, [email protected]_x000D_
* @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_
* @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_
* @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_
* @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_
*/_x000D_
_x000D_
// Verandering: Presentation wordt een Observable_x000D_
public class Presentation {_x000D_
private String showTitle; // de titel van de presentatie_x000D_
private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_
private int currentSlideNumber = 0; // het slidenummer<SUF>
// Verandering: we kennen slideViewComponent niet meer direct_x000D_
// private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_
_x000D_
public Presentation() {_x000D_
// Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_
//slideViewComponent = null;_x000D_
clear();_x000D_
}_x000D_
_x000D_
// Methode die wordt gebruikt door de Controller_x000D_
// om te bepalen wat er getoond wordt._x000D_
public int getSize() {_x000D_
return showList.size();_x000D_
}_x000D_
_x000D_
public String getTitle() {_x000D_
return showTitle;_x000D_
}_x000D_
_x000D_
public void setTitle(String nt) {_x000D_
showTitle = nt;_x000D_
}_x000D_
_x000D_
// Verandering: deze methode hebben we niet meer nodig_x000D_
// public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_
// this.slideViewComponent = slideViewerComponent;_x000D_
// }_x000D_
_x000D_
// geef het nummer van de huidige slide_x000D_
public int getSlideNumber() {_x000D_
return currentSlideNumber;_x000D_
}_x000D_
_x000D_
// verander het huidige-slide-nummer en laat het aan het window weten._x000D_
public void setSlideNumber(int number) {_x000D_
currentSlideNumber = number;_x000D_
// Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_
//if (slideViewComponent != null) {_x000D_
// slideViewComponent.update(this, getCurrentSlide());_x000D_
//}_x000D_
}_x000D_
_x000D_
// Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_
void clear() {_x000D_
showList = new ArrayList<Slide>();_x000D_
setTitle("New presentation");_x000D_
setSlideNumber(-1);_x000D_
}_x000D_
_x000D_
// Voeg een slide toe aan de presentatie_x000D_
public void append(Slide slide) {_x000D_
showList.add(slide);_x000D_
}_x000D_
_x000D_
// Geef een slide met een bepaald slidenummer_x000D_
public Slide getSlide(int number) {_x000D_
if (number < 0 || number >= getSize()){_x000D_
return null;_x000D_
}_x000D_
return (Slide)showList.get(number);_x000D_
}_x000D_
_x000D_
// Geef de huidige Slide_x000D_
public Slide getCurrentSlide() {_x000D_
return getSlide(currentSlideNumber);_x000D_
}_x000D_
}_x000D_
| True | 1,280 | 17 | 1,460 | 19 | 1,393 | 16 | 1,460 | 19 | 1,552 | 20 | false | false | false | false | false | true |
2,850 | 65568_3 | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.spellchecker.xml;
import com.intellij.codeInspection.SuppressQuickFix;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.LeafPsiElement;
import com.intellij.psi.templateLanguages.TemplateLanguage;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.xml.*;
import com.intellij.spellchecker.inspections.PlainTextSplitter;
import com.intellij.spellchecker.inspections.Splitter;
import com.intellij.spellchecker.tokenizer.LanguageSpellchecking;
import com.intellij.spellchecker.tokenizer.SuppressibleSpellcheckingStrategy;
import com.intellij.spellchecker.tokenizer.TokenConsumer;
import com.intellij.spellchecker.tokenizer.Tokenizer;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomUtil;
import com.intellij.xml.util.XmlEnumeratedValueReference;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
public class XmlSpellcheckingStrategy extends SuppressibleSpellcheckingStrategy {
private final Tokenizer<? extends PsiElement> myXmlTextTokenizer = createTextTokenizer();
private final Tokenizer<? extends PsiElement> myXmlAttributeTokenizer = createAttributeValueTokenizer();
@Override
public @NotNull Tokenizer getTokenizer(PsiElement element) {
if (element instanceof XmlText) {
return myXmlTextTokenizer;
}
if (element instanceof XmlToken
&& ((XmlToken)element).getTokenType() == XmlTokenType.XML_DATA_CHARACTERS
&& !isXmlDataCharactersParentHandledByItsStrategy(element.getParent())) {
// Special case for all other XML_DATA_CHARACTERS, which are not handled through parent PSI
if (isInTemplateLanguageFile(element))
return EMPTY_TOKENIZER;
return TEXT_TOKENIZER;
}
if (element instanceof XmlAttributeValue) {
return myXmlAttributeTokenizer;
}
return super.getTokenizer(element);
}
@Override
public boolean isSuppressedFor(@NotNull PsiElement element, @NotNull String name) {
DomElement domElement = DomUtil.getDomElement(element);
if (domElement != null) {
if (domElement.getAnnotation(NoSpellchecking.class) != null) {
return true;
}
}
return false;
}
@Override
public SuppressQuickFix[] getSuppressActions(@NotNull PsiElement element, @NotNull String name) {
return SuppressQuickFix.EMPTY_ARRAY;
}
protected Tokenizer<? extends PsiElement> createAttributeValueTokenizer() {
return new XmlAttributeValueTokenizer(PlainTextSplitter.getInstance());
}
private boolean isXmlDataCharactersParentHandledByItsStrategy(@Nullable PsiElement parent) {
if (parent == null) return false;
var strategy = ContainerUtil.findInstance(
LanguageSpellchecking.INSTANCE.allForLanguage(parent.getLanguage()),
XmlSpellcheckingStrategy.class);
return strategy != null ? strategy.isXmlDataCharactersParentHandled(parent)
: isXmlDataCharactersParentHandled(parent);
}
protected boolean isXmlDataCharactersParentHandled(@NotNull PsiElement parent) {
return parent instanceof XmlText
|| parent.getNode().getElementType() == XmlElementType.XML_CDATA;
}
protected boolean isInTemplateLanguageFile(PsiElement element) {
PsiFile file = element.getContainingFile();
return file == null || file.getLanguage() instanceof TemplateLanguage;
}
protected Tokenizer<? extends PsiElement> createTextTokenizer() {
return new XmlTextTokenizer(PlainTextSplitter.getInstance());
}
protected abstract static class XmlTextContentTokenizer<T extends XmlElement> extends XmlTokenizerBase<T> {
public XmlTextContentTokenizer(Splitter splitter) {
super(splitter);
}
protected abstract boolean isContentToken(IElementType tokenType);
@Override
protected @NotNull List<@NotNull TextRange> getSpellcheckOuterContentRanges(@NotNull T element) {
List<TextRange> result = new SmartList<>(super.getSpellcheckOuterContentRanges(element));
element.acceptChildren(new XmlElementVisitor() {
@Override
public void visitElement(@NotNull PsiElement element) {
if (element.getNode().getElementType() == XmlElementType.XML_CDATA) {
element.acceptChildren(this);
}
else if (!(element instanceof LeafPsiElement)
|| !isContentToken(element.getNode().getElementType())) {
result.add(element.getTextRangeInParent());
}
}
});
return result;
}
}
protected static class XmlTextTokenizer extends XmlTextContentTokenizer<XmlText> {
public XmlTextTokenizer(Splitter splitter) {
super(splitter);
}
@Override
protected boolean isContentToken(IElementType tokenType) {
return tokenType == XmlTokenType.XML_DATA_CHARACTERS
|| tokenType == XmlTokenType.XML_CDATA_START
|| tokenType == XmlTokenType.XML_CDATA_END
|| XmlTokenType.WHITESPACES.contains(tokenType);
}
}
protected static class XmlAttributeValueTokenizer extends XmlTextContentTokenizer<XmlAttributeValue> {
public XmlAttributeValueTokenizer(Splitter splitter) {
super(splitter);
}
@Override
protected boolean isContentToken(IElementType tokenType) {
return tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN
|| tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER
|| tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER
|| XmlTokenType.WHITESPACES.contains(tokenType);
}
@Override
protected @NotNull List<@NotNull SpellcheckRange> getSpellcheckRanges(@NotNull XmlAttributeValue element) {
TextRange range = ElementManipulators.getValueTextRange(element);
if (range.isEmpty()) return emptyList();
String text = ElementManipulators.getValueText(element);
return singletonList(new SpellcheckRange(text, false, range.getStartOffset(), TextRange.allOf(text)));
}
@Override
public void tokenize(@NotNull XmlAttributeValue element, @NotNull TokenConsumer consumer) {
PsiReference[] references = element.getReferences();
for (PsiReference reference : references) {
if (reference instanceof XmlEnumeratedValueReference) {
if (reference.resolve() != null) {
// this is probably valid enumeration value from XSD/RNG schema, such as SVG
return;
}
}
}
final String valueTextTrimmed = element.getValue().trim();
// do not inspect colors like #00aaFF
if (valueTextTrimmed.startsWith("#") && valueTextTrimmed.length() <= 9 && isHexString(valueTextTrimmed.substring(1))) {
return;
}
super.tokenize(element, consumer);
}
private static boolean isHexString(final String s) {
for (int i = 0; i < s.length(); i++) {
if (!StringUtil.isHexDigit(s.charAt(i))) {
return false;
}
}
return true;
}
}
}
| google/intellij-community | xml/impl/src/com/intellij/spellchecker/xml/XmlSpellcheckingStrategy.java | 2,180 | // do not inspect colors like #00aaFF | line_comment | nl | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.spellchecker.xml;
import com.intellij.codeInspection.SuppressQuickFix;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.LeafPsiElement;
import com.intellij.psi.templateLanguages.TemplateLanguage;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.xml.*;
import com.intellij.spellchecker.inspections.PlainTextSplitter;
import com.intellij.spellchecker.inspections.Splitter;
import com.intellij.spellchecker.tokenizer.LanguageSpellchecking;
import com.intellij.spellchecker.tokenizer.SuppressibleSpellcheckingStrategy;
import com.intellij.spellchecker.tokenizer.TokenConsumer;
import com.intellij.spellchecker.tokenizer.Tokenizer;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomUtil;
import com.intellij.xml.util.XmlEnumeratedValueReference;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
public class XmlSpellcheckingStrategy extends SuppressibleSpellcheckingStrategy {
private final Tokenizer<? extends PsiElement> myXmlTextTokenizer = createTextTokenizer();
private final Tokenizer<? extends PsiElement> myXmlAttributeTokenizer = createAttributeValueTokenizer();
@Override
public @NotNull Tokenizer getTokenizer(PsiElement element) {
if (element instanceof XmlText) {
return myXmlTextTokenizer;
}
if (element instanceof XmlToken
&& ((XmlToken)element).getTokenType() == XmlTokenType.XML_DATA_CHARACTERS
&& !isXmlDataCharactersParentHandledByItsStrategy(element.getParent())) {
// Special case for all other XML_DATA_CHARACTERS, which are not handled through parent PSI
if (isInTemplateLanguageFile(element))
return EMPTY_TOKENIZER;
return TEXT_TOKENIZER;
}
if (element instanceof XmlAttributeValue) {
return myXmlAttributeTokenizer;
}
return super.getTokenizer(element);
}
@Override
public boolean isSuppressedFor(@NotNull PsiElement element, @NotNull String name) {
DomElement domElement = DomUtil.getDomElement(element);
if (domElement != null) {
if (domElement.getAnnotation(NoSpellchecking.class) != null) {
return true;
}
}
return false;
}
@Override
public SuppressQuickFix[] getSuppressActions(@NotNull PsiElement element, @NotNull String name) {
return SuppressQuickFix.EMPTY_ARRAY;
}
protected Tokenizer<? extends PsiElement> createAttributeValueTokenizer() {
return new XmlAttributeValueTokenizer(PlainTextSplitter.getInstance());
}
private boolean isXmlDataCharactersParentHandledByItsStrategy(@Nullable PsiElement parent) {
if (parent == null) return false;
var strategy = ContainerUtil.findInstance(
LanguageSpellchecking.INSTANCE.allForLanguage(parent.getLanguage()),
XmlSpellcheckingStrategy.class);
return strategy != null ? strategy.isXmlDataCharactersParentHandled(parent)
: isXmlDataCharactersParentHandled(parent);
}
protected boolean isXmlDataCharactersParentHandled(@NotNull PsiElement parent) {
return parent instanceof XmlText
|| parent.getNode().getElementType() == XmlElementType.XML_CDATA;
}
protected boolean isInTemplateLanguageFile(PsiElement element) {
PsiFile file = element.getContainingFile();
return file == null || file.getLanguage() instanceof TemplateLanguage;
}
protected Tokenizer<? extends PsiElement> createTextTokenizer() {
return new XmlTextTokenizer(PlainTextSplitter.getInstance());
}
protected abstract static class XmlTextContentTokenizer<T extends XmlElement> extends XmlTokenizerBase<T> {
public XmlTextContentTokenizer(Splitter splitter) {
super(splitter);
}
protected abstract boolean isContentToken(IElementType tokenType);
@Override
protected @NotNull List<@NotNull TextRange> getSpellcheckOuterContentRanges(@NotNull T element) {
List<TextRange> result = new SmartList<>(super.getSpellcheckOuterContentRanges(element));
element.acceptChildren(new XmlElementVisitor() {
@Override
public void visitElement(@NotNull PsiElement element) {
if (element.getNode().getElementType() == XmlElementType.XML_CDATA) {
element.acceptChildren(this);
}
else if (!(element instanceof LeafPsiElement)
|| !isContentToken(element.getNode().getElementType())) {
result.add(element.getTextRangeInParent());
}
}
});
return result;
}
}
protected static class XmlTextTokenizer extends XmlTextContentTokenizer<XmlText> {
public XmlTextTokenizer(Splitter splitter) {
super(splitter);
}
@Override
protected boolean isContentToken(IElementType tokenType) {
return tokenType == XmlTokenType.XML_DATA_CHARACTERS
|| tokenType == XmlTokenType.XML_CDATA_START
|| tokenType == XmlTokenType.XML_CDATA_END
|| XmlTokenType.WHITESPACES.contains(tokenType);
}
}
protected static class XmlAttributeValueTokenizer extends XmlTextContentTokenizer<XmlAttributeValue> {
public XmlAttributeValueTokenizer(Splitter splitter) {
super(splitter);
}
@Override
protected boolean isContentToken(IElementType tokenType) {
return tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN
|| tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER
|| tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER
|| XmlTokenType.WHITESPACES.contains(tokenType);
}
@Override
protected @NotNull List<@NotNull SpellcheckRange> getSpellcheckRanges(@NotNull XmlAttributeValue element) {
TextRange range = ElementManipulators.getValueTextRange(element);
if (range.isEmpty()) return emptyList();
String text = ElementManipulators.getValueText(element);
return singletonList(new SpellcheckRange(text, false, range.getStartOffset(), TextRange.allOf(text)));
}
@Override
public void tokenize(@NotNull XmlAttributeValue element, @NotNull TokenConsumer consumer) {
PsiReference[] references = element.getReferences();
for (PsiReference reference : references) {
if (reference instanceof XmlEnumeratedValueReference) {
if (reference.resolve() != null) {
// this is probably valid enumeration value from XSD/RNG schema, such as SVG
return;
}
}
}
final String valueTextTrimmed = element.getValue().trim();
// do not<SUF>
if (valueTextTrimmed.startsWith("#") && valueTextTrimmed.length() <= 9 && isHexString(valueTextTrimmed.substring(1))) {
return;
}
super.tokenize(element, consumer);
}
private static boolean isHexString(final String s) {
for (int i = 0; i < s.length(); i++) {
if (!StringUtil.isHexDigit(s.charAt(i))) {
return false;
}
}
return true;
}
}
}
| False | 1,502 | 11 | 1,692 | 11 | 1,810 | 11 | 1,692 | 11 | 2,114 | 11 | false | false | false | false | false | true |
4,476 | 193877_8 | /**
* This file is part of RefactorGuidance project. Which explores possibilities to generate context based
* instructions on how to refactor a piece of Java code. This applied in an education setting (bachelor SE students)
*
* Copyright (C) 2018, Patrick de Beer, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 analysis.context;
import aig.AdaptiveInstructionGraph;
import aig.CodeContext;
import analysis.ICodeAnalyzer;
import analysis.MethodAnalyzer.ClassMethodFinder;
import analysis.dataflow.MethodDataFlowAnalyzer;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
/**
* Class builds up a set of context detectors that are needed to detect contextual situations
* in a given adaptive instruction graph. The list of detectors can be provided to the procedural
* guidance generator
*/
public class ContextDetectorSetBuilder {
private AdaptiveInstructionGraph _aig = null;
private ContextConfiguration _analyzerConfig = null;
private List<IContextDetector> _contextDetectors = new ArrayList<IContextDetector>();
private List<ICodeAnalyzer> _analyzers = new ArrayList<ICodeAnalyzer>();
public void SetAIT(AdaptiveInstructionGraph aig) {
setAIT(aig);
}
public void setAIT(AdaptiveInstructionGraph aig) {
this._aig = aig;
}
public List<IContextDetector> getContextDetectors() throws Exception {
if(_analyzerConfig == null) {
throw new Exception("No ContextConfiguration object was defined. call setContextAnalyzerConfiguration(...) first");
}
EnumSet<CodeContext.CodeContextEnum> completeCodeContext = this._aig.allUniqueCodeContextInGraph();
String refactoringProcessName = this._aig.getRefactorMechanic();
if(refactoringProcessName.contentEquals("Rename Method"))
{
// Maak de analyzers 1x aan in, om geen dubbele instanties te krijgen
// They can be directly initialized if contextanalyzerconfiguration object is present
// voor deze specifieke method
// uitlezen cu + methodname of line numers
// initieren ClassMethodFinder analyzer (en evt. andere analyzers)
// instantieren detectors, waarbij in het config object de juiste analyzers staan, die een detector
// intern weet op te vragen.
// Voeg de analuzers toe aan ContextAnalyzerCOnfiguration
BuildRenameContextDetectors(completeCodeContext); // provides possible analyzers + input
}
else
if(refactoringProcessName.contentEquals("Extract Method") )
{
BuildExtractMethodContextDetectors(completeCodeContext);
}
return this._contextDetectors;
}
/**
* Through the returned configuration object, the created analyzers can be accessed
* - to initialize from the outside
* - to be used by the detectors to access necessary information
* @return
*/
public ContextConfiguration getContextAnalyzerConfiguration()
{
return _analyzerConfig;
}
public void setContextConfiguration(ContextConfiguration config)
{
_analyzerConfig = config;
}
//@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory
//
private void BuildRenameContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext)
{
// 1. setup the analyzers and add them to the generic config object.
_analyzerConfig.setCMFAnalyzer(new ClassMethodFinder());
_analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName());
// 2. Create the relevant detectors and provided them with the generic config object
UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig);
}
//@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory
//
private void BuildExtractMethodContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext)
{
// 1. setup the analyzers and add them to the generic config object.
_analyzerConfig.setCMFAnalyzer(new ClassMethodFinder());
_analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName());
_analyzerConfig.setMethodDataFlowAnalyzer(new MethodDataFlowAnalyzer());
_analyzerConfig.getMethodDataFlowAnalyzer().initialize(
_analyzerConfig.getCMFAnalyzer().getMethodDescriberForLocation(_analyzerConfig.getCodeSection().begin()).getMethodDeclaration(),
_analyzerConfig.getCodeSection());
// 2. Create the relevant detectors and provided them with the generic config object
UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig);
}
/**
* A set of context detectors is build based on the context set that is provided.
* The @ContextConfiguration object is used to provide detectors with necessary input in a generic way
*
* @param completeCodeContext Context detectors that should be instantiated
* @param analyzerConfig Necessary input to properly initialize detectors and possible analyzers
*/
private void UniversalBuildContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext,
ContextConfiguration analyzerConfig)
{
if (ContextDetectorForAllContextDecisions(completeCodeContext)) {
try {
for (CodeContext.CodeContextEnum context : completeCodeContext) {
if (!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) {
Class<?> classCtxt = Class.forName("analysis.context." + context.name());
Class<?> classConfig = Class.forName("analysis.context.ContextConfiguration");
Constructor<?> constructor = classCtxt.getConstructor(classConfig);
IContextDetector instance =
(IContextDetector) constructor.newInstance(analyzerConfig);
_contextDetectors.add(instance);
}
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
/**
* Internally used to validate if all requested detectors in the context set are actually
* present as classes in our java project
*
* @param completeCodeContext
* @return True, when all necessary classes could be found
*/
private boolean ContextDetectorForAllContextDecisions(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) {
boolean allDefined = true;
try {
for (CodeContext.CodeContextEnum context : completeCodeContext) {
if(!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString()))
Class.forName("analysis.context." + context.name());
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println("class " + cnfe.getMessage() + " not defined");
allDefined = false;
}
return allDefined;
}
public void setConfiguration(ContextConfiguration configuration) {
this._analyzerConfig = configuration;
}
}
| the-refactorers/RefactorGuidanceTool | src/main/java/analysis/context/ContextDetectorSetBuilder.java | 2,084 | // intern weet op te vragen. | line_comment | nl | /**
* This file is part of RefactorGuidance project. Which explores possibilities to generate context based
* instructions on how to refactor a piece of Java code. This applied in an education setting (bachelor SE students)
*
* Copyright (C) 2018, Patrick de Beer, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 analysis.context;
import aig.AdaptiveInstructionGraph;
import aig.CodeContext;
import analysis.ICodeAnalyzer;
import analysis.MethodAnalyzer.ClassMethodFinder;
import analysis.dataflow.MethodDataFlowAnalyzer;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
/**
* Class builds up a set of context detectors that are needed to detect contextual situations
* in a given adaptive instruction graph. The list of detectors can be provided to the procedural
* guidance generator
*/
public class ContextDetectorSetBuilder {
private AdaptiveInstructionGraph _aig = null;
private ContextConfiguration _analyzerConfig = null;
private List<IContextDetector> _contextDetectors = new ArrayList<IContextDetector>();
private List<ICodeAnalyzer> _analyzers = new ArrayList<ICodeAnalyzer>();
public void SetAIT(AdaptiveInstructionGraph aig) {
setAIT(aig);
}
public void setAIT(AdaptiveInstructionGraph aig) {
this._aig = aig;
}
public List<IContextDetector> getContextDetectors() throws Exception {
if(_analyzerConfig == null) {
throw new Exception("No ContextConfiguration object was defined. call setContextAnalyzerConfiguration(...) first");
}
EnumSet<CodeContext.CodeContextEnum> completeCodeContext = this._aig.allUniqueCodeContextInGraph();
String refactoringProcessName = this._aig.getRefactorMechanic();
if(refactoringProcessName.contentEquals("Rename Method"))
{
// Maak de analyzers 1x aan in, om geen dubbele instanties te krijgen
// They can be directly initialized if contextanalyzerconfiguration object is present
// voor deze specifieke method
// uitlezen cu + methodname of line numers
// initieren ClassMethodFinder analyzer (en evt. andere analyzers)
// instantieren detectors, waarbij in het config object de juiste analyzers staan, die een detector
// intern weet<SUF>
// Voeg de analuzers toe aan ContextAnalyzerCOnfiguration
BuildRenameContextDetectors(completeCodeContext); // provides possible analyzers + input
}
else
if(refactoringProcessName.contentEquals("Extract Method") )
{
BuildExtractMethodContextDetectors(completeCodeContext);
}
return this._contextDetectors;
}
/**
* Through the returned configuration object, the created analyzers can be accessed
* - to initialize from the outside
* - to be used by the detectors to access necessary information
* @return
*/
public ContextConfiguration getContextAnalyzerConfiguration()
{
return _analyzerConfig;
}
public void setContextConfiguration(ContextConfiguration config)
{
_analyzerConfig = config;
}
//@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory
//
private void BuildRenameContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext)
{
// 1. setup the analyzers and add them to the generic config object.
_analyzerConfig.setCMFAnalyzer(new ClassMethodFinder());
_analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName());
// 2. Create the relevant detectors and provided them with the generic config object
UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig);
}
//@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory
//
private void BuildExtractMethodContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext)
{
// 1. setup the analyzers and add them to the generic config object.
_analyzerConfig.setCMFAnalyzer(new ClassMethodFinder());
_analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName());
_analyzerConfig.setMethodDataFlowAnalyzer(new MethodDataFlowAnalyzer());
_analyzerConfig.getMethodDataFlowAnalyzer().initialize(
_analyzerConfig.getCMFAnalyzer().getMethodDescriberForLocation(_analyzerConfig.getCodeSection().begin()).getMethodDeclaration(),
_analyzerConfig.getCodeSection());
// 2. Create the relevant detectors and provided them with the generic config object
UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig);
}
/**
* A set of context detectors is build based on the context set that is provided.
* The @ContextConfiguration object is used to provide detectors with necessary input in a generic way
*
* @param completeCodeContext Context detectors that should be instantiated
* @param analyzerConfig Necessary input to properly initialize detectors and possible analyzers
*/
private void UniversalBuildContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext,
ContextConfiguration analyzerConfig)
{
if (ContextDetectorForAllContextDecisions(completeCodeContext)) {
try {
for (CodeContext.CodeContextEnum context : completeCodeContext) {
if (!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) {
Class<?> classCtxt = Class.forName("analysis.context." + context.name());
Class<?> classConfig = Class.forName("analysis.context.ContextConfiguration");
Constructor<?> constructor = classCtxt.getConstructor(classConfig);
IContextDetector instance =
(IContextDetector) constructor.newInstance(analyzerConfig);
_contextDetectors.add(instance);
}
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
/**
* Internally used to validate if all requested detectors in the context set are actually
* present as classes in our java project
*
* @param completeCodeContext
* @return True, when all necessary classes could be found
*/
private boolean ContextDetectorForAllContextDecisions(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) {
boolean allDefined = true;
try {
for (CodeContext.CodeContextEnum context : completeCodeContext) {
if(!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString()))
Class.forName("analysis.context." + context.name());
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println("class " + cnfe.getMessage() + " not defined");
allDefined = false;
}
return allDefined;
}
public void setConfiguration(ContextConfiguration configuration) {
this._analyzerConfig = configuration;
}
}
| False | 1,646 | 9 | 1,755 | 10 | 1,835 | 7 | 1,755 | 10 | 2,099 | 9 | false | false | false | false | false | true |
645 | 69594_0 | package AbsentieLijst.userInterfaceLaag;_x000D_
_x000D_
import AbsentieLijst.*;_x000D_
import javafx.collections.FXCollections;_x000D_
import javafx.collections.ObservableList;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.fxml.FXMLLoader;_x000D_
import javafx.scene.Parent;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.control.ComboBox;_x000D_
import javafx.scene.control.DatePicker;_x000D_
import javafx.scene.control.Label;_x000D_
import javafx.scene.image.Image;_x000D_
import javafx.stage.Modality;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
import java.sql.Time;_x000D_
import java.time.LocalDate;_x000D_
import java.util.ArrayList;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class ToekomstigAfmeldenController {_x000D_
public Button ButtonOpslaan;_x000D_
public Button ButtonAnnuleren;_x000D_
public DatePicker DatePickerDate;_x000D_
public ComboBox ComboBoxReden;_x000D_
public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_
public Button overzicht;_x000D_
public Label label;_x000D_
public ComboBox tijd;_x000D_
_x000D_
School HU = School.getSchool();_x000D_
ObservableList<String> options =_x000D_
FXCollections.observableArrayList(_x000D_
"Bruiloft",_x000D_
"Tandarts afspraak",_x000D_
"Begravenis", "Wegens corona.", "Overig"_x000D_
);_x000D_
_x000D_
_x000D_
public void initialize() {_x000D_
ComboBoxReden.setItems(options);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
public void ActionOpslaan(ActionEvent actionEvent) {_x000D_
if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_
LocalDate datum = DatePickerDate.getValue();_x000D_
Object time = tijd.getValue();_x000D_
try {_x000D_
for (Klas klas : HU.getKlassen()) {_x000D_
for (Student student : klas.getStudenten()) {_x000D_
if (student.getisIngelogd()) {_x000D_
HashMap<String, Les> alleLessen = klas.getLessen();_x000D_
for (String lesNaam : alleLessen.keySet()) {_x000D_
if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_
alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in de les_x000D_
student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_
Button source = (Button) actionEvent.getSource();_x000D_
Stage stage = (Stage) source.getScene().getWindow();_x000D_
stage.close();_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
} catch (Exception e) {_x000D_
label.setText("ddddd");_x000D_
}_x000D_
} else label.setText("Je moet Datum en reden kiezen");_x000D_
}_x000D_
_x000D_
public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_
Button source = (Button) actionEvent.getSource();_x000D_
Stage stage = (Stage) source.getScene().getWindow();_x000D_
stage.close();_x000D_
}_x000D_
_x000D_
public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_
ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_
for (Klas klas : HU.getKlassen()) {_x000D_
for (Student student : klas.getStudenten()) {_x000D_
if (student.getisIngelogd()) {_x000D_
ArrayList<String> les = new ArrayList<>();_x000D_
_x000D_
HashMap<String, Les> alleLessen = klas.getLessen();_x000D_
for (Les lesNaam : alleLessen.values())_x000D_
if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_
// for (String les1 : alleLessen.keySet()) {_x000D_
les.add(lesNaam.getNaam());_x000D_
lessen.addAll(les);_x000D_
tijd.setItems(lessen);_x000D_
}_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
| HBO-ICT-GP-SD/Laatsteversie | AbsentieLijst/src/AbsentieLijst/userInterfaceLaag/ToekomstigAfmeldenController.java | 1,160 | //afgemeld_lijst in de les_x000D_ | line_comment | nl | package AbsentieLijst.userInterfaceLaag;_x000D_
_x000D_
import AbsentieLijst.*;_x000D_
import javafx.collections.FXCollections;_x000D_
import javafx.collections.ObservableList;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.fxml.FXMLLoader;_x000D_
import javafx.scene.Parent;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.control.ComboBox;_x000D_
import javafx.scene.control.DatePicker;_x000D_
import javafx.scene.control.Label;_x000D_
import javafx.scene.image.Image;_x000D_
import javafx.stage.Modality;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
import java.sql.Time;_x000D_
import java.time.LocalDate;_x000D_
import java.util.ArrayList;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class ToekomstigAfmeldenController {_x000D_
public Button ButtonOpslaan;_x000D_
public Button ButtonAnnuleren;_x000D_
public DatePicker DatePickerDate;_x000D_
public ComboBox ComboBoxReden;_x000D_
public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_
public Button overzicht;_x000D_
public Label label;_x000D_
public ComboBox tijd;_x000D_
_x000D_
School HU = School.getSchool();_x000D_
ObservableList<String> options =_x000D_
FXCollections.observableArrayList(_x000D_
"Bruiloft",_x000D_
"Tandarts afspraak",_x000D_
"Begravenis", "Wegens corona.", "Overig"_x000D_
);_x000D_
_x000D_
_x000D_
public void initialize() {_x000D_
ComboBoxReden.setItems(options);_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
public void ActionOpslaan(ActionEvent actionEvent) {_x000D_
if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_
LocalDate datum = DatePickerDate.getValue();_x000D_
Object time = tijd.getValue();_x000D_
try {_x000D_
for (Klas klas : HU.getKlassen()) {_x000D_
for (Student student : klas.getStudenten()) {_x000D_
if (student.getisIngelogd()) {_x000D_
HashMap<String, Les> alleLessen = klas.getLessen();_x000D_
for (String lesNaam : alleLessen.keySet()) {_x000D_
if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_
alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in<SUF>
student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_
Button source = (Button) actionEvent.getSource();_x000D_
Stage stage = (Stage) source.getScene().getWindow();_x000D_
stage.close();_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
} catch (Exception e) {_x000D_
label.setText("ddddd");_x000D_
}_x000D_
} else label.setText("Je moet Datum en reden kiezen");_x000D_
}_x000D_
_x000D_
public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_
Button source = (Button) actionEvent.getSource();_x000D_
Stage stage = (Stage) source.getScene().getWindow();_x000D_
stage.close();_x000D_
}_x000D_
_x000D_
public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_
ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_
for (Klas klas : HU.getKlassen()) {_x000D_
for (Student student : klas.getStudenten()) {_x000D_
if (student.getisIngelogd()) {_x000D_
ArrayList<String> les = new ArrayList<>();_x000D_
_x000D_
HashMap<String, Les> alleLessen = klas.getLessen();_x000D_
for (Les lesNaam : alleLessen.values())_x000D_
if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_
// for (String les1 : alleLessen.keySet()) {_x000D_
les.add(lesNaam.getNaam());_x000D_
lessen.addAll(les);_x000D_
tijd.setItems(lessen);_x000D_
}_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
| True | 1,461 | 16 | 1,586 | 17 | 1,603 | 16 | 1,586 | 17 | 1,762 | 17 | false | false | false | false | false | true |
4,535 | 10292_3 | package be.kuleuven.cs.distrinet.jnome.core.type;
import java.util.ArrayList;
import java.util.List;
import org.aikodi.chameleon.core.element.Element;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.TypeReference;
import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter;
import org.aikodi.chameleon.oo.type.generics.ExtendsConstraint;
import org.aikodi.chameleon.oo.type.generics.ExtendsWildcardType;
import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter;
import org.aikodi.chameleon.oo.type.generics.TypeArgument;
import org.aikodi.chameleon.oo.type.generics.TypeConstraint;
import org.aikodi.chameleon.oo.type.generics.TypeParameter;
import org.aikodi.chameleon.oo.view.ObjectOrientedView;
import org.aikodi.chameleon.workspace.View;
import be.kuleuven.cs.distrinet.jnome.core.language.Java7;
public class PureWildcard extends TypeArgument {
public PureWildcard() {
}
public TypeParameter capture(FormalTypeParameter formal) {
CapturedTypeParameter newParameter = new CapturedTypeParameter(formal.name());
capture(formal.constraints()).forEach(c -> newParameter.addConstraint(c));
return newParameter;
}
/**
* @param constraints
* @return
*/
public List<TypeConstraint> capture(List<TypeConstraint> constraints) {
List<TypeConstraint> newConstraints = new ArrayList<>();
for(TypeConstraint constraint: constraints) {
TypeConstraint clone = cloneAndResetTypeReference(constraint,constraint);
newConstraints.add(clone);
}
//FIXME This should actually be determined by the type parameter itself.
// perhaps it should compute its own upper bound reference
if(newConstraints.size() == 0) {
Java7 java = language(Java7.class);
BasicJavaTypeReference objectRef = java.createTypeReference(java.getDefaultSuperClassFQN());
TypeReference tref = java.createNonLocalTypeReference(objectRef,namespace().defaultNamespace());
newConstraints.add(new ExtendsConstraint(tref));
}
return newConstraints;
}
@Override
protected PureWildcard cloneSelf() {
return new PureWildcard();
}
// TypeVariable concept invoeren, en lowerbound,... verplaatsen naar daar? Deze is context sensitive. Hoewel, dat
// wordt toch nooit direct vergeleken. Er moet volgens mij altijd eerst gecaptured worden, dus dan moet dit inderdaad
// verplaatst worden. NOPE, niet altijd eerst capturen.
@Override
public Type lowerBound() throws LookupException {
View view = view();
ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class);
return l.getNullType(view.namespace());
}
@Override
public Type type() throws LookupException {
ExtendsWildcardType result = new ExtendsWildcardType(upperBound());
result.setUniParent(namespace().defaultNamespace());
return result;
// PureWildCardType pureWildCardType = new PureWildCardType(parameterBound());
// pureWildCardType.setUniParent(this);
// return pureWildCardType;
}
// public Type parameterBound() throws LookupException {
//// BasicJavaTypeReference nearestAncestor = nearestAncestor(BasicJavaTypeReference.class);
//// List<TypeArgument> args = nearestAncestor.typeArguments();
//// int index = args.indexOf(this);
//// // Wrong, this should not be the type constructor, we need to take into account the
//// // type instance
//// Type typeConstructor = nearestAncestor.typeConstructor();
//// Type typeInstance = nearestAncestor.getElement();
//// TypeParameter formalParameter = typeConstructor.parameter(TypeParameter.class,index);
//// TypeParameter actualParameter = typeInstance.parameter(TypeParameter.class, index);
//// TypeReference formalUpperBoundReference = formalParameter.upperBoundReference();
//// TypeReference clonedUpperBoundReference = clone(formalUpperBoundReference);
//// clonedUpperBoundReference.setUniParent(actualParameter);
////
////// Type result = formalParameter.upperBound(); // This fixes testGenericRejuse
//// Type result = clonedUpperBoundReference.getElement();
//// return result;
// }
@Override
public boolean uniSameAs(Element other) throws LookupException {
return other instanceof PureWildcard;
}
@Override
public Type upperBound() throws LookupException {
//return language(ObjectOrientedLanguage.class).getDefaultSuperClass();
return view(ObjectOrientedView.class).topLevelType();
}
@Override
public Verification verifySelf() {
return Valid.create();
}
public String toString(java.util.Set<Element> visited) {
return "?";
}
@Override
public boolean isWildCardBound() {
return true;
}
}
| tivervac/jnome | src/be/kuleuven/cs/distrinet/jnome/core/type/PureWildcard.java | 1,478 | // TypeVariable concept invoeren, en lowerbound,... verplaatsen naar daar? Deze is context sensitive. Hoewel, dat | line_comment | nl | package be.kuleuven.cs.distrinet.jnome.core.type;
import java.util.ArrayList;
import java.util.List;
import org.aikodi.chameleon.core.element.Element;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.TypeReference;
import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter;
import org.aikodi.chameleon.oo.type.generics.ExtendsConstraint;
import org.aikodi.chameleon.oo.type.generics.ExtendsWildcardType;
import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter;
import org.aikodi.chameleon.oo.type.generics.TypeArgument;
import org.aikodi.chameleon.oo.type.generics.TypeConstraint;
import org.aikodi.chameleon.oo.type.generics.TypeParameter;
import org.aikodi.chameleon.oo.view.ObjectOrientedView;
import org.aikodi.chameleon.workspace.View;
import be.kuleuven.cs.distrinet.jnome.core.language.Java7;
public class PureWildcard extends TypeArgument {
public PureWildcard() {
}
public TypeParameter capture(FormalTypeParameter formal) {
CapturedTypeParameter newParameter = new CapturedTypeParameter(formal.name());
capture(formal.constraints()).forEach(c -> newParameter.addConstraint(c));
return newParameter;
}
/**
* @param constraints
* @return
*/
public List<TypeConstraint> capture(List<TypeConstraint> constraints) {
List<TypeConstraint> newConstraints = new ArrayList<>();
for(TypeConstraint constraint: constraints) {
TypeConstraint clone = cloneAndResetTypeReference(constraint,constraint);
newConstraints.add(clone);
}
//FIXME This should actually be determined by the type parameter itself.
// perhaps it should compute its own upper bound reference
if(newConstraints.size() == 0) {
Java7 java = language(Java7.class);
BasicJavaTypeReference objectRef = java.createTypeReference(java.getDefaultSuperClassFQN());
TypeReference tref = java.createNonLocalTypeReference(objectRef,namespace().defaultNamespace());
newConstraints.add(new ExtendsConstraint(tref));
}
return newConstraints;
}
@Override
protected PureWildcard cloneSelf() {
return new PureWildcard();
}
// TypeVariable concept<SUF>
// wordt toch nooit direct vergeleken. Er moet volgens mij altijd eerst gecaptured worden, dus dan moet dit inderdaad
// verplaatst worden. NOPE, niet altijd eerst capturen.
@Override
public Type lowerBound() throws LookupException {
View view = view();
ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class);
return l.getNullType(view.namespace());
}
@Override
public Type type() throws LookupException {
ExtendsWildcardType result = new ExtendsWildcardType(upperBound());
result.setUniParent(namespace().defaultNamespace());
return result;
// PureWildCardType pureWildCardType = new PureWildCardType(parameterBound());
// pureWildCardType.setUniParent(this);
// return pureWildCardType;
}
// public Type parameterBound() throws LookupException {
//// BasicJavaTypeReference nearestAncestor = nearestAncestor(BasicJavaTypeReference.class);
//// List<TypeArgument> args = nearestAncestor.typeArguments();
//// int index = args.indexOf(this);
//// // Wrong, this should not be the type constructor, we need to take into account the
//// // type instance
//// Type typeConstructor = nearestAncestor.typeConstructor();
//// Type typeInstance = nearestAncestor.getElement();
//// TypeParameter formalParameter = typeConstructor.parameter(TypeParameter.class,index);
//// TypeParameter actualParameter = typeInstance.parameter(TypeParameter.class, index);
//// TypeReference formalUpperBoundReference = formalParameter.upperBoundReference();
//// TypeReference clonedUpperBoundReference = clone(formalUpperBoundReference);
//// clonedUpperBoundReference.setUniParent(actualParameter);
////
////// Type result = formalParameter.upperBound(); // This fixes testGenericRejuse
//// Type result = clonedUpperBoundReference.getElement();
//// return result;
// }
@Override
public boolean uniSameAs(Element other) throws LookupException {
return other instanceof PureWildcard;
}
@Override
public Type upperBound() throws LookupException {
//return language(ObjectOrientedLanguage.class).getDefaultSuperClass();
return view(ObjectOrientedView.class).topLevelType();
}
@Override
public Verification verifySelf() {
return Valid.create();
}
public String toString(java.util.Set<Element> visited) {
return "?";
}
@Override
public boolean isWildCardBound() {
return true;
}
}
| False | 1,117 | 28 | 1,317 | 32 | 1,313 | 25 | 1,317 | 32 | 1,513 | 30 | false | false | false | false | false | true |
4,516 | 147808_16 | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
/*
Bad ones
Model 1 = 93,119,
Model 2 = 67,98,
Classifier MP_ED acc =0.45555555555555555
Model 1 = 84,118,
Model 2 = 66,109,
*/
package statistics.simulators;
import fileIO.OutFile;
import java.util.*;
import java.io.*;
import statistics.distributions.NormalDistribution;
import statistics.simulators.DictionaryModel.ShapeType;
import static statistics.simulators.Model.rand;
import statistics.simulators.ShapeletModel.Shape;
public class MatrixProfileModelVersion1 extends Model {
private int nosLocations=2; //
private int shapeLength=29;
public static double MINBASE=-2;
public static double MINAMP=2;
public static double MAXBASE=2;
public static double MAXAMP=4;
DictionaryModel.Shape shape;//Will change for each series
private static int GLOBALSERIESLENGTH=500;
private int seriesLength; // Need to set intervals, maybe allow different lengths?
private int base=-1;
private int amplitude=2;
private int shapeCount=0;
private boolean invert=false;
boolean discord=false;
double[] shapeVals;
ArrayList<Integer> locations;
public static int getGlobalLength(){ return GLOBALSERIESLENGTH;}
public MatrixProfileModelVersion1(){
shapeCount=0;//rand.nextInt(ShapeType.values().length);
seriesLength=GLOBALSERIESLENGTH;
locations=new ArrayList<>();
setNonOverlappingIntervals();
shapeVals=new double[shapeLength];
generateRandomShapeVals();
}
public MatrixProfileModelVersion1(boolean d){
shapeCount=0;//rand.nextInt(ShapeType.values().length);
discord=d;
if(discord)
nosLocations=1;
seriesLength=GLOBALSERIESLENGTH;
locations=new ArrayList<>();
setNonOverlappingIntervals();
shapeVals=new double[shapeLength];
generateRandomShapeVals();
}
private void generateRandomShapeVals(){
for(int i=0;i<shapeLength;i++)
shapeVals[i]=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
}
public void setSeriesLength(int n){
seriesLength=n;
}
public static void setGlobalSeriesLength(int n){
GLOBALSERIESLENGTH=n;
}
public void setNonOverlappingIntervals(){
//Use Aarons way
ArrayList<Integer> startPoints=new ArrayList<>();
for(int i=shapeLength+1;i<seriesLength-shapeLength;i++)
startPoints.add(i);
for(int i=0;i<nosLocations;i++){
int pos=rand.nextInt(startPoints.size());
int l=startPoints.get(pos);
locations.add(l);
//+/- windowSize/2
if(pos<shapeLength)
pos=0;
else
pos=pos-shapeLength;
for(int j=0;startPoints.size()>pos && j<(3*shapeLength);j++)
startPoints.remove(pos);
/*
//Me giving up and just randomly placing the shapes until they are all non overlapping
for(int i=0;i<nosLocations;i++){
boolean ok=false;
int l=shapeLength/2;
while(!ok){
ok=true;
//Search mid points to level the distribution up somewhat
// System.out.println("Series length ="+seriesLength);
do{
l=rand.nextInt(seriesLength-shapeLength)+shapeLength/2;
}
while((l+shapeLength/2)>=seriesLength-shapeLength);
for(int in:locations){
//I think this is setting them too big
if((l>=in-shapeLength && l<in+shapeLength) //l inside ins
||(l<in-shapeLength && l+shapeLength>in) ){ //ins inside l
ok=false;
// System.out.println(l+" overlaps with "+in);
break;
}
}
}
*/
// System.out.println("Adding "+l);
}
/*//Revert to start points
for(int i=0;i<locations.size();i++){
int val=locations.get(i);
locations.set(i, val-shapeLength/2);
}
*/ Collections.sort(locations);
// System.out.println("MODEL START POINTS =");
// for(int i=0;i<locations.size();i++)
// System.out.println(locations.get(i));
}
@Override
public void setParameters(double[] p) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setLocations(ArrayList<Integer> l, int length){
locations=new ArrayList<>(l);
shapeLength=length;
}
public ArrayList<Integer> getIntervals(){return locations;}
public int getShapeLength(){ return shapeLength;}
public void generateBaseShape(){
//Randomise BASE and AMPLITUDE
double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble();
ShapeType[] all=ShapeType.values();
ShapeType st=all[(shapeCount++)%all.length];
shape=new DictionaryModel.Shape(st,shapeLength,b,a);
// shape=new DictionaryModel.Shape(DictionaryModel.ShapeType.SPIKE,shapeLength,b,a);
// System.out.println("Shape is "+shape);
// shape.nextShape();
// shape
}
@Override
public double[] generateSeries(int n)
{
t=0;
double[] d;
generateRandomShapeVals();
//Resets the starting locations each time this is called
if(invert){
d= new double[n];
for(int i=0;i<n;i++)
d[i]=-generate();
invert=false;
}
else{
generateBaseShape();
d = new double[n];
for(int i=0;i<n;i++)
d[i]=generate();
invert=true;
}
return d;
}
private double generateConfig1(){
//Noise
// System.out.println("Error var ="+error.getVariance());
double value=0;
//Find the next shape
int insertionPoint=0;
while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t)
insertionPoint++;
//Bigger than all the start points, set to last
if(insertionPoint>=locations.size()){
insertionPoint=locations.size()-1;
}
int point=locations.get(insertionPoint);
if(point<=t && point+shapeLength>t)//in shape1
value=shapeVals[(int)(t-point)];
else
value= error.simulate();
// value+=shape.generateWithinShapelet((int)(t-point));
// System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t);
t++;
return value;
}
private double generateConfig2(){
//Noise
// System.out.println("Error var ="+error.getVariance());
double value=error.simulate();
//Find the next shape
int insertionPoint=0;
while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t)
insertionPoint++;
//Bigger than all the start points, set to last
if(insertionPoint>=locations.size()){
insertionPoint=locations.size()-1;
}
int point=locations.get(insertionPoint);
if(insertionPoint>0 && point==t){//New shape, randomise scale
// double b=shape.getBase()/5;
// double a=shape.getAmp()/5;
double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble();
shape.setAmp(a);
shape.setBase(b);
// System.out.println("changing second shape");
}
if(point<=t && point+shapeLength>t){//in shape1
value+=shape.generateWithinShapelet((int)(t-point));
// System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t);
}
t++;
return value;
}
//Generate point t
@Override
public double generate(){
return generateConfig1();
}
public static void generateExampleData(){
int length=500;
GLOBALSERIESLENGTH=length;
Model.setGlobalRandomSeed(3);
Model.setDefaultSigma(0);
MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1();
MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1();
double[][] d=new double[20][];
for(int i=0;i<10;i++){
d[i]=m1.generateSeries(length);
}
for(int i=10;i<20;i++){
d[i]=m1.generateSeries(length);
}
OutFile of=new OutFile("C:\\temp\\MP_ExampleSeries.csv");
for(int i=0;i<length;i++){
for(int j=0;j<10;j++)
of.writeString(d[j][i]+",");
of.writeString("\n");
}
}
public String toString(){
String str="";
for(Integer i:locations)
str+=i+",";
return str;
}
public static void main(String[] args){
generateExampleData();
System.exit(0);
//Set up two models with same intervals but different shapes
int length=500;
Model.setGlobalRandomSeed(10);
Model.setDefaultSigma(0.1);
MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1();
MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1();
double[] d1=m1.generateSeries(length);
double[] d2=m2.generateSeries(length);
OutFile of=new OutFile("C:\\temp\\MP_Ex.csv");
for(int i=0;i<length;i++)
of.writeLine(d1[i]+","+d2[i]);
}
}
| time-series-machine-learning/tsml-java | src/main/java/statistics/simulators/MatrixProfileModelVersion1.java | 3,086 | // System.out.println("Error var ="+error.getVariance()); | line_comment | nl | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
/*
Bad ones
Model 1 = 93,119,
Model 2 = 67,98,
Classifier MP_ED acc =0.45555555555555555
Model 1 = 84,118,
Model 2 = 66,109,
*/
package statistics.simulators;
import fileIO.OutFile;
import java.util.*;
import java.io.*;
import statistics.distributions.NormalDistribution;
import statistics.simulators.DictionaryModel.ShapeType;
import static statistics.simulators.Model.rand;
import statistics.simulators.ShapeletModel.Shape;
public class MatrixProfileModelVersion1 extends Model {
private int nosLocations=2; //
private int shapeLength=29;
public static double MINBASE=-2;
public static double MINAMP=2;
public static double MAXBASE=2;
public static double MAXAMP=4;
DictionaryModel.Shape shape;//Will change for each series
private static int GLOBALSERIESLENGTH=500;
private int seriesLength; // Need to set intervals, maybe allow different lengths?
private int base=-1;
private int amplitude=2;
private int shapeCount=0;
private boolean invert=false;
boolean discord=false;
double[] shapeVals;
ArrayList<Integer> locations;
public static int getGlobalLength(){ return GLOBALSERIESLENGTH;}
public MatrixProfileModelVersion1(){
shapeCount=0;//rand.nextInt(ShapeType.values().length);
seriesLength=GLOBALSERIESLENGTH;
locations=new ArrayList<>();
setNonOverlappingIntervals();
shapeVals=new double[shapeLength];
generateRandomShapeVals();
}
public MatrixProfileModelVersion1(boolean d){
shapeCount=0;//rand.nextInt(ShapeType.values().length);
discord=d;
if(discord)
nosLocations=1;
seriesLength=GLOBALSERIESLENGTH;
locations=new ArrayList<>();
setNonOverlappingIntervals();
shapeVals=new double[shapeLength];
generateRandomShapeVals();
}
private void generateRandomShapeVals(){
for(int i=0;i<shapeLength;i++)
shapeVals[i]=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
}
public void setSeriesLength(int n){
seriesLength=n;
}
public static void setGlobalSeriesLength(int n){
GLOBALSERIESLENGTH=n;
}
public void setNonOverlappingIntervals(){
//Use Aarons way
ArrayList<Integer> startPoints=new ArrayList<>();
for(int i=shapeLength+1;i<seriesLength-shapeLength;i++)
startPoints.add(i);
for(int i=0;i<nosLocations;i++){
int pos=rand.nextInt(startPoints.size());
int l=startPoints.get(pos);
locations.add(l);
//+/- windowSize/2
if(pos<shapeLength)
pos=0;
else
pos=pos-shapeLength;
for(int j=0;startPoints.size()>pos && j<(3*shapeLength);j++)
startPoints.remove(pos);
/*
//Me giving up and just randomly placing the shapes until they are all non overlapping
for(int i=0;i<nosLocations;i++){
boolean ok=false;
int l=shapeLength/2;
while(!ok){
ok=true;
//Search mid points to level the distribution up somewhat
// System.out.println("Series length ="+seriesLength);
do{
l=rand.nextInt(seriesLength-shapeLength)+shapeLength/2;
}
while((l+shapeLength/2)>=seriesLength-shapeLength);
for(int in:locations){
//I think this is setting them too big
if((l>=in-shapeLength && l<in+shapeLength) //l inside ins
||(l<in-shapeLength && l+shapeLength>in) ){ //ins inside l
ok=false;
// System.out.println(l+" overlaps with "+in);
break;
}
}
}
*/
// System.out.println("Adding "+l);
}
/*//Revert to start points
for(int i=0;i<locations.size();i++){
int val=locations.get(i);
locations.set(i, val-shapeLength/2);
}
*/ Collections.sort(locations);
// System.out.println("MODEL START POINTS =");
// for(int i=0;i<locations.size();i++)
// System.out.println(locations.get(i));
}
@Override
public void setParameters(double[] p) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setLocations(ArrayList<Integer> l, int length){
locations=new ArrayList<>(l);
shapeLength=length;
}
public ArrayList<Integer> getIntervals(){return locations;}
public int getShapeLength(){ return shapeLength;}
public void generateBaseShape(){
//Randomise BASE and AMPLITUDE
double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble();
ShapeType[] all=ShapeType.values();
ShapeType st=all[(shapeCount++)%all.length];
shape=new DictionaryModel.Shape(st,shapeLength,b,a);
// shape=new DictionaryModel.Shape(DictionaryModel.ShapeType.SPIKE,shapeLength,b,a);
// System.out.println("Shape is "+shape);
// shape.nextShape();
// shape
}
@Override
public double[] generateSeries(int n)
{
t=0;
double[] d;
generateRandomShapeVals();
//Resets the starting locations each time this is called
if(invert){
d= new double[n];
for(int i=0;i<n;i++)
d[i]=-generate();
invert=false;
}
else{
generateBaseShape();
d = new double[n];
for(int i=0;i<n;i++)
d[i]=generate();
invert=true;
}
return d;
}
private double generateConfig1(){
//Noise
// System.out.println("Error var ="+error.getVariance());
double value=0;
//Find the next shape
int insertionPoint=0;
while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t)
insertionPoint++;
//Bigger than all the start points, set to last
if(insertionPoint>=locations.size()){
insertionPoint=locations.size()-1;
}
int point=locations.get(insertionPoint);
if(point<=t && point+shapeLength>t)//in shape1
value=shapeVals[(int)(t-point)];
else
value= error.simulate();
// value+=shape.generateWithinShapelet((int)(t-point));
// System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t);
t++;
return value;
}
private double generateConfig2(){
//Noise
// System.out.println("Error var<SUF>
double value=error.simulate();
//Find the next shape
int insertionPoint=0;
while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t)
insertionPoint++;
//Bigger than all the start points, set to last
if(insertionPoint>=locations.size()){
insertionPoint=locations.size()-1;
}
int point=locations.get(insertionPoint);
if(insertionPoint>0 && point==t){//New shape, randomise scale
// double b=shape.getBase()/5;
// double a=shape.getAmp()/5;
double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble();
shape.setAmp(a);
shape.setBase(b);
// System.out.println("changing second shape");
}
if(point<=t && point+shapeLength>t){//in shape1
value+=shape.generateWithinShapelet((int)(t-point));
// System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t);
}
t++;
return value;
}
//Generate point t
@Override
public double generate(){
return generateConfig1();
}
public static void generateExampleData(){
int length=500;
GLOBALSERIESLENGTH=length;
Model.setGlobalRandomSeed(3);
Model.setDefaultSigma(0);
MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1();
MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1();
double[][] d=new double[20][];
for(int i=0;i<10;i++){
d[i]=m1.generateSeries(length);
}
for(int i=10;i<20;i++){
d[i]=m1.generateSeries(length);
}
OutFile of=new OutFile("C:\\temp\\MP_ExampleSeries.csv");
for(int i=0;i<length;i++){
for(int j=0;j<10;j++)
of.writeString(d[j][i]+",");
of.writeString("\n");
}
}
public String toString(){
String str="";
for(Integer i:locations)
str+=i+",";
return str;
}
public static void main(String[] args){
generateExampleData();
System.exit(0);
//Set up two models with same intervals but different shapes
int length=500;
Model.setGlobalRandomSeed(10);
Model.setDefaultSigma(0.1);
MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1();
MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1();
double[] d1=m1.generateSeries(length);
double[] d2=m2.generateSeries(length);
OutFile of=new OutFile("C:\\temp\\MP_Ex.csv");
for(int i=0;i<length;i++)
of.writeLine(d1[i]+","+d2[i]);
}
}
| False | 2,361 | 15 | 2,635 | 17 | 2,844 | 17 | 2,635 | 17 | 3,061 | 18 | false | false | false | false | false | true |
222 | 167130_0 | package keezen;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Decks implements Serializable{
Kaart[] drawPile;
Kaart[] discardPile;
public Decks (){
}
public Kaart[] getDrawPile(){
return drawPile;
}
public void setAantalKaarten(int aantalKaarten){
drawPile = new Kaart[aantalKaarten];
discardPile = new Kaart[aantalKaarten];
}
public void setDrawPile(Kaart[] drawPile){
this.drawPile = drawPile;
}
public Kaart[] getDiscardPile(){
return discardPile;
}
public void setDiscardPile(Kaart[] discardPile){
this.discardPile = discardPile;
}
}
/*public class Decks implements Serializable {
Kaart[] drawPile;
Kaart[] discardPile;
public Decks (int aantalKaarten){
drawPile = new Kaart[aantalKaarten];
discardPile = new Kaart[aantalKaarten];
}
public Kaart[] getDrawPile() {
return drawPile;
}
public void setDrawPile(Kaart[] drawPile) {
this.drawPile = drawPile;
}
public Kaart[] getDiscardPile() {
return discardPile;
}
public void setDiscardPile(Kaart[] discardPile) {
this.discardPile = discardPile;
}
}*/
| Bobster94/Keezen | src/keezen/Decks.java | 459 | /*public class Decks implements Serializable {
Kaart[] drawPile;
Kaart[] discardPile;
public Decks (int aantalKaarten){
drawPile = new Kaart[aantalKaarten];
discardPile = new Kaart[aantalKaarten];
}
public Kaart[] getDrawPile() {
return drawPile;
}
public void setDrawPile(Kaart[] drawPile) {
this.drawPile = drawPile;
}
public Kaart[] getDiscardPile() {
return discardPile;
}
public void setDiscardPile(Kaart[] discardPile) {
this.discardPile = discardPile;
}
}*/ | block_comment | nl | package keezen;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Decks implements Serializable{
Kaart[] drawPile;
Kaart[] discardPile;
public Decks (){
}
public Kaart[] getDrawPile(){
return drawPile;
}
public void setAantalKaarten(int aantalKaarten){
drawPile = new Kaart[aantalKaarten];
discardPile = new Kaart[aantalKaarten];
}
public void setDrawPile(Kaart[] drawPile){
this.drawPile = drawPile;
}
public Kaart[] getDiscardPile(){
return discardPile;
}
public void setDiscardPile(Kaart[] discardPile){
this.discardPile = discardPile;
}
}
/*public class Decks<SUF>*/
| False | 342 | 157 | 420 | 186 | 367 | 162 | 420 | 186 | 474 | 208 | false | false | false | false | false | true |
556 | 77274_2 | package com.jypec.wavelet.liftingTransforms;
import com.jypec.util.arrays.ArrayTransforms;
import com.jypec.wavelet.Wavelet;
import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform;
/**
* CDF 9 7 adaptation from:
* https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform
*
* @author Daniel
*
*/
public class LiftingCdf97WaveletTransform implements Wavelet {
private static final float COEFF_PREDICT_1 = -1.586134342f;
private static final float COEFF_PREDICT_2 = 0.8829110762f;
private static final float COEFF_UPDATE_1= -0.05298011854f;
private static final float COEFF_UPDATE_2 = 0.4435068522f;
private static final float COEFF_SCALE = 1/1.149604398f;
/**
* Adds to each odd indexed sample its neighbors multiplied by the given coefficient
* Wraps around if needed, mirroring the array <br>
* E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br>
* {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4}
* @param s the signal to be treated
* @param n the length of s
* @param COEFF the prediction coefficient
*/
private void predict(float[] s, int n, float COEFF) {
// Predict inner values
for (int i = 1; i < n - 1; i+=2) {
s[i] += COEFF * (s[i-1] + s[i+1]);
}
// Wrap around
if (n % 2 == 0 && n > 1) {
s[n-1] += 2*COEFF*s[n-2];
}
}
/**
* Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient
* Wraps around if needed, mirroring the array
* E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3}
* {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1}
* @param s the signal to be treated
* @param n the length of s
* @param COEFF the updating coefficient
*/
private void update(float[]s, int n, float COEFF) {
// Update first coeff
if (n > 1) {
s[0] += 2*COEFF*s[1];
}
// Update inner values
for (int i = 2; i < n - 1; i+=2) {
s[i] += COEFF * (s[i-1] + s[i+1]);
}
// Wrap around
if (n % 2 != 0 && n > 1) {
s[n-1] += 2*COEFF*s[n-2];
}
}
/**
* Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF
* @param s the signal to be scaled
* @param n the length of s
* @param COEFF the coefficient applied
*/
private void scale(float[] s, int n, float COEFF) {
for (int i = 0; i < n; i++) {
if (i%2 == 1) {
s[i] *= COEFF;
} else {
s[i] /= COEFF;
}
}
}
@Override
public void forwardTransform(float[] s, int n) {
//predict and update
predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1);
update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1);
predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2);
update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2);
//scale values
scale(s, n, LiftingCdf97WaveletTransform.COEFF_SCALE);
//pack values (low freq first, high freq last)
ArrayTransforms.pack(s, n);
}
@Override
public void reverseTransform(float[] s, int n) {
//unpack values
ArrayTransforms.unpack(s, n);
//unscale values
scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_SCALE);
//unpredict and unupdate
update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2);
predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2);
update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1);
predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1);
}
@Override
public float maxResult(float min, float max) {
return new KernelCdf97WaveletTransform().maxResult(min, max);
}
@Override
public float minResult(float min, float max) {
return new KernelCdf97WaveletTransform().minResult(min, max);
}
}
| GRSEB9S/Jypec | src/com/jypec/wavelet/liftingTransforms/LiftingCdf97WaveletTransform.java | 1,512 | // Predict inner values | line_comment | nl | package com.jypec.wavelet.liftingTransforms;
import com.jypec.util.arrays.ArrayTransforms;
import com.jypec.wavelet.Wavelet;
import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform;
/**
* CDF 9 7 adaptation from:
* https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform
*
* @author Daniel
*
*/
public class LiftingCdf97WaveletTransform implements Wavelet {
private static final float COEFF_PREDICT_1 = -1.586134342f;
private static final float COEFF_PREDICT_2 = 0.8829110762f;
private static final float COEFF_UPDATE_1= -0.05298011854f;
private static final float COEFF_UPDATE_2 = 0.4435068522f;
private static final float COEFF_SCALE = 1/1.149604398f;
/**
* Adds to each odd indexed sample its neighbors multiplied by the given coefficient
* Wraps around if needed, mirroring the array <br>
* E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br>
* {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4}
* @param s the signal to be treated
* @param n the length of s
* @param COEFF the prediction coefficient
*/
private void predict(float[] s, int n, float COEFF) {
// Predict inner<SUF>
for (int i = 1; i < n - 1; i+=2) {
s[i] += COEFF * (s[i-1] + s[i+1]);
}
// Wrap around
if (n % 2 == 0 && n > 1) {
s[n-1] += 2*COEFF*s[n-2];
}
}
/**
* Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient
* Wraps around if needed, mirroring the array
* E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3}
* {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1}
* @param s the signal to be treated
* @param n the length of s
* @param COEFF the updating coefficient
*/
private void update(float[]s, int n, float COEFF) {
// Update first coeff
if (n > 1) {
s[0] += 2*COEFF*s[1];
}
// Update inner values
for (int i = 2; i < n - 1; i+=2) {
s[i] += COEFF * (s[i-1] + s[i+1]);
}
// Wrap around
if (n % 2 != 0 && n > 1) {
s[n-1] += 2*COEFF*s[n-2];
}
}
/**
* Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF
* @param s the signal to be scaled
* @param n the length of s
* @param COEFF the coefficient applied
*/
private void scale(float[] s, int n, float COEFF) {
for (int i = 0; i < n; i++) {
if (i%2 == 1) {
s[i] *= COEFF;
} else {
s[i] /= COEFF;
}
}
}
@Override
public void forwardTransform(float[] s, int n) {
//predict and update
predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1);
update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1);
predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2);
update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2);
//scale values
scale(s, n, LiftingCdf97WaveletTransform.COEFF_SCALE);
//pack values (low freq first, high freq last)
ArrayTransforms.pack(s, n);
}
@Override
public void reverseTransform(float[] s, int n) {
//unpack values
ArrayTransforms.unpack(s, n);
//unscale values
scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_SCALE);
//unpredict and unupdate
update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2);
predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2);
update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1);
predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1);
}
@Override
public float maxResult(float min, float max) {
return new KernelCdf97WaveletTransform().maxResult(min, max);
}
@Override
public float minResult(float min, float max) {
return new KernelCdf97WaveletTransform().minResult(min, max);
}
}
| False | 1,313 | 4 | 1,421 | 4 | 1,427 | 4 | 1,421 | 4 | 1,623 | 5 | false | false | false | false | false | true |
4,470 | 18288_9 | /*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server;
import de._13ducks.cor.debug.UltimateDebug;
import de._13ducks.cor.game.server.movement.ServerMoveManager;
import de._13ducks.cor.networks.server.ServerNetController;
import de._13ducks.cor.game.Building;
import de._13ducks.cor.game.Unit;
import de._13ducks.cor.game.NetPlayer.races;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import de._13ducks.cor.game.Core;
import de._13ducks.cor.game.NetPlayer;
import de._13ducks.cor.game.server.movement.ServerAttackManager;
/**
* Der Server-Kern
*
* Startet einen Server mit den dazugehörigen Server-Modulen etc...
*
* Erzeugt ein seperates Logfile (server_log.txt)
*
* @author tfg
*/
public class ServerCore extends Core {
ServerCore.InnerServer rgi;
ServerNetController servNet;
ServerMapModule mapMod;
ServerGameController gamectrl;
ServerStatistics sstat; //Statistik
ServerMoveManager smoveman;
public boolean ready; // gibt an, ob das Spiel gestartet werden soll.
public ServerCore(boolean debug, String Mapname) {
debugmode = debug;
rgi = new ServerCore.InnerServer();
initLogger();
rgi.logger("[Core] Reading config...");
if (debugmode) {
System.out.println("Configuration:");
}
// Konfigurationsdatei lesen
cfgvalues = new HashMap();
File cfgFile = new File("server_cfg.txt");
try {
FileReader cfgReader = new FileReader(cfgFile);
BufferedReader reader = new BufferedReader(cfgReader);
String zeile = null;
int i = 0; // Anzahl der Durchläufe zählen
while ((zeile = reader.readLine()) != null) {
// Liest Zeile fuer Zeile, jetzt auswerten und in Variablen
// schreiben
int indexgleich = zeile.indexOf('='); // Istgleich suchen
if (indexgleich == -1) {
} else {
String v1 = zeile.substring(0, indexgleich); // Vor dem =
// rauschneiden
String v2 = zeile.substring(indexgleich + 1); // Nach dem
// =
// rausschneiden
System.out.println(v1 + " = " + v2);
cfgvalues.put(v1, v2);
if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen
rgi.logger("[Core-Log] " + v1 + "=" + v2);
}
}
}
reader.close();
} catch (FileNotFoundException e1) {
// cfg-Datei nicht gefunden - inakzeptabel!
rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one...");
try {
cfgFile.createNewFile();
} catch (IOException ex) {
System.out.print("Error creating server_cfg.txt .");
}
//rgi.shutdown(1);
} catch (IOException e2) {
// Inakzeptabel
e2.printStackTrace();
rgi.logger("[Core-ERROR] Critical I/O Error");
rgi.shutdown(1);
}
if ("true".equals(cfgvalues.get("ultimateDebug"))) {
UltimateDebug udb = UltimateDebug.getInstance();
udb.authorizeDebug(this, rgi);
}
// Läuft als Server
rgi.logger("[CoreInit]: Starting server mode...");
// Module laden
rgi.logger("[CoreInit]: Loading modules...");
rgi.logger("[CoreInit]: Loading gamecontroller");
gamectrl = new ServerGameController(rgi);
// Netzwerk
rgi.logger("[CoreInit]: Loading serverNetController");
servNet = new ServerNetController(rgi, this);
rgi.logger("[CoreInit]: Loading serverMapmodul");
mapMod = new ServerMapModule(rgi);
rgi.logger("[CoreInit]: Loading serverStatistics");
sstat = new ServerStatistics(rgi);
rgi.logger("[CoreInit]: Loading serverMoveManager");
smoveman = new ServerMoveManager();
// Alle Module geladen, starten
rgi.initInner();
rgi.logger("[Core]: Initializing modules...");
mapMod.initModule();
rgi.logger("[Core]: Init done, starting Server...");
Thread t = new Thread(servNet);
t.start();
rgi.logger("[Core]: Server running");
try {
// Auf Startsignal warten
while (!this.ready) {
Thread.sleep(1000);
}
// Jetzt darf niemand mehr rein
servNet.closeAcception();
// Zufallsvölker bestimmen und allen Clients mitteilen:
for (NetPlayer p : this.gamectrl.playerList) {
if (p.lobbyRace == races.random) {
if (Math.rint(Math.random()) == 1) {
p.lobbyRace = 1;
this.servNet.broadcastString(("91" + p.nickName), (byte) 14);
} else {
p.lobbyRace = 2;
this.servNet.broadcastString(("92" + p.nickName), (byte) 14);
}
}
}
// Clients vorbereiten
servNet.loadGame();
// Warte darauf, das alle soweit sind
waitForStatus(1);
// Spiel laden
mapMod.loadMap(Mapname);
waitForStatus(2);
// Game vorbereiten
servNet.initGame((byte) 8);
// Starteinheiten & Gebäude an das gewählte Volk anpassen:
for (NetPlayer player : this.gamectrl.playerList) {
// Gebäude:
for (Building building : this.rgi.netmap.buildingList) {
if (building.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
building.performUpgrade(rgi, 1001);
} else if (player.lobbyRace == races.human) {
building.performUpgrade(rgi, 1);
}
}
}
// Einheiten:
for (Unit unit : this.rgi.netmap.unitList) {
if (unit.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
// 401=human worker, 1401=undead worker
if (unit.getDescTypeId() == 401) {
unit.performUpgrade(rgi, 1401);
}
// 402=human scout, 1402=undead mage
if (unit.getDescTypeId() == 402) {
unit.performUpgrade(rgi, 1402);
}
} else if (player.lobbyRace == races.human) {
// 1401=undead worker, 401=human worker
if (unit.getDescTypeId() == 1401) {
unit.performUpgrade(rgi, 401);
}
// 1402=undead mage, 402=human scout
if (unit.getDescTypeId() == 1402) {
unit.performUpgrade(rgi, 402);
}
}
}
}
}
waitForStatus(3);
servNet.startGame();
} catch (InterruptedException ex) {
}
}
/**
* Synchronisierte Funktipon zum Strings senden
* wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat
* @param s - zu sendender String
* @param cmdid - command-id
*/
public synchronized void broadcastStringSynchronized(String s, byte cmdid) {
s += "\0";
this.servNet.broadcastString(s, cmdid);
}
private void waitForStatus(int status) throws InterruptedException {
while (true) {
Thread.sleep(50);
boolean go = true;
for (ServerNetController.ServerHandler servhan : servNet.clientconnection) {
if (servhan.loadStatus < status) {
go = false;
break;
}
}
if (go) {
break;
}
}
}
@Override
public void initLogger() {
if (!logOFF) {
// Erstellt ein neues Logfile
try {
FileWriter logcreator = new FileWriter("server_log.txt");
logcreator.close();
} catch (IOException ex) {
// Warscheinlich darf man das nicht, den Adminmodus emfehlen
JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
rgi.shutdown(2);
}
}
}
public class InnerServer extends Core.CoreInner {
public ServerNetController netctrl;
public ServerMapModule netmap;
public ServerGameController game;
public ServerStatistics serverstats;
String lastlog = "";
public ServerMoveManager moveMan;
public ServerAttackManager atkMan;
@Override
public void initInner() {
super.initInner();
// Server-Referenz initialisiern:
Server.setInnerServer(this);
netctrl = servNet;
netmap = mapMod;
game = gamectrl;
serverstats = sstat;
moveMan = smoveman;
atkMan = new ServerAttackManager();
}
@Override
public void logger(String x) {
if (!logOFF) {
if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern
lastlog = x;
// Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die
// log-Datei
try {
FileWriter logwriter = new FileWriter("server_log.txt", true);
String temp = String.format("%tc", new Date()) + " - " + x + "\n";
logwriter.append(temp);
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
@Override
public void logger(Throwable t) {
if (!logOFF) {
// Nimmt Exceptions an und schreibt den Stacktrace ins
// logfile
try {
if (debugmode) {
System.out.println("ERROR!!!! More info in logfile...");
}
FileWriter logwriter = new FileWriter("server_log.txt", true);
logwriter.append('\n' + String.format("%tc", new Date()) + " - ");
logwriter.append("[JavaError]: " + t.toString() + '\n');
StackTraceElement[] errorArray;
errorArray = t.getStackTrace();
for (int i = 0; i < errorArray.length; i++) {
logwriter.append(" " + errorArray[i].toString() + '\n');
}
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
}
| tfg13/Centuries-of-Rage | src/de/_13ducks/cor/game/server/ServerCore.java | 3,501 | // Alle Module geladen, starten | line_comment | nl | /*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server;
import de._13ducks.cor.debug.UltimateDebug;
import de._13ducks.cor.game.server.movement.ServerMoveManager;
import de._13ducks.cor.networks.server.ServerNetController;
import de._13ducks.cor.game.Building;
import de._13ducks.cor.game.Unit;
import de._13ducks.cor.game.NetPlayer.races;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import de._13ducks.cor.game.Core;
import de._13ducks.cor.game.NetPlayer;
import de._13ducks.cor.game.server.movement.ServerAttackManager;
/**
* Der Server-Kern
*
* Startet einen Server mit den dazugehörigen Server-Modulen etc...
*
* Erzeugt ein seperates Logfile (server_log.txt)
*
* @author tfg
*/
public class ServerCore extends Core {
ServerCore.InnerServer rgi;
ServerNetController servNet;
ServerMapModule mapMod;
ServerGameController gamectrl;
ServerStatistics sstat; //Statistik
ServerMoveManager smoveman;
public boolean ready; // gibt an, ob das Spiel gestartet werden soll.
public ServerCore(boolean debug, String Mapname) {
debugmode = debug;
rgi = new ServerCore.InnerServer();
initLogger();
rgi.logger("[Core] Reading config...");
if (debugmode) {
System.out.println("Configuration:");
}
// Konfigurationsdatei lesen
cfgvalues = new HashMap();
File cfgFile = new File("server_cfg.txt");
try {
FileReader cfgReader = new FileReader(cfgFile);
BufferedReader reader = new BufferedReader(cfgReader);
String zeile = null;
int i = 0; // Anzahl der Durchläufe zählen
while ((zeile = reader.readLine()) != null) {
// Liest Zeile fuer Zeile, jetzt auswerten und in Variablen
// schreiben
int indexgleich = zeile.indexOf('='); // Istgleich suchen
if (indexgleich == -1) {
} else {
String v1 = zeile.substring(0, indexgleich); // Vor dem =
// rauschneiden
String v2 = zeile.substring(indexgleich + 1); // Nach dem
// =
// rausschneiden
System.out.println(v1 + " = " + v2);
cfgvalues.put(v1, v2);
if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen
rgi.logger("[Core-Log] " + v1 + "=" + v2);
}
}
}
reader.close();
} catch (FileNotFoundException e1) {
// cfg-Datei nicht gefunden - inakzeptabel!
rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one...");
try {
cfgFile.createNewFile();
} catch (IOException ex) {
System.out.print("Error creating server_cfg.txt .");
}
//rgi.shutdown(1);
} catch (IOException e2) {
// Inakzeptabel
e2.printStackTrace();
rgi.logger("[Core-ERROR] Critical I/O Error");
rgi.shutdown(1);
}
if ("true".equals(cfgvalues.get("ultimateDebug"))) {
UltimateDebug udb = UltimateDebug.getInstance();
udb.authorizeDebug(this, rgi);
}
// Läuft als Server
rgi.logger("[CoreInit]: Starting server mode...");
// Module laden
rgi.logger("[CoreInit]: Loading modules...");
rgi.logger("[CoreInit]: Loading gamecontroller");
gamectrl = new ServerGameController(rgi);
// Netzwerk
rgi.logger("[CoreInit]: Loading serverNetController");
servNet = new ServerNetController(rgi, this);
rgi.logger("[CoreInit]: Loading serverMapmodul");
mapMod = new ServerMapModule(rgi);
rgi.logger("[CoreInit]: Loading serverStatistics");
sstat = new ServerStatistics(rgi);
rgi.logger("[CoreInit]: Loading serverMoveManager");
smoveman = new ServerMoveManager();
// Alle Module<SUF>
rgi.initInner();
rgi.logger("[Core]: Initializing modules...");
mapMod.initModule();
rgi.logger("[Core]: Init done, starting Server...");
Thread t = new Thread(servNet);
t.start();
rgi.logger("[Core]: Server running");
try {
// Auf Startsignal warten
while (!this.ready) {
Thread.sleep(1000);
}
// Jetzt darf niemand mehr rein
servNet.closeAcception();
// Zufallsvölker bestimmen und allen Clients mitteilen:
for (NetPlayer p : this.gamectrl.playerList) {
if (p.lobbyRace == races.random) {
if (Math.rint(Math.random()) == 1) {
p.lobbyRace = 1;
this.servNet.broadcastString(("91" + p.nickName), (byte) 14);
} else {
p.lobbyRace = 2;
this.servNet.broadcastString(("92" + p.nickName), (byte) 14);
}
}
}
// Clients vorbereiten
servNet.loadGame();
// Warte darauf, das alle soweit sind
waitForStatus(1);
// Spiel laden
mapMod.loadMap(Mapname);
waitForStatus(2);
// Game vorbereiten
servNet.initGame((byte) 8);
// Starteinheiten & Gebäude an das gewählte Volk anpassen:
for (NetPlayer player : this.gamectrl.playerList) {
// Gebäude:
for (Building building : this.rgi.netmap.buildingList) {
if (building.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
building.performUpgrade(rgi, 1001);
} else if (player.lobbyRace == races.human) {
building.performUpgrade(rgi, 1);
}
}
}
// Einheiten:
for (Unit unit : this.rgi.netmap.unitList) {
if (unit.getPlayerId() == player.playerId) {
if (player.lobbyRace == races.undead) {
// 401=human worker, 1401=undead worker
if (unit.getDescTypeId() == 401) {
unit.performUpgrade(rgi, 1401);
}
// 402=human scout, 1402=undead mage
if (unit.getDescTypeId() == 402) {
unit.performUpgrade(rgi, 1402);
}
} else if (player.lobbyRace == races.human) {
// 1401=undead worker, 401=human worker
if (unit.getDescTypeId() == 1401) {
unit.performUpgrade(rgi, 401);
}
// 1402=undead mage, 402=human scout
if (unit.getDescTypeId() == 1402) {
unit.performUpgrade(rgi, 402);
}
}
}
}
}
waitForStatus(3);
servNet.startGame();
} catch (InterruptedException ex) {
}
}
/**
* Synchronisierte Funktipon zum Strings senden
* wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat
* @param s - zu sendender String
* @param cmdid - command-id
*/
public synchronized void broadcastStringSynchronized(String s, byte cmdid) {
s += "\0";
this.servNet.broadcastString(s, cmdid);
}
private void waitForStatus(int status) throws InterruptedException {
while (true) {
Thread.sleep(50);
boolean go = true;
for (ServerNetController.ServerHandler servhan : servNet.clientconnection) {
if (servhan.loadStatus < status) {
go = false;
break;
}
}
if (go) {
break;
}
}
}
@Override
public void initLogger() {
if (!logOFF) {
// Erstellt ein neues Logfile
try {
FileWriter logcreator = new FileWriter("server_log.txt");
logcreator.close();
} catch (IOException ex) {
// Warscheinlich darf man das nicht, den Adminmodus emfehlen
JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
rgi.shutdown(2);
}
}
}
public class InnerServer extends Core.CoreInner {
public ServerNetController netctrl;
public ServerMapModule netmap;
public ServerGameController game;
public ServerStatistics serverstats;
String lastlog = "";
public ServerMoveManager moveMan;
public ServerAttackManager atkMan;
@Override
public void initInner() {
super.initInner();
// Server-Referenz initialisiern:
Server.setInnerServer(this);
netctrl = servNet;
netmap = mapMod;
game = gamectrl;
serverstats = sstat;
moveMan = smoveman;
atkMan = new ServerAttackManager();
}
@Override
public void logger(String x) {
if (!logOFF) {
if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern
lastlog = x;
// Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die
// log-Datei
try {
FileWriter logwriter = new FileWriter("server_log.txt", true);
String temp = String.format("%tc", new Date()) + " - " + x + "\n";
logwriter.append(temp);
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
@Override
public void logger(Throwable t) {
if (!logOFF) {
// Nimmt Exceptions an und schreibt den Stacktrace ins
// logfile
try {
if (debugmode) {
System.out.println("ERROR!!!! More info in logfile...");
}
FileWriter logwriter = new FileWriter("server_log.txt", true);
logwriter.append('\n' + String.format("%tc", new Date()) + " - ");
logwriter.append("[JavaError]: " + t.toString() + '\n');
StackTraceElement[] errorArray;
errorArray = t.getStackTrace();
for (int i = 0; i < errorArray.length; i++) {
logwriter.append(" " + errorArray[i].toString() + '\n');
}
logwriter.flush();
logwriter.close();
} catch (IOException ex) {
ex.printStackTrace();
shutdown(2);
}
}
}
}
}
| True | 2,732 | 8 | 3,026 | 9 | 3,095 | 6 | 3,026 | 9 | 3,534 | 8 | false | false | false | false | false | true |
501 | 15652_9 | /* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */
/* JavaCCOptions:STATIC=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package fhv;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (without unicode processing).
*/
public class SimpleCharStream
{
/** Whether parser is static. */
public static final boolean staticFlag = true;
static int bufsize;
static int available;
static int tokenBegin;
/** Position in buffer. */
static public int bufpos = -1;
static protected int bufline[];
static protected int bufcolumn[];
static protected int column = 0;
static protected int line = 1;
static protected boolean prevCharIsCR = false;
static protected boolean prevCharIsLF = false;
static protected java.io.Reader inputStream;
static protected char[] buffer;
static protected int maxNextCharInd = 0;
static protected int inBuf = 0;
static protected int tabSize = 8;
static protected void setTabSize(int i) { tabSize = i; }
static protected int getTabSize(int i) { return tabSize; }
static protected void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos += (bufsize - tokenBegin));
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos -= tokenBegin);
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
bufsize += 2048;
available = bufsize;
tokenBegin = 0;
}
static protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
/** Start. */
static public char BeginToken() throws java.io.IOException
{
tokenBegin = -1;
char c = readChar();
tokenBegin = bufpos;
return c;
}
static protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (tabSize - (column % tabSize));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
/** Read a character. */
static public char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
return buffer[bufpos];
}
if (++bufpos >= maxNextCharInd)
FillBuff();
char c = buffer[bufpos];
UpdateLineColumn(c);
return c;
}
@Deprecated
/**
* @deprecated
* @see #getEndColumn
*/
static public int getColumn() {
return bufcolumn[bufpos];
}
@Deprecated
/**
* @deprecated
* @see #getEndLine
*/
static public int getLine() {
return bufline[bufpos];
}
/** Get token end column number. */
static public int getEndColumn() {
return bufcolumn[bufpos];
}
/** Get token end line number. */
static public int getEndLine() {
return bufline[bufpos];
}
/** Get token beginning column number. */
static public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
/** Get token beginning line number. */
static public int getBeginLine() {
return bufline[tokenBegin];
}
/** Backup a number of characters. */
static public void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
if (inputStream != null)
throw new Error("\n ERROR: Second call to the constructor of a static SimpleCharStream.\n" +
" You must either use ReInit() or set the JavaCC option STATIC to false\n" +
" during the generation of this class.");
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length)
{
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
bufpos = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Get token literal value. */
static public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
/** Get the suffix. */
static public char[] GetSuffix(int len)
{
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else
{
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
/** Reset buffer when finished. */
static public void Done()
{
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.
*/
static public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
}
/* JavaCC - OriginalChecksum=767e99b039c1576e8d2b2c644c6d31bb (do not edit this line) */
| FHV-ITM13/Just-Language | Justy_Wachter/src/fhv/SimpleCharStream.java | 3,932 | /** Get token beginning column number. */ | block_comment | nl | /* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */
/* JavaCCOptions:STATIC=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package fhv;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (without unicode processing).
*/
public class SimpleCharStream
{
/** Whether parser is static. */
public static final boolean staticFlag = true;
static int bufsize;
static int available;
static int tokenBegin;
/** Position in buffer. */
static public int bufpos = -1;
static protected int bufline[];
static protected int bufcolumn[];
static protected int column = 0;
static protected int line = 1;
static protected boolean prevCharIsCR = false;
static protected boolean prevCharIsLF = false;
static protected java.io.Reader inputStream;
static protected char[] buffer;
static protected int maxNextCharInd = 0;
static protected int inBuf = 0;
static protected int tabSize = 8;
static protected void setTabSize(int i) { tabSize = i; }
static protected int getTabSize(int i) { return tabSize; }
static protected void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos += (bufsize - tokenBegin));
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos -= tokenBegin);
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
bufsize += 2048;
available = bufsize;
tokenBegin = 0;
}
static protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
/** Start. */
static public char BeginToken() throws java.io.IOException
{
tokenBegin = -1;
char c = readChar();
tokenBegin = bufpos;
return c;
}
static protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (tabSize - (column % tabSize));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
/** Read a character. */
static public char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
return buffer[bufpos];
}
if (++bufpos >= maxNextCharInd)
FillBuff();
char c = buffer[bufpos];
UpdateLineColumn(c);
return c;
}
@Deprecated
/**
* @deprecated
* @see #getEndColumn
*/
static public int getColumn() {
return bufcolumn[bufpos];
}
@Deprecated
/**
* @deprecated
* @see #getEndLine
*/
static public int getLine() {
return bufline[bufpos];
}
/** Get token end column number. */
static public int getEndColumn() {
return bufcolumn[bufpos];
}
/** Get token end line number. */
static public int getEndLine() {
return bufline[bufpos];
}
/** Get token beginning<SUF>*/
static public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
/** Get token beginning line number. */
static public int getBeginLine() {
return bufline[tokenBegin];
}
/** Backup a number of characters. */
static public void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
if (inputStream != null)
throw new Error("\n ERROR: Second call to the constructor of a static SimpleCharStream.\n" +
" You must either use ReInit() or set the JavaCC option STATIC to false\n" +
" during the generation of this class.");
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length)
{
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
bufpos = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Get token literal value. */
static public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
/** Get the suffix. */
static public char[] GetSuffix(int len)
{
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else
{
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
/** Reset buffer when finished. */
static public void Done()
{
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.
*/
static public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
}
/* JavaCC - OriginalChecksum=767e99b039c1576e8d2b2c644c6d31bb (do not edit this line) */
| False | 3,180 | 8 | 3,372 | 8 | 3,750 | 8 | 3,372 | 8 | 3,978 | 8 | false | false | false | false | false | true |
3,832 | 169507_0 | package nl.njtromp.adventofcode_2020;
import java.util.Arrays;
public class Infi {
static long aantalPakjes(long lengteZijkant) {
return
3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal
4 * sommatie(lengteZijkant) + // Schuine zijden (4 halve driehoeken)
2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven)
}
private static long sommatie(long n) {
return (n-1)*n/2;
}
private static long bepaalLengte(long aantalInwoners) {
long lengte = 1;
while (aantalPakjes(lengte) < aantalInwoners) {
lengte++;
}
return lengte;
}
public static void main(String[] args) {
long lengte = bepaalLengte(17_493_412);
System.out.printf("De minimale lengte van een zijde is: %d\n", lengte);
long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L};
System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8);
}
}
| njtromp/AdventOfCode-2020 | src/main/java/nl/njtromp/adventofcode_2020/Infi.java | 436 | // Schuine zijden (4 halve driehoeken) | line_comment | nl | package nl.njtromp.adventofcode_2020;
import java.util.Arrays;
public class Infi {
static long aantalPakjes(long lengteZijkant) {
return
3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal
4 * sommatie(lengteZijkant) + // Schuine zijden<SUF>
2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven)
}
private static long sommatie(long n) {
return (n-1)*n/2;
}
private static long bepaalLengte(long aantalInwoners) {
long lengte = 1;
while (aantalPakjes(lengte) < aantalInwoners) {
lengte++;
}
return lengte;
}
public static void main(String[] args) {
long lengte = bepaalLengte(17_493_412);
System.out.printf("De minimale lengte van een zijde is: %d\n", lengte);
long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L};
System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8);
}
}
| True | 416 | 15 | 461 | 17 | 420 | 12 | 461 | 17 | 465 | 14 | false | false | false | false | false | true |
1,893 | 30813_5 | package shapes;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import properties.Property;
import utility.MeasureFetcher;
import utility.Util;
import be.kuleuven.cs.oss.polymorphicviews.plugin.PolymorphicChartParameters;
public abstract class ShapeGenerator {
protected MeasureFetcher measureFetcher;
protected Shape[] shapes;
protected PolymorphicChartParameters params;
private Property<Double> width;
private Property<Double> height;
private Property<Color> color;
public ShapeGenerator(MeasureFetcher measureFetcher, Property<Double> width, Property<Double> height, Property<Color> color) {
this.measureFetcher=measureFetcher;
this.width = width;
this.height = height;
this.color = color;
}
/**
* This method gives all boxes the correct values.
* @param width that should be given to all boxes (number or metric)
* @param height that should be given to all boxes (number or metric)
* @param color that should be given to all boxes (rgb format or grayscale with metric)
* @return
*/
public Shape[] getShapes() {
return this.shapes;
}
/**
* This method returns a list of colors, one for each shape. If
* the input is in RGB format, the color is the same for all shapes. If the
* format "min<float>max<float>key<string>" is used as input, the color of
* each box is dependent on a specific measure of the box. Else, the color
* will be set to default color
*
* @param color
* the color/metric to be used
* @return a list with a color for each box
*/
protected List<Color> getShapeColors(String color) {
List<Color> result = new ArrayList<Color>();
if(Util.isValidColor(color)){
Color rgb = Util.parseColor(color);
result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb));
}
else{ //the color parsing is invalid and the string should be of the format "min<float>max<float>key<string>"
try{
String[] splitted = Util.splitOnDelimiter(color, new String[]{"min","max","key"});
Double min = Double.parseDouble(splitted[0]);
Double max = Double.parseDouble(splitted[1]);
String key = splitted[2];
result = getGrayScaleColors(min, max, key);
}
//Given input is not valid
catch (IllegalArgumentException f){
Color rgb = Util.parseColor(PolymorphicChartParameters.DEFAULT_BOXCOLOR);
result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb));
}
}
return result;
}
/**
* This method scales a list of metric values to a new list, with the lowest
* value of the metric scaled to min, and the highest scaled to max.
*
* @param min
* the minimum color value of the list with scaled colors
* @param max
* the maximum color value of the list with scaled colors
* @param key
* the key that represents the metric that should be scaled
* @return a list with the scaled color values
*/
private List<Color> getGrayScaleColors(Double min, Double max, String key) throws IllegalArgumentException{
//TODO hoe werkt dees eigenlijk. vage opgave
Map<String, Double> colors = measureFetcher.getMeasureValues(key);
Map<String, Double> scaledColors = Util.scaleGrey(colors, min, max);
List<Color> result = new ArrayList<Color>();
try{
for (int i = 0; i < shapes.length; i++) {
String name = shapes[i].getName();
int colorValue = scaledColors.get(name).intValue();
Color c = new Color(colorValue, colorValue, colorValue);
result.add(c);
}
return result;
}
catch(Exception e){
throw new IllegalArgumentException();
}
}
/**
* This method names all the shapes with the correct resource names.
*/
protected void nameShapes() {
List<String> names = measureFetcher.getResourceNames();
int i = 0;
for (String s : names) {
shapes[i].setName(s);
i++;
}
}
} | WoutV/OSS_1415 | sonar-polymorphic-views/src/main/java/shapes/ShapeGenerator.java | 1,195 | //TODO hoe werkt dees eigenlijk. vage opgave | line_comment | nl | package shapes;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import properties.Property;
import utility.MeasureFetcher;
import utility.Util;
import be.kuleuven.cs.oss.polymorphicviews.plugin.PolymorphicChartParameters;
public abstract class ShapeGenerator {
protected MeasureFetcher measureFetcher;
protected Shape[] shapes;
protected PolymorphicChartParameters params;
private Property<Double> width;
private Property<Double> height;
private Property<Color> color;
public ShapeGenerator(MeasureFetcher measureFetcher, Property<Double> width, Property<Double> height, Property<Color> color) {
this.measureFetcher=measureFetcher;
this.width = width;
this.height = height;
this.color = color;
}
/**
* This method gives all boxes the correct values.
* @param width that should be given to all boxes (number or metric)
* @param height that should be given to all boxes (number or metric)
* @param color that should be given to all boxes (rgb format or grayscale with metric)
* @return
*/
public Shape[] getShapes() {
return this.shapes;
}
/**
* This method returns a list of colors, one for each shape. If
* the input is in RGB format, the color is the same for all shapes. If the
* format "min<float>max<float>key<string>" is used as input, the color of
* each box is dependent on a specific measure of the box. Else, the color
* will be set to default color
*
* @param color
* the color/metric to be used
* @return a list with a color for each box
*/
protected List<Color> getShapeColors(String color) {
List<Color> result = new ArrayList<Color>();
if(Util.isValidColor(color)){
Color rgb = Util.parseColor(color);
result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb));
}
else{ //the color parsing is invalid and the string should be of the format "min<float>max<float>key<string>"
try{
String[] splitted = Util.splitOnDelimiter(color, new String[]{"min","max","key"});
Double min = Double.parseDouble(splitted[0]);
Double max = Double.parseDouble(splitted[1]);
String key = splitted[2];
result = getGrayScaleColors(min, max, key);
}
//Given input is not valid
catch (IllegalArgumentException f){
Color rgb = Util.parseColor(PolymorphicChartParameters.DEFAULT_BOXCOLOR);
result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb));
}
}
return result;
}
/**
* This method scales a list of metric values to a new list, with the lowest
* value of the metric scaled to min, and the highest scaled to max.
*
* @param min
* the minimum color value of the list with scaled colors
* @param max
* the maximum color value of the list with scaled colors
* @param key
* the key that represents the metric that should be scaled
* @return a list with the scaled color values
*/
private List<Color> getGrayScaleColors(Double min, Double max, String key) throws IllegalArgumentException{
//TODO hoe<SUF>
Map<String, Double> colors = measureFetcher.getMeasureValues(key);
Map<String, Double> scaledColors = Util.scaleGrey(colors, min, max);
List<Color> result = new ArrayList<Color>();
try{
for (int i = 0; i < shapes.length; i++) {
String name = shapes[i].getName();
int colorValue = scaledColors.get(name).intValue();
Color c = new Color(colorValue, colorValue, colorValue);
result.add(c);
}
return result;
}
catch(Exception e){
throw new IllegalArgumentException();
}
}
/**
* This method names all the shapes with the correct resource names.
*/
protected void nameShapes() {
List<String> names = measureFetcher.getResourceNames();
int i = 0;
for (String s : names) {
shapes[i].setName(s);
i++;
}
}
} | False | 937 | 15 | 1,078 | 16 | 1,099 | 12 | 1,078 | 16 | 1,275 | 17 | false | false | false | false | false | true |
1,859 | 150349_0 | /* avondvierdaagse.java
*
* Pieter Eendebak
* eendebak at math uu nl
*
*/
import java.util.StringTokenizer;
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.lang.Math;
class Mud {
public long x, y;
}
class MudCompare implements Comparator{
public int compare(Object a, Object b) {
Mud A = (Mud)a;
Mud B = (Mud)b;
return (A.x-B.x)<0?-1:1;
}
}
class Main {
public static StringTokenizer tok;
public static String line;
public static BufferedReader in;
public static void write(String s) {
System.out.print(s);
}
public static void writen(String s) {
System.out.print(s+"\n");
}
public static int readInt() throws Exception {
tok();
return nextInt();
}
public static void tok() throws Exception {
tok = new StringTokenizer(in.readLine());
}
public static String nextString() throws Exception {
return (String)tok.nextToken();
}
public static int nextInt() throws Exception {
return Integer.parseInt((String)tok.nextToken());
}
public static void main(String[] args) throws Exception {
in = new BufferedReader( new InputStreamReader(System.in) );
int runs = readInt();
for( int run=0; run<runs; run++ )
doit();
}
public static void doit() throws Exception
{
int n; long l;
// read in data
tok();
n = nextInt();
l = nextInt();
//writen("Doing run with "+n+" mudpools");
Mud [] mudpool = new Mud[n];
int i = 0, j;
for(i=0;i<n;i++) {
tok();
mudpool[i] = new Mud();
mudpool[i].x = nextInt();
mudpool[i].y = nextInt();
//writen("read " + mudpool[i].x + " " + mudpool[i].y);
}
// find optimal number of planks
Arrays.sort( mudpool, new MudCompare());
long end=0;
long pl=0;
i=0;
while(i<n) {
//writen("i: " + i + " pl: " + pl + " end: " + end);
if(mudpool[i].y>end) {
// add new plank
end = l + Math.max(end, mudpool[i].x);
pl++;
}
else i++;
}
// print the results
writen(""+pl);
}
}
| WISVCH/chipcie-website | static/archive/2004/nkp/c/oplossing.java | 782 | /* avondvierdaagse.java
*
* Pieter Eendebak
* eendebak at math uu nl
*
*/ | block_comment | nl | /* avondvierdaagse.java
*<SUF>*/
import java.util.StringTokenizer;
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.lang.Math;
class Mud {
public long x, y;
}
class MudCompare implements Comparator{
public int compare(Object a, Object b) {
Mud A = (Mud)a;
Mud B = (Mud)b;
return (A.x-B.x)<0?-1:1;
}
}
class Main {
public static StringTokenizer tok;
public static String line;
public static BufferedReader in;
public static void write(String s) {
System.out.print(s);
}
public static void writen(String s) {
System.out.print(s+"\n");
}
public static int readInt() throws Exception {
tok();
return nextInt();
}
public static void tok() throws Exception {
tok = new StringTokenizer(in.readLine());
}
public static String nextString() throws Exception {
return (String)tok.nextToken();
}
public static int nextInt() throws Exception {
return Integer.parseInt((String)tok.nextToken());
}
public static void main(String[] args) throws Exception {
in = new BufferedReader( new InputStreamReader(System.in) );
int runs = readInt();
for( int run=0; run<runs; run++ )
doit();
}
public static void doit() throws Exception
{
int n; long l;
// read in data
tok();
n = nextInt();
l = nextInt();
//writen("Doing run with "+n+" mudpools");
Mud [] mudpool = new Mud[n];
int i = 0, j;
for(i=0;i<n;i++) {
tok();
mudpool[i] = new Mud();
mudpool[i].x = nextInt();
mudpool[i].y = nextInt();
//writen("read " + mudpool[i].x + " " + mudpool[i].y);
}
// find optimal number of planks
Arrays.sort( mudpool, new MudCompare());
long end=0;
long pl=0;
i=0;
while(i<n) {
//writen("i: " + i + " pl: " + pl + " end: " + end);
if(mudpool[i].y>end) {
// add new plank
end = l + Math.max(end, mudpool[i].x);
pl++;
}
else i++;
}
// print the results
writen(""+pl);
}
}
| False | 600 | 30 | 721 | 34 | 720 | 29 | 721 | 34 | 847 | 34 | false | false | false | false | false | true |
2,133 | 202595_10 | Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in
diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
INTUITION,
go along to diaonals and incrememnt but i-1, j+1
to do in reverse order, store all elements in arraylist and then reverse
REGULAR DIAONGAL MATRIX
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
int m= matrix.length;
int n= matrix[0].length;
int index =0;
int[] res = new int[m*n];
for(int k=0; k<=m-1; k++){
int i=k; // to print all the diagonals starting on left row
int j=0; //starts on first col always
while(i>=0){ //go until we reach the upper bord
res[index++]=matrix[i][j];
i=i-1;
j=j+1;
}
}
for(int k=1; k<=n-1; k++){ //HAVE TO START FROM K=1 to skip over the diagonl that gets counted twice
int i = m-1; //starts on last rol always
int j= k; //to print all diagonals starting at bottom row
while(j<=n-1){ //go until we reach the right border
res[index++]=matrix[i][j];
i=i-1;
j=j+1;
}
}
return res;
}
}
SAME AS DIAOGONAL, but if the diagonl we are on is odd, we will reverse all the elemetnts,
THEN add to result
//TC: O(N*M) to go thorugh the entire matrix, O(K) to clear the matrix
//SC: O(min(N,M)) to store elements in arraylist
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return new int[0];
int m = matrix.length;
int n = matrix[0].length;
int[] res = new int[m*n];
int resIndex = 0;
ArrayList<Integer> temp = new ArrayList<>();
for(int k=0; k<m; k++){
temp.clear(); //clear out this temp array
int i = k;
int j =0;
while(i>=0){
temp.add(matrix[i][j]); //copy this elemeent
i= i-1;
j=j+1;
}
if(k%2 == 1){
Collections.reverse(temp);
}
for(int x: temp){
res[resIndex++] = x;
}
}
for(int k=1; k<n; k++){ //NOTE, need to go from k=1 to skip of, BIGGEST DIAGONAL counted twice
temp.clear(); //clear out this temp array
int i = m-1;
int j = k;
while(j< n){
temp.add((matrix[i][j]));
i=i-1;
j=j+1;
}
if(k%2 == 1){
Collections.reverse(temp);
}
for(int x: temp){
res[resIndex++] = x;
}
}
return res;
}
}
// If out of bottom border (row >= m) then row = m - 1; col += 2; change walk direction.
// if out of right border (col >= n) then col = n - 1; row += 2; change walk direction.
// if out of top border (row < 0) then row = 0; change walk direction.
// if out of left border (col < 0) then col = 0; change walk direction.
// Otherwise, just go along with the current direction.
BEST SOLUTION
//O(M*N)
//O(1) constant space solutioN!!!!
public class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0) return new int[0];
int m = matrix.length, n = matrix[0].length;
int[] result = new int[m * n];
int row = 0, col = 0, d = 0; //first direction we go is upright
int[][] dirs = {{-1, 1}, {1, -1}};
for (int i = 0; i < m * n; i++) {
result[i] = matrix[row][col];
row += dirs[d][0];
col += dirs[d][1];
if (row >= m) { row = m - 1; col += 2; d = 1 - d;}
if (col >= n) { col = n - 1; row += 2; d = 1 - d;} //out on right botder
if (row < 0) { row = 0; d = 1 - d;} //out on top border, reset
if (col < 0) { col = 0; d = 1 - d;} // out on left border, reset col
}
return result;
}
} | armankhondker/best-leetcode-resources | leetcode-solutions/diagonalMatrixPrint.java | 1,455 | //copy this elemeent | line_comment | nl | Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in
diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
INTUITION,
go along to diaonals and incrememnt but i-1, j+1
to do in reverse order, store all elements in arraylist and then reverse
REGULAR DIAONGAL MATRIX
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
int m= matrix.length;
int n= matrix[0].length;
int index =0;
int[] res = new int[m*n];
for(int k=0; k<=m-1; k++){
int i=k; // to print all the diagonals starting on left row
int j=0; //starts on first col always
while(i>=0){ //go until we reach the upper bord
res[index++]=matrix[i][j];
i=i-1;
j=j+1;
}
}
for(int k=1; k<=n-1; k++){ //HAVE TO START FROM K=1 to skip over the diagonl that gets counted twice
int i = m-1; //starts on last rol always
int j= k; //to print all diagonals starting at bottom row
while(j<=n-1){ //go until we reach the right border
res[index++]=matrix[i][j];
i=i-1;
j=j+1;
}
}
return res;
}
}
SAME AS DIAOGONAL, but if the diagonl we are on is odd, we will reverse all the elemetnts,
THEN add to result
//TC: O(N*M) to go thorugh the entire matrix, O(K) to clear the matrix
//SC: O(min(N,M)) to store elements in arraylist
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return new int[0];
int m = matrix.length;
int n = matrix[0].length;
int[] res = new int[m*n];
int resIndex = 0;
ArrayList<Integer> temp = new ArrayList<>();
for(int k=0; k<m; k++){
temp.clear(); //clear out this temp array
int i = k;
int j =0;
while(i>=0){
temp.add(matrix[i][j]); //copy this<SUF>
i= i-1;
j=j+1;
}
if(k%2 == 1){
Collections.reverse(temp);
}
for(int x: temp){
res[resIndex++] = x;
}
}
for(int k=1; k<n; k++){ //NOTE, need to go from k=1 to skip of, BIGGEST DIAGONAL counted twice
temp.clear(); //clear out this temp array
int i = m-1;
int j = k;
while(j< n){
temp.add((matrix[i][j]));
i=i-1;
j=j+1;
}
if(k%2 == 1){
Collections.reverse(temp);
}
for(int x: temp){
res[resIndex++] = x;
}
}
return res;
}
}
// If out of bottom border (row >= m) then row = m - 1; col += 2; change walk direction.
// if out of right border (col >= n) then col = n - 1; row += 2; change walk direction.
// if out of top border (row < 0) then row = 0; change walk direction.
// if out of left border (col < 0) then col = 0; change walk direction.
// Otherwise, just go along with the current direction.
BEST SOLUTION
//O(M*N)
//O(1) constant space solutioN!!!!
public class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0) return new int[0];
int m = matrix.length, n = matrix[0].length;
int[] result = new int[m * n];
int row = 0, col = 0, d = 0; //first direction we go is upright
int[][] dirs = {{-1, 1}, {1, -1}};
for (int i = 0; i < m * n; i++) {
result[i] = matrix[row][col];
row += dirs[d][0];
col += dirs[d][1];
if (row >= m) { row = m - 1; col += 2; d = 1 - d;}
if (col >= n) { col = n - 1; row += 2; d = 1 - d;} //out on right botder
if (row < 0) { row = 0; d = 1 - d;} //out on top border, reset
if (col < 0) { col = 0; d = 1 - d;} // out on left border, reset col
}
return result;
}
} | False | 1,213 | 7 | 1,293 | 7 | 1,374 | 7 | 1,293 | 7 | 1,445 | 7 | false | false | false | false | false | true |
2,501 | 75359_9 | /**
* Repraesentiert ein Auto.
*
*/
abstract class Car implements Runnable{
//Repraesentiert einer der vier Himmelsrichtungen, in die das Auto zeigen kann.
private Orientations orientation;
private int x;
private int y;
private String name;
protected int millisecondsToWait;
protected Racetrack currentRacetrack;
private Thread t;
private int steps = 0;
private int score = 0;
/**
* Initialisiere ein Auto.
*
* @param x - Startposition
* @param y - Startposition
* @param startOrientation - Anfangsorientierung
* @param carName - Name des Autos
*/
public Car(int x, int y, Orientations startOrientation, String carName){
this.x = x;
this.y = y;
this.orientation = startOrientation;
this.name = carName;
this.millisecondsToWait = 0;
}
public Car(Orientations startOrientation, String carName){
this(0, 0, startOrientation, carName);
}
//VB: setOrientation darf nur ausgefuehrt werden, wenn vorher eine passende
//Beweung stattgefunden hat.
public void setOrientation(Orientations orientation){
this.orientation = orientation;
}
public Orientations getOrientation(){
return this.orientation;
}
public int getX(){
return this.x;
}
public int getY(){
return this.y;
}
//VB: x >= 0
public void setX(int x) {
this.x = x;
}
//VB: y >= 0
public void setY(int y) {
this.y = y;
}
//VB: rt != null
//VB: Das Rennen auf diesem Track darf noch nicht begonnen haben
public void setRacetrack(Racetrack rt) {
this.currentRacetrack = rt;
}
//VB: Rennen hat begonnen
//NB: Der Thread laeuft.
public void startCar(){
this.t = new Thread(this);
t.start();
}
//Autos haben nur einen eingeschraenkten Aktionsradius, der hier ueberprueft wird.
//Unterklassen liefern passenden boolean zurueck.
protected boolean canDriveTo(Directions direction){
return false;
}
//Wird vom Thread aufgerufen. Implementierung in Unterklassen.
protected abstract void drive() throws InterruptedException;
public int getScore() {
return score;
}
//Erhoeht den Score um eins.
public void upScore() {
score += 1;
}
// Verringert den Score um eins.
public void downScore() {
score -= 1;
}
public int getSteps() {
return steps;
}
//Erhoeht die Schritte um eins.
public void upSteps() {
steps += 1;
}
// NB: Thread wurde angewiesen, abzubrechen.
public void stop(){
if(t != null){
t.interrupt();
}
}
/**
* Thread Methode, die unterbrochen werden kann. Ruft drive Methode auf.
* Am Ende der Methode wird der Name und Score ausgegeben, da das
* Rennen zu Ende ist.
*
*/
@Override
public void run() {
while( !Thread.interrupted() ){
try {
this.drive();
Thread.sleep(millisecondsToWait);
}catch(InterruptedException e){
break;
}
}
System.out.println("Auto \'"+name + "\' Punkte=" + score);
}
@Override
public String toString() {
return name;
}
// NB: Es laeuft fuer diese Instanz kein Thread mehr.
public void join() throws InterruptedException {
t.join();
}
}
| danurna/oop7 | src/Car.java | 1,086 | //VB: Rennen hat begonnen | line_comment | nl | /**
* Repraesentiert ein Auto.
*
*/
abstract class Car implements Runnable{
//Repraesentiert einer der vier Himmelsrichtungen, in die das Auto zeigen kann.
private Orientations orientation;
private int x;
private int y;
private String name;
protected int millisecondsToWait;
protected Racetrack currentRacetrack;
private Thread t;
private int steps = 0;
private int score = 0;
/**
* Initialisiere ein Auto.
*
* @param x - Startposition
* @param y - Startposition
* @param startOrientation - Anfangsorientierung
* @param carName - Name des Autos
*/
public Car(int x, int y, Orientations startOrientation, String carName){
this.x = x;
this.y = y;
this.orientation = startOrientation;
this.name = carName;
this.millisecondsToWait = 0;
}
public Car(Orientations startOrientation, String carName){
this(0, 0, startOrientation, carName);
}
//VB: setOrientation darf nur ausgefuehrt werden, wenn vorher eine passende
//Beweung stattgefunden hat.
public void setOrientation(Orientations orientation){
this.orientation = orientation;
}
public Orientations getOrientation(){
return this.orientation;
}
public int getX(){
return this.x;
}
public int getY(){
return this.y;
}
//VB: x >= 0
public void setX(int x) {
this.x = x;
}
//VB: y >= 0
public void setY(int y) {
this.y = y;
}
//VB: rt != null
//VB: Das Rennen auf diesem Track darf noch nicht begonnen haben
public void setRacetrack(Racetrack rt) {
this.currentRacetrack = rt;
}
//VB: Rennen<SUF>
//NB: Der Thread laeuft.
public void startCar(){
this.t = new Thread(this);
t.start();
}
//Autos haben nur einen eingeschraenkten Aktionsradius, der hier ueberprueft wird.
//Unterklassen liefern passenden boolean zurueck.
protected boolean canDriveTo(Directions direction){
return false;
}
//Wird vom Thread aufgerufen. Implementierung in Unterklassen.
protected abstract void drive() throws InterruptedException;
public int getScore() {
return score;
}
//Erhoeht den Score um eins.
public void upScore() {
score += 1;
}
// Verringert den Score um eins.
public void downScore() {
score -= 1;
}
public int getSteps() {
return steps;
}
//Erhoeht die Schritte um eins.
public void upSteps() {
steps += 1;
}
// NB: Thread wurde angewiesen, abzubrechen.
public void stop(){
if(t != null){
t.interrupt();
}
}
/**
* Thread Methode, die unterbrochen werden kann. Ruft drive Methode auf.
* Am Ende der Methode wird der Name und Score ausgegeben, da das
* Rennen zu Ende ist.
*
*/
@Override
public void run() {
while( !Thread.interrupted() ){
try {
this.drive();
Thread.sleep(millisecondsToWait);
}catch(InterruptedException e){
break;
}
}
System.out.println("Auto \'"+name + "\' Punkte=" + score);
}
@Override
public String toString() {
return name;
}
// NB: Es laeuft fuer diese Instanz kein Thread mehr.
public void join() throws InterruptedException {
t.join();
}
}
| False | 868 | 8 | 905 | 10 | 982 | 6 | 905 | 10 | 1,078 | 8 | false | false | false | false | false | true |
808 | 152641_17 | package intecbrussel.be.Vaccination;_x000D_
_x000D_
import java.util.*;_x000D_
import java.util.stream.Collectors;_x000D_
_x000D_
public class AnimalShelter {_x000D_
private List<Animal> animals;_x000D_
private int animalId;_x000D_
_x000D_
public AnimalShelter() {_x000D_
this.animals = new ArrayList<>();_x000D_
this.animalId = 1;_x000D_
}_x000D_
_x000D_
public List<Animal> getAnimals() {_x000D_
return animals;_x000D_
}_x000D_
_x000D_
public void setAnimals(List<Animal> animals) {_x000D_
this.animals = animals;_x000D_
}_x000D_
_x000D_
public int getAnimalId() {_x000D_
return animalId;_x000D_
}_x000D_
_x000D_
public void setAnimalId(int animalId) {_x000D_
this.animalId = animalId;_x000D_
}_x000D_
//1_x000D_
public void printAnimals(){_x000D_
for (Animal animal : animals){_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
}_x000D_
// sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber._x000D_
//2_x000D_
public void sortAnimals(){_x000D_
animals.sort(Comparator.comparing(Animal::getAnimalNumber));_x000D_
}_x000D_
//sorteert de dieren op naam_x000D_
//3_x000D_
public void sortAnimalsByName(){_x000D_
animals.sort(Comparator.comparing(Animal::getName));_x000D_
}_x000D_
// sorteert de dieren op leeftijd_x000D_
//4_x000D_
public void sortAnimalsByAge(){_x000D_
animals.sort(Comparator.comparing(Animal::getAge));_x000D_
}_x000D_
//print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte_x000D_
//5_x000D_
public void printAnimalsNotVaccinated(Disease disease){_x000D_
List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());_x000D_
for (Animal animal : notVaccinated){_x000D_
System.out.println(animal.getName()+" is not vaccinated "+disease.name());_x000D_
}_x000D_
}_x000D_
//zoek dier op dierennummer_x000D_
//6_x000D_
public Animal findAnimal(int animalNumber) {_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAnimalNumber() == animalNumber){_x000D_
return animal;_x000D_
}_x000D_
}_x000D_
return null;_x000D_
// return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();_x000D_
}_x000D_
_x000D_
//zoek dier op dierennaam_x000D_
//7_x000D_
public Optional<Animal> findAnimal(String name){_x000D_
return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();_x000D_
_x000D_
}_x000D_
// behandel opgegeven dier_x000D_
//8_x000D_
public void treatAnimal(int animalNumber){_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAnimalNumber()==animalNumber){_x000D_
System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
//System.out.println("animal with number "+animalNumber+"not found");_x000D_
/* animals.stream()_x000D_
.sorted(Comparator.comparingInt(Animal::getAnimalNumber))_x000D_
.forEach(animal -> System.out.println(_x000D_
"Animal number: "+animal.getAnimalNumber()+_x000D_
"| name: "+animal.getName()+_x000D_
"| age: "+animal.getAge()+_x000D_
"| is clean? "+animal.getIsVaccinated()_x000D_
));///////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_
/*Optional<Animal> optionalAnimal = findAnimal(animalNumber);_x000D_
if (optionalAnimal.isPresent()){_x000D_
Animal animal = optionalAnimal.get();_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}else {_x000D_
System.out.println("animal met number "+animalNumber+"not found");_x000D_
}*/_x000D_
}_x000D_
//behandel opgegeven dier_x000D_
//9_x000D_
public void treatAnimal(String name){_x000D_
for (Animal animal : animals){_x000D_
if (animal.getName()==name){_x000D_
System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());_x000D_
_x000D_
}_x000D_
}_x000D_
/*animals.stream()_x000D_
.sorted(Comparator.comparing(Animal::getName))_x000D_
.forEach(animal -> System.out.println(_x000D_
"name: "+animal.getName()+_x000D_
"| animal number: "+animal.getAnimalNumber()+_x000D_
"| age: "+animal.getAge()+_x000D_
"| is clean? "+animal.getIsVaccinated()_x000D_
));/////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_
/* Optional<Animal> optionalAnimal = findAnimal(name);_x000D_
if (optionalAnimal.isPresent()){_x000D_
Animal animal = optionalAnimal.get();_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}else {_x000D_
System.out.println("animal met name "+name+ "not found");_x000D_
}*/_x000D_
_x000D_
}_x000D_
//behandel alle dieren_x000D_
//10_x000D_
public void treatAllAnimals(){_x000D_
for (Animal animal : animals){_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
_x000D_
}_x000D_
//geef het oudste dier terug_x000D_
//11_x000D_
public Animal findOldestAnimal() throws NoSuchElementException {_x000D_
if (animals.isEmpty()) {_x000D_
throw new NoSuchElementException("No animal found in this list");_x000D_
}_x000D_
Animal oldestAnimal = animals.get(0);_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAge() > oldestAnimal.getAge()){_x000D_
oldestAnimal = animal;_x000D_
//System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
}_x000D_
return oldestAnimal;_x000D_
_x000D_
}_x000D_
_x000D_
// geef het aantal dieren terug_x000D_
//12_x000D_
public int countAnimals(){_x000D_
if (animals != null){_x000D_
return animals.size();_x000D_
}else {_x000D_
return 0;_x000D_
}_x000D_
}_x000D_
_x000D_
//voeg een dier toe aan de lijst van animals_x000D_
//13_x000D_
public void addAnimal(Animal animal) throws IllegalArgumentException{_x000D_
if (animal != null){_x000D_
animal.setAnimalNumber(animalId);//toewijzen de nummer animal_x000D_
animals.add(animal);//add de animal to de list_x000D_
animalId++;//verhoog de animal id_x000D_
}else {_x000D_
throw new IllegalArgumentException("Can not add null animal to de list");_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
| JananJavdan/Vaccination | Vaccination/src/main/java/intecbrussel/be/Vaccination/AnimalShelter.java | 2,073 | //toewijzen de nummer animal_x000D_ | line_comment | nl | package intecbrussel.be.Vaccination;_x000D_
_x000D_
import java.util.*;_x000D_
import java.util.stream.Collectors;_x000D_
_x000D_
public class AnimalShelter {_x000D_
private List<Animal> animals;_x000D_
private int animalId;_x000D_
_x000D_
public AnimalShelter() {_x000D_
this.animals = new ArrayList<>();_x000D_
this.animalId = 1;_x000D_
}_x000D_
_x000D_
public List<Animal> getAnimals() {_x000D_
return animals;_x000D_
}_x000D_
_x000D_
public void setAnimals(List<Animal> animals) {_x000D_
this.animals = animals;_x000D_
}_x000D_
_x000D_
public int getAnimalId() {_x000D_
return animalId;_x000D_
}_x000D_
_x000D_
public void setAnimalId(int animalId) {_x000D_
this.animalId = animalId;_x000D_
}_x000D_
//1_x000D_
public void printAnimals(){_x000D_
for (Animal animal : animals){_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
}_x000D_
// sorteert de dieren volgens hun natuurlijke volgorde, dit is volgens hun animalNumber._x000D_
//2_x000D_
public void sortAnimals(){_x000D_
animals.sort(Comparator.comparing(Animal::getAnimalNumber));_x000D_
}_x000D_
//sorteert de dieren op naam_x000D_
//3_x000D_
public void sortAnimalsByName(){_x000D_
animals.sort(Comparator.comparing(Animal::getName));_x000D_
}_x000D_
// sorteert de dieren op leeftijd_x000D_
//4_x000D_
public void sortAnimalsByAge(){_x000D_
animals.sort(Comparator.comparing(Animal::getAge));_x000D_
}_x000D_
//print alle dieren af die niet gevaccineert zijn voor een opgegeven ziekte_x000D_
//5_x000D_
public void printAnimalsNotVaccinated(Disease disease){_x000D_
List<Animal> notVaccinated = animals.stream().filter(animal -> animal.getIsVaccinated().getOrDefault(disease, false)).collect(Collectors.toList());_x000D_
for (Animal animal : notVaccinated){_x000D_
System.out.println(animal.getName()+" is not vaccinated "+disease.name());_x000D_
}_x000D_
}_x000D_
//zoek dier op dierennummer_x000D_
//6_x000D_
public Animal findAnimal(int animalNumber) {_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAnimalNumber() == animalNumber){_x000D_
return animal;_x000D_
}_x000D_
}_x000D_
return null;_x000D_
// return animals.stream().filter(animal -> animal.getAnimalNumber()==animalNumber).findFirst();_x000D_
}_x000D_
_x000D_
//zoek dier op dierennaam_x000D_
//7_x000D_
public Optional<Animal> findAnimal(String name){_x000D_
return animals.stream().filter(animal -> animal.getName().equalsIgnoreCase(name)).findFirst();_x000D_
_x000D_
}_x000D_
// behandel opgegeven dier_x000D_
//8_x000D_
public void treatAnimal(int animalNumber){_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAnimalNumber()==animalNumber){_x000D_
System.out.println("treat animal by number: "+animal.getAnimalNumber()+animal.getIsVaccinated());_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
//System.out.println("animal with number "+animalNumber+"not found");_x000D_
/* animals.stream()_x000D_
.sorted(Comparator.comparingInt(Animal::getAnimalNumber))_x000D_
.forEach(animal -> System.out.println(_x000D_
"Animal number: "+animal.getAnimalNumber()+_x000D_
"| name: "+animal.getName()+_x000D_
"| age: "+animal.getAge()+_x000D_
"| is clean? "+animal.getIsVaccinated()_x000D_
));///////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_
/*Optional<Animal> optionalAnimal = findAnimal(animalNumber);_x000D_
if (optionalAnimal.isPresent()){_x000D_
Animal animal = optionalAnimal.get();_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}else {_x000D_
System.out.println("animal met number "+animalNumber+"not found");_x000D_
}*/_x000D_
}_x000D_
//behandel opgegeven dier_x000D_
//9_x000D_
public void treatAnimal(String name){_x000D_
for (Animal animal : animals){_x000D_
if (animal.getName()==name){_x000D_
System.out.println("treat animal by name: "+animal.getName()+animal.getIsVaccinated());_x000D_
_x000D_
}_x000D_
}_x000D_
/*animals.stream()_x000D_
.sorted(Comparator.comparing(Animal::getName))_x000D_
.forEach(animal -> System.out.println(_x000D_
"name: "+animal.getName()+_x000D_
"| animal number: "+animal.getAnimalNumber()+_x000D_
"| age: "+animal.getAge()+_x000D_
"| is clean? "+animal.getIsVaccinated()_x000D_
));/////////////////////////////////////////////////////////////////////////////////////////////////////_x000D_
/* Optional<Animal> optionalAnimal = findAnimal(name);_x000D_
if (optionalAnimal.isPresent()){_x000D_
Animal animal = optionalAnimal.get();_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}else {_x000D_
System.out.println("animal met name "+name+ "not found");_x000D_
}*/_x000D_
_x000D_
}_x000D_
//behandel alle dieren_x000D_
//10_x000D_
public void treatAllAnimals(){_x000D_
for (Animal animal : animals){_x000D_
animal.treatAnimal();_x000D_
System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
_x000D_
}_x000D_
//geef het oudste dier terug_x000D_
//11_x000D_
public Animal findOldestAnimal() throws NoSuchElementException {_x000D_
if (animals.isEmpty()) {_x000D_
throw new NoSuchElementException("No animal found in this list");_x000D_
}_x000D_
Animal oldestAnimal = animals.get(0);_x000D_
for (Animal animal : animals){_x000D_
if (animal.getAge() > oldestAnimal.getAge()){_x000D_
oldestAnimal = animal;_x000D_
//System.out.println("Name: "+animal.getName()+" | "+" Age: "+animal.getAge()+" | "+" Animal number: "+animal.getAnimalNumber()+" | "+" is clean ? "+animal.getIsVaccinated());_x000D_
}_x000D_
}_x000D_
return oldestAnimal;_x000D_
_x000D_
}_x000D_
_x000D_
// geef het aantal dieren terug_x000D_
//12_x000D_
public int countAnimals(){_x000D_
if (animals != null){_x000D_
return animals.size();_x000D_
}else {_x000D_
return 0;_x000D_
}_x000D_
}_x000D_
_x000D_
//voeg een dier toe aan de lijst van animals_x000D_
//13_x000D_
public void addAnimal(Animal animal) throws IllegalArgumentException{_x000D_
if (animal != null){_x000D_
animal.setAnimalNumber(animalId);//toewijzen de<SUF>
animals.add(animal);//add de animal to de list_x000D_
animalId++;//verhoog de animal id_x000D_
}else {_x000D_
throw new IllegalArgumentException("Can not add null animal to de list");_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
| True | 2,629 | 15 | 2,846 | 16 | 2,850 | 15 | 2,846 | 16 | 3,229 | 16 | false | false | false | false | false | true |
891 | 42237_0 | package P2;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerDAOPsql implements ReizigerDAO {
private Connection conn = Main.getConnection();
public ReizigerDAOPsql(Connection conn) throws SQLException {
this.conn = conn;
}
@Override
public boolean save(Reiziger reiziger) {
// Waarom return je een boolean ipv een list aangezien je de eerste zoveel Reizigers moet teruggeven...?
try {
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO reiziger values (?, ?, ?, ?, ?)");
preparedStatement.setInt(1, reiziger.getId());
preparedStatement.setString(2, reiziger.getVoorletters());
preparedStatement.setString(3, reiziger.getTussenvoegsel());
preparedStatement.setString(4, reiziger.getAchternaam());
preparedStatement.setDate(5, (Date) reiziger.getGeboortedatum());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Opslaan geen succes.");
return false;
}
}
@Override
public boolean update(Reiziger reiziger) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("UPDATE reiziger SET voorletters = ?, tussenvoegsel = ?, achternaam = ?, geboortedatum = ? WHERE reiziger_id = ?");
preparedStatement.setString(1, reiziger.getVoorletters());
preparedStatement.setString(2, reiziger.getTussenvoegsel());
preparedStatement.setString(3, reiziger.getAchternaam());
preparedStatement.setDate(4, (Date) reiziger.getGeboortedatum());
preparedStatement.setInt(5, reiziger.getId());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Update kon niet voltooid worden door een onbekende reden");
return false;
}
}
@Override
public boolean delete(Reiziger reiziger) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("DELETE FROM reiziger WHERE reiziger_id = ?");
preparedStatement.setInt(1, reiziger.getId());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Delete is fout gegaan door een onbekende reden");
return false;
}
}
@Override
public Reiziger findById(int id) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE reiziger_id = ?");
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
String voorletters = null;
String tussenvoegsel = null;
String achternaam = null;
Date geboortedatum = null;
Reiziger reiziger;
while (resultSet.next()) {
voorletters = resultSet.getString("voorletters");
tussenvoegsel = resultSet.getString("tussenvoegsel");
achternaam = resultSet.getString("achternaam");
geboortedatum = resultSet.getDate("geboortedatum");
}
reiziger = new Reiziger(id, voorletters, tussenvoegsel, achternaam, geboortedatum);
return reiziger;
} catch (SQLException sqlException) {
System.out.println("Geen reiziger gevonden met id: " + id);
return null;
}
}
@Override
public List<Reiziger> findByGbDatum(String datum) {
try {
List<Reiziger> opDatum = new ArrayList<>();
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE geboortedatum = ?");
preparedStatement.setDate(1, Date.valueOf(datum));
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String id = resultSet.getString("reiziger_id");
int reizigerId = Integer.parseInt(id);
String voorletters = resultSet.getString("voorletters");
String tussenvoegsel = resultSet.getString("tussenvoegsel");
String achternaam = resultSet.getString("achternaam");
Date geboortedatum = resultSet.getDate("geboortedatum");
Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum);
opDatum.add(reiziger);
}
return opDatum;
} catch (SQLException sqlException) {
System.out.println("Datum is niet gevonden of onjuist, controleer de input.");
return null;
}
}
@Override
public List<Reiziger> findAll() {
try {
List<Reiziger> alleReizigers = new ArrayList<>();
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger;");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String id = resultSet.getString("reiziger_id");
int reizigerId = Integer.parseInt(id);
String voorletters = resultSet.getString("voorletters");
String tussenvoegsel = resultSet.getString("tussenvoegsel");
String achternaam = resultSet.getString("achternaam");
Date geboortedatum = resultSet.getDate("geboortedatum");
Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum);
alleReizigers.add(reiziger);
}
return alleReizigers;
} catch (SQLException sqlException) {
System.out.println("Er is een onbekende fout opgetreden in findAll()");
return null;
}
}
}
| JustMilan/DP | src/main/java/P2/ReizigerDAOPsql.java | 1,642 | // Waarom return je een boolean ipv een list aangezien je de eerste zoveel Reizigers moet teruggeven...? | line_comment | nl | package P2;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerDAOPsql implements ReizigerDAO {
private Connection conn = Main.getConnection();
public ReizigerDAOPsql(Connection conn) throws SQLException {
this.conn = conn;
}
@Override
public boolean save(Reiziger reiziger) {
// Waarom return<SUF>
try {
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO reiziger values (?, ?, ?, ?, ?)");
preparedStatement.setInt(1, reiziger.getId());
preparedStatement.setString(2, reiziger.getVoorletters());
preparedStatement.setString(3, reiziger.getTussenvoegsel());
preparedStatement.setString(4, reiziger.getAchternaam());
preparedStatement.setDate(5, (Date) reiziger.getGeboortedatum());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Opslaan geen succes.");
return false;
}
}
@Override
public boolean update(Reiziger reiziger) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("UPDATE reiziger SET voorletters = ?, tussenvoegsel = ?, achternaam = ?, geboortedatum = ? WHERE reiziger_id = ?");
preparedStatement.setString(1, reiziger.getVoorletters());
preparedStatement.setString(2, reiziger.getTussenvoegsel());
preparedStatement.setString(3, reiziger.getAchternaam());
preparedStatement.setDate(4, (Date) reiziger.getGeboortedatum());
preparedStatement.setInt(5, reiziger.getId());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Update kon niet voltooid worden door een onbekende reden");
return false;
}
}
@Override
public boolean delete(Reiziger reiziger) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("DELETE FROM reiziger WHERE reiziger_id = ?");
preparedStatement.setInt(1, reiziger.getId());
return preparedStatement.execute();
} catch (SQLException sqlException) {
System.out.println("Delete is fout gegaan door een onbekende reden");
return false;
}
}
@Override
public Reiziger findById(int id) {
try {
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE reiziger_id = ?");
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
String voorletters = null;
String tussenvoegsel = null;
String achternaam = null;
Date geboortedatum = null;
Reiziger reiziger;
while (resultSet.next()) {
voorletters = resultSet.getString("voorletters");
tussenvoegsel = resultSet.getString("tussenvoegsel");
achternaam = resultSet.getString("achternaam");
geboortedatum = resultSet.getDate("geboortedatum");
}
reiziger = new Reiziger(id, voorletters, tussenvoegsel, achternaam, geboortedatum);
return reiziger;
} catch (SQLException sqlException) {
System.out.println("Geen reiziger gevonden met id: " + id);
return null;
}
}
@Override
public List<Reiziger> findByGbDatum(String datum) {
try {
List<Reiziger> opDatum = new ArrayList<>();
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger WHERE geboortedatum = ?");
preparedStatement.setDate(1, Date.valueOf(datum));
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String id = resultSet.getString("reiziger_id");
int reizigerId = Integer.parseInt(id);
String voorletters = resultSet.getString("voorletters");
String tussenvoegsel = resultSet.getString("tussenvoegsel");
String achternaam = resultSet.getString("achternaam");
Date geboortedatum = resultSet.getDate("geboortedatum");
Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum);
opDatum.add(reiziger);
}
return opDatum;
} catch (SQLException sqlException) {
System.out.println("Datum is niet gevonden of onjuist, controleer de input.");
return null;
}
}
@Override
public List<Reiziger> findAll() {
try {
List<Reiziger> alleReizigers = new ArrayList<>();
PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM reiziger;");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String id = resultSet.getString("reiziger_id");
int reizigerId = Integer.parseInt(id);
String voorletters = resultSet.getString("voorletters");
String tussenvoegsel = resultSet.getString("tussenvoegsel");
String achternaam = resultSet.getString("achternaam");
Date geboortedatum = resultSet.getDate("geboortedatum");
Reiziger reiziger = new Reiziger(reizigerId, voorletters, tussenvoegsel, achternaam, geboortedatum);
alleReizigers.add(reiziger);
}
return alleReizigers;
} catch (SQLException sqlException) {
System.out.println("Er is een onbekende fout opgetreden in findAll()");
return null;
}
}
}
| False | 1,226 | 30 | 1,383 | 33 | 1,357 | 21 | 1,369 | 33 | 1,591 | 32 | false | false | false | false | false | true |
1,721 | 202684_3 |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Here you can try out the combined functionality of your classes
TodoList list = new TodoList();
Scanner scanner = new Scanner(System.in);
UserInterface ui = new UserInterface(list, scanner);
ui.start();
// list.add("iets doen");
// list.add("nog iets doen");
// list.add("andermaal iets doen");
// list.add("een vierde taak");
// list.print();
// list.remove(3);
// System.out.println("");
// list.print();
}
}
| Thibault-be/MOOC-Helsinki-Java-2 | part08-Part08_05.TodoList/src/main/java/Main.java | 174 | // list.add("een vierde taak"); | line_comment | nl |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Here you can try out the combined functionality of your classes
TodoList list = new TodoList();
Scanner scanner = new Scanner(System.in);
UserInterface ui = new UserInterface(list, scanner);
ui.start();
// list.add("iets doen");
// list.add("nog iets doen");
// list.add("andermaal iets doen");
// list.add("een vierde<SUF>
// list.print();
// list.remove(3);
// System.out.println("");
// list.print();
}
}
| False | 133 | 10 | 160 | 12 | 164 | 11 | 160 | 12 | 187 | 11 | false | false | false | false | false | true |
1,554 | 47470_4 | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.plugins.nl_pdok_report.utils.api;
import java.util.Objects;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import org.geotools.referencing.CRS;
import org.geotools.referencing.operation.transform.IdentityTransform;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.api.referencing.operation.MathTransform;
import org.geotools.api.referencing.operation.TransformException;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.plugins.nl_pdok_report.ReportNewBAG;
import org.openstreetmap.josm.plugins.nl_pdok_report.utils.ReportProperties;
/**
* Encodes in JSON a location changeset. Former location and compass angle (CA) are systematically provided, even if not
* changed.
*/
public final class JsonNewReportEncoder {
private static MathTransform transform;
private JsonNewReportEncoder() {
// Private constructor to avoid instantiation
}
public static JsonObjectBuilder encodeNewReport(ReportNewBAG report) {
LatLon reportLatLon = reportLatLon(report.getLatLon());
JsonObjectBuilder result = Json.createObjectBuilder();
Objects.requireNonNull(report);
result.add("type", "FeatureCollection");
result.add("name", "TerugmeldingGeneriek");
result
.add("crs", Json.createObjectBuilder()
.add("type", "name")
.add("properties", Json.createObjectBuilder()
.add("name", "urn:ogc:def:crs:EPSG::28992")));
result.add(
"features", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "Feature")
.addAll(getReport(report))
.add("geometry", Json.createObjectBuilder()
.add("type", "Point")
.add("coordinates", Json.createArrayBuilder()
.add(reportLatLon.getX())
.add(reportLatLon.getY())
)
)
)
);
return result;
}
private static JsonObjectBuilder getReport(ReportNewBAG report) {
JsonObjectBuilder result = Json.createObjectBuilder();
JsonObjectBuilder properties = Json.createObjectBuilder();
properties.add("registratie", report.getBaseRegistration());
// Verplicht. Keuze uit BGT,BAG,BRT of KLIC
// properties.add("product", ...);
// Optioneel. Let op: alleen gebruiken bij de registratie BRT met TOP10,TOP25,TOP50,TOP100,TOP250,TOP500 of
// TOP1000, anders veld weglaten.
properties.add("bron", "OpenStreetMap (JOSM plugin)"); //ReportPlugin.getPluginVersionString());
// Verplicht, applicatie (app, portal, site e.d.) waar de terugmelding vandaan komt.
properties.add("omschrijving", report.getDescription());
// Verplicht. Omschrijf zo duidelijk mogelijk wat er onjuist is op de locatie. Let op: deze omschrijving wordt
// openbaar gemaakt! Geen persoonlijke gegevens invullen en minimaal 5 karakters.
// properties.add("objectId", "");
// Optioneel, het id (referentie/nummer) van het object waar de terugmelding betrekking op heeft. Let op: op dit
// moment alleen bruikbaar bij registraties BAG en KLIC.
// properties.add("objectType", "");
// Optioneel, het type (soort) van het object waar de terugmelding betrekking op heeft. Let op: op dit moment
// alleen bruikbaar bij registraties BAG en KLIC.
// properties.add("klicmeldnummer", )
// Verplicht bij registratie KLIC, het graaf (meld)nummer. Let op: alleen gebruiken bij de registratie KLIC,
// anders veld weglaten.
// properties.add("EigenVeld2", "");
// Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean
// zijn toegestaan. Let op: op dit moment alleen bruikbaar bij registraties BAG en KLIC.
if (ReportProperties.USER_EMAIL.isSet()) {
properties.add("email", ReportProperties.USER_EMAIL.get());
// Optioneel. E-mail adres van de terugmelder waarop status updates van de bronhouder zullen worden ontvangen.
// NB Op de acceptatie omgeving zullen er geen daadwerkelijke e-mails worden gestuurd."
}
if (!ReportProperties.USER_ORGANISATION.get().isEmpty())
{
properties.add("Organisatie", ReportProperties.USER_ORGANISATION.get());
// Optioneel. Aanvullende informatie kunt u kwijt in extra velden: denk aan organisatie van de terugmelder, extra
// informatie voor de bronhouder, contactinformatie of een eigen referentie van de terugmelding. Let op: op dit
// moment alleen bruikbaar bij registraties BAG en KLIC.
// Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean
// zijn toegestaan. In plaats van EigenVeld1 of EigenVeld2 kunt u zelf een passende naam kiezen.
}
// final JsonArrayBuilder bagChanges = Json.createArrayBuilder();
// for (File file : report.getFile) {
// bagChanges.add(encodeBAGChanges(img));
// }
result.add("properties", properties);
return result;
}
/**
* Encodes a {@link LatLon} with projection EPSG:4326 to a {@link LatLon} with projection EPSG:28992.
*
* @param osmLatLon
* the {@link LatLon} containing coordinate in EPSG:4326
* @return the encoded {@link LatLon} coordinate in EPSG:28992.
*/
public static LatLon reportLatLon(LatLon osmLatLon) {
final double[] result = {osmLatLon.getX(), osmLatLon.getY()};
if (transform == null)
{
transform = IdentityTransform.create(2);
try {
CoordinateReferenceSystem osmCrs = CRS.decode("EPSG:4326");
CoordinateReferenceSystem crsReport = CRS.decode("EPSG:28992", true);
transform = CRS.findMathTransform(osmCrs, crsReport);
} catch (FactoryException e) {
throw new UnsupportedOperationException(e);
}
}
try {
transform.transform(result, 0, result, 0, 1);
} catch (TransformException e) {
throw new UnsupportedOperationException("Cannot transform a point from the input dataset", e);
}
return new LatLon(result[1], result[0]); // swap coordinated???
}
}
| SanderH/josm-nl-report | src/main/java/org/openstreetmap/josm/plugins/nl_pdok_report/utils/api/JsonNewReportEncoder.java | 1,967 | // Optioneel. Let op: alleen gebruiken bij de registratie BRT met TOP10,TOP25,TOP50,TOP100,TOP250,TOP500 of | line_comment | nl | // License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.plugins.nl_pdok_report.utils.api;
import java.util.Objects;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import org.geotools.referencing.CRS;
import org.geotools.referencing.operation.transform.IdentityTransform;
import org.geotools.api.referencing.FactoryException;
import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
import org.geotools.api.referencing.operation.MathTransform;
import org.geotools.api.referencing.operation.TransformException;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.plugins.nl_pdok_report.ReportNewBAG;
import org.openstreetmap.josm.plugins.nl_pdok_report.utils.ReportProperties;
/**
* Encodes in JSON a location changeset. Former location and compass angle (CA) are systematically provided, even if not
* changed.
*/
public final class JsonNewReportEncoder {
private static MathTransform transform;
private JsonNewReportEncoder() {
// Private constructor to avoid instantiation
}
public static JsonObjectBuilder encodeNewReport(ReportNewBAG report) {
LatLon reportLatLon = reportLatLon(report.getLatLon());
JsonObjectBuilder result = Json.createObjectBuilder();
Objects.requireNonNull(report);
result.add("type", "FeatureCollection");
result.add("name", "TerugmeldingGeneriek");
result
.add("crs", Json.createObjectBuilder()
.add("type", "name")
.add("properties", Json.createObjectBuilder()
.add("name", "urn:ogc:def:crs:EPSG::28992")));
result.add(
"features", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "Feature")
.addAll(getReport(report))
.add("geometry", Json.createObjectBuilder()
.add("type", "Point")
.add("coordinates", Json.createArrayBuilder()
.add(reportLatLon.getX())
.add(reportLatLon.getY())
)
)
)
);
return result;
}
private static JsonObjectBuilder getReport(ReportNewBAG report) {
JsonObjectBuilder result = Json.createObjectBuilder();
JsonObjectBuilder properties = Json.createObjectBuilder();
properties.add("registratie", report.getBaseRegistration());
// Verplicht. Keuze uit BGT,BAG,BRT of KLIC
// properties.add("product", ...);
// Optioneel. Let<SUF>
// TOP1000, anders veld weglaten.
properties.add("bron", "OpenStreetMap (JOSM plugin)"); //ReportPlugin.getPluginVersionString());
// Verplicht, applicatie (app, portal, site e.d.) waar de terugmelding vandaan komt.
properties.add("omschrijving", report.getDescription());
// Verplicht. Omschrijf zo duidelijk mogelijk wat er onjuist is op de locatie. Let op: deze omschrijving wordt
// openbaar gemaakt! Geen persoonlijke gegevens invullen en minimaal 5 karakters.
// properties.add("objectId", "");
// Optioneel, het id (referentie/nummer) van het object waar de terugmelding betrekking op heeft. Let op: op dit
// moment alleen bruikbaar bij registraties BAG en KLIC.
// properties.add("objectType", "");
// Optioneel, het type (soort) van het object waar de terugmelding betrekking op heeft. Let op: op dit moment
// alleen bruikbaar bij registraties BAG en KLIC.
// properties.add("klicmeldnummer", )
// Verplicht bij registratie KLIC, het graaf (meld)nummer. Let op: alleen gebruiken bij de registratie KLIC,
// anders veld weglaten.
// properties.add("EigenVeld2", "");
// Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean
// zijn toegestaan. Let op: op dit moment alleen bruikbaar bij registraties BAG en KLIC.
if (ReportProperties.USER_EMAIL.isSet()) {
properties.add("email", ReportProperties.USER_EMAIL.get());
// Optioneel. E-mail adres van de terugmelder waarop status updates van de bronhouder zullen worden ontvangen.
// NB Op de acceptatie omgeving zullen er geen daadwerkelijke e-mails worden gestuurd."
}
if (!ReportProperties.USER_ORGANISATION.get().isEmpty())
{
properties.add("Organisatie", ReportProperties.USER_ORGANISATION.get());
// Optioneel. Aanvullende informatie kunt u kwijt in extra velden: denk aan organisatie van de terugmelder, extra
// informatie voor de bronhouder, contactinformatie of een eigen referentie van de terugmelding. Let op: op dit
// moment alleen bruikbaar bij registraties BAG en KLIC.
// Optioneel. U kunt diverse eigen velden naar wens toevoegen. Alleen de JSON data types Number, String en Boolean
// zijn toegestaan. In plaats van EigenVeld1 of EigenVeld2 kunt u zelf een passende naam kiezen.
}
// final JsonArrayBuilder bagChanges = Json.createArrayBuilder();
// for (File file : report.getFile) {
// bagChanges.add(encodeBAGChanges(img));
// }
result.add("properties", properties);
return result;
}
/**
* Encodes a {@link LatLon} with projection EPSG:4326 to a {@link LatLon} with projection EPSG:28992.
*
* @param osmLatLon
* the {@link LatLon} containing coordinate in EPSG:4326
* @return the encoded {@link LatLon} coordinate in EPSG:28992.
*/
public static LatLon reportLatLon(LatLon osmLatLon) {
final double[] result = {osmLatLon.getX(), osmLatLon.getY()};
if (transform == null)
{
transform = IdentityTransform.create(2);
try {
CoordinateReferenceSystem osmCrs = CRS.decode("EPSG:4326");
CoordinateReferenceSystem crsReport = CRS.decode("EPSG:28992", true);
transform = CRS.findMathTransform(osmCrs, crsReport);
} catch (FactoryException e) {
throw new UnsupportedOperationException(e);
}
}
try {
transform.transform(result, 0, result, 0, 1);
} catch (TransformException e) {
throw new UnsupportedOperationException("Cannot transform a point from the input dataset", e);
}
return new LatLon(result[1], result[0]); // swap coordinated???
}
}
| False | 1,579 | 44 | 1,744 | 49 | 1,724 | 43 | 1,745 | 49 | 1,964 | 52 | false | false | false | false | false | true |
3,239 | 99431_5 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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 net.java.sip.communicator.impl.protocol.irc;
/**
* IRC color codes that can be specified in the color control code.
*
* @author Danny van Heumen
*/
public enum Color
{
/**
* White.
*/
WHITE("White"),
/**
* Black.
*/
BLACK("Black"),
/**
* Navy.
*/
BLUE("Navy"),
/**
* Green.
*/
GREEN("Green"),
/**
* Red.
*/
RED("Red"),
/**
* Maroon.
*/
BROWN("Maroon"),
/**
* Purple.
*/
PURPLE("Purple"),
/**
* Orange.
*/
ORANGE("Orange"),
/**
* Yellow.
*/
YELLOW("Yellow"),
/**
* Lime.
*/
LIGHT_GREEN("Lime"),
/**
* Teal.
*/
TEAL("Teal"),
/**
* Cyan.
*/
LIGHT_CYAN("Cyan"),
/**
* RoyalBlue.
*/
LIGHT_BLUE("RoyalBlue"),
/**
* Fuchsia.
*/
PINK("Fuchsia"),
/**
* Grey.
*/
GREY("Grey"),
/**
* Silver.
*/
LIGHT_GREY("Silver");
/**
* Instance containing the html representation of this color.
*/
private String html;
/**
* Constructor for enum entries.
*
* @param html HTML representation for color
*/
private Color(final String html)
{
this.html = html;
}
/**
* Get the HTML representation of this color.
*
* @return returns html representation or null if none exist
*/
public String getHtml()
{
return this.html;
}
}
| jitsi/jitsi | modules/impl/protocol-irc/src/main/java/net/java/sip/communicator/impl/protocol/irc/Color.java | 690 | /**
* Green.
*/ | block_comment | nl | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* 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 net.java.sip.communicator.impl.protocol.irc;
/**
* IRC color codes that can be specified in the color control code.
*
* @author Danny van Heumen
*/
public enum Color
{
/**
* White.
*/
WHITE("White"),
/**
* Black.
*/
BLACK("Black"),
/**
* Navy.
*/
BLUE("Navy"),
/**
* Green.
<SUF>*/
GREEN("Green"),
/**
* Red.
*/
RED("Red"),
/**
* Maroon.
*/
BROWN("Maroon"),
/**
* Purple.
*/
PURPLE("Purple"),
/**
* Orange.
*/
ORANGE("Orange"),
/**
* Yellow.
*/
YELLOW("Yellow"),
/**
* Lime.
*/
LIGHT_GREEN("Lime"),
/**
* Teal.
*/
TEAL("Teal"),
/**
* Cyan.
*/
LIGHT_CYAN("Cyan"),
/**
* RoyalBlue.
*/
LIGHT_BLUE("RoyalBlue"),
/**
* Fuchsia.
*/
PINK("Fuchsia"),
/**
* Grey.
*/
GREY("Grey"),
/**
* Silver.
*/
LIGHT_GREY("Silver");
/**
* Instance containing the html representation of this color.
*/
private String html;
/**
* Constructor for enum entries.
*
* @param html HTML representation for color
*/
private Color(final String html)
{
this.html = html;
}
/**
* Get the HTML representation of this color.
*
* @return returns html representation or null if none exist
*/
public String getHtml()
{
return this.html;
}
}
| False | 530 | 7 | 579 | 7 | 634 | 9 | 579 | 7 | 738 | 9 | false | false | false | false | false | true |
3,819 | 27626_0 | package semisplay;
public interface SearchTree<E extends Comparable<E>> extends Iterable<E> {
/** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit.
* @return true als de sleutel effectief toegevoegd werd. */
boolean add(E e);
/** Zoek de gegeven sleutel op in de boom.
* @return true als de sleutel gevonden werd. */
boolean contains(E e);
/** Verwijder de gegeven sleutel uit de boom.
* @return true als de sleutel gevonden en verwijderd werd. */
boolean remove(E e);
/** @return het aantal sleutels in de boom. */
int size();
/** @return de diepte van de boom. */
int depth();
}
| nielsdos/Semisplay-tree | src/semisplay/SearchTree.java | 203 | /** Voeg de gegeven sleutel toe aan de boom als deze er nog niet in zit.
* @return true als de sleutel effectief toegevoegd werd. */ | block_comment | nl | package semisplay;
public interface SearchTree<E extends Comparable<E>> extends Iterable<E> {
/** Voeg de gegeven<SUF>*/
boolean add(E e);
/** Zoek de gegeven sleutel op in de boom.
* @return true als de sleutel gevonden werd. */
boolean contains(E e);
/** Verwijder de gegeven sleutel uit de boom.
* @return true als de sleutel gevonden en verwijderd werd. */
boolean remove(E e);
/** @return het aantal sleutels in de boom. */
int size();
/** @return de diepte van de boom. */
int depth();
}
| True | 182 | 43 | 207 | 45 | 184 | 36 | 207 | 45 | 217 | 44 | false | false | false | false | false | true |
646 | 172943_2 | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuilder buffer = new StringBuilder();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
}
| HDauven/S32JSF3 | JSF31_w04_KochFractalFX-startup/JSF31KochFractalFX - startup/src/timeutil/TimeStamp.java | 1,267 | /**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/ | block_comment | nl | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik<SUF>*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.currentTimeMillis();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.currentTimeMillis(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " mSec.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuilder buffer = new StringBuilder();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
}
| True | 1,079 | 32 | 1,174 | 30 | 1,116 | 25 | 1,174 | 30 | 1,285 | 32 | false | false | false | false | false | true |
517 | 106041_3 | /**
* Project Zelula
*
* Contextproject TI2800
* TU Delft - University of Technology
*
* Authors:
* Felix Akkermans, Niels Doekemeijer, Thomas van Helden
* Albert ten Napel, Jan Pieter Waagmeester
*
* https://github.com/FelixAkk/synthbio
*/
package synthbio.models;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Point representation
* @author jieter
*/
public class Position{
private double x;
private double y;
public Position(double x, double y){
this.x=x;
this.y=y;
}
/**
* Create a undefined position defaulting to 0,0
*/
public Position(){
this(0, 0);
}
/**
* getters
*/
public double getX(){
return this.x;
}
public double getY(){
return this.y;
}
/**
* Calculate the distance between two positions
*
* @param that Position to calculate distance to.
* @return The distance between this and that.
*/
public double distanceTo(Position that){
return Math.sqrt(
Math.pow(this.getX()-that.getX(), 2) +
Math.pow(this.getY()-that.getY(), 2)
);
}
public boolean equals(Object other){
if(!(other instanceof Position)){
return false;
}
Position that=(Position)other;
return this.getX()==that.getX() && this.getY()==that.getY();
}
/**
* Return a simple String representation
*/
public String toString(){
return "("+this.getX()+","+this.getY()+")";
}
/**
* Deserialize JSON to a Position
*/
public static Position fromJSON(String json) throws JSONException{
return Position.fromJSON(new JSONObject(json));
}
public static Position fromJSON(JSONObject json) throws JSONException{
return new Position(json.getDouble("x"), json.getDouble("y"));
}
}
| FelixAkk/synthbio | program/WEB-INF/src/synthbio/models/Position.java | 583 | /**
* getters
*/ | block_comment | nl | /**
* Project Zelula
*
* Contextproject TI2800
* TU Delft - University of Technology
*
* Authors:
* Felix Akkermans, Niels Doekemeijer, Thomas van Helden
* Albert ten Napel, Jan Pieter Waagmeester
*
* https://github.com/FelixAkk/synthbio
*/
package synthbio.models;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Point representation
* @author jieter
*/
public class Position{
private double x;
private double y;
public Position(double x, double y){
this.x=x;
this.y=y;
}
/**
* Create a undefined position defaulting to 0,0
*/
public Position(){
this(0, 0);
}
/**
* getters
<SUF>*/
public double getX(){
return this.x;
}
public double getY(){
return this.y;
}
/**
* Calculate the distance between two positions
*
* @param that Position to calculate distance to.
* @return The distance between this and that.
*/
public double distanceTo(Position that){
return Math.sqrt(
Math.pow(this.getX()-that.getX(), 2) +
Math.pow(this.getY()-that.getY(), 2)
);
}
public boolean equals(Object other){
if(!(other instanceof Position)){
return false;
}
Position that=(Position)other;
return this.getX()==that.getX() && this.getY()==that.getY();
}
/**
* Return a simple String representation
*/
public String toString(){
return "("+this.getX()+","+this.getY()+")";
}
/**
* Deserialize JSON to a Position
*/
public static Position fromJSON(String json) throws JSONException{
return Position.fromJSON(new JSONObject(json));
}
public static Position fromJSON(JSONObject json) throws JSONException{
return new Position(json.getDouble("x"), json.getDouble("y"));
}
}
| False | 430 | 7 | 536 | 6 | 532 | 8 | 536 | 6 | 609 | 9 | false | false | false | false | false | true |
3,798 | 167369_5 | /**
* NetXMS - open source network management system
* Copyright (C) 2003-2022 Victor Kirhenshtein
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.netxms.client.constants;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* OSPF neighbor state
*/
public enum OSPFNeighborState
{
UNKNOWN(0, ""),
DOWN(1, "DOWN"),
ATTEMPT(2, "ATTEMPT"),
INIT(3, "INIT"),
TWO_WAY(4, "TWO-WAY"),
EXCHANGE_START(5, "EXCHANGE START"),
EXCHANGE(6, "EXCHANGE"),
LOADING(7, "LOADING"),
FULL(8, "FULL");
private static Logger logger = LoggerFactory.getLogger(OSPFNeighborState.class);
private static Map<Integer, OSPFNeighborState> lookupTable = new HashMap<Integer, OSPFNeighborState>();
static
{
for(OSPFNeighborState element : OSPFNeighborState.values())
{
lookupTable.put(element.value, element);
}
}
private int value;
private String text;
/**
* Internal constructor
*
* @param value integer value
* @param text text value
*/
private OSPFNeighborState(int value, String text)
{
this.value = value;
this.text = text;
}
/**
* Get integer value
*
* @return integer value
*/
public int getValue()
{
return value;
}
/**
* Get text value
*
* @return text value
*/
public String getText()
{
return text;
}
/**
* Get enum element by integer value
*
* @param value integer value
* @return enum element corresponding to given integer value or fall-back element for invalid value
*/
public static OSPFNeighborState getByValue(int value)
{
final OSPFNeighborState element = lookupTable.get(value);
if (element == null)
{
logger.warn("Unknown element " + value);
return UNKNOWN; // fall-back
}
return element;
}
}
| netxms/netxms | src/client/java/netxms-client/src/main/java/org/netxms/client/constants/OSPFNeighborState.java | 814 | /**
* Get enum element by integer value
*
* @param value integer value
* @return enum element corresponding to given integer value or fall-back element for invalid value
*/ | block_comment | nl | /**
* NetXMS - open source network management system
* Copyright (C) 2003-2022 Victor Kirhenshtein
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.netxms.client.constants;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* OSPF neighbor state
*/
public enum OSPFNeighborState
{
UNKNOWN(0, ""),
DOWN(1, "DOWN"),
ATTEMPT(2, "ATTEMPT"),
INIT(3, "INIT"),
TWO_WAY(4, "TWO-WAY"),
EXCHANGE_START(5, "EXCHANGE START"),
EXCHANGE(6, "EXCHANGE"),
LOADING(7, "LOADING"),
FULL(8, "FULL");
private static Logger logger = LoggerFactory.getLogger(OSPFNeighborState.class);
private static Map<Integer, OSPFNeighborState> lookupTable = new HashMap<Integer, OSPFNeighborState>();
static
{
for(OSPFNeighborState element : OSPFNeighborState.values())
{
lookupTable.put(element.value, element);
}
}
private int value;
private String text;
/**
* Internal constructor
*
* @param value integer value
* @param text text value
*/
private OSPFNeighborState(int value, String text)
{
this.value = value;
this.text = text;
}
/**
* Get integer value
*
* @return integer value
*/
public int getValue()
{
return value;
}
/**
* Get text value
*
* @return text value
*/
public String getText()
{
return text;
}
/**
* Get enum element<SUF>*/
public static OSPFNeighborState getByValue(int value)
{
final OSPFNeighborState element = lookupTable.get(value);
if (element == null)
{
logger.warn("Unknown element " + value);
return UNKNOWN; // fall-back
}
return element;
}
}
| False | 639 | 42 | 688 | 39 | 732 | 45 | 688 | 39 | 842 | 45 | false | false | false | false | false | true |
994 | 14145_0 | public class Werknemer {
public String voornaam;
public String achternaam;
public int werknemerNummer;
protected float salaris;
public static int aantalWerknemers;
public void salarisVerhogen(int percentage) {
float verhogingsfactor = (float)percentage/100;
salaris += salaris*verhogingsfactor;
}
public float getSalaris() {
return salaris;
}
public Werknemer(String voornaam, String achternaam, int wNummer, float salaris) {
this.voornaam = voornaam; //this.var => altijd dataleden
this.achternaam = achternaam;
werknemerNummer = wNummer;
this.salaris = salaris;
aantalWerknemers++;
}
} | LukaVerhoeven/Digital-Broadcast | Werknemer.java | 220 | //this.var => altijd dataleden | line_comment | nl | public class Werknemer {
public String voornaam;
public String achternaam;
public int werknemerNummer;
protected float salaris;
public static int aantalWerknemers;
public void salarisVerhogen(int percentage) {
float verhogingsfactor = (float)percentage/100;
salaris += salaris*verhogingsfactor;
}
public float getSalaris() {
return salaris;
}
public Werknemer(String voornaam, String achternaam, int wNummer, float salaris) {
this.voornaam = voornaam; //this.var =><SUF>
this.achternaam = achternaam;
werknemerNummer = wNummer;
this.salaris = salaris;
aantalWerknemers++;
}
} | False | 181 | 8 | 224 | 11 | 200 | 9 | 224 | 11 | 230 | 10 | false | false | false | false | false | true |
2,480 | 35814_3 | import java.io.File;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class MP1 {
Random generator;
String userName;
String inputFileName;
String delimiters = " \t,;.?!-:@[](){}_*/";
String[] stopWordsArray = {"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours",
"yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its",
"itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that",
"these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having",
"do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while",
"of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before",
"after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again",
"further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each",
"few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than",
"too", "very", "s", "t", "can", "will", "just", "don", "should", "now"};
void initialRandomGenerator(String seed) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
messageDigest.update(seed.toLowerCase().trim().getBytes());
byte[] seedMD5 = messageDigest.digest();
long longSeed = 0;
for (int i = 0; i < seedMD5.length; i++) {
longSeed += ((long) seedMD5[i] & 0xffL) << (8 * i);
}
this.generator = new Random(longSeed);
}
Integer[] getIndexes() throws NoSuchAlgorithmException {
Integer n = 10000;
Integer number_of_lines = 50000;
Integer[] ret = new Integer[n];
this.initialRandomGenerator(this.userName);
for (int i = 0; i < n; i++) {
ret[i] = generator.nextInt(number_of_lines);
}
return ret;
}
public MP1(String userName, String inputFileName) {
this.userName = userName;
this.inputFileName = inputFileName;
}
public String[] process() throws Exception {
String[] ret = new String[20];
//TODO
// read input file
String line;
try (
InputStream fis = new FileInputStream(this.inputFileName);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
) {
int i=0;
/* begin Code B */
String regel=""; //debug
regel="A._B._een_twee(drie)vier_(vijf)"; //debug
/* code1 */ String[] result = regel.split("[\\s_()]"); // split op whitespace, of '_' of '(' of ')'
// resultaat zit nu in een Array van strings
//print het aantal elementen in de array //debug
System.out.println(result.length); //debug
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
/*eind code B */
// zie nog https://d396qusza40orc.cloudfront.net/cloudapplications/mps/mp1/MP1_Instructions.pdf
/* begin code A*/
while ((line = br.readLine()) != null) {
// Deal with the line
// nog "nod code A verwerken voor de variable line"
// dit nog vervangen
if (i<20) {
ret[i] = line;
} i++;
// dit nog vervangen
}
/* einde code A*/
}
return ret;
}
public static void main(String[] args) throws Exception {
if (args.length < 1){
System.out.println("MP1 <User ID>");
}
else {
String userName = args[0];
String inputFileName = "./input.txt";
MP1 mp = new MP1(userName, inputFileName);
String[] topItems = mp.process();
for (String item: topItems){
System.out.println(item);
}
}
}
}
| cx1964/cx1964BladMuziek | Klassiek/Chopin_Frédéric/MP1.v002.java | 1,466 | // resultaat zit nu in een Array van strings | line_comment | nl | import java.io.File;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class MP1 {
Random generator;
String userName;
String inputFileName;
String delimiters = " \t,;.?!-:@[](){}_*/";
String[] stopWordsArray = {"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours",
"yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its",
"itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that",
"these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having",
"do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while",
"of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before",
"after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again",
"further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each",
"few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than",
"too", "very", "s", "t", "can", "will", "just", "don", "should", "now"};
void initialRandomGenerator(String seed) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
messageDigest.update(seed.toLowerCase().trim().getBytes());
byte[] seedMD5 = messageDigest.digest();
long longSeed = 0;
for (int i = 0; i < seedMD5.length; i++) {
longSeed += ((long) seedMD5[i] & 0xffL) << (8 * i);
}
this.generator = new Random(longSeed);
}
Integer[] getIndexes() throws NoSuchAlgorithmException {
Integer n = 10000;
Integer number_of_lines = 50000;
Integer[] ret = new Integer[n];
this.initialRandomGenerator(this.userName);
for (int i = 0; i < n; i++) {
ret[i] = generator.nextInt(number_of_lines);
}
return ret;
}
public MP1(String userName, String inputFileName) {
this.userName = userName;
this.inputFileName = inputFileName;
}
public String[] process() throws Exception {
String[] ret = new String[20];
//TODO
// read input file
String line;
try (
InputStream fis = new FileInputStream(this.inputFileName);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
) {
int i=0;
/* begin Code B */
String regel=""; //debug
regel="A._B._een_twee(drie)vier_(vijf)"; //debug
/* code1 */ String[] result = regel.split("[\\s_()]"); // split op whitespace, of '_' of '(' of ')'
// resultaat zit<SUF>
//print het aantal elementen in de array //debug
System.out.println(result.length); //debug
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
/*eind code B */
// zie nog https://d396qusza40orc.cloudfront.net/cloudapplications/mps/mp1/MP1_Instructions.pdf
/* begin code A*/
while ((line = br.readLine()) != null) {
// Deal with the line
// nog "nod code A verwerken voor de variable line"
// dit nog vervangen
if (i<20) {
ret[i] = line;
} i++;
// dit nog vervangen
}
/* einde code A*/
}
return ret;
}
public static void main(String[] args) throws Exception {
if (args.length < 1){
System.out.println("MP1 <User ID>");
}
else {
String userName = args[0];
String inputFileName = "./input.txt";
MP1 mp = new MP1(userName, inputFileName);
String[] topItems = mp.process();
for (String item: topItems){
System.out.println(item);
}
}
}
}
| True | 1,190 | 11 | 1,280 | 11 | 1,358 | 9 | 1,280 | 11 | 1,496 | 12 | false | false | false | false | false | true |
1,117 | 18183_3 | import java.awt.Rectangle;_x000D_
import java.awt.Graphics;_x000D_
import java.awt.image.BufferedImage;_x000D_
import java.awt.image.ImageObserver;_x000D_
import java.io.File;_x000D_
import javax.imageio.ImageIO;_x000D_
import java.io.IOException;_x000D_
_x000D_
_x000D_
/** De klasse voor een Bitmap item_x000D_
* <P>_x000D_
* This program is distributed under the terms of the accompanying_x000D_
* COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_
* Please read it. Your use of the software constitutes acceptance_x000D_
* of the terms in the COPYRIGHT.txt file._x000D_
* @author Ian F. Darwin, [email protected]_x000D_
* @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn_x000D_
* @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman_x000D_
* @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_
* @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_
*/_x000D_
_x000D_
public class BitmapItem extends SlideItem {_x000D_
private BufferedImage bufferedImage;_x000D_
private String imageName;_x000D_
_x000D_
// level staat voor het item-level; name voor de naam van het bestand met het plaatje_x000D_
public BitmapItem(int level, String name) {_x000D_
super(level);_x000D_
imageName = name;_x000D_
try {_x000D_
bufferedImage = ImageIO.read(new File(imageName));_x000D_
}_x000D_
catch (IOException e) {_x000D_
System.err.println("Bestand " + imageName + " niet gevonden") ;_x000D_
}_x000D_
}_x000D_
_x000D_
// Een leeg bitmap-item_x000D_
public BitmapItem() {_x000D_
this(0, null);_x000D_
}_x000D_
_x000D_
// geef de bestandsnaam van het plaatje_x000D_
public String getName() {_x000D_
return imageName;_x000D_
}_x000D_
_x000D_
// geef de bounding box van het plaatje_x000D_
public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {_x000D_
return new Rectangle((int) (myStyle.indent * scale), 0,_x000D_
(int) (bufferedImage.getWidth(observer) * scale),_x000D_
((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));_x000D_
}_x000D_
_x000D_
// teken het plaatje_x000D_
public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {_x000D_
int width = x + (int) (myStyle.indent * scale);_x000D_
int height = y + (int) (myStyle.leading * scale);_x000D_
g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),_x000D_
(int) (bufferedImage.getHeight(observer)*scale), observer);_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
return "BitmapItem[" + getLevel() + "," + imageName + "]";_x000D_
}_x000D_
}_x000D_
| MichielMertens/OU_JP_MM_EVB | src/BitmapItem.java | 794 | // geef de bestandsnaam van het plaatje_x000D_ | line_comment | nl | import java.awt.Rectangle;_x000D_
import java.awt.Graphics;_x000D_
import java.awt.image.BufferedImage;_x000D_
import java.awt.image.ImageObserver;_x000D_
import java.io.File;_x000D_
import javax.imageio.ImageIO;_x000D_
import java.io.IOException;_x000D_
_x000D_
_x000D_
/** De klasse voor een Bitmap item_x000D_
* <P>_x000D_
* This program is distributed under the terms of the accompanying_x000D_
* COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_
* Please read it. Your use of the software constitutes acceptance_x000D_
* of the terms in the COPYRIGHT.txt file._x000D_
* @author Ian F. Darwin, [email protected]_x000D_
* @version $Id: BitmapItem.java,v 1.1 2002/12/17 Gert Florijn_x000D_
* @version $Id: BitmapItem.java,v 1.2 2003/12/17 Sylvia Stuurman_x000D_
* @version $Id: BitmapItem.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_
* @version $Id: BitmapItem.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_
*/_x000D_
_x000D_
public class BitmapItem extends SlideItem {_x000D_
private BufferedImage bufferedImage;_x000D_
private String imageName;_x000D_
_x000D_
// level staat voor het item-level; name voor de naam van het bestand met het plaatje_x000D_
public BitmapItem(int level, String name) {_x000D_
super(level);_x000D_
imageName = name;_x000D_
try {_x000D_
bufferedImage = ImageIO.read(new File(imageName));_x000D_
}_x000D_
catch (IOException e) {_x000D_
System.err.println("Bestand " + imageName + " niet gevonden") ;_x000D_
}_x000D_
}_x000D_
_x000D_
// Een leeg bitmap-item_x000D_
public BitmapItem() {_x000D_
this(0, null);_x000D_
}_x000D_
_x000D_
// geef de<SUF>
public String getName() {_x000D_
return imageName;_x000D_
}_x000D_
_x000D_
// geef de bounding box van het plaatje_x000D_
public Rectangle getBoundingBox(Graphics g, ImageObserver observer, float scale, Style myStyle) {_x000D_
return new Rectangle((int) (myStyle.indent * scale), 0,_x000D_
(int) (bufferedImage.getWidth(observer) * scale),_x000D_
((int) (myStyle.leading * scale)) + (int) (bufferedImage.getHeight(observer) * scale));_x000D_
}_x000D_
_x000D_
// teken het plaatje_x000D_
public void draw(int x, int y, float scale, Graphics g, Style myStyle, ImageObserver observer) {_x000D_
int width = x + (int) (myStyle.indent * scale);_x000D_
int height = y + (int) (myStyle.leading * scale);_x000D_
g.drawImage(bufferedImage, width, height,(int) (bufferedImage.getWidth(observer)*scale),_x000D_
(int) (bufferedImage.getHeight(observer)*scale), observer);_x000D_
}_x000D_
_x000D_
public String toString() {_x000D_
return "BitmapItem[" + getLevel() + "," + imageName + "]";_x000D_
}_x000D_
}_x000D_
| True | 1,028 | 19 | 1,152 | 20 | 1,141 | 17 | 1,152 | 20 | 1,232 | 20 | false | false | false | false | false | true |
839 | 57662_0 | package servlets;_x000D_
_x000D_
import java.io.IOException;_x000D_
import java.sql.Connection;_x000D_
import java.util.ArrayList;_x000D_
_x000D_
import javax.servlet.RequestDispatcher;_x000D_
import javax.servlet.ServletException;_x000D_
import javax.servlet.http.HttpServlet;_x000D_
import javax.servlet.http.HttpServletRequest;_x000D_
import javax.servlet.http.HttpServletResponse;_x000D_
_x000D_
import database.ConnectDBProduct;_x000D_
import domeinklassen.Product;_x000D_
_x000D_
public class ProductServlet extends HttpServlet{_x000D_
private static final long serialVersionUID = 1L;_x000D_
_x000D_
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {_x000D_
_x000D_
Connection con = (Connection)req.getSession().getAttribute("verbinding");_x000D_
String knop = req.getParameter("knop");_x000D_
_x000D_
ConnectDBProduct conn = new ConnectDBProduct(con); _x000D_
ArrayList<Product> deVoorraad = conn.getProducten();_x000D_
RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij default naar voorraadoverzicht_x000D_
_x000D_
//forward voorraadlijst naar de overzicht-pagina._x000D_
if(knop.equals("overzicht")){_x000D_
if(deVoorraad.size() == 0){_x000D_
req.setAttribute("msg", "Geen producten beschikbaar!");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("voorraadlijst", deVoorraad);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
}_x000D_
} _x000D_
//forward lijst producten onder min voorraad_x000D_
else if (knop.equals("OnderVoorraad")){_x000D_
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_
if(ondermin.size() == 0){_x000D_
req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("voorraadlijst", ondermin);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
}_x000D_
}_x000D_
//bestel producten onder min voorraad_x000D_
else if(knop.equals("WerkVoorraadBij")){_x000D_
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_
if(ondermin.size() == 0){_x000D_
req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_
}_x000D_
else{_x000D_
rd = req.getRequestDispatcher("nieuwebestelling.jsp");_x000D_
req.setAttribute("stap1", "Done");_x000D_
req.setAttribute("teBestellenProducten", ondermin);_x000D_
}_x000D_
}_x000D_
//maak een nieuw product aan_x000D_
else if(knop.equals("nieuw")){_x000D_
String nm = req.getParameter("naam");_x000D_
String ma = req.getParameter("minaantal");_x000D_
String eh = req.getParameter("eenheid");_x000D_
String pps = req.getParameter("pps");_x000D_
ArrayList<String> velden = new ArrayList<String>();_x000D_
velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");_x000D_
_x000D_
//check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)_x000D_
boolean allesIngevuld = true;_x000D_
for(String s : velden){_x000D_
if(s.equals("")){_x000D_
allesIngevuld = false;_x000D_
req.setAttribute("error", "Vul alle velden in!");_x000D_
break;_x000D_
}_x000D_
}_x000D_
//als gegevens ingevuld_x000D_
if(allesIngevuld){ _x000D_
try{ //check voor geldige nummers_x000D_
//maak product aan in database en haal op_x000D_
Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));_x000D_
//stuur toString() van nieuwe product terug_x000D_
String terug = "Nieuw product aangemaakt: " + nieuw.toString();_x000D_
req.setAttribute("msg", terug);_x000D_
}_x000D_
catch(Exception ex){_x000D_
System.out.println(ex);_x000D_
req.setAttribute("error", "Voer geldige nummers in!");_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
//zoek product op naam of artikelnummer_x000D_
else if(knop.equals("zoek")){_x000D_
String nm = req.getParameter("zoeknaam");_x000D_
String eh = req.getParameter("zoekeenheid");_x000D_
String anr = req.getParameter("zoeknummer"); _x000D_
ArrayList<Product> terug = new ArrayList<Product>();_x000D_
//check welke zoekterm er in is gevoerd_x000D_
if(!anr.equals("")){_x000D_
//check voor geldig artikelnummer (int)_x000D_
try{_x000D_
int nummer = Integer.parseInt(anr);_x000D_
terug.add(conn.zoekProduct(nummer));_x000D_
}catch(NumberFormatException e){_x000D_
req.setAttribute("error", "Vul een geldig artikelnummer in!");_x000D_
}_x000D_
}_x000D_
if(!nm.equals("")){_x000D_
for(Product p : conn.zoekProductNaam(nm)){_x000D_
terug.add(p);_x000D_
}_x000D_
} _x000D_
if(!eh.equals("")){_x000D_
for(Product p : conn.zoekProductEenheid(eh)){_x000D_
terug.add(p);_x000D_
}_x000D_
} _x000D_
else{_x000D_
req.setAttribute("error", "Vul een zoekcriterium in!");_x000D_
}_x000D_
if(terug.size() == 0){_x000D_
req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("zoekmsg", "Product(en) gevonden!"); _x000D_
req.setAttribute("arraygevonden", terug); _x000D_
}_x000D_
}_x000D_
_x000D_
//wijzig gezochte product_x000D_
else if(knop.equals("wijzig")){_x000D_
String productnummer = req.getParameter("product");_x000D_
Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));_x000D_
req.setAttribute("product", hetProduct);_x000D_
rd = req.getRequestDispatcher("wijzigproduct.jsp");_x000D_
} _x000D_
else if(knop.equals("verwijder")){_x000D_
String p = req.getParameter("product");_x000D_
if(conn.verwijderProduct(Integer.parseInt(p))){_x000D_
req.setAttribute("msg", "Product met succes verwijderd.");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("error", "Kon product niet verwijderen!");_x000D_
}_x000D_
deVoorraad = conn.getProducten();_x000D_
req.setAttribute("voorraadlijst", deVoorraad);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
} _x000D_
rd.forward(req, resp); _x000D_
}_x000D_
} | Jfeurich/Themaopdracht2 | Themaopdracht/src/servlets/ProductServlet.java | 1,844 | //stuur bij default naar voorraadoverzicht_x000D_ | line_comment | nl | package servlets;_x000D_
_x000D_
import java.io.IOException;_x000D_
import java.sql.Connection;_x000D_
import java.util.ArrayList;_x000D_
_x000D_
import javax.servlet.RequestDispatcher;_x000D_
import javax.servlet.ServletException;_x000D_
import javax.servlet.http.HttpServlet;_x000D_
import javax.servlet.http.HttpServletRequest;_x000D_
import javax.servlet.http.HttpServletResponse;_x000D_
_x000D_
import database.ConnectDBProduct;_x000D_
import domeinklassen.Product;_x000D_
_x000D_
public class ProductServlet extends HttpServlet{_x000D_
private static final long serialVersionUID = 1L;_x000D_
_x000D_
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {_x000D_
_x000D_
Connection con = (Connection)req.getSession().getAttribute("verbinding");_x000D_
String knop = req.getParameter("knop");_x000D_
_x000D_
ConnectDBProduct conn = new ConnectDBProduct(con); _x000D_
ArrayList<Product> deVoorraad = conn.getProducten();_x000D_
RequestDispatcher rd = req.getRequestDispatcher("product.jsp"); //stuur bij<SUF>
_x000D_
//forward voorraadlijst naar de overzicht-pagina._x000D_
if(knop.equals("overzicht")){_x000D_
if(deVoorraad.size() == 0){_x000D_
req.setAttribute("msg", "Geen producten beschikbaar!");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("voorraadlijst", deVoorraad);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
}_x000D_
} _x000D_
//forward lijst producten onder min voorraad_x000D_
else if (knop.equals("OnderVoorraad")){_x000D_
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_
if(ondermin.size() == 0){_x000D_
req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("voorraadlijst", ondermin);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
}_x000D_
}_x000D_
//bestel producten onder min voorraad_x000D_
else if(knop.equals("WerkVoorraadBij")){_x000D_
ArrayList<Product> ondermin = conn.getProductenOnderMinimum();_x000D_
if(ondermin.size() == 0){_x000D_
req.setAttribute("msg", "Alle producten zijn op voorraad!");_x000D_
}_x000D_
else{_x000D_
rd = req.getRequestDispatcher("nieuwebestelling.jsp");_x000D_
req.setAttribute("stap1", "Done");_x000D_
req.setAttribute("teBestellenProducten", ondermin);_x000D_
}_x000D_
}_x000D_
//maak een nieuw product aan_x000D_
else if(knop.equals("nieuw")){_x000D_
String nm = req.getParameter("naam");_x000D_
String ma = req.getParameter("minaantal");_x000D_
String eh = req.getParameter("eenheid");_x000D_
String pps = req.getParameter("pps");_x000D_
ArrayList<String> velden = new ArrayList<String>();_x000D_
velden.add(nm); velden.add(ma); velden.add(eh); velden.add("pps");_x000D_
_x000D_
//check of nodige velden in zijn gevuld (artikelnummer bestaat niet meer omdat de database die straks gaat aanmaken)_x000D_
boolean allesIngevuld = true;_x000D_
for(String s : velden){_x000D_
if(s.equals("")){_x000D_
allesIngevuld = false;_x000D_
req.setAttribute("error", "Vul alle velden in!");_x000D_
break;_x000D_
}_x000D_
}_x000D_
//als gegevens ingevuld_x000D_
if(allesIngevuld){ _x000D_
try{ //check voor geldige nummers_x000D_
//maak product aan in database en haal op_x000D_
Product nieuw = conn.nieuwProduct(nm, Integer.parseInt(ma), eh, Double.parseDouble(pps));_x000D_
//stuur toString() van nieuwe product terug_x000D_
String terug = "Nieuw product aangemaakt: " + nieuw.toString();_x000D_
req.setAttribute("msg", terug);_x000D_
}_x000D_
catch(Exception ex){_x000D_
System.out.println(ex);_x000D_
req.setAttribute("error", "Voer geldige nummers in!");_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
//zoek product op naam of artikelnummer_x000D_
else if(knop.equals("zoek")){_x000D_
String nm = req.getParameter("zoeknaam");_x000D_
String eh = req.getParameter("zoekeenheid");_x000D_
String anr = req.getParameter("zoeknummer"); _x000D_
ArrayList<Product> terug = new ArrayList<Product>();_x000D_
//check welke zoekterm er in is gevoerd_x000D_
if(!anr.equals("")){_x000D_
//check voor geldig artikelnummer (int)_x000D_
try{_x000D_
int nummer = Integer.parseInt(anr);_x000D_
terug.add(conn.zoekProduct(nummer));_x000D_
}catch(NumberFormatException e){_x000D_
req.setAttribute("error", "Vul een geldig artikelnummer in!");_x000D_
}_x000D_
}_x000D_
if(!nm.equals("")){_x000D_
for(Product p : conn.zoekProductNaam(nm)){_x000D_
terug.add(p);_x000D_
}_x000D_
} _x000D_
if(!eh.equals("")){_x000D_
for(Product p : conn.zoekProductEenheid(eh)){_x000D_
terug.add(p);_x000D_
}_x000D_
} _x000D_
else{_x000D_
req.setAttribute("error", "Vul een zoekcriterium in!");_x000D_
}_x000D_
if(terug.size() == 0){_x000D_
req.setAttribute("zoekmsg", "Geen producten gevonden met ingevulde criteria");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("zoekmsg", "Product(en) gevonden!"); _x000D_
req.setAttribute("arraygevonden", terug); _x000D_
}_x000D_
}_x000D_
_x000D_
//wijzig gezochte product_x000D_
else if(knop.equals("wijzig")){_x000D_
String productnummer = req.getParameter("product");_x000D_
Product hetProduct = conn.zoekProduct(Integer.parseInt(productnummer));_x000D_
req.setAttribute("product", hetProduct);_x000D_
rd = req.getRequestDispatcher("wijzigproduct.jsp");_x000D_
} _x000D_
else if(knop.equals("verwijder")){_x000D_
String p = req.getParameter("product");_x000D_
if(conn.verwijderProduct(Integer.parseInt(p))){_x000D_
req.setAttribute("msg", "Product met succes verwijderd.");_x000D_
}_x000D_
else{_x000D_
req.setAttribute("error", "Kon product niet verwijderen!");_x000D_
}_x000D_
deVoorraad = conn.getProducten();_x000D_
req.setAttribute("voorraadlijst", deVoorraad);_x000D_
rd = req.getRequestDispatcher("productenoverzicht.jsp");_x000D_
} _x000D_
rd.forward(req, resp); _x000D_
}_x000D_
} | True | 2,350 | 18 | 2,680 | 19 | 2,527 | 18 | 2,680 | 19 | 3,025 | 19 | false | false | false | false | false | true |
3,516 | 88901_3 | /**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.servlet.pic;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lucee.commons.io.IOUtil;
import lucee.runtime.net.http.ReqRspUtil;
/**
* Die Klasse PicServlet wird verwendet um Bilder darzustellen, alle Bilder die innerhalb des
* Deployer angezeigt werden, werden ueber diese Klasse aus der lucee.jar Datei geladen, das macht
* die Applikation flexibler und verlangt nicht das die Bilder fuer die Applikation an einem
* bestimmten Ort abgelegt sein muessen.
*/
public final class PicServlet extends HttpServlet {
/**
* Verzeichnis in welchem die bilder liegen
*/
public final static String PIC_SOURCE = "/resource/img/";
/**
* Interpretiert den Script-Name und laedt das entsprechende Bild aus den internen Resourcen.
*
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
// get out Stream
// pic
String[] arrPath = (req.getServletPath()).split("\\.");
String pic = PIC_SOURCE + "404.gif";
if (arrPath.length >= 3) {
pic = PIC_SOURCE + ((arrPath[arrPath.length - 3] + "." + arrPath[arrPath.length - 2]).replaceFirst("/", ""));
// mime type
String mime = "image/" + arrPath[arrPath.length - 2];
ReqRspUtil.setContentType(rsp, mime);
}
// write data from pic input to response output
OutputStream os = null;
InputStream is = null;
try {
os = rsp.getOutputStream();
is = getClass().getResourceAsStream(pic);
if (is == null) {
is = getClass().getResourceAsStream(PIC_SOURCE + "404.gif");
}
byte[] buf = new byte[4 * 1024];
int nread = 0;
while ((nread = is.read(buf)) >= 0) {
os.write(buf, 0, nread);
}
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
finally {
IOUtil.close(is, os);
}
}
} | lucee/Lucee | core/src/main/java/lucee/servlet/pic/PicServlet.java | 936 | /**
* Interpretiert den Script-Name und laedt das entsprechende Bild aus den internen Resourcen.
*
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/ | block_comment | nl | /**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.servlet.pic;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lucee.commons.io.IOUtil;
import lucee.runtime.net.http.ReqRspUtil;
/**
* Die Klasse PicServlet wird verwendet um Bilder darzustellen, alle Bilder die innerhalb des
* Deployer angezeigt werden, werden ueber diese Klasse aus der lucee.jar Datei geladen, das macht
* die Applikation flexibler und verlangt nicht das die Bilder fuer die Applikation an einem
* bestimmten Ort abgelegt sein muessen.
*/
public final class PicServlet extends HttpServlet {
/**
* Verzeichnis in welchem die bilder liegen
*/
public final static String PIC_SOURCE = "/resource/img/";
/**
* Interpretiert den Script-Name<SUF>*/
@Override
protected void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
// get out Stream
// pic
String[] arrPath = (req.getServletPath()).split("\\.");
String pic = PIC_SOURCE + "404.gif";
if (arrPath.length >= 3) {
pic = PIC_SOURCE + ((arrPath[arrPath.length - 3] + "." + arrPath[arrPath.length - 2]).replaceFirst("/", ""));
// mime type
String mime = "image/" + arrPath[arrPath.length - 2];
ReqRspUtil.setContentType(rsp, mime);
}
// write data from pic input to response output
OutputStream os = null;
InputStream is = null;
try {
os = rsp.getOutputStream();
is = getClass().getResourceAsStream(pic);
if (is == null) {
is = getClass().getResourceAsStream(PIC_SOURCE + "404.gif");
}
byte[] buf = new byte[4 * 1024];
int nread = 0;
while ((nread = is.read(buf)) >= 0) {
os.write(buf, 0, nread);
}
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
finally {
IOUtil.close(is, os);
}
}
} | False | 721 | 53 | 860 | 68 | 826 | 67 | 860 | 68 | 997 | 76 | false | false | false | false | false | true |
804 | 203327_6 | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van de opties van het menu
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | JanVHanssen/WorkloadPlanner | app/src/main/java/be/ucll/workloadplanner/MainActivity.java | 1,848 | // Instellen van de opties van het menu | line_comment | nl | package be.ucll.workloadplanner;
import static android.content.ContentValues.TAG;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
// Hoofdscherm waarin de verschillende fragmenten geladen worden
public class MainActivity extends AppCompatActivity {
private NavController navController;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore db;
private String userRole;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
setSupportActionBar(findViewById(R.id.toolbar));
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
navController = navHostFragment.getNavController();
logCurrentUserId();
}
// Controle ingelogde user om te checken of de login gewerkt heeft
private void logCurrentUserId() {
FirebaseUser user = getCurrentUser();
if (user != null) {
String phoneNumber = user.getPhoneNumber();
if (phoneNumber != null) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("userId", phoneNumber)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String userId = documentSnapshot.getString("userId");
Log.d("MainActivity", "User ID: " + userId);
getUserRole(userId); // Call to get user role after user ID retrieval
} else {
Log.d("MainActivity", "User document does not exist");
}
})
.addOnFailureListener(e -> {
Log.e("MainActivity", "Error getting user document", e);
});
} else {
Log.d("MainActivity", "No phone number associated with the current user");
}
} else {
Log.d("MainActivity", "No user is currently authenticated");
}
}
// Huidige gebruiker ophalen
private FirebaseUser getCurrentUser() {
return firebaseAuth.getCurrentUser();
}
// Voor het weergeven van het menu rechtsboven
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Hide or show menu items based on user role
MenuItem homeItem = menu.findItem(R.id.action_home);
MenuItem addTicketItem = menu.findItem(R.id.action_addTicket);
MenuItem logoutItem = menu.findItem(R.id.action_logout);
if (userRole != null && userRole.equals("Project Manager")) {
homeItem.setVisible(true);
addTicketItem.setVisible(true);
logoutItem.setVisible(true);
} else if (userRole != null && userRole.equals("Member")) {
homeItem.setVisible(true);
addTicketItem.setVisible(false);
logoutItem.setVisible(true);
} else {
addTicketItem.setVisible(false);
logoutItem.setVisible(false);
}
return true;
}
// Instellen van<SUF>
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_home) {
navController.navigate(R.id.action_any_fragment_to_tickets);
return true;
}
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container_view);
if (navHostFragment != null) {
Fragment currentFragment = navHostFragment.getChildFragmentManager().getPrimaryNavigationFragment();
// Now you have the current fragment
Log.d("MainActivity", "Current fragment: " + currentFragment.getClass().getSimpleName());
if (currentFragment instanceof TicketsFragment || currentFragment instanceof AddTicketFragment || currentFragment instanceof UpdateTicketFragment) {
if (item.getItemId() == R.id.action_addTicket) {
Log.d("MainActivity", "Adding ticket...");
navController.navigate(R.id.action_any_fragment_to_addTicket);
return true;
}
}
}
if (item.getItemId() == R.id.action_logout) {
firebaseAuth.signOut();
Log.d("MainActivity", "User logged out. Is user still logged in: " + (firebaseAuth.getCurrentUser() != null));
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// De rol van de gebruiker opzoeken, member of project manager
private void getUserRole(String userId) {
FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo("userId", userId)
.get()
.addOnSuccessListener(queryDocumentSnapshots -> {
if (!queryDocumentSnapshots.isEmpty()) {
DocumentSnapshot documentSnapshot = queryDocumentSnapshots.getDocuments().get(0);
String role = documentSnapshot.getString("role");
if (role != null) {
Log.d(TAG, "User id found: " + userId);
Log.d(TAG, "User role found: " + role);
userRole = role; // Update user role variable
invalidateOptionsMenu(); // Refresh menu to reflect changes
} else {
Log.d(TAG, "Role field not found in user document");
}
} else {
Log.d(TAG, "User document not found for userId: " + userId);
}
})
.addOnFailureListener(e -> {
Log.e(TAG, "Error fetching user document", e);
});
}
} | True | 1,238 | 10 | 1,486 | 10 | 1,550 | 10 | 1,486 | 10 | 1,781 | 10 | false | false | false | false | false | true |
1,508 | 37934_2 | package nl.sbdeveloper.leastslack;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LeastSlack {
private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)");
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Geef een bestandsnaam mee!");
System.exit(0);
return;
}
URL resource = LeastSlack.class.getClassLoader().getResource(args[0]);
if (resource == null) {
System.out.println("De meegegeven bestandsnaam bestaat niet!");
System.exit(0);
return;
}
Scanner fileScanner = new Scanner(resource.openStream());
JobShop shop = new JobShop();
int jobs = 0;
int machines = 0;
int lowestMachine = Integer.MAX_VALUE;
boolean wasFirstLine;
int currentJob = 0;
Matcher matcher;
while (fileScanner.hasNextLine()) {
matcher = pattern.matcher(fileScanner.nextLine());
wasFirstLine = false;
if (jobs != 0 && machines != 0) {
Job job = new Job(currentJob);
shop.getJobs().add(job);
}
while (matcher.find()) {
if (jobs == 0 || machines == 0) {
jobs = Integer.parseInt(matcher.group(1));
machines = Integer.parseInt(matcher.group(2));
wasFirstLine = true;
break;
} else {
int id = Integer.parseInt(matcher.group(1));
int duration = Integer.parseInt(matcher.group(2));
if (id < lowestMachine) lowestMachine = id;
Task task = new Task(id, duration);
int finalCurrentJob = currentJob;
Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst();
if (jobOpt.isEmpty()) break;
jobOpt.get().getTasks().add(task);
}
}
if (!wasFirstLine) currentJob++;
}
fileScanner.close();
//////////////////////////////////
shop.getJobs().forEach(Job::calculateEarliestStart);
shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration))
.ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration())));
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
//TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine
//TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80.
// int loop = 0;
int time = 0;
// while (loop < 40) {
while (!shop.isAllJobsDone()) {
// loop++;
System.out.println("------START------");
List<Job> conflictedJobs = new ArrayList<>();
int smallestTaskDuration = Integer.MAX_VALUE;
Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration
for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) {
if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip!
pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID()));
conflictedJobs.add(pair.getKey());
continue;
}
System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + ".");
pair.getValue().setDone(true);
pair.getKey().setBeginTime(time);
foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration());
if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration();
}
for (Job job : conflictedJobs) {
job.calculateEarliestStart();
}
if (!conflictedJobs.isEmpty()) {
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
}
if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden.
time += smallestTaskDuration;
for (Job j : shop.getJobs()) {
if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time);
}
System.out.println("Time: " + time);
}
for (Job j : shop.getJobs()) {
System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime());
}
}
}
| SBDPlugins/LeastSlackTime-OSM | src/main/java/nl/sbdeveloper/leastslack/LeastSlack.java | 1,705 | // int loop = 0; | line_comment | nl | package nl.sbdeveloper.leastslack;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LeastSlack {
private static final Pattern pattern = Pattern.compile("(\\d+)[ \\t]+(\\d+)");
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Geef een bestandsnaam mee!");
System.exit(0);
return;
}
URL resource = LeastSlack.class.getClassLoader().getResource(args[0]);
if (resource == null) {
System.out.println("De meegegeven bestandsnaam bestaat niet!");
System.exit(0);
return;
}
Scanner fileScanner = new Scanner(resource.openStream());
JobShop shop = new JobShop();
int jobs = 0;
int machines = 0;
int lowestMachine = Integer.MAX_VALUE;
boolean wasFirstLine;
int currentJob = 0;
Matcher matcher;
while (fileScanner.hasNextLine()) {
matcher = pattern.matcher(fileScanner.nextLine());
wasFirstLine = false;
if (jobs != 0 && machines != 0) {
Job job = new Job(currentJob);
shop.getJobs().add(job);
}
while (matcher.find()) {
if (jobs == 0 || machines == 0) {
jobs = Integer.parseInt(matcher.group(1));
machines = Integer.parseInt(matcher.group(2));
wasFirstLine = true;
break;
} else {
int id = Integer.parseInt(matcher.group(1));
int duration = Integer.parseInt(matcher.group(2));
if (id < lowestMachine) lowestMachine = id;
Task task = new Task(id, duration);
int finalCurrentJob = currentJob;
Optional<Job> jobOpt = shop.getJobs().stream().filter(j -> j.getId() == finalCurrentJob).findFirst();
if (jobOpt.isEmpty()) break;
jobOpt.get().getTasks().add(task);
}
}
if (!wasFirstLine) currentJob++;
}
fileScanner.close();
//////////////////////////////////
shop.getJobs().forEach(Job::calculateEarliestStart);
shop.getJobs().stream().max(Comparator.comparing(Job::calculateTotalDuration))
.ifPresent(job -> shop.getJobs().forEach(j -> j.calculateLatestStart(job.calculateTotalDuration())));
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
//TODO Fix dat hij de earliest start update als een taak begint die langer duurt dan de earliest start van een taak op de machine
//TODO In het huidige voorbeeld start Job 1 op Machine 0 (ES van 40, tijd 40) en heeft Job 2 op Machine 0 een ES van 60. Machine 0 is bezet tot 80, wat betekent dat die van Machine 0 moet updaten naar 80.
// int loop<SUF>
int time = 0;
// while (loop < 40) {
while (!shop.isAllJobsDone()) {
// loop++;
System.out.println("------START------");
List<Job> conflictedJobs = new ArrayList<>();
int smallestTaskDuration = Integer.MAX_VALUE;
Map<Integer, Integer> foundTaskDurations = new HashMap<>(); //Key = machine ID, value = duration
for (Map.Entry<Job, Task> pair : shop.getTasksWithEarliestTimeNow(time)) {
if (foundTaskDurations.containsKey(pair.getValue().getMachineID())) { //Er is al een task met een kleinere slack gestart, er was dus een conflict op dit tijdstip!
pair.getValue().setEarliestStart(foundTaskDurations.get(pair.getValue().getMachineID()));
conflictedJobs.add(pair.getKey());
continue;
}
System.out.println("Job " + pair.getKey().getId() + " wordt uitgevoerd op machine " + pair.getValue().getMachineID() + ".");
pair.getValue().setDone(true);
pair.getKey().setBeginTime(time);
foundTaskDurations.put(pair.getValue().getMachineID(), pair.getValue().getDuration());
if (pair.getValue().getDuration() < smallestTaskDuration) smallestTaskDuration = pair.getValue().getDuration();
}
for (Job job : conflictedJobs) {
job.calculateEarliestStart();
}
if (!conflictedJobs.isEmpty()) {
shop.calculateSlack();
for (Job j : shop.getJobs()) {
System.out.println("Job " + j.getId() + " heeft een total duration van " + j.calculateTotalDuration() + " en een slack van " + j.getSlack() + ":");
for (Task t : j.getTasks()) {
System.out.println("Task " + t.getMachineID() + " heeft een LS van " + t.getLatestStart() + " en een ES van " + t.getEarliestStart());
}
}
}
if (smallestTaskDuration == Integer.MAX_VALUE) smallestTaskDuration = 1; //Als er op dit tijdstip geen taken draaien, tellen we er 1 bij op tot we weer wat vinden.
time += smallestTaskDuration;
for (Job j : shop.getJobs()) {
if (j.getEndTime() == 0 && j.hasAllTasksDone()) j.setEndTime(time);
}
System.out.println("Time: " + time);
}
for (Job j : shop.getJobs()) {
System.out.println(j.getId() + "\t" + j.getBeginTime() + "\t" + j.getEndTime());
}
}
}
| True | 1,320 | 8 | 1,492 | 8 | 1,539 | 8 | 1,492 | 8 | 1,719 | 8 | false | false | false | false | false | true |
1,356 | 4744_9 |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class DemoWorld extends World {
// Declareren van CollisionEngine
private CollisionEngine ce;
// Declareren van TileEngine
private TileEngine te;
/**
* Constructor for objects of class MyWorld.
*
*/
public DemoWorld() {
// 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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -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, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -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, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},};
// initialiseren van de TileEngine klasse om de map aan de world toe te voegen
te = new TileEngine(this, 60, 60);
te.setTileFactory(new DemoTileFactory());
te.setMap(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);
// 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);
// 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
DemoHero hero = new DemoHero(ce, te);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 300, 200);
addObject(new Enemy(), 1170, 410);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
}
@Override
public void act() {
ce.update();
}
}
| ROCMondriaanTIN/project-greenfoot-game-2dook | DemoWorld.java | 3,194 | // 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 R. Springer
*/
public class DemoWorld extends World {
// Declareren van CollisionEngine
private CollisionEngine ce;
// Declareren van TileEngine
private TileEngine te;
/**
* Constructor for objects of class MyWorld.
*
*/
public DemoWorld() {
// 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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -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, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -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, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
{10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},};
// initialiseren van de TileEngine klasse om de map aan de world toe te voegen
te = new TileEngine(this, 60, 60);
te.setTileFactory(new DemoTileFactory());
te.setMap(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);
// Initialiseren van<SUF>
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// 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
DemoHero hero = new DemoHero(ce, te);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 300, 200);
addObject(new Enemy(), 1170, 410);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
}
@Override
public void act() {
ce.update();
}
}
| True | 3,419 | 24 | 3,459 | 24 | 3,455 | 20 | 3,459 | 24 | 3,542 | 25 | false | false | false | false | false | true |
2,193 | 55393_3 | /*
* SPDX-FileCopyrightText: 2021 Atos
* SPDX-License-Identifier: EUPL-1.2+
*/
package net.atos.client.zgw.drc.model;
import static net.atos.client.zgw.shared.util.DateTimeUtil.DATE_TIME_FORMAT_WITH_MILLISECONDS;
import java.net.URI;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.UUID;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbProperty;
import javax.json.bind.annotation.JsonbTransient;
import net.atos.client.zgw.shared.model.Vertrouwelijkheidaanduiding;
import net.atos.client.zgw.shared.util.URIUtil;
/**
*
*/
public abstract class AbstractEnkelvoudigInformatieobject {
public static final int IDENTIFICATIE_MAX_LENGTH = 40;
public static final int TITEL_MAX_LENGTH = 200;
public static final int BESTANDSNAAM_MAX_LENGTH = 255;
public static final int FORMAAT_MAX_LENGTH = 255;
public static final int AUTEUR_MAX_LENGTH = 200;
public static final int BESCHRIJVING_MAX_LENGTH = 1000;
/**
* URL-referentie naar dit object. Dit is de unieke identificatie en locatie van dit object.
*/
private URI url;
/**
* Een binnen een gegeven context ondubbelzinnige referentie naar het INFORMATIEOBJECT.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#IDENTIFICATIE_MAX_LENGTH}
*/
private String identificatie;
/**
* Het RSIN van de Niet-natuurlijk persoon zijnde de organisatie die het informatieobject heeft gecreeerd of heeft ontvangen
* en als eerste in een samenwerkingsketen heeft vastgelegd.
*/
private String bronorganisatie;
/**
* Een datum of een gebeurtenis in de levenscyclus van het INFORMATIEOBJECT
*/
private LocalDate creatiedatum;
/**
* De naam waaronder het INFORMATIEOBJECT formeel bekend is.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#TITEL_MAX_LENGTH}
*/
private String titel;
/**
* Aanduiding van de mate waarin het INFORMATIEOBJECT voor de openbaarheid bestemd is
*/
private Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding;
/**
* De persoon of organisatie die in de eerste plaats verantwoordelijk is voor het creeren van de inhoud van het INFORMATIEOBJECT
* maxLength: {@link AbstractEnkelvoudigInformatieobject#AUTEUR_MAX_LENGTH}
*/
private String auteur;
/**
* Aanduiding van de stand van zaken van een INFORMATIEOBJECT.
* De waarden ''in bewerking'' en ''ter vaststelling'' komen niet voor als het attribuut `ontvangstdatum` van een waarde is voorzien.
* Wijziging van de Status in ''gearchiveerd'' impliceert dat het informatieobject een duurzaam, niet-wijzigbaar Formaat dient te hebben
*/
private InformatieobjectStatus status;
/**
* Het "Media Type" (voorheen "MIME type") voor de wijze waaropde inhoud van het INFORMATIEOBJECT is vastgelegd in een computerbestand.
* Voorbeeld: `application/msword`. Zie: https://www.iana.org/assignments/media-types/media-types.xhtml
* maxLength: {@link AbstractEnkelvoudigInformatieobject#FORMAAT_MAX_LENGTH}
*/
private String formaat;
/**
* Een ISO 639-2/B taalcode waarin de inhoud van het INFORMATIEOBJECT is vastgelegd.
* Voorbeeld: `nld`. Zie: https://www.iso.org/standard/4767.html
* maxLength: 3
* minLength: 3
*/
private String taal;
/**
* Het (automatische) versienummer van het INFORMATIEOBJECT.
* Deze begint bij 1 als het INFORMATIEOBJECT aangemaakt wordt.
*/
private Integer versie;
/**
* Een datumtijd in ISO8601 formaat waarop deze versie van het INFORMATIEOBJECT is aangemaakt of gewijzigd.
*/
@JsonbDateFormat(DATE_TIME_FORMAT_WITH_MILLISECONDS)
private ZonedDateTime beginRegistratie;
/**
* De naam van het fysieke bestand waarin de inhoud van het informatieobject is vastgelegd, inclusief extensie.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#BESTANDSNAAM_MAX_LENGTH}
*/
private String bestandsnaam;
/**
* Aantal bytes dat de inhoud van INFORMATIEOBJECT in beslag neemt.
*/
private Long bestandsomvang;
/**
* De URL waarmee de inhoud van het INFORMATIEOBJECT op te vragen
*/
private URI link;
/**
* Een generieke beschrijving van de inhoud van het INFORMATIEOBJECT.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#BESCHRIJVING_MAX_LENGTH}
*/
private String beschrijving;
/**
* De datum waarop het INFORMATIEOBJECT ontvangen is.
* Verplicht te registreren voor INFORMATIEOBJECTen die van buiten de zaakbehandelende organisatie(s) ontvangen zijn.
* Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn
* waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt.
*/
@JsonbProperty(nillable = true)
private LocalDate ontvangstdatum;
/**
* De datum waarop het INFORMATIEOBJECT verzonden is, zoals deze op het INFORMATIEOBJECT vermeld is.
* Dit geldt voor zowel inkomende als uitgaande INFORMATIEOBJECTen.
* Eenzelfde informatieobject kan niet tegelijk inkomend en uitgaand zijn.
* Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn
* waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt.
*/
@JsonbProperty(nillable = true)
private LocalDate verzenddatum;
/**
* Indicatie of er beperkingen gelden aangaande het gebruik van het informatieobject anders dan raadpleging.
* Dit veld mag `null` zijn om aan te geven dat de indicatie nog niet bekend is.
* Als de indicatie gezet is, dan kan je de gebruiksrechten die van toepassing zijn raadplegen via de GEBRUIKSRECHTen resource.
*/
private Boolean indicatieGebruiksrecht;
/**
* Aanduiding van de rechtskracht van een informatieobject.
* Mag niet van een waarde zijn voorzien als de `status` de waarde 'in bewerking' of 'ter vaststelling' heeft.
*/
private Ondertekening ondertekening;
/**
* Uitdrukking van mate van volledigheid en onbeschadigd zijn van digitaal bestand.
*/
private Integriteit integriteit;
/**
* URL-referentie naar het INFORMATIEOBJECTTYPE (in de Catalogi API).
*/
private URI informatieobjecttype;
/**
* Geeft aan of het document gelocked is. Alleen als een document gelocked is, mogen er aanpassingen gemaakt worden.
*/
private Boolean locked;
public URI getUrl() {
return url;
}
public void setUrl(final URI url) {
this.url = url;
}
public String getIdentificatie() {
return identificatie;
}
public void setIdentificatie(final String identificatie) {
this.identificatie = identificatie;
}
public String getBronorganisatie() {
return bronorganisatie;
}
public void setBronorganisatie(final String bronorganisatie) {
this.bronorganisatie = bronorganisatie;
}
public LocalDate getCreatiedatum() {
return creatiedatum;
}
public void setCreatiedatum(final LocalDate creatiedatum) {
this.creatiedatum = creatiedatum;
}
public String getTitel() {
return titel;
}
public void setTitel(final String titel) {
this.titel = titel;
}
public Vertrouwelijkheidaanduiding getVertrouwelijkheidaanduiding() {
return vertrouwelijkheidaanduiding;
}
public void setVertrouwelijkheidaanduiding(final Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding) {
this.vertrouwelijkheidaanduiding = vertrouwelijkheidaanduiding;
}
public String getAuteur() {
return auteur;
}
public void setAuteur(final String auteur) {
this.auteur = auteur;
}
public InformatieobjectStatus getStatus() {
return status;
}
public void setStatus(final InformatieobjectStatus status) {
this.status = status;
}
public String getFormaat() {
return formaat;
}
public void setFormaat(final String formaat) {
this.formaat = formaat;
}
public String getTaal() {
return taal;
}
public void setTaal(final String taal) {
this.taal = taal;
}
public Integer getVersie() {
return versie;
}
public void setVersie(final Integer versie) {
this.versie = versie;
}
public ZonedDateTime getBeginRegistratie() {
return beginRegistratie;
}
public void setBeginRegistratie(final ZonedDateTime beginRegistratie) {
this.beginRegistratie = beginRegistratie;
}
public String getBestandsnaam() {
return bestandsnaam;
}
public void setBestandsnaam(final String bestandsnaam) {
this.bestandsnaam = bestandsnaam;
}
public Long getBestandsomvang() {
return bestandsomvang;
}
public void setBestandsomvang(final Long bestandsomvang) {
this.bestandsomvang = bestandsomvang;
}
public URI getLink() {
return link;
}
public void setLink(final URI link) {
this.link = link;
}
public String getBeschrijving() {
return beschrijving;
}
public void setBeschrijving(final String beschrijving) {
this.beschrijving = beschrijving;
}
public LocalDate getOntvangstdatum() {
return ontvangstdatum;
}
public void setOntvangstdatum(final LocalDate ontvangstdatum) {
this.ontvangstdatum = ontvangstdatum;
}
public LocalDate getVerzenddatum() {
return verzenddatum;
}
public void setVerzenddatum(final LocalDate verzenddatum) {
this.verzenddatum = verzenddatum;
}
public Boolean getIndicatieGebruiksrecht() {
return indicatieGebruiksrecht;
}
public void setIndicatieGebruiksrecht(final Boolean indicatieGebruiksrecht) {
this.indicatieGebruiksrecht = indicatieGebruiksrecht;
}
public Ondertekening getOndertekening() {
if (ondertekening != null && ondertekening.getDatum() == null && ondertekening.getSoort() == null) {
return null;
}
return ondertekening;
}
public void setOndertekening(final Ondertekening ondertekening) {
this.ondertekening = ondertekening;
}
public Integriteit getIntegriteit() {
return integriteit;
}
public void setIntegriteit(final Integriteit integriteit) {
this.integriteit = integriteit;
}
public URI getInformatieobjecttype() {
return informatieobjecttype;
}
public void setInformatieobjecttype(final URI informatieobjecttype) {
this.informatieobjecttype = informatieobjecttype;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(final Boolean locked) {
this.locked = locked;
}
@JsonbTransient
public UUID getUUID() {
return URIUtil.parseUUIDFromResourceURI(url);
}
@JsonbTransient
public UUID getInformatieobjectTypeUUID() {
return URIUtil.parseUUIDFromResourceURI(informatieobjecttype);
}
}
| bartlukens/zaakafhandelcomponent | src/main/java/net/atos/client/zgw/drc/model/AbstractEnkelvoudigInformatieobject.java | 3,539 | /**
* Het RSIN van de Niet-natuurlijk persoon zijnde de organisatie die het informatieobject heeft gecreeerd of heeft ontvangen
* en als eerste in een samenwerkingsketen heeft vastgelegd.
*/ | block_comment | nl | /*
* SPDX-FileCopyrightText: 2021 Atos
* SPDX-License-Identifier: EUPL-1.2+
*/
package net.atos.client.zgw.drc.model;
import static net.atos.client.zgw.shared.util.DateTimeUtil.DATE_TIME_FORMAT_WITH_MILLISECONDS;
import java.net.URI;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.UUID;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbProperty;
import javax.json.bind.annotation.JsonbTransient;
import net.atos.client.zgw.shared.model.Vertrouwelijkheidaanduiding;
import net.atos.client.zgw.shared.util.URIUtil;
/**
*
*/
public abstract class AbstractEnkelvoudigInformatieobject {
public static final int IDENTIFICATIE_MAX_LENGTH = 40;
public static final int TITEL_MAX_LENGTH = 200;
public static final int BESTANDSNAAM_MAX_LENGTH = 255;
public static final int FORMAAT_MAX_LENGTH = 255;
public static final int AUTEUR_MAX_LENGTH = 200;
public static final int BESCHRIJVING_MAX_LENGTH = 1000;
/**
* URL-referentie naar dit object. Dit is de unieke identificatie en locatie van dit object.
*/
private URI url;
/**
* Een binnen een gegeven context ondubbelzinnige referentie naar het INFORMATIEOBJECT.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#IDENTIFICATIE_MAX_LENGTH}
*/
private String identificatie;
/**
* Het RSIN van<SUF>*/
private String bronorganisatie;
/**
* Een datum of een gebeurtenis in de levenscyclus van het INFORMATIEOBJECT
*/
private LocalDate creatiedatum;
/**
* De naam waaronder het INFORMATIEOBJECT formeel bekend is.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#TITEL_MAX_LENGTH}
*/
private String titel;
/**
* Aanduiding van de mate waarin het INFORMATIEOBJECT voor de openbaarheid bestemd is
*/
private Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding;
/**
* De persoon of organisatie die in de eerste plaats verantwoordelijk is voor het creeren van de inhoud van het INFORMATIEOBJECT
* maxLength: {@link AbstractEnkelvoudigInformatieobject#AUTEUR_MAX_LENGTH}
*/
private String auteur;
/**
* Aanduiding van de stand van zaken van een INFORMATIEOBJECT.
* De waarden ''in bewerking'' en ''ter vaststelling'' komen niet voor als het attribuut `ontvangstdatum` van een waarde is voorzien.
* Wijziging van de Status in ''gearchiveerd'' impliceert dat het informatieobject een duurzaam, niet-wijzigbaar Formaat dient te hebben
*/
private InformatieobjectStatus status;
/**
* Het "Media Type" (voorheen "MIME type") voor de wijze waaropde inhoud van het INFORMATIEOBJECT is vastgelegd in een computerbestand.
* Voorbeeld: `application/msword`. Zie: https://www.iana.org/assignments/media-types/media-types.xhtml
* maxLength: {@link AbstractEnkelvoudigInformatieobject#FORMAAT_MAX_LENGTH}
*/
private String formaat;
/**
* Een ISO 639-2/B taalcode waarin de inhoud van het INFORMATIEOBJECT is vastgelegd.
* Voorbeeld: `nld`. Zie: https://www.iso.org/standard/4767.html
* maxLength: 3
* minLength: 3
*/
private String taal;
/**
* Het (automatische) versienummer van het INFORMATIEOBJECT.
* Deze begint bij 1 als het INFORMATIEOBJECT aangemaakt wordt.
*/
private Integer versie;
/**
* Een datumtijd in ISO8601 formaat waarop deze versie van het INFORMATIEOBJECT is aangemaakt of gewijzigd.
*/
@JsonbDateFormat(DATE_TIME_FORMAT_WITH_MILLISECONDS)
private ZonedDateTime beginRegistratie;
/**
* De naam van het fysieke bestand waarin de inhoud van het informatieobject is vastgelegd, inclusief extensie.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#BESTANDSNAAM_MAX_LENGTH}
*/
private String bestandsnaam;
/**
* Aantal bytes dat de inhoud van INFORMATIEOBJECT in beslag neemt.
*/
private Long bestandsomvang;
/**
* De URL waarmee de inhoud van het INFORMATIEOBJECT op te vragen
*/
private URI link;
/**
* Een generieke beschrijving van de inhoud van het INFORMATIEOBJECT.
* maxLength: {@link AbstractEnkelvoudigInformatieobject#BESCHRIJVING_MAX_LENGTH}
*/
private String beschrijving;
/**
* De datum waarop het INFORMATIEOBJECT ontvangen is.
* Verplicht te registreren voor INFORMATIEOBJECTen die van buiten de zaakbehandelende organisatie(s) ontvangen zijn.
* Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn
* waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt.
*/
@JsonbProperty(nillable = true)
private LocalDate ontvangstdatum;
/**
* De datum waarop het INFORMATIEOBJECT verzonden is, zoals deze op het INFORMATIEOBJECT vermeld is.
* Dit geldt voor zowel inkomende als uitgaande INFORMATIEOBJECTen.
* Eenzelfde informatieobject kan niet tegelijk inkomend en uitgaand zijn.
* Ontvangst en verzending is voorbehouden aan documenten die van of naar andere personen ontvangen of verzonden zijn
* waarbij die personen niet deel uit maken van de behandeling van de zaak waarin het document een rol speelt.
*/
@JsonbProperty(nillable = true)
private LocalDate verzenddatum;
/**
* Indicatie of er beperkingen gelden aangaande het gebruik van het informatieobject anders dan raadpleging.
* Dit veld mag `null` zijn om aan te geven dat de indicatie nog niet bekend is.
* Als de indicatie gezet is, dan kan je de gebruiksrechten die van toepassing zijn raadplegen via de GEBRUIKSRECHTen resource.
*/
private Boolean indicatieGebruiksrecht;
/**
* Aanduiding van de rechtskracht van een informatieobject.
* Mag niet van een waarde zijn voorzien als de `status` de waarde 'in bewerking' of 'ter vaststelling' heeft.
*/
private Ondertekening ondertekening;
/**
* Uitdrukking van mate van volledigheid en onbeschadigd zijn van digitaal bestand.
*/
private Integriteit integriteit;
/**
* URL-referentie naar het INFORMATIEOBJECTTYPE (in de Catalogi API).
*/
private URI informatieobjecttype;
/**
* Geeft aan of het document gelocked is. Alleen als een document gelocked is, mogen er aanpassingen gemaakt worden.
*/
private Boolean locked;
public URI getUrl() {
return url;
}
public void setUrl(final URI url) {
this.url = url;
}
public String getIdentificatie() {
return identificatie;
}
public void setIdentificatie(final String identificatie) {
this.identificatie = identificatie;
}
public String getBronorganisatie() {
return bronorganisatie;
}
public void setBronorganisatie(final String bronorganisatie) {
this.bronorganisatie = bronorganisatie;
}
public LocalDate getCreatiedatum() {
return creatiedatum;
}
public void setCreatiedatum(final LocalDate creatiedatum) {
this.creatiedatum = creatiedatum;
}
public String getTitel() {
return titel;
}
public void setTitel(final String titel) {
this.titel = titel;
}
public Vertrouwelijkheidaanduiding getVertrouwelijkheidaanduiding() {
return vertrouwelijkheidaanduiding;
}
public void setVertrouwelijkheidaanduiding(final Vertrouwelijkheidaanduiding vertrouwelijkheidaanduiding) {
this.vertrouwelijkheidaanduiding = vertrouwelijkheidaanduiding;
}
public String getAuteur() {
return auteur;
}
public void setAuteur(final String auteur) {
this.auteur = auteur;
}
public InformatieobjectStatus getStatus() {
return status;
}
public void setStatus(final InformatieobjectStatus status) {
this.status = status;
}
public String getFormaat() {
return formaat;
}
public void setFormaat(final String formaat) {
this.formaat = formaat;
}
public String getTaal() {
return taal;
}
public void setTaal(final String taal) {
this.taal = taal;
}
public Integer getVersie() {
return versie;
}
public void setVersie(final Integer versie) {
this.versie = versie;
}
public ZonedDateTime getBeginRegistratie() {
return beginRegistratie;
}
public void setBeginRegistratie(final ZonedDateTime beginRegistratie) {
this.beginRegistratie = beginRegistratie;
}
public String getBestandsnaam() {
return bestandsnaam;
}
public void setBestandsnaam(final String bestandsnaam) {
this.bestandsnaam = bestandsnaam;
}
public Long getBestandsomvang() {
return bestandsomvang;
}
public void setBestandsomvang(final Long bestandsomvang) {
this.bestandsomvang = bestandsomvang;
}
public URI getLink() {
return link;
}
public void setLink(final URI link) {
this.link = link;
}
public String getBeschrijving() {
return beschrijving;
}
public void setBeschrijving(final String beschrijving) {
this.beschrijving = beschrijving;
}
public LocalDate getOntvangstdatum() {
return ontvangstdatum;
}
public void setOntvangstdatum(final LocalDate ontvangstdatum) {
this.ontvangstdatum = ontvangstdatum;
}
public LocalDate getVerzenddatum() {
return verzenddatum;
}
public void setVerzenddatum(final LocalDate verzenddatum) {
this.verzenddatum = verzenddatum;
}
public Boolean getIndicatieGebruiksrecht() {
return indicatieGebruiksrecht;
}
public void setIndicatieGebruiksrecht(final Boolean indicatieGebruiksrecht) {
this.indicatieGebruiksrecht = indicatieGebruiksrecht;
}
public Ondertekening getOndertekening() {
if (ondertekening != null && ondertekening.getDatum() == null && ondertekening.getSoort() == null) {
return null;
}
return ondertekening;
}
public void setOndertekening(final Ondertekening ondertekening) {
this.ondertekening = ondertekening;
}
public Integriteit getIntegriteit() {
return integriteit;
}
public void setIntegriteit(final Integriteit integriteit) {
this.integriteit = integriteit;
}
public URI getInformatieobjecttype() {
return informatieobjecttype;
}
public void setInformatieobjecttype(final URI informatieobjecttype) {
this.informatieobjecttype = informatieobjecttype;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(final Boolean locked) {
this.locked = locked;
}
@JsonbTransient
public UUID getUUID() {
return URIUtil.parseUUIDFromResourceURI(url);
}
@JsonbTransient
public UUID getInformatieobjectTypeUUID() {
return URIUtil.parseUUIDFromResourceURI(informatieobjecttype);
}
}
| True | 2,944 | 54 | 3,230 | 66 | 3,088 | 51 | 3,231 | 66 | 3,615 | 60 | false | false | false | false | false | true |
3,248 | 107719_3 | import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
/*
* This file is part of the RoomSports distribution
* (https://github.com/jobeagle/roomsports/roomsports.git).
*
* Copyright (c) 2020 Bruno Schmidt ([email protected]).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* 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/>.
*****************************************************************************
* Update.java
*****************************************************************************
*
* Diese Klasse beinhaltet den automatischen Update.
* Um die eigenen Klassen (und EXE-Dateien problemlos überschreiben zu können
* ist der Update in ein extra Jar-Archiv ausgelagert.
*
*/
public class Update {
private final static String zipFile = "rsupdate.zip";
private final static String downloadURL = "https://www.mtbsimulator.de/rs/download/"+zipFile;
private static Thread worker;
private final static String root = "update/";
private static boolean logDebug = true; // Debugstatus für das Logging ein/aus
private static boolean updateComplete = false;
private static Shell shell;
private static Label lblInfo = null;
private static String infoText = new String("");
private static String javaRT = System.getProperty("java.home") + "\\bin\\javaw.exe";
/**
* Alle Aktionen werden hier in einem extra Thread durchgeführt.
*/
private static void download()
{
worker = new Thread(
new Runnable(){
public void run()
{
try {
Mlog.info("Update startet mit Download");
downloadFile(downloadURL);
Mlog.debug("Unzip...");
unzip();
Mlog.debug("kopiere Dateien");
copyFiles(new File(root),new File("").getAbsolutePath());
infoText = "aufräumen";
Mlog.debug("aufraeumen");
cleanup();
infoText = "Update beendet";
Mlog.debug(infoText);
startRs();
Mlog.info("RS gestartet");
updateComplete = true;
} catch (Exception ex) {
updateComplete = true;
String fehler = "Beim Updatevorgang ist ein Fehler aufgetreten!";
Mlog.error(fehler);
Mlog.ex(ex);
startRs();
Mlog.info("RS gestartet (ex)");
}
}
});
worker.start();
}
/**
* RoomSports wieder starten.
*/
private static void startRs() {
Mlog.debug("Starte RoomSports...");
String[] run = {javaRT,"-jar","rs.jar"};
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
Mlog.ex(ex);;
}
}
/**
* ZIP-Datei und Updateverzeichnis werden gelöscht.
*/
private static void cleanup()
{
Mlog.debug("Cleanup wird durchgeführt...");
File f = new File(zipFile);
f.delete();
remove(new File(root));
new File(root).delete();
}
/**
* löscht rekursiv Dateien bzw. Verzeichnisse
* @param f
*/
private static void remove(File f)
{
File[]files = f.listFiles();
for(File ff:files)
{
if(ff.isDirectory())
{
remove(ff);
ff.delete();
}
else
{
ff.delete();
}
}
}
/**
* Kopiert die entzippten Dateien vom Verzeichnis update in das Programmverzeichnis
* von RoomSports.
* @param f Pfad des Quellverzeichnisses (update)
* @param dir Zielverzeichnisname (Programmverzeichnis)
* @throws IOException
*/
private static void copyFiles(File f,String dir) throws IOException
{
File[]files = f.listFiles();
for(File ff:files)
{
if(ff.isDirectory()){
new File(dir+"/"+ff.getName()).mkdir();
copyFiles(ff,dir+"/"+ff.getName());
}
else
{
copy(ff.getAbsolutePath(),dir+"/"+ff.getName());
}
}
}
/**
* Ein einfacher Dateikopierer.
* @param srFile Quellverzeichnis
* @param dtFile Zielverzeichnis
* @throws FileNotFoundException
* @throws IOException
*/
public static void copy(String srFile, String dtFile) throws FileNotFoundException, IOException{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
}
/**
* Das "zipfile" wird entzipped.
* @throws IOException
*/
private static void unzip() throws IOException
{
int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(zipFile);
Enumeration<? extends ZipEntry> e = zipfile.entries();
(new File(root)).mkdir();
while(e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
infoText = "Extrahiere: " +entry;
Mlog.debug(infoText);
if(entry.isDirectory())
(new File(root+entry.getName())).mkdir();
else{
(new File(root+entry.getName())).createNewFile();
is = new BufferedInputStream
(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new
FileOutputStream(root+entry.getName());
dest = new
BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER))
!= -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
}
zipfile.close();
}
/**
* Lädt die Datei aus der übergebenen URL herunter.
* @param link
* @throws MalformedURLException
* @throws IOException
*/
private static void downloadFile(String link) throws MalformedURLException, IOException
{
URL url = new URL(link);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
long max = conn.getContentLength();
infoText = "download " + max + " Bytes";
Mlog.debug("Download Datei ...Update Größe(komprimiert): " + max + " Bytes");
BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(zipFile)));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1) {
fOut.write(buffer, 0, bytesRead);
}
fOut.flush();
fOut.close();
is.close();
Mlog.debug("Download abgeschlossen");
}
/**
* Anzeige des aktuellen Status im Label
* @param info
*/
private static void showInfoText(String info) {
lblInfo.setText(info);
lblInfo.redraw();
}
/**
* Hauptprogramm des Updaters
* @param args
*/
public static void main(String[] args) {
FontData wertKlFont = new FontData("Arial",(int) (14),SWT.BOLD);
Display display = new Display ();
shell = new Shell(display);
shell.addListener(SWT.Show, new Listener() {
public void handleEvent(Event event) {
Mlog.init();
Mlog.setDebugstatus(logDebug);
download();
}
});
shell.setSize(310, 113);
shell.setBounds(120, 10, 310, 80);
shell.setText("Update");
lblInfo = new Label(shell, SWT.NONE);
lblInfo.setBounds(10, 10, 290, 20);
lblInfo.setFont(new Font(display, wertKlFont));
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
showInfoText(infoText);
display.sleep();
if (updateComplete) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Mlog.ex(e);
}
shell.dispose();
}
}
}
display.dispose();
}
}
| jobeagle/roomsports | updater/src/Update.java | 2,877 | /**
* RoomSports wieder starten.
*/ | block_comment | nl | import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
/*
* This file is part of the RoomSports distribution
* (https://github.com/jobeagle/roomsports/roomsports.git).
*
* Copyright (c) 2020 Bruno Schmidt ([email protected]).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* 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/>.
*****************************************************************************
* Update.java
*****************************************************************************
*
* Diese Klasse beinhaltet den automatischen Update.
* Um die eigenen Klassen (und EXE-Dateien problemlos überschreiben zu können
* ist der Update in ein extra Jar-Archiv ausgelagert.
*
*/
public class Update {
private final static String zipFile = "rsupdate.zip";
private final static String downloadURL = "https://www.mtbsimulator.de/rs/download/"+zipFile;
private static Thread worker;
private final static String root = "update/";
private static boolean logDebug = true; // Debugstatus für das Logging ein/aus
private static boolean updateComplete = false;
private static Shell shell;
private static Label lblInfo = null;
private static String infoText = new String("");
private static String javaRT = System.getProperty("java.home") + "\\bin\\javaw.exe";
/**
* Alle Aktionen werden hier in einem extra Thread durchgeführt.
*/
private static void download()
{
worker = new Thread(
new Runnable(){
public void run()
{
try {
Mlog.info("Update startet mit Download");
downloadFile(downloadURL);
Mlog.debug("Unzip...");
unzip();
Mlog.debug("kopiere Dateien");
copyFiles(new File(root),new File("").getAbsolutePath());
infoText = "aufräumen";
Mlog.debug("aufraeumen");
cleanup();
infoText = "Update beendet";
Mlog.debug(infoText);
startRs();
Mlog.info("RS gestartet");
updateComplete = true;
} catch (Exception ex) {
updateComplete = true;
String fehler = "Beim Updatevorgang ist ein Fehler aufgetreten!";
Mlog.error(fehler);
Mlog.ex(ex);
startRs();
Mlog.info("RS gestartet (ex)");
}
}
});
worker.start();
}
/**
* RoomSports wieder starten.<SUF>*/
private static void startRs() {
Mlog.debug("Starte RoomSports...");
String[] run = {javaRT,"-jar","rs.jar"};
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
Mlog.ex(ex);;
}
}
/**
* ZIP-Datei und Updateverzeichnis werden gelöscht.
*/
private static void cleanup()
{
Mlog.debug("Cleanup wird durchgeführt...");
File f = new File(zipFile);
f.delete();
remove(new File(root));
new File(root).delete();
}
/**
* löscht rekursiv Dateien bzw. Verzeichnisse
* @param f
*/
private static void remove(File f)
{
File[]files = f.listFiles();
for(File ff:files)
{
if(ff.isDirectory())
{
remove(ff);
ff.delete();
}
else
{
ff.delete();
}
}
}
/**
* Kopiert die entzippten Dateien vom Verzeichnis update in das Programmverzeichnis
* von RoomSports.
* @param f Pfad des Quellverzeichnisses (update)
* @param dir Zielverzeichnisname (Programmverzeichnis)
* @throws IOException
*/
private static void copyFiles(File f,String dir) throws IOException
{
File[]files = f.listFiles();
for(File ff:files)
{
if(ff.isDirectory()){
new File(dir+"/"+ff.getName()).mkdir();
copyFiles(ff,dir+"/"+ff.getName());
}
else
{
copy(ff.getAbsolutePath(),dir+"/"+ff.getName());
}
}
}
/**
* Ein einfacher Dateikopierer.
* @param srFile Quellverzeichnis
* @param dtFile Zielverzeichnis
* @throws FileNotFoundException
* @throws IOException
*/
public static void copy(String srFile, String dtFile) throws FileNotFoundException, IOException{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
}
/**
* Das "zipfile" wird entzipped.
* @throws IOException
*/
private static void unzip() throws IOException
{
int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(zipFile);
Enumeration<? extends ZipEntry> e = zipfile.entries();
(new File(root)).mkdir();
while(e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
infoText = "Extrahiere: " +entry;
Mlog.debug(infoText);
if(entry.isDirectory())
(new File(root+entry.getName())).mkdir();
else{
(new File(root+entry.getName())).createNewFile();
is = new BufferedInputStream
(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new
FileOutputStream(root+entry.getName());
dest = new
BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER))
!= -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
}
zipfile.close();
}
/**
* Lädt die Datei aus der übergebenen URL herunter.
* @param link
* @throws MalformedURLException
* @throws IOException
*/
private static void downloadFile(String link) throws MalformedURLException, IOException
{
URL url = new URL(link);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
long max = conn.getContentLength();
infoText = "download " + max + " Bytes";
Mlog.debug("Download Datei ...Update Größe(komprimiert): " + max + " Bytes");
BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(zipFile)));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1) {
fOut.write(buffer, 0, bytesRead);
}
fOut.flush();
fOut.close();
is.close();
Mlog.debug("Download abgeschlossen");
}
/**
* Anzeige des aktuellen Status im Label
* @param info
*/
private static void showInfoText(String info) {
lblInfo.setText(info);
lblInfo.redraw();
}
/**
* Hauptprogramm des Updaters
* @param args
*/
public static void main(String[] args) {
FontData wertKlFont = new FontData("Arial",(int) (14),SWT.BOLD);
Display display = new Display ();
shell = new Shell(display);
shell.addListener(SWT.Show, new Listener() {
public void handleEvent(Event event) {
Mlog.init();
Mlog.setDebugstatus(logDebug);
download();
}
});
shell.setSize(310, 113);
shell.setBounds(120, 10, 310, 80);
shell.setText("Update");
lblInfo = new Label(shell, SWT.NONE);
lblInfo.setBounds(10, 10, 290, 20);
lblInfo.setFont(new Font(display, wertKlFont));
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
showInfoText(infoText);
display.sleep();
if (updateComplete) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Mlog.ex(e);
}
shell.dispose();
}
}
}
display.dispose();
}
}
| False | 2,142 | 11 | 2,585 | 13 | 2,529 | 12 | 2,586 | 13 | 3,190 | 14 | false | false | false | false | false | true |
644 | 44589_2 | package nl.han.ica.oopd.waterworld;
import nl.han.ica.oopg.collision.ICollidableWithGameObjects;
import nl.han.ica.oopg.objects.GameObject;
import nl.han.ica.oopg.sound.Sound;
import processing.core.PGraphics;
import java.util.List;
/**
* @author Ralph Niels
* Bel-klasse
*/
public class Bubble extends GameObject implements ICollidableWithGameObjects {
private final Sound popSound;
private WaterWorld world;
private int bubbleSize;
/**
* Constructor
*
* @param bubbleSize Afmeting van de bel
* @param world Referentie naar de wereld
* @param popSound Geluid dat moet klinken als de bel knapt
*/
public Bubble(int bubbleSize, WaterWorld world, Sound popSound) {
this.bubbleSize = bubbleSize;
this.popSound = popSound;
this.world = world;
setySpeed(-bubbleSize / 10f);
/* De volgende regels zijn in een zelfgekend object nodig
om collisiondetectie mogelijk te maken.
*/
setHeight(bubbleSize);
setWidth(bubbleSize);
}
@Override
public void update() {
if (getY() <= 100) {
world.deleteGameObject(this);
}
}
@Override
public void draw(PGraphics g) {
g.ellipseMode(g.CORNER); // Omdat cirkel anders vanuit midden wordt getekend en dat problemen geeft bij collisiondetectie
g.stroke(0, 50, 200, 100);
g.fill(0, 50, 200, 50);
g.ellipse(getX(), getY(), bubbleSize, bubbleSize);
}
@Override
public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) {
for (GameObject g : collidedGameObjects) {
if (g instanceof Swordfish) {
popSound.rewind();
popSound.play();
world.deleteGameObject(this);
world.increaseBubblesPopped();
}
}
}
}
| HANICA/waterworld | src/main/java/nl/han/ica/oopd/waterworld/Bubble.java | 586 | /* De volgende regels zijn in een zelfgekend object nodig
om collisiondetectie mogelijk te maken.
*/ | block_comment | nl | package nl.han.ica.oopd.waterworld;
import nl.han.ica.oopg.collision.ICollidableWithGameObjects;
import nl.han.ica.oopg.objects.GameObject;
import nl.han.ica.oopg.sound.Sound;
import processing.core.PGraphics;
import java.util.List;
/**
* @author Ralph Niels
* Bel-klasse
*/
public class Bubble extends GameObject implements ICollidableWithGameObjects {
private final Sound popSound;
private WaterWorld world;
private int bubbleSize;
/**
* Constructor
*
* @param bubbleSize Afmeting van de bel
* @param world Referentie naar de wereld
* @param popSound Geluid dat moet klinken als de bel knapt
*/
public Bubble(int bubbleSize, WaterWorld world, Sound popSound) {
this.bubbleSize = bubbleSize;
this.popSound = popSound;
this.world = world;
setySpeed(-bubbleSize / 10f);
/* De volgende regels<SUF>*/
setHeight(bubbleSize);
setWidth(bubbleSize);
}
@Override
public void update() {
if (getY() <= 100) {
world.deleteGameObject(this);
}
}
@Override
public void draw(PGraphics g) {
g.ellipseMode(g.CORNER); // Omdat cirkel anders vanuit midden wordt getekend en dat problemen geeft bij collisiondetectie
g.stroke(0, 50, 200, 100);
g.fill(0, 50, 200, 50);
g.ellipse(getX(), getY(), bubbleSize, bubbleSize);
}
@Override
public void gameObjectCollisionOccurred(List<GameObject> collidedGameObjects) {
for (GameObject g : collidedGameObjects) {
if (g instanceof Swordfish) {
popSound.rewind();
popSound.play();
world.deleteGameObject(this);
world.increaseBubblesPopped();
}
}
}
}
| True | 474 | 28 | 520 | 30 | 527 | 25 | 520 | 30 | 600 | 32 | false | false | false | false | false | true |
1,577 | 55900_5 | package nl.shadowlink.tools.shadowlib.model.model;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import nl.shadowlink.tools.io.Vector4D;
import java.util.ArrayList;
/**
* @author Shadow-Link
*/
public class Strip {
private ArrayList<Polygon> poly = new ArrayList();
private ArrayList<Vertex> vert = new ArrayList();
private int polyCount;
private int materialIndex; // shader index
public Vertex max = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
public Vertex min = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
public Vertex center = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
public Vector4D sphere = new Vector4D(0.0f, 0.0f, 0.0f, 0.0f);
/**
* Creates a new strip with the given amount of polys and materialindex
*
* @param polyCount number of polys
* @param materialIndex index of the material
*/
public Strip(int polyCount, int materialIndex) {
this.polyCount = polyCount;
this.materialIndex = materialIndex;
}
/**
* Adds a poly to this strip
*
* @param polygon to add
*/
public void addPoly(Polygon polygon) {
poly.add(polygon);
}
/**
* Add vertex to this strip and checks if it's not already in the strip
*
* @param vertex to add
* @return index where the vertex has been added
*/
public int addVertex(Vertex vertex) {
int ret = -1;
if (!vert.contains(vertex)) {
ret = vert.size();
vert.add(vertex);
// //Message.displayMsgLow("Added vertex at " + ret);
} else {
ret = vert.indexOf(vertex);
// //Message.displayMsgLow("Vertex bestond al in deze strip " + ret);
}
return ret;
}
/**
* Adds vertex to the strip without checking if it already exists
*
* @param vertex the vertex to add
*/
public void addVertexToStrip(Vertex vertex) {
vert.add(vertex);
checkBounds(vertex);
}
public Polygon getPoly(int id) {
return poly.get(id);
}
public int getPolyCount() {
return poly.size();
}
public int getShaderNumber() {
return materialIndex;
}
public int getVertexCount() {
return vert.size();
}
public Vertex getVertex(int i) {
return vert.get(i);
}
/**
* Render this strip
*
* @param gl used to render this strip
*/
public void render(GL2 gl) {
gl.glBegin(GL.GL_TRIANGLES); //begin triangle object
for (int i = 0; i < poly.size(); i++) { //zolang we polygons hebben
Polygon pol = poly.get(i);
Vertex verta = vert.get(pol.a);
Vertex vertb = vert.get(pol.b);
Vertex vertc = vert.get(pol.c);
gl.glTexCoord2f(verta.u, verta.v);
gl.glVertex3f(verta.x, verta.y, verta.z); //eerste vertex van polygon
gl.glTexCoord2f(vertb.u, vertb.v);
gl.glVertex3f(vertb.x, vertb.y, vertb.z); // tweede vertex van polygon
gl.glTexCoord2f(vertc.u, vertc.v);
gl.glVertex3f(vertc.x, vertc.y, vertc.z); // derde vertex van polygon
}
gl.glEnd();
}
/**
* Check if the vertex is out of the current bounds if so it will set the bounds of this element to the current
* vertex
*
* @param vertex Vertex to check this with
*/
public void checkBounds(Vertex vertex) {
if (vertex.getVertexX() > max.getVertexX())
max.setVertexX(vertex.getVertexX());
if (vertex.getVertexY() > max.getVertexY())
max.setVertexY(vertex.getVertexY());
if (vertex.getVertexZ() > max.getVertexZ())
max.setVertexZ(vertex.getVertexZ());
if (vertex.getVertexX() < min.getVertexX())
min.setVertexX(vertex.getVertexX());
if (vertex.getVertexY() < min.getVertexY())
min.setVertexY(vertex.getVertexY());
if (vertex.getVertexZ() < min.getVertexZ())
min.setVertexZ(vertex.getVertexZ());
center.setVertexX((max.getVertexX() + min.getVertexX()) / 2);
center.setVertexY((max.getVertexY() + min.getVertexY()) / 2);
center.setVertexZ((max.getVertexZ() + min.getVertexZ()) / 2);
sphere.x = center.x;
sphere.y = center.y;
sphere.z = center.z;
sphere.w = getMax();
}
private float getMax() {
float value = max.x;
if (value < max.y)
value = max.y;
if (value < max.z)
value = max.z;
if (value < 0 - min.x)
value = 0 - min.x;
if (value < 0 - min.y)
value = 0 - min.y;
if (value < 0 - min.z)
value = 0 - min.z;
// System.out.println("Max is: " + value);
return value;
}
}
| ShadwLink/Shadow-Mapper | src/main/java/nl/shadowlink/tools/shadowlib/model/model/Strip.java | 1,590 | // //Message.displayMsgLow("Vertex bestond al in deze strip " + ret); | line_comment | nl | package nl.shadowlink.tools.shadowlib.model.model;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import nl.shadowlink.tools.io.Vector4D;
import java.util.ArrayList;
/**
* @author Shadow-Link
*/
public class Strip {
private ArrayList<Polygon> poly = new ArrayList();
private ArrayList<Vertex> vert = new ArrayList();
private int polyCount;
private int materialIndex; // shader index
public Vertex max = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
public Vertex min = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
public Vertex center = new Vertex(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
public Vector4D sphere = new Vector4D(0.0f, 0.0f, 0.0f, 0.0f);
/**
* Creates a new strip with the given amount of polys and materialindex
*
* @param polyCount number of polys
* @param materialIndex index of the material
*/
public Strip(int polyCount, int materialIndex) {
this.polyCount = polyCount;
this.materialIndex = materialIndex;
}
/**
* Adds a poly to this strip
*
* @param polygon to add
*/
public void addPoly(Polygon polygon) {
poly.add(polygon);
}
/**
* Add vertex to this strip and checks if it's not already in the strip
*
* @param vertex to add
* @return index where the vertex has been added
*/
public int addVertex(Vertex vertex) {
int ret = -1;
if (!vert.contains(vertex)) {
ret = vert.size();
vert.add(vertex);
// //Message.displayMsgLow("Added vertex at " + ret);
} else {
ret = vert.indexOf(vertex);
// //Message.displayMsgLow("Vertex bestond<SUF>
}
return ret;
}
/**
* Adds vertex to the strip without checking if it already exists
*
* @param vertex the vertex to add
*/
public void addVertexToStrip(Vertex vertex) {
vert.add(vertex);
checkBounds(vertex);
}
public Polygon getPoly(int id) {
return poly.get(id);
}
public int getPolyCount() {
return poly.size();
}
public int getShaderNumber() {
return materialIndex;
}
public int getVertexCount() {
return vert.size();
}
public Vertex getVertex(int i) {
return vert.get(i);
}
/**
* Render this strip
*
* @param gl used to render this strip
*/
public void render(GL2 gl) {
gl.glBegin(GL.GL_TRIANGLES); //begin triangle object
for (int i = 0; i < poly.size(); i++) { //zolang we polygons hebben
Polygon pol = poly.get(i);
Vertex verta = vert.get(pol.a);
Vertex vertb = vert.get(pol.b);
Vertex vertc = vert.get(pol.c);
gl.glTexCoord2f(verta.u, verta.v);
gl.glVertex3f(verta.x, verta.y, verta.z); //eerste vertex van polygon
gl.glTexCoord2f(vertb.u, vertb.v);
gl.glVertex3f(vertb.x, vertb.y, vertb.z); // tweede vertex van polygon
gl.glTexCoord2f(vertc.u, vertc.v);
gl.glVertex3f(vertc.x, vertc.y, vertc.z); // derde vertex van polygon
}
gl.glEnd();
}
/**
* Check if the vertex is out of the current bounds if so it will set the bounds of this element to the current
* vertex
*
* @param vertex Vertex to check this with
*/
public void checkBounds(Vertex vertex) {
if (vertex.getVertexX() > max.getVertexX())
max.setVertexX(vertex.getVertexX());
if (vertex.getVertexY() > max.getVertexY())
max.setVertexY(vertex.getVertexY());
if (vertex.getVertexZ() > max.getVertexZ())
max.setVertexZ(vertex.getVertexZ());
if (vertex.getVertexX() < min.getVertexX())
min.setVertexX(vertex.getVertexX());
if (vertex.getVertexY() < min.getVertexY())
min.setVertexY(vertex.getVertexY());
if (vertex.getVertexZ() < min.getVertexZ())
min.setVertexZ(vertex.getVertexZ());
center.setVertexX((max.getVertexX() + min.getVertexX()) / 2);
center.setVertexY((max.getVertexY() + min.getVertexY()) / 2);
center.setVertexZ((max.getVertexZ() + min.getVertexZ()) / 2);
sphere.x = center.x;
sphere.y = center.y;
sphere.z = center.z;
sphere.w = getMax();
}
private float getMax() {
float value = max.x;
if (value < max.y)
value = max.y;
if (value < max.z)
value = max.z;
if (value < 0 - min.x)
value = 0 - min.x;
if (value < 0 - min.y)
value = 0 - min.y;
if (value < 0 - min.z)
value = 0 - min.z;
// System.out.println("Max is: " + value);
return value;
}
}
| False | 1,269 | 18 | 1,409 | 19 | 1,521 | 19 | 1,409 | 19 | 1,622 | 20 | false | false | false | false | false | true |
1,020 | 209269_11 | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} | MRoeland/KoalaExpress | app/src/main/java/be/ehb/koalaexpress/CheckoutActivity.java | 1,762 | // 3 seconden wachten vooraleer naar fragment te springen om tijd te geven order op te slaan | line_comment | nl | package be.ehb.koalaexpress;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import be.ehb.koalaexpress.Tasks.Task_SendOrderToDB;
import be.ehb.koalaexpress.models.WinkelMandje;
import cz.msebera.android.httpclient.Header;
public class CheckoutActivity extends AppCompatActivity {
TextView orderID_label;
TextView payerID_label;
TextView paymentAmount_label;
Button confirm_btn;
Button annuleren_btn;
ProgressBar progressbar;
public String orderID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hiding ActionBar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
setContentView(R.layout.activity_checkout);
//get the orderID from the query parameter
Uri redirectUri = getIntent().getData();
List<String> segmentsInUrl = redirectUri.getPathSegments();
//hier kan je succes of failure halen uit de segmenstInURL
orderID = redirectUri.getQueryParameter("token");
String payerID = redirectUri.getQueryParameter("PayerID");
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.INVISIBLE);
//set the orderID string to the UI
orderID_label = (TextView) findViewById(R.id.orderID);
orderID_label.setText("Checkout ID: " +orderID);
payerID_label = (TextView) findViewById(R.id.payerid);
payerID_label.setText("Je Betaler Id is: " +payerID);
paymentAmount_label = (TextView) findViewById(R.id.amt);
paymentAmount_label.setText(String.format("Te betalen: € %.02f", KoalaDataRepository.getInstance().mWinkelMandje.getValue().mTotalPrice));
//add an onClick listener to the confirm button
confirm_btn = findViewById(R.id.confirm_btn);
confirm_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
captureOrder(orderID); //function to finalize the payment
}
});
annuleren_btn= findViewById(R.id.annuleren_btn);
annuleren_btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
returnToOrderZonderConfirm();
}
});
}
void captureOrder(String orderID){
//get the accessToken from MainActivity
progressbar.setVisibility(View.VISIBLE);
String accessToken = KoalaDataRepository.getInstance().PaypalAccessToken;
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Accept", "application/json");
client.addHeader("Content-type", "application/json");
client.addHeader("Authorization", "Bearer " + accessToken);
client.post("https://api-m.sandbox.paypal.com/v2/checkout/orders/"+orderID+"/capture", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable throwable) {
Log.i("RESPONSE", response);
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
// eerst het resultaat van call verwerken om paymentid op te halen
String paymentId = "";
try {
JSONObject jsonResponse = new JSONObject(response);
String orderId = jsonResponse.getString("id"); // This is the order ID
JSONArray purchaseUnits = jsonResponse.getJSONArray("purchase_units");
if (purchaseUnits.length() > 0) {
JSONObject purchaseUnit = purchaseUnits.getJSONObject(0);
JSONArray payments = purchaseUnit.getJSONObject("payments").getJSONArray("captures");
if (payments.length() > 0) {
JSONObject payment = payments.getJSONObject(0);
paymentId = payment.getString("id"); // dit is de payment id
}
}
} catch (JSONException e) {
e.printStackTrace();
}
KoalaDataRepository repo = KoalaDataRepository.getInstance();
WinkelMandje mandje = repo.mWinkelMandje.getValue();
mandje.mPayPalPaymentId = paymentId;
Date currentDate = new Date();
mandje.mPayedOnDate = new Timestamp(currentDate.getTime());
repo.mWinkelMandje.setValue(mandje);
// order opslaan in db
Task_SendOrderToDB taak = new Task_SendOrderToDB();
taak.execute(mandje);
// 3 seconden<SUF>
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//redirect back to home page of app
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeSucces");
intent.putExtra("AfgeslotenOrderId",orderID);
intent.putExtra("AfgeslotenPaymentId",mandje.mPayPalPaymentId);
progressbar.setVisibility(View.INVISIBLE);
startActivity(intent);
}
}, 3000); // 3000ms delay
}
});
}
public void returnToOrderZonderConfirm() {
Intent intent = new Intent(CheckoutActivity.this, MainActivity.class);
intent.putExtra("JumpToFragment","WinkelMandjeAnnuleren");
startActivity(intent);
}
} | True | 1,227 | 25 | 1,446 | 29 | 1,477 | 23 | 1,446 | 29 | 1,708 | 26 | false | false | false | false | false | true |
4,675 | 20602_2 | import java.util.*;
import java.util.stream.*;
import java.lang.Math;
import java.lang.Exception;
public class PrefixTreeApp {
// returns up to n candidates start with given prefix
public static <T> List<Map.Entry<String, T>> lookup(PrefixTree.Node<T> t,
String key, int n) {
if (t == null)
return Collections.emptyList();
String prefix = "";
boolean match;
do {
match = false;
for (Map.Entry<String, PrefixTree.Node<T>> entry : t.subTrees.entrySet()) {
String k = entry.getKey();
PrefixTree.Node<T> tr = entry.getValue();
if (k.startsWith(key)) { // key is prefix of k
return expand(prefix + k, tr, n);
}
if (key.startsWith(k)) {
match = true;
key = key.substring(k.length());
t = tr;
prefix = prefix + k;
break;
}
}
} while (match);
return Collections.emptyList();
}
static <T> List<Map.Entry<String, T>> expand(String prefix, PrefixTree.Node<T> t, int n) {
List<Map.Entry<String, T>> res = new ArrayList<>();
Queue<Map.Entry<String, PrefixTree.Node<T> >> q = new LinkedList<>();
q.offer(entryOf(prefix, t));
while(res.size() < n && !q.isEmpty()) {
Map.Entry<String, PrefixTree.Node<T>> entry = q.poll();
String s = entry.getKey();
PrefixTree.Node<T> tr = entry.getValue();
if (tr.value.isPresent()) {
res.add(entryOf(s, tr.value.get()));
}
for (Map.Entry<String, PrefixTree.Node<T>> e :
new TreeMap<>(tr.subTrees).entrySet()) {
q.offer(entryOf(s + e.getKey(), e.getValue()));
}
}
return res;
}
static <K, V> Map.Entry<K, V> entryOf(K key, V val) {
return new AbstractMap.SimpleImmutableEntry<K, V>(key, val);
}
// T9 map
static final Map<Character, String> MAP_T9 = new HashMap<Character, String>(){{
put('1', ",."); put('2', "abc"); put('3', "def");
put('4', "ghi"); put('5', "jkl"); put('6', "mno");
put('7', "pqrs"); put('8', "tuv"); put('9', "wxyz");
}};
// T9 reverse map
static final Map<Character, Character> RMAP_T9 = new HashMap<Character, Character>(){{
for (Character d : MAP_T9.keySet()) {
String cs = MAP_T9.get(d);
for (int i = 0; i < cs.length(); ++i)
put(cs.charAt(i), d);
}
}};
/*
* The T9 reverse map can be built with stream, but it's hard to read
*
* static final Map<Character, Character> RMAP_T9 = MAP_T9.entrySet().stream()
* .flatMap(e -> e.getValue().chars().mapToObj(i -> (char)i)
* .map(c -> entryOf(c, e.getKey())))
* .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
*/
public static String digits(String w) {
StringBuilder d = new StringBuilder();
for(int i = 0; i < w.length(); ++i)
d.append(RMAP_T9.get(w.charAt(i)));
return d.toString();
}
static class Tuple<T> {
String prefix;
String key;
PrefixTree.Node<T> tree;
Tuple(String p, String k, PrefixTree.Node<T> t) {
prefix = p; key = k; tree = t;
}
public static <T> Tuple<T> of(String prefix, String key,
PrefixTree.Node<T> tree) {
return new Tuple<T>(prefix, key, tree);
}
}
static String limit(int n, String s) {
return s.substring(0, Math.min(n, s.length()));
}
public static <T> List<String> lookupT9(PrefixTree.Node<T> t, String key) {
List<String> res = new ArrayList<>();
if (t == null || key.isEmpty())
return res;
Queue<Tuple<T>> q = new LinkedList<>();
q.offer(Tuple.of("", key, t));
while (!q.isEmpty()) {
Tuple<T> elem = q.poll();
for (Map.Entry<String, PrefixTree.Node<T>> e :
elem.tree.subTrees.entrySet()) {
String k = e.getKey();
String ds = digits(k);
if (ds.startsWith(elem.key)) {
res.add(limit(key.length(), elem.prefix + k));
} else if (elem.key.startsWith(ds)) {
q.offer(Tuple.of(elem.prefix + k,
elem.key.substring(k.length()),
e.getValue()));
}
}
}
return res;
}
public static class Test {
final static String[] testKeys =
new String[]{"a", "an", "another", "abandon", "about", "adam", "boy", "body", "zoo"};
final static String[] testVals =
new String[]{"the first letter of English",
"used instead of 'a' when the following word begins witha vowel sound",
"one more person or thing or an extra amount",
"to leave a place, thing or person forever",
"on the subject of; connected with",
"a character in the Bible who was the first man made by God",
"a male child or, more generally, a male of any age",
"the whole physical structure that forms a person or animal",
"an area in which animals, especially wild animals, are kept so that people can go and look at them, or study them"};
static void testEdict() {
PrefixTree.Node<String> t = null;
Map<String, String> m = new HashMap<>();
int n = Math.min(testKeys.length, testVals.length);
for (int i = 0; i < n; ++i) {
t = PrefixTree.insert(t, testKeys[i], testVals[i]);
m.put(testKeys[i], testVals[i]);
}
verifyLookup(m, t, "a", 5);
verifyLookup(m, t, "a", 6);
verifyLookup(m, t, "a", 7);
verifyLookup(m, t, "ab", 2);
verifyLookup(m, t, "ab", 5);
verifyLookup(m, t, "b", 2);
verifyLookup(m, t, "bo", 5);
verifyLookup(m, t, "z", 3);
}
static void verifyLookup(Map<String, String> m, PrefixTree.Node<String> t, String key, int n) {
System.out.format("lookup %s with limit: %d\n", key, n);
SortedMap<String, String> m1 = new TreeMap<>();
for (Map.Entry<String, String> e : lookup(t, key, n)) {
m1.put(e.getKey(), e.getValue());
}
SortedMap<String, String> m2 =
take(n, toSortedMap(m.entrySet().stream()
.filter(e -> e.getKey().startsWith(key))));
if (!m2.equals(m1))
throw new RuntimeException("\n" + m1.toString() + "\n!=\n" + m2.toString());
System.out.println("result:\n" + m1.toString());
}
static <T> SortedMap<String, T> take(int n, SortedMap<String, T> m) {
return toSortedMap(m.entrySet().stream().limit(n));
}
static <K, V> SortedMap<K, V> toSortedMap(Stream<Map.Entry<K, V>> s) {
return new TreeMap<>(s.collect(Collectors.toMap(e -> e.getKey(), e ->e.getValue())));
}
public static void testT9() {
//System.out.println("T9 map: " + MAP_T9);
//System.out.println("reverse T9 map: " + RMAP_T9);
final String txt = "home good gone hood a another an";
final String[] words = txt.split("\\W+");
PrefixTree.Node<Integer> t = PrefixTree.fromString(txt);
for (String testDigits : new String[]{"4663", "22", "2668437"}) {
for (int i = 1; i <= testDigits.length(); ++i) {
String ds = limit(i, testDigits);
SortedSet<String> as = new TreeSet<>(lookupT9(t, ds));
SortedSet<String> bs = new TreeSet<>();
for (String w : words) {
String candidate = limit(i, w);
if (digits(candidate).equals(ds))
bs.add(candidate);
}
//System.out.println("T9 look up: " + as);
//System.out.println("Brute force:" + bs);
if (!as.equals(bs))
throw new RuntimeException("T9 look up " + as + "\n!=\n" +
"Brute force" + bs + "\n");
}
}
System.out.println("T9 verified");
}
public static void test() {
testEdict();
testT9();
}
}
}
| warmchang/AlgoXY-algorithms | datastruct/tree/trie/src/PrefixTreeApp.java | 2,711 | // T9 reverse map | line_comment | nl | import java.util.*;
import java.util.stream.*;
import java.lang.Math;
import java.lang.Exception;
public class PrefixTreeApp {
// returns up to n candidates start with given prefix
public static <T> List<Map.Entry<String, T>> lookup(PrefixTree.Node<T> t,
String key, int n) {
if (t == null)
return Collections.emptyList();
String prefix = "";
boolean match;
do {
match = false;
for (Map.Entry<String, PrefixTree.Node<T>> entry : t.subTrees.entrySet()) {
String k = entry.getKey();
PrefixTree.Node<T> tr = entry.getValue();
if (k.startsWith(key)) { // key is prefix of k
return expand(prefix + k, tr, n);
}
if (key.startsWith(k)) {
match = true;
key = key.substring(k.length());
t = tr;
prefix = prefix + k;
break;
}
}
} while (match);
return Collections.emptyList();
}
static <T> List<Map.Entry<String, T>> expand(String prefix, PrefixTree.Node<T> t, int n) {
List<Map.Entry<String, T>> res = new ArrayList<>();
Queue<Map.Entry<String, PrefixTree.Node<T> >> q = new LinkedList<>();
q.offer(entryOf(prefix, t));
while(res.size() < n && !q.isEmpty()) {
Map.Entry<String, PrefixTree.Node<T>> entry = q.poll();
String s = entry.getKey();
PrefixTree.Node<T> tr = entry.getValue();
if (tr.value.isPresent()) {
res.add(entryOf(s, tr.value.get()));
}
for (Map.Entry<String, PrefixTree.Node<T>> e :
new TreeMap<>(tr.subTrees).entrySet()) {
q.offer(entryOf(s + e.getKey(), e.getValue()));
}
}
return res;
}
static <K, V> Map.Entry<K, V> entryOf(K key, V val) {
return new AbstractMap.SimpleImmutableEntry<K, V>(key, val);
}
// T9 map
static final Map<Character, String> MAP_T9 = new HashMap<Character, String>(){{
put('1', ",."); put('2', "abc"); put('3', "def");
put('4', "ghi"); put('5', "jkl"); put('6', "mno");
put('7', "pqrs"); put('8', "tuv"); put('9', "wxyz");
}};
// T9 reverse<SUF>
static final Map<Character, Character> RMAP_T9 = new HashMap<Character, Character>(){{
for (Character d : MAP_T9.keySet()) {
String cs = MAP_T9.get(d);
for (int i = 0; i < cs.length(); ++i)
put(cs.charAt(i), d);
}
}};
/*
* The T9 reverse map can be built with stream, but it's hard to read
*
* static final Map<Character, Character> RMAP_T9 = MAP_T9.entrySet().stream()
* .flatMap(e -> e.getValue().chars().mapToObj(i -> (char)i)
* .map(c -> entryOf(c, e.getKey())))
* .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
*/
public static String digits(String w) {
StringBuilder d = new StringBuilder();
for(int i = 0; i < w.length(); ++i)
d.append(RMAP_T9.get(w.charAt(i)));
return d.toString();
}
static class Tuple<T> {
String prefix;
String key;
PrefixTree.Node<T> tree;
Tuple(String p, String k, PrefixTree.Node<T> t) {
prefix = p; key = k; tree = t;
}
public static <T> Tuple<T> of(String prefix, String key,
PrefixTree.Node<T> tree) {
return new Tuple<T>(prefix, key, tree);
}
}
static String limit(int n, String s) {
return s.substring(0, Math.min(n, s.length()));
}
public static <T> List<String> lookupT9(PrefixTree.Node<T> t, String key) {
List<String> res = new ArrayList<>();
if (t == null || key.isEmpty())
return res;
Queue<Tuple<T>> q = new LinkedList<>();
q.offer(Tuple.of("", key, t));
while (!q.isEmpty()) {
Tuple<T> elem = q.poll();
for (Map.Entry<String, PrefixTree.Node<T>> e :
elem.tree.subTrees.entrySet()) {
String k = e.getKey();
String ds = digits(k);
if (ds.startsWith(elem.key)) {
res.add(limit(key.length(), elem.prefix + k));
} else if (elem.key.startsWith(ds)) {
q.offer(Tuple.of(elem.prefix + k,
elem.key.substring(k.length()),
e.getValue()));
}
}
}
return res;
}
public static class Test {
final static String[] testKeys =
new String[]{"a", "an", "another", "abandon", "about", "adam", "boy", "body", "zoo"};
final static String[] testVals =
new String[]{"the first letter of English",
"used instead of 'a' when the following word begins witha vowel sound",
"one more person or thing or an extra amount",
"to leave a place, thing or person forever",
"on the subject of; connected with",
"a character in the Bible who was the first man made by God",
"a male child or, more generally, a male of any age",
"the whole physical structure that forms a person or animal",
"an area in which animals, especially wild animals, are kept so that people can go and look at them, or study them"};
static void testEdict() {
PrefixTree.Node<String> t = null;
Map<String, String> m = new HashMap<>();
int n = Math.min(testKeys.length, testVals.length);
for (int i = 0; i < n; ++i) {
t = PrefixTree.insert(t, testKeys[i], testVals[i]);
m.put(testKeys[i], testVals[i]);
}
verifyLookup(m, t, "a", 5);
verifyLookup(m, t, "a", 6);
verifyLookup(m, t, "a", 7);
verifyLookup(m, t, "ab", 2);
verifyLookup(m, t, "ab", 5);
verifyLookup(m, t, "b", 2);
verifyLookup(m, t, "bo", 5);
verifyLookup(m, t, "z", 3);
}
static void verifyLookup(Map<String, String> m, PrefixTree.Node<String> t, String key, int n) {
System.out.format("lookup %s with limit: %d\n", key, n);
SortedMap<String, String> m1 = new TreeMap<>();
for (Map.Entry<String, String> e : lookup(t, key, n)) {
m1.put(e.getKey(), e.getValue());
}
SortedMap<String, String> m2 =
take(n, toSortedMap(m.entrySet().stream()
.filter(e -> e.getKey().startsWith(key))));
if (!m2.equals(m1))
throw new RuntimeException("\n" + m1.toString() + "\n!=\n" + m2.toString());
System.out.println("result:\n" + m1.toString());
}
static <T> SortedMap<String, T> take(int n, SortedMap<String, T> m) {
return toSortedMap(m.entrySet().stream().limit(n));
}
static <K, V> SortedMap<K, V> toSortedMap(Stream<Map.Entry<K, V>> s) {
return new TreeMap<>(s.collect(Collectors.toMap(e -> e.getKey(), e ->e.getValue())));
}
public static void testT9() {
//System.out.println("T9 map: " + MAP_T9);
//System.out.println("reverse T9 map: " + RMAP_T9);
final String txt = "home good gone hood a another an";
final String[] words = txt.split("\\W+");
PrefixTree.Node<Integer> t = PrefixTree.fromString(txt);
for (String testDigits : new String[]{"4663", "22", "2668437"}) {
for (int i = 1; i <= testDigits.length(); ++i) {
String ds = limit(i, testDigits);
SortedSet<String> as = new TreeSet<>(lookupT9(t, ds));
SortedSet<String> bs = new TreeSet<>();
for (String w : words) {
String candidate = limit(i, w);
if (digits(candidate).equals(ds))
bs.add(candidate);
}
//System.out.println("T9 look up: " + as);
//System.out.println("Brute force:" + bs);
if (!as.equals(bs))
throw new RuntimeException("T9 look up " + as + "\n!=\n" +
"Brute force" + bs + "\n");
}
}
System.out.println("T9 verified");
}
public static void test() {
testEdict();
testT9();
}
}
}
| False | 2,022 | 5 | 2,304 | 5 | 2,494 | 5 | 2,304 | 5 | 2,695 | 5 | false | false | false | false | false | true |
4,291 | 19807_8 | package rekenen;
import rekenen.plugins.Plugin;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* PEER TUTORING
* P2W3
*/
public class Rekenmachine {
private final int MAX_AANTAL_PLUGINS = 10;
private Plugin[] ingeladenPlugins;
private int aantalPlugins;
private StringBuilder log;
private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMMM yyyy hh:mm:ss.SSSS");
public Rekenmachine() {
this.ingeladenPlugins = new Plugin[MAX_AANTAL_PLUGINS];
aantalPlugins = 0;
initLog();
}
public void installeer(Plugin teInstallerenPlugin) {
//Opgave 2.1.a
// Simpele oplossing:
boolean isInstalled = false;
for (int i = 0; i < aantalPlugins; i++) {
if (ingeladenPlugins[i].getCommand().equals(teInstallerenPlugin.getCommand())) {
isInstalled = true;
break;
}
}
if (!isInstalled)
ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin;
// Java 8 Streams oplossing:
/*
Arrays.stream(ingeladenPlugins) -> maakt van de array een Stream
.filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())) -> gooi de elementen die null zijn en waarvan het commando niet hetzelfde is weg
findAny() -> geef mij eender welk element dat de stream overleeft heeft, geencapsuleerd in een Optional (we zijn namelijk niet zeker dat er een is)
.isPresent() -> is er een element dat de filter overleefd heeft?
*/
// if (!Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())).findAny().isPresent() && aantalPlugins < MAX_AANTAL_PLUGINS) {
// ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin;
// }
}
public double bereken(String command, double x, double y) {
//Opgave 2.1.b
// Simpele oplossing:
Plugin plugin = null;
for (int i = 0; i < aantalPlugins; i++) {
if(ingeladenPlugins[i].getCommand().equals(command.trim())){
plugin = ingeladenPlugins[i];
break;
}
}
if(plugin!= null){
double result = plugin.bereken(x,y);
log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.getAuteur()));
return result;
} else {
System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command));
return Double.POSITIVE_INFINITY;
}
// Java 8 Streams:
// Optional<Plugin> plugin = Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(command.trim())).findAny();
// if (plugin.isPresent()) {
// double result = plugin.get().bereken(x, y);
// log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.get().getAuteur()));
// return result;
// } else {
// System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command));
// return Double.POSITIVE_INFINITY;
// }
}
@Override
public String toString() {
//Opgave 2.1c
// Simpele oplossing:
String result = "Geïnstalleerde Plugins:";
for (int i = 0; i < aantalPlugins; i++) {
result += " " + ingeladenPlugins[i].getCommand();
}
return result;
// Java 8 Streams:
/*
.map(p -> " " + p.getCommand()) -> maak van elk object in de stream (dus van elke plugin) een nieuw object. Dit object is " " + het commando van de plugin.
.collect(Collectors.joining("")) -> .collect haalt alle elementen in de stream bij elkaar. Collectors.joining("") plakt al de elementen aan elkaar.
*/
// return "Geïnstalleerde Plugins:" + Arrays.stream(ingeladenPlugins).filter(p -> p != null).map(p -> " " + p.getCommand()).collect(Collectors.joining(""));
}
public String getLog() {
String result = log.toString();
initLog();
return result;
}
private void initLog() {
this.log = new StringBuilder();
this.log.append("==== LOG ====");
}
}
| sgentens/Peer-Tutoring-Sessie7 | Sessie7/src/rekenen/Rekenmachine.java | 1,405 | // double result = plugin.get().bereken(x, y); | line_comment | nl | package rekenen;
import rekenen.plugins.Plugin;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* PEER TUTORING
* P2W3
*/
public class Rekenmachine {
private final int MAX_AANTAL_PLUGINS = 10;
private Plugin[] ingeladenPlugins;
private int aantalPlugins;
private StringBuilder log;
private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMMM yyyy hh:mm:ss.SSSS");
public Rekenmachine() {
this.ingeladenPlugins = new Plugin[MAX_AANTAL_PLUGINS];
aantalPlugins = 0;
initLog();
}
public void installeer(Plugin teInstallerenPlugin) {
//Opgave 2.1.a
// Simpele oplossing:
boolean isInstalled = false;
for (int i = 0; i < aantalPlugins; i++) {
if (ingeladenPlugins[i].getCommand().equals(teInstallerenPlugin.getCommand())) {
isInstalled = true;
break;
}
}
if (!isInstalled)
ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin;
// Java 8 Streams oplossing:
/*
Arrays.stream(ingeladenPlugins) -> maakt van de array een Stream
.filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())) -> gooi de elementen die null zijn en waarvan het commando niet hetzelfde is weg
findAny() -> geef mij eender welk element dat de stream overleeft heeft, geencapsuleerd in een Optional (we zijn namelijk niet zeker dat er een is)
.isPresent() -> is er een element dat de filter overleefd heeft?
*/
// if (!Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(teInstallerenPlugin.getCommand())).findAny().isPresent() && aantalPlugins < MAX_AANTAL_PLUGINS) {
// ingeladenPlugins[aantalPlugins++] = teInstallerenPlugin;
// }
}
public double bereken(String command, double x, double y) {
//Opgave 2.1.b
// Simpele oplossing:
Plugin plugin = null;
for (int i = 0; i < aantalPlugins; i++) {
if(ingeladenPlugins[i].getCommand().equals(command.trim())){
plugin = ingeladenPlugins[i];
break;
}
}
if(plugin!= null){
double result = plugin.bereken(x,y);
log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.getAuteur()));
return result;
} else {
System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command));
return Double.POSITIVE_INFINITY;
}
// Java 8 Streams:
// Optional<Plugin> plugin = Arrays.stream(ingeladenPlugins).filter(p -> p != null && p.getCommand().equals(command.trim())).findAny();
// if (plugin.isPresent()) {
// double result<SUF>
// log.append(String.format("\n[%s] %.2f %s %.2f = %.2f (by %s)", dateTimeFormatter.format(LocalDateTime.now()), x, command, y, result, plugin.get().getAuteur()));
// return result;
// } else {
// System.out.println(String.format("Plugin %s is niet geïnstalleerd.", command));
// return Double.POSITIVE_INFINITY;
// }
}
@Override
public String toString() {
//Opgave 2.1c
// Simpele oplossing:
String result = "Geïnstalleerde Plugins:";
for (int i = 0; i < aantalPlugins; i++) {
result += " " + ingeladenPlugins[i].getCommand();
}
return result;
// Java 8 Streams:
/*
.map(p -> " " + p.getCommand()) -> maak van elk object in de stream (dus van elke plugin) een nieuw object. Dit object is " " + het commando van de plugin.
.collect(Collectors.joining("")) -> .collect haalt alle elementen in de stream bij elkaar. Collectors.joining("") plakt al de elementen aan elkaar.
*/
// return "Geïnstalleerde Plugins:" + Arrays.stream(ingeladenPlugins).filter(p -> p != null).map(p -> " " + p.getCommand()).collect(Collectors.joining(""));
}
public String getLog() {
String result = log.toString();
initLog();
return result;
}
private void initLog() {
this.log = new StringBuilder();
this.log.append("==== LOG ====");
}
}
| True | 1,089 | 14 | 1,231 | 16 | 1,232 | 16 | 1,231 | 16 | 1,388 | 16 | false | false | false | false | false | true |
1,448 | 172434_16 | package com.jess.arms.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.jess.arms.base.BaseApplication;
import org.simple.eventbus.EventBus;
import java.security.MessageDigest;
import static com.jess.arms.base.AppManager.APPMANAGER_MESSAGE;
import static com.jess.arms.base.AppManager.APP_EXIT;
import static com.jess.arms.base.AppManager.KILL_ALL;
import static com.jess.arms.base.AppManager.SHOW_SNACKBAR;
import static com.jess.arms.base.AppManager.START_ACTIVITY;
/**
* Created by jess on 2015/11/23.
*/
public class UiUtils {
static public Toast mToast;
/**
* 设置hint大小
*
* @param size
* @param v
* @param res
*/
public static void setViewHintSize(int size, TextView v, int res) {
SpannableString ss = new SpannableString(getResources().getString(
res));
// 新建一个属性对象,设置文字的大小
AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);
// 附加属性到文本
ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// 设置hint
v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
}
/**
* dip转pix
*
* @param dpValue
* @return
*/
public static int dip2px(float dpValue) {
final float scale = BaseApplication.getContext().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 获得资源
*/
public static Resources getResources() {
return BaseApplication.getContext().getResources();
}
/**
* 得到字符数组
*/
public static String[] getStringArray(int id) {
return getResources().getStringArray(id);
}
/**
* pix转dip
*/
public static int pix2dip(int pix) {
final float densityDpi = getResources().getDisplayMetrics().density;
return (int) (pix / densityDpi + 0.5f);
}
/**
* 获得上下文
*
* @return
*/
public static Context getContext() {
return BaseApplication.getContext();
}
/**
* 从dimens中获得尺寸
*
* @param homePicHeight
* @return
*/
public static int getDimens(int homePicHeight) {
return (int) getResources().getDimension(homePicHeight);
}
/**
* 从dimens中获得尺寸
*
* @param
* @return
*/
public static float getDimens(String dimenNmae) {
return getResources().getDimension(getResources().getIdentifier(dimenNmae, "dimen", getContext().getPackageName()));
}
/**
* 从String 中获得字符
*
* @return
*/
public static String getString(int stringID) {
return getResources().getString(stringID);
}
/**
* 从String 中获得字符
*
* @return
*/
public static String getString(String strName) {
return getString(getResources().getIdentifier(strName, "string", getContext().getPackageName()));
}
/**
* findview
*
* @param view
* @param viewName
* @param <T>
* @return
*/
public static <T extends View> T findViewByName(View view, String viewName) {
int id = getResources().getIdentifier(viewName, "id", getContext().getPackageName());
T v = (T) view.findViewById(id);
return v;
}
/**
* findview
*
* @param activity
* @param viewName
* @param <T>
* @return
*/
public static <T extends View> T findViewByName(Activity activity, String viewName) {
int id = getResources().getIdentifier(viewName, "id", getContext().getPackageName());
T v = (T) activity.findViewById(id);
return v;
}
/**
* 根据lauout名字获得id
*
* @param layoutName
* @return
*/
public static int findLayout(String layoutName) {
int id = getResources().getIdentifier(layoutName, "layout", getContext().getPackageName());
return id;
}
/**
* 填充view
*
* @param detailScreen
* @return
*/
public static View inflate(int detailScreen) {
return View.inflate(getContext(), detailScreen, null);
}
/**
* 单列toast
*
* @param string
*/
public static void makeText(String string) {
if (mToast == null) {
mToast = Toast.makeText(getContext(), string, Toast.LENGTH_SHORT);
}
mToast.setText(string);
mToast.show();
}
/**
* 用snackbar显示
*
* @param text
*/
public static void SnackbarText(String text) {
Message message = new Message();
message.what = SHOW_SNACKBAR;
message.obj = text;
message.arg1 = 0;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
/**
* 用snackbar长时间显示
*
* @param text
*/
public static void SnackbarTextWithLong(String text) {
Message message = new Message();
message.what = SHOW_SNACKBAR;
message.obj = text;
message.arg1 = 1;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
/**
* 通过资源id获得drawable
*
* @param rID
* @return
*/
public static Drawable getDrawablebyResource(int rID) {
return getResources().getDrawable(rID);
}
/**
* 跳转界面
*
* @param activity
* @param homeActivityClass
*/
public static void startActivity(Activity activity, Class homeActivityClass) {
Intent intent = new Intent(getContext(), homeActivityClass);
activity.startActivity(intent);
}
/**
* 跳转界面3
*
* @param
* @param homeActivityClass
*/
public static void startActivity(Class homeActivityClass) {
Message message = new Message();
message.what = START_ACTIVITY;
message.obj = homeActivityClass;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
/**
* 跳转界面3
*
* @param
*/
public static void startActivity(Intent content) {
Message message = new Message();
message.what = START_ACTIVITY;
message.obj = content;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
/**
* 跳转界面4
*
* @param
*/
public static void startActivity(Activity activity, Intent intent) {
activity.startActivity(intent);
}
public static int getLayoutId(String layoutName) {
return getResources().getIdentifier(layoutName, "layout", getContext().getPackageName());
}
/**
* 获得屏幕的宽度
*
* @return
*/
public static int getScreenWidth() {
return getResources().getDisplayMetrics().widthPixels;
}
/**
* 获得屏幕的高度
*
* @return
*/
public static int getScreenHeidth() {
return getResources().getDisplayMetrics().heightPixels;
}
/**
* 获得颜色
*/
public static int getColor(int rid) {
return getResources().getColor(rid);
}
/**
* 获得颜色
*/
public static int getColor(String colorName) {
return getColor(getResources().getIdentifier(colorName, "color", getContext().getPackageName()));
}
/**
* 移除孩子
*
* @param view
*/
public static void removeChild(View view) {
ViewParent parent = view.getParent();
if (parent instanceof ViewGroup) {
ViewGroup group = (ViewGroup) parent;
group.removeView(view);
}
}
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
return false;
}
/**
* MD5
*
* @param string
* @return
* @throws Exception
*/
public static String MD5encode(String string) {
byte[] hash = new byte[0];
try {
hash = MessageDigest.getInstance("MD5").digest(
string.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) {
hex.append("0");
}
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
/**
* 全屏,并且沉侵式状态栏
*
* @param activity
*/
public static void statuInScreen(Activity activity) {
WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
activity.getWindow().setAttributes(attrs);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
/**
* 配置recycleview
*
* @param recyclerView
* @param layoutManager
*/
public static void configRecycleView(final RecyclerView recyclerView
, RecyclerView.LayoutManager layoutManager) {
recyclerView.setLayoutManager(layoutManager);
//如果可以确定每个item的高度是固定的,设置这个选项可以提高性能
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
public static void killAll(){
Message message = new Message();
message.what = KILL_ALL;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
public static void exitApp(){
Message message = new Message();
message.what = APP_EXIT;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
}
| ReepicheepRed/PhotoMark-official | arms/src/main/java/com/jess/arms/utils/UiUtils.java | 3,086 | /**
* 填充view
*
* @param detailScreen
* @return
*/ | block_comment | nl | package com.jess.arms.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.jess.arms.base.BaseApplication;
import org.simple.eventbus.EventBus;
import java.security.MessageDigest;
import static com.jess.arms.base.AppManager.APPMANAGER_MESSAGE;
import static com.jess.arms.base.AppManager.APP_EXIT;
import static com.jess.arms.base.AppManager.KILL_ALL;
import static com.jess.arms.base.AppManager.SHOW_SNACKBAR;
import static com.jess.arms.base.AppManager.START_ACTIVITY;
/**
* Created by jess on 2015/11/23.
*/
public class UiUtils {
static public Toast mToast;
/**
* 设置hint大小
*
* @param size
* @param v
* @param res
*/
public static void setViewHintSize(int size, TextView v, int res) {
SpannableString ss = new SpannableString(getResources().getString(
res));
// 新建一个属性对象,设置文字的大小
AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true);
// 附加属性到文本
ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// 设置hint
v.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
}
/**
* dip转pix
*
* @param dpValue
* @return
*/
public static int dip2px(float dpValue) {
final float scale = BaseApplication.getContext().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 获得资源
*/
public static Resources getResources() {
return BaseApplication.getContext().getResources();
}
/**
* 得到字符数组
*/
public static String[] getStringArray(int id) {
return getResources().getStringArray(id);
}
/**
* pix转dip
*/
public static int pix2dip(int pix) {
final float densityDpi = getResources().getDisplayMetrics().density;
return (int) (pix / densityDpi + 0.5f);
}
/**
* 获得上下文
*
* @return
*/
public static Context getContext() {
return BaseApplication.getContext();
}
/**
* 从dimens中获得尺寸
*
* @param homePicHeight
* @return
*/
public static int getDimens(int homePicHeight) {
return (int) getResources().getDimension(homePicHeight);
}
/**
* 从dimens中获得尺寸
*
* @param
* @return
*/
public static float getDimens(String dimenNmae) {
return getResources().getDimension(getResources().getIdentifier(dimenNmae, "dimen", getContext().getPackageName()));
}
/**
* 从String 中获得字符
*
* @return
*/
public static String getString(int stringID) {
return getResources().getString(stringID);
}
/**
* 从String 中获得字符
*
* @return
*/
public static String getString(String strName) {
return getString(getResources().getIdentifier(strName, "string", getContext().getPackageName()));
}
/**
* findview
*
* @param view
* @param viewName
* @param <T>
* @return
*/
public static <T extends View> T findViewByName(View view, String viewName) {
int id = getResources().getIdentifier(viewName, "id", getContext().getPackageName());
T v = (T) view.findViewById(id);
return v;
}
/**
* findview
*
* @param activity
* @param viewName
* @param <T>
* @return
*/
public static <T extends View> T findViewByName(Activity activity, String viewName) {
int id = getResources().getIdentifier(viewName, "id", getContext().getPackageName());
T v = (T) activity.findViewById(id);
return v;
}
/**
* 根据lauout名字获得id
*
* @param layoutName
* @return
*/
public static int findLayout(String layoutName) {
int id = getResources().getIdentifier(layoutName, "layout", getContext().getPackageName());
return id;
}
/**
* 填充view
<SUF>*/
public static View inflate(int detailScreen) {
return View.inflate(getContext(), detailScreen, null);
}
/**
* 单列toast
*
* @param string
*/
public static void makeText(String string) {
if (mToast == null) {
mToast = Toast.makeText(getContext(), string, Toast.LENGTH_SHORT);
}
mToast.setText(string);
mToast.show();
}
/**
* 用snackbar显示
*
* @param text
*/
public static void SnackbarText(String text) {
Message message = new Message();
message.what = SHOW_SNACKBAR;
message.obj = text;
message.arg1 = 0;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
/**
* 用snackbar长时间显示
*
* @param text
*/
public static void SnackbarTextWithLong(String text) {
Message message = new Message();
message.what = SHOW_SNACKBAR;
message.obj = text;
message.arg1 = 1;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
/**
* 通过资源id获得drawable
*
* @param rID
* @return
*/
public static Drawable getDrawablebyResource(int rID) {
return getResources().getDrawable(rID);
}
/**
* 跳转界面
*
* @param activity
* @param homeActivityClass
*/
public static void startActivity(Activity activity, Class homeActivityClass) {
Intent intent = new Intent(getContext(), homeActivityClass);
activity.startActivity(intent);
}
/**
* 跳转界面3
*
* @param
* @param homeActivityClass
*/
public static void startActivity(Class homeActivityClass) {
Message message = new Message();
message.what = START_ACTIVITY;
message.obj = homeActivityClass;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
/**
* 跳转界面3
*
* @param
*/
public static void startActivity(Intent content) {
Message message = new Message();
message.what = START_ACTIVITY;
message.obj = content;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
/**
* 跳转界面4
*
* @param
*/
public static void startActivity(Activity activity, Intent intent) {
activity.startActivity(intent);
}
public static int getLayoutId(String layoutName) {
return getResources().getIdentifier(layoutName, "layout", getContext().getPackageName());
}
/**
* 获得屏幕的宽度
*
* @return
*/
public static int getScreenWidth() {
return getResources().getDisplayMetrics().widthPixels;
}
/**
* 获得屏幕的高度
*
* @return
*/
public static int getScreenHeidth() {
return getResources().getDisplayMetrics().heightPixels;
}
/**
* 获得颜色
*/
public static int getColor(int rid) {
return getResources().getColor(rid);
}
/**
* 获得颜色
*/
public static int getColor(String colorName) {
return getColor(getResources().getIdentifier(colorName, "color", getContext().getPackageName()));
}
/**
* 移除孩子
*
* @param view
*/
public static void removeChild(View view) {
ViewParent parent = view.getParent();
if (parent instanceof ViewGroup) {
ViewGroup group = (ViewGroup) parent;
group.removeView(view);
}
}
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
return false;
}
/**
* MD5
*
* @param string
* @return
* @throws Exception
*/
public static String MD5encode(String string) {
byte[] hash = new byte[0];
try {
hash = MessageDigest.getInstance("MD5").digest(
string.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) {
hex.append("0");
}
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
/**
* 全屏,并且沉侵式状态栏
*
* @param activity
*/
public static void statuInScreen(Activity activity) {
WindowManager.LayoutParams attrs = activity.getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
activity.getWindow().setAttributes(attrs);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
/**
* 配置recycleview
*
* @param recyclerView
* @param layoutManager
*/
public static void configRecycleView(final RecyclerView recyclerView
, RecyclerView.LayoutManager layoutManager) {
recyclerView.setLayoutManager(layoutManager);
//如果可以确定每个item的高度是固定的,设置这个选项可以提高性能
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
public static void killAll(){
Message message = new Message();
message.what = KILL_ALL;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
public static void exitApp(){
Message message = new Message();
message.what = APP_EXIT;
EventBus.getDefault().post(message, APPMANAGER_MESSAGE);
}
}
| False | 2,327 | 25 | 2,523 | 21 | 2,762 | 25 | 2,523 | 21 | 3,240 | 30 | false | false | false | false | false | true |
3,993 | 19056_6 | package bozels.gui.panels;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import bozels.gui.actions.BooleanValueSelectAction;
import bozels.gui.basicComponents.AutoJLabel;
import bozels.gui.basicComponents.ColorButton;
import bozels.gui.basicComponents.coloringTextField.DoubleValueTextField;
import bozels.gui.resourceModel.ResourceTracker;
import bozels.gui.resourceModel.guiColorModel.GUIColorModel;
import bozels.gui.resourceModel.localeConstant.LocaleConstant;
import bozels.physicsModel.material.Material;
import bozels.superModel.SuperModel;
import bozels.valueWrappers.Value;
import bozels.visualisatie.gameColorModel.GameColorModel;
/**
* Bozels
*
* Door:
* Pieter Vander Vennet
* 1ste Bachelor Informatica
* Universiteit Gent
*
*/
public class OneMaterialEditorPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final GUIColorModel colorSettings;
public OneMaterialEditorPanel(final SuperModel supM, final Material mat, boolean showBreakable) {
final ResourceTracker tracker = supM.getResourceModel();
colorSettings = supM.getResourceModel().getGuiColorModel();
// \\//\\//\\//\\ LABELS //\\//\\//\\//\\
JLabel density = new AutoJLabel(tracker, LocaleConstant.DENSITY);
JLabel restit = new AutoJLabel(tracker, LocaleConstant.RESTITUTION);
JLabel friction = new AutoJLabel(tracker, LocaleConstant.FRICTION);
JLabel color = new AutoJLabel(tracker, LocaleConstant.COLOR);
JLabel empty = new JLabel();
JLabel powerThrs = new AutoJLabel(tracker, LocaleConstant.POWER_THRESHOLD);
JLabel strength = new AutoJLabel(tracker, LocaleConstant.STRENGTH);
JLabel sleepingColor = new AutoJLabel(tracker, LocaleConstant.SLEEPING_COLOR);
// \\//\\//\\//\\ COlor chooser //\\//\\//\\//\\
GameColorModel cm = supM.getGameColorModel();
LocaleConstant name = mat.getMaterialName();
int key = mat.getColorKey();
JButton colorPicker = new ColorButton(supM, name, null, cm.getColorValue(key));
JButton sleepingColorPicker = new ColorButton(supM, name, null , cm.getSleepingColorValue(key));
// \\//\\//\\//\\ FIELDS //\\//\\//\\//\\
JTextField dens = createField(mat.getDensitValue());
JTextField rest = createField(mat.getRestitutionValue());
JTextField frict = createField(mat.getFrictionValue());
JTextField powThr = createField(mat.getPowerThresholdValue());
JTextField str = createField(mat.getStrengthValue());
// \\//\\//\\//\\ Checkbox //\\//\\//\\//\\
BooleanValueSelectAction sw = new BooleanValueSelectAction(mat.getCanBreak(),
LocaleConstant.BREAKABLE, tracker);
sw.getSwitchesWith().add(powThr);
sw.getSwitchesWith().add(str);
sw.revalidate();
JCheckBox breakable = new JCheckBox(sw);
// \\//\\//\\//\\ LAYOUT //\\//\\//\\//\\
GroupLayout l = new GroupLayout(this);
this.setLayout(l);
/*
* VERANTWOORDING:
*
* Hier een if-else voor de layout is inderdaad lelijk.
* Ik heb echter gekozen om deze hier te gebruiken,
* omdat op deze manier de layout van het linker- en rechterstuk dezelfde layout kunnen gebruiken.
*
* Op deze manier zullen de layouts altijd mooi samenblijven, hoewel dit minder elegant is naar
* klassenstructuur toe.
*
*/
if(showBreakable){
l.setHorizontalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.TRAILING,
density,restit, friction, color))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
dens, rest, frict, colorPicker))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(createPar(l, Alignment.TRAILING,
empty, powerThrs, strength, sleepingColor))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
breakable, powThr, str, sleepingColorPicker))
);
l.setVerticalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.BASELINE, density, dens, empty, breakable))
.addGroup(createPar(l, Alignment.BASELINE, restit, rest, powerThrs, powThr))
.addGroup(createPar(l, Alignment.BASELINE, friction, frict, strength, str))
.addGroup(createPar(l, Alignment.BASELINE, color, colorPicker, sleepingColor, sleepingColorPicker)
)
.addContainerGap()
);
}else{
l.setHorizontalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.TRAILING,
density,restit, friction, color))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
dens, rest, frict, colorPicker))
);
l.setVerticalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.BASELINE, density, dens))
.addGroup(createPar(l, Alignment.BASELINE, restit, rest))
.addGroup(createPar(l, Alignment.BASELINE, friction, frict))
.addGroup(createPar(l, Alignment.BASELINE, color, colorPicker))
.addContainerGap());
}
}
private ParallelGroup createPar(GroupLayout l, Alignment al, JComponent... components){
ParallelGroup group = l.createParallelGroup(al);
for (JComponent jComponent : components) {
group.addComponent(jComponent);
}
return group;
}
private DoubleValueTextField createField(Value<Double> val){
return new DoubleValueTextField(colorSettings, val, 0, 10000, 10000);
}
}
| pietervdvn/Bozels | src/bozels/gui/panels/OneMaterialEditorPanel.java | 1,960 | /*
* VERANTWOORDING:
*
* Hier een if-else voor de layout is inderdaad lelijk.
* Ik heb echter gekozen om deze hier te gebruiken,
* omdat op deze manier de layout van het linker- en rechterstuk dezelfde layout kunnen gebruiken.
*
* Op deze manier zullen de layouts altijd mooi samenblijven, hoewel dit minder elegant is naar
* klassenstructuur toe.
*
*/ | block_comment | nl | package bozels.gui.panels;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import bozels.gui.actions.BooleanValueSelectAction;
import bozels.gui.basicComponents.AutoJLabel;
import bozels.gui.basicComponents.ColorButton;
import bozels.gui.basicComponents.coloringTextField.DoubleValueTextField;
import bozels.gui.resourceModel.ResourceTracker;
import bozels.gui.resourceModel.guiColorModel.GUIColorModel;
import bozels.gui.resourceModel.localeConstant.LocaleConstant;
import bozels.physicsModel.material.Material;
import bozels.superModel.SuperModel;
import bozels.valueWrappers.Value;
import bozels.visualisatie.gameColorModel.GameColorModel;
/**
* Bozels
*
* Door:
* Pieter Vander Vennet
* 1ste Bachelor Informatica
* Universiteit Gent
*
*/
public class OneMaterialEditorPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final GUIColorModel colorSettings;
public OneMaterialEditorPanel(final SuperModel supM, final Material mat, boolean showBreakable) {
final ResourceTracker tracker = supM.getResourceModel();
colorSettings = supM.getResourceModel().getGuiColorModel();
// \\//\\//\\//\\ LABELS //\\//\\//\\//\\
JLabel density = new AutoJLabel(tracker, LocaleConstant.DENSITY);
JLabel restit = new AutoJLabel(tracker, LocaleConstant.RESTITUTION);
JLabel friction = new AutoJLabel(tracker, LocaleConstant.FRICTION);
JLabel color = new AutoJLabel(tracker, LocaleConstant.COLOR);
JLabel empty = new JLabel();
JLabel powerThrs = new AutoJLabel(tracker, LocaleConstant.POWER_THRESHOLD);
JLabel strength = new AutoJLabel(tracker, LocaleConstant.STRENGTH);
JLabel sleepingColor = new AutoJLabel(tracker, LocaleConstant.SLEEPING_COLOR);
// \\//\\//\\//\\ COlor chooser //\\//\\//\\//\\
GameColorModel cm = supM.getGameColorModel();
LocaleConstant name = mat.getMaterialName();
int key = mat.getColorKey();
JButton colorPicker = new ColorButton(supM, name, null, cm.getColorValue(key));
JButton sleepingColorPicker = new ColorButton(supM, name, null , cm.getSleepingColorValue(key));
// \\//\\//\\//\\ FIELDS //\\//\\//\\//\\
JTextField dens = createField(mat.getDensitValue());
JTextField rest = createField(mat.getRestitutionValue());
JTextField frict = createField(mat.getFrictionValue());
JTextField powThr = createField(mat.getPowerThresholdValue());
JTextField str = createField(mat.getStrengthValue());
// \\//\\//\\//\\ Checkbox //\\//\\//\\//\\
BooleanValueSelectAction sw = new BooleanValueSelectAction(mat.getCanBreak(),
LocaleConstant.BREAKABLE, tracker);
sw.getSwitchesWith().add(powThr);
sw.getSwitchesWith().add(str);
sw.revalidate();
JCheckBox breakable = new JCheckBox(sw);
// \\//\\//\\//\\ LAYOUT //\\//\\//\\//\\
GroupLayout l = new GroupLayout(this);
this.setLayout(l);
/*
* VERANTWOORDING:
<SUF>*/
if(showBreakable){
l.setHorizontalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.TRAILING,
density,restit, friction, color))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
dens, rest, frict, colorPicker))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(createPar(l, Alignment.TRAILING,
empty, powerThrs, strength, sleepingColor))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
breakable, powThr, str, sleepingColorPicker))
);
l.setVerticalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.BASELINE, density, dens, empty, breakable))
.addGroup(createPar(l, Alignment.BASELINE, restit, rest, powerThrs, powThr))
.addGroup(createPar(l, Alignment.BASELINE, friction, frict, strength, str))
.addGroup(createPar(l, Alignment.BASELINE, color, colorPicker, sleepingColor, sleepingColorPicker)
)
.addContainerGap()
);
}else{
l.setHorizontalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.TRAILING,
density,restit, friction, color))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(createPar(l, Alignment.LEADING,
dens, rest, frict, colorPicker))
);
l.setVerticalGroup(l.createSequentialGroup()
.addGroup(createPar(l, Alignment.BASELINE, density, dens))
.addGroup(createPar(l, Alignment.BASELINE, restit, rest))
.addGroup(createPar(l, Alignment.BASELINE, friction, frict))
.addGroup(createPar(l, Alignment.BASELINE, color, colorPicker))
.addContainerGap());
}
}
private ParallelGroup createPar(GroupLayout l, Alignment al, JComponent... components){
ParallelGroup group = l.createParallelGroup(al);
for (JComponent jComponent : components) {
group.addComponent(jComponent);
}
return group;
}
private DoubleValueTextField createField(Value<Double> val){
return new DoubleValueTextField(colorSettings, val, 0, 10000, 10000);
}
}
| True | 1,371 | 117 | 1,652 | 137 | 1,601 | 119 | 1,652 | 137 | 2,113 | 154 | false | false | false | false | false | true |
3,892 | 138253_15 | /*
* Copyright (C) 2021 B3Partners B.V.
*/
package nl.b3p.brmo.loader.xml;
import nl.b3p.brmo.loader.BrmoFramework;
import nl.b3p.brmo.loader.StagingProxy;
import nl.b3p.brmo.loader.entity.Bericht;
import nl.b3p.brmo.loader.entity.WozBericht;
import nl.b3p.brmo.loader.util.RsgbTransformer;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WozXMLReader extends BrmoXMLReader {
public static final String PREFIX_PRS = "WOZ.NPS.";
public static final String PREFIX_NNP = "WOZ.NNP.";
public static final String PREFIX_WOZ = "WOZ.WOZ.";
public static final String PREFIX_VES = "WOZ.VES.";
private static final Log LOG = LogFactory.getLog(WozXMLReader.class);
private final String pathToXsl = "/xsl/woz-brxml-preprocessor.xsl";
private final StagingProxy staging;
private final XPathFactory xPathfactory = XPathFactory.newInstance();
private InputStream in;
private Templates template;
private NodeList objectNodes = null;
private int index;
private String brOrigXML = null;
public WozXMLReader(InputStream in, Date d, StagingProxy staging) throws Exception {
this.in = in;
this.staging = staging;
setBestandsDatum(d);
init();
}
@Override
public void init() throws Exception {
soort = BrmoFramework.BR_WOZ;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in = new TeeInputStream(in, bos, true);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(in);
brOrigXML = bos.toString(StandardCharsets.UTF_8);
LOG.trace("Originele WOZ xml is: \n" + brOrigXML);
TransformerFactory tf = TransformerFactory.newInstance();
tf.setURIResolver((href, base) -> {
LOG.debug("looking for: " + href + " base: " + base);
return new StreamSource(RsgbTransformer.class.getResourceAsStream("/xsl/" + href));
});
Source xsl = new StreamSource(this.getClass().getResourceAsStream(pathToXsl));
this.template = tf.newTemplates(xsl);
XPath xpath = xPathfactory.newXPath();
if (this.getBestandsDatum() == null) {
// probeer datum nog uit doc te halen..
LOG.debug("Tijdstip bericht was niet gegeven; alsnog proberen op te zoeken in bericht.");
XPathExpression tijdstipBericht = xpath.compile("//*[local-name()='tijdstipBericht']");
Node datum = (Node) tijdstipBericht.evaluate(doc, XPathConstants.NODE);
setDatumAsString(datum.getTextContent(), "yyyyMMddHHmmssSSS");
LOG.debug("Tijdstip bericht ingesteld op " + getBestandsDatum());
}
// woz:object nodes
XPathExpression objectNode = xpath.compile("//*[local-name()='object']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
// mogelijk zijn er omhang berichten (WGEM_hangSubjectOm_Di01)
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNPS']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente NPS omhangbericht");
}
}
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNNP']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente NNP omhangbericht");
}
}
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteVES']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente VES omhangbericht");
}
}
index = 0;
}
@Override
public boolean hasNext() throws Exception {
return index < objectNodes.getLength();
}
@Override
public WozBericht next() throws Exception {
Node n = objectNodes.item(index);
index++;
String object_ref = getObjectRef(n);
StringWriter sw = new StringWriter();
// kijk hier of dit bericht een voorganger heeft: zo niet, dan moet niet de preprocessor template gebruikt worden, maar de gewone.
Bericht old = staging.getPreviousBericht(object_ref, getBestandsDatum(), -1L, new StringBuilder());
Transformer t;
if (old != null) {
LOG.debug("gebruik preprocessor xsl");
t = this.template.newTransformer();
} else {
LOG.debug("gebruik extractie xsl");
t = TransformerFactory.newInstance().newTransformer();
}
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.setOutputProperty(OutputKeys.INDENT, "no");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.transform(new DOMSource(n), new StreamResult(sw));
Map<String, String> bsns = extractBSN(n);
String el = getXML(bsns);
String origXML = sw.toString();
String brXML = "<root>" + origXML;
brXML += el + "</root>";
WozBericht b = new WozBericht(brXML);
b.setDatum(getBestandsDatum());
if (index == 1) {
// alleen op 1e brmo bericht van mogelijk meer uit originele bericht
b.setBrOrgineelXml(brOrigXML);
}
// TODO volgorde nummer:
// bepaal aan de hand van de object_ref of volgordenummer opgehoogd moet worden. Een soap bericht kan meerdere
// object entiteiten bevatten die een eigen type objectref krijgen. bijv. een entiteittype="WOZ" en een entiteittype="NPS"
// bovendien kan een entiteittype="WOZ" een genests gerelateerde hebben die een apart bericht moet/zou kunnen opleveren met objectref
// van een NPS, maar met een hoger volgordenummer...
// vooralsnog halen we niet de geneste entiteiten uit het bericht
b.setVolgordeNummer(index);
if (index > 1) {
// om om het probleem van 2 subjecten uit 1 bericht op zelfde tijdstip dus heen te werken hoger volgordenummer ook iets later maken
b.setDatum(new Date(getBestandsDatum().getTime() + 10));
}
b.setObjectRef(object_ref);
if (StringUtils.isEmpty(b.getObjectRef())) {
// geen object_ref kunnen vaststellen; dan ook niet transformeren
b.setStatus(Bericht.STATUS.STAGING_NOK);
b.setOpmerking("Er kon geen object_ref bepaald worden uit de natuurlijke sleutel van het bericht.");
}
LOG.trace("bericht: " + b);
return b;
}
private String getObjectRef(Node wozObjectNode) throws XPathExpressionException {
// WOZ:object StUF:entiteittype="WOZ"/WOZ:wozObjectNummer
XPathExpression wozObjectNummer = xPathfactory.newXPath().compile("./*[local-name()='wozObjectNummer']");
NodeList obRefs = (NodeList) wozObjectNummer.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0) {
return PREFIX_WOZ + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="NPS"/WOZ:isEen/WOZ:gerelateerde/BG:inp.bsn
XPathExpression bsn = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inp.bsn']");
obRefs = (NodeList) bsn.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0) {
return PREFIX_PRS + getHash(obRefs.item(0).getTextContent());
}
// WOZ:object StUF:entiteittype="NNP"/WOZ:isEen/WOZ:gerelateerde/BG:inn.nnpId
XPathExpression nnpIdXpath = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inn.nnpId']");
obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_NNP + obRefs.item(0).getTextContent();
}
// er komen berichten voor in test set waarin geen nnpId zit, maar wel "aanvullingSoFiNummer" is gevuld...
// WOZ:object StUF:entiteittype="NNP"/WOZ:aanvullingSoFiNummer
nnpIdXpath = xPathfactory.newXPath().compile("*[@StUF:entiteittype='NNP']/*[local-name()='aanvullingSoFiNummer']");
obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
LOG.warn("WOZ NNP zonder `inn.nnpId`, gebruik `aanvullingSoFiNummer` voor id.");
return PREFIX_NNP + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="WRD"/WOZ:isVoor/WOZ:gerelateerde/WOZ:wozObjectNummer
XPathExpression wrd = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='wozObjectNummer']");
obRefs = (NodeList) wrd.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_WOZ + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="VES"/WOZ:isEen/WOZ:gerelateerde/BG:vestigingsNummer
XPathExpression ves = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='vestigingsNummer']");
obRefs = (NodeList) ves.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_VES + obRefs.item(0).getTextContent();
}
return null;
}
/**
* maakt een map met bsn,bsnhash.
*
* @param n document node met bsn-nummer
* @return hashmap met bsn,bsnhash
* @throws XPathExpressionException if any
*/
public Map<String, String> extractBSN(Node n) throws XPathExpressionException {
Map<String, String> hashes = new HashMap<>();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//*[local-name() = 'inp.bsn']");
NodeList nodelist = (NodeList) expr.evaluate(n, XPathConstants.NODESET);
for (int i = 0; i < nodelist.getLength(); i++) {
Node bsn = nodelist.item(i);
String bsnString = bsn.getTextContent();
String hash = getHash(bsnString);
hashes.put(bsnString, hash);
}
return hashes;
}
public String getXML(Map<String, String> map) throws ParserConfigurationException {
if (map.isEmpty()) {
// als in bericht geen personen zitten
return "";
}
String root = "<bsnhashes>";
for (Map.Entry<String, String> entry : map.entrySet()) {
if (!entry.getKey().isEmpty() && !entry.getValue().isEmpty()) {
String hash = entry.getValue();
String el = "<" + PREFIX_PRS + entry.getKey() + ">" + hash + "</" + PREFIX_PRS + entry.getKey() + ">";
root += el;
}
}
root += "</bsnhashes>";
return root;
}
}
| opengeogroep/brmo | brmo-loader/src/main/java/nl/b3p/brmo/loader/xml/WozXMLReader.java | 4,086 | /*[local-name()='inn.nnpId']");
obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_NNP + obRefs.item(0).getTextContent();
}
// er komen berichten voor in test set waarin geen nnpId zit, maar wel "aanvullingSoFiNummer" is gevuld...
// WOZ:object StUF:entiteittype="NNP"/WOZ:aanvullingSoFiNummer
nnpIdXpath = xPathfactory.newXPath().compile("*[@StUF:entiteittype='NNP']/*[local-name()='aanvullingSoFiNummer']");
obRefs = (NodeList) nnpIdXpath.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
LOG.warn("WOZ NNP zonder `inn.nnpId`, gebruik `aanvullingSoFiNummer` voor id.");
return PREFIX_NNP + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="WRD"/WOZ:isVoor/WOZ:gerelateerde/WOZ:wozObjectNummer
XPathExpression wrd = xPathfactory.newXPath().compile("./*/ | block_comment | nl | /*
* Copyright (C) 2021 B3Partners B.V.
*/
package nl.b3p.brmo.loader.xml;
import nl.b3p.brmo.loader.BrmoFramework;
import nl.b3p.brmo.loader.StagingProxy;
import nl.b3p.brmo.loader.entity.Bericht;
import nl.b3p.brmo.loader.entity.WozBericht;
import nl.b3p.brmo.loader.util.RsgbTransformer;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WozXMLReader extends BrmoXMLReader {
public static final String PREFIX_PRS = "WOZ.NPS.";
public static final String PREFIX_NNP = "WOZ.NNP.";
public static final String PREFIX_WOZ = "WOZ.WOZ.";
public static final String PREFIX_VES = "WOZ.VES.";
private static final Log LOG = LogFactory.getLog(WozXMLReader.class);
private final String pathToXsl = "/xsl/woz-brxml-preprocessor.xsl";
private final StagingProxy staging;
private final XPathFactory xPathfactory = XPathFactory.newInstance();
private InputStream in;
private Templates template;
private NodeList objectNodes = null;
private int index;
private String brOrigXML = null;
public WozXMLReader(InputStream in, Date d, StagingProxy staging) throws Exception {
this.in = in;
this.staging = staging;
setBestandsDatum(d);
init();
}
@Override
public void init() throws Exception {
soort = BrmoFramework.BR_WOZ;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in = new TeeInputStream(in, bos, true);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(in);
brOrigXML = bos.toString(StandardCharsets.UTF_8);
LOG.trace("Originele WOZ xml is: \n" + brOrigXML);
TransformerFactory tf = TransformerFactory.newInstance();
tf.setURIResolver((href, base) -> {
LOG.debug("looking for: " + href + " base: " + base);
return new StreamSource(RsgbTransformer.class.getResourceAsStream("/xsl/" + href));
});
Source xsl = new StreamSource(this.getClass().getResourceAsStream(pathToXsl));
this.template = tf.newTemplates(xsl);
XPath xpath = xPathfactory.newXPath();
if (this.getBestandsDatum() == null) {
// probeer datum nog uit doc te halen..
LOG.debug("Tijdstip bericht was niet gegeven; alsnog proberen op te zoeken in bericht.");
XPathExpression tijdstipBericht = xpath.compile("//*[local-name()='tijdstipBericht']");
Node datum = (Node) tijdstipBericht.evaluate(doc, XPathConstants.NODE);
setDatumAsString(datum.getTextContent(), "yyyyMMddHHmmssSSS");
LOG.debug("Tijdstip bericht ingesteld op " + getBestandsDatum());
}
// woz:object nodes
XPathExpression objectNode = xpath.compile("//*[local-name()='object']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
// mogelijk zijn er omhang berichten (WGEM_hangSubjectOm_Di01)
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNPS']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente NPS omhangbericht");
}
}
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteNNP']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente NNP omhangbericht");
}
}
if (objectNodes.getLength() < 1) {
objectNode = xpath.compile("//*[local-name()='nieuweGemeenteVES']");
objectNodes = (NodeList) objectNode.evaluate(doc, XPathConstants.NODESET);
if (LOG.isDebugEnabled() && objectNodes.getLength() > 0) {
LOG.debug("nieuweGemeente VES omhangbericht");
}
}
index = 0;
}
@Override
public boolean hasNext() throws Exception {
return index < objectNodes.getLength();
}
@Override
public WozBericht next() throws Exception {
Node n = objectNodes.item(index);
index++;
String object_ref = getObjectRef(n);
StringWriter sw = new StringWriter();
// kijk hier of dit bericht een voorganger heeft: zo niet, dan moet niet de preprocessor template gebruikt worden, maar de gewone.
Bericht old = staging.getPreviousBericht(object_ref, getBestandsDatum(), -1L, new StringBuilder());
Transformer t;
if (old != null) {
LOG.debug("gebruik preprocessor xsl");
t = this.template.newTransformer();
} else {
LOG.debug("gebruik extractie xsl");
t = TransformerFactory.newInstance().newTransformer();
}
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.setOutputProperty(OutputKeys.INDENT, "no");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.transform(new DOMSource(n), new StreamResult(sw));
Map<String, String> bsns = extractBSN(n);
String el = getXML(bsns);
String origXML = sw.toString();
String brXML = "<root>" + origXML;
brXML += el + "</root>";
WozBericht b = new WozBericht(brXML);
b.setDatum(getBestandsDatum());
if (index == 1) {
// alleen op 1e brmo bericht van mogelijk meer uit originele bericht
b.setBrOrgineelXml(brOrigXML);
}
// TODO volgorde nummer:
// bepaal aan de hand van de object_ref of volgordenummer opgehoogd moet worden. Een soap bericht kan meerdere
// object entiteiten bevatten die een eigen type objectref krijgen. bijv. een entiteittype="WOZ" en een entiteittype="NPS"
// bovendien kan een entiteittype="WOZ" een genests gerelateerde hebben die een apart bericht moet/zou kunnen opleveren met objectref
// van een NPS, maar met een hoger volgordenummer...
// vooralsnog halen we niet de geneste entiteiten uit het bericht
b.setVolgordeNummer(index);
if (index > 1) {
// om om het probleem van 2 subjecten uit 1 bericht op zelfde tijdstip dus heen te werken hoger volgordenummer ook iets later maken
b.setDatum(new Date(getBestandsDatum().getTime() + 10));
}
b.setObjectRef(object_ref);
if (StringUtils.isEmpty(b.getObjectRef())) {
// geen object_ref kunnen vaststellen; dan ook niet transformeren
b.setStatus(Bericht.STATUS.STAGING_NOK);
b.setOpmerking("Er kon geen object_ref bepaald worden uit de natuurlijke sleutel van het bericht.");
}
LOG.trace("bericht: " + b);
return b;
}
private String getObjectRef(Node wozObjectNode) throws XPathExpressionException {
// WOZ:object StUF:entiteittype="WOZ"/WOZ:wozObjectNummer
XPathExpression wozObjectNummer = xPathfactory.newXPath().compile("./*[local-name()='wozObjectNummer']");
NodeList obRefs = (NodeList) wozObjectNummer.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0) {
return PREFIX_WOZ + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="NPS"/WOZ:isEen/WOZ:gerelateerde/BG:inp.bsn
XPathExpression bsn = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inp.bsn']");
obRefs = (NodeList) bsn.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0) {
return PREFIX_PRS + getHash(obRefs.item(0).getTextContent());
}
// WOZ:object StUF:entiteittype="NNP"/WOZ:isEen/WOZ:gerelateerde/BG:inn.nnpId
XPathExpression nnpIdXpath = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='inn.nnpId']");
<SUF>*/*[local-name()='gerelateerde']/*[local-name()='wozObjectNummer']");
obRefs = (NodeList) wrd.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_WOZ + obRefs.item(0).getTextContent();
}
// WOZ:object StUF:entiteittype="VES"/WOZ:isEen/WOZ:gerelateerde/BG:vestigingsNummer
XPathExpression ves = xPathfactory.newXPath().compile("./*/*[local-name()='gerelateerde']/*[local-name()='vestigingsNummer']");
obRefs = (NodeList) ves.evaluate(wozObjectNode, XPathConstants.NODESET);
if (obRefs.getLength() > 0 && !StringUtils.isEmpty(obRefs.item(0).getTextContent())) {
return PREFIX_VES + obRefs.item(0).getTextContent();
}
return null;
}
/**
* maakt een map met bsn,bsnhash.
*
* @param n document node met bsn-nummer
* @return hashmap met bsn,bsnhash
* @throws XPathExpressionException if any
*/
public Map<String, String> extractBSN(Node n) throws XPathExpressionException {
Map<String, String> hashes = new HashMap<>();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//*[local-name() = 'inp.bsn']");
NodeList nodelist = (NodeList) expr.evaluate(n, XPathConstants.NODESET);
for (int i = 0; i < nodelist.getLength(); i++) {
Node bsn = nodelist.item(i);
String bsnString = bsn.getTextContent();
String hash = getHash(bsnString);
hashes.put(bsnString, hash);
}
return hashes;
}
public String getXML(Map<String, String> map) throws ParserConfigurationException {
if (map.isEmpty()) {
// als in bericht geen personen zitten
return "";
}
String root = "<bsnhashes>";
for (Map.Entry<String, String> entry : map.entrySet()) {
if (!entry.getKey().isEmpty() && !entry.getValue().isEmpty()) {
String hash = entry.getValue();
String el = "<" + PREFIX_PRS + entry.getKey() + ">" + hash + "</" + PREFIX_PRS + entry.getKey() + ">";
root += el;
}
}
root += "</bsnhashes>";
return root;
}
}
| False | 3,121 | 327 | 3,564 | 360 | 3,565 | 350 | 3,564 | 360 | 4,091 | 416 | true | true | true | true | true | false |
3,242 | 109250_5 | /**
* Created by alexandru on 7/8/16.
*/
package jlg.jade.asterix.cat048;
import jlg.jade.asterix.VariableLengthAsterixData;
import java.util.BitSet;
/**
* Cat048Item170 - Track Status
* Status of monoradar track (PSR and/or SSR updated).
*/
public class Cat048Item170 extends VariableLengthAsterixData {
private int sensorMaintainingTrackType; // RAD
private int confirmedTrack; // CNF
private int trackConfidenceLevel; // DOU
private int manoeuvreDetectionInHorizontalSense; // MAH
private int climbingDescendingMode; // CDM
private int signalEndOfTrack; // TRE
private int ghostVsTrueTarget; // GHO
private int maintainedWithNeighbourSupport; // SUP
private int coordinatePlotType; // TCC
@Override
protected void decodeFromByteArray(byte[] input, int offset) {
// decode first part
BitSet firstPartBits = BitSet.valueOf(new byte[]{input[offset]});
// decode CNF - bit position 7
final int CNF_BIT_INDEX = 7;
if (firstPartBits.get(CNF_BIT_INDEX)) {
this.confirmedTrack = 1;
} else {
this.confirmedTrack = 0;
}
appendItemDebugMsg("CNF", this.confirmedTrack);
// decode RAD - bits 6-5
decodeRAD(firstPartBits);
// decode DOU - bit 4
final int DOU_BIT_INDEX = 4;
if (firstPartBits.get(DOU_BIT_INDEX)) {
this.trackConfidenceLevel = 1;
} else {
this.trackConfidenceLevel = 0;
}
appendItemDebugMsg("DOU", this.trackConfidenceLevel);
// decode MAH - bit 3
final int MAH_BIT_INDEX = 3;
if (firstPartBits.get(MAH_BIT_INDEX)) {
this.manoeuvreDetectionInHorizontalSense = 1;
} else {
this.manoeuvreDetectionInHorizontalSense = 0;
}
appendItemDebugMsg("MAH", this.manoeuvreDetectionInHorizontalSense);
// decode CMD - bits 2-1
decodeCDM(firstPartBits);
// decode first extent if present
if (this.getSizeInBytes() > 1) {
BitSet firstExtentBits = BitSet.valueOf(new byte[]{input[offset+1]});
// decode TRE - bit position 7
final int TRE_BIT_INDEX = 7;
if(firstExtentBits.get(TRE_BIT_INDEX)){
this.signalEndOfTrack = 1;
} else {
this.signalEndOfTrack = 0;
}
appendItemDebugMsg("TRE", this.signalEndOfTrack);
// decode GHO
final int GHO_BIT_INDEX = 6;
if(firstExtentBits.get(GHO_BIT_INDEX)){
this.ghostVsTrueTarget = 1;
} else {
this.ghostVsTrueTarget = 0;
}
appendItemDebugMsg("GHO", this.ghostVsTrueTarget);
// decode SUP
final int SUP_BIT_INDEX = 5;
if(firstExtentBits.get(SUP_BIT_INDEX)){
this.maintainedWithNeighbourSupport = 1;
} else {
this.maintainedWithNeighbourSupport = 0;
}
appendItemDebugMsg("SUP", this.maintainedWithNeighbourSupport);
// decode TCC
final int TCC_BIT_INDEX = 4;
if(firstExtentBits.get(TCC_BIT_INDEX)){
this.coordinatePlotType = 1;
} else {
this.coordinatePlotType = 0;
}
appendItemDebugMsg("TCC", this.coordinatePlotType);
}
}
@Override
protected String setDisplayName() {
return "Cat048Item170 - Track Status";
}
/**
* @return type of Sensor(s) maintaining Track - RAD
*/
public int getSensorMaintainingTrackType() {
return sensorMaintainingTrackType;
}
public int getConfirmedTrack() {
return confirmedTrack;
}
public int getTrackConfidenceLevel() {
return trackConfidenceLevel;
}
public int getManoeuvreDetectionInHorizontalSense() {
return manoeuvreDetectionInHorizontalSense;
}
public int getClimbingDescendingMode() {
return climbingDescendingMode;
}
public int getSignalEndOfTrack() {
return signalEndOfTrack;
}
public int getGhostVsTrueTarget() {
return ghostVsTrueTarget;
}
public int getMaintainedWithNeighbourSupport() {
return maintainedWithNeighbourSupport;
}
public int getCoordinatePlotType() {
return coordinatePlotType;
}
private void decodeRAD(BitSet firstPartBits) {
final int RAD_BIT0_INDEX = 5;
final int RAD_BIT1_INDEX = 6;
int RADBit0Value = 0;
int RADBit1Value = 0;
if (firstPartBits.get(RAD_BIT0_INDEX)) {
RADBit0Value = 1;
}
if (firstPartBits.get(RAD_BIT1_INDEX)) {
RADBit1Value = 1;
}
this.sensorMaintainingTrackType = RADBit1Value * 2 + RADBit0Value;
appendItemDebugMsg("RAD", this.sensorMaintainingTrackType);
}
private void decodeCDM(BitSet firstPartBits) {
final int CDM_BIT0_INDEX = 1;
final int CMD_BIT1_INDEX = 2;
int CDMBit0Value = 0;
int CDMBit1Value = 0;
if (firstPartBits.get(CDM_BIT0_INDEX)) {
CDMBit0Value = 1;
}
if (firstPartBits.get(CMD_BIT1_INDEX)) {
CDMBit1Value = 1;
}
this.climbingDescendingMode = CDMBit1Value * 2 + CDMBit0Value;
appendItemDebugMsg("CDM", this.climbingDescendingMode);
}
}
| jlgconsulting/JADE-JavaAsterixDecoderEncoder | src/main/java/jlg/jade/asterix/cat048/Cat048Item170.java | 1,795 | // decode DOU - bit 4 | line_comment | nl | /**
* Created by alexandru on 7/8/16.
*/
package jlg.jade.asterix.cat048;
import jlg.jade.asterix.VariableLengthAsterixData;
import java.util.BitSet;
/**
* Cat048Item170 - Track Status
* Status of monoradar track (PSR and/or SSR updated).
*/
public class Cat048Item170 extends VariableLengthAsterixData {
private int sensorMaintainingTrackType; // RAD
private int confirmedTrack; // CNF
private int trackConfidenceLevel; // DOU
private int manoeuvreDetectionInHorizontalSense; // MAH
private int climbingDescendingMode; // CDM
private int signalEndOfTrack; // TRE
private int ghostVsTrueTarget; // GHO
private int maintainedWithNeighbourSupport; // SUP
private int coordinatePlotType; // TCC
@Override
protected void decodeFromByteArray(byte[] input, int offset) {
// decode first part
BitSet firstPartBits = BitSet.valueOf(new byte[]{input[offset]});
// decode CNF - bit position 7
final int CNF_BIT_INDEX = 7;
if (firstPartBits.get(CNF_BIT_INDEX)) {
this.confirmedTrack = 1;
} else {
this.confirmedTrack = 0;
}
appendItemDebugMsg("CNF", this.confirmedTrack);
// decode RAD - bits 6-5
decodeRAD(firstPartBits);
// decode DOU<SUF>
final int DOU_BIT_INDEX = 4;
if (firstPartBits.get(DOU_BIT_INDEX)) {
this.trackConfidenceLevel = 1;
} else {
this.trackConfidenceLevel = 0;
}
appendItemDebugMsg("DOU", this.trackConfidenceLevel);
// decode MAH - bit 3
final int MAH_BIT_INDEX = 3;
if (firstPartBits.get(MAH_BIT_INDEX)) {
this.manoeuvreDetectionInHorizontalSense = 1;
} else {
this.manoeuvreDetectionInHorizontalSense = 0;
}
appendItemDebugMsg("MAH", this.manoeuvreDetectionInHorizontalSense);
// decode CMD - bits 2-1
decodeCDM(firstPartBits);
// decode first extent if present
if (this.getSizeInBytes() > 1) {
BitSet firstExtentBits = BitSet.valueOf(new byte[]{input[offset+1]});
// decode TRE - bit position 7
final int TRE_BIT_INDEX = 7;
if(firstExtentBits.get(TRE_BIT_INDEX)){
this.signalEndOfTrack = 1;
} else {
this.signalEndOfTrack = 0;
}
appendItemDebugMsg("TRE", this.signalEndOfTrack);
// decode GHO
final int GHO_BIT_INDEX = 6;
if(firstExtentBits.get(GHO_BIT_INDEX)){
this.ghostVsTrueTarget = 1;
} else {
this.ghostVsTrueTarget = 0;
}
appendItemDebugMsg("GHO", this.ghostVsTrueTarget);
// decode SUP
final int SUP_BIT_INDEX = 5;
if(firstExtentBits.get(SUP_BIT_INDEX)){
this.maintainedWithNeighbourSupport = 1;
} else {
this.maintainedWithNeighbourSupport = 0;
}
appendItemDebugMsg("SUP", this.maintainedWithNeighbourSupport);
// decode TCC
final int TCC_BIT_INDEX = 4;
if(firstExtentBits.get(TCC_BIT_INDEX)){
this.coordinatePlotType = 1;
} else {
this.coordinatePlotType = 0;
}
appendItemDebugMsg("TCC", this.coordinatePlotType);
}
}
@Override
protected String setDisplayName() {
return "Cat048Item170 - Track Status";
}
/**
* @return type of Sensor(s) maintaining Track - RAD
*/
public int getSensorMaintainingTrackType() {
return sensorMaintainingTrackType;
}
public int getConfirmedTrack() {
return confirmedTrack;
}
public int getTrackConfidenceLevel() {
return trackConfidenceLevel;
}
public int getManoeuvreDetectionInHorizontalSense() {
return manoeuvreDetectionInHorizontalSense;
}
public int getClimbingDescendingMode() {
return climbingDescendingMode;
}
public int getSignalEndOfTrack() {
return signalEndOfTrack;
}
public int getGhostVsTrueTarget() {
return ghostVsTrueTarget;
}
public int getMaintainedWithNeighbourSupport() {
return maintainedWithNeighbourSupport;
}
public int getCoordinatePlotType() {
return coordinatePlotType;
}
private void decodeRAD(BitSet firstPartBits) {
final int RAD_BIT0_INDEX = 5;
final int RAD_BIT1_INDEX = 6;
int RADBit0Value = 0;
int RADBit1Value = 0;
if (firstPartBits.get(RAD_BIT0_INDEX)) {
RADBit0Value = 1;
}
if (firstPartBits.get(RAD_BIT1_INDEX)) {
RADBit1Value = 1;
}
this.sensorMaintainingTrackType = RADBit1Value * 2 + RADBit0Value;
appendItemDebugMsg("RAD", this.sensorMaintainingTrackType);
}
private void decodeCDM(BitSet firstPartBits) {
final int CDM_BIT0_INDEX = 1;
final int CMD_BIT1_INDEX = 2;
int CDMBit0Value = 0;
int CDMBit1Value = 0;
if (firstPartBits.get(CDM_BIT0_INDEX)) {
CDMBit0Value = 1;
}
if (firstPartBits.get(CMD_BIT1_INDEX)) {
CDMBit1Value = 1;
}
this.climbingDescendingMode = CDMBit1Value * 2 + CDMBit0Value;
appendItemDebugMsg("CDM", this.climbingDescendingMode);
}
}
| False | 1,362 | 8 | 1,463 | 8 | 1,518 | 7 | 1,463 | 8 | 1,778 | 8 | false | false | false | false | false | true |
3,283 | 119538_0 | package nl.hanze.hive;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.spy;
public class HiveGameLogic {
//1c. Elke speler heeft aan het begin van het spel de beschikking over één
// bijenkoningin, twee spinnen, twee kevers, drie soldatenmieren en drie
// sprinkhanen in zijn eigen kleur.
@Test
void whenGameStartThenPlayerHaveACompleteDeck() {
HiveGame hiveGame = new HiveGame();
HashMap<Hive.Tile, Integer> playersDeck = hiveGame.getPlayersDeck(Hive.Player.WHITE);
assertEquals(playersDeck.get(Hive.Tile.QUEEN_BEE), 1);
assertEquals(playersDeck.get(Hive.Tile.SPIDER), 2);
assertEquals(playersDeck.get(Hive.Tile.BEETLE), 2);
assertEquals(playersDeck.get(Hive.Tile.SOLDIER_ANT), 3);
assertEquals(playersDeck.get(Hive.Tile.GRASSHOPPER), 3);
}
// 3. Spelverloop Wit heeft de eerste beurt.
@Test
void whenGameStartThenPlayersItsWhiteturn() {
HiveGame hiveGame = new HiveGame();
Hive.Player player = hiveGame.getCurrenPlayer();
assertEquals(Hive.Player.WHITE, player);
}
// 3 Tijdens zijn beurt kan een speler een steen spelen, een steen verplaatsen of
// passen; daarna is de tegenstander aan de beurt
@Test
void whenPlayerMakesAMoveThenGiveTurntoOppositePlayer() throws Hive.IllegalMove {
HiveGame hiveGame = new HiveGame();
hiveGame.play(Hive.Tile.GRASSHOPPER, 0, 0);
assertEquals(Hive.Player.BLACK, hiveGame.getCurrenPlayer());
}
// 3c Een speler wint als alle zes velden naast de bijenkoningin van de
//tegenstander bezet zijn
@Test
void whenPlayerBlacksQueenHisBeeIsSurroundedThenPlayerWhiteWins() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertTrue(hiveGame.isWinner(Hive.Player.WHITE));
}
@Test
void whenPlayerWhiteQueenHisBeeIsSurroundedThenPlayerBlackWins() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertTrue(hiveGame.isWinner(Hive.Player.BLACK));
}
@Test
void whenQueenBeeisNotSurroundedThereIsNoWinner() {
HiveGame hiveGame = spy(HiveGame.class);
for (Hive.Player player : Hive.Player.values()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, player, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertFalse(hiveGame.isWinner(player));
}
}
// 3d. Als beide spelers tegelijk zouden winnen is het in plaats daarvan een
//gelijkspel.
@Test
void whenBothPlayersHaveASurroundedQueenBeeThenItsADraw() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0);
for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r);
}
for (Hexagon neighbour : new Hexagon(1, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.BLACK, neighbour.q, neighbour.r);
}
assertTrue(hiveGame.isDraw());
}
@Test
void whenOnlyPlayerWhiteIsSurroundedThenItsNotaDraw() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0);
for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r);
}
assertFalse(hiveGame.isDraw());
}
}
| jparengkuan/Hive_TDD | src/test/java/nl/hanze/hive/HiveGameLogic.java | 2,099 | //1c. Elke speler heeft aan het begin van het spel de beschikking over één | line_comment | nl | package nl.hanze.hive;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.spy;
public class HiveGameLogic {
//1c. Elke<SUF>
// bijenkoningin, twee spinnen, twee kevers, drie soldatenmieren en drie
// sprinkhanen in zijn eigen kleur.
@Test
void whenGameStartThenPlayerHaveACompleteDeck() {
HiveGame hiveGame = new HiveGame();
HashMap<Hive.Tile, Integer> playersDeck = hiveGame.getPlayersDeck(Hive.Player.WHITE);
assertEquals(playersDeck.get(Hive.Tile.QUEEN_BEE), 1);
assertEquals(playersDeck.get(Hive.Tile.SPIDER), 2);
assertEquals(playersDeck.get(Hive.Tile.BEETLE), 2);
assertEquals(playersDeck.get(Hive.Tile.SOLDIER_ANT), 3);
assertEquals(playersDeck.get(Hive.Tile.GRASSHOPPER), 3);
}
// 3. Spelverloop Wit heeft de eerste beurt.
@Test
void whenGameStartThenPlayersItsWhiteturn() {
HiveGame hiveGame = new HiveGame();
Hive.Player player = hiveGame.getCurrenPlayer();
assertEquals(Hive.Player.WHITE, player);
}
// 3 Tijdens zijn beurt kan een speler een steen spelen, een steen verplaatsen of
// passen; daarna is de tegenstander aan de beurt
@Test
void whenPlayerMakesAMoveThenGiveTurntoOppositePlayer() throws Hive.IllegalMove {
HiveGame hiveGame = new HiveGame();
hiveGame.play(Hive.Tile.GRASSHOPPER, 0, 0);
assertEquals(Hive.Player.BLACK, hiveGame.getCurrenPlayer());
}
// 3c Een speler wint als alle zes velden naast de bijenkoningin van de
//tegenstander bezet zijn
@Test
void whenPlayerBlacksQueenHisBeeIsSurroundedThenPlayerWhiteWins() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertTrue(hiveGame.isWinner(Hive.Player.WHITE));
}
@Test
void whenPlayerWhiteQueenHisBeeIsSurroundedThenPlayerBlackWins() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertTrue(hiveGame.isWinner(Hive.Player.BLACK));
}
@Test
void whenQueenBeeisNotSurroundedThereIsNoWinner() {
HiveGame hiveGame = spy(HiveGame.class);
for (Hive.Player player : Hive.Player.values()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, player, 0, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, 0, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 1, -1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.BLACK, -1, +1);
hiveGame.hiveBoard.placeTile(Hive.Tile.GRASSHOPPER, Hive.Player.WHITE, 0, 1);
assertFalse(hiveGame.isWinner(player));
}
}
// 3d. Als beide spelers tegelijk zouden winnen is het in plaats daarvan een
//gelijkspel.
@Test
void whenBothPlayersHaveASurroundedQueenBeeThenItsADraw() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0);
for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r);
}
for (Hexagon neighbour : new Hexagon(1, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.BLACK, neighbour.q, neighbour.r);
}
assertTrue(hiveGame.isDraw());
}
@Test
void whenOnlyPlayerWhiteIsSurroundedThenItsNotaDraw() {
HiveGame hiveGame = spy(HiveGame.class);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.WHITE, -2, 0);
hiveGame.hiveBoard.placeTile(Hive.Tile.QUEEN_BEE, Hive.Player.BLACK, 1, 0);
for (Hexagon neighbour : new Hexagon(-2, 0).getAllNeighBours()) {
hiveGame.hiveBoard.placeTile(Hive.Tile.SOLDIER_ANT, Hive.Player.WHITE, neighbour.q, neighbour.r);
}
assertFalse(hiveGame.isDraw());
}
}
| True | 1,538 | 21 | 1,785 | 24 | 1,736 | 19 | 1,785 | 24 | 2,195 | 22 | false | false | false | false | false | true |
3,003 | 18201_15 | package novi.basics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static novi.basics.main2.*;
public class Game {
private char[] 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'};
// maximale aantal rondes opslaan
maxRounds = board.length;
this.player1 = player1;
this.player2 = player2;
drawCount = 0;
activePlayer = player1;
}
public void play() {
// opslaan hoeveel keer er gelijk spel is geweest
// -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is)
// speelbord tonen
printBoard();
// starten met de beurt (maximaal 9 beurten)
for (int round = 0; round < maxRounds; round++) {
// naam van de actieve speler opslaan
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();
// 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) {
PLAYERPOSITION.add(chosenField);
// maak de actieve speler, speler 2
activePlayer = player2;
}
// anders
else {
// maak de actieve speler weer speler 1
activePlayer = player1;
PLAYER2POSITION.add(chosenField);
}
} //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");
}
String result = chekWinner();
if (result.length() > 0) {
System.out.println(result);
}
// -- terug naar het begin van de volgende beurt
}
}
public void printBoard() {
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();
}
public String chekWinner() {
List topRow = Arrays.asList(1, 2, 3);
List middleRow = Arrays.asList(4, 5, 6);
List bottomrow = Arrays.asList(7, 8, 9);
List leftColom = Arrays.asList(1, 4, 7);
List middleColom = Arrays.asList(2, 5, 8);
List rightColom = Arrays.asList(9, 6, 3);
List cross1 = Arrays.asList(1, 5, 9);
List cross2 = Arrays.asList(7, 5, 3);
List<List> winning = new ArrayList<List>();
winning.add(topRow);
winning.add(middleRow);
winning.add(bottomrow);
winning.add(leftColom);
winning.add(middleColom);
winning.add(rightColom);
winning.add(cross1);
winning.add(cross2);
for (List l : winning) {
if (PLAYERPOSITION.containsAll(l)) {
player1.addscore();
return player1.getName() + " score: " + player1.getScore() + "\n" + player2.getName() + " score: " + player2.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYER2POSITION.containsAll(l)) {
player2.addscore();
return player2.getName() + " score: " + player2.getScore() + "\n" + player1.getName() + " score: " + player1.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYERPOSITION.size() + PLAYER2POSITION.size() == 9) {
drawCount++;
return "drawcount is:" + drawCount;
}
}
return " ";
}
} | hogeschoolnovi/tic-tac-toe-vurgill | src/novi/basics/Game.java | 1,791 | // het nieuwe speelbord tonen | line_comment | nl | package novi.basics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static novi.basics.main2.*;
public class Game {
private char[] 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'};
// maximale aantal rondes opslaan
maxRounds = board.length;
this.player1 = player1;
this.player2 = player2;
drawCount = 0;
activePlayer = player1;
}
public void play() {
// opslaan hoeveel keer er gelijk spel is geweest
// -- vanaf hier gaan we het spel opnieuw spelen met dezelfde spelers (nadat op het eind keuze 1 gekozen is)
// speelbord tonen
printBoard();
// starten met de beurt (maximaal 9 beurten)
for (int round = 0; round < maxRounds; round++) {
// naam van de actieve speler opslaan
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<SUF>
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:
if (activePlayer == player1) {
PLAYERPOSITION.add(chosenField);
// maak de actieve speler, speler 2
activePlayer = player2;
}
// anders
else {
// maak de actieve speler weer speler 1
activePlayer = player1;
PLAYER2POSITION.add(chosenField);
}
} //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");
}
String result = chekWinner();
if (result.length() > 0) {
System.out.println(result);
}
// -- terug naar het begin van de volgende beurt
}
}
public void printBoard() {
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();
}
public String chekWinner() {
List topRow = Arrays.asList(1, 2, 3);
List middleRow = Arrays.asList(4, 5, 6);
List bottomrow = Arrays.asList(7, 8, 9);
List leftColom = Arrays.asList(1, 4, 7);
List middleColom = Arrays.asList(2, 5, 8);
List rightColom = Arrays.asList(9, 6, 3);
List cross1 = Arrays.asList(1, 5, 9);
List cross2 = Arrays.asList(7, 5, 3);
List<List> winning = new ArrayList<List>();
winning.add(topRow);
winning.add(middleRow);
winning.add(bottomrow);
winning.add(leftColom);
winning.add(middleColom);
winning.add(rightColom);
winning.add(cross1);
winning.add(cross2);
for (List l : winning) {
if (PLAYERPOSITION.containsAll(l)) {
player1.addscore();
return player1.getName() + " score: " + player1.getScore() + "\n" + player2.getName() + " score: " + player2.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYER2POSITION.containsAll(l)) {
player2.addscore();
return player2.getName() + " score: " + player2.getScore() + "\n" + player1.getName() + " score: " + player1.getScore() + "\n" + "drawcount: " + "" + drawCount;
} else if (PLAYERPOSITION.size() + PLAYER2POSITION.size() == 9) {
drawCount++;
return "drawcount is:" + drawCount;
}
}
return " ";
}
} | True | 1,489 | 9 | 1,620 | 11 | 1,578 | 7 | 1,620 | 11 | 1,815 | 9 | false | false | false | false | false | true |
4,283 | 44571_0 |
public class DataController {
private static DataController instance = null;
ModelDiagram md; // mogelijk meerdere diagrammen?
private DataController() {
}
public DataController getInstance() {
if(instance == null)
instance = new DataController();
return instance;
}
public ModelDiagram getModel() {
}
}
| senkz/PaF-Relationship-helper-for-usecases-and-UML | src/DataController.java | 99 | // mogelijk meerdere diagrammen? | line_comment | nl |
public class DataController {
private static DataController instance = null;
ModelDiagram md; // mogelijk meerdere<SUF>
private DataController() {
}
public DataController getInstance() {
if(instance == null)
instance = new DataController();
return instance;
}
public ModelDiagram getModel() {
}
}
| True | 72 | 8 | 88 | 9 | 93 | 6 | 88 | 9 | 106 | 9 | false | false | false | false | false | true |
3,470 | 79029_2 | package be;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import com.exlibris.dps.IEWebServices;
import com.exlibris.dps.IEWebServices_Service;
import com.exlibris.dps.PermanentManagerWS;
import com.exlibris.dps.PermanentManagerWS_Service;
public class CreateMetadataEntry {
private IEWebServices ieWebServices;
private PermanentManagerWS pmWebServices;
public CreateMetadataEntry(String generalFileName, String metadataFileName) {
super();
}
private String readFile(String fileName) throws IOException {
File f = new File(fileName);
byte[] bytes = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(bytes);
return new String(bytes, "UTF-8");
}
public void soapCreateMetadataEntry(String generalFileName, String metadataFileName) {
try {
Thread.sleep(3000);
ieWebServices = new IEWebServices_Service(new URL(Handle.prop.getProperty("IE_WSDL_URL")),new QName("http://dps.exlibris.com/", "IEWebServices")).getIEWebServicesPort();
pmWebServices = new PermanentManagerWS_Service(new URL(Handle.prop.getProperty("PM_WSDL_URL")),new QName("http://dps.exlibris.com/", "PermanentManagerWS")).getPermanentManagerWSPort();
String generalXml = readFile(generalFileName);
String metadataXml = readFile(metadataFileName);
if(!metadataXml.contains("<xb:digital_entity_result") || !metadataFileName.equalsIgnoreCase("general.xml"))
{
Object[] parameters = new Object[] {generalXml, "", "descriptive",
"dc", metadataXml};
// String ret = (String) pmWebServices.storeMetadata(arg0, arg1, arg2, arg3);
// extractMid(ret, metadataFileName);
}
else {
throw new WrongFormatException("Het metadatabestand bevat de verkeerde informatie");
}
} catch (IOException e) {
System.err.println(e.toString());
} catch (InterruptedException e) {
System.err.println(e.toString());
}
}
public void extractMid(String result, String metadataFileName) throws IOException
{
if (!result.contains("error")) {
String REGEX = "<mid>(.*)</mid>";
Pattern p = Pattern.compile(REGEX);
Matcher items = p.matcher(result);
if (items.find()) {
String mid = items.group(1);
// PrintStream out = new PrintStream(System.out, true, "UTF-8");
// out.println(ret);
// Schrijf het resultaat naar een bestand. Het kan gebruikt worden om te zien of er geen foutmeldingen zijn opgetreden
// Maak file
FileWriter fstream = new FileWriter(metadataFileName + "_" + mid + ".out");
BufferedWriter outPut = new BufferedWriter(fstream);
// Schrijf de content
outPut.write(readFile(metadataFileName));
//Sluit de file
outPut.close();
} else {
throw new NotFoundException("Mid niet gevonden voor: " + result);
}
}
}
}
| libis/RosettaUpdater | src/be/CreateMetadataEntry.java | 1,031 | // Schrijf het resultaat naar een bestand. Het kan gebruikt worden om te zien of er geen foutmeldingen zijn opgetreden | line_comment | nl | package be;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import com.exlibris.dps.IEWebServices;
import com.exlibris.dps.IEWebServices_Service;
import com.exlibris.dps.PermanentManagerWS;
import com.exlibris.dps.PermanentManagerWS_Service;
public class CreateMetadataEntry {
private IEWebServices ieWebServices;
private PermanentManagerWS pmWebServices;
public CreateMetadataEntry(String generalFileName, String metadataFileName) {
super();
}
private String readFile(String fileName) throws IOException {
File f = new File(fileName);
byte[] bytes = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(bytes);
return new String(bytes, "UTF-8");
}
public void soapCreateMetadataEntry(String generalFileName, String metadataFileName) {
try {
Thread.sleep(3000);
ieWebServices = new IEWebServices_Service(new URL(Handle.prop.getProperty("IE_WSDL_URL")),new QName("http://dps.exlibris.com/", "IEWebServices")).getIEWebServicesPort();
pmWebServices = new PermanentManagerWS_Service(new URL(Handle.prop.getProperty("PM_WSDL_URL")),new QName("http://dps.exlibris.com/", "PermanentManagerWS")).getPermanentManagerWSPort();
String generalXml = readFile(generalFileName);
String metadataXml = readFile(metadataFileName);
if(!metadataXml.contains("<xb:digital_entity_result") || !metadataFileName.equalsIgnoreCase("general.xml"))
{
Object[] parameters = new Object[] {generalXml, "", "descriptive",
"dc", metadataXml};
// String ret = (String) pmWebServices.storeMetadata(arg0, arg1, arg2, arg3);
// extractMid(ret, metadataFileName);
}
else {
throw new WrongFormatException("Het metadatabestand bevat de verkeerde informatie");
}
} catch (IOException e) {
System.err.println(e.toString());
} catch (InterruptedException e) {
System.err.println(e.toString());
}
}
public void extractMid(String result, String metadataFileName) throws IOException
{
if (!result.contains("error")) {
String REGEX = "<mid>(.*)</mid>";
Pattern p = Pattern.compile(REGEX);
Matcher items = p.matcher(result);
if (items.find()) {
String mid = items.group(1);
// PrintStream out = new PrintStream(System.out, true, "UTF-8");
// out.println(ret);
// Schrijf het<SUF>
// Maak file
FileWriter fstream = new FileWriter(metadataFileName + "_" + mid + ".out");
BufferedWriter outPut = new BufferedWriter(fstream);
// Schrijf de content
outPut.write(readFile(metadataFileName));
//Sluit de file
outPut.close();
} else {
throw new NotFoundException("Mid niet gevonden voor: " + result);
}
}
}
}
| True | 720 | 32 | 850 | 34 | 917 | 27 | 850 | 34 | 1,087 | 36 | false | false | false | false | false | true |
1,246 | 107759_4 | package field.graphics.core;
import static org.lwjgl.opengl.GL11.GL_MODELVIEW;
import static org.lwjgl.opengl.GL11.GL_PROJECTION;
import static org.lwjgl.opengl.GL11.GL_TEXTURE;
import static org.lwjgl.opengl.GL11.glFrustum;
import static org.lwjgl.opengl.GL11.glLoadIdentity;
import static org.lwjgl.opengl.GL11.glMatrixMode;
import static org.lwjgl.opengl.GL11.glViewport;
import static org.lwjgl.opengl.GL13.GL_TEXTURE0;
import static org.lwjgl.opengl.GL13.GL_TEXTURE1;
import static org.lwjgl.opengl.GL13.glActiveTexture;
import java.util.Random;
import org.lwjgl.util.glu.GLU;
import field.graphics.windowing.FullScreenCanvasSWT;
import field.launch.SystemProperties;
import field.math.linalg.Vector3;
public class StereoCamera extends BasicCamera {
// there are two ways of doing stereo, modifying the position of the
// camera and angling the cameras in
// or translating the frustum a little
float io_frustra = 0.0f;
Vector3 io_position = new Vector3();
float io_lookat = 0.0f;
boolean noStereo = SystemProperties.getIntProperty("zeroStereo", 0) == 1;
float multiplyDisparity = (float) SystemProperties.getDoubleProperty("multiplyDisparity", 1);
public StereoCamera setIOFrustra(float i) {
this.io_frustra = i;
return this;
}
public StereoCamera setIOPosition(Vector3 v) {
this.io_position = new Vector3(v);
return this;
}
public StereoCamera setIOPosition(float m) {
this.io_position = new Vector3(m, m, m);
return this;
}
public StereoCamera setIOLookAt(float x) {
this.io_lookat = x;
return this;
}
public float getIOLookAt() {
return io_lookat;
}
static float flipped = (SystemProperties.getIntProperty("stereoEyeFlipped", 0) == 1 ? -1 : 1);
static boolean passive = (SystemProperties.getIntProperty("passiveStereo", 0) == 1);
double disparityPerDistance = SystemProperties.getDoubleProperty("defaultDisparityPerDistance", 0);
boolean texture0IsRight = false;
public float[] previousModelViewLeft;
public float[] previousModelViewRight;
float extraAmount = 1;
@Override
public void performPass() {
pre();
boolean wasDirty = projectionDirty || modelViewDirty;
{
// if (passive) {
// if (FullScreenCanvasSWT.getSide() ==
// FullScreenCanvasSWT.StereoSide.left) {
// // glViewport(oX, oY, width / 2,
// // height);
// glViewport(oX + width / 2, oY, width / 2, height);
// } else {
// glViewport(oX, oY, width / 2, height);
// }
//
// }
// else
// {
glViewport(oX, oY, width, height);
// }
CoreHelpers.glMatrixMode(GL_PROJECTION);
CoreHelpers.glLoadIdentity();
float right = (float) (near * Math.tan((Math.PI * fov / 180f) / 2) * aspect) * frustrumMul;
float top = (float) (near * Math.tan((Math.PI * fov / 180f) / 2)) * frustrumMul;
float x = flipped * io_frustra * FullScreenCanvasSWT.getSide().x;
if (noStereo)
x = 0;
CoreHelpers.glFrustum(-right + (right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount + x)), right + right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount + x), -top + top * tshift, top + top * tshift, near, far);
CoreHelpers.glMatrixMode(GL_MODELVIEW);
projectionDirty = false;
}
{
CoreHelpers.glMatrixMode(GL_MODELVIEW);
CoreHelpers.glLoadIdentity();
Vector3 left = new Vector3().cross(getViewRay(null), getUp(null)).normalize();
Vector3 io_position = new Vector3(this.io_position);
io_position.x += disparityPerDistance * lookAt.distanceFrom(position);
io_position.y += disparityPerDistance * lookAt.distanceFrom(position);
io_position.z += disparityPerDistance * lookAt.distanceFrom(position);
io_position.scale(multiplyDisparity);
if (noStereo)
left.scale(0);
float x = flipped * io_frustra * FullScreenCanvasSWT.getSide().x;
float right = (float) (near * Math.tan((Math.PI * fov / 180f) / 2) * aspect) * frustrumMul;
CoreHelpers.gluLookAt(position.x + flipped * (io_position.x) * FullScreenCanvasSWT.getSide().x * left.x, position.y + flipped * io_position.y * FullScreenCanvasSWT.getSide().x * left.y, position.z + flipped * io_position.z * FullScreenCanvasSWT.getSide().x * left.z, lookAt.x + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.x, lookAt.y + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.y, lookAt.z + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.z, up.x, up.y, up.z);
CoreHelpers.glActiveTexture(GL_TEXTURE0);
CoreHelpers.glMatrixMode(GL_TEXTURE);
CoreHelpers.glLoadIdentity();
if (!texture0IsRight)
CoreHelpers.gluLookAt(position.x + flipped * io_position.x * FullScreenCanvasSWT.getSide().x * left.x, position.y + flipped * io_position.y * FullScreenCanvasSWT.getSide().x * left.y, position.z + flipped * io_position.z * FullScreenCanvasSWT.getSide().x * left.z, lookAt.x + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.x, lookAt.y + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.y, lookAt.z + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.z, up.x, up.y, up.z);
else
CoreHelpers.gluLookAt(position.x + flipped * io_position.x * 1 * left.x, position.y + flipped * io_position.y * 1 * left.y, position.z + flipped * io_position.z * 1 * left.z, lookAt.x + flipped * io_lookat * 1 * left.x, lookAt.y + flipped * io_lookat * 1 * left.y, lookAt.z + flipped * io_lookat * 1 * left.z, up.x, up.y, up.z);
CoreHelpers.glActiveTexture(GL_TEXTURE1);
CoreHelpers.glMatrixMode(GL_TEXTURE);
CoreHelpers.glLoadIdentity();
float top = (float) (near * Math.tan((Math.PI * fov / 180f) / 2)) * frustrumMul;
x = 0;
CoreHelpers.glFrustum(-right + (right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount)), right + right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount), -top + top * tshift, top + top * tshift, near, far);
CoreHelpers.gluLookAt(position.x, position.y, position.z, lookAt.x, lookAt.y, lookAt.z, up.x, up.y, up.z);
CoreHelpers.glMatrixMode(GL_MODELVIEW);
CoreHelpers.glActiveTexture(GL_TEXTURE0);
modelViewDirty = false;
}
post();
if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left)
randomSource.left();
else if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.right)
randomSource.right();
if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) {
previousModelViewRight = modelView;
previousModelView = previousModelViewLeft;
} else if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.right) {
previousModelViewLeft = modelView;
previousModelView = previousModelViewRight;
} else {
previousModelView = previousModelViewLeft;
previousModelViewLeft = modelView;
}
projection = getCurrentProjectionMatrixNow(null);
modelView = getCurrentModelViewMatrixNow(null);
if (dropFrame) {
if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) {
previousModelViewLeft = modelView;
} else {
previousModelViewRight = modelView;
}
}
currentCamera = this;
}
public void copyTo(BasicCamera shim) {
super.copyTo(shim);
if (shim instanceof StereoCamera) {
((StereoCamera) shim).io_frustra = io_frustra;
((StereoCamera) shim).io_position = io_position;
((StereoCamera) shim).io_lookat = io_lookat;
}
}
public StereoNoiseSource randomSource = new StereoNoiseSource();
static public class StereoNoiseSource {
private Random r;
public StereoNoiseSource() {
r = new Random();
}
public float get() {
return r.nextFloat();
}
long leftseed = System.currentTimeMillis();
public void left() {
r = new Random(leftseed);
r.nextFloat();
r.nextFloat();
}
public void right() {
leftseed = System.currentTimeMillis();
r = new Random(leftseed);
r.nextFloat();
r.nextFloat();
}
}
public float getIOFrustra() {
return io_frustra;
}
public Vector3 getIOPosition() {
return io_position;
}
public static double getRandomNumber() {
return Math.random();
//
// if (BasicCamera.currentCamera instanceof StereoCamera)
// {
// return
// ((StereoCamera)BasicCamera.currentCamera).randomSource.get();
// }
// else
// {
// ;//System.out.println(" warning: current camera is not a stereo camera ");
// return Math.random();
// }
}
}
| OpenEndedGroup/Field | Contents/core/java/field/graphics/core/StereoCamera.java | 3,086 | // if (FullScreenCanvasSWT.getSide() == | line_comment | nl | package field.graphics.core;
import static org.lwjgl.opengl.GL11.GL_MODELVIEW;
import static org.lwjgl.opengl.GL11.GL_PROJECTION;
import static org.lwjgl.opengl.GL11.GL_TEXTURE;
import static org.lwjgl.opengl.GL11.glFrustum;
import static org.lwjgl.opengl.GL11.glLoadIdentity;
import static org.lwjgl.opengl.GL11.glMatrixMode;
import static org.lwjgl.opengl.GL11.glViewport;
import static org.lwjgl.opengl.GL13.GL_TEXTURE0;
import static org.lwjgl.opengl.GL13.GL_TEXTURE1;
import static org.lwjgl.opengl.GL13.glActiveTexture;
import java.util.Random;
import org.lwjgl.util.glu.GLU;
import field.graphics.windowing.FullScreenCanvasSWT;
import field.launch.SystemProperties;
import field.math.linalg.Vector3;
public class StereoCamera extends BasicCamera {
// there are two ways of doing stereo, modifying the position of the
// camera and angling the cameras in
// or translating the frustum a little
float io_frustra = 0.0f;
Vector3 io_position = new Vector3();
float io_lookat = 0.0f;
boolean noStereo = SystemProperties.getIntProperty("zeroStereo", 0) == 1;
float multiplyDisparity = (float) SystemProperties.getDoubleProperty("multiplyDisparity", 1);
public StereoCamera setIOFrustra(float i) {
this.io_frustra = i;
return this;
}
public StereoCamera setIOPosition(Vector3 v) {
this.io_position = new Vector3(v);
return this;
}
public StereoCamera setIOPosition(float m) {
this.io_position = new Vector3(m, m, m);
return this;
}
public StereoCamera setIOLookAt(float x) {
this.io_lookat = x;
return this;
}
public float getIOLookAt() {
return io_lookat;
}
static float flipped = (SystemProperties.getIntProperty("stereoEyeFlipped", 0) == 1 ? -1 : 1);
static boolean passive = (SystemProperties.getIntProperty("passiveStereo", 0) == 1);
double disparityPerDistance = SystemProperties.getDoubleProperty("defaultDisparityPerDistance", 0);
boolean texture0IsRight = false;
public float[] previousModelViewLeft;
public float[] previousModelViewRight;
float extraAmount = 1;
@Override
public void performPass() {
pre();
boolean wasDirty = projectionDirty || modelViewDirty;
{
// if (passive) {
// if (FullScreenCanvasSWT.getSide()<SUF>
// FullScreenCanvasSWT.StereoSide.left) {
// // glViewport(oX, oY, width / 2,
// // height);
// glViewport(oX + width / 2, oY, width / 2, height);
// } else {
// glViewport(oX, oY, width / 2, height);
// }
//
// }
// else
// {
glViewport(oX, oY, width, height);
// }
CoreHelpers.glMatrixMode(GL_PROJECTION);
CoreHelpers.glLoadIdentity();
float right = (float) (near * Math.tan((Math.PI * fov / 180f) / 2) * aspect) * frustrumMul;
float top = (float) (near * Math.tan((Math.PI * fov / 180f) / 2)) * frustrumMul;
float x = flipped * io_frustra * FullScreenCanvasSWT.getSide().x;
if (noStereo)
x = 0;
CoreHelpers.glFrustum(-right + (right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount + x)), right + right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount + x), -top + top * tshift, top + top * tshift, near, far);
CoreHelpers.glMatrixMode(GL_MODELVIEW);
projectionDirty = false;
}
{
CoreHelpers.glMatrixMode(GL_MODELVIEW);
CoreHelpers.glLoadIdentity();
Vector3 left = new Vector3().cross(getViewRay(null), getUp(null)).normalize();
Vector3 io_position = new Vector3(this.io_position);
io_position.x += disparityPerDistance * lookAt.distanceFrom(position);
io_position.y += disparityPerDistance * lookAt.distanceFrom(position);
io_position.z += disparityPerDistance * lookAt.distanceFrom(position);
io_position.scale(multiplyDisparity);
if (noStereo)
left.scale(0);
float x = flipped * io_frustra * FullScreenCanvasSWT.getSide().x;
float right = (float) (near * Math.tan((Math.PI * fov / 180f) / 2) * aspect) * frustrumMul;
CoreHelpers.gluLookAt(position.x + flipped * (io_position.x) * FullScreenCanvasSWT.getSide().x * left.x, position.y + flipped * io_position.y * FullScreenCanvasSWT.getSide().x * left.y, position.z + flipped * io_position.z * FullScreenCanvasSWT.getSide().x * left.z, lookAt.x + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.x, lookAt.y + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.y, lookAt.z + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.z, up.x, up.y, up.z);
CoreHelpers.glActiveTexture(GL_TEXTURE0);
CoreHelpers.glMatrixMode(GL_TEXTURE);
CoreHelpers.glLoadIdentity();
if (!texture0IsRight)
CoreHelpers.gluLookAt(position.x + flipped * io_position.x * FullScreenCanvasSWT.getSide().x * left.x, position.y + flipped * io_position.y * FullScreenCanvasSWT.getSide().x * left.y, position.z + flipped * io_position.z * FullScreenCanvasSWT.getSide().x * left.z, lookAt.x + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.x, lookAt.y + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.y, lookAt.z + flipped * io_lookat * FullScreenCanvasSWT.getSide().x * left.z, up.x, up.y, up.z);
else
CoreHelpers.gluLookAt(position.x + flipped * io_position.x * 1 * left.x, position.y + flipped * io_position.y * 1 * left.y, position.z + flipped * io_position.z * 1 * left.z, lookAt.x + flipped * io_lookat * 1 * left.x, lookAt.y + flipped * io_lookat * 1 * left.y, lookAt.z + flipped * io_lookat * 1 * left.z, up.x, up.y, up.z);
CoreHelpers.glActiveTexture(GL_TEXTURE1);
CoreHelpers.glMatrixMode(GL_TEXTURE);
CoreHelpers.glLoadIdentity();
float top = (float) (near * Math.tan((Math.PI * fov / 180f) / 2)) * frustrumMul;
x = 0;
CoreHelpers.glFrustum(-right + (right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount)), right + right * (rshift + FullScreenCanvasSWT.currentCanvas.extraShiftX * extraAmount), -top + top * tshift, top + top * tshift, near, far);
CoreHelpers.gluLookAt(position.x, position.y, position.z, lookAt.x, lookAt.y, lookAt.z, up.x, up.y, up.z);
CoreHelpers.glMatrixMode(GL_MODELVIEW);
CoreHelpers.glActiveTexture(GL_TEXTURE0);
modelViewDirty = false;
}
post();
if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left)
randomSource.left();
else if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.right)
randomSource.right();
if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) {
previousModelViewRight = modelView;
previousModelView = previousModelViewLeft;
} else if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.right) {
previousModelViewLeft = modelView;
previousModelView = previousModelViewRight;
} else {
previousModelView = previousModelViewLeft;
previousModelViewLeft = modelView;
}
projection = getCurrentProjectionMatrixNow(null);
modelView = getCurrentModelViewMatrixNow(null);
if (dropFrame) {
if (FullScreenCanvasSWT.getSide() == FullScreenCanvasSWT.StereoSide.left) {
previousModelViewLeft = modelView;
} else {
previousModelViewRight = modelView;
}
}
currentCamera = this;
}
public void copyTo(BasicCamera shim) {
super.copyTo(shim);
if (shim instanceof StereoCamera) {
((StereoCamera) shim).io_frustra = io_frustra;
((StereoCamera) shim).io_position = io_position;
((StereoCamera) shim).io_lookat = io_lookat;
}
}
public StereoNoiseSource randomSource = new StereoNoiseSource();
static public class StereoNoiseSource {
private Random r;
public StereoNoiseSource() {
r = new Random();
}
public float get() {
return r.nextFloat();
}
long leftseed = System.currentTimeMillis();
public void left() {
r = new Random(leftseed);
r.nextFloat();
r.nextFloat();
}
public void right() {
leftseed = System.currentTimeMillis();
r = new Random(leftseed);
r.nextFloat();
r.nextFloat();
}
}
public float getIOFrustra() {
return io_frustra;
}
public Vector3 getIOPosition() {
return io_position;
}
public static double getRandomNumber() {
return Math.random();
//
// if (BasicCamera.currentCamera instanceof StereoCamera)
// {
// return
// ((StereoCamera)BasicCamera.currentCamera).randomSource.get();
// }
// else
// {
// ;//System.out.println(" warning: current camera is not a stereo camera ");
// return Math.random();
// }
}
}
| False | 2,347 | 11 | 2,850 | 12 | 2,705 | 11 | 2,850 | 12 | 3,325 | 13 | false | false | false | false | false | true |
1,021 | 121263_0 | //bestandsnaam: Oef2.java //<-- uitzonderlijke zelf importerende bibliotheek (moet dus niet in staan feitelijk)
/**
*De klasse Oef2 is een java applicatie
*
*@author Sophie Moons
*@version 1,0
*/
import java.lang.*;
public class Oef2{
/**
*Dit is een main function, hier start het programma
*@param args -> hiermee kan een array meegegeven worden via command line
*/
public static void main(String args[])
{
String[] dagen={"zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"};
int h=1;
System.out.println("Data februari 2009:\n");
while (h<29) //28 dagen toen
{
for(int i=0;i<dagen.length;i++)
{
System.out.println(dagen[i]+" "+h+" februari");
h++;
}
}
}//einde main
}//einde program | MTA-Digital-Broadcast-2/A-Moons-Sophie-De-Cock-Nicolas-Project-MHP | Sophie Moons/Labo Java/blz19/Oef2.java | 263 | //bestandsnaam: Oef2.java //<-- uitzonderlijke zelf importerende bibliotheek (moet dus niet in staan feitelijk) | line_comment | nl | //bestandsnaam: Oef2.java<SUF>
/**
*De klasse Oef2 is een java applicatie
*
*@author Sophie Moons
*@version 1,0
*/
import java.lang.*;
public class Oef2{
/**
*Dit is een main function, hier start het programma
*@param args -> hiermee kan een array meegegeven worden via command line
*/
public static void main(String args[])
{
String[] dagen={"zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"};
int h=1;
System.out.println("Data februari 2009:\n");
while (h<29) //28 dagen toen
{
for(int i=0;i<dagen.length;i++)
{
System.out.println(dagen[i]+" "+h+" februari");
h++;
}
}
}//einde main
}//einde program | True | 222 | 35 | 275 | 41 | 233 | 31 | 275 | 41 | 270 | 37 | false | false | false | false | false | true |
4,184 | 22211_0 | package nl.designpatterns.builder;
import java.util.Date;
public class VacationBuilder {
private static VacationBuilder builder = new VacationBuilder();
private VacationBuilder() {}
public static VacationBuilder getInstance() {
return builder;
}
private Vacation vacation = new Vacation();
public void addPersoon(String voornaam, String achternaam) {
Persoon p = new Persoon(achternaam, voornaam, new Date());
this.vacation.addPersoon(p);
}
public void setHotel(String name) {
this.vacation.setHotel(new Hotel(name));
}
public void setReservation(String in, String uit) {
// test normaliter zou ik datum moeten parsen maar dat vind ik nog steeds zuigen in Java.
Date inDate = new Date();
Date outDate = new Date(new Date().getTime()-10000);
Reservation reservation = new Reservation(inDate, outDate);
this.vacation.setReservation(reservation);
}
public void addActivity(Activity activity) {
this.vacation.addActivity(activity);
}
public Vacation getVacation() {
return this.vacation;
}
}
| rloman/design-patterns | src/main/java/nl/designpatterns/builder/VacationBuilder.java | 356 | // test normaliter zou ik datum moeten parsen maar dat vind ik nog steeds zuigen in Java. | line_comment | nl | package nl.designpatterns.builder;
import java.util.Date;
public class VacationBuilder {
private static VacationBuilder builder = new VacationBuilder();
private VacationBuilder() {}
public static VacationBuilder getInstance() {
return builder;
}
private Vacation vacation = new Vacation();
public void addPersoon(String voornaam, String achternaam) {
Persoon p = new Persoon(achternaam, voornaam, new Date());
this.vacation.addPersoon(p);
}
public void setHotel(String name) {
this.vacation.setHotel(new Hotel(name));
}
public void setReservation(String in, String uit) {
// test normaliter<SUF>
Date inDate = new Date();
Date outDate = new Date(new Date().getTime()-10000);
Reservation reservation = new Reservation(inDate, outDate);
this.vacation.setReservation(reservation);
}
public void addActivity(Activity activity) {
this.vacation.addActivity(activity);
}
public Vacation getVacation() {
return this.vacation;
}
}
| False | 260 | 22 | 328 | 28 | 325 | 21 | 328 | 28 | 400 | 25 | false | false | false | false | false | true |
4,029 | 18945_0 | package codefromvideo.mockito;_x000D_
_x000D_
import java.util.List;_x000D_
_x000D_
public class Winkelmand {_x000D_
_x000D_
public boolean voegProductToeAanWinkelmand(_x000D_
Sessie sessie,_x000D_
Product nieuwProduct) {_x000D_
List<Product> producten = sessie.getProducten();_x000D_
_x000D_
if (productZitNogNietInLijst(nieuwProduct, producten)) {_x000D_
producten.add(nieuwProduct);_x000D_
sessie.setProducten(producten);_x000D_
return true;_x000D_
} else {_x000D_
// product mag maar 1 keer in winkelmand zitten_x000D_
return false;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean productZitNogNietInLijst(Product nieuwProduct, List<Product> producten) {_x000D_
return producten.stream().noneMatch(p -> p.getNaam().equals(nieuwProduct.getNaam()));_x000D_
}_x000D_
}_x000D_
| praegus/intro-unittesten | src/main/java/codefromvideo/mockito/Winkelmand.java | 234 | // product mag maar 1 keer in winkelmand zitten_x000D_ | line_comment | nl | package codefromvideo.mockito;_x000D_
_x000D_
import java.util.List;_x000D_
_x000D_
public class Winkelmand {_x000D_
_x000D_
public boolean voegProductToeAanWinkelmand(_x000D_
Sessie sessie,_x000D_
Product nieuwProduct) {_x000D_
List<Product> producten = sessie.getProducten();_x000D_
_x000D_
if (productZitNogNietInLijst(nieuwProduct, producten)) {_x000D_
producten.add(nieuwProduct);_x000D_
sessie.setProducten(producten);_x000D_
return true;_x000D_
} else {_x000D_
// product mag<SUF>
return false;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean productZitNogNietInLijst(Product nieuwProduct, List<Product> producten) {_x000D_
return producten.stream().noneMatch(p -> p.getNaam().equals(nieuwProduct.getNaam()));_x000D_
}_x000D_
}_x000D_
| True | 341 | 19 | 372 | 24 | 361 | 18 | 372 | 24 | 397 | 22 | false | false | false | false | false | true |
4,597 | 10051_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 jmtp;
import java.math.BigInteger;
import java.util.Date;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.Guid;
import be.derycke.pieter.com.OleDate;
/**
*
* @author Pieter De Rycke
*/
class PortableDeviceObjectImplWin32 implements PortableDeviceObject {
protected PortableDeviceContentImplWin32 content;
protected PortableDevicePropertiesImplWin32 properties;
protected PortableDeviceKeyCollectionImplWin32 keyCollection;
protected PortableDeviceValuesImplWin32 values;
protected String objectID;
PortableDeviceObjectImplWin32(String objectID,
PortableDeviceContentImplWin32 content,
PortableDevicePropertiesImplWin32 properties) {
this.objectID = objectID;
this.content = content;
this.properties = properties;
try {
this.keyCollection = new PortableDeviceKeyCollectionImplWin32();
this.values = new PortableDeviceValuesImplWin32();
}
catch (COMException e) {
e.printStackTrace();
}
}
/**
* Een String property opvragen.
* @param key
* @return
*/
protected String retrieveStringValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getStringValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return null;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -> de string werd niet ingesteld
}
}
}
protected void changeStringValue(PropertyKey key, String value) {
try {
values.clear();
values.setStringValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected long retrieveLongValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return -1;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return -1;
}
}
}
protected void changeLongValue(PropertyKey key, long value) {
try {
values.clear();
values.setUnsignedIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected Date retrieveDateValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key));
}
catch(COMException e) {
return null;
}
}
protected void changeDateValue(PropertyKey key, Date value) {
try {
values.clear();
values.setFloateValue(key, (float)new OleDate(value).toDouble());
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {}
}
protected boolean retrieveBooleanValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getBoolValue(key);
}
catch(COMException e) {
return false;
}
}
protected Guid retrieveGuidValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getGuidValue(key);
}
catch(COMException e) {
return null;
}
}
protected BigInteger retrieveBigIntegerValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getUnsignedLargeIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return new BigInteger("-1");
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -> de string werd niet ingesteld
}
}
}
protected void changeBigIntegerValue(PropertyKey key, BigInteger value) {
try {
values.clear();
values.setUnsignedLargeIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
public String getID() {
return objectID;
}
public String getName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME);
}
public String getOriginalFileName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME);
}
public boolean canDelete() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE);
}
public boolean isHidden() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN);
}
public boolean isSystemObject() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM);
}
public Date getDateModified() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED);
}
public Date getDateCreated() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED);
}
public Date getDateAuthored() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED);
}
public PortableDeviceObject getParent() {
String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID);
if(parentID != null)
return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties);
else
return null;
}
public BigInteger getSize() {
return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE);
}
public String getPersistentUniqueIdentifier() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID);
}
public boolean isDrmProtected() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED);
}
public String getSyncID() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID);
}
//TODO slechts tijdelijk de guids geven -> enum aanmaken
public Guid getFormat() {
return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT);
}
public void setSyncID(String value) {
changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value);
}
public void delete() {
try {
PortableDevicePropVariantCollectionImplWin32 collection =
new PortableDevicePropVariantCollectionImplWin32();
collection.add(new PropVariant(this.objectID));
this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection);
}
catch(COMException e) {
//TODO -> misschien een exception gooien?
e.printStackTrace();
}
}
@Override
public String toString() {
return objectID;
}
public boolean equals(Object o) {
if(o instanceof PortableDeviceObjectImplWin32) {
PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o;
return object.objectID.equals(this.objectID);
}
else
return false;
}
}
| ultrah/jMTPe | source/java/src/jmtp/PortableDeviceObjectImplWin32.java | 2,931 | //comexception -> de string werd niet ingesteld | 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 jmtp;
import java.math.BigInteger;
import java.util.Date;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.Guid;
import be.derycke.pieter.com.OleDate;
/**
*
* @author Pieter De Rycke
*/
class PortableDeviceObjectImplWin32 implements PortableDeviceObject {
protected PortableDeviceContentImplWin32 content;
protected PortableDevicePropertiesImplWin32 properties;
protected PortableDeviceKeyCollectionImplWin32 keyCollection;
protected PortableDeviceValuesImplWin32 values;
protected String objectID;
PortableDeviceObjectImplWin32(String objectID,
PortableDeviceContentImplWin32 content,
PortableDevicePropertiesImplWin32 properties) {
this.objectID = objectID;
this.content = content;
this.properties = properties;
try {
this.keyCollection = new PortableDeviceKeyCollectionImplWin32();
this.values = new PortableDeviceValuesImplWin32();
}
catch (COMException e) {
e.printStackTrace();
}
}
/**
* Een String property opvragen.
* @param key
* @return
*/
protected String retrieveStringValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getStringValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return null;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -><SUF>
}
}
}
protected void changeStringValue(PropertyKey key, String value) {
try {
values.clear();
values.setStringValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected long retrieveLongValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return -1;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return -1;
}
}
}
protected void changeLongValue(PropertyKey key, long value) {
try {
values.clear();
values.setUnsignedIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected Date retrieveDateValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key));
}
catch(COMException e) {
return null;
}
}
protected void changeDateValue(PropertyKey key, Date value) {
try {
values.clear();
values.setFloateValue(key, (float)new OleDate(value).toDouble());
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {}
}
protected boolean retrieveBooleanValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getBoolValue(key);
}
catch(COMException e) {
return false;
}
}
protected Guid retrieveGuidValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getGuidValue(key);
}
catch(COMException e) {
return null;
}
}
protected BigInteger retrieveBigIntegerValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getUnsignedLargeIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return new BigInteger("-1");
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -> de string werd niet ingesteld
}
}
}
protected void changeBigIntegerValue(PropertyKey key, BigInteger value) {
try {
values.clear();
values.setUnsignedLargeIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
public String getID() {
return objectID;
}
public String getName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME);
}
public String getOriginalFileName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME);
}
public boolean canDelete() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE);
}
public boolean isHidden() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN);
}
public boolean isSystemObject() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM);
}
public Date getDateModified() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED);
}
public Date getDateCreated() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED);
}
public Date getDateAuthored() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED);
}
public PortableDeviceObject getParent() {
String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID);
if(parentID != null)
return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties);
else
return null;
}
public BigInteger getSize() {
return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE);
}
public String getPersistentUniqueIdentifier() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID);
}
public boolean isDrmProtected() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED);
}
public String getSyncID() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID);
}
//TODO slechts tijdelijk de guids geven -> enum aanmaken
public Guid getFormat() {
return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT);
}
public void setSyncID(String value) {
changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value);
}
public void delete() {
try {
PortableDevicePropVariantCollectionImplWin32 collection =
new PortableDevicePropVariantCollectionImplWin32();
collection.add(new PropVariant(this.objectID));
this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection);
}
catch(COMException e) {
//TODO -> misschien een exception gooien?
e.printStackTrace();
}
}
@Override
public String toString() {
return objectID;
}
public boolean equals(Object o) {
if(o instanceof PortableDeviceObjectImplWin32) {
PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o;
return object.objectID.equals(this.objectID);
}
else
return false;
}
}
| True | 2,127 | 10 | 2,491 | 12 | 2,732 | 11 | 2,491 | 12 | 3,051 | 11 | false | false | false | false | false | true |
1,206 | 71697_2 | package com.hollingsworth.arsnouveau.common.entity;
import com.hollingsworth.arsnouveau.ArsNouveau;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ObjectHolder;
@ObjectHolder(ArsNouveau.MODID)
public class ModEntities {
public static final EntityType<EntityProjectileSpell> SPELL_PROJ = null;
// public static void init() {
// // Every entity in our mod has an ID (local to this mod)
// int id = 1;
// EntityRegistry.registerModEntity(new ResourceLocation(""), EntityProjectileSpell.class, "ProjectileSpell", id++, ExampleMod.instance, 64, 3, true);
//// EntityRegistry.registerModEntity(EntityWeirdZombie.class, "WeirdZombie", id++, ModTut.instance, 64, 3, true, 0x996600, 0x00ff00);
////
//// // We want our mob to spawn in Plains and ice plains biomes. If you don't add this then it will not spawn automatically
//// // but you can of course still make it spawn manually
//// EntityRegistry.addSpawn(EntityWeirdZombie.class, 100, 3, 5, EnumCreatureType.MONSTER, Biomes.PLAINS, Biomes.ICE_PLAINS);
////
//// // This is the loot table for our mob
//// LootTableList.register(EntityWeirdZombie.LOOT);
// }
@Mod.EventBusSubscriber(modid = ArsNouveau.MODID, bus= Mod.EventBusSubscriber.Bus.MOD)
public static class RegistrationHandler {
public static final int lightballID = 29;
/**
* Register this mod's {@link Entity} types.
*
* @param event The event
*/
@SubscribeEvent
public static void registerEntities(final RegistryEvent.Register<EntityType<?>> event) {
System.out.println("Registered entitites");
// final EntityEntry[] entries = {
// createBuilder("mod_projectile_spell")
// .entity(EntityProjectileSpell.class)
// .tracker(64, 20, false)
// .build(),
//
//
// };
final EntityType<EntityProjectileSpell> spell_proj = build(
"spell_proj",
EntityType.Builder.<EntityProjectileSpell>create(EntityProjectileSpell::new, EntityClassification.MISC)
.size(0.5f, 0.5f)
.setTrackingRange(10)
.setShouldReceiveVelocityUpdates(true)
.setUpdateInterval(60).setCustomClientFactory(EntityProjectileSpell::new));
final EntityType<EntityEvokerFangs> evokerFangs = build(
"fangs",
EntityType.Builder.<EntityEvokerFangs>create(EntityEvokerFangs::new, EntityClassification.MISC)
.size(0.5F, 0.8F)
.setUpdateInterval(60));
final EntityType<EntityAllyVex> allyVex = build(
"ally_vex",
EntityType.Builder.<EntityAllyVex>create(EntityAllyVex::new, EntityClassification.MISC)
.size(0.4F, 0.8F).immuneToFire()
.setUpdateInterval(60));
event.getRegistry().registerAll(
spell_proj,
evokerFangs,
allyVex
);
//ENT_PROJECTILE = registerEntity(EntityType.Builder.<EntityModProjectile>create(EntityClassification.MISC).setCustomClientFactory(EntityModProjectile::new).size(0.25F, 0.25F), "ent_projectile");
// EntityRegistry.registerModEntity(new ResourceLocation(ExampleMod.MODID, "dmlightball"),
// EntityProjectileSpell.class, ExampleMod.MODID + ".dmlightball", lightballID, ExampleMod.instance,
// 80, 20, true);
//event.getRegistry().registerAll(entries);
}
}
/**
* Build an {@link EntityType} from a {@link EntityType.Builder} using the specified name.
*
* @param name The entity type name
* @param builder The entity type builder to build
* @return The built entity type
*/
private static <T extends Entity> EntityType<T> build(final String name, final EntityType.Builder<T> builder) {
final ResourceLocation registryName = new ResourceLocation(ArsNouveau.MODID, name);
final EntityType<T> entityType = builder
.build(registryName.toString());
entityType.setRegistryName(registryName);
return entityType;
}
}
| NielsPilgaard/Ars-Nouveau | src/main/java/com/hollingsworth/arsnouveau/common/entity/ModEntities.java | 1,353 | // int id = 1; | line_comment | nl | package com.hollingsworth.arsnouveau.common.entity;
import com.hollingsworth.arsnouveau.ArsNouveau;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ObjectHolder;
@ObjectHolder(ArsNouveau.MODID)
public class ModEntities {
public static final EntityType<EntityProjectileSpell> SPELL_PROJ = null;
// public static void init() {
// // Every entity in our mod has an ID (local to this mod)
// int id<SUF>
// EntityRegistry.registerModEntity(new ResourceLocation(""), EntityProjectileSpell.class, "ProjectileSpell", id++, ExampleMod.instance, 64, 3, true);
//// EntityRegistry.registerModEntity(EntityWeirdZombie.class, "WeirdZombie", id++, ModTut.instance, 64, 3, true, 0x996600, 0x00ff00);
////
//// // We want our mob to spawn in Plains and ice plains biomes. If you don't add this then it will not spawn automatically
//// // but you can of course still make it spawn manually
//// EntityRegistry.addSpawn(EntityWeirdZombie.class, 100, 3, 5, EnumCreatureType.MONSTER, Biomes.PLAINS, Biomes.ICE_PLAINS);
////
//// // This is the loot table for our mob
//// LootTableList.register(EntityWeirdZombie.LOOT);
// }
@Mod.EventBusSubscriber(modid = ArsNouveau.MODID, bus= Mod.EventBusSubscriber.Bus.MOD)
public static class RegistrationHandler {
public static final int lightballID = 29;
/**
* Register this mod's {@link Entity} types.
*
* @param event The event
*/
@SubscribeEvent
public static void registerEntities(final RegistryEvent.Register<EntityType<?>> event) {
System.out.println("Registered entitites");
// final EntityEntry[] entries = {
// createBuilder("mod_projectile_spell")
// .entity(EntityProjectileSpell.class)
// .tracker(64, 20, false)
// .build(),
//
//
// };
final EntityType<EntityProjectileSpell> spell_proj = build(
"spell_proj",
EntityType.Builder.<EntityProjectileSpell>create(EntityProjectileSpell::new, EntityClassification.MISC)
.size(0.5f, 0.5f)
.setTrackingRange(10)
.setShouldReceiveVelocityUpdates(true)
.setUpdateInterval(60).setCustomClientFactory(EntityProjectileSpell::new));
final EntityType<EntityEvokerFangs> evokerFangs = build(
"fangs",
EntityType.Builder.<EntityEvokerFangs>create(EntityEvokerFangs::new, EntityClassification.MISC)
.size(0.5F, 0.8F)
.setUpdateInterval(60));
final EntityType<EntityAllyVex> allyVex = build(
"ally_vex",
EntityType.Builder.<EntityAllyVex>create(EntityAllyVex::new, EntityClassification.MISC)
.size(0.4F, 0.8F).immuneToFire()
.setUpdateInterval(60));
event.getRegistry().registerAll(
spell_proj,
evokerFangs,
allyVex
);
//ENT_PROJECTILE = registerEntity(EntityType.Builder.<EntityModProjectile>create(EntityClassification.MISC).setCustomClientFactory(EntityModProjectile::new).size(0.25F, 0.25F), "ent_projectile");
// EntityRegistry.registerModEntity(new ResourceLocation(ExampleMod.MODID, "dmlightball"),
// EntityProjectileSpell.class, ExampleMod.MODID + ".dmlightball", lightballID, ExampleMod.instance,
// 80, 20, true);
//event.getRegistry().registerAll(entries);
}
}
/**
* Build an {@link EntityType} from a {@link EntityType.Builder} using the specified name.
*
* @param name The entity type name
* @param builder The entity type builder to build
* @return The built entity type
*/
private static <T extends Entity> EntityType<T> build(final String name, final EntityType.Builder<T> builder) {
final ResourceLocation registryName = new ResourceLocation(ArsNouveau.MODID, name);
final EntityType<T> entityType = builder
.build(registryName.toString());
entityType.setRegistryName(registryName);
return entityType;
}
}
| False | 1,032 | 8 | 1,178 | 8 | 1,182 | 8 | 1,178 | 8 | 1,375 | 8 | false | false | false | false | false | true |
906 | 124743_29 | package com.bai.util;
import static java.lang.Integer.parseInt;
import com.bai.checkers.CheckerManager;
import ghidra.util.exception.InvalidInputException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Configuration class.
*/
public class Config {
/**
* The config parser for headless mode arguments.
*/
public static class HeadlessParser {
private static boolean checkArgument(String optionName, String[] args, int argi)
throws InvalidInputException {
// everything after this requires an argument
if (!optionName.equalsIgnoreCase(args[argi])) {
return false;
}
if (argi + 1 == args.length) {
throw new InvalidInputException(optionName + " requires an argument");
}
return true;
}
private static String[] getSubArguments(String[] args, int argi) {
List<String> subArgs = new LinkedList<>();
int i = argi + 1;
while (i < args.length && !args[i].startsWith("-")) {
subArgs.add(args[i++]);
}
return subArgs.toArray(new String[0]);
}
private static void usage() {
System.out.println("Usage: ");
System.out.println(
"analyzeHeadless <project_location> <project_name[/folder_path]> -import <file>");
System.out.println("-postScript BinAbsInspector.java \"@@<script parameters>\"");
System.out.println("where <script parameters> in following format: ");
System.out.println(" [-K <kElement>]");
System.out.println(" [-callStringK <callStringMaxLen>]");
System.out.println(" [-Z3Timeout <timeout>]");
System.out.println(" [-timeout <timeout>]");
System.out.println(" [-entry <address>]");
System.out.println(" [-externalMap <file>]");
System.out.println(" [-json]");
System.out.println(" [-disableZ3]");
System.out.println(" [-all]");
System.out.println(" [-debug]");
System.out.println(" [-PreserveCalleeSavedReg]");
System.out.println(" [-check \"<cweNo1>[;<cweNo2>...]\"]");
}
public static Config parseConfig(String fullArgs) {
Config config = new Config();
if (fullArgs.isEmpty()) {
return config;
}
if (fullArgs.getBytes()[0] != '@' && fullArgs.getBytes()[1] != '@') {
System.out.println("Wrong parameters: <script parameters> should start with '@@'");
usage();
System.exit(-1);
}
try {
String[] args = fullArgs.substring(2).split(" ");
for (int argi = 0; argi < args.length; argi++) {
String arg = args[argi];
if (checkArgument("-K", args, argi)) {
config.setK(parseInt(args[++argi]));
} else if (checkArgument("-callStringK", args, argi)) {
config.setCallStringK(parseInt(args[++argi]));
} else if (checkArgument("-Z3Timeout", args, argi)) {
config.setZ3TimeOut(parseInt(args[++argi]));
} else if (checkArgument("-timeout", args, argi)) {
config.setTimeout(parseInt(args[++argi]));
} else if (checkArgument("-entry", args, argi)) {
config.setEntryAddress(args[++argi]);
} else if (checkArgument("-externalMap", args, argi)) {
config.setExternalMapPath(args[++argi]);
} else if (arg.equalsIgnoreCase("-json")) {
config.setOutputJson(true);
} else if (arg.equalsIgnoreCase("-disableZ3")) {
config.setEnableZ3(false);
} else if (arg.equalsIgnoreCase("-all")) {
CheckerManager.loadAllCheckers(config);
} else if (arg.equalsIgnoreCase("-debug")) {
config.setDebug(true);
} else if (arg.equalsIgnoreCase("-preserveCalleeSavedReg")) {
config.setPreserveCalleeSavedReg(true);
} else if (checkArgument("-check", args, argi)) {
String[] checkers = getSubArguments(args, argi);
Arrays.stream(checkers)
.filter(CheckerManager::hasChecker)
.forEach(config::addChecker);
argi += checkers.length;
}
}
} catch (InvalidInputException | IllegalArgumentException e) {
System.out.println("Fail to parse config from: \"" + fullArgs + "\"");
usage();
System.exit(-1);
}
System.out.println("Loaded config: " + config);
return config;
}
}
private static final int DEFAULT_Z3_TIMEOUT = 1000; // unit in millisecond
private static final int DEFAULT_CALLSTRING_K = 3;
private static final int DEFAULT_K = 50;
private static final int DEFAULT_TIMEOUT = -1; // unit in second, no timeout by default
private int z3TimeOut;
private boolean isDebug;
private boolean isOutputJson;
@SuppressWarnings("checkstyle:MemberName")
private int K;
private int callStringK;
private List<String> checkers = new ArrayList<>();
private String entryAddress;
private int timeout;
private boolean isEnableZ3;
private String externalMapPath;
private boolean isGUI;
private boolean preserveCalleeSavedReg;
// for tactic tuning, see:
// http://www.cs.tau.ac.il/~msagiv/courses/asv/z3py/strategies-examples.htm
private List<String> z3Tactics = new ArrayList<>();
public Config() {
// default config
this.callStringK = DEFAULT_CALLSTRING_K;
this.K = DEFAULT_K;
this.isDebug = false;
this.isOutputJson = false;
this.z3TimeOut = DEFAULT_Z3_TIMEOUT; // ms
this.timeout = DEFAULT_TIMEOUT;
this.entryAddress = null;
this.isEnableZ3 = true;
this.externalMapPath = null;
this.preserveCalleeSavedReg = false;
}
/**
* Get the timeout (millisecond) for z3 constraint solving.
* @return the timeout (millisecond).
*/
public int getZ3TimeOut() {
return z3TimeOut;
}
/**
* Set the timeout (millisecond) for z3 constraint solving.
* @param z3TimeOut the timeout (millisecond).
*/
public void setZ3TimeOut(int z3TimeOut) {
this.z3TimeOut = z3TimeOut;
}
/**
* Get a list of z3 tactic names.
* @return the list of z3 tactic names.
*/
public List<String> getZ3Tactics() {
return z3Tactics;
}
/**
* Checks if in debug config.
* @return true if in debug config, false otherwise.
*/
public boolean isDebug() {
return isDebug;
}
/**
* Set debug config.
* @param debug in debug config or not.
*/
public void setDebug(boolean debug) {
this.isDebug = debug;
}
/**
* Check if using json output.
* @return ture if using json output, false otherwise.
*/
public boolean isOutputJson() {
return isOutputJson;
}
/**
* Set json output
* @param isOutputJson use json format output or not.
*/
public void setOutputJson(boolean isOutputJson) {
this.isOutputJson = isOutputJson;
}
/**
* Get the K parameter.
* @return the K parameter.
*/
public int getK() {
return K;
}
/**
* Set the K parameter.
* @param k the K parameter.
*/
public void setK(int k) {
K = k;
}
/**
* Get the call string max length: K.
* @return the call string k.
*/
public int getCallStringK() {
return callStringK;
}
/**
* Set the call string max length: K.
* @param callStringK the call string k.
*/
public void setCallStringK(int callStringK) {
this.callStringK = callStringK;
}
/**
* Get a list of checker names to run.
* @return a list of checker names.
*/
public List<String> getCheckers() {
return checkers;
}
/**
* Add a checker to run.
* @param name the checker name.
*/
public void addChecker(String name) {
checkers.add(name);
}
/**
* Clear all checkers config.
*/
public void clearCheckers() {
checkers.clear();
}
/**
* Get the analysis timeout (in second).
* @return the analysis timout (in second).
*/
public int getTimeout() {
return timeout;
}
/**
* Set the analysis timeout (in second).
* @param timeout the analysis timout (in second).
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* Get the entry address string.
* @return the entry address string.
*/
public String getEntryAddress() {
return entryAddress;
}
/**
* Set the entry address, accept format of decimal or hexadecimal.
* @param entryAddress the entry address.
*/
public void setEntryAddress(String entryAddress) {
this.entryAddress = entryAddress;
}
/**
* Checks if enable z3 constraint solving.
* @return true if enabled, false otherwise.
*/
public boolean isEnableZ3() {
return isEnableZ3;
}
/**
* Enable z3 config.
* @param enableZ3 enable or not.
*/
public void setEnableZ3(boolean enableZ3) {
isEnableZ3 = enableZ3;
}
/**
* Get the path of external map config json file.
* @return the file path.
*/
public String getExternalMapPath() {
return externalMapPath;
}
/**
* Set the path of external map config json file.
* @param externalMapPath the file path.
*/
public void setExternalMapPath(String externalMapPath) {
this.externalMapPath = externalMapPath;
}
/**
* Checks if running in GUI mode.
* @return true if in GUI mode, false otherwise.
*/
public boolean isGUI() {
return isGUI;
}
/**
* @hidden
* @param isGUI
*/
public void setGUI(boolean isGUI) {
this.isGUI = isGUI;
}
/**
* Preserve the callee saved registers.
* @param preserveCalleeSavedReg preserve or not.
*/
public void setPreserveCalleeSavedReg(boolean preserveCalleeSavedReg) {
this.preserveCalleeSavedReg = preserveCalleeSavedReg;
}
/**
* Get if the callee saved registers are preserved.
* @return true if preserved, false otherwise.
*/
public boolean getPreserveCalleeSavedReg() {
return preserveCalleeSavedReg;
}
@Override
public String toString() {
return "Config{"
+ "z3TimeOut=" + z3TimeOut
+ ", isDebug=" + isDebug
+ ", isOutputJson=" + isOutputJson
+ ", K=" + K
+ ", callStringK=" + callStringK
+ ", checkers=" + checkers
+ ", entryAddress='" + entryAddress + '\''
+ ", timeout=" + timeout
+ ", isEnableZ3=" + isEnableZ3
+ ", z3Tactics=" + z3Tactics
+ ", externalMapPath=" + externalMapPath
+ '}';
}
}
| KeenSecurityLab/BinAbsInspector | src/main/java/com/bai/util/Config.java | 3,334 | /**
* @hidden
* @param isGUI
*/ | block_comment | nl | package com.bai.util;
import static java.lang.Integer.parseInt;
import com.bai.checkers.CheckerManager;
import ghidra.util.exception.InvalidInputException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Configuration class.
*/
public class Config {
/**
* The config parser for headless mode arguments.
*/
public static class HeadlessParser {
private static boolean checkArgument(String optionName, String[] args, int argi)
throws InvalidInputException {
// everything after this requires an argument
if (!optionName.equalsIgnoreCase(args[argi])) {
return false;
}
if (argi + 1 == args.length) {
throw new InvalidInputException(optionName + " requires an argument");
}
return true;
}
private static String[] getSubArguments(String[] args, int argi) {
List<String> subArgs = new LinkedList<>();
int i = argi + 1;
while (i < args.length && !args[i].startsWith("-")) {
subArgs.add(args[i++]);
}
return subArgs.toArray(new String[0]);
}
private static void usage() {
System.out.println("Usage: ");
System.out.println(
"analyzeHeadless <project_location> <project_name[/folder_path]> -import <file>");
System.out.println("-postScript BinAbsInspector.java \"@@<script parameters>\"");
System.out.println("where <script parameters> in following format: ");
System.out.println(" [-K <kElement>]");
System.out.println(" [-callStringK <callStringMaxLen>]");
System.out.println(" [-Z3Timeout <timeout>]");
System.out.println(" [-timeout <timeout>]");
System.out.println(" [-entry <address>]");
System.out.println(" [-externalMap <file>]");
System.out.println(" [-json]");
System.out.println(" [-disableZ3]");
System.out.println(" [-all]");
System.out.println(" [-debug]");
System.out.println(" [-PreserveCalleeSavedReg]");
System.out.println(" [-check \"<cweNo1>[;<cweNo2>...]\"]");
}
public static Config parseConfig(String fullArgs) {
Config config = new Config();
if (fullArgs.isEmpty()) {
return config;
}
if (fullArgs.getBytes()[0] != '@' && fullArgs.getBytes()[1] != '@') {
System.out.println("Wrong parameters: <script parameters> should start with '@@'");
usage();
System.exit(-1);
}
try {
String[] args = fullArgs.substring(2).split(" ");
for (int argi = 0; argi < args.length; argi++) {
String arg = args[argi];
if (checkArgument("-K", args, argi)) {
config.setK(parseInt(args[++argi]));
} else if (checkArgument("-callStringK", args, argi)) {
config.setCallStringK(parseInt(args[++argi]));
} else if (checkArgument("-Z3Timeout", args, argi)) {
config.setZ3TimeOut(parseInt(args[++argi]));
} else if (checkArgument("-timeout", args, argi)) {
config.setTimeout(parseInt(args[++argi]));
} else if (checkArgument("-entry", args, argi)) {
config.setEntryAddress(args[++argi]);
} else if (checkArgument("-externalMap", args, argi)) {
config.setExternalMapPath(args[++argi]);
} else if (arg.equalsIgnoreCase("-json")) {
config.setOutputJson(true);
} else if (arg.equalsIgnoreCase("-disableZ3")) {
config.setEnableZ3(false);
} else if (arg.equalsIgnoreCase("-all")) {
CheckerManager.loadAllCheckers(config);
} else if (arg.equalsIgnoreCase("-debug")) {
config.setDebug(true);
} else if (arg.equalsIgnoreCase("-preserveCalleeSavedReg")) {
config.setPreserveCalleeSavedReg(true);
} else if (checkArgument("-check", args, argi)) {
String[] checkers = getSubArguments(args, argi);
Arrays.stream(checkers)
.filter(CheckerManager::hasChecker)
.forEach(config::addChecker);
argi += checkers.length;
}
}
} catch (InvalidInputException | IllegalArgumentException e) {
System.out.println("Fail to parse config from: \"" + fullArgs + "\"");
usage();
System.exit(-1);
}
System.out.println("Loaded config: " + config);
return config;
}
}
private static final int DEFAULT_Z3_TIMEOUT = 1000; // unit in millisecond
private static final int DEFAULT_CALLSTRING_K = 3;
private static final int DEFAULT_K = 50;
private static final int DEFAULT_TIMEOUT = -1; // unit in second, no timeout by default
private int z3TimeOut;
private boolean isDebug;
private boolean isOutputJson;
@SuppressWarnings("checkstyle:MemberName")
private int K;
private int callStringK;
private List<String> checkers = new ArrayList<>();
private String entryAddress;
private int timeout;
private boolean isEnableZ3;
private String externalMapPath;
private boolean isGUI;
private boolean preserveCalleeSavedReg;
// for tactic tuning, see:
// http://www.cs.tau.ac.il/~msagiv/courses/asv/z3py/strategies-examples.htm
private List<String> z3Tactics = new ArrayList<>();
public Config() {
// default config
this.callStringK = DEFAULT_CALLSTRING_K;
this.K = DEFAULT_K;
this.isDebug = false;
this.isOutputJson = false;
this.z3TimeOut = DEFAULT_Z3_TIMEOUT; // ms
this.timeout = DEFAULT_TIMEOUT;
this.entryAddress = null;
this.isEnableZ3 = true;
this.externalMapPath = null;
this.preserveCalleeSavedReg = false;
}
/**
* Get the timeout (millisecond) for z3 constraint solving.
* @return the timeout (millisecond).
*/
public int getZ3TimeOut() {
return z3TimeOut;
}
/**
* Set the timeout (millisecond) for z3 constraint solving.
* @param z3TimeOut the timeout (millisecond).
*/
public void setZ3TimeOut(int z3TimeOut) {
this.z3TimeOut = z3TimeOut;
}
/**
* Get a list of z3 tactic names.
* @return the list of z3 tactic names.
*/
public List<String> getZ3Tactics() {
return z3Tactics;
}
/**
* Checks if in debug config.
* @return true if in debug config, false otherwise.
*/
public boolean isDebug() {
return isDebug;
}
/**
* Set debug config.
* @param debug in debug config or not.
*/
public void setDebug(boolean debug) {
this.isDebug = debug;
}
/**
* Check if using json output.
* @return ture if using json output, false otherwise.
*/
public boolean isOutputJson() {
return isOutputJson;
}
/**
* Set json output
* @param isOutputJson use json format output or not.
*/
public void setOutputJson(boolean isOutputJson) {
this.isOutputJson = isOutputJson;
}
/**
* Get the K parameter.
* @return the K parameter.
*/
public int getK() {
return K;
}
/**
* Set the K parameter.
* @param k the K parameter.
*/
public void setK(int k) {
K = k;
}
/**
* Get the call string max length: K.
* @return the call string k.
*/
public int getCallStringK() {
return callStringK;
}
/**
* Set the call string max length: K.
* @param callStringK the call string k.
*/
public void setCallStringK(int callStringK) {
this.callStringK = callStringK;
}
/**
* Get a list of checker names to run.
* @return a list of checker names.
*/
public List<String> getCheckers() {
return checkers;
}
/**
* Add a checker to run.
* @param name the checker name.
*/
public void addChecker(String name) {
checkers.add(name);
}
/**
* Clear all checkers config.
*/
public void clearCheckers() {
checkers.clear();
}
/**
* Get the analysis timeout (in second).
* @return the analysis timout (in second).
*/
public int getTimeout() {
return timeout;
}
/**
* Set the analysis timeout (in second).
* @param timeout the analysis timout (in second).
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* Get the entry address string.
* @return the entry address string.
*/
public String getEntryAddress() {
return entryAddress;
}
/**
* Set the entry address, accept format of decimal or hexadecimal.
* @param entryAddress the entry address.
*/
public void setEntryAddress(String entryAddress) {
this.entryAddress = entryAddress;
}
/**
* Checks if enable z3 constraint solving.
* @return true if enabled, false otherwise.
*/
public boolean isEnableZ3() {
return isEnableZ3;
}
/**
* Enable z3 config.
* @param enableZ3 enable or not.
*/
public void setEnableZ3(boolean enableZ3) {
isEnableZ3 = enableZ3;
}
/**
* Get the path of external map config json file.
* @return the file path.
*/
public String getExternalMapPath() {
return externalMapPath;
}
/**
* Set the path of external map config json file.
* @param externalMapPath the file path.
*/
public void setExternalMapPath(String externalMapPath) {
this.externalMapPath = externalMapPath;
}
/**
* Checks if running in GUI mode.
* @return true if in GUI mode, false otherwise.
*/
public boolean isGUI() {
return isGUI;
}
/**
* @hidden
<SUF>*/
public void setGUI(boolean isGUI) {
this.isGUI = isGUI;
}
/**
* Preserve the callee saved registers.
* @param preserveCalleeSavedReg preserve or not.
*/
public void setPreserveCalleeSavedReg(boolean preserveCalleeSavedReg) {
this.preserveCalleeSavedReg = preserveCalleeSavedReg;
}
/**
* Get if the callee saved registers are preserved.
* @return true if preserved, false otherwise.
*/
public boolean getPreserveCalleeSavedReg() {
return preserveCalleeSavedReg;
}
@Override
public String toString() {
return "Config{"
+ "z3TimeOut=" + z3TimeOut
+ ", isDebug=" + isDebug
+ ", isOutputJson=" + isOutputJson
+ ", K=" + K
+ ", callStringK=" + callStringK
+ ", checkers=" + checkers
+ ", entryAddress='" + entryAddress + '\''
+ ", timeout=" + timeout
+ ", isEnableZ3=" + isEnableZ3
+ ", z3Tactics=" + z3Tactics
+ ", externalMapPath=" + externalMapPath
+ '}';
}
}
| False | 2,594 | 15 | 2,755 | 13 | 3,053 | 16 | 2,755 | 13 | 3,324 | 17 | false | false | false | false | false | true |
1,132 | 141414_9 | /****************************************************************************
Copyright 2009, Colorado School of Mines and others.
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 edu.mines.jtk.sgl;
import java.awt.Color;
import edu.mines.jtk.dsp.*;
import static edu.mines.jtk.util.ArrayMath.*;
/**
* An axis-aligned panel that displays a slice of a 3D metric tensor field.
* The tensors correspond to symmetric positive-definite 3x3 matrices, and
* are rendered as ellipsoids.
* @author Chris Engelsma and Dave Hale, Colorado School of Mines.
* @version 2009.08.29
*/
public class TensorsPanel extends AxisAlignedPanel {
/**
* Constructs a tensors panel for the specified tensor field.
* Assumes default unit samplings.
* @param et the eigentensors; by reference, not by copy.
*/
public TensorsPanel(EigenTensors3 et) {
this(new Sampling(et.getN1()),
new Sampling(et.getN2()),
new Sampling(et.getN3()),
et);
}
/**
* Constructs a tensors panel for the specified tensor field.
* @param s1 sampling of 1st dimension (Z axis).
* @param s2 sampling of 2nd dimension (Y axis).
* @param s3 sampling of 3rd dimension (X axis).
* @param et the eigentensors; by reference, not by copy.
*/
public TensorsPanel(
Sampling s1, Sampling s2, Sampling s3, EigenTensors3 et)
{
_sx = s3;
_sy = s2;
_sz = s1;
_et = et;
_emax = findMaxEigenvalue();
setStates(StateSet.forTwoSidedShinySurface(Color.CYAN));
}
/**
* Updates the panel.
* This method should be called when the tensor field
* referenced by this tensors panel has been modified.
*/
public void update() {
dirtyDraw();
}
/**
* Sets the maximum size of the ellipsoids.
* As this size is increased, the number of ellipsoids decreases.
* @param size the maximum ellipsoid size, in samples.
*/
public void setEllipsoidSize(int size) {
_ellipsoidSize = size;
dirtyDraw();
}
/////////////////////////////////////////////////////////////////////////////
// protected
protected void draw(DrawContext dc) {
AxisAlignedFrame aaf = this.getFrame();
if (aaf==null)
return;
Axis axis = aaf.getAxis();
drawEllipsoids(axis);
}
/////////////////////////////////////////////////////////////////////////////
// private
private Sampling _sx,_sy,_sz;
private EigenTensors3 _et;
private float _emax;
private int _ellipsoidSize = 10;
private EllipsoidGlyph _eg = new EllipsoidGlyph();
/**
* Draws the tensors as ellipsoids.
*/
private void drawEllipsoids(Axis axis) {
// Tensor sampling.
int nx = _sx.getCount();
int ny = _sy.getCount();
int nz = _sz.getCount();
double dx = _sx.getDelta();
double dy = _sy.getDelta();
double dz = _sz.getDelta();
double fx = _sx.getFirst();
double fy = _sy.getFirst();
double fz = _sz.getFirst();
// Min/max (x,y,z) coordinates.
double xmin = _sx.getFirst();
double xmax = _sx.getLast();
double ymin = _sy.getFirst();
double ymax = _sy.getLast();
double zmin = _sz.getFirst();
double zmax = _sz.getLast();
// Maximum length of eigenvectors u, v and w.
float dmax = 0.5f*_ellipsoidSize;
float dxmax = (float)dx*dmax;
float dymax = (float)dy*dmax;
float dzmax = (float)dz*dmax;
// Distance between ellipsoid centers (in samples).
int kec = (int)(2.0*dmax);
// Scaling factor for the eigenvectors.
float scale = dmax/sqrt(_emax);
// Smallest eigenvalue permitted.
float etiny = 0.0001f*_emax;
// Current frame.
AxisAlignedFrame aaf = this.getFrame();
if (axis==Axis.X) {
// Y-Axis.
int nyc = (int)((ymax-ymin)/(2.0f*dymax));
double dyc = kec*dy;
double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc);
int jyc = (int)(fyc/dy);
// Z-Axis.
int nzc = (int)((zmax-zmin)/(2.0f*dzmax));
double dzc = kec*dz;
double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc);
int jzc = (int)(fzc/dz);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// X-Axis.
float xc = 0.5f*(float)(xmax+xmin);
int ix = _sx.indexOfNearest(xc);
for (int iy=jyc; iy<ny; iy+=kec) {
float yc = (float)(fy+iy*dy);
if (ymin<yc-dymax && yc+dymax<ymax) {
for (int iz=jzc; iz<nz; iz+=kec) {
float zc = (float)(fz+iz*dz);
if (zmin<zc-dzmax && zc+dzmax<zmax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
} else if (axis==Axis.Y) {
// X-Axis.
int nxc = (int)((xmax-xmin)/(2.0f*dxmax));
double dxc = kec*dx;
double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc);
int jxc = (int)(fxc/dx);
// Z-Axis.
int nzc = (int)((zmax-zmin)/(2.0f*dzmax));
double dzc = kec*dz;
double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc);
int jzc = (int)(fzc/dz);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// Y-Axis.
float yc = 0.5f*(float)(ymax+ymin);
int iy = _sy.indexOfNearest(yc);
for (int ix=jxc; ix<nx; ix+=kec) {
float xc = (float)(fx+ix*dx);
if (xmin<xc-dxmax && xc+dxmax<xmax) {
for (int iz=jzc; iz<nz; iz+=kec) {
float zc = (float)(fz+iz*dz);
if (zmin<zc-dzmax && zc+dzmax<zmax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
} else if (axis==Axis.Z) {
// X-Axis.
int nxc = (int)((xmax-xmin)/(2.0f*dxmax));
double dxc = kec*dx;
double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc);
int jxc = (int)(fxc/dx);
// Y-Axis.
int nyc = (int)((ymax-ymin)/(2.0f*dymax));
double dyc = kec*dy;
double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc);
int jyc = (int)(fyc/dy);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// Z-Axis.
float zc = 0.5f*(float)(zmax+zmin);
int iz = _sz.indexOfNearest(zc);
for (int ix=jxc; ix<nx; ix+=kec) {
float xc = (float)(fx+ix*dx);
if (xmin<xc-dxmax && xc+dxmax<xmax) {
for (int iy=jyc; iy<ny; iy+=kec) {
float yc = (float)(fy+iy*dy);
if (ymin<yc-dymax && yc+dymax<ymax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
}
}
/**
* Finds the largest eigenvalue to be used for scaling.
*/
private float findMaxEigenvalue() {
int n1 = _et.getN1();
int n2 = _et.getN2();
int n3 = _et.getN3();
float[] e = new float[3];
float emax = 0.0f;
for (int i3=0; i3<n3; ++i3) {
for (int i2=0; i2<n2; ++i2) {
for (int i1=0; i1<n1; ++i1) {
_et.getEigenvalues(i1,i2,i3,e);
float emaxi = max(e[0],e[1],e[2]);
if (emax<emaxi)
emax = emaxi;
}
}
}
return emax;
}
}
| MinesJTK/jtk | core/src/main/java/edu/mines/jtk/sgl/TensorsPanel.java | 4,182 | // Distance between ellipsoid centers (in samples). | line_comment | nl | /****************************************************************************
Copyright 2009, Colorado School of Mines and others.
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 edu.mines.jtk.sgl;
import java.awt.Color;
import edu.mines.jtk.dsp.*;
import static edu.mines.jtk.util.ArrayMath.*;
/**
* An axis-aligned panel that displays a slice of a 3D metric tensor field.
* The tensors correspond to symmetric positive-definite 3x3 matrices, and
* are rendered as ellipsoids.
* @author Chris Engelsma and Dave Hale, Colorado School of Mines.
* @version 2009.08.29
*/
public class TensorsPanel extends AxisAlignedPanel {
/**
* Constructs a tensors panel for the specified tensor field.
* Assumes default unit samplings.
* @param et the eigentensors; by reference, not by copy.
*/
public TensorsPanel(EigenTensors3 et) {
this(new Sampling(et.getN1()),
new Sampling(et.getN2()),
new Sampling(et.getN3()),
et);
}
/**
* Constructs a tensors panel for the specified tensor field.
* @param s1 sampling of 1st dimension (Z axis).
* @param s2 sampling of 2nd dimension (Y axis).
* @param s3 sampling of 3rd dimension (X axis).
* @param et the eigentensors; by reference, not by copy.
*/
public TensorsPanel(
Sampling s1, Sampling s2, Sampling s3, EigenTensors3 et)
{
_sx = s3;
_sy = s2;
_sz = s1;
_et = et;
_emax = findMaxEigenvalue();
setStates(StateSet.forTwoSidedShinySurface(Color.CYAN));
}
/**
* Updates the panel.
* This method should be called when the tensor field
* referenced by this tensors panel has been modified.
*/
public void update() {
dirtyDraw();
}
/**
* Sets the maximum size of the ellipsoids.
* As this size is increased, the number of ellipsoids decreases.
* @param size the maximum ellipsoid size, in samples.
*/
public void setEllipsoidSize(int size) {
_ellipsoidSize = size;
dirtyDraw();
}
/////////////////////////////////////////////////////////////////////////////
// protected
protected void draw(DrawContext dc) {
AxisAlignedFrame aaf = this.getFrame();
if (aaf==null)
return;
Axis axis = aaf.getAxis();
drawEllipsoids(axis);
}
/////////////////////////////////////////////////////////////////////////////
// private
private Sampling _sx,_sy,_sz;
private EigenTensors3 _et;
private float _emax;
private int _ellipsoidSize = 10;
private EllipsoidGlyph _eg = new EllipsoidGlyph();
/**
* Draws the tensors as ellipsoids.
*/
private void drawEllipsoids(Axis axis) {
// Tensor sampling.
int nx = _sx.getCount();
int ny = _sy.getCount();
int nz = _sz.getCount();
double dx = _sx.getDelta();
double dy = _sy.getDelta();
double dz = _sz.getDelta();
double fx = _sx.getFirst();
double fy = _sy.getFirst();
double fz = _sz.getFirst();
// Min/max (x,y,z) coordinates.
double xmin = _sx.getFirst();
double xmax = _sx.getLast();
double ymin = _sy.getFirst();
double ymax = _sy.getLast();
double zmin = _sz.getFirst();
double zmax = _sz.getLast();
// Maximum length of eigenvectors u, v and w.
float dmax = 0.5f*_ellipsoidSize;
float dxmax = (float)dx*dmax;
float dymax = (float)dy*dmax;
float dzmax = (float)dz*dmax;
// Distance between<SUF>
int kec = (int)(2.0*dmax);
// Scaling factor for the eigenvectors.
float scale = dmax/sqrt(_emax);
// Smallest eigenvalue permitted.
float etiny = 0.0001f*_emax;
// Current frame.
AxisAlignedFrame aaf = this.getFrame();
if (axis==Axis.X) {
// Y-Axis.
int nyc = (int)((ymax-ymin)/(2.0f*dymax));
double dyc = kec*dy;
double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc);
int jyc = (int)(fyc/dy);
// Z-Axis.
int nzc = (int)((zmax-zmin)/(2.0f*dzmax));
double dzc = kec*dz;
double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc);
int jzc = (int)(fzc/dz);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// X-Axis.
float xc = 0.5f*(float)(xmax+xmin);
int ix = _sx.indexOfNearest(xc);
for (int iy=jyc; iy<ny; iy+=kec) {
float yc = (float)(fy+iy*dy);
if (ymin<yc-dymax && yc+dymax<ymax) {
for (int iz=jzc; iz<nz; iz+=kec) {
float zc = (float)(fz+iz*dz);
if (zmin<zc-dzmax && zc+dzmax<zmax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
} else if (axis==Axis.Y) {
// X-Axis.
int nxc = (int)((xmax-xmin)/(2.0f*dxmax));
double dxc = kec*dx;
double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc);
int jxc = (int)(fxc/dx);
// Z-Axis.
int nzc = (int)((zmax-zmin)/(2.0f*dzmax));
double dzc = kec*dz;
double fzc = 0.5f*((zmax-zmin)-(nzc-1)*dzc);
int jzc = (int)(fzc/dz);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// Y-Axis.
float yc = 0.5f*(float)(ymax+ymin);
int iy = _sy.indexOfNearest(yc);
for (int ix=jxc; ix<nx; ix+=kec) {
float xc = (float)(fx+ix*dx);
if (xmin<xc-dxmax && xc+dxmax<xmax) {
for (int iz=jzc; iz<nz; iz+=kec) {
float zc = (float)(fz+iz*dz);
if (zmin<zc-dzmax && zc+dzmax<zmax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
} else if (axis==Axis.Z) {
// X-Axis.
int nxc = (int)((xmax-xmin)/(2.0f*dxmax));
double dxc = kec*dx;
double fxc = 0.5f*((xmax-xmin)-(nxc-1)*dxc);
int jxc = (int)(fxc/dx);
// Y-Axis.
int nyc = (int)((ymax-ymin)/(2.0f*dymax));
double dyc = kec*dy;
double fyc = 0.5f*((ymax-ymin)-(nyc-1)*dyc);
int jyc = (int)(fyc/dy);
xmin = aaf.getCornerMin().x;
xmax = aaf.getCornerMax().x;
ymin = aaf.getCornerMin().y;
ymax = aaf.getCornerMax().y;
zmin = aaf.getCornerMin().z;
zmax = aaf.getCornerMax().z;
// Z-Axis.
float zc = 0.5f*(float)(zmax+zmin);
int iz = _sz.indexOfNearest(zc);
for (int ix=jxc; ix<nx; ix+=kec) {
float xc = (float)(fx+ix*dx);
if (xmin<xc-dxmax && xc+dxmax<xmax) {
for (int iy=jyc; iy<ny; iy+=kec) {
float yc = (float)(fy+iy*dy);
if (ymin<yc-dymax && yc+dymax<ymax) {
float[] e = _et.getEigenvalues(iz,iy,ix);
float[] u = _et.getEigenvectorU(iz,iy,ix);
float[] v = _et.getEigenvectorV(iz,iy,ix);
float[] w = _et.getEigenvectorW(iz,iy,ix);
float eu = e[0], ev = e[1], ew = e[2];
if (eu<=etiny) eu = etiny;
if (ev<=etiny) ev = etiny;
if (ew<=etiny) ew = etiny;
float uz = u[0], uy = u[1], ux = u[2];
float vz = v[0], vy = v[1], vx = v[2];
float wz = w[0], wy = w[1], wx = w[2];
float su = scale*sqrt(eu);
float sv = scale*sqrt(ev);
float sw = scale*sqrt(ew);
ux *= su*dx; uy *= su*dy; uz *= su*dz;
vx *= sv*dx; vy *= sv*dy; vz *= sv*dz;
wx *= sw*dx; wy *= sw*dy; wz *= sw*dz;
_eg.draw(xc,yc,zc,ux,uy,uz,vx,vy,vz,wx,wy,wz);
}
}
}
}
}
}
/**
* Finds the largest eigenvalue to be used for scaling.
*/
private float findMaxEigenvalue() {
int n1 = _et.getN1();
int n2 = _et.getN2();
int n3 = _et.getN3();
float[] e = new float[3];
float emax = 0.0f;
for (int i3=0; i3<n3; ++i3) {
for (int i2=0; i2<n2; ++i2) {
for (int i1=0; i1<n1; ++i1) {
_et.getEigenvalues(i1,i2,i3,e);
float emaxi = max(e[0],e[1],e[2]);
if (emax<emaxi)
emax = emaxi;
}
}
}
return emax;
}
}
| False | 3,260 | 10 | 3,465 | 11 | 3,629 | 9 | 3,468 | 11 | 4,082 | 13 | false | false | false | false | false | true |
1,380 | 70587_16 | package src;
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-JustDylan23 | src/TileEngine.java | 2,422 | // Toevoegen aan onze lokale array. Makkelijk om de tile op te halen | line_comment | nl | package src;
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<SUF>
// 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;
}
}
| True | 1,977 | 19 | 2,082 | 24 | 2,265 | 17 | 2,096 | 24 | 2,484 | 22 | false | false | false | false | false | true |
2,070 | 49880_4 | /*
* Geotoolkit.org - An Open Source Java GIS Toolkit
* http://www.geotoolkit.org
*
* (C) 2014, Geomatys
*
* This library 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 2.1 of the License.
*
* This library 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.
*/
package org.geotoolkit.processing.coverage.shadedrelief;
import org.apache.sis.parameter.ParameterBuilder;
import org.geotoolkit.coverage.grid.GridCoverage2D;
import org.geotoolkit.processing.AbstractProcessDescriptor;
import org.geotoolkit.process.Process;
import org.geotoolkit.process.ProcessDescriptor;
import org.geotoolkit.processing.GeotkProcessingRegistry;
import org.geotoolkit.processing.ProcessBundle;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.operation.MathTransform1D;
import org.opengis.util.InternationalString;
/**
*
* @author Johann Sorel (Geomatys)
*/
public class ShadedReliefDescriptor extends AbstractProcessDescriptor {
public static final String NAME = "coverage:shadedrelief";
public static final InternationalString abs = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_abstract);
/*
* Coverage base image
*/
public static final String IN_COVERAGE_PARAM_NAME = "inCoverage";
public static final InternationalString IN_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inCoverage);
public static final ParameterDescriptor<GridCoverage2D> COVERAGE = new ParameterBuilder()
.addName(IN_COVERAGE_PARAM_NAME)
.setRemarks(IN_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage2D.class, null);
/*
* Coverage elevation
*/
public static final String IN_ELEVATION_PARAM_NAME = "inElevation";
public static final InternationalString IN_ELEVATION_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<GridCoverage2D> ELEVATION = new ParameterBuilder()
.addName(IN_ELEVATION_PARAM_NAME)
.setRemarks(IN_ELEVATION_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage2D.class, null);
/*
* Coverage elevation value to meters
*/
public static final String IN_ELECONV_PARAM_NAME = "inEleEnv";
public static final InternationalString IN_ELECONV_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<MathTransform1D> ELECONV = new ParameterBuilder()
.addName(IN_ELECONV_PARAM_NAME)
.setRemarks(IN_ELECONV_PARAM_REMARKS)
.setRequired(true)
.create(MathTransform1D.class, null);
/**Input parameters */
public static final ParameterDescriptorGroup INPUT_DESC =
new ParameterBuilder().addName("InputParameters").createGroup(COVERAGE, ELEVATION, ELECONV);
/*
* Coverage result
*/
public static final String OUT_COVERAGE_PARAM_NAME = "outCoverage";
public static final InternationalString OUT_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_outCoverage);
public static final ParameterDescriptor<GridCoverage2D> OUTCOVERAGE = new ParameterBuilder()
.addName(OUT_COVERAGE_PARAM_NAME)
.setRemarks(OUT_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage2D.class, null);
/**Output parameters */
public static final ParameterDescriptorGroup OUTPUT_DESC = new ParameterBuilder().addName("OutputParameters").createGroup(OUTCOVERAGE);
public static final ProcessDescriptor INSTANCE = new ShadedReliefDescriptor();
private ShadedReliefDescriptor() {
super(NAME, GeotkProcessingRegistry.IDENTIFICATION, abs, INPUT_DESC, OUTPUT_DESC);
}
@Override
public Process createProcess(final ParameterValueGroup input) {
return new ShadedRelief(INSTANCE, input);
}
}
| anttileppa/geotoolkit | modules/processing/geotk-processing/src/main/java/org/geotoolkit/processing/coverage/shadedrelief/ShadedReliefDescriptor.java | 1,324 | /*
* Coverage elevation value to meters
*/ | block_comment | nl | /*
* Geotoolkit.org - An Open Source Java GIS Toolkit
* http://www.geotoolkit.org
*
* (C) 2014, Geomatys
*
* This library 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 2.1 of the License.
*
* This library 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.
*/
package org.geotoolkit.processing.coverage.shadedrelief;
import org.apache.sis.parameter.ParameterBuilder;
import org.geotoolkit.coverage.grid.GridCoverage2D;
import org.geotoolkit.processing.AbstractProcessDescriptor;
import org.geotoolkit.process.Process;
import org.geotoolkit.process.ProcessDescriptor;
import org.geotoolkit.processing.GeotkProcessingRegistry;
import org.geotoolkit.processing.ProcessBundle;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.operation.MathTransform1D;
import org.opengis.util.InternationalString;
/**
*
* @author Johann Sorel (Geomatys)
*/
public class ShadedReliefDescriptor extends AbstractProcessDescriptor {
public static final String NAME = "coverage:shadedrelief";
public static final InternationalString abs = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_abstract);
/*
* Coverage base image
*/
public static final String IN_COVERAGE_PARAM_NAME = "inCoverage";
public static final InternationalString IN_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inCoverage);
public static final ParameterDescriptor<GridCoverage2D> COVERAGE = new ParameterBuilder()
.addName(IN_COVERAGE_PARAM_NAME)
.setRemarks(IN_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage2D.class, null);
/*
* Coverage elevation
*/
public static final String IN_ELEVATION_PARAM_NAME = "inElevation";
public static final InternationalString IN_ELEVATION_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<GridCoverage2D> ELEVATION = new ParameterBuilder()
.addName(IN_ELEVATION_PARAM_NAME)
.setRemarks(IN_ELEVATION_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage2D.class, null);
/*
* Coverage elevation value<SUF>*/
public static final String IN_ELECONV_PARAM_NAME = "inEleEnv";
public static final InternationalString IN_ELECONV_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_inElevation);
public static final ParameterDescriptor<MathTransform1D> ELECONV = new ParameterBuilder()
.addName(IN_ELECONV_PARAM_NAME)
.setRemarks(IN_ELECONV_PARAM_REMARKS)
.setRequired(true)
.create(MathTransform1D.class, null);
/**Input parameters */
public static final ParameterDescriptorGroup INPUT_DESC =
new ParameterBuilder().addName("InputParameters").createGroup(COVERAGE, ELEVATION, ELECONV);
/*
* Coverage result
*/
public static final String OUT_COVERAGE_PARAM_NAME = "outCoverage";
public static final InternationalString OUT_COVERAGE_PARAM_REMARKS = ProcessBundle.formatInternational(ProcessBundle.Keys.coverage_shadedrelief_outCoverage);
public static final ParameterDescriptor<GridCoverage2D> OUTCOVERAGE = new ParameterBuilder()
.addName(OUT_COVERAGE_PARAM_NAME)
.setRemarks(OUT_COVERAGE_PARAM_REMARKS)
.setRequired(true)
.create(GridCoverage2D.class, null);
/**Output parameters */
public static final ParameterDescriptorGroup OUTPUT_DESC = new ParameterBuilder().addName("OutputParameters").createGroup(OUTCOVERAGE);
public static final ProcessDescriptor INSTANCE = new ShadedReliefDescriptor();
private ShadedReliefDescriptor() {
super(NAME, GeotkProcessingRegistry.IDENTIFICATION, abs, INPUT_DESC, OUTPUT_DESC);
}
@Override
public Process createProcess(final ParameterValueGroup input) {
return new ShadedRelief(INSTANCE, input);
}
}
| False | 983 | 11 | 1,140 | 10 | 1,122 | 12 | 1,140 | 10 | 1,358 | 14 | false | false | false | false | false | true |
2,839 | 200247_32 | /**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2013, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
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 + "'");
}
} | google-code-export/openhab | bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java | 2,883 | // in german Massentrom | line_comment | nl | /**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2013, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
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 + "'");
}
} | False | 2,269 | 6 | 2,689 | 7 | 2,490 | 6 | 2,689 | 7 | 3,216 | 7 | false | false | false | false | false | true |
3,714 | 8823_0 | package com.github.monkeywie.proxyee.util;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.AsciiString;
public class HttpUtil {
/**
* 检测url是否匹配
*/
public static boolean checkUrl(HttpRequest httpRequest, String regex) {
String host = httpRequest.headers().get(HttpHeaderNames.HOST);
if (host != null && regex != null) {
String url;
if (httpRequest.uri().indexOf("/") == 0) {
if (httpRequest.uri().length() > 1) {
url = host + httpRequest.uri();
} else {
url = host;
}
} else {
url = httpRequest.uri();
}
return url.matches(regex);
}
return false;
}
/**
* 检测头中的值是否为预期
*
* @param httpHeaders
* @param name
* @param regex
* @return
*/
public static boolean checkHeader(HttpHeaders httpHeaders, AsciiString name, String regex) {
String s = httpHeaders.get(name);
return s != null && s.matches(regex);
}
/**
* 检测是否为请求网页资源
*/
public static boolean isHtml(HttpRequest httpRequest, HttpResponse httpResponse) {
String accept = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
String contentType = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE);
return httpResponse.status().code() == 200 && accept != null && accept
.matches("^.*text/html.*$") && contentType != null && contentType
.matches("^text/html.*$");
}
}
| monkeyWie/proxyee | src/main/java/com/github/monkeywie/proxyee/util/HttpUtil.java | 509 | /**
* 检测url是否匹配
*/ | block_comment | nl | package com.github.monkeywie.proxyee.util;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.AsciiString;
public class HttpUtil {
/**
* 检测url是否匹配
<SUF>*/
public static boolean checkUrl(HttpRequest httpRequest, String regex) {
String host = httpRequest.headers().get(HttpHeaderNames.HOST);
if (host != null && regex != null) {
String url;
if (httpRequest.uri().indexOf("/") == 0) {
if (httpRequest.uri().length() > 1) {
url = host + httpRequest.uri();
} else {
url = host;
}
} else {
url = httpRequest.uri();
}
return url.matches(regex);
}
return false;
}
/**
* 检测头中的值是否为预期
*
* @param httpHeaders
* @param name
* @param regex
* @return
*/
public static boolean checkHeader(HttpHeaders httpHeaders, AsciiString name, String regex) {
String s = httpHeaders.get(name);
return s != null && s.matches(regex);
}
/**
* 检测是否为请求网页资源
*/
public static boolean isHtml(HttpRequest httpRequest, HttpResponse httpResponse) {
String accept = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
String contentType = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE);
return httpResponse.status().code() == 200 && accept != null && accept
.matches("^.*text/html.*$") && contentType != null && contentType
.matches("^text/html.*$");
}
}
| False | 382 | 13 | 421 | 10 | 462 | 11 | 421 | 10 | 524 | 19 | false | false | false | false | false | true |
4,134 | 74020_0 | package Controller;
import Firebase.FirebaseActionObserver;
import Firebase.FirebaseGameObserver;
import Firebase.FirebaseGameService;
import com.google.cloud.firestore.DocumentChange;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import javafx.application.Platform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FirebaseGameController implements FirebaseActionObserver {
private GameController gameCon;
private FirebaseGameService service;
private Map<String, FirebaseGameObserver> observers = new HashMap<>();
public FirebaseGameController(String gameName, GameController gameCon) {
this.gameCon = gameCon;
service = new FirebaseGameService(gameName);
turnActionListener(this);
}
private void placeAction(Map<String, Object> map) {
service.placeAction(getEventNumber(), map);
}
//Met 3 is het grootste aantal
private String getEventNumber(){
String id = String.valueOf(service.getLastestEventNumber());
StringBuilder str = new StringBuilder(id);
while(str.length() < 3) str.insert(0, "0");
return str.toString();
}
public void nextPhaseAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "phase");
map.put("id", "nextPhase");
map.put("action", "nextPhase");
placeAction(map);
}
public void buyCombiAction(int number) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "buy");
map.put("item", number);
placeAction(map);
}
public void addCombiAction(String race, String power) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "add");
map.put("race", race);
map.put("power", power);
placeAction(map);
}
public void attackAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "attack");
map.put("areaId", areaId);
placeAction(map);
}
public void addsFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "add");
map.put("areaId", areaId);
placeAction(map);
}
public void removeFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "remove");
map.put("areaId", areaId);
placeAction(map);
}
public void leavesFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "leaves");
map.put("areaId", areaId);
placeAction(map);
}
public void declineAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "decline");
map.put("action", "decline");
placeAction(map);
}
private void turnActionListener(final FirebaseActionObserver controller) {
service.actionListener(controller);
}
public void register(String id, FirebaseGameObserver observer) {
observers.put(id, observer);
}
@Override
public void update(QuerySnapshot qs) {
List<DocumentChange> updateList = qs.getDocumentChanges();
for (DocumentChange documentChange : updateList) {
DocumentSnapshot doc = documentChange.getDocument();
System.out.println("Id: " + doc.getId());
System.out.println(doc.getData());
Platform.runLater(() -> observers.get(doc.getString("division")).update(doc));
}
}
}
| realDragonium/SmallWorld3D | src/main/java/Controller/FirebaseGameController.java | 1,106 | //Met 3 is het grootste aantal | line_comment | nl | package Controller;
import Firebase.FirebaseActionObserver;
import Firebase.FirebaseGameObserver;
import Firebase.FirebaseGameService;
import com.google.cloud.firestore.DocumentChange;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import javafx.application.Platform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FirebaseGameController implements FirebaseActionObserver {
private GameController gameCon;
private FirebaseGameService service;
private Map<String, FirebaseGameObserver> observers = new HashMap<>();
public FirebaseGameController(String gameName, GameController gameCon) {
this.gameCon = gameCon;
service = new FirebaseGameService(gameName);
turnActionListener(this);
}
private void placeAction(Map<String, Object> map) {
service.placeAction(getEventNumber(), map);
}
//Met 3<SUF>
private String getEventNumber(){
String id = String.valueOf(service.getLastestEventNumber());
StringBuilder str = new StringBuilder(id);
while(str.length() < 3) str.insert(0, "0");
return str.toString();
}
public void nextPhaseAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "phase");
map.put("id", "nextPhase");
map.put("action", "nextPhase");
placeAction(map);
}
public void buyCombiAction(int number) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "buy");
map.put("item", number);
placeAction(map);
}
public void addCombiAction(String race, String power) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "add");
map.put("race", race);
map.put("power", power);
placeAction(map);
}
public void attackAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "attack");
map.put("areaId", areaId);
placeAction(map);
}
public void addsFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "add");
map.put("areaId", areaId);
placeAction(map);
}
public void removeFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "remove");
map.put("areaId", areaId);
placeAction(map);
}
public void leavesFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "leaves");
map.put("areaId", areaId);
placeAction(map);
}
public void declineAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "decline");
map.put("action", "decline");
placeAction(map);
}
private void turnActionListener(final FirebaseActionObserver controller) {
service.actionListener(controller);
}
public void register(String id, FirebaseGameObserver observer) {
observers.put(id, observer);
}
@Override
public void update(QuerySnapshot qs) {
List<DocumentChange> updateList = qs.getDocumentChanges();
for (DocumentChange documentChange : updateList) {
DocumentSnapshot doc = documentChange.getDocument();
System.out.println("Id: " + doc.getId());
System.out.println(doc.getData());
Platform.runLater(() -> observers.get(doc.getString("division")).update(doc));
}
}
}
| True | 824 | 9 | 961 | 11 | 1,027 | 8 | 961 | 11 | 1,088 | 9 | false | false | false | false | false | true |
1,683 | 174029_21 | package Graph;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Float;
import java.io.Serializable;
import org.openstreetmap.gui.jmapviewer.Coordinate;
import allgemein.Konstanten;
public class Kante implements Serializable, Comparable<Kante> {
private static final long serialVersionUID = 3225424268243577145L;
// StartKnoten
private final Knoten from;
// EndKnoten
private final Knoten to;
// Abstand der Start und Endknoten in Metern
private float abstand;
private Point2D.Float midPoint;
private String typ;
private boolean gesperrt;
private boolean erreichbar;
private float plastikMenge = 0f;
private float restMenge = 0f;
private float papierMenge = 0f;
private float bioMenge = 0f;
private float muellmenge = 0f;
public int id;
public Kante(Knoten from, Knoten to, boolean gesperrt, String typ) {
this.from = from;
this.to = to;
this.abstand = Kante.CalcDistance(from, to);
this.gesperrt = gesperrt;
this.typ = typ;
this.calcMidPoint();
this.calcMuellmenge();
}
// TODO Methode verteileMuell, die für jede Muellart den float Wert auf den
// Wert dert Variable muellmenge setzt
public void calcMuellmenge() {
this.muellmenge = Konstanten.getMengeTyp(this.typ) * this.abstand;
this.plastikMenge = muellmenge;
this.restMenge = muellmenge;
this.bioMenge = muellmenge;
this.papierMenge = muellmenge;
}
public void addMuell(float muell) {
this.muellmenge += muell;
this.bioMenge += muell;
this.papierMenge += muell;
this.plastikMenge += muell;
this.restMenge += muell;
}
/**
* Liefert die Menge fuer eine bestimmte Muellart (bei einem leeren String
* wird das Attribut muellMenge zurueckgeliefert)
*
* @param muellArt
* @return die Menge einer bestimmten Muellart
*/
public float getMuellMengeArt(String muellArt) {
if (muellArt.equals(allgemein.Konstanten.MUELLART_PLASTIK)) {
return plastikMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_REST)) {
return restMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_PAPIER)) {
return papierMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_BIO)) {
return bioMenge;
} else {
return this.muellmenge;
}
}
public void setMuellMengeArt(float muellMenge, String muellArt) {
if (muellArt.equals(allgemein.Konstanten.MUELLART_PLASTIK)) {
this.plastikMenge = muellMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_REST)) {
this.restMenge = muellMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_PAPIER)) {
this.papierMenge = muellMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_BIO)) {
this.bioMenge = muellMenge;
} else {
this.muellmenge = muellMenge;
}
}
public void setMuellMengeAll(float muellMenge) {
this.muellmenge = muellMenge;
this.bioMenge = muellMenge;
this.papierMenge = muellMenge;
this.plastikMenge = muellMenge;
this.restMenge = muellMenge;
}
public void setTyp(String typ) {
this.typ = typ;
}
public String getTyp() {
return this.typ;
}
public void setGeperrt(boolean gesperrt) {
this.gesperrt = gesperrt;
}
public boolean getGesperrt() {
return this.gesperrt;
}
public void setErreichbar(boolean erreichbar) {
this.erreichbar = erreichbar;
}
public boolean getErreichbar() {
return this.erreichbar;
}
public Knoten getTo() {
return this.to;
}
public Knoten getFrom() {
return this.from;
}
public float getAbstand() {
return this.abstand;
}
public void setAbstand(float abstand) {
this.abstand = abstand;
}
public Point2D.Float getMidPoint() {
return this.midPoint;
}
public void calcMidPoint() {
this.midPoint = new Point2D.Float((this.getTo().getLat() + this
.getFrom().getLat()) / 2, (this.getTo().getLon() + this
.getFrom().getLon()) / 2);
}
public Knoten getOther(Knoten knoten) {
if (knoten == from)
return to;
else if (knoten == to)
return from;
else
return null;
}
static private float CalcDistance(Knoten from, Knoten to) {
final int R = 6371; // Radius of the earth
float lat1 = from.getLat();
float lon1 = from.getLon();
float lat2 = to.getLat();
float lon2 = to.getLon();
Double latDistance = toRad(lat2 - lat1);
Double lonDistance = toRad(lon2 - lon1);
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(toRad(lat1)) * Math.cos(toRad(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
float abstand = (float) (R * c) * 1000;
return abstand;
}
private static Double toRad(float value) {
return value * Math.PI / 180;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
// result.append("[[abstand=" + this.abstand + "] [typ=" + this.typ
// + "] [erreichbar=" + this.erreichbar + "] [zu=" + this.gesperrt
// + "]]\n");
result.append(" " + to + "\n");
result.append(" " + from + "\n");
return result.toString();
}
@Override
public int compareTo(Kante k) {
if (this.getAbstand() == k.getAbstand())
return 0;
else if (this.getAbstand() > k.getAbstand())
return 1;
else
return -1;
}
}
// TODO vor Release entfernen, wenn nicht benoetigt
// public void writeExternal(ObjectOutput out) {
// try {
// System.out.println("Coming into the writeExternal of Kante :");
// out.writeFloat(abstand);
// out.writeObject(typ);
// out.writeBoolean(gesperrt);
// out.writeBoolean(erreichbar);
// out.writeBoolean(besucht);
// out.writeFloat(plastikMenge);
// out.writeFloat(restMenge);
// out.writeFloat(papierMenge);
// out.writeFloat(bioMenge);
// out.writeFloat(muellmenge);
// out.writeInt(id);
//
// // out.writeObject(innerObject);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// public void readExternal(ObjectInput in) {
// try {
// System.out.println("Coming into the readExternal of Kante:");
//
// min = (Point2D.Float) in.readObject();
// max = (Point2D.Float) in.readObject();
//
// // knoten = (ArrayList<Knoten>) in.readObject();
// int knotenAnzahl = in.readInt();
// knoten.clear();
// for (int i = 0; i < knotenAnzahl; i++) {
// knoten.add((Knoten) in.readObject());
// }
//
// plastik = (Knoten) in.readObject();
// papier = (Knoten) in.readObject();
// rest = (Knoten) in.readObject();
// bio = (Knoten) in.readObject();
// depot = (Knoten) in.readObject();
//
// // innerObject=(Obj)in.readObject();
// } catch (Exception e) {
// e.printStackTrace();
// }
// } | Tandrial/AI-SE-Bsc | SEP_SoSe13/Abnahme/SourceCode/Graph/Kante.java | 2,508 | // bio = (Knoten) in.readObject(); | line_comment | nl | package Graph;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Float;
import java.io.Serializable;
import org.openstreetmap.gui.jmapviewer.Coordinate;
import allgemein.Konstanten;
public class Kante implements Serializable, Comparable<Kante> {
private static final long serialVersionUID = 3225424268243577145L;
// StartKnoten
private final Knoten from;
// EndKnoten
private final Knoten to;
// Abstand der Start und Endknoten in Metern
private float abstand;
private Point2D.Float midPoint;
private String typ;
private boolean gesperrt;
private boolean erreichbar;
private float plastikMenge = 0f;
private float restMenge = 0f;
private float papierMenge = 0f;
private float bioMenge = 0f;
private float muellmenge = 0f;
public int id;
public Kante(Knoten from, Knoten to, boolean gesperrt, String typ) {
this.from = from;
this.to = to;
this.abstand = Kante.CalcDistance(from, to);
this.gesperrt = gesperrt;
this.typ = typ;
this.calcMidPoint();
this.calcMuellmenge();
}
// TODO Methode verteileMuell, die für jede Muellart den float Wert auf den
// Wert dert Variable muellmenge setzt
public void calcMuellmenge() {
this.muellmenge = Konstanten.getMengeTyp(this.typ) * this.abstand;
this.plastikMenge = muellmenge;
this.restMenge = muellmenge;
this.bioMenge = muellmenge;
this.papierMenge = muellmenge;
}
public void addMuell(float muell) {
this.muellmenge += muell;
this.bioMenge += muell;
this.papierMenge += muell;
this.plastikMenge += muell;
this.restMenge += muell;
}
/**
* Liefert die Menge fuer eine bestimmte Muellart (bei einem leeren String
* wird das Attribut muellMenge zurueckgeliefert)
*
* @param muellArt
* @return die Menge einer bestimmten Muellart
*/
public float getMuellMengeArt(String muellArt) {
if (muellArt.equals(allgemein.Konstanten.MUELLART_PLASTIK)) {
return plastikMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_REST)) {
return restMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_PAPIER)) {
return papierMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_BIO)) {
return bioMenge;
} else {
return this.muellmenge;
}
}
public void setMuellMengeArt(float muellMenge, String muellArt) {
if (muellArt.equals(allgemein.Konstanten.MUELLART_PLASTIK)) {
this.plastikMenge = muellMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_REST)) {
this.restMenge = muellMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_PAPIER)) {
this.papierMenge = muellMenge;
} else if (muellArt.equals(allgemein.Konstanten.MUELLART_BIO)) {
this.bioMenge = muellMenge;
} else {
this.muellmenge = muellMenge;
}
}
public void setMuellMengeAll(float muellMenge) {
this.muellmenge = muellMenge;
this.bioMenge = muellMenge;
this.papierMenge = muellMenge;
this.plastikMenge = muellMenge;
this.restMenge = muellMenge;
}
public void setTyp(String typ) {
this.typ = typ;
}
public String getTyp() {
return this.typ;
}
public void setGeperrt(boolean gesperrt) {
this.gesperrt = gesperrt;
}
public boolean getGesperrt() {
return this.gesperrt;
}
public void setErreichbar(boolean erreichbar) {
this.erreichbar = erreichbar;
}
public boolean getErreichbar() {
return this.erreichbar;
}
public Knoten getTo() {
return this.to;
}
public Knoten getFrom() {
return this.from;
}
public float getAbstand() {
return this.abstand;
}
public void setAbstand(float abstand) {
this.abstand = abstand;
}
public Point2D.Float getMidPoint() {
return this.midPoint;
}
public void calcMidPoint() {
this.midPoint = new Point2D.Float((this.getTo().getLat() + this
.getFrom().getLat()) / 2, (this.getTo().getLon() + this
.getFrom().getLon()) / 2);
}
public Knoten getOther(Knoten knoten) {
if (knoten == from)
return to;
else if (knoten == to)
return from;
else
return null;
}
static private float CalcDistance(Knoten from, Knoten to) {
final int R = 6371; // Radius of the earth
float lat1 = from.getLat();
float lon1 = from.getLon();
float lat2 = to.getLat();
float lon2 = to.getLon();
Double latDistance = toRad(lat2 - lat1);
Double lonDistance = toRad(lon2 - lon1);
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(toRad(lat1)) * Math.cos(toRad(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
float abstand = (float) (R * c) * 1000;
return abstand;
}
private static Double toRad(float value) {
return value * Math.PI / 180;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
// result.append("[[abstand=" + this.abstand + "] [typ=" + this.typ
// + "] [erreichbar=" + this.erreichbar + "] [zu=" + this.gesperrt
// + "]]\n");
result.append(" " + to + "\n");
result.append(" " + from + "\n");
return result.toString();
}
@Override
public int compareTo(Kante k) {
if (this.getAbstand() == k.getAbstand())
return 0;
else if (this.getAbstand() > k.getAbstand())
return 1;
else
return -1;
}
}
// TODO vor Release entfernen, wenn nicht benoetigt
// public void writeExternal(ObjectOutput out) {
// try {
// System.out.println("Coming into the writeExternal of Kante :");
// out.writeFloat(abstand);
// out.writeObject(typ);
// out.writeBoolean(gesperrt);
// out.writeBoolean(erreichbar);
// out.writeBoolean(besucht);
// out.writeFloat(plastikMenge);
// out.writeFloat(restMenge);
// out.writeFloat(papierMenge);
// out.writeFloat(bioMenge);
// out.writeFloat(muellmenge);
// out.writeInt(id);
//
// // out.writeObject(innerObject);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// public void readExternal(ObjectInput in) {
// try {
// System.out.println("Coming into the readExternal of Kante:");
//
// min = (Point2D.Float) in.readObject();
// max = (Point2D.Float) in.readObject();
//
// // knoten = (ArrayList<Knoten>) in.readObject();
// int knotenAnzahl = in.readInt();
// knoten.clear();
// for (int i = 0; i < knotenAnzahl; i++) {
// knoten.add((Knoten) in.readObject());
// }
//
// plastik = (Knoten) in.readObject();
// papier = (Knoten) in.readObject();
// rest = (Knoten) in.readObject();
// bio =<SUF>
// depot = (Knoten) in.readObject();
//
// // innerObject=(Obj)in.readObject();
// } catch (Exception e) {
// e.printStackTrace();
// }
// } | False | 2,029 | 12 | 2,505 | 13 | 2,271 | 11 | 2,505 | 13 | 2,644 | 13 | false | false | false | false | false | true |
1,546 | 95112_3 | package simu.test;_x000D_
import simu.eduni.distributions.Normal;_x000D_
import simu.framework.Kello;_x000D_
import simu.framework.ITapahtumanTyyppi;_x000D_
import simu.framework.Tapahtuma;_x000D_
_x000D_
import static simu.model.TapahtumanTyyppi.ARR1;_x000D_
import static simu.model.TapahtumanTyyppi.*;_x000D_
_x000D_
/** Saapumisprosessin test -luokka */_x000D_
public class SaapumisprosessiForTest {_x000D_
/** Tapahtumalista */_x000D_
private TapahtumalistaForTest tapahtumalista;_x000D_
/** Tapahtuman tyyppi */_x000D_
private ITapahtumanTyyppi tyyppi;_x000D_
_x000D_
/** Ulkomaan lentojen lahtoaika */_x000D_
private double ulkoLahtoAika;_x000D_
_x000D_
/** Lentojen vali */_x000D_
private double lentojenVali;_x000D_
_x000D_
/** Saapumisprosessin test -luokan konstruktori */_x000D_
public SaapumisprosessiForTest(TapahtumalistaForTest tl, ITapahtumanTyyppi tyyppi, double ulkoLahtoAika, double lentojenVali) {_x000D_
//this.generaattori = g;_x000D_
this.tapahtumalista = tl;_x000D_
this.tyyppi = tyyppi;_x000D_
this.ulkoLahtoAika = ulkoLahtoAika;_x000D_
this.lentojenVali = lentojenVali;_x000D_
}_x000D_
_x000D_
/** Metodi generoi seuraavat tapahtumat */_x000D_
public void generoiSeuraava() {_x000D_
_x000D_
// Lahtoaika ulkomaalennoille_x000D_
double ulkoLahtoAika = Kello.getInstance().getAika() + new Normal(this.ulkoLahtoAika, 5).sample();_x000D_
_x000D_
// Lahtoaika sisalennoille_x000D_
double lahtoAika = ulkoLahtoAika + this.lentojenVali; //new Normal(this.lentojenVali, 5).sample() ;_x000D_
_x000D_
// Luodaan tapahtuma "Ulkomaan lento"_x000D_
Tapahtuma tUlko = new Tapahtuma(tyyppi, ulkoLahtoAika, true);_x000D_
tapahtumalista.lisaa(tUlko);_x000D_
_x000D_
// Luodaan tapahtuma "Sisamaan lento"_x000D_
Tapahtuma tSisa = new Tapahtuma(SISA, lahtoAika, false);_x000D_
tapahtumalista.lisaa(tSisa);_x000D_
_x000D_
// Luodaan 10 tapahtumaa "Saapuva asiakas ulkomaalle"_x000D_
for (int i=0; i<10; i++) {_x000D_
Tapahtuma t1 = new Tapahtuma(ARR1, ulkoLahtoAika - (new Normal(240, 15).sample()), true);_x000D_
tapahtumalista.lisaa(t1);_x000D_
}_x000D_
_x000D_
// Luodaan 10 tapahtumaa "Saapuva asiakas sisalennolle"_x000D_
for (int i=0; i<10; i++) {_x000D_
Tapahtuma t2 = new Tapahtuma(ARR2, lahtoAika - (new Normal(240, 15).sample()), false);_x000D_
tapahtumalista.lisaa(t2);_x000D_
}_x000D_
}_x000D_
} | Sami-Juhani/AP-Simulation-Java | src/main/java/simu/test/SaapumisprosessiForTest.java | 877 | //this.generaattori = g;_x000D_ | line_comment | nl | package simu.test;_x000D_
import simu.eduni.distributions.Normal;_x000D_
import simu.framework.Kello;_x000D_
import simu.framework.ITapahtumanTyyppi;_x000D_
import simu.framework.Tapahtuma;_x000D_
_x000D_
import static simu.model.TapahtumanTyyppi.ARR1;_x000D_
import static simu.model.TapahtumanTyyppi.*;_x000D_
_x000D_
/** Saapumisprosessin test -luokka */_x000D_
public class SaapumisprosessiForTest {_x000D_
/** Tapahtumalista */_x000D_
private TapahtumalistaForTest tapahtumalista;_x000D_
/** Tapahtuman tyyppi */_x000D_
private ITapahtumanTyyppi tyyppi;_x000D_
_x000D_
/** Ulkomaan lentojen lahtoaika */_x000D_
private double ulkoLahtoAika;_x000D_
_x000D_
/** Lentojen vali */_x000D_
private double lentojenVali;_x000D_
_x000D_
/** Saapumisprosessin test -luokan konstruktori */_x000D_
public SaapumisprosessiForTest(TapahtumalistaForTest tl, ITapahtumanTyyppi tyyppi, double ulkoLahtoAika, double lentojenVali) {_x000D_
//this.generaattori =<SUF>
this.tapahtumalista = tl;_x000D_
this.tyyppi = tyyppi;_x000D_
this.ulkoLahtoAika = ulkoLahtoAika;_x000D_
this.lentojenVali = lentojenVali;_x000D_
}_x000D_
_x000D_
/** Metodi generoi seuraavat tapahtumat */_x000D_
public void generoiSeuraava() {_x000D_
_x000D_
// Lahtoaika ulkomaalennoille_x000D_
double ulkoLahtoAika = Kello.getInstance().getAika() + new Normal(this.ulkoLahtoAika, 5).sample();_x000D_
_x000D_
// Lahtoaika sisalennoille_x000D_
double lahtoAika = ulkoLahtoAika + this.lentojenVali; //new Normal(this.lentojenVali, 5).sample() ;_x000D_
_x000D_
// Luodaan tapahtuma "Ulkomaan lento"_x000D_
Tapahtuma tUlko = new Tapahtuma(tyyppi, ulkoLahtoAika, true);_x000D_
tapahtumalista.lisaa(tUlko);_x000D_
_x000D_
// Luodaan tapahtuma "Sisamaan lento"_x000D_
Tapahtuma tSisa = new Tapahtuma(SISA, lahtoAika, false);_x000D_
tapahtumalista.lisaa(tSisa);_x000D_
_x000D_
// Luodaan 10 tapahtumaa "Saapuva asiakas ulkomaalle"_x000D_
for (int i=0; i<10; i++) {_x000D_
Tapahtuma t1 = new Tapahtuma(ARR1, ulkoLahtoAika - (new Normal(240, 15).sample()), true);_x000D_
tapahtumalista.lisaa(t1);_x000D_
}_x000D_
_x000D_
// Luodaan 10 tapahtumaa "Saapuva asiakas sisalennolle"_x000D_
for (int i=0; i<10; i++) {_x000D_
Tapahtuma t2 = new Tapahtuma(ARR2, lahtoAika - (new Normal(240, 15).sample()), false);_x000D_
tapahtumalista.lisaa(t2);_x000D_
}_x000D_
}_x000D_
} | False | 1,163 | 16 | 1,254 | 16 | 1,173 | 16 | 1,254 | 16 | 1,318 | 17 | false | false | false | false | false | true |
1,073 | 8369_0 | package be.jpendel.application;
import be.jpendel.domain.person.Person;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/* TODO : mark: PersonMapper en PersonDTO moeten volgens mij in de domain layer
*/
class PersonMapper {
private PersonMapper() {
}
static List<PersonDTO> map(Collection<Person> persons) {
return persons.stream().map(PersonMapper::map).collect(Collectors.toList());
}
static PersonDTO map(Person person) {
return PersonDTO.newBuilder()
.withUuid(person.getId())
.withFirstName(person.getFirstName())
.withLastName(person.getLastName())
.withBirthDate(person.getBirthDate())
.withPhone(person.getPhone())
.build();
}
}
| MarkDechamps/jpendel | application/src/main/java/be/jpendel/application/PersonMapper.java | 233 | /* TODO : mark: PersonMapper en PersonDTO moeten volgens mij in de domain layer
*/ | block_comment | nl | package be.jpendel.application;
import be.jpendel.domain.person.Person;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/* TODO : mark:<SUF>*/
class PersonMapper {
private PersonMapper() {
}
static List<PersonDTO> map(Collection<Person> persons) {
return persons.stream().map(PersonMapper::map).collect(Collectors.toList());
}
static PersonDTO map(Person person) {
return PersonDTO.newBuilder()
.withUuid(person.getId())
.withFirstName(person.getFirstName())
.withLastName(person.getLastName())
.withBirthDate(person.getBirthDate())
.withPhone(person.getPhone())
.build();
}
}
| True | 157 | 20 | 202 | 22 | 205 | 19 | 202 | 22 | 232 | 22 | false | false | false | false | false | true |
4,172 | 46346_1 | package com.example.plugindemo.activity.category;
import java.text.Collator;
import android.app.TwsActivity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.plugindemo.R;
import com.tencent.tws.assistant.widget.SideBar;
import com.tencent.tws.assistant.widget.SideBar.OnTouchingLetterChangedListener;
public class SideBarActivity extends TwsActivity implements ListView.OnScrollListener {
private ListView mListView;
private SideBar mSideBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sidebar_widget);
setTitle("测试共享控件SideBar");
mListView = (ListView) findViewById(R.id.listview);
mSideBar = (SideBar) findViewById(R.id.sidebar);
mSideBar.setIsCSP(true);
mSideBar.setOnTouchingLetterChangedListener(mLetterChangedListener);
mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings));
mSideBar.updateEntriesPropWithContentArray(mStrings);
mSideBar.setHubbleNormalBgColor(0xFF60DBAA); // default is 0xFF000000
mSideBar.setHubbleNonExistBgColor(0xFFc5c5c5); // default is 0xFFe5e5e5
mSideBar.setHubbleNormalTextColor(0xFFFFFFFF); // default is 0xFFFFFFFF
mSideBar.setHubbleNonExistTextColor(0xFFdddddd); // default is
// 0xFFFFFFFF
mSideBar.setNormalColor(0xFF101010); // default is 0xcc000000
mSideBar.setNonExistColor(0xFFc5c5c5); // default is 0x4c000000
mSideBar.setSelectedColor(0xff22b2b6); // default is 0xff22b2b6
mSideBar.updateEntriesPropWithContentArray(mStrings);
mListView.setOnScrollListener(this);
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int index = getSectionForPosition(firstVisibleItem);
mSideBar.updateCurrentIndex(index);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
OnTouchingLetterChangedListener mLetterChangedListener = new OnTouchingLetterChangedListener() {
@Override
public void onTouchingLetterChanged(int letterIndex) {
}
@Override
public void onTouchingLetterChanged(String touchIndexString) {
int index = getPositionForSection(touchIndexString);
mListView.setSelection(index);
}
@Override
public void onTouchUp() {
}
};
public int getPositionForSection(String s) {
for (int i = 0; i < mStrings.length; i++) {
char firstLetter = mStrings[i].charAt(0);
if (compare(firstLetter + "", s) == 0) {
return i;
}
}
return -1;
}
public int getSectionForPosition(int position) {
char firstLetter = mStrings[position].charAt(0);
String[] DEFALUT_ENTRIES = (String[]) mSideBar.getSideBarEntries();
for (int i = 0; i < DEFALUT_ENTRIES.length; i++) {
if (compare(firstLetter + "", DEFALUT_ENTRIES[i]) == 0) {
return i;
}
}
return 0; // Don't recognize the letter - falls under zero'th section
}
protected int compare(String word, String letter) {
final String firstLetter;
if (word.length() == 0) {
firstLetter = " ";
} else {
firstLetter = word.substring(0, 1);
}
Collator collator = java.text.Collator.getInstance();
collator.setStrength(java.text.Collator.PRIMARY);
return collator.compare(firstLetter, letter);
}
public static final String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance",
"Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
"Caciocavallo", "Caciotta", "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie",
"Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat", "Capriole Banon",
"Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano", "Castelleno", "Castelmagno",
"Castelo Branco", "Castigliano", "Cathelain", "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou",
"Chabichou du Poitou", "Chabis de Gatine", "Double Gloucester", "Double Worcester", "Dreux a la Feuille",
"Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue", "Duroblando", "Durrus",
"Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz", "Gammelost", "Gaperon a l'Ail", "Garrotxa",
"Gastanberra", "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola",
"Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
"Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel", "Grataron d' Areches", "Gratte-Paille",
"Graviera", "Greuilh", "Greve", "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi",
"Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti", "Heidi Gruyere",
"Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve", "Hipi Iti", "Hubbardston Blue Cow",
"Hushallsost", "Iberico", "Idaho Goatster", "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu",
"Isle of Mull", "Jarlsberg", "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa",
"Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine", "Kikorangi",
"King Island Cape Wickham Brie", "King River Gold", "Klosterkaese", "Knockalara", "Kugelkase",
"L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere", "La Vache Qui Rit", "Laguiole", "Lairobell",
"Lajta", "Lanark Blue", "Lancashire", "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo",
"Le Lacandou", "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger",
"Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings", "Livarot",
"Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse", "Loddiswell Avondale", "Longhorn",
"Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam", "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern",
"Mamirolle", "Manchego", "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin",
"Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)", "Mascarpone Torta", "Matocq",
"Maytag Blue", "Meira", "Menallack Farmhouse", "Menonita", "Meredith Blue", "Mesost",
"Metton (Cancoillotte)", "Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar",
"Mini Baby Bells", "Mixte", "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio",
"Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne", "Mothais a la Feuille",
"Mozzarella", "Mozzarella (Australian)", "Mozzarella di Bufala", "Mozzarella Fresh, in water",
"Mozzarella Rolls", "Munster", "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel",
"Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca", "Olde York", "Olivet au Foin",
"Olivet Bleu", "Olivet Cendre", "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier",
"Ossau-Iraty", "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela",
"Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano", "Pas de l'Escalette",
"Passendale", "Pasteurized Processed", "Pate de Fromage", "Patefine Fort", "Pave d'Affinois",
"Pave d'Auge", "Pave de Chirac", "Pave du Berry", "Pecorino", "Pecorino in Walnut Leaves",
"Pecorino Romano", "Peekskill Pyramid", "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera",
"Penbryn", "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse",
"Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin", "Plateau de Herve",
"Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin", "Pont l'Eveque", "Port Nicholson",
"Port-Salut", "Postel", "Pouligny-Saint-Pierre", "Zamorano", "Zanetti Grana Padano",
"Zanetti Parmigiano Reggiano", "# Reggiano", "★ Zaneo" };
}
| rickdynasty/TwsPluginFramework | TwsPluginDemo/src/main/java/com/example/plugindemo/activity/category/SideBarActivity.java | 3,132 | // default is 0xFFe5e5e5 | line_comment | nl | package com.example.plugindemo.activity.category;
import java.text.Collator;
import android.app.TwsActivity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.plugindemo.R;
import com.tencent.tws.assistant.widget.SideBar;
import com.tencent.tws.assistant.widget.SideBar.OnTouchingLetterChangedListener;
public class SideBarActivity extends TwsActivity implements ListView.OnScrollListener {
private ListView mListView;
private SideBar mSideBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sidebar_widget);
setTitle("测试共享控件SideBar");
mListView = (ListView) findViewById(R.id.listview);
mSideBar = (SideBar) findViewById(R.id.sidebar);
mSideBar.setIsCSP(true);
mSideBar.setOnTouchingLetterChangedListener(mLetterChangedListener);
mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings));
mSideBar.updateEntriesPropWithContentArray(mStrings);
mSideBar.setHubbleNormalBgColor(0xFF60DBAA); // default is 0xFF000000
mSideBar.setHubbleNonExistBgColor(0xFFc5c5c5); // default is<SUF>
mSideBar.setHubbleNormalTextColor(0xFFFFFFFF); // default is 0xFFFFFFFF
mSideBar.setHubbleNonExistTextColor(0xFFdddddd); // default is
// 0xFFFFFFFF
mSideBar.setNormalColor(0xFF101010); // default is 0xcc000000
mSideBar.setNonExistColor(0xFFc5c5c5); // default is 0x4c000000
mSideBar.setSelectedColor(0xff22b2b6); // default is 0xff22b2b6
mSideBar.updateEntriesPropWithContentArray(mStrings);
mListView.setOnScrollListener(this);
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int index = getSectionForPosition(firstVisibleItem);
mSideBar.updateCurrentIndex(index);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
OnTouchingLetterChangedListener mLetterChangedListener = new OnTouchingLetterChangedListener() {
@Override
public void onTouchingLetterChanged(int letterIndex) {
}
@Override
public void onTouchingLetterChanged(String touchIndexString) {
int index = getPositionForSection(touchIndexString);
mListView.setSelection(index);
}
@Override
public void onTouchUp() {
}
};
public int getPositionForSection(String s) {
for (int i = 0; i < mStrings.length; i++) {
char firstLetter = mStrings[i].charAt(0);
if (compare(firstLetter + "", s) == 0) {
return i;
}
}
return -1;
}
public int getSectionForPosition(int position) {
char firstLetter = mStrings[position].charAt(0);
String[] DEFALUT_ENTRIES = (String[]) mSideBar.getSideBarEntries();
for (int i = 0; i < DEFALUT_ENTRIES.length; i++) {
if (compare(firstLetter + "", DEFALUT_ENTRIES[i]) == 0) {
return i;
}
}
return 0; // Don't recognize the letter - falls under zero'th section
}
protected int compare(String word, String letter) {
final String firstLetter;
if (word.length() == 0) {
firstLetter = " ";
} else {
firstLetter = word.substring(0, 1);
}
Collator collator = java.text.Collator.getInstance();
collator.setStrength(java.text.Collator.PRIMARY);
return collator.compare(firstLetter, letter);
}
public static final String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance",
"Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
"Caciocavallo", "Caciotta", "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie",
"Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat", "Capriole Banon",
"Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano", "Castelleno", "Castelmagno",
"Castelo Branco", "Castigliano", "Cathelain", "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou",
"Chabichou du Poitou", "Chabis de Gatine", "Double Gloucester", "Double Worcester", "Dreux a la Feuille",
"Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue", "Duroblando", "Durrus",
"Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz", "Gammelost", "Gaperon a l'Ail", "Garrotxa",
"Gastanberra", "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola",
"Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
"Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel", "Grataron d' Areches", "Gratte-Paille",
"Graviera", "Greuilh", "Greve", "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi",
"Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti", "Heidi Gruyere",
"Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve", "Hipi Iti", "Hubbardston Blue Cow",
"Hushallsost", "Iberico", "Idaho Goatster", "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu",
"Isle of Mull", "Jarlsberg", "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa",
"Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine", "Kikorangi",
"King Island Cape Wickham Brie", "King River Gold", "Klosterkaese", "Knockalara", "Kugelkase",
"L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere", "La Vache Qui Rit", "Laguiole", "Lairobell",
"Lajta", "Lanark Blue", "Lancashire", "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo",
"Le Lacandou", "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger",
"Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings", "Livarot",
"Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse", "Loddiswell Avondale", "Longhorn",
"Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam", "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern",
"Mamirolle", "Manchego", "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin",
"Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)", "Mascarpone Torta", "Matocq",
"Maytag Blue", "Meira", "Menallack Farmhouse", "Menonita", "Meredith Blue", "Mesost",
"Metton (Cancoillotte)", "Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar",
"Mini Baby Bells", "Mixte", "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio",
"Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne", "Mothais a la Feuille",
"Mozzarella", "Mozzarella (Australian)", "Mozzarella di Bufala", "Mozzarella Fresh, in water",
"Mozzarella Rolls", "Munster", "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel",
"Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca", "Olde York", "Olivet au Foin",
"Olivet Bleu", "Olivet Cendre", "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier",
"Ossau-Iraty", "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela",
"Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano", "Pas de l'Escalette",
"Passendale", "Pasteurized Processed", "Pate de Fromage", "Patefine Fort", "Pave d'Affinois",
"Pave d'Auge", "Pave de Chirac", "Pave du Berry", "Pecorino", "Pecorino in Walnut Leaves",
"Pecorino Romano", "Peekskill Pyramid", "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera",
"Penbryn", "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse",
"Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin", "Plateau de Herve",
"Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin", "Pont l'Eveque", "Port Nicholson",
"Port-Salut", "Postel", "Pouligny-Saint-Pierre", "Zamorano", "Zanetti Grana Padano",
"Zanetti Parmigiano Reggiano", "# Reggiano", "★ Zaneo" };
}
| False | 2,689 | 12 | 3,045 | 12 | 2,659 | 12 | 3,046 | 12 | 3,293 | 13 | false | false | false | false | false | true |
2,942 | 29048_15 | package pca;
import cern.colt.matrix.DoubleFactory2D;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
import cern.colt.matrix.linalg.Algebra;
import cern.jet.math.Functions;
import util.Log;
import util.Log.LogType;
import util.TimeCounter;
public class PCA {
protected int numComponents; /* Dimension of reduced data. */
protected DoubleMatrix2D data = null; /* Original data */
private DoubleMatrix2D reducedData = null; /* Data after PCA */
protected DoubleMatrix2D basis = null; /* Transformation matrix between sample and feature space. */
protected DoubleMatrix1D eigenValues = null; /* Eigen Values used for standard deviation */
private DoubleMatrix1D mean = null;
private boolean meanDirty = true;
private boolean dataLock = false; /* If the data already has been centered. */
public PCA() {
}
public PCA(int numComponents,
DoubleMatrix2D reducedData,
DoubleMatrix1D eigenValues,
DoubleMatrix1D mean) {
this.numComponents = numComponents;
this.reducedData = reducedData;
this.eigenValues = eigenValues;
this.mean = mean;
this.meanDirty = false;
this.dataLock = true;
}
/** Create a new PCA with the provided data, with one column = one sample. */
public PCA(DoubleMatrix2D data) {
this.data = data;
}
/** Add a new sample in the PCA. The first sample added decide the sample's size.
* If further add is done with a different size, an exception is throw.
*/
public void addSample(DoubleMatrix1D sample) {
if(dataLock)
throw new RuntimeException("Data already locked.");
if(data == null) {
/* Sub-optimal, involve 2 copies. */
data = DoubleFactory2D.dense.make(sample.toArray(), sample.size());
}
else {
if(data.rows() != sample.size())
throw new RuntimeException("Unexpected sample length.");
/* Sub-optimal, involve 3 copies. */
DoubleMatrix2D sample2d = DoubleFactory2D.dense.make(sample.toArray(), sample.size());
data = DoubleFactory2D.dense.appendColumns(data, sample2d).copy();
}
}
/** Compute the PCA and reduce the data. */
public void computePCA(int numComponents) {
TimeCounter t = new TimeCounter("PCA: computation of basis and reduced data.");
this.numComponents = numComponents;
Log.info(LogType.MODEL, "PCA computation with " + numComponents + " dimensions.");
centerData();
doComputeBasis();
/* Compute reduced data. */
reducedData = new Algebra().mult(data, basis.viewDice());
t.stop();
}
public boolean computationDone() {
return dataLock;
}
/** This method should compute the basis matrix and the eigenValue matrix. */
protected void doComputeBasis() {
/* This class need to be subclassed to implement a PCA method. */
assert(false);
}
/** @return the basis vector. */
public DoubleMatrix2D getBasis() {
assert basis != null;
return basis;
}
/** @return a vector of the feature space basis. */
public DoubleMatrix1D getBasisVector(int index) {
assert basis != null;
return basis.viewColumn(index);
}
/** @return one eigen value. */
public double getEigenValue(int index) {
ensureReducedData();
return eigenValues.get(index);
}
/** @return the number of component of the feature space. */
public int getNumComponents() {
ensureReducedData();
return numComponents;
}
/** @return the size of one sample. */
public int getSampleSize() {
if(data == null)
return 0;
return data.rows();
}
/** @return how many sample are stored. */
public int getSampleNumber() {
if(data == null)
return 0;
return data.columns();
}
/** @return one original sample. */
public DoubleMatrix1D getSample(int index) {
return data.viewColumn(index);
}
/** @return one of the reduced model. */
public DoubleMatrix1D getFeatureSample(int index) {
return reducedData.viewColumn(index).copy().assign(mean, Functions.plus);
}
/** @return a sample from the original data expressed in the feature space.
* @param index the index of the sample in the original data.
*/
public DoubleMatrix1D sampleToFeatureSpace(int index) {
return sampleToFeatureSpaceNoMean(data.viewColumn(index));
}
/** @return an arbitrary sample expressed in the feature space.
* @param sample the sample data. Length should be the same as the original data.
*/
public DoubleMatrix1D sampleToFeatureSpace(DoubleMatrix1D sample) {
ensureMean();
return sampleToFeatureSpaceNoMean(sample.copy().assign(mean, Functions.minus));
}
/** Internal sampleToFeatureSpace, for data that are already mean subtracted.
* @param sample the sample to convert.
*/
private DoubleMatrix1D sampleToFeatureSpaceNoMean(DoubleMatrix1D sample) {
ensureReducedData();
if(sample.size() != data.rows())
throw new IllegalArgumentException("Unexpected sample length.");
return new Algebra().mult(basis, sample);
}
/** @return an arbitrary sample expressed in the sample space.
* @param sample the sample data. Length should be the same as the feature space dimension.
*/
public DoubleMatrix1D sampleToSampleSpace(DoubleMatrix1D sample) {
if(sample.size() != numComponents)
throw new IllegalArgumentException("Unexpected sample length.");
ensureMean();
DoubleMatrix1D s_copy = sample.copy();
s_copy.assign(eigenValues, Functions.mult);
DoubleMatrix1D result = new Algebra().mult(reducedData, s_copy);
return result.assign(mean, Functions.plus);
}
/** Compute the error resulting for a projection to feature space and back for a sample.
* This could be used to test the membership of a sample to the feature space.
*/
public double errorMembership(DoubleMatrix1D sample) {
DoubleMatrix1D feat = sampleToFeatureSpace(sample);
DoubleMatrix1D back = sampleToSampleSpace(feat);
sample.assign(back, Functions.minus);
sample.assign(Functions.square);
return Math.sqrt(sample.zSum());
}
/** @return the mean sample. */
public DoubleMatrix1D getMean() {
ensureMean();
return mean;
}
@Override
public String toString() {
return "PCA: \n" + basis;
}
/** Update the mean sample of the original data. */
private void computeMean() {
Log.debug(LogType.MODEL, "PCA: compute mean sample.");
if(mean == null)
mean = new DenseDoubleMatrix1D(data.rows());
else
mean.assign(0.0);
for(int i = 0; i < data.rows(); i++) {
mean.set(i, data.viewRow(i).zSum() / data.columns());
}
meanDirty = false;
}
/** Subtract the mean from all samples. */
private void centerData() {
Log.debug(LogType.MODEL, "PCA: lock data.");
this.dataLock = true;
ensureMean();
for(int i = 0; i < data.columns(); i++)
data.viewColumn(i).assign(mean, Functions.minus);
}
/** If no explicit computeBasis call have been made with a numComponents,
* we compute the PCA with the same dimension as the original data. */
private void ensureReducedData() {
if(reducedData == null)
computePCA(data.rows());
}
/** Ensure that the mean is properly computed. */
private void ensureMean() {
if(meanDirty)
computeMean();
}
}
| hillday/3DMM | src/pca/PCA.java | 2,160 | /** @return one eigen value. */ | block_comment | nl | package pca;
import cern.colt.matrix.DoubleFactory2D;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.DoubleMatrix2D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
import cern.colt.matrix.linalg.Algebra;
import cern.jet.math.Functions;
import util.Log;
import util.Log.LogType;
import util.TimeCounter;
public class PCA {
protected int numComponents; /* Dimension of reduced data. */
protected DoubleMatrix2D data = null; /* Original data */
private DoubleMatrix2D reducedData = null; /* Data after PCA */
protected DoubleMatrix2D basis = null; /* Transformation matrix between sample and feature space. */
protected DoubleMatrix1D eigenValues = null; /* Eigen Values used for standard deviation */
private DoubleMatrix1D mean = null;
private boolean meanDirty = true;
private boolean dataLock = false; /* If the data already has been centered. */
public PCA() {
}
public PCA(int numComponents,
DoubleMatrix2D reducedData,
DoubleMatrix1D eigenValues,
DoubleMatrix1D mean) {
this.numComponents = numComponents;
this.reducedData = reducedData;
this.eigenValues = eigenValues;
this.mean = mean;
this.meanDirty = false;
this.dataLock = true;
}
/** Create a new PCA with the provided data, with one column = one sample. */
public PCA(DoubleMatrix2D data) {
this.data = data;
}
/** Add a new sample in the PCA. The first sample added decide the sample's size.
* If further add is done with a different size, an exception is throw.
*/
public void addSample(DoubleMatrix1D sample) {
if(dataLock)
throw new RuntimeException("Data already locked.");
if(data == null) {
/* Sub-optimal, involve 2 copies. */
data = DoubleFactory2D.dense.make(sample.toArray(), sample.size());
}
else {
if(data.rows() != sample.size())
throw new RuntimeException("Unexpected sample length.");
/* Sub-optimal, involve 3 copies. */
DoubleMatrix2D sample2d = DoubleFactory2D.dense.make(sample.toArray(), sample.size());
data = DoubleFactory2D.dense.appendColumns(data, sample2d).copy();
}
}
/** Compute the PCA and reduce the data. */
public void computePCA(int numComponents) {
TimeCounter t = new TimeCounter("PCA: computation of basis and reduced data.");
this.numComponents = numComponents;
Log.info(LogType.MODEL, "PCA computation with " + numComponents + " dimensions.");
centerData();
doComputeBasis();
/* Compute reduced data. */
reducedData = new Algebra().mult(data, basis.viewDice());
t.stop();
}
public boolean computationDone() {
return dataLock;
}
/** This method should compute the basis matrix and the eigenValue matrix. */
protected void doComputeBasis() {
/* This class need to be subclassed to implement a PCA method. */
assert(false);
}
/** @return the basis vector. */
public DoubleMatrix2D getBasis() {
assert basis != null;
return basis;
}
/** @return a vector of the feature space basis. */
public DoubleMatrix1D getBasisVector(int index) {
assert basis != null;
return basis.viewColumn(index);
}
/** @return one eigen<SUF>*/
public double getEigenValue(int index) {
ensureReducedData();
return eigenValues.get(index);
}
/** @return the number of component of the feature space. */
public int getNumComponents() {
ensureReducedData();
return numComponents;
}
/** @return the size of one sample. */
public int getSampleSize() {
if(data == null)
return 0;
return data.rows();
}
/** @return how many sample are stored. */
public int getSampleNumber() {
if(data == null)
return 0;
return data.columns();
}
/** @return one original sample. */
public DoubleMatrix1D getSample(int index) {
return data.viewColumn(index);
}
/** @return one of the reduced model. */
public DoubleMatrix1D getFeatureSample(int index) {
return reducedData.viewColumn(index).copy().assign(mean, Functions.plus);
}
/** @return a sample from the original data expressed in the feature space.
* @param index the index of the sample in the original data.
*/
public DoubleMatrix1D sampleToFeatureSpace(int index) {
return sampleToFeatureSpaceNoMean(data.viewColumn(index));
}
/** @return an arbitrary sample expressed in the feature space.
* @param sample the sample data. Length should be the same as the original data.
*/
public DoubleMatrix1D sampleToFeatureSpace(DoubleMatrix1D sample) {
ensureMean();
return sampleToFeatureSpaceNoMean(sample.copy().assign(mean, Functions.minus));
}
/** Internal sampleToFeatureSpace, for data that are already mean subtracted.
* @param sample the sample to convert.
*/
private DoubleMatrix1D sampleToFeatureSpaceNoMean(DoubleMatrix1D sample) {
ensureReducedData();
if(sample.size() != data.rows())
throw new IllegalArgumentException("Unexpected sample length.");
return new Algebra().mult(basis, sample);
}
/** @return an arbitrary sample expressed in the sample space.
* @param sample the sample data. Length should be the same as the feature space dimension.
*/
public DoubleMatrix1D sampleToSampleSpace(DoubleMatrix1D sample) {
if(sample.size() != numComponents)
throw new IllegalArgumentException("Unexpected sample length.");
ensureMean();
DoubleMatrix1D s_copy = sample.copy();
s_copy.assign(eigenValues, Functions.mult);
DoubleMatrix1D result = new Algebra().mult(reducedData, s_copy);
return result.assign(mean, Functions.plus);
}
/** Compute the error resulting for a projection to feature space and back for a sample.
* This could be used to test the membership of a sample to the feature space.
*/
public double errorMembership(DoubleMatrix1D sample) {
DoubleMatrix1D feat = sampleToFeatureSpace(sample);
DoubleMatrix1D back = sampleToSampleSpace(feat);
sample.assign(back, Functions.minus);
sample.assign(Functions.square);
return Math.sqrt(sample.zSum());
}
/** @return the mean sample. */
public DoubleMatrix1D getMean() {
ensureMean();
return mean;
}
@Override
public String toString() {
return "PCA: \n" + basis;
}
/** Update the mean sample of the original data. */
private void computeMean() {
Log.debug(LogType.MODEL, "PCA: compute mean sample.");
if(mean == null)
mean = new DenseDoubleMatrix1D(data.rows());
else
mean.assign(0.0);
for(int i = 0; i < data.rows(); i++) {
mean.set(i, data.viewRow(i).zSum() / data.columns());
}
meanDirty = false;
}
/** Subtract the mean from all samples. */
private void centerData() {
Log.debug(LogType.MODEL, "PCA: lock data.");
this.dataLock = true;
ensureMean();
for(int i = 0; i < data.columns(); i++)
data.viewColumn(i).assign(mean, Functions.minus);
}
/** If no explicit computeBasis call have been made with a numComponents,
* we compute the PCA with the same dimension as the original data. */
private void ensureReducedData() {
if(reducedData == null)
computePCA(data.rows());
}
/** Ensure that the mean is properly computed. */
private void ensureMean() {
if(meanDirty)
computeMean();
}
}
| True | 1,718 | 8 | 2,048 | 8 | 2,043 | 8 | 2,048 | 8 | 2,326 | 8 | false | false | false | false | false | true |
394 | 175634_1 | package gameEngine.ramses.events;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
public class EventQueueRoom {
//static class die een add en resolved event functie heeft.
//als een event word geadd word er bij alle eventHandlers gekeken of het hun event is. Zo ja activeer het.
//private static ArrayList<Event> _allEvents = new ArrayList<Event>();
public static void addQueueItem(Event event,EventDispatcher dispatcher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
ArrayList<ListenerItem> listListeners = dispatcher.getAllListeners();
EventDispatcher currentParent;
event.dispatcher = dispatcher;
event.caster = dispatcher;
callMethodsInListOfEvent(listListeners,event);
if(event.isBubbles()){
currentParent = dispatcher.getParentListener();
while(currentParent != null){
event.caster = currentParent;
listListeners = currentParent.getAllListeners();
callMethodsInListOfEvent(listListeners,event);
currentParent = currentParent.getParentListener();
}
}
}
private static void callMethodsInListOfEvent(ArrayList<ListenerItem> listToLoop, Event event) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
ListenerItem currentItem;
ArrayList<ListenerItem> list = listToLoop;
if(list.size() > 0){
for(int i = list.size() - 1; i >= 0 ; i--){
currentItem = list.get(i);
if(currentItem.getType() == event.getType()){
currentItem.getMethodData().getMethod().invoke(currentItem.getMethodData().getMethodHolder(), event);
}
}
}
}
}
| Darkfafi/JavaFrameworkRDP | src/gameEngine/ramses/events/EventQueueRoom.java | 475 | //als een event word geadd word er bij alle eventHandlers gekeken of het hun event is. Zo ja activeer het. | line_comment | nl | package gameEngine.ramses.events;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
public class EventQueueRoom {
//static class die een add en resolved event functie heeft.
//als een<SUF>
//private static ArrayList<Event> _allEvents = new ArrayList<Event>();
public static void addQueueItem(Event event,EventDispatcher dispatcher) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
ArrayList<ListenerItem> listListeners = dispatcher.getAllListeners();
EventDispatcher currentParent;
event.dispatcher = dispatcher;
event.caster = dispatcher;
callMethodsInListOfEvent(listListeners,event);
if(event.isBubbles()){
currentParent = dispatcher.getParentListener();
while(currentParent != null){
event.caster = currentParent;
listListeners = currentParent.getAllListeners();
callMethodsInListOfEvent(listListeners,event);
currentParent = currentParent.getParentListener();
}
}
}
private static void callMethodsInListOfEvent(ArrayList<ListenerItem> listToLoop, Event event) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
ListenerItem currentItem;
ArrayList<ListenerItem> list = listToLoop;
if(list.size() > 0){
for(int i = list.size() - 1; i >= 0 ; i--){
currentItem = list.get(i);
if(currentItem.getType() == event.getType()){
currentItem.getMethodData().getMethod().invoke(currentItem.getMethodData().getMethodHolder(), event);
}
}
}
}
}
| True | 339 | 28 | 405 | 30 | 405 | 28 | 405 | 30 | 512 | 29 | false | false | false | false | false | true |
958 | 97801_0 | package gui.screens;
import domein.DomeinController;
import gui.company.CompanyCardComponent;
import gui.components.CustomMenu;
import gui.components.LanguageBundle;
import io.github.palexdev.materialfx.controls.MFXButton;
import io.github.palexdev.materialfx.controls.MFXCheckbox;
import io.github.palexdev.materialfx.controls.MFXScrollPane;
import io.github.palexdev.materialfx.controls.MFXSlider;
import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import resources.ResourceController;
import java.util.Locale;
public class SettingScreen extends MFXScrollPane {
private DomeinController dc;
private ResourceController rs;
private BorderPane root;
private CustomMenu menu;
private VBox pane = new VBox();
private ComboBox<String> languageComboBox;
private static Label title;
private static MFXCheckbox checkbox;
private static Label soundLabel;
private static Label languageLabel;
public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) {
this.dc = dc;
pane.setAlignment(Pos.TOP_CENTER);
pane.setSpacing(200);
this.rs = rs;
this.root = root;
this.menu = menu;
this.setContent(pane);
this.setFitToHeight(true);
this.setFitToWidth(true);
setup();
}
public void setup() {
title = new Label(LanguageBundle.getString("SettingScreen_setting"));
title.getStyleClass().add("title");
soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound"));
VBox layoutBox = new VBox();
MFXSlider slider = new MFXSlider();
slider.setMin(0);
slider.setMax(100);
slider.setValue(rs.getCurrentVolume()*100);
slider.setOnMouseReleased(e -> {
System.out.println(slider.getValue());
rs.changeVolume(slider.getValue());
});
languageLabel = new Label("Language");
languageComboBox = new ComboBox<>();
HBox.setHgrow(languageComboBox, Priority.ALWAYS);
languageComboBox.getItems().addAll("en", "nl");
languageComboBox.setValue("en");
// voeg een listener toe aan de ComboBox om de taal te wijzigen
languageComboBox.setOnAction(e -> switchLanguage());
layoutBox.setAlignment(Pos.CENTER);
checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute"));
checkbox.setSelected(rs.isMute());
checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected()));
layoutBox.setSpacing(20);
layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox);
pane.getChildren().addAll(title, layoutBox);
}
private void switchLanguage() {
Locale selectedLocale;
String selectedLanguage = languageComboBox.getValue();
if (selectedLanguage.equals("en")) {
selectedLocale = new Locale("en");
} else {
selectedLocale = new Locale("nl");
}
// Wijzig de taal in de hele applicatie
LanguageBundle.setLocale(selectedLocale);
//update taal van pagina waarop je staat
updateText();
/*LoginScreen.updateText();
MainScreen.updateText();
CompanyCardComponent.updateText();
NotificationScreen.updateText();
OrderScreen.updateText();
TransportDienstScreen.updateText();
RegisterScreen.updateText();
MyProductsScreen.updateText();*/
}
public static void updateText() {
title.setText(LanguageBundle.getString("SettingScreen_setting"));
checkbox.setText(LanguageBundle.getString("SettingScreen_mute"));
soundLabel.setText(LanguageBundle.getString("SettingScreen_sound"));
}
}
| LaurensDM/Webshop-desktop | src/main/java/gui/screens/SettingScreen.java | 1,144 | // voeg een listener toe aan de ComboBox om de taal te wijzigen | line_comment | nl | package gui.screens;
import domein.DomeinController;
import gui.company.CompanyCardComponent;
import gui.components.CustomMenu;
import gui.components.LanguageBundle;
import io.github.palexdev.materialfx.controls.MFXButton;
import io.github.palexdev.materialfx.controls.MFXCheckbox;
import io.github.palexdev.materialfx.controls.MFXScrollPane;
import io.github.palexdev.materialfx.controls.MFXSlider;
import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import resources.ResourceController;
import java.util.Locale;
public class SettingScreen extends MFXScrollPane {
private DomeinController dc;
private ResourceController rs;
private BorderPane root;
private CustomMenu menu;
private VBox pane = new VBox();
private ComboBox<String> languageComboBox;
private static Label title;
private static MFXCheckbox checkbox;
private static Label soundLabel;
private static Label languageLabel;
public SettingScreen(BorderPane root, CustomMenu menu, DomeinController dc, ResourceController rs) {
this.dc = dc;
pane.setAlignment(Pos.TOP_CENTER);
pane.setSpacing(200);
this.rs = rs;
this.root = root;
this.menu = menu;
this.setContent(pane);
this.setFitToHeight(true);
this.setFitToWidth(true);
setup();
}
public void setup() {
title = new Label(LanguageBundle.getString("SettingScreen_setting"));
title.getStyleClass().add("title");
soundLabel = new Label(LanguageBundle.getString("SettingScreen_sound"));
VBox layoutBox = new VBox();
MFXSlider slider = new MFXSlider();
slider.setMin(0);
slider.setMax(100);
slider.setValue(rs.getCurrentVolume()*100);
slider.setOnMouseReleased(e -> {
System.out.println(slider.getValue());
rs.changeVolume(slider.getValue());
});
languageLabel = new Label("Language");
languageComboBox = new ComboBox<>();
HBox.setHgrow(languageComboBox, Priority.ALWAYS);
languageComboBox.getItems().addAll("en", "nl");
languageComboBox.setValue("en");
// voeg een<SUF>
languageComboBox.setOnAction(e -> switchLanguage());
layoutBox.setAlignment(Pos.CENTER);
checkbox = new MFXCheckbox(LanguageBundle.getString("SettingScreen_mute"));
checkbox.setSelected(rs.isMute());
checkbox.setOnAction(e -> rs.handleMute(checkbox.isSelected()));
layoutBox.setSpacing(20);
layoutBox.getChildren().addAll(soundLabel, slider, checkbox, languageLabel, languageComboBox);
pane.getChildren().addAll(title, layoutBox);
}
private void switchLanguage() {
Locale selectedLocale;
String selectedLanguage = languageComboBox.getValue();
if (selectedLanguage.equals("en")) {
selectedLocale = new Locale("en");
} else {
selectedLocale = new Locale("nl");
}
// Wijzig de taal in de hele applicatie
LanguageBundle.setLocale(selectedLocale);
//update taal van pagina waarop je staat
updateText();
/*LoginScreen.updateText();
MainScreen.updateText();
CompanyCardComponent.updateText();
NotificationScreen.updateText();
OrderScreen.updateText();
TransportDienstScreen.updateText();
RegisterScreen.updateText();
MyProductsScreen.updateText();*/
}
public static void updateText() {
title.setText(LanguageBundle.getString("SettingScreen_setting"));
checkbox.setText(LanguageBundle.getString("SettingScreen_mute"));
soundLabel.setText(LanguageBundle.getString("SettingScreen_sound"));
}
}
| True | 774 | 17 | 939 | 19 | 981 | 15 | 939 | 19 | 1,104 | 18 | false | false | false | false | false | true |
1,685 | 55988_1 | package com.crm.qa.pages;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.crm.qa.base.TestBase;
public class EntrepreneursPageFree extends TestBase{
//Page factory OR Object Repository
@FindBy(xpath="//input[@id='filter-search-input']")
WebElement findEntrepreneur;
@FindBy(xpath="//span[@class='material-icons clear-icon']")
WebElement clickCancel;
@FindBy(xpath="//*[@id=\"dropdown-werkdenkniveau\"]/button")
WebElement workingThinkingLevel;
@FindBy(xpath="//*[@id=\"dropdown-werkdenkniveau\"]/div/form/div[4]/label")
WebElement selectWorkingThinkingLevel;
@FindBy(xpath="//*[@id=\"dropdown-vakgebied\"]/button")
WebElement descipline;
@FindBy(xpath="//*[@id=\"dropdown-vakgebied\"]/div/form/div[7]/label")
WebElement selectDescipline;
@FindBy(xpath="//*[@id=\"dropdown-interessegebied\"]/button")
WebElement areaOfInterest;
@FindBy(xpath="//*[@id=\"dropdown-interessegebied\"]/div/form/div[8]/label")
WebElement selectAreaOfInterest;
@FindBy(xpath="//*[@id=\"dropdown-skills-btn\"]")
WebElement skills;
@FindBy(xpath="//input[@placeholder='Zoek een vaardigheid']")
WebElement enterSkill;
@FindBy(xpath="//*[@id=\"result-list-31667\"]/a/div[2]/span/span")
WebElement selectSkill;
@FindBy(xpath="/html/body/div[1]/main/div/nav/div[2]/div/div[4]/div/form/div[1]/div/div/div[2]/a/div[2]/span/span")
WebElement selectSkillToolTip;
@FindBy(xpath="//*[@id=\"dropdown-skills\"]/div/form/div[4]/button")
WebElement clickApplyFilter;
@FindBy(xpath="//*[@id=\"dropdown-skills\"]/div/form/div[4]/a[2]")
WebElement clickResetFilter;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select")
WebElement clickSortingDropDown;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select/option[3]")
WebElement selectSortingZtoA;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select/option[2]")
WebElement selectSortingAtoZ;
//Initialization
public EntrepreneursPageFree() {
PageFactory.initElements(Driver, this);
}
//Actions
public void enterEntrepreneur(String value) {
findEntrepreneur.sendKeys(value);
}
public void clickCancel() {
clickCancel.click();
}
public void clickWorkingThinkingDropDown() {
workingThinkingLevel.click();
}
public void selectWorkingThinkingLevel() {
selectWorkingThinkingLevel.click();
}
public void clickDesciplineDropDown() {
descipline.click();
}
public void selectDescipline() {
selectDescipline.click();
}
public void clickAreaOfInterestDropDown() {
areaOfInterest.click();
}
public void selectAreaOfInterest() {
selectAreaOfInterest.click();
}
public void clickSkillsTab() {
skills.click();
}
public void enterSkill() {
enterSkill.click();
}
public void enterSkill(String value) {
enterSkill.sendKeys(value);
}
public void selectSkillToolTip() {
//selectSkillToolTip.click();
enterSkill.sendKeys(Keys.TAB);
}
public void clickApplyFilter() {
clickApplyFilter.click();
}
public void clickResetFilter() {
clickResetFilter.click();
}
public void clickSortingDropDown() {
clickSortingDropDown.click();
}
public void selectSortingZtoA() {
selectSortingZtoA.click();
}
public void selectSortingAtoZ() {
selectSortingAtoZ.click();
}
}
| TarunBtn/FreeCRMTestOne | FreeCRMTestOne/src/main/java/com/crm/qa/pages/EntrepreneursPageFree.java | 1,319 | //input[@placeholder='Zoek een vaardigheid']") | line_comment | nl | package com.crm.qa.pages;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.crm.qa.base.TestBase;
public class EntrepreneursPageFree extends TestBase{
//Page factory OR Object Repository
@FindBy(xpath="//input[@id='filter-search-input']")
WebElement findEntrepreneur;
@FindBy(xpath="//span[@class='material-icons clear-icon']")
WebElement clickCancel;
@FindBy(xpath="//*[@id=\"dropdown-werkdenkniveau\"]/button")
WebElement workingThinkingLevel;
@FindBy(xpath="//*[@id=\"dropdown-werkdenkniveau\"]/div/form/div[4]/label")
WebElement selectWorkingThinkingLevel;
@FindBy(xpath="//*[@id=\"dropdown-vakgebied\"]/button")
WebElement descipline;
@FindBy(xpath="//*[@id=\"dropdown-vakgebied\"]/div/form/div[7]/label")
WebElement selectDescipline;
@FindBy(xpath="//*[@id=\"dropdown-interessegebied\"]/button")
WebElement areaOfInterest;
@FindBy(xpath="//*[@id=\"dropdown-interessegebied\"]/div/form/div[8]/label")
WebElement selectAreaOfInterest;
@FindBy(xpath="//*[@id=\"dropdown-skills-btn\"]")
WebElement skills;
@FindBy(xpath="//input[@placeholder='Zoek een<SUF>
WebElement enterSkill;
@FindBy(xpath="//*[@id=\"result-list-31667\"]/a/div[2]/span/span")
WebElement selectSkill;
@FindBy(xpath="/html/body/div[1]/main/div/nav/div[2]/div/div[4]/div/form/div[1]/div/div/div[2]/a/div[2]/span/span")
WebElement selectSkillToolTip;
@FindBy(xpath="//*[@id=\"dropdown-skills\"]/div/form/div[4]/button")
WebElement clickApplyFilter;
@FindBy(xpath="//*[@id=\"dropdown-skills\"]/div/form/div[4]/a[2]")
WebElement clickResetFilter;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select")
WebElement clickSortingDropDown;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select/option[3]")
WebElement selectSortingZtoA;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select/option[2]")
WebElement selectSortingAtoZ;
//Initialization
public EntrepreneursPageFree() {
PageFactory.initElements(Driver, this);
}
//Actions
public void enterEntrepreneur(String value) {
findEntrepreneur.sendKeys(value);
}
public void clickCancel() {
clickCancel.click();
}
public void clickWorkingThinkingDropDown() {
workingThinkingLevel.click();
}
public void selectWorkingThinkingLevel() {
selectWorkingThinkingLevel.click();
}
public void clickDesciplineDropDown() {
descipline.click();
}
public void selectDescipline() {
selectDescipline.click();
}
public void clickAreaOfInterestDropDown() {
areaOfInterest.click();
}
public void selectAreaOfInterest() {
selectAreaOfInterest.click();
}
public void clickSkillsTab() {
skills.click();
}
public void enterSkill() {
enterSkill.click();
}
public void enterSkill(String value) {
enterSkill.sendKeys(value);
}
public void selectSkillToolTip() {
//selectSkillToolTip.click();
enterSkill.sendKeys(Keys.TAB);
}
public void clickApplyFilter() {
clickApplyFilter.click();
}
public void clickResetFilter() {
clickResetFilter.click();
}
public void clickSortingDropDown() {
clickSortingDropDown.click();
}
public void selectSortingZtoA() {
selectSortingZtoA.click();
}
public void selectSortingAtoZ() {
selectSortingAtoZ.click();
}
}
| False | 829 | 15 | 1,092 | 15 | 1,076 | 11 | 1,092 | 15 | 1,297 | 15 | false | false | false | false | false | true |
592 | 52480_0 | package com.digicoachindezorg.digicoachindezorg_backend.config;
/*
CORS (Cross Origin Resource Sharing) is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
| Gentlemannerss/digicoachindezorg_backend | src/main/java/com/digicoachindezorg/digicoachindezorg_backend/config/GlobalCorsConfiguration.java | 323 | /*
CORS (Cross Origin Resource Sharing) is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/ | block_comment | nl | package com.digicoachindezorg.digicoachindezorg_backend.config;
/*
CORS (Cross Origin<SUF>*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
| True | 251 | 107 | 298 | 124 | 279 | 98 | 298 | 124 | 323 | 120 | false | false | false | false | false | true |
772 | 24453_2 | package edu.ap.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import edu.ap.spring.controller.RedisController;
import edu.ap.spring.redis.RedisService;
@SpringBootApplication
public class RedisApplication {
private String CHANNEL = "edu:ap:redis";
@Autowired
private RedisService service;
//Subscript op channel
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new ChannelTopic(CHANNEL));
return container;
}
//Deze luistert op channel en wanneer er een message komt stuur die deze onMessage functie van Controller
@Bean
MessageListenerAdapter listenerAdapter(RedisController controller) {
return new MessageListenerAdapter(controller, "onMessage");
}
//Deze gaat de database leeg maken en een message daarin toevoegen
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return (args) -> {
// empty db
this.service.flushDb();
// messaging
service.sendMessage(CHANNEL, "Hello from Spring Boot");
};
}
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
| IsmatFaizi/studeren-examen | Spring-Redis/src/main/java/edu/ap/spring/RedisApplication.java | 524 | //Deze gaat de database leeg maken en een message daarin toevoegen | line_comment | nl | package edu.ap.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import edu.ap.spring.controller.RedisController;
import edu.ap.spring.redis.RedisService;
@SpringBootApplication
public class RedisApplication {
private String CHANNEL = "edu:ap:redis";
@Autowired
private RedisService service;
//Subscript op channel
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new ChannelTopic(CHANNEL));
return container;
}
//Deze luistert op channel en wanneer er een message komt stuur die deze onMessage functie van Controller
@Bean
MessageListenerAdapter listenerAdapter(RedisController controller) {
return new MessageListenerAdapter(controller, "onMessage");
}
//Deze gaat<SUF>
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return (args) -> {
// empty db
this.service.flushDb();
// messaging
service.sendMessage(CHANNEL, "Hello from Spring Boot");
};
}
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
| True | 357 | 17 | 438 | 20 | 460 | 15 | 438 | 20 | 523 | 19 | false | false | false | false | false | true |
2,605 | 171856_2 | /*
* Copyright 2014 http://Bither.net
*
* 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 net.bither.util;
import android.os.Handler;
import com.google.bitcoin.store.WalletProtobufSerializer;
import net.bither.bitherj.core.Address;
import net.bither.bitherj.core.BitherjSettings;
import net.bither.bitherj.crypto.ECKey;
import net.bither.bitherj.utils.PrivateKeyUtil;
import net.bither.bitherj.utils.Utils;
import net.bither.preference.AppSharedPreference;
import net.bither.runnable.BaseRunnable;
import net.bither.runnable.HandlerMessage;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class UpgradeUtil {
// old watch only dir
private static final String WALLET_WATCH_ONLY_OLD = "w";
public static final int BITHERJ_VERSION_CODE = 9;
private static final String WALLET_SEQUENCE_WATCH_ONLY = "sequence_watch_only";
private static final String WALLET_SEQUENCE_PRIVATE = "sequence_private";
private static final String WALLET_ROM_CACHE = "wallet";
private static final String WALLET_WATCH_ONLY = "watch";
private static final String WALLET_HOT = "hot";
private static final String WALLET_COLD = "cold";
private static final String WALLET_ERROR = "error";
private UpgradeUtil() {
}
public static boolean needUpgrade() {
int verionCode = AppSharedPreference.getInstance().getVerionCode();
return verionCode < BITHERJ_VERSION_CODE && verionCode > 0 || getOldWatchOnlyCacheDir().exists();
}
public static void upgradeNewVerion(Handler handler) {
BaseRunnable baseRunnable = new BaseRunnable() {
@Override
public void run() {
obtainMessage(HandlerMessage.MSG_PREPARE);
try {
long beginTime = System.currentTimeMillis();
if (getOldWatchOnlyCacheDir().exists()) {
upgradeV4();
upgradeToBitherj();
}
int verionCode = AppSharedPreference.getInstance().getVerionCode();
if (verionCode < BITHERJ_VERSION_CODE && verionCode > 0) {
upgradeToBitherj();
}
long nowTime = System.currentTimeMillis();
if (nowTime - beginTime < 2000) {
Thread.sleep(2000 - (nowTime - beginTime));
}
obtainMessage(HandlerMessage.MSG_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
obtainMessage(HandlerMessage.MSG_FAILURE);
}
}
};
baseRunnable.setHandler(handler);
new Thread(baseRunnable).start();
}
//upgrde when version code <9
private static void upgradeToBitherj() throws Exception {
List<ECKey> ecKeyPrivates = initPrivateWallet(readPrivateAddressSequence());
List<ECKey> ecKeysWatchOnly = initWatchOnlyWallet(readWatchOnlyAddressSequence());
List<Address> privateAddressList = new ArrayList<Address>();
List<Address> watchOnlyAddressList = new ArrayList<Address>();
for (int i = 0; i < ecKeyPrivates.size(); i++) {
ECKey ecKey = ecKeyPrivates.get(i);
Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(), PrivateKeyUtil.getPrivateKeyString(ecKey), false);
privateAddressList.add(address);
}
if (privateAddressList.size() > 0) {
KeyUtil.addAddressListByDesc(null, privateAddressList);
}
for (int i = 0; i < ecKeysWatchOnly.size(); i++) {
ECKey ecKey = ecKeysWatchOnly.get(i);
Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(), null, false);
watchOnlyAddressList.add(address);
}
if (watchOnlyAddressList.size() > 0) {
KeyUtil.addAddressListByDesc(null, watchOnlyAddressList);
}
}
private static void upgradeV4() {
AppSharedPreference.getInstance().clear();
File walletFile = UpgradeUtil.getOldWatchOnlyCacheDir();
FileUtil.delFolder(walletFile.getAbsolutePath());
File watchOnlyAddressSequenceFile = getWatchOnlyAddressSequenceFile();
if (watchOnlyAddressSequenceFile.exists()) {
watchOnlyAddressSequenceFile.delete();
}
//upgrade
// File blockFile = FileUtil.getBlockChainFile();
// if (blockFile.exists()) {
// blockFile.delete();
// }
File errorFolder = getWatchErrorDir();
FileUtil.delFolder(errorFolder.getAbsolutePath());
}
public static File getOldWatchOnlyCacheDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_WATCH_ONLY_OLD);
return file;
}
private static List<ECKey> initPrivateWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getPrivateCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
private static List<ECKey> initWatchOnlyWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getWatchOnlyCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
public static File getPrivateCacheDir() {
File file = Utils.getWalletRomCache();
String dirName = WALLET_HOT;
if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
dirName = WALLET_COLD;
}
file = new File(file, dirName);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File getWatchOnlyCacheDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_WATCH_ONLY);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File getWatchErrorDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_ERROR);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
private static File[] sortAddressFile(File[] fs, final List<String> sequence) {
Arrays.sort(fs, new Comparator<File>() {
public int compare(File f1, File f2) {
long diff = sequence.indexOf(f1.getName())
- sequence.indexOf(f2.getName());
if (diff > 0) {
return 1;
} else if (diff == 0) {
return 0;
} else {
return -1;
}
}
});
return fs;
}
private static ECKey loadECKey(File walletFile) throws Exception {
FileInputStream walletStream = null;
walletStream = new FileInputStream(walletFile);
ECKey ecKey = new
WalletProtobufSerializer()
.readWallet(walletStream);
return ecKey;
}
public static File getWarmPrivateAddressSequenceFile() {
File dir = Utils.getWalletRomCache();
File file = new File(dir, WALLET_SEQUENCE_PRIVATE);
return file;
}
public static File getWatchOnlyAddressSequenceFile() {
File dir = Utils.getWalletRomCache();
File file = new File(dir, WALLET_SEQUENCE_WATCH_ONLY);
return file;
}
private static List<String> readPrivateAddressSequence() {
File file = getWarmPrivateAddressSequenceFile();
if (file.exists()) {
ArrayList<String> addresses = (ArrayList<String>) FileUtil
.deserialize(file);
return addresses;
} else {
return null;
}
}
private static List<String> readWatchOnlyAddressSequence() {
File file = getWatchOnlyAddressSequenceFile();
if (file.exists()) {
ArrayList<String> addresses = (ArrayList<String>) FileUtil
.deserialize(file);
return addresses;
} else {
return null;
}
}
}
| dworznik/bither-android | bither-android/src/net/bither/util/UpgradeUtil.java | 2,635 | //upgrde when version code <9 | line_comment | nl | /*
* Copyright 2014 http://Bither.net
*
* 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 net.bither.util;
import android.os.Handler;
import com.google.bitcoin.store.WalletProtobufSerializer;
import net.bither.bitherj.core.Address;
import net.bither.bitherj.core.BitherjSettings;
import net.bither.bitherj.crypto.ECKey;
import net.bither.bitherj.utils.PrivateKeyUtil;
import net.bither.bitherj.utils.Utils;
import net.bither.preference.AppSharedPreference;
import net.bither.runnable.BaseRunnable;
import net.bither.runnable.HandlerMessage;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class UpgradeUtil {
// old watch only dir
private static final String WALLET_WATCH_ONLY_OLD = "w";
public static final int BITHERJ_VERSION_CODE = 9;
private static final String WALLET_SEQUENCE_WATCH_ONLY = "sequence_watch_only";
private static final String WALLET_SEQUENCE_PRIVATE = "sequence_private";
private static final String WALLET_ROM_CACHE = "wallet";
private static final String WALLET_WATCH_ONLY = "watch";
private static final String WALLET_HOT = "hot";
private static final String WALLET_COLD = "cold";
private static final String WALLET_ERROR = "error";
private UpgradeUtil() {
}
public static boolean needUpgrade() {
int verionCode = AppSharedPreference.getInstance().getVerionCode();
return verionCode < BITHERJ_VERSION_CODE && verionCode > 0 || getOldWatchOnlyCacheDir().exists();
}
public static void upgradeNewVerion(Handler handler) {
BaseRunnable baseRunnable = new BaseRunnable() {
@Override
public void run() {
obtainMessage(HandlerMessage.MSG_PREPARE);
try {
long beginTime = System.currentTimeMillis();
if (getOldWatchOnlyCacheDir().exists()) {
upgradeV4();
upgradeToBitherj();
}
int verionCode = AppSharedPreference.getInstance().getVerionCode();
if (verionCode < BITHERJ_VERSION_CODE && verionCode > 0) {
upgradeToBitherj();
}
long nowTime = System.currentTimeMillis();
if (nowTime - beginTime < 2000) {
Thread.sleep(2000 - (nowTime - beginTime));
}
obtainMessage(HandlerMessage.MSG_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
obtainMessage(HandlerMessage.MSG_FAILURE);
}
}
};
baseRunnable.setHandler(handler);
new Thread(baseRunnable).start();
}
//upgrde when<SUF>
private static void upgradeToBitherj() throws Exception {
List<ECKey> ecKeyPrivates = initPrivateWallet(readPrivateAddressSequence());
List<ECKey> ecKeysWatchOnly = initWatchOnlyWallet(readWatchOnlyAddressSequence());
List<Address> privateAddressList = new ArrayList<Address>();
List<Address> watchOnlyAddressList = new ArrayList<Address>();
for (int i = 0; i < ecKeyPrivates.size(); i++) {
ECKey ecKey = ecKeyPrivates.get(i);
Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(), PrivateKeyUtil.getPrivateKeyString(ecKey), false);
privateAddressList.add(address);
}
if (privateAddressList.size() > 0) {
KeyUtil.addAddressListByDesc(null, privateAddressList);
}
for (int i = 0; i < ecKeysWatchOnly.size(); i++) {
ECKey ecKey = ecKeysWatchOnly.get(i);
Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(), null, false);
watchOnlyAddressList.add(address);
}
if (watchOnlyAddressList.size() > 0) {
KeyUtil.addAddressListByDesc(null, watchOnlyAddressList);
}
}
private static void upgradeV4() {
AppSharedPreference.getInstance().clear();
File walletFile = UpgradeUtil.getOldWatchOnlyCacheDir();
FileUtil.delFolder(walletFile.getAbsolutePath());
File watchOnlyAddressSequenceFile = getWatchOnlyAddressSequenceFile();
if (watchOnlyAddressSequenceFile.exists()) {
watchOnlyAddressSequenceFile.delete();
}
//upgrade
// File blockFile = FileUtil.getBlockChainFile();
// if (blockFile.exists()) {
// blockFile.delete();
// }
File errorFolder = getWatchErrorDir();
FileUtil.delFolder(errorFolder.getAbsolutePath());
}
public static File getOldWatchOnlyCacheDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_WATCH_ONLY_OLD);
return file;
}
private static List<ECKey> initPrivateWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getPrivateCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
private static List<ECKey> initWatchOnlyWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getWatchOnlyCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
public static File getPrivateCacheDir() {
File file = Utils.getWalletRomCache();
String dirName = WALLET_HOT;
if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
dirName = WALLET_COLD;
}
file = new File(file, dirName);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File getWatchOnlyCacheDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_WATCH_ONLY);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File getWatchErrorDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_ERROR);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
private static File[] sortAddressFile(File[] fs, final List<String> sequence) {
Arrays.sort(fs, new Comparator<File>() {
public int compare(File f1, File f2) {
long diff = sequence.indexOf(f1.getName())
- sequence.indexOf(f2.getName());
if (diff > 0) {
return 1;
} else if (diff == 0) {
return 0;
} else {
return -1;
}
}
});
return fs;
}
private static ECKey loadECKey(File walletFile) throws Exception {
FileInputStream walletStream = null;
walletStream = new FileInputStream(walletFile);
ECKey ecKey = new
WalletProtobufSerializer()
.readWallet(walletStream);
return ecKey;
}
public static File getWarmPrivateAddressSequenceFile() {
File dir = Utils.getWalletRomCache();
File file = new File(dir, WALLET_SEQUENCE_PRIVATE);
return file;
}
public static File getWatchOnlyAddressSequenceFile() {
File dir = Utils.getWalletRomCache();
File file = new File(dir, WALLET_SEQUENCE_WATCH_ONLY);
return file;
}
private static List<String> readPrivateAddressSequence() {
File file = getWarmPrivateAddressSequenceFile();
if (file.exists()) {
ArrayList<String> addresses = (ArrayList<String>) FileUtil
.deserialize(file);
return addresses;
} else {
return null;
}
}
private static List<String> readWatchOnlyAddressSequence() {
File file = getWatchOnlyAddressSequenceFile();
if (file.exists()) {
ArrayList<String> addresses = (ArrayList<String>) FileUtil
.deserialize(file);
return addresses;
} else {
return null;
}
}
}
| False | 1,979 | 9 | 2,234 | 9 | 2,402 | 9 | 2,234 | 9 | 2,681 | 9 | false | false | false | false | false | true |
2,996 | 60681_1 | package novi.basics;
public class Player {
//attributen: informatie verzamelen
private String name;
private char token;
private int score;
//methoden: acties die de speler uit kan voeren
//constructor
public Player(String name, char token) {
this.name = name;
this.token = token;
score = 0;
}
//get methoden
public String getName() {
return name;
}
public char getToken() {
return token;
}
public int getScore() {
return score;
}
//set methoden
/*public void setScore(int score) {
this.score = score;
}*/
public void addScore() {
score++;
}
} | hogeschoolnovi/tic-tac-toe-Quinten-dev | src/novi/basics/Player.java | 201 | //methoden: acties die de speler uit kan voeren | line_comment | nl | package novi.basics;
public class Player {
//attributen: informatie verzamelen
private String name;
private char token;
private int score;
//methoden: acties<SUF>
//constructor
public Player(String name, char token) {
this.name = name;
this.token = token;
score = 0;
}
//get methoden
public String getName() {
return name;
}
public char getToken() {
return token;
}
public int getScore() {
return score;
}
//set methoden
/*public void setScore(int score) {
this.score = score;
}*/
public void addScore() {
score++;
}
} | True | 165 | 14 | 169 | 14 | 192 | 12 | 169 | 14 | 202 | 14 | false | false | false | false | false | true |
2,618 | 100813_17 | /**
** Person.java
**
** Copyright 2011 by Sarah Wise, Mark Coletti, Andrew Crooks, and
** George Mason University.
**
** Licensed under the Academic Free License version 3.0
**
** See the file "LICENSE" for more information
**
** $Id$
**/
package sim.app.geo.schellingpolygon;
import java.util.ArrayList;
import sim.engine.SimState;
import sim.engine.Steppable;
public class Person implements Steppable
{
String color;
double preference;
Polygon region;
double personalThreshold = .5;
int numMoves = 0;
/**
* Constructor function
* @param c
*/
public Person(String c)
{
color = c;
}
/**
* Moves the Person to the given Polygon
* @param p - the Polygon to which the Person should move
*/
public void updateLocation(Polygon p)
{
// leave old tile, if previously was on a tile
if (region != null)
{
region.residents.remove(this);
region.soc = "UNOCCUPIED";
}
// go to new tile
region = p;
region.residents.add(this);
region.soc = color;
numMoves++; // increment the number of times moved
}
/**
*
* @param poly the proposed location
* @return whether the given Polygon is an acceptable location for the Person,
* based on the Person's personalThreshold
*/
boolean acceptable(Polygon poly)
{
// decide if Person is unhappy with surroundings
double unlike = 0, total = 0.;
for (Polygon p : poly.neighbors)
{
if (p.soc.equals("UNOCCUPIED")) // empty spaces don't count
{
continue;
}
if (!p.soc.equals(color)) // is this neighbor an unlike neighbor?
{
unlike++;
}
total++; // total count of neighbors
}
double percentUnlike = unlike / Math.max(total, 1); // don't divide by 0!
// if unhappy, return false
if (percentUnlike >= personalThreshold)
{
return false;
} else // if happy, return true
{
return true;
}
}
/**
* @param ps the list of Polygons open to the Person
* @return the closest available Polygon that meets the Person's needs, if such
* a Polygon exists. If no such Polygon exists, returns null.
*/
Polygon bestMove(ArrayList<Polygon> ps)
{
Polygon result = null;
double bestDist = Double.MAX_VALUE;
// go through all polygons and determine the best move to make
for (Polygon p : ps)
{
if (!p.soc.equals("UNOCCUPIED"))
{
continue; // not available
} else if (p.geometry.getCentroid().distance(
region.geometry.getCentroid()) >= bestDist) // distance between centroids
//else if( p.geometry.distance( region.geometry ) >= bestDist)
// distance between region borders
{
continue; // we already have a better option
} else if (!acceptable(p))
{
continue; // not an acceptable neighborhood
} else
{ // otherwise it's an acceptable region and the closest region yet
result = p;
bestDist = p.geometry.distance(region.geometry);
}
}
return result;
}
/**
* Determines whether the Person's current location is acceptable. If not, attempts
* to move the Person to a better location.
*/
@Override
public void step(SimState state)
{
if (!acceptable(region))
{ // the current location is unacceptable
// System.out.println("unacceptable!");
// try to find and move to a better location
Polygon potentialNew = bestMove(((PolySchelling) state).polys);
if (potentialNew != null) // a better location was found
{
updateLocation(potentialNew);
} else // no better location was found. Stay in place.
{
// System.out.println("...but immobile");
}
}
}
}
| eclab/mason | contrib/geomason/src/main/java/sim/app/geo/schellingpolygon/Person.java | 1,161 | //else if( p.geometry.distance( region.geometry ) >= bestDist) | line_comment | nl | /**
** Person.java
**
** Copyright 2011 by Sarah Wise, Mark Coletti, Andrew Crooks, and
** George Mason University.
**
** Licensed under the Academic Free License version 3.0
**
** See the file "LICENSE" for more information
**
** $Id$
**/
package sim.app.geo.schellingpolygon;
import java.util.ArrayList;
import sim.engine.SimState;
import sim.engine.Steppable;
public class Person implements Steppable
{
String color;
double preference;
Polygon region;
double personalThreshold = .5;
int numMoves = 0;
/**
* Constructor function
* @param c
*/
public Person(String c)
{
color = c;
}
/**
* Moves the Person to the given Polygon
* @param p - the Polygon to which the Person should move
*/
public void updateLocation(Polygon p)
{
// leave old tile, if previously was on a tile
if (region != null)
{
region.residents.remove(this);
region.soc = "UNOCCUPIED";
}
// go to new tile
region = p;
region.residents.add(this);
region.soc = color;
numMoves++; // increment the number of times moved
}
/**
*
* @param poly the proposed location
* @return whether the given Polygon is an acceptable location for the Person,
* based on the Person's personalThreshold
*/
boolean acceptable(Polygon poly)
{
// decide if Person is unhappy with surroundings
double unlike = 0, total = 0.;
for (Polygon p : poly.neighbors)
{
if (p.soc.equals("UNOCCUPIED")) // empty spaces don't count
{
continue;
}
if (!p.soc.equals(color)) // is this neighbor an unlike neighbor?
{
unlike++;
}
total++; // total count of neighbors
}
double percentUnlike = unlike / Math.max(total, 1); // don't divide by 0!
// if unhappy, return false
if (percentUnlike >= personalThreshold)
{
return false;
} else // if happy, return true
{
return true;
}
}
/**
* @param ps the list of Polygons open to the Person
* @return the closest available Polygon that meets the Person's needs, if such
* a Polygon exists. If no such Polygon exists, returns null.
*/
Polygon bestMove(ArrayList<Polygon> ps)
{
Polygon result = null;
double bestDist = Double.MAX_VALUE;
// go through all polygons and determine the best move to make
for (Polygon p : ps)
{
if (!p.soc.equals("UNOCCUPIED"))
{
continue; // not available
} else if (p.geometry.getCentroid().distance(
region.geometry.getCentroid()) >= bestDist) // distance between centroids
//else if(<SUF>
// distance between region borders
{
continue; // we already have a better option
} else if (!acceptable(p))
{
continue; // not an acceptable neighborhood
} else
{ // otherwise it's an acceptable region and the closest region yet
result = p;
bestDist = p.geometry.distance(region.geometry);
}
}
return result;
}
/**
* Determines whether the Person's current location is acceptable. If not, attempts
* to move the Person to a better location.
*/
@Override
public void step(SimState state)
{
if (!acceptable(region))
{ // the current location is unacceptable
// System.out.println("unacceptable!");
// try to find and move to a better location
Polygon potentialNew = bestMove(((PolySchelling) state).polys);
if (potentialNew != null) // a better location was found
{
updateLocation(potentialNew);
} else // no better location was found. Stay in place.
{
// System.out.println("...but immobile");
}
}
}
}
| False | 910 | 15 | 967 | 18 | 1,049 | 18 | 967 | 18 | 1,161 | 18 | false | false | false | false | false | true |
248 | 178223_2 | package dag15;
import java.lang.constant.Constable;
public class Java17Switch {
enum KLEUREN {
BLAUW, GEEL, ROOD;
}
public static void main(String[] args) {
int x = 8;
switch(x) {
default:
System.out.println("Wat is dit?");
break;
case 0:
System.out.println("X is nul");
break;
case 1:
System.out.println("X is een");
break;
case 2:
System.out.println("X is twee");
break;
}
// nieuwe versie, geen break nodig bij ->
switch(x) {
case 0 -> System.out.println("X is nul");
case 1 -> { System.out.println("X is een"); break; } // dit mag
case 2 -> System.out.println("X is twee");
default -> System.out.println("Wat is dit?");
}
// waarde returnen met switch statement
String getal = switch(x) {
case 0 -> "X is nul";
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// waarde returnen met switch statement en expliciet yield
String getal1 = switch(x) {
case 0: yield "X is nul";
case 1: yield "X is een";
case 2: yield "X is twee";
default: yield "Wat is dit?";
};
// waarde returnen met switch statement en meer acties
String getal2 = switch(x) {
case 0 -> {
System.out.println("Het is nul :)");
yield "X is nul";
}
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// enums en switch
KLEUREN kleur = KLEUREN.GEEL;
String s;
switch (kleur) {
case ROOD:
System.out.println("rood");
s = "rood";
break;
case BLAUW:
System.out.println("blauw");
s = "blauw";
break;
case GEEL:
s = "geel";
break;
default:
s = "watdan?!";
}
System.out.println(s);
// als je alle labels behandelt geen default nodig
var s1 = switch (kleur) {
case ROOD -> "rood";
case BLAUW -> KLEUREN.BLAUW;
case GEEL -> 2;
};
System.out.println(s1 + " " + s1.getClass());
}
}
| BrightBoost/ocp | src/main/java/dag15/Java17Switch.java | 754 | // waarde returnen met switch statement en expliciet yield | line_comment | nl | package dag15;
import java.lang.constant.Constable;
public class Java17Switch {
enum KLEUREN {
BLAUW, GEEL, ROOD;
}
public static void main(String[] args) {
int x = 8;
switch(x) {
default:
System.out.println("Wat is dit?");
break;
case 0:
System.out.println("X is nul");
break;
case 1:
System.out.println("X is een");
break;
case 2:
System.out.println("X is twee");
break;
}
// nieuwe versie, geen break nodig bij ->
switch(x) {
case 0 -> System.out.println("X is nul");
case 1 -> { System.out.println("X is een"); break; } // dit mag
case 2 -> System.out.println("X is twee");
default -> System.out.println("Wat is dit?");
}
// waarde returnen met switch statement
String getal = switch(x) {
case 0 -> "X is nul";
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// waarde returnen<SUF>
String getal1 = switch(x) {
case 0: yield "X is nul";
case 1: yield "X is een";
case 2: yield "X is twee";
default: yield "Wat is dit?";
};
// waarde returnen met switch statement en meer acties
String getal2 = switch(x) {
case 0 -> {
System.out.println("Het is nul :)");
yield "X is nul";
}
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// enums en switch
KLEUREN kleur = KLEUREN.GEEL;
String s;
switch (kleur) {
case ROOD:
System.out.println("rood");
s = "rood";
break;
case BLAUW:
System.out.println("blauw");
s = "blauw";
break;
case GEEL:
s = "geel";
break;
default:
s = "watdan?!";
}
System.out.println(s);
// als je alle labels behandelt geen default nodig
var s1 = switch (kleur) {
case ROOD -> "rood";
case BLAUW -> KLEUREN.BLAUW;
case GEEL -> 2;
};
System.out.println(s1 + " " + s1.getClass());
}
}
| True | 610 | 12 | 672 | 13 | 697 | 12 | 672 | 13 | 754 | 12 | false | false | false | false | false | true |
2,453 | 194301_0 | package be.ipeters.brol.cpbelcar.services;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.ibatis.javassist.bytecode.Descriptor.Iterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import be.ipeters.brol.cpbelcar.domain.Car;
import be.ipeters.brol.cpbelcar.domain.CarProduct;
import be.ipeters.brol.cpbelcar.domain.Production;
import be.ipeters.brol.cpbelcar.mappers.CarMapper;
@Service
public class CarService implements CrudService<Car, Integer> {
private boolean isCarCreationPossible = false;
private Integer pcgetProductId;
private Integer partStock = 0;
private Integer carStock = 0;
private Double partPrice=0.0;
private Double carPrice = 0.0;
private Integer partId = 0;
private Production production;
@Autowired
private CarMapper carMapper;
@Autowired
private SupplierOrderService supplierorderService;
@Autowired
private CarProductService cpService;
@Autowired
private ProductService productService;
@Autowired
private ProductionService productionService;
public CarService() {
super();
}
public CarService(CarMapper carMock) {
this.carMapper = carMock;
}
@Override
public void save(Car entity) {
/*
* bij een nieuwe wagen van een bepaald type dient de stock +1 te worden
* tegelijk 4 parts -1
*/
checkPartsAvailable(entity.getId());
if (isCarCreationPossible) {
// verminder de stock van elk onderdeel
partId=entity.getId();
adaptPartStock( partId);
// carMapper.insert(entity); // not creating a new line in the table, so update the stock
this.updateStockPlusOne(entity);
filloutProduction();
productionService.save(production);
System.out.println("We have: "+production.getDescription());
} else {
System.out.println("Not all parts are available...");
}
}
protected void filloutProduction() {
// fill out the fields orderId, orderlineId, description, lastUpdate
production=new Production(1, 1, 1, "created car of type "+partId, LocalDate.now());
}
protected void adaptPartStock(Integer carId) {
// verminder stock van elk van de 4 parts met id=partID
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
for (CarProduct pc : cpList) {
System.out.println("productService.updateProductStock(pc.getProductId()):"+pc.getProductId());
partStock=productService.getProductStock(pc.getProductId());
System.out.println("partStock="+partStock+", for part "+pc.getProductId()+", which is "+productService.findById(pc.getProductId()));
partStock--;
System.out.println("partStock="+partStock);
productService.updateStockMinOne(pc.getProductId());
}
}
public boolean checkPartsAvailable(Integer carId) {
Map<Integer, Integer> cpMap = new HashMap<Integer, Integer>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot produce a car with id " + carId + ".");
isCarCreationPossible = false;
} else { //
for (CarProduct pc : cpList) {
pcgetProductId = pc.getProductId();
System.out.println(pcgetProductId);
partStock = productService.findById(pcgetProductId).getStock();
cpMap.put(pcgetProductId, partStock);
switch (partStock) {
case 0:
// part not available
System.out
.println("part <" + productService.findById(pcgetProductId).getName() + "> not available");
System.out.println("Need to order this part...");
// create SupplierOrder // Order this part
supplierorderService.createSupplierOrderViaPartId(pcgetProductId);
isCarCreationPossible = false;
break;
default:
System.out.println("available!");
isCarCreationPossible = true;
}
}
// check if at least one part is missing to set isCarCreationPossible=false;
for (Map.Entry<Integer, Integer> entry : cpMap.entrySet()) {
if (entry.getValue() == 0) {
isCarCreationPossible = false;
}
}
}
System.out.println("isCarCreationPossible=" + isCarCreationPossible);
return isCarCreationPossible;
}
public Double calculateCarOrderPrice(Integer carId) {
System.out.println("carService - calculateCarOrderPrice");
carPrice=0.0;
Map<Integer, Double> cpMap = new HashMap<Integer, Double>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot calculate a price for car with id " + carId + ".");
} else {
for (CarProduct cp : cpList) {
pcgetProductId = cp.getProductId();
partPrice = productService.findById(pcgetProductId).getConsumerPrice();
System.out.println(pcgetProductId+ " costs " +partPrice);
carPrice+=partPrice;
}
}
System.out.println("carPrice=" + carPrice);
return carPrice;
}
@Override
public Car findById(Integer key) {
return carMapper.findById(key);
}
@Override
public List<Car> findAll() {
return carMapper.findAll();
}
@Override
public void deleteById(Integer key) {
carMapper.deleteById(key);
}
@Override
public void update(Car entity) {
carMapper.update(entity);
}
public Integer getCarStock(Integer key) {
return carMapper.getCarStock(key);
}
public void updateStockMinOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("carStock="+carStock);
carStock--;
System.out.println("carStock="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public void updateStockPlusOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
carStock++;
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public Integer getProductStock(int carProductId) {
// TODO Auto-generated method stub
return this.findById(carProductId).getStock();
}
}
| cpjjpeters/javafx1 | src/main/java/be/ipeters/brol/cpbelcar/services/CarService.java | 2,080 | /*
* bij een nieuwe wagen van een bepaald type dient de stock +1 te worden
* tegelijk 4 parts -1
*/ | block_comment | nl | package be.ipeters.brol.cpbelcar.services;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.ibatis.javassist.bytecode.Descriptor.Iterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import be.ipeters.brol.cpbelcar.domain.Car;
import be.ipeters.brol.cpbelcar.domain.CarProduct;
import be.ipeters.brol.cpbelcar.domain.Production;
import be.ipeters.brol.cpbelcar.mappers.CarMapper;
@Service
public class CarService implements CrudService<Car, Integer> {
private boolean isCarCreationPossible = false;
private Integer pcgetProductId;
private Integer partStock = 0;
private Integer carStock = 0;
private Double partPrice=0.0;
private Double carPrice = 0.0;
private Integer partId = 0;
private Production production;
@Autowired
private CarMapper carMapper;
@Autowired
private SupplierOrderService supplierorderService;
@Autowired
private CarProductService cpService;
@Autowired
private ProductService productService;
@Autowired
private ProductionService productionService;
public CarService() {
super();
}
public CarService(CarMapper carMock) {
this.carMapper = carMock;
}
@Override
public void save(Car entity) {
/*
* bij een nieuwe<SUF>*/
checkPartsAvailable(entity.getId());
if (isCarCreationPossible) {
// verminder de stock van elk onderdeel
partId=entity.getId();
adaptPartStock( partId);
// carMapper.insert(entity); // not creating a new line in the table, so update the stock
this.updateStockPlusOne(entity);
filloutProduction();
productionService.save(production);
System.out.println("We have: "+production.getDescription());
} else {
System.out.println("Not all parts are available...");
}
}
protected void filloutProduction() {
// fill out the fields orderId, orderlineId, description, lastUpdate
production=new Production(1, 1, 1, "created car of type "+partId, LocalDate.now());
}
protected void adaptPartStock(Integer carId) {
// verminder stock van elk van de 4 parts met id=partID
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
for (CarProduct pc : cpList) {
System.out.println("productService.updateProductStock(pc.getProductId()):"+pc.getProductId());
partStock=productService.getProductStock(pc.getProductId());
System.out.println("partStock="+partStock+", for part "+pc.getProductId()+", which is "+productService.findById(pc.getProductId()));
partStock--;
System.out.println("partStock="+partStock);
productService.updateStockMinOne(pc.getProductId());
}
}
public boolean checkPartsAvailable(Integer carId) {
Map<Integer, Integer> cpMap = new HashMap<Integer, Integer>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot produce a car with id " + carId + ".");
isCarCreationPossible = false;
} else { //
for (CarProduct pc : cpList) {
pcgetProductId = pc.getProductId();
System.out.println(pcgetProductId);
partStock = productService.findById(pcgetProductId).getStock();
cpMap.put(pcgetProductId, partStock);
switch (partStock) {
case 0:
// part not available
System.out
.println("part <" + productService.findById(pcgetProductId).getName() + "> not available");
System.out.println("Need to order this part...");
// create SupplierOrder // Order this part
supplierorderService.createSupplierOrderViaPartId(pcgetProductId);
isCarCreationPossible = false;
break;
default:
System.out.println("available!");
isCarCreationPossible = true;
}
}
// check if at least one part is missing to set isCarCreationPossible=false;
for (Map.Entry<Integer, Integer> entry : cpMap.entrySet()) {
if (entry.getValue() == 0) {
isCarCreationPossible = false;
}
}
}
System.out.println("isCarCreationPossible=" + isCarCreationPossible);
return isCarCreationPossible;
}
public Double calculateCarOrderPrice(Integer carId) {
System.out.println("carService - calculateCarOrderPrice");
carPrice=0.0;
Map<Integer, Double> cpMap = new HashMap<Integer, Double>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot calculate a price for car with id " + carId + ".");
} else {
for (CarProduct cp : cpList) {
pcgetProductId = cp.getProductId();
partPrice = productService.findById(pcgetProductId).getConsumerPrice();
System.out.println(pcgetProductId+ " costs " +partPrice);
carPrice+=partPrice;
}
}
System.out.println("carPrice=" + carPrice);
return carPrice;
}
@Override
public Car findById(Integer key) {
return carMapper.findById(key);
}
@Override
public List<Car> findAll() {
return carMapper.findAll();
}
@Override
public void deleteById(Integer key) {
carMapper.deleteById(key);
}
@Override
public void update(Car entity) {
carMapper.update(entity);
}
public Integer getCarStock(Integer key) {
return carMapper.getCarStock(key);
}
public void updateStockMinOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("carStock="+carStock);
carStock--;
System.out.println("carStock="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public void updateStockPlusOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
carStock++;
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public Integer getProductStock(int carProductId) {
// TODO Auto-generated method stub
return this.findById(carProductId).getStock();
}
}
| True | 1,517 | 35 | 1,876 | 36 | 1,860 | 32 | 1,876 | 36 | 2,255 | 40 | false | false | false | false | false | true |
2,753 | 43284_7 | import java.nio.BufferOverflowException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Spel {
ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
//ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
ArrayList<Speler> spelerArrayList = new ArrayList<>();
ArrayList<Gans> gansArrayList = new ArrayList<>();
ArrayList<Gans> speelVolgorde = new ArrayList<>();
Dobbelsteen steen1 = new Dobbelsteen();
Dobbelsteen steen2 = new Dobbelsteen();
public void maakSpelers() {
Bord das = new Bord();
das.fillVakjeArraylist();
System.out.println("hoeveel spelers zijn er");
Scanner in = new Scanner(System.in);
int userInput = 0;
int spelers = 0;
try {
userInput = Integer.parseInt(in.next());
System.out.println("je nummer was" + userInput);
if (userInput < 0) {
throw new ArithmeticException("negatief!");
}
if (userInput >= 7) {
throw new BufferOverflowException();
}
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println("");
}
spelers = userInput;
for (int i = 0; i < spelers; i++) {
try {
System.out.println("voer je naam in");
Scanner in2 = new Scanner(System.in);
String userNaamInput = in2.next();
System.out.println("je naam is " + userNaamInput);
Speler speler = new Speler("usernaam", i + 1);
System.out.println(userNaamInput + " jij bent speler " + i + 1 + " je ganskleur is " + gansKleuren.get(i));
Gans gans = new Gans(gansKleuren.get(i), speler);
spelerArrayList.add(speler);
gansArrayList.add(gans);
} catch (BufferOverflowException ignore) {
}
}
//speler volgorde bepalen
speelVolgorde = bepaalSpeelVolgorde(gansArrayList,steen1);
System.out.println(speelVolgorde);
//methode roll 1
System.out.println("druk op een toests om terug te gaan");
userInput = Integer.parseInt(in.next());
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println(" ");
}
// break; // breaks out of the loop, do not remove fully
} catch (NumberFormatException ignore) {
System.out.println("voer alleen getallen ");
} catch (ArithmeticException ignore) {
System.out.println("negatief ");
} catch (BufferOverflowException ignore) {
System.out.println("veel te groot getal ");
}
}
public void speelronde(ArrayList<Gans> speelVolgorde, Dobbelsteen steen1, Dobbelsteen steen2 ){
for (Gans gans: speelVolgorde) {
if (gans.BeurtOverslaan == true){
continue;
}
int waardeSteen1 = steen1.roll();
int waardeSteen2 = steen2.roll();
// TODO: 13/10/2022 // check voor specialle combi bij en eerste worp
int totaalWaardeWorp = waardeSteen1 + waardeSteen2;
int curPos = gans.getPositie();
}
// TODO: 12/10/2022 for each speler, check if beurt overslaan, roll 2 dobbelstenen, addup, check if arrayIndex empty, move on array
}
public ArrayList<Gans> bepaalSpeelVolgorde(ArrayList<Gans> gansArrayList, Dobbelsteen steen){
ArrayList<Gans> newSpeelvolgorde = new ArrayList<>();
//int[] rolls = new int[gansArrayList.size()];
int x= 0;
ArrayList<Integer> rolls = new ArrayList<>();
for (Gans i: gansArrayList) {
int currentRoll = steen.roll();
while (rolls.contains(currentRoll)){ // waarneer 2 spelers dezelfde worp hebben moet de laatste speler gooien tot hij een niet eerder gegooide waarde krijgt.
currentRoll = steen.roll();
}
rolls.add(currentRoll);
x+=1;
}
// sort players ; sort indexes; how to remember reference to player
// [5,3,4,1]
// get index max; place index in new VolgordeArray, set value in worp array to 0;
for (Gans ii: gansArrayList) {
int max = 0;
for (int val : rolls) {
if (val > max) {
max = val;
}
}
int indexMax = rolls.indexOf(max);
newSpeelvolgorde.add(gansArrayList.get(indexMax));
rolls.set(indexMax, 0);
}
return newSpeelvolgorde;
}
}
| gabeplz/ganzebordStan | src/Spel.java | 1,513 | // waarneer 2 spelers dezelfde worp hebben moet de laatste speler gooien tot hij een niet eerder gegooide waarde krijgt. | line_comment | nl | import java.nio.BufferOverflowException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Spel {
ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
//ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
ArrayList<Speler> spelerArrayList = new ArrayList<>();
ArrayList<Gans> gansArrayList = new ArrayList<>();
ArrayList<Gans> speelVolgorde = new ArrayList<>();
Dobbelsteen steen1 = new Dobbelsteen();
Dobbelsteen steen2 = new Dobbelsteen();
public void maakSpelers() {
Bord das = new Bord();
das.fillVakjeArraylist();
System.out.println("hoeveel spelers zijn er");
Scanner in = new Scanner(System.in);
int userInput = 0;
int spelers = 0;
try {
userInput = Integer.parseInt(in.next());
System.out.println("je nummer was" + userInput);
if (userInput < 0) {
throw new ArithmeticException("negatief!");
}
if (userInput >= 7) {
throw new BufferOverflowException();
}
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println("");
}
spelers = userInput;
for (int i = 0; i < spelers; i++) {
try {
System.out.println("voer je naam in");
Scanner in2 = new Scanner(System.in);
String userNaamInput = in2.next();
System.out.println("je naam is " + userNaamInput);
Speler speler = new Speler("usernaam", i + 1);
System.out.println(userNaamInput + " jij bent speler " + i + 1 + " je ganskleur is " + gansKleuren.get(i));
Gans gans = new Gans(gansKleuren.get(i), speler);
spelerArrayList.add(speler);
gansArrayList.add(gans);
} catch (BufferOverflowException ignore) {
}
}
//speler volgorde bepalen
speelVolgorde = bepaalSpeelVolgorde(gansArrayList,steen1);
System.out.println(speelVolgorde);
//methode roll 1
System.out.println("druk op een toests om terug te gaan");
userInput = Integer.parseInt(in.next());
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println(" ");
}
// break; // breaks out of the loop, do not remove fully
} catch (NumberFormatException ignore) {
System.out.println("voer alleen getallen ");
} catch (ArithmeticException ignore) {
System.out.println("negatief ");
} catch (BufferOverflowException ignore) {
System.out.println("veel te groot getal ");
}
}
public void speelronde(ArrayList<Gans> speelVolgorde, Dobbelsteen steen1, Dobbelsteen steen2 ){
for (Gans gans: speelVolgorde) {
if (gans.BeurtOverslaan == true){
continue;
}
int waardeSteen1 = steen1.roll();
int waardeSteen2 = steen2.roll();
// TODO: 13/10/2022 // check voor specialle combi bij en eerste worp
int totaalWaardeWorp = waardeSteen1 + waardeSteen2;
int curPos = gans.getPositie();
}
// TODO: 12/10/2022 for each speler, check if beurt overslaan, roll 2 dobbelstenen, addup, check if arrayIndex empty, move on array
}
public ArrayList<Gans> bepaalSpeelVolgorde(ArrayList<Gans> gansArrayList, Dobbelsteen steen){
ArrayList<Gans> newSpeelvolgorde = new ArrayList<>();
//int[] rolls = new int[gansArrayList.size()];
int x= 0;
ArrayList<Integer> rolls = new ArrayList<>();
for (Gans i: gansArrayList) {
int currentRoll = steen.roll();
while (rolls.contains(currentRoll)){ // waarneer 2<SUF>
currentRoll = steen.roll();
}
rolls.add(currentRoll);
x+=1;
}
// sort players ; sort indexes; how to remember reference to player
// [5,3,4,1]
// get index max; place index in new VolgordeArray, set value in worp array to 0;
for (Gans ii: gansArrayList) {
int max = 0;
for (int val : rolls) {
if (val > max) {
max = val;
}
}
int indexMax = rolls.indexOf(max);
newSpeelvolgorde.add(gansArrayList.get(indexMax));
rolls.set(indexMax, 0);
}
return newSpeelvolgorde;
}
}
| True | 1,201 | 36 | 1,344 | 44 | 1,326 | 28 | 1,344 | 44 | 1,477 | 40 | false | false | false | false | false | true |
299 | 57243_0 | package cheese.squeeze.gameObjects;_x000D_
_x000D_
import java.util.Iterator;_x000D_
import java.util.List;_x000D_
_x000D_
import cheese.squeeze.helpers.AssetLoader;_x000D_
_x000D_
import com.badlogic.gdx.Gdx;_x000D_
import com.badlogic.gdx.math.MathUtils;_x000D_
import com.badlogic.gdx.math.Vector2;_x000D_
_x000D_
//TODO: direction bijhouden, en veranderen als we aan een gotopoint belanden._x000D_
public class Mouse {_x000D_
_x000D_
private Vector2 position;_x000D_
private Vector2 velocity;_x000D_
private final float FLIKERING =100;_x000D_
private float EYEOPEN;_x000D_
private boolean open = true;_x000D_
_x000D_
private float orignSpeed;_x000D_
private float speed;_x000D_
private float tolerance = 0.02f;_x000D_
_x000D_
private Vector2 absolutePosition;_x000D_
_x000D_
private float rotation;_x000D_
private Vector2 mouseNose = AssetLoader.mouseNose;_x000D_
_x000D_
private Line currentLine;_x000D_
private Line nextLine;_x000D_
private Vector2 goToOrientation;_x000D_
private Vector2 nextGoToPoint;_x000D_
private boolean ended = false;_x000D_
_x000D_
public Mouse(float speed, Line line){_x000D_
EYEOPEN = (float) (FLIKERING*Math.random());_x000D_
float x = line.getX1();_x000D_
float y = line.getY1();_x000D_
//float y = 0;_x000D_
position = new Vector2(x,y);_x000D_
this.currentLine = line;_x000D_
this.speed = speed;_x000D_
this.orignSpeed = speed;_x000D_
//position = new Vector2(x-(mouseNose.x), y- (mouseNose.y));_x000D_
_x000D_
velocity = new Vector2(0, 0);_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
updatePath();_x000D_
}_x000D_
_x000D_
public boolean isOnHorizontalLine() {_x000D_
if(currentLine instanceof HorizontalLine) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void update(float delta) {_x000D_
EYEOPEN--;_x000D_
_x000D_
if (nextGoToPoint != null) {_x000D_
if(atIntersection()) {_x000D_
//System.out.println("intersection reached!");_x000D_
//the mouse stands now at the previous nextGoToPoint_x000D_
setPosition(nextGoToPoint.x, nextGoToPoint.y);_x000D_
//nextGoToPoint is yet to be determined_x000D_
nextGoToPoint = null;_x000D_
//This mouse is now on the new line. _x000D_
//If there is no next line, the mouse stays on this line._x000D_
currentLine = (nextLine != null) ? nextLine : currentLine;_x000D_
//nextLine is yet to be determined._x000D_
nextLine = null;_x000D_
if (currentLine instanceof VerticalLine){_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
} else if (currentLine instanceof HorizontalLine) {_x000D_
if (getPosition().equals(currentLine.getPoint1()))_x000D_
goToOrientation = currentLine.getPoint2().cpy().sub(currentLine.getPoint1());_x000D_
else_x000D_
goToOrientation = currentLine.getPoint1().cpy().sub(currentLine.getPoint2());_x000D_
}_x000D_
//updateVelocityDirection();_x000D_
//pick a new destination_x000D_
updatePath();_x000D_
}_x000D_
//set the mouses new speed._x000D_
if (atIntersection()) {_x000D_
//The mouse ran into something with a dead end._x000D_
((VerticalLine) currentLine).getGoal().activate();_x000D_
velocity.set(Vector2.Zero);_x000D_
ended = true;_x000D_
} else {_x000D_
updateVelocityDirection();_x000D_
}_x000D_
//move the mouse._x000D_
updateVelocityDirection();_x000D_
// setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta);_x000D_
setPosition(getX() + velocity.x * 1, getY() + velocity.y * 1);_x000D_
//System.out.println(this.rotation);_x000D_
} _x000D_
}_x000D_
_x000D_
private void updateVelocityDirection() {_x000D_
if(!ended) {_x000D_
float angle = (float) Math.atan2(nextGoToPoint.y - getY(), nextGoToPoint.x - getX());_x000D_
velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed);_x000D_
//set the mouses angle._x000D_
setRotation(angle * MathUtils.radiansToDegrees);_x000D_
}_x000D_
else {_x000D_
setRotation(90);_x000D_
}_x000D_
}_x000D_
_x000D_
public void updatePath() {_x000D_
Vector2 nextIntersection = currentLine.getNextIntersection(getPosition(), goToOrientation);_x000D_
nextLine = currentLine.getNeighbour(getPosition(), goToOrientation);_x000D_
if (nextIntersection == null) {_x000D_
nextGoToPoint = currentLine.getEndPoint(getPosition(), velocity);_x000D_
} else {_x000D_
nextGoToPoint = nextIntersection;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean atIntersection() {_x000D_
float dynTolerance = speed / tolerance * Gdx.graphics.getDeltaTime();_x000D_
//System.out.println("dyn tol: " + dynTolerance);_x000D_
return Math.abs(nextGoToPoint.x - getX()) <= dynTolerance _x000D_
&& Math.abs(nextGoToPoint.y - getY()) <= dynTolerance;_x000D_
}_x000D_
_x000D_
private void setRotation(float f) {_x000D_
this.rotation = f;_x000D_
_x000D_
}_x000D_
_x000D_
public float getX() {_x000D_
return position.x;_x000D_
}_x000D_
_x000D_
public float getY() {_x000D_
return position.y;_x000D_
}_x000D_
_x000D_
private void setPosition(float x,float y) {_x000D_
this.position.set(x, y);_x000D_
}_x000D_
_x000D_
public float getXAbs() {_x000D_
return this.absolutePosition.x;_x000D_
}_x000D_
_x000D_
public float getYAbs() {_x000D_
return this.absolutePosition.y;_x000D_
}_x000D_
_x000D_
public float getRotation() {_x000D_
return rotation;_x000D_
}_x000D_
_x000D_
_x000D_
public Vector2 getPosition() {_x000D_
return position;_x000D_
}_x000D_
_x000D_
public boolean isEnded() {_x000D_
return ended ;_x000D_
}_x000D_
_x000D_
public float getSpeed() {_x000D_
// TODO Auto-generated method stub_x000D_
return velocity.x + velocity.y;_x000D_
}_x000D_
_x000D_
//public void changeNextWayPoints(ArrayList<Vector2> newWaypoints) {_x000D_
// this.setPath(nPath);_x000D_
//}_x000D_
_x000D_
public boolean eyesOpen() {_x000D_
if(EYEOPEN < 0 && !open) {_x000D_
EYEOPEN = (float) ((FLIKERING*2)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
if(EYEOPEN < 0 && open) {_x000D_
EYEOPEN = (float) ((FLIKERING/5)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
return open;_x000D_
}_x000D_
_x000D_
public void setSpeed(float angle) {_x000D_
this.speed = this.orignSpeed + this.orignSpeed*angle;_x000D_
}_x000D_
_x000D_
public float getSpeedLine() {_x000D_
return this.speed - this.orignSpeed;_x000D_
}_x000D_
_x000D_
}_x000D_
| Camambar/CheeseSqueeze | core/src/cheese/squeeze/gameObjects/Mouse.java | 1,855 | //TODO: direction bijhouden, en veranderen als we aan een gotopoint belanden._x000D_ | line_comment | nl | package cheese.squeeze.gameObjects;_x000D_
_x000D_
import java.util.Iterator;_x000D_
import java.util.List;_x000D_
_x000D_
import cheese.squeeze.helpers.AssetLoader;_x000D_
_x000D_
import com.badlogic.gdx.Gdx;_x000D_
import com.badlogic.gdx.math.MathUtils;_x000D_
import com.badlogic.gdx.math.Vector2;_x000D_
_x000D_
//TODO: direction<SUF>
public class Mouse {_x000D_
_x000D_
private Vector2 position;_x000D_
private Vector2 velocity;_x000D_
private final float FLIKERING =100;_x000D_
private float EYEOPEN;_x000D_
private boolean open = true;_x000D_
_x000D_
private float orignSpeed;_x000D_
private float speed;_x000D_
private float tolerance = 0.02f;_x000D_
_x000D_
private Vector2 absolutePosition;_x000D_
_x000D_
private float rotation;_x000D_
private Vector2 mouseNose = AssetLoader.mouseNose;_x000D_
_x000D_
private Line currentLine;_x000D_
private Line nextLine;_x000D_
private Vector2 goToOrientation;_x000D_
private Vector2 nextGoToPoint;_x000D_
private boolean ended = false;_x000D_
_x000D_
public Mouse(float speed, Line line){_x000D_
EYEOPEN = (float) (FLIKERING*Math.random());_x000D_
float x = line.getX1();_x000D_
float y = line.getY1();_x000D_
//float y = 0;_x000D_
position = new Vector2(x,y);_x000D_
this.currentLine = line;_x000D_
this.speed = speed;_x000D_
this.orignSpeed = speed;_x000D_
//position = new Vector2(x-(mouseNose.x), y- (mouseNose.y));_x000D_
_x000D_
velocity = new Vector2(0, 0);_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
updatePath();_x000D_
}_x000D_
_x000D_
public boolean isOnHorizontalLine() {_x000D_
if(currentLine instanceof HorizontalLine) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void update(float delta) {_x000D_
EYEOPEN--;_x000D_
_x000D_
if (nextGoToPoint != null) {_x000D_
if(atIntersection()) {_x000D_
//System.out.println("intersection reached!");_x000D_
//the mouse stands now at the previous nextGoToPoint_x000D_
setPosition(nextGoToPoint.x, nextGoToPoint.y);_x000D_
//nextGoToPoint is yet to be determined_x000D_
nextGoToPoint = null;_x000D_
//This mouse is now on the new line. _x000D_
//If there is no next line, the mouse stays on this line._x000D_
currentLine = (nextLine != null) ? nextLine : currentLine;_x000D_
//nextLine is yet to be determined._x000D_
nextLine = null;_x000D_
if (currentLine instanceof VerticalLine){_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
} else if (currentLine instanceof HorizontalLine) {_x000D_
if (getPosition().equals(currentLine.getPoint1()))_x000D_
goToOrientation = currentLine.getPoint2().cpy().sub(currentLine.getPoint1());_x000D_
else_x000D_
goToOrientation = currentLine.getPoint1().cpy().sub(currentLine.getPoint2());_x000D_
}_x000D_
//updateVelocityDirection();_x000D_
//pick a new destination_x000D_
updatePath();_x000D_
}_x000D_
//set the mouses new speed._x000D_
if (atIntersection()) {_x000D_
//The mouse ran into something with a dead end._x000D_
((VerticalLine) currentLine).getGoal().activate();_x000D_
velocity.set(Vector2.Zero);_x000D_
ended = true;_x000D_
} else {_x000D_
updateVelocityDirection();_x000D_
}_x000D_
//move the mouse._x000D_
updateVelocityDirection();_x000D_
// setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta);_x000D_
setPosition(getX() + velocity.x * 1, getY() + velocity.y * 1);_x000D_
//System.out.println(this.rotation);_x000D_
} _x000D_
}_x000D_
_x000D_
private void updateVelocityDirection() {_x000D_
if(!ended) {_x000D_
float angle = (float) Math.atan2(nextGoToPoint.y - getY(), nextGoToPoint.x - getX());_x000D_
velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed);_x000D_
//set the mouses angle._x000D_
setRotation(angle * MathUtils.radiansToDegrees);_x000D_
}_x000D_
else {_x000D_
setRotation(90);_x000D_
}_x000D_
}_x000D_
_x000D_
public void updatePath() {_x000D_
Vector2 nextIntersection = currentLine.getNextIntersection(getPosition(), goToOrientation);_x000D_
nextLine = currentLine.getNeighbour(getPosition(), goToOrientation);_x000D_
if (nextIntersection == null) {_x000D_
nextGoToPoint = currentLine.getEndPoint(getPosition(), velocity);_x000D_
} else {_x000D_
nextGoToPoint = nextIntersection;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean atIntersection() {_x000D_
float dynTolerance = speed / tolerance * Gdx.graphics.getDeltaTime();_x000D_
//System.out.println("dyn tol: " + dynTolerance);_x000D_
return Math.abs(nextGoToPoint.x - getX()) <= dynTolerance _x000D_
&& Math.abs(nextGoToPoint.y - getY()) <= dynTolerance;_x000D_
}_x000D_
_x000D_
private void setRotation(float f) {_x000D_
this.rotation = f;_x000D_
_x000D_
}_x000D_
_x000D_
public float getX() {_x000D_
return position.x;_x000D_
}_x000D_
_x000D_
public float getY() {_x000D_
return position.y;_x000D_
}_x000D_
_x000D_
private void setPosition(float x,float y) {_x000D_
this.position.set(x, y);_x000D_
}_x000D_
_x000D_
public float getXAbs() {_x000D_
return this.absolutePosition.x;_x000D_
}_x000D_
_x000D_
public float getYAbs() {_x000D_
return this.absolutePosition.y;_x000D_
}_x000D_
_x000D_
public float getRotation() {_x000D_
return rotation;_x000D_
}_x000D_
_x000D_
_x000D_
public Vector2 getPosition() {_x000D_
return position;_x000D_
}_x000D_
_x000D_
public boolean isEnded() {_x000D_
return ended ;_x000D_
}_x000D_
_x000D_
public float getSpeed() {_x000D_
// TODO Auto-generated method stub_x000D_
return velocity.x + velocity.y;_x000D_
}_x000D_
_x000D_
//public void changeNextWayPoints(ArrayList<Vector2> newWaypoints) {_x000D_
// this.setPath(nPath);_x000D_
//}_x000D_
_x000D_
public boolean eyesOpen() {_x000D_
if(EYEOPEN < 0 && !open) {_x000D_
EYEOPEN = (float) ((FLIKERING*2)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
if(EYEOPEN < 0 && open) {_x000D_
EYEOPEN = (float) ((FLIKERING/5)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
return open;_x000D_
}_x000D_
_x000D_
public void setSpeed(float angle) {_x000D_
this.speed = this.orignSpeed + this.orignSpeed*angle;_x000D_
}_x000D_
_x000D_
public float getSpeedLine() {_x000D_
return this.speed - this.orignSpeed;_x000D_
}_x000D_
_x000D_
}_x000D_
| True | 2,610 | 28 | 2,932 | 29 | 2,921 | 24 | 2,932 | 29 | 3,304 | 29 | false | false | false | false | false | true |
2,157 | 33415_10 | package me.devsaki.hentoid.enums;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.HashSet;
import java.util.Set;
import io.objectbox.converter.PropertyConverter;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.json.core.JsonSiteSettings;
import me.devsaki.hentoid.util.network.HttpHelperKt;
import timber.log.Timber;
/**
* Site enumerator
*/
public enum Site {
// NOTE : to maintain compatiblity with saved JSON files and prefs, do _not_ edit either existing names or codes
FAKKU(0, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku), // Legacy support for old fakku archives
PURURIN(1, "Pururin", "https://pururin.to", R.drawable.ic_site_pururin),
HITOMI(2, "hitomi", "https://hitomi.la", R.drawable.ic_site_hitomi),
NHENTAI(3, "nhentai", "https://nhentai.net", R.drawable.ic_site_nhentai),
TSUMINO(4, "tsumino", "https://www.tsumino.com", R.drawable.ic_site_tsumino),
HENTAICAFE(5, "hentaicafe", "https://hentai.cafe", R.drawable.ic_site_hentaicafe),
ASMHENTAI(6, "asmhentai", "https://asmhentai.com", R.drawable.ic_site_asmhentai),
ASMHENTAI_COMICS(7, "asmhentai comics", "https://comics.asmhentai.com", R.drawable.ic_site_asmcomics),
EHENTAI(8, "e-hentai", "https://e-hentai.org", R.drawable.ic_site_ehentai),
FAKKU2(9, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku),
NEXUS(10, "Hentai Nexus", "https://hentainexus.com", R.drawable.ic_site_nexus),
MUSES(11, "8Muses", "https://www.8muses.com", R.drawable.ic_site_8muses),
DOUJINS(12, "doujins.com", "https://doujins.com/", R.drawable.ic_site_doujins),
LUSCIOUS(13, "luscious.net", "https://members.luscious.net/manga/", R.drawable.ic_site_luscious),
EXHENTAI(14, "exhentai", "https://exhentai.org", R.drawable.ic_site_exhentai),
PORNCOMIX(15, "porncomixonline", "https://www.porncomixonline.net/", R.drawable.ic_site_porncomix),
HBROWSE(16, "Hbrowse", "https://www.hbrowse.com/", R.drawable.ic_site_hbrowse),
HENTAI2READ(17, "Hentai2Read", "https://hentai2read.com/", R.drawable.ic_site_hentai2read),
HENTAIFOX(18, "Hentaifox", "https://hentaifox.com", R.drawable.ic_site_hentaifox),
MRM(19, "MyReadingManga", "https://myreadingmanga.info/", R.drawable.ic_site_mrm),
MANHWA(20, "ManwhaHentai", "https://manhwahentai.me/", R.drawable.ic_site_manhwa),
IMHENTAI(21, "Imhentai", "https://imhentai.xxx", R.drawable.ic_site_imhentai),
TOONILY(22, "Toonily", "https://toonily.com/", R.drawable.ic_site_toonily),
ALLPORNCOMIC(23, "Allporncomic", "https://allporncomic.com/", R.drawable.ic_site_allporncomic),
PIXIV(24, "Pixiv", "https://www.pixiv.net/", R.drawable.ic_site_pixiv),
MANHWA18(25, "Manhwa18", "https://manhwa18.com/", R.drawable.ic_site_manhwa18),
MULTPORN(26, "Multporn", "https://multporn.net/", R.drawable.ic_site_multporn),
SIMPLY(27, "Simply Hentai", "https://www.simply-hentai.com/", R.drawable.ic_site_simply),
HDPORNCOMICS(28, "HD Porn Comics", "https://hdporncomics.com/", R.drawable.ic_site_hdporncomics),
EDOUJIN(29, "Edoujin", "https://edoujin.net/", R.drawable.ic_site_edoujin),
KSK(30, "Koushoku", "https://ksk.moe", R.drawable.ic_site_ksk),
ANCHIRA(31, "Anchira", "https://anchira.to", R.drawable.ic_site_anchira),
DEVIANTART(32, "DeviantArt", "https://www.deviantart.com/", R.drawable.ic_site_deviantart),
NONE(98, "none", "", R.drawable.ic_attribute_source), // External library; fallback site
PANDA(99, "panda", "https://www.mangapanda.com", R.drawable.ic_site_panda); // Safe-for-work/wife/gf option; not used anymore and kept here for retrocompatibility
private static final Site[] INVISIBLE_SITES = {
NEXUS, // Dead
HBROWSE, // Dead
HENTAICAFE, // Removed as per Fakku request + dead
KSK, // Dead
FAKKU, // Old Fakku; kept for retrocompatibility
FAKKU2, // Dropped after Fakku decided to flag downloading accounts and IPs
ASMHENTAI_COMICS, // Does not work directly
PANDA, // Dropped; kept for retrocompatibility
NONE // Technical fallback
};
private final int code;
private final String description;
private final String url;
private final int ico;
// Default values overridden in sites.json
private boolean useMobileAgent = true;
private boolean useHentoidAgent = false;
private boolean useWebviewAgent = true;
// Download behaviour control
private boolean hasBackupURLs = false;
private boolean hasCoverBasedPageUpdates = false;
private boolean useCloudflare = false;
private boolean hasUniqueBookId = false;
private int requestsCapPerSecond = -1;
private int parallelDownloadCap = 0;
// Controls for "Mark downloaded/merged" in browser
private int bookCardDepth = 2;
private Set<String> bookCardExcludedParentClasses = new HashSet<>();
// Controls for "Mark books with blocked tags" in browser
private int galleryHeight = -1;
// Determine which Jsoup output to use when rewriting the HTML
// 0 : html; 1 : xml
private int jsoupOutputSyntax = 0;
Site(int code,
String description,
String url,
int ico) {
this.code = code;
this.description = description;
this.url = url;
this.ico = ico;
}
public static Site searchByCode(long code) {
for (Site s : values())
if (s.getCode() == code) return s;
return NONE;
}
// Same as ValueOf with a fallback to NONE
// (vital for forward compatibility)
public static Site searchByName(String name) {
for (Site s : values())
if (s.name().equalsIgnoreCase(name)) return s;
return NONE;
}
@Nullable
public static Site searchByUrl(String url) {
if (null == url || url.isEmpty()) {
Timber.w("Invalid url");
return null;
}
for (Site s : Site.values())
if (s.code > 0 && HttpHelperKt.getDomainFromUri(url).equalsIgnoreCase(HttpHelperKt.getDomainFromUri(s.url)))
return s;
return Site.NONE;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
public int getIco() {
return ico;
}
public boolean useMobileAgent() {
return useMobileAgent;
}
public boolean useHentoidAgent() {
return useHentoidAgent;
}
public boolean useWebviewAgent() {
return useWebviewAgent;
}
public boolean hasBackupURLs() {
return hasBackupURLs;
}
public boolean hasCoverBasedPageUpdates() {
return hasCoverBasedPageUpdates;
}
public boolean isUseCloudflare() {
return useCloudflare;
}
public boolean hasUniqueBookId() {
return hasUniqueBookId;
}
public int getRequestsCapPerSecond() {
return requestsCapPerSecond;
}
public int getParallelDownloadCap() {
return parallelDownloadCap;
}
public int getBookCardDepth() {
return bookCardDepth;
}
public Set<String> getBookCardExcludedParentClasses() {
return bookCardExcludedParentClasses;
}
public int getGalleryHeight() {
return galleryHeight;
}
public int getJsoupOutputSyntax() { return jsoupOutputSyntax; }
public boolean isVisible() {
for (Site s : INVISIBLE_SITES) if (s.equals(this)) return false;
return true;
}
public String getFolder() {
if (this == FAKKU)
return "Downloads";
else
return description;
}
public String getUserAgent() {
if (useMobileAgent())
return HttpHelperKt.getMobileUserAgent(useHentoidAgent(), useWebviewAgent());
else
return HttpHelperKt.getDesktopUserAgent(useHentoidAgent(), useWebviewAgent());
}
public void updateFrom(@NonNull final JsonSiteSettings.JsonSite jsonSite) {
if (jsonSite.getUseMobileAgent() != null) useMobileAgent = jsonSite.getUseMobileAgent();
if (jsonSite.getUseHentoidAgent() != null) useHentoidAgent = jsonSite.getUseHentoidAgent();
if (jsonSite.getUseWebviewAgent() != null) useWebviewAgent = jsonSite.getUseWebviewAgent();
if (jsonSite.getHasBackupURLs() != null) hasBackupURLs = jsonSite.getHasBackupURLs();
if (jsonSite.getHasCoverBasedPageUpdates() != null)
hasCoverBasedPageUpdates = jsonSite.getHasCoverBasedPageUpdates();
if (jsonSite.getUseCloudflare() != null)
useCloudflare = jsonSite.getUseCloudflare();
if (jsonSite.getHasUniqueBookId() != null)
hasUniqueBookId = jsonSite.getHasUniqueBookId();
if (jsonSite.getParallelDownloadCap() != null)
parallelDownloadCap = jsonSite.getParallelDownloadCap();
if (jsonSite.getRequestsCapPerSecond() != null)
requestsCapPerSecond = jsonSite.getRequestsCapPerSecond();
if (jsonSite.getBookCardDepth() != null)
bookCardDepth = jsonSite.getBookCardDepth();
if (jsonSite.getBookCardExcludedParentClasses() != null)
bookCardExcludedParentClasses = new HashSet<>(jsonSite.getBookCardExcludedParentClasses());
if (jsonSite.getGalleryHeight() != null)
galleryHeight = jsonSite.getGalleryHeight();
if (jsonSite.getJsoupOutputSyntax() != null)
jsoupOutputSyntax = jsonSite.getJsoupOutputSyntax();
}
public static class SiteConverter implements PropertyConverter<Site, Long> {
@Override
public Site convertToEntityProperty(Long databaseValue) {
if (databaseValue == null) {
return Site.NONE;
}
for (Site site : Site.values()) {
if (site.getCode() == databaseValue) {
return site;
}
}
return Site.NONE;
}
@Override
public Long convertToDatabaseValue(Site entityProperty) {
return entityProperty == null ? null : (long) entityProperty.getCode();
}
}
}
| avluis/Hentoid | app/src/main/java/me/devsaki/hentoid/enums/Site.java | 3,408 | // Default values overridden in sites.json | line_comment | nl | package me.devsaki.hentoid.enums;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.HashSet;
import java.util.Set;
import io.objectbox.converter.PropertyConverter;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.json.core.JsonSiteSettings;
import me.devsaki.hentoid.util.network.HttpHelperKt;
import timber.log.Timber;
/**
* Site enumerator
*/
public enum Site {
// NOTE : to maintain compatiblity with saved JSON files and prefs, do _not_ edit either existing names or codes
FAKKU(0, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku), // Legacy support for old fakku archives
PURURIN(1, "Pururin", "https://pururin.to", R.drawable.ic_site_pururin),
HITOMI(2, "hitomi", "https://hitomi.la", R.drawable.ic_site_hitomi),
NHENTAI(3, "nhentai", "https://nhentai.net", R.drawable.ic_site_nhentai),
TSUMINO(4, "tsumino", "https://www.tsumino.com", R.drawable.ic_site_tsumino),
HENTAICAFE(5, "hentaicafe", "https://hentai.cafe", R.drawable.ic_site_hentaicafe),
ASMHENTAI(6, "asmhentai", "https://asmhentai.com", R.drawable.ic_site_asmhentai),
ASMHENTAI_COMICS(7, "asmhentai comics", "https://comics.asmhentai.com", R.drawable.ic_site_asmcomics),
EHENTAI(8, "e-hentai", "https://e-hentai.org", R.drawable.ic_site_ehentai),
FAKKU2(9, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku),
NEXUS(10, "Hentai Nexus", "https://hentainexus.com", R.drawable.ic_site_nexus),
MUSES(11, "8Muses", "https://www.8muses.com", R.drawable.ic_site_8muses),
DOUJINS(12, "doujins.com", "https://doujins.com/", R.drawable.ic_site_doujins),
LUSCIOUS(13, "luscious.net", "https://members.luscious.net/manga/", R.drawable.ic_site_luscious),
EXHENTAI(14, "exhentai", "https://exhentai.org", R.drawable.ic_site_exhentai),
PORNCOMIX(15, "porncomixonline", "https://www.porncomixonline.net/", R.drawable.ic_site_porncomix),
HBROWSE(16, "Hbrowse", "https://www.hbrowse.com/", R.drawable.ic_site_hbrowse),
HENTAI2READ(17, "Hentai2Read", "https://hentai2read.com/", R.drawable.ic_site_hentai2read),
HENTAIFOX(18, "Hentaifox", "https://hentaifox.com", R.drawable.ic_site_hentaifox),
MRM(19, "MyReadingManga", "https://myreadingmanga.info/", R.drawable.ic_site_mrm),
MANHWA(20, "ManwhaHentai", "https://manhwahentai.me/", R.drawable.ic_site_manhwa),
IMHENTAI(21, "Imhentai", "https://imhentai.xxx", R.drawable.ic_site_imhentai),
TOONILY(22, "Toonily", "https://toonily.com/", R.drawable.ic_site_toonily),
ALLPORNCOMIC(23, "Allporncomic", "https://allporncomic.com/", R.drawable.ic_site_allporncomic),
PIXIV(24, "Pixiv", "https://www.pixiv.net/", R.drawable.ic_site_pixiv),
MANHWA18(25, "Manhwa18", "https://manhwa18.com/", R.drawable.ic_site_manhwa18),
MULTPORN(26, "Multporn", "https://multporn.net/", R.drawable.ic_site_multporn),
SIMPLY(27, "Simply Hentai", "https://www.simply-hentai.com/", R.drawable.ic_site_simply),
HDPORNCOMICS(28, "HD Porn Comics", "https://hdporncomics.com/", R.drawable.ic_site_hdporncomics),
EDOUJIN(29, "Edoujin", "https://edoujin.net/", R.drawable.ic_site_edoujin),
KSK(30, "Koushoku", "https://ksk.moe", R.drawable.ic_site_ksk),
ANCHIRA(31, "Anchira", "https://anchira.to", R.drawable.ic_site_anchira),
DEVIANTART(32, "DeviantArt", "https://www.deviantart.com/", R.drawable.ic_site_deviantart),
NONE(98, "none", "", R.drawable.ic_attribute_source), // External library; fallback site
PANDA(99, "panda", "https://www.mangapanda.com", R.drawable.ic_site_panda); // Safe-for-work/wife/gf option; not used anymore and kept here for retrocompatibility
private static final Site[] INVISIBLE_SITES = {
NEXUS, // Dead
HBROWSE, // Dead
HENTAICAFE, // Removed as per Fakku request + dead
KSK, // Dead
FAKKU, // Old Fakku; kept for retrocompatibility
FAKKU2, // Dropped after Fakku decided to flag downloading accounts and IPs
ASMHENTAI_COMICS, // Does not work directly
PANDA, // Dropped; kept for retrocompatibility
NONE // Technical fallback
};
private final int code;
private final String description;
private final String url;
private final int ico;
// Default values<SUF>
private boolean useMobileAgent = true;
private boolean useHentoidAgent = false;
private boolean useWebviewAgent = true;
// Download behaviour control
private boolean hasBackupURLs = false;
private boolean hasCoverBasedPageUpdates = false;
private boolean useCloudflare = false;
private boolean hasUniqueBookId = false;
private int requestsCapPerSecond = -1;
private int parallelDownloadCap = 0;
// Controls for "Mark downloaded/merged" in browser
private int bookCardDepth = 2;
private Set<String> bookCardExcludedParentClasses = new HashSet<>();
// Controls for "Mark books with blocked tags" in browser
private int galleryHeight = -1;
// Determine which Jsoup output to use when rewriting the HTML
// 0 : html; 1 : xml
private int jsoupOutputSyntax = 0;
Site(int code,
String description,
String url,
int ico) {
this.code = code;
this.description = description;
this.url = url;
this.ico = ico;
}
public static Site searchByCode(long code) {
for (Site s : values())
if (s.getCode() == code) return s;
return NONE;
}
// Same as ValueOf with a fallback to NONE
// (vital for forward compatibility)
public static Site searchByName(String name) {
for (Site s : values())
if (s.name().equalsIgnoreCase(name)) return s;
return NONE;
}
@Nullable
public static Site searchByUrl(String url) {
if (null == url || url.isEmpty()) {
Timber.w("Invalid url");
return null;
}
for (Site s : Site.values())
if (s.code > 0 && HttpHelperKt.getDomainFromUri(url).equalsIgnoreCase(HttpHelperKt.getDomainFromUri(s.url)))
return s;
return Site.NONE;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
public int getIco() {
return ico;
}
public boolean useMobileAgent() {
return useMobileAgent;
}
public boolean useHentoidAgent() {
return useHentoidAgent;
}
public boolean useWebviewAgent() {
return useWebviewAgent;
}
public boolean hasBackupURLs() {
return hasBackupURLs;
}
public boolean hasCoverBasedPageUpdates() {
return hasCoverBasedPageUpdates;
}
public boolean isUseCloudflare() {
return useCloudflare;
}
public boolean hasUniqueBookId() {
return hasUniqueBookId;
}
public int getRequestsCapPerSecond() {
return requestsCapPerSecond;
}
public int getParallelDownloadCap() {
return parallelDownloadCap;
}
public int getBookCardDepth() {
return bookCardDepth;
}
public Set<String> getBookCardExcludedParentClasses() {
return bookCardExcludedParentClasses;
}
public int getGalleryHeight() {
return galleryHeight;
}
public int getJsoupOutputSyntax() { return jsoupOutputSyntax; }
public boolean isVisible() {
for (Site s : INVISIBLE_SITES) if (s.equals(this)) return false;
return true;
}
public String getFolder() {
if (this == FAKKU)
return "Downloads";
else
return description;
}
public String getUserAgent() {
if (useMobileAgent())
return HttpHelperKt.getMobileUserAgent(useHentoidAgent(), useWebviewAgent());
else
return HttpHelperKt.getDesktopUserAgent(useHentoidAgent(), useWebviewAgent());
}
public void updateFrom(@NonNull final JsonSiteSettings.JsonSite jsonSite) {
if (jsonSite.getUseMobileAgent() != null) useMobileAgent = jsonSite.getUseMobileAgent();
if (jsonSite.getUseHentoidAgent() != null) useHentoidAgent = jsonSite.getUseHentoidAgent();
if (jsonSite.getUseWebviewAgent() != null) useWebviewAgent = jsonSite.getUseWebviewAgent();
if (jsonSite.getHasBackupURLs() != null) hasBackupURLs = jsonSite.getHasBackupURLs();
if (jsonSite.getHasCoverBasedPageUpdates() != null)
hasCoverBasedPageUpdates = jsonSite.getHasCoverBasedPageUpdates();
if (jsonSite.getUseCloudflare() != null)
useCloudflare = jsonSite.getUseCloudflare();
if (jsonSite.getHasUniqueBookId() != null)
hasUniqueBookId = jsonSite.getHasUniqueBookId();
if (jsonSite.getParallelDownloadCap() != null)
parallelDownloadCap = jsonSite.getParallelDownloadCap();
if (jsonSite.getRequestsCapPerSecond() != null)
requestsCapPerSecond = jsonSite.getRequestsCapPerSecond();
if (jsonSite.getBookCardDepth() != null)
bookCardDepth = jsonSite.getBookCardDepth();
if (jsonSite.getBookCardExcludedParentClasses() != null)
bookCardExcludedParentClasses = new HashSet<>(jsonSite.getBookCardExcludedParentClasses());
if (jsonSite.getGalleryHeight() != null)
galleryHeight = jsonSite.getGalleryHeight();
if (jsonSite.getJsoupOutputSyntax() != null)
jsoupOutputSyntax = jsonSite.getJsoupOutputSyntax();
}
public static class SiteConverter implements PropertyConverter<Site, Long> {
@Override
public Site convertToEntityProperty(Long databaseValue) {
if (databaseValue == null) {
return Site.NONE;
}
for (Site site : Site.values()) {
if (site.getCode() == databaseValue) {
return site;
}
}
return Site.NONE;
}
@Override
public Long convertToDatabaseValue(Site entityProperty) {
return entityProperty == null ? null : (long) entityProperty.getCode();
}
}
}
| False | 2,704 | 7 | 2,996 | 8 | 3,070 | 8 | 2,996 | 8 | 3,443 | 9 | false | false | false | false | false | true |
1,827 | 99855_5 | package be.valuya.bob.core.reader;
import be.valuya.advantaje.core.AdvantajeRecord;
import be.valuya.bob.core.domain.BobAccount;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;
public class BobAccountRecordReader {
public BobAccount readAccount(AdvantajeRecord advantajeRecord) {
String aid = advantajeRecord.getValue("AID"); //: (STRING, 10): 1
Optional<Boolean> aistitle = advantajeRecord.getValueOptional("AISTITLE"); //: (LOGICAL, 1): true
Optional<String> heading1 = advantajeRecord.getValueOptional("HEADING1"); //: (STRING, 40): Fonds propres
Optional<String> heading2 = advantajeRecord.getValueOptional("HEADING2"); //: (STRING, 40): Eigen vermogen
Optional<String> longheading1 = advantajeRecord.getValueOptional("LONGHEADING1"); //: (STRING, 120): Fonds propres, provisions pour risques et charges et dettes à plus d'un an
Optional<String> longheading2 = advantajeRecord.getValueOptional("LONGHEADING2"); //: (STRING, 120): Eigen vermogen, voorzieningen voor risico's en kosten en schulden op meer dan een jaar
Optional<String> asecondid = advantajeRecord.getValueOptional("ASECONDID"); //: (STRING, 10):
Optional<String> afree = advantajeRecord.getValueOptional("AFREE"); //: (STRING, 40):
Optional<String> acat = advantajeRecord.getValueOptional("ACAT"); //: (STRING, 3):
Optional<String> aintcat = advantajeRecord.getValueOptional("AINTCAT"); //: (STRING, 10):
Optional<String> acatcomm = advantajeRecord.getValueOptional("ACATCOMM"); //: (STRING, 1):
Optional<String> adbcd = advantajeRecord.getValueOptional("ADBCD"); //: (STRING, 1): C
Optional<Boolean> aiscost = advantajeRecord.getValueOptional("AISCOST"); //: (LOGICAL, 1): [-]
Optional<String> avattype = advantajeRecord.getValueOptional("AVATTYPE"); //: (STRING, 1):
Optional<String> avatenat1 = advantajeRecord.getValueOptional("AVATENAT1"); //: (STRING, 3):
Optional<String> avatenat2 = advantajeRecord.getValueOptional("AVATENAT2"); //: (STRING, 3):
Optional<Double> avatecmp = advantajeRecord.getValueOptional("AVATECMP"); //: (DOUBLE, 8): [-]
Optional<String> avatnnat1 = advantajeRecord.getValueOptional("AVATNNAT1"); //: (STRING, 3):
Optional<String> avatnnat2 = advantajeRecord.getValueOptional("AVATNNAT2"); //: (STRING, 3):
Optional<Double> avatncmp = advantajeRecord.getValueOptional("AVATNCMP"); //: (DOUBLE, 8): [-]
Optional<String> avatinat1 = advantajeRecord.getValueOptional("AVATINAT1"); //: (STRING, 3):
Optional<String> avatinat2 = advantajeRecord.getValueOptional("AVATINAT2"); //: (STRING, 3):
Optional<Double> avaticmp = advantajeRecord.getValueOptional("AVATICMP"); //: (DOUBLE, 8): [-]
Optional<Boolean> aissummary = advantajeRecord.getValueOptional("AISSUMMARY"); //: (LOGICAL, 1): false
Optional<Boolean> aisstatus = advantajeRecord.getValueOptional("AISSTATUS"); //: (LOGICAL, 1): [-]
Optional<Boolean> aisreadonl = advantajeRecord.getValueOptional("AISREADONL"); //: (LOGICAL, 1): false
Optional<Boolean> aissecret = advantajeRecord.getValueOptional("AISSECRET"); //: (LOGICAL, 1): false
Optional<Boolean> vtravfa = advantajeRecord.getValueOptional("VTRAVFA"); //: (LOGICAL, 1): [-]
Optional<Boolean> aismatch = advantajeRecord.getValueOptional("AISMATCH"); //: (LOGICAL, 1): false
Optional<String> depacc = advantajeRecord.getValueOptional("DEPACC"); //: (STRING, 10):
Optional<String> provacc = advantajeRecord.getValueOptional("PROVACC"); //: (STRING, 10):
Optional<Boolean> hisintrastat = advantajeRecord.getValueOptional("HISINTRASTAT"); //: (LOGICAL, 1): [-]
Optional<Integer> amatchno = advantajeRecord.getValueOptional("AMATCHNO"); //: (INTEGER, 4): [-]
Optional<String> abalance = advantajeRecord.getValueOptional("ABALANCE"); //: (STRING, 10): LIABILIT
Optional<String> arem = advantajeRecord.getValueOptional("AREM"); //: (STRING, 35):
Optional<Boolean> avatcas = advantajeRecord.getValueOptional("AVATCAS"); //: (LOGICAL, 1): [-]
Optional<Boolean> acctsecondid = advantajeRecord.getValueOptional("ACCTSECONDID"); //: (LOGICAL, 1): [-]
Optional<byte[]> amemo = advantajeRecord.getValueOptional("AMEMO"); //: (BINARY, 9): [B@3cda1055
Optional<Double> prcndcharges = advantajeRecord.getValueOptional("PRCNDCHARGES"); //: (DOUBLE, 8): 0.0
Optional<Double> prcprivate = advantajeRecord.getValueOptional("PRCPRIVATE"); //: (DOUBLE, 8): 0.0
Optional<String> typendcharges = advantajeRecord.getValueOptional("TYPENDCHARGES"); //: (STRING, 12):
Optional<String> createdby = advantajeRecord.getValueOptional("CREATEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> createdon = advantajeRecord.getValueOptional("CREATEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> modifiedby = advantajeRecord.getValueOptional("MODIFIEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> modifiedon = advantajeRecord.getValueOptional("MODIFIEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> trftstatus = advantajeRecord.getValueOptional("TRFTSTATUS"); //: (STRING, 3): A
Optional<String> stationid = advantajeRecord.getValueOptional("STATIONID"); //: (STRING, 3):
Optional<String> afixtype = advantajeRecord.getValueOptional("AFIXTYPE"); //: (STRING, 10):
Optional<Boolean> asleeping = advantajeRecord.getValueOptional("ASLEEPING"); //: (LOGICAL, 1): false
Optional<Boolean> discadvnot = advantajeRecord.getValueOptional("DISCADVNOT"); //: (LOGICAL, 1): false
Optional<String> subtype = advantajeRecord.getValueOptional("SUBTYPE"); //: (STRING, 10): LEQUITY
Optional<String> provaccexc = advantajeRecord.getValueOptional("PROVACCEXC"); //: (STRING, 10):
Optional<String> annexid = advantajeRecord.getValueOptional("ANNEXID"); //: (STRING, 15):
Optional<String> altacct = advantajeRecord.getValueOptional("ALTACCT"); //: (STRING, 10):
Optional<String> aautoop = advantajeRecord.getValueOptional("AAUTOOP"); //: (STRING, 2):
Optional<String> aoldid = advantajeRecord.getValueOptional("AOLDID"); //: (STRING, 10):
Optional<String> aprivaccount = advantajeRecord.getValueOptional("APRIVACCOUNT"); //: (STRING, 10):
Optional<String> oldheading1 = advantajeRecord.getValueOptional("OLDHEADING1"); //: (STRING, 40):
Optional<String> oldheading2 = advantajeRecord.getValueOptional("OLDHEADING2"); //: (STRING, 40):
Optional<Boolean> naeprior = advantajeRecord.getValueOptional("NAEPRIOR"); //: (LOGICAL, 1): [-]
Optional<Boolean> asynchro = advantajeRecord.getValueOptional("ASYNCHRO"); //: (LOGICAL, 1): true
Optional<String> apcnid = advantajeRecord.getValueOptional("APCNID"); //: (STRING, 10):
Optional<BigDecimal> avatecmpOptional = avatecmp.map(this::toBigDecimal);
Optional<BigDecimal> avatncmpOptional = avatncmp.map(this::toBigDecimal);
Optional<BigDecimal> avaticmpOptional = avaticmp.map(this::toBigDecimal);
Optional<BigDecimal> prcndchargesOptional = prcndcharges.map(this::toBigDecimal);
Optional<BigDecimal> prcprivateOptional = prcprivate.map(this::toBigDecimal);
BobAccount bobAccount = new BobAccount();
bobAccount.setAid(aid);
bobAccount.setaIsTitle(aistitle.orElse(null));
bobAccount.setHeading1(heading1.orElse(null));
bobAccount.setHeading2(heading2.orElse(null));
bobAccount.setLongHeading1(longheading1.orElse(null));
bobAccount.setLongHeading2(longheading2.orElse(null));
bobAccount.setSecondId(asecondid.orElse(null));
bobAccount.setFree(afree.orElse(null));
bobAccount.setaCat(acat.orElse(null));
bobAccount.setaIntCat(aintcat.orElse(null));
bobAccount.setaCatComm(acatcomm.orElse(null));
bobAccount.setAdbcd(adbcd.orElse(null));
bobAccount.setAiscost(aiscost.orElse(null));
bobAccount.setAvattype(avattype.orElse(null));
bobAccount.setAvatenat1(avatenat1.orElse(null));
bobAccount.setAvatenat2(avatenat2.orElse(null));
bobAccount.setAvatecmp(avatecmpOptional.orElse(null));
bobAccount.setAvatnnat1(avatnnat1.orElse(null));
bobAccount.setAvatnnat2(avatnnat2.orElse(null));
bobAccount.setAvatncmp(avatncmpOptional.orElse(null));
bobAccount.setAvatinat1(avatinat1.orElse(null));
bobAccount.setAvatinat2(avatinat2.orElse(null));
bobAccount.setAvaticmp(avaticmpOptional.orElse(null));
bobAccount.setAissummary(aissummary.orElse(null));
bobAccount.setAisstatus(aisstatus.orElse(null));
bobAccount.setAisreadonl(aisreadonl.orElse(null));
bobAccount.setAissecret(aissecret.orElse(null));
bobAccount.setVtravfa(vtravfa.orElse(null));
bobAccount.setAismatch(aismatch.orElse(null));
bobAccount.setDepacc(depacc.orElse(null));
bobAccount.setProvacc(provacc.orElse(null));
bobAccount.setHisintrastat(hisintrastat.orElse(null));
bobAccount.setAmatchno(amatchno.orElse(null));
bobAccount.setAbalance(abalance.orElse(null));
bobAccount.setArem(arem.orElse(null));
bobAccount.setAvatcas(avatcas.orElse(null));
bobAccount.setAcctsecondid(acctsecondid.orElse(null));
bobAccount.setAmemo(amemo.orElse(null));
bobAccount.setPrcndcharges(prcndchargesOptional.orElse(null));
bobAccount.setPrcprivate(prcprivateOptional.orElse(null));
bobAccount.setTypendcharges(typendcharges.orElse(null));
bobAccount.setCreatedby(createdby.orElse(null));
bobAccount.setCreatedon(createdon.orElse(null));
bobAccount.setModifiedby(modifiedby.orElse(null));
bobAccount.setModifiedon(modifiedon.orElse(null));
bobAccount.setTrftstatus(trftstatus.orElse(null));
bobAccount.setStationid(stationid.orElse(null));
bobAccount.setAfixtype(afixtype.orElse(null));
bobAccount.setAsleeping(asleeping.orElse(null));
bobAccount.setDiscadvnot(discadvnot.orElse(null));
bobAccount.setSubtype(subtype.orElse(null));
bobAccount.setProvaccexc(provaccexc.orElse(null));
bobAccount.setAnnexid(annexid.orElse(null));
bobAccount.setAltacct(altacct.orElse(null));
bobAccount.setAautoop(aautoop.orElse(null));
bobAccount.setAoldid(aoldid.orElse(null));
bobAccount.setAprivaccount(aprivaccount.orElse(null));
bobAccount.setOldheading1(oldheading1.orElse(null));
bobAccount.setOldheading2(oldheading2.orElse(null));
bobAccount.setNaeprior(naeprior.orElse(null));
bobAccount.setAsynchro(asynchro.orElse(null));
bobAccount.setApcnid(apcnid.orElse(null));
return bobAccount;
}
private BigDecimal toBigDecimal(Double aDouble) {
return BigDecimal.valueOf(aDouble);
}
}
| Valuya/bobthetinker | bobthetinker-core/src/main/java/be/valuya/bob/core/reader/BobAccountRecordReader.java | 3,727 | //: (STRING, 120): Eigen vermogen, voorzieningen voor risico's en kosten en schulden op meer dan een jaar | line_comment | nl | package be.valuya.bob.core.reader;
import be.valuya.advantaje.core.AdvantajeRecord;
import be.valuya.bob.core.domain.BobAccount;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;
public class BobAccountRecordReader {
public BobAccount readAccount(AdvantajeRecord advantajeRecord) {
String aid = advantajeRecord.getValue("AID"); //: (STRING, 10): 1
Optional<Boolean> aistitle = advantajeRecord.getValueOptional("AISTITLE"); //: (LOGICAL, 1): true
Optional<String> heading1 = advantajeRecord.getValueOptional("HEADING1"); //: (STRING, 40): Fonds propres
Optional<String> heading2 = advantajeRecord.getValueOptional("HEADING2"); //: (STRING, 40): Eigen vermogen
Optional<String> longheading1 = advantajeRecord.getValueOptional("LONGHEADING1"); //: (STRING, 120): Fonds propres, provisions pour risques et charges et dettes à plus d'un an
Optional<String> longheading2 = advantajeRecord.getValueOptional("LONGHEADING2"); //: (STRING,<SUF>
Optional<String> asecondid = advantajeRecord.getValueOptional("ASECONDID"); //: (STRING, 10):
Optional<String> afree = advantajeRecord.getValueOptional("AFREE"); //: (STRING, 40):
Optional<String> acat = advantajeRecord.getValueOptional("ACAT"); //: (STRING, 3):
Optional<String> aintcat = advantajeRecord.getValueOptional("AINTCAT"); //: (STRING, 10):
Optional<String> acatcomm = advantajeRecord.getValueOptional("ACATCOMM"); //: (STRING, 1):
Optional<String> adbcd = advantajeRecord.getValueOptional("ADBCD"); //: (STRING, 1): C
Optional<Boolean> aiscost = advantajeRecord.getValueOptional("AISCOST"); //: (LOGICAL, 1): [-]
Optional<String> avattype = advantajeRecord.getValueOptional("AVATTYPE"); //: (STRING, 1):
Optional<String> avatenat1 = advantajeRecord.getValueOptional("AVATENAT1"); //: (STRING, 3):
Optional<String> avatenat2 = advantajeRecord.getValueOptional("AVATENAT2"); //: (STRING, 3):
Optional<Double> avatecmp = advantajeRecord.getValueOptional("AVATECMP"); //: (DOUBLE, 8): [-]
Optional<String> avatnnat1 = advantajeRecord.getValueOptional("AVATNNAT1"); //: (STRING, 3):
Optional<String> avatnnat2 = advantajeRecord.getValueOptional("AVATNNAT2"); //: (STRING, 3):
Optional<Double> avatncmp = advantajeRecord.getValueOptional("AVATNCMP"); //: (DOUBLE, 8): [-]
Optional<String> avatinat1 = advantajeRecord.getValueOptional("AVATINAT1"); //: (STRING, 3):
Optional<String> avatinat2 = advantajeRecord.getValueOptional("AVATINAT2"); //: (STRING, 3):
Optional<Double> avaticmp = advantajeRecord.getValueOptional("AVATICMP"); //: (DOUBLE, 8): [-]
Optional<Boolean> aissummary = advantajeRecord.getValueOptional("AISSUMMARY"); //: (LOGICAL, 1): false
Optional<Boolean> aisstatus = advantajeRecord.getValueOptional("AISSTATUS"); //: (LOGICAL, 1): [-]
Optional<Boolean> aisreadonl = advantajeRecord.getValueOptional("AISREADONL"); //: (LOGICAL, 1): false
Optional<Boolean> aissecret = advantajeRecord.getValueOptional("AISSECRET"); //: (LOGICAL, 1): false
Optional<Boolean> vtravfa = advantajeRecord.getValueOptional("VTRAVFA"); //: (LOGICAL, 1): [-]
Optional<Boolean> aismatch = advantajeRecord.getValueOptional("AISMATCH"); //: (LOGICAL, 1): false
Optional<String> depacc = advantajeRecord.getValueOptional("DEPACC"); //: (STRING, 10):
Optional<String> provacc = advantajeRecord.getValueOptional("PROVACC"); //: (STRING, 10):
Optional<Boolean> hisintrastat = advantajeRecord.getValueOptional("HISINTRASTAT"); //: (LOGICAL, 1): [-]
Optional<Integer> amatchno = advantajeRecord.getValueOptional("AMATCHNO"); //: (INTEGER, 4): [-]
Optional<String> abalance = advantajeRecord.getValueOptional("ABALANCE"); //: (STRING, 10): LIABILIT
Optional<String> arem = advantajeRecord.getValueOptional("AREM"); //: (STRING, 35):
Optional<Boolean> avatcas = advantajeRecord.getValueOptional("AVATCAS"); //: (LOGICAL, 1): [-]
Optional<Boolean> acctsecondid = advantajeRecord.getValueOptional("ACCTSECONDID"); //: (LOGICAL, 1): [-]
Optional<byte[]> amemo = advantajeRecord.getValueOptional("AMEMO"); //: (BINARY, 9): [B@3cda1055
Optional<Double> prcndcharges = advantajeRecord.getValueOptional("PRCNDCHARGES"); //: (DOUBLE, 8): 0.0
Optional<Double> prcprivate = advantajeRecord.getValueOptional("PRCPRIVATE"); //: (DOUBLE, 8): 0.0
Optional<String> typendcharges = advantajeRecord.getValueOptional("TYPENDCHARGES"); //: (STRING, 12):
Optional<String> createdby = advantajeRecord.getValueOptional("CREATEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> createdon = advantajeRecord.getValueOptional("CREATEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> modifiedby = advantajeRecord.getValueOptional("MODIFIEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> modifiedon = advantajeRecord.getValueOptional("MODIFIEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> trftstatus = advantajeRecord.getValueOptional("TRFTSTATUS"); //: (STRING, 3): A
Optional<String> stationid = advantajeRecord.getValueOptional("STATIONID"); //: (STRING, 3):
Optional<String> afixtype = advantajeRecord.getValueOptional("AFIXTYPE"); //: (STRING, 10):
Optional<Boolean> asleeping = advantajeRecord.getValueOptional("ASLEEPING"); //: (LOGICAL, 1): false
Optional<Boolean> discadvnot = advantajeRecord.getValueOptional("DISCADVNOT"); //: (LOGICAL, 1): false
Optional<String> subtype = advantajeRecord.getValueOptional("SUBTYPE"); //: (STRING, 10): LEQUITY
Optional<String> provaccexc = advantajeRecord.getValueOptional("PROVACCEXC"); //: (STRING, 10):
Optional<String> annexid = advantajeRecord.getValueOptional("ANNEXID"); //: (STRING, 15):
Optional<String> altacct = advantajeRecord.getValueOptional("ALTACCT"); //: (STRING, 10):
Optional<String> aautoop = advantajeRecord.getValueOptional("AAUTOOP"); //: (STRING, 2):
Optional<String> aoldid = advantajeRecord.getValueOptional("AOLDID"); //: (STRING, 10):
Optional<String> aprivaccount = advantajeRecord.getValueOptional("APRIVACCOUNT"); //: (STRING, 10):
Optional<String> oldheading1 = advantajeRecord.getValueOptional("OLDHEADING1"); //: (STRING, 40):
Optional<String> oldheading2 = advantajeRecord.getValueOptional("OLDHEADING2"); //: (STRING, 40):
Optional<Boolean> naeprior = advantajeRecord.getValueOptional("NAEPRIOR"); //: (LOGICAL, 1): [-]
Optional<Boolean> asynchro = advantajeRecord.getValueOptional("ASYNCHRO"); //: (LOGICAL, 1): true
Optional<String> apcnid = advantajeRecord.getValueOptional("APCNID"); //: (STRING, 10):
Optional<BigDecimal> avatecmpOptional = avatecmp.map(this::toBigDecimal);
Optional<BigDecimal> avatncmpOptional = avatncmp.map(this::toBigDecimal);
Optional<BigDecimal> avaticmpOptional = avaticmp.map(this::toBigDecimal);
Optional<BigDecimal> prcndchargesOptional = prcndcharges.map(this::toBigDecimal);
Optional<BigDecimal> prcprivateOptional = prcprivate.map(this::toBigDecimal);
BobAccount bobAccount = new BobAccount();
bobAccount.setAid(aid);
bobAccount.setaIsTitle(aistitle.orElse(null));
bobAccount.setHeading1(heading1.orElse(null));
bobAccount.setHeading2(heading2.orElse(null));
bobAccount.setLongHeading1(longheading1.orElse(null));
bobAccount.setLongHeading2(longheading2.orElse(null));
bobAccount.setSecondId(asecondid.orElse(null));
bobAccount.setFree(afree.orElse(null));
bobAccount.setaCat(acat.orElse(null));
bobAccount.setaIntCat(aintcat.orElse(null));
bobAccount.setaCatComm(acatcomm.orElse(null));
bobAccount.setAdbcd(adbcd.orElse(null));
bobAccount.setAiscost(aiscost.orElse(null));
bobAccount.setAvattype(avattype.orElse(null));
bobAccount.setAvatenat1(avatenat1.orElse(null));
bobAccount.setAvatenat2(avatenat2.orElse(null));
bobAccount.setAvatecmp(avatecmpOptional.orElse(null));
bobAccount.setAvatnnat1(avatnnat1.orElse(null));
bobAccount.setAvatnnat2(avatnnat2.orElse(null));
bobAccount.setAvatncmp(avatncmpOptional.orElse(null));
bobAccount.setAvatinat1(avatinat1.orElse(null));
bobAccount.setAvatinat2(avatinat2.orElse(null));
bobAccount.setAvaticmp(avaticmpOptional.orElse(null));
bobAccount.setAissummary(aissummary.orElse(null));
bobAccount.setAisstatus(aisstatus.orElse(null));
bobAccount.setAisreadonl(aisreadonl.orElse(null));
bobAccount.setAissecret(aissecret.orElse(null));
bobAccount.setVtravfa(vtravfa.orElse(null));
bobAccount.setAismatch(aismatch.orElse(null));
bobAccount.setDepacc(depacc.orElse(null));
bobAccount.setProvacc(provacc.orElse(null));
bobAccount.setHisintrastat(hisintrastat.orElse(null));
bobAccount.setAmatchno(amatchno.orElse(null));
bobAccount.setAbalance(abalance.orElse(null));
bobAccount.setArem(arem.orElse(null));
bobAccount.setAvatcas(avatcas.orElse(null));
bobAccount.setAcctsecondid(acctsecondid.orElse(null));
bobAccount.setAmemo(amemo.orElse(null));
bobAccount.setPrcndcharges(prcndchargesOptional.orElse(null));
bobAccount.setPrcprivate(prcprivateOptional.orElse(null));
bobAccount.setTypendcharges(typendcharges.orElse(null));
bobAccount.setCreatedby(createdby.orElse(null));
bobAccount.setCreatedon(createdon.orElse(null));
bobAccount.setModifiedby(modifiedby.orElse(null));
bobAccount.setModifiedon(modifiedon.orElse(null));
bobAccount.setTrftstatus(trftstatus.orElse(null));
bobAccount.setStationid(stationid.orElse(null));
bobAccount.setAfixtype(afixtype.orElse(null));
bobAccount.setAsleeping(asleeping.orElse(null));
bobAccount.setDiscadvnot(discadvnot.orElse(null));
bobAccount.setSubtype(subtype.orElse(null));
bobAccount.setProvaccexc(provaccexc.orElse(null));
bobAccount.setAnnexid(annexid.orElse(null));
bobAccount.setAltacct(altacct.orElse(null));
bobAccount.setAautoop(aautoop.orElse(null));
bobAccount.setAoldid(aoldid.orElse(null));
bobAccount.setAprivaccount(aprivaccount.orElse(null));
bobAccount.setOldheading1(oldheading1.orElse(null));
bobAccount.setOldheading2(oldheading2.orElse(null));
bobAccount.setNaeprior(naeprior.orElse(null));
bobAccount.setAsynchro(asynchro.orElse(null));
bobAccount.setApcnid(apcnid.orElse(null));
return bobAccount;
}
private BigDecimal toBigDecimal(Double aDouble) {
return BigDecimal.valueOf(aDouble);
}
}
| True | 2,951 | 32 | 3,321 | 37 | 3,299 | 28 | 3,320 | 36 | 3,745 | 35 | false | false | false | false | false | true |
2,563 | 69191_0 | package nl.han;
import java.util.ArrayList;
public class Antwoordformulier {
private ArrayList<String> gegevenAntwoorden;
private int aantalGoed;
private Score score;
private Long startTijd;
public Antwoordformulier(){
gegevenAntwoorden = new ArrayList<>();
score = new Score();
startTijd = System.currentTimeMillis();
aantalGoed = 0;
}
public void vraagGoed(){ aantalGoed++;};
public void addAntwoord(String gegevenAntwoord){
gegevenAntwoorden.add(gegevenAntwoord);
}
public String getAntwoord(int i){
return gegevenAntwoorden.get(i);
}
public void maakWoord(String woord){
score.checkWoord(woord);
}
public int berekenScore(Berekening berekening){
var verstrekenTijd = System.currentTimeMillis() - startTijd;
//Bereken de score met berekening A
return score.berekenScore(berekening, verstrekenTijd, aantalGoed);
}
}
| diorcula/OOAD_casestudy-parola | source/src/nl/han/Antwoordformulier.java | 293 | //Bereken de score met berekening A | line_comment | nl | package nl.han;
import java.util.ArrayList;
public class Antwoordformulier {
private ArrayList<String> gegevenAntwoorden;
private int aantalGoed;
private Score score;
private Long startTijd;
public Antwoordformulier(){
gegevenAntwoorden = new ArrayList<>();
score = new Score();
startTijd = System.currentTimeMillis();
aantalGoed = 0;
}
public void vraagGoed(){ aantalGoed++;};
public void addAntwoord(String gegevenAntwoord){
gegevenAntwoorden.add(gegevenAntwoord);
}
public String getAntwoord(int i){
return gegevenAntwoorden.get(i);
}
public void maakWoord(String woord){
score.checkWoord(woord);
}
public int berekenScore(Berekening berekening){
var verstrekenTijd = System.currentTimeMillis() - startTijd;
//Bereken de<SUF>
return score.berekenScore(berekening, verstrekenTijd, aantalGoed);
}
}
| True | 242 | 10 | 275 | 11 | 254 | 9 | 275 | 11 | 302 | 11 | false | false | false | false | false | true |
4,279 | 118739_2 | /*
* Copyright 2012-2014 eBay Software Foundation and selendroid committers.
*
* 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 io.selendroid.server.handler;
import io.selendroid.server.common.Response;
import io.selendroid.server.common.SelendroidResponse;
import io.selendroid.server.common.http.HttpRequest;
import io.selendroid.server.model.AndroidElement;
import io.selendroid.server.model.Session;
import io.selendroid.server.util.SelendroidLogger;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Send keys to a given element.
*/
public class SendKeysToElement extends SafeRequestHandler {
public SendKeysToElement(String mappedUri) {
super(mappedUri);
}
@Override
public Response safeHandle(HttpRequest request) throws JSONException {
SelendroidLogger.info("send keys to element command");
String id = getElementId(request);
AndroidElement element = getElementFromCache(request, id);
String[] keysToSend = extractKeysToSendFromPayload(request);
if (isNativeEvents(request)) {
element.enterText(keysToSend);
}else{
element.setText(keysToSend);
}
return new SelendroidResponse(getSessionId(request), "");
}
boolean isNativeEvents(HttpRequest request) {
JSONObject config =
getSelendroidDriver(request).getSession().getCommandConfiguration(
Session.SEND_KEYS_TO_ELEMENT);
if (config != null && config.has(Session.NATIVE_EVENTS_PROPERTY)) {
try {
return config.getBoolean(Session.NATIVE_EVENTS_PROPERTY);
} catch (JSONException e) {}
}
// default is native events
return true;
}
}
| selendroid/selendroid | selendroid-server/src/main/java/io/selendroid/server/handler/SendKeysToElement.java | 608 | // default is native events | line_comment | nl | /*
* Copyright 2012-2014 eBay Software Foundation and selendroid committers.
*
* 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 io.selendroid.server.handler;
import io.selendroid.server.common.Response;
import io.selendroid.server.common.SelendroidResponse;
import io.selendroid.server.common.http.HttpRequest;
import io.selendroid.server.model.AndroidElement;
import io.selendroid.server.model.Session;
import io.selendroid.server.util.SelendroidLogger;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Send keys to a given element.
*/
public class SendKeysToElement extends SafeRequestHandler {
public SendKeysToElement(String mappedUri) {
super(mappedUri);
}
@Override
public Response safeHandle(HttpRequest request) throws JSONException {
SelendroidLogger.info("send keys to element command");
String id = getElementId(request);
AndroidElement element = getElementFromCache(request, id);
String[] keysToSend = extractKeysToSendFromPayload(request);
if (isNativeEvents(request)) {
element.enterText(keysToSend);
}else{
element.setText(keysToSend);
}
return new SelendroidResponse(getSessionId(request), "");
}
boolean isNativeEvents(HttpRequest request) {
JSONObject config =
getSelendroidDriver(request).getSession().getCommandConfiguration(
Session.SEND_KEYS_TO_ELEMENT);
if (config != null && config.has(Session.NATIVE_EVENTS_PROPERTY)) {
try {
return config.getBoolean(Session.NATIVE_EVENTS_PROPERTY);
} catch (JSONException e) {}
}
// default is<SUF>
return true;
}
}
| False | 462 | 5 | 542 | 5 | 565 | 5 | 542 | 5 | 638 | 5 | false | false | false | false | false | true |
276 | 141676_10 | /***************************************************************************
* (C) Copyright 2003-2022 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.core.rp.achievement.factory;
import java.util.Collection;
import java.util.LinkedList;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.rp.achievement.Achievement;
import games.stendhal.server.core.rp.achievement.Category;
import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition;
import games.stendhal.server.entity.Entity;
import games.stendhal.server.entity.npc.ChatCondition;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.player.Player;
/**
* Factory for quest achievements
*
* @author kymara
*/
public class FriendAchievementFactory extends AbstractAchievementFactory {
public static final String ID_CHILD_FRIEND = "friend.quests.children";
public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find";
public static final String ID_GOOD_SAMARITAN = "friend.karma.250";
public static final String ID_STILL_BELIEVING = "friend.meet.seasonal";
@Override
protected Category getCategory() {
return Category.FRIEND;
}
@Override
public Collection<Achievement> createAchievements() {
final LinkedList<Achievement> achievements = new LinkedList<Achievement>();
// TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time)
// Befriend Susi and complete quests for all children
achievements.add(createAchievement(
ID_CHILD_FRIEND, "Childrens' Friend",
"Complete quests for all children",
Achievement.MEDIUM_BASE_SCORE, true,
new AndCondition(
// Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java)
new QuestStartedCondition("susi"),
// Help Tad, Semos Town Hall (Medicine for Tad)
new QuestCompletedCondition("introduce_players"),
// Plink, Semos Plains North
new QuestCompletedCondition("plinks_toy"),
// Anna, in Ados
new QuestCompletedCondition("toys_collector"),
// Sally, Orril River
// 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT));
new AndCondition(
new QuestActiveCondition("campfire"),
new QuestNotInStateCondition("campfire", "start")),
// Annie, Kalavan city gardens
new QuestStateStartsWithCondition("icecream_for_annie","eating;"),
// Elisabeth, Kirdneh
new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"),
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Hughie, Ados farmhouse
new AndCondition(
new QuestActiveCondition("fishsoup_for_hughie"),
new QuestNotInStateCondition("fishsoup_for_hughie", "start")),
// Finn Farmer, George
new QuestCompletedCondition("coded_message"),
// Marianne, Deniran City S
new AndCondition(
new QuestActiveCondition("eggs_for_marianne"),
new QuestNotInStateCondition("eggs_for_marianne", "start"))
)));
// quests about finding people
achievements.add(createAchievement(
ID_PRIVATE_DETECTIVE, "Private Detective",
"Find all lost and hidden people",
Achievement.HARD_BASE_SCORE, true,
new AndCondition(
// Rat Children (Agnus)
new QuestCompletedCondition("find_rat_kids"),
// Find Ghosts (Carena)
new QuestCompletedCondition("find_ghosts"),
// Meet Angels (any of the cherubs)
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
if (!player.hasQuest("seven_cherubs")) {
return false;
}
final String npcDoneText = player.getQuest("seven_cherubs");
final String[] done = npcDoneText.split(";");
final int left = 7 - done.length;
return left < 0;
}
},
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom")
)));
// earn over 250 karma
achievements.add(createAchievement(
ID_GOOD_SAMARITAN, "Good Samaritan",
"Earn a very good karma",
Achievement.MEDIUM_BASE_SCORE, true,
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
return player.getKarma() > 250;
}
}));
// meet Santa Claus and Easter Bunny
achievements.add(createAchievement(
ID_STILL_BELIEVING, "Still Believing",
"Meet Santa Claus and Easter Bunny",
Achievement.EASY_BASE_SCORE, true,
new AndCondition(
new QuestWithPrefixCompletedCondition("meet_santa_"),
new QuestWithPrefixCompletedCondition("meet_bunny_"))));
return achievements;
}
}
| C8620/stendhal | src/games/stendhal/server/core/rp/achievement/factory/FriendAchievementFactory.java | 1,834 | // Annie, Kalavan city gardens | line_comment | nl | /***************************************************************************
* (C) Copyright 2003-2022 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.core.rp.achievement.factory;
import java.util.Collection;
import java.util.LinkedList;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.rp.achievement.Achievement;
import games.stendhal.server.core.rp.achievement.Category;
import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition;
import games.stendhal.server.entity.Entity;
import games.stendhal.server.entity.npc.ChatCondition;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.player.Player;
/**
* Factory for quest achievements
*
* @author kymara
*/
public class FriendAchievementFactory extends AbstractAchievementFactory {
public static final String ID_CHILD_FRIEND = "friend.quests.children";
public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find";
public static final String ID_GOOD_SAMARITAN = "friend.karma.250";
public static final String ID_STILL_BELIEVING = "friend.meet.seasonal";
@Override
protected Category getCategory() {
return Category.FRIEND;
}
@Override
public Collection<Achievement> createAchievements() {
final LinkedList<Achievement> achievements = new LinkedList<Achievement>();
// TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time)
// Befriend Susi and complete quests for all children
achievements.add(createAchievement(
ID_CHILD_FRIEND, "Childrens' Friend",
"Complete quests for all children",
Achievement.MEDIUM_BASE_SCORE, true,
new AndCondition(
// Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java)
new QuestStartedCondition("susi"),
// Help Tad, Semos Town Hall (Medicine for Tad)
new QuestCompletedCondition("introduce_players"),
// Plink, Semos Plains North
new QuestCompletedCondition("plinks_toy"),
// Anna, in Ados
new QuestCompletedCondition("toys_collector"),
// Sally, Orril River
// 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT));
new AndCondition(
new QuestActiveCondition("campfire"),
new QuestNotInStateCondition("campfire", "start")),
// Annie, Kalavan<SUF>
new QuestStateStartsWithCondition("icecream_for_annie","eating;"),
// Elisabeth, Kirdneh
new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"),
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Hughie, Ados farmhouse
new AndCondition(
new QuestActiveCondition("fishsoup_for_hughie"),
new QuestNotInStateCondition("fishsoup_for_hughie", "start")),
// Finn Farmer, George
new QuestCompletedCondition("coded_message"),
// Marianne, Deniran City S
new AndCondition(
new QuestActiveCondition("eggs_for_marianne"),
new QuestNotInStateCondition("eggs_for_marianne", "start"))
)));
// quests about finding people
achievements.add(createAchievement(
ID_PRIVATE_DETECTIVE, "Private Detective",
"Find all lost and hidden people",
Achievement.HARD_BASE_SCORE, true,
new AndCondition(
// Rat Children (Agnus)
new QuestCompletedCondition("find_rat_kids"),
// Find Ghosts (Carena)
new QuestCompletedCondition("find_ghosts"),
// Meet Angels (any of the cherubs)
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
if (!player.hasQuest("seven_cherubs")) {
return false;
}
final String npcDoneText = player.getQuest("seven_cherubs");
final String[] done = npcDoneText.split(";");
final int left = 7 - done.length;
return left < 0;
}
},
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom")
)));
// earn over 250 karma
achievements.add(createAchievement(
ID_GOOD_SAMARITAN, "Good Samaritan",
"Earn a very good karma",
Achievement.MEDIUM_BASE_SCORE, true,
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
return player.getKarma() > 250;
}
}));
// meet Santa Claus and Easter Bunny
achievements.add(createAchievement(
ID_STILL_BELIEVING, "Still Believing",
"Meet Santa Claus and Easter Bunny",
Achievement.EASY_BASE_SCORE, true,
new AndCondition(
new QuestWithPrefixCompletedCondition("meet_santa_"),
new QuestWithPrefixCompletedCondition("meet_bunny_"))));
return achievements;
}
}
| False | 1,342 | 7 | 1,624 | 10 | 1,519 | 7 | 1,624 | 10 | 2,051 | 9 | false | false | false | false | false | true |
1,989 | 192437_0 | package com.aivarsliepa.budgetappapi.integrationtests;
import com.aivarsliepa.budgetappapi.constants.URLPaths;
import com.aivarsliepa.budgetappapi.data.payloads.JwtAuthResponseBody;
import com.aivarsliepa.budgetappapi.data.payloads.LoginRequestBody;
import com.aivarsliepa.budgetappapi.data.payloads.RegisterRequestBody;
import com.aivarsliepa.budgetappapi.data.user.UserModel;
import com.aivarsliepa.budgetappapi.data.user.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static io.jsonwebtoken.lang.Assert.hasText;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
public class AuthTest {
private static final String REGISTER_URL = URLPaths.Auth.BASE + URLPaths.Auth.REGISTER;
private static final String LOGIN_URL = URLPaths.Auth.BASE + URLPaths.Auth.LOGIN;
private static final String USERNAME_1 = "username_1";
private static final String PASSWORD_1 = "password_1";
private static final String PASSWORD_2 = "password_2";
@Autowired
private MockMvc mvc;
@Autowired
private UserRepository userRepository;
@Autowired
private ObjectMapper mapper;
@Autowired
private PasswordEncoder passwordEncoder;
@Before
public void setUp() {
userRepository.deleteAll();
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
@Test
public void register_happyPath() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_1);
var response = mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
// validate jwt is in response
var responseBody = mapper.readValue(response, JwtAuthResponseBody.class);
hasText(responseBody.getToken());
// validate that registered user is persisted
var persistedUserOpt = userRepository.findByUsername(USERNAME_1);
if (persistedUserOpt.isEmpty()) {
fail("User not persisted");
}
assertEquals(persistedUserOpt.get().getUsername(), USERNAME_1);
}
@Test
public void register_invalidInputData_usernameNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_confirmPasswordNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_usernameEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername("");
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername(USERNAME_1);
requestBody.setPassword("");
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_confirmPasswordEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword("");
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordsDoesNotMatch() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_2);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_usernameAlreadyExists() throws Exception {
// make sure user exists
var existingUser = new UserModel();
var encodedPassword = passwordEncoder.encode(PASSWORD_1);
existingUser.setPassword(encodedPassword);
existingUser.setUsername(USERNAME_1);
userRepository.save(existingUser);
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_2);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_2);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
// verify that user count is still 1
var userList = userRepository.findAll();
assertEquals(1, userList.size());
// verify that user password was not overwritten
var user = userRepository.findByUsername(USERNAME_1);
if (user.isEmpty()) {
fail("User should be not be empty!");
}
assertEquals(encodedPassword, user.get().getPassword());
}
@Test
public void login_happyPath() throws Exception {
// make sure user exists
var user = new UserModel();
user.setPassword(passwordEncoder.encode(PASSWORD_1));
user.setUsername(USERNAME_1);
userRepository.save(user);
var requestBody = new LoginRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
var response = mvc.perform(post(LOGIN_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
// validate jwt is in response
var responseBody = mapper.readValue(response, JwtAuthResponseBody.class);
hasText(responseBody.getToken());
}
@Test
public void login_invalidPassword() throws Exception {
// make sure user exists
var user = new UserModel();
user.setPassword(passwordEncoder.encode(PASSWORD_1));
user.setUsername(USERNAME_1);
userRepository.save(user);
var requestBody = new LoginRequestBody();
requestBody.setPassword(PASSWORD_2);
requestBody.setUsername(USERNAME_1);
mvc.perform(post(LOGIN_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isUnauthorized())
.andExpect(content().string(""));
}
}
| aivarsliepa/budget-app-api | src/test/java/com/aivarsliepa/budgetappapi/integrationtests/AuthTest.java | 2,840 | // validate jwt is in response | line_comment | nl | package com.aivarsliepa.budgetappapi.integrationtests;
import com.aivarsliepa.budgetappapi.constants.URLPaths;
import com.aivarsliepa.budgetappapi.data.payloads.JwtAuthResponseBody;
import com.aivarsliepa.budgetappapi.data.payloads.LoginRequestBody;
import com.aivarsliepa.budgetappapi.data.payloads.RegisterRequestBody;
import com.aivarsliepa.budgetappapi.data.user.UserModel;
import com.aivarsliepa.budgetappapi.data.user.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static io.jsonwebtoken.lang.Assert.hasText;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
public class AuthTest {
private static final String REGISTER_URL = URLPaths.Auth.BASE + URLPaths.Auth.REGISTER;
private static final String LOGIN_URL = URLPaths.Auth.BASE + URLPaths.Auth.LOGIN;
private static final String USERNAME_1 = "username_1";
private static final String PASSWORD_1 = "password_1";
private static final String PASSWORD_2 = "password_2";
@Autowired
private MockMvc mvc;
@Autowired
private UserRepository userRepository;
@Autowired
private ObjectMapper mapper;
@Autowired
private PasswordEncoder passwordEncoder;
@Before
public void setUp() {
userRepository.deleteAll();
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
@Test
public void register_happyPath() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_1);
var response = mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
// validate jwt<SUF>
var responseBody = mapper.readValue(response, JwtAuthResponseBody.class);
hasText(responseBody.getToken());
// validate that registered user is persisted
var persistedUserOpt = userRepository.findByUsername(USERNAME_1);
if (persistedUserOpt.isEmpty()) {
fail("User not persisted");
}
assertEquals(persistedUserOpt.get().getUsername(), USERNAME_1);
}
@Test
public void register_invalidInputData_usernameNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_confirmPasswordNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_usernameEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername("");
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername(USERNAME_1);
requestBody.setPassword("");
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_confirmPasswordEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword("");
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordsDoesNotMatch() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_2);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_usernameAlreadyExists() throws Exception {
// make sure user exists
var existingUser = new UserModel();
var encodedPassword = passwordEncoder.encode(PASSWORD_1);
existingUser.setPassword(encodedPassword);
existingUser.setUsername(USERNAME_1);
userRepository.save(existingUser);
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_2);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_2);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
// verify that user count is still 1
var userList = userRepository.findAll();
assertEquals(1, userList.size());
// verify that user password was not overwritten
var user = userRepository.findByUsername(USERNAME_1);
if (user.isEmpty()) {
fail("User should be not be empty!");
}
assertEquals(encodedPassword, user.get().getPassword());
}
@Test
public void login_happyPath() throws Exception {
// make sure user exists
var user = new UserModel();
user.setPassword(passwordEncoder.encode(PASSWORD_1));
user.setUsername(USERNAME_1);
userRepository.save(user);
var requestBody = new LoginRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
var response = mvc.perform(post(LOGIN_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
// validate jwt is in response
var responseBody = mapper.readValue(response, JwtAuthResponseBody.class);
hasText(responseBody.getToken());
}
@Test
public void login_invalidPassword() throws Exception {
// make sure user exists
var user = new UserModel();
user.setPassword(passwordEncoder.encode(PASSWORD_1));
user.setUsername(USERNAME_1);
userRepository.save(user);
var requestBody = new LoginRequestBody();
requestBody.setPassword(PASSWORD_2);
requestBody.setUsername(USERNAME_1);
mvc.perform(post(LOGIN_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isUnauthorized())
.andExpect(content().string(""));
}
}
| False | 1,784 | 6 | 2,202 | 6 | 2,278 | 6 | 2,202 | 6 | 2,777 | 7 | false | false | false | false | false | true |
4,752 | 16548_3 | /*--------------------------------------------------------------------------
* Copyright 2008 Taro L. Saito
*
* 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.
*--------------------------------------------------------------------------*/
// --------------------------------------
// sqlite-jdbc Project
//
// OSInfo.java
// Since: May 20, 2008
//
// $URL$
// $Author$
// --------------------------------------
package org.sqlite.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Locale;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides OS name and architecture name.
*
* @author leo
*/
public class OSInfo {
protected static ProcessRunner processRunner = new ProcessRunner();
private static final HashMap<String, String> archMapping = new HashMap<>();
public static final String X86 = "x86";
public static final String X86_64 = "x86_64";
public static final String IA64_32 = "ia64_32";
public static final String IA64 = "ia64";
public static final String PPC = "ppc";
public static final String PPC64 = "ppc64";
static {
// x86 mappings
archMapping.put(X86, X86);
archMapping.put("i386", X86);
archMapping.put("i486", X86);
archMapping.put("i586", X86);
archMapping.put("i686", X86);
archMapping.put("pentium", X86);
// x86_64 mappings
archMapping.put(X86_64, X86_64);
archMapping.put("amd64", X86_64);
archMapping.put("em64t", X86_64);
archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac
// Itanium 64-bit mappings
archMapping.put(IA64, IA64);
archMapping.put("ia64w", IA64);
// Itanium 32-bit mappings, usually an HP-UX construct
archMapping.put(IA64_32, IA64_32);
archMapping.put("ia64n", IA64_32);
// PowerPC mappings
archMapping.put(PPC, PPC);
archMapping.put("power", PPC);
archMapping.put("powerpc", PPC);
archMapping.put("power_pc", PPC);
archMapping.put("power_rs", PPC);
// TODO: PowerPC 64bit mappings
archMapping.put(PPC64, PPC64);
archMapping.put("power64", PPC64);
archMapping.put("powerpc64", PPC64);
archMapping.put("power_pc64", PPC64);
archMapping.put("power_rs64", PPC64);
archMapping.put("ppc64el", PPC64);
archMapping.put("ppc64le", PPC64);
}
public static void main(String[] args) {
if (args.length >= 1) {
if ("--os".equals(args[0])) {
System.out.print(getOSName());
return;
} else if ("--arch".equals(args[0])) {
System.out.print(getArchName());
return;
}
}
System.out.print(getNativeLibFolderPathForCurrentOS());
}
public static String getNativeLibFolderPathForCurrentOS() {
return getOSName() + "/" + getArchName();
}
public static String getOSName() {
return translateOSNameToFolderName(System.getProperty("os.name"));
}
public static boolean isAndroid() {
return isAndroidRuntime() || isAndroidTermux();
}
public static boolean isAndroidRuntime() {
return System.getProperty("java.runtime.name", "").toLowerCase().contains("android");
}
public static boolean isAndroidTermux() {
try {
return processRunner.runAndWaitFor("uname -o").toLowerCase().contains("android");
} catch (Exception ignored) {
return false;
}
}
public static boolean isMusl() {
Path mapFilesDir = Paths.get("/proc/self/map_files");
try (Stream<Path> dirStream = Files.list(mapFilesDir)) {
return dirStream
.map(
path -> {
try {
return path.toRealPath().toString();
} catch (IOException e) {
return "";
}
})
.anyMatch(s -> s.toLowerCase().contains("musl"));
} catch (Exception ignored) {
// fall back to checking for alpine linux in the event we're using an older kernel which
// may not fail the above check
return isAlpineLinux();
}
}
private static boolean isAlpineLinux() {
try (Stream<String> osLines = Files.lines(Paths.get("/etc/os-release"))) {
return osLines.anyMatch(l -> l.startsWith("ID") && l.contains("alpine"));
} catch (Exception ignored2) {
}
return false;
}
static String getHardwareName() {
try {
return processRunner.runAndWaitFor("uname -m");
} catch (Throwable e) {
LogHolder.logger.error("Error while running uname -m", e);
return "unknown";
}
}
static String resolveArmArchType() {
if (System.getProperty("os.name").contains("Linux")) {
String armType = getHardwareName();
// armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l,
// aarch64, i686
// for Android, we fold everything that is not aarch64 into arm
if (isAndroid()) {
if (armType.startsWith("aarch64")) {
// Use arm64
return "aarch64";
} else {
return "arm";
}
}
if (armType.startsWith("armv6")) {
// Raspberry PI
return "armv6";
} else if (armType.startsWith("armv7")) {
// Generic
return "armv7";
} else if (armType.startsWith("armv5")) {
// Use armv5, soft-float ABI
return "arm";
} else if (armType.startsWith("aarch64")) {
// Use arm64
return "aarch64";
}
// Java 1.8 introduces a system property to determine armel or armhf
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545
String abi = System.getProperty("sun.arch.abi");
if (abi != null && abi.startsWith("gnueabihf")) {
return "armv7";
}
// For java7, we still need to run some shell commands to determine ABI of JVM
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if (exitCode == 0) {
String[] cmdarray = {
"/bin/sh",
"-c",
"find '"
+ javaHome
+ "' -name 'libjvm.so' | head -1 | xargs readelf -A | "
+ "grep 'Tag_ABI_VFP_args: VFP registers'"
};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return "armv7";
}
} else {
LogHolder.logger.warn(
"readelf not found. Cannot check if running on an armhf system, armel architecture will be presumed");
}
} catch (IOException | InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
// Use armv5, soft-float ABI
return "arm";
}
public static String getArchName() {
String override = System.getProperty("org.sqlite.osinfo.architecture");
if (override != null) {
return override;
}
String osArch = System.getProperty("os.arch");
if (osArch.startsWith("arm")) {
osArch = resolveArmArchType();
} else {
String lc = osArch.toLowerCase(Locale.US);
if (archMapping.containsKey(lc)) return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
static String translateOSNameToFolderName(String osName) {
if (osName.contains("Windows")) {
return "Windows";
} else if (osName.contains("Mac") || osName.contains("Darwin")) {
return "Mac";
} else if (osName.contains("AIX")) {
return "AIX";
} else if (isMusl()) {
return "Linux-Musl";
} else if (isAndroid()) {
return "Linux-Android";
} else if (osName.contains("Linux")) {
return "Linux";
} else {
return osName.replaceAll("\\W", "");
}
}
static String translateArchNameToFolderName(String archName) {
return archName.replaceAll("\\W", "");
}
/**
* Class-wrapper around the logger object to avoid build-time initialization of the logging
* framework in native-image
*/
private static class LogHolder {
private static final Logger logger = LoggerFactory.getLogger(OSInfo.class);
}
}
| xerial/sqlite-jdbc | src/main/java/org/sqlite/util/OSInfo.java | 2,785 | // Needed for openjdk7 in Mac | line_comment | nl | /*--------------------------------------------------------------------------
* Copyright 2008 Taro L. Saito
*
* 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.
*--------------------------------------------------------------------------*/
// --------------------------------------
// sqlite-jdbc Project
//
// OSInfo.java
// Since: May 20, 2008
//
// $URL$
// $Author$
// --------------------------------------
package org.sqlite.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Locale;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides OS name and architecture name.
*
* @author leo
*/
public class OSInfo {
protected static ProcessRunner processRunner = new ProcessRunner();
private static final HashMap<String, String> archMapping = new HashMap<>();
public static final String X86 = "x86";
public static final String X86_64 = "x86_64";
public static final String IA64_32 = "ia64_32";
public static final String IA64 = "ia64";
public static final String PPC = "ppc";
public static final String PPC64 = "ppc64";
static {
// x86 mappings
archMapping.put(X86, X86);
archMapping.put("i386", X86);
archMapping.put("i486", X86);
archMapping.put("i586", X86);
archMapping.put("i686", X86);
archMapping.put("pentium", X86);
// x86_64 mappings
archMapping.put(X86_64, X86_64);
archMapping.put("amd64", X86_64);
archMapping.put("em64t", X86_64);
archMapping.put("universal", X86_64); // Needed for<SUF>
// Itanium 64-bit mappings
archMapping.put(IA64, IA64);
archMapping.put("ia64w", IA64);
// Itanium 32-bit mappings, usually an HP-UX construct
archMapping.put(IA64_32, IA64_32);
archMapping.put("ia64n", IA64_32);
// PowerPC mappings
archMapping.put(PPC, PPC);
archMapping.put("power", PPC);
archMapping.put("powerpc", PPC);
archMapping.put("power_pc", PPC);
archMapping.put("power_rs", PPC);
// TODO: PowerPC 64bit mappings
archMapping.put(PPC64, PPC64);
archMapping.put("power64", PPC64);
archMapping.put("powerpc64", PPC64);
archMapping.put("power_pc64", PPC64);
archMapping.put("power_rs64", PPC64);
archMapping.put("ppc64el", PPC64);
archMapping.put("ppc64le", PPC64);
}
public static void main(String[] args) {
if (args.length >= 1) {
if ("--os".equals(args[0])) {
System.out.print(getOSName());
return;
} else if ("--arch".equals(args[0])) {
System.out.print(getArchName());
return;
}
}
System.out.print(getNativeLibFolderPathForCurrentOS());
}
public static String getNativeLibFolderPathForCurrentOS() {
return getOSName() + "/" + getArchName();
}
public static String getOSName() {
return translateOSNameToFolderName(System.getProperty("os.name"));
}
public static boolean isAndroid() {
return isAndroidRuntime() || isAndroidTermux();
}
public static boolean isAndroidRuntime() {
return System.getProperty("java.runtime.name", "").toLowerCase().contains("android");
}
public static boolean isAndroidTermux() {
try {
return processRunner.runAndWaitFor("uname -o").toLowerCase().contains("android");
} catch (Exception ignored) {
return false;
}
}
public static boolean isMusl() {
Path mapFilesDir = Paths.get("/proc/self/map_files");
try (Stream<Path> dirStream = Files.list(mapFilesDir)) {
return dirStream
.map(
path -> {
try {
return path.toRealPath().toString();
} catch (IOException e) {
return "";
}
})
.anyMatch(s -> s.toLowerCase().contains("musl"));
} catch (Exception ignored) {
// fall back to checking for alpine linux in the event we're using an older kernel which
// may not fail the above check
return isAlpineLinux();
}
}
private static boolean isAlpineLinux() {
try (Stream<String> osLines = Files.lines(Paths.get("/etc/os-release"))) {
return osLines.anyMatch(l -> l.startsWith("ID") && l.contains("alpine"));
} catch (Exception ignored2) {
}
return false;
}
static String getHardwareName() {
try {
return processRunner.runAndWaitFor("uname -m");
} catch (Throwable e) {
LogHolder.logger.error("Error while running uname -m", e);
return "unknown";
}
}
static String resolveArmArchType() {
if (System.getProperty("os.name").contains("Linux")) {
String armType = getHardwareName();
// armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l,
// aarch64, i686
// for Android, we fold everything that is not aarch64 into arm
if (isAndroid()) {
if (armType.startsWith("aarch64")) {
// Use arm64
return "aarch64";
} else {
return "arm";
}
}
if (armType.startsWith("armv6")) {
// Raspberry PI
return "armv6";
} else if (armType.startsWith("armv7")) {
// Generic
return "armv7";
} else if (armType.startsWith("armv5")) {
// Use armv5, soft-float ABI
return "arm";
} else if (armType.startsWith("aarch64")) {
// Use arm64
return "aarch64";
}
// Java 1.8 introduces a system property to determine armel or armhf
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545
String abi = System.getProperty("sun.arch.abi");
if (abi != null && abi.startsWith("gnueabihf")) {
return "armv7";
}
// For java7, we still need to run some shell commands to determine ABI of JVM
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if (exitCode == 0) {
String[] cmdarray = {
"/bin/sh",
"-c",
"find '"
+ javaHome
+ "' -name 'libjvm.so' | head -1 | xargs readelf -A | "
+ "grep 'Tag_ABI_VFP_args: VFP registers'"
};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return "armv7";
}
} else {
LogHolder.logger.warn(
"readelf not found. Cannot check if running on an armhf system, armel architecture will be presumed");
}
} catch (IOException | InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
// Use armv5, soft-float ABI
return "arm";
}
public static String getArchName() {
String override = System.getProperty("org.sqlite.osinfo.architecture");
if (override != null) {
return override;
}
String osArch = System.getProperty("os.arch");
if (osArch.startsWith("arm")) {
osArch = resolveArmArchType();
} else {
String lc = osArch.toLowerCase(Locale.US);
if (archMapping.containsKey(lc)) return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
static String translateOSNameToFolderName(String osName) {
if (osName.contains("Windows")) {
return "Windows";
} else if (osName.contains("Mac") || osName.contains("Darwin")) {
return "Mac";
} else if (osName.contains("AIX")) {
return "AIX";
} else if (isMusl()) {
return "Linux-Musl";
} else if (isAndroid()) {
return "Linux-Android";
} else if (osName.contains("Linux")) {
return "Linux";
} else {
return osName.replaceAll("\\W", "");
}
}
static String translateArchNameToFolderName(String archName) {
return archName.replaceAll("\\W", "");
}
/**
* Class-wrapper around the logger object to avoid build-time initialization of the logging
* framework in native-image
*/
private static class LogHolder {
private static final Logger logger = LoggerFactory.getLogger(OSInfo.class);
}
}
| False | 2,259 | 8 | 2,442 | 9 | 2,638 | 8 | 2,442 | 9 | 2,848 | 9 | false | false | false | false | false | true |
1,078 | 145235_18 | package tesc1;
import java.io.*;
import java.lang.String;
import java.util.Vector;
import absyn.*;
import util.*;
/**
* Label-Parser fuer den Editor.
* <p>
* @author Michael Suelzer, Christoph Schuette.
* @version $Id: TESCLabelParser.java,v 1.5 1999-02-07 11:58:30 swtech20 Exp $
*/
class TESCLabelParser extends TESCParser {
protected Statechart statechart;
// Der Standard-Ktor muss verborgen werden, da
// das Parsen eines Labels ohne Statechart
// keinen Sinn macht.
private TESCLabelParser() {};
/**
* Constructor.
*/
public TESCLabelParser (Statechart sc) {
statechart = sc;
eventlist = sc.events;
bvarlist = sc.bvars;
pathlist = sc.cnames;
}
/**
* Startet den Parsevorgang fuer ein Label.
*/
public TLabel readLabel (BufferedReader br) throws IOException {
warningText = new Vector ();
warningCount = 0 ;
errorText = new Vector ();
errorCount = 0;
lexer = new TESCTokenizer (br);
token = lexer.getNextToken ();
debug ("parseLabel");
TLabel label = parseLabel ();
// Die geaenderten Listen nach aussen geben
statechart.bvars = bvarlist;
statechart.events = eventlist;
statechart.cnames = pathlist;
return label;
}
/**
* LABEL ::= {GUARD} {"/" ACTION}
*/
public TLabel parseLabel () throws IOException {
//debug ("Enter parseLabel");
Guard guard = parseGuardSTMStyle ();
Action action = null;
if (token.getId () == Token.TOK_SLASH) {
matchToken (Token.Slash);
action = parseActions ();
}
else
action = new ActionEmpty (new Dummy ());
// Caption fuer TLabel aufbauen.
TLabel label = new TLabel (guard, action);
TESCSaver saver = new TESCSaver (null);
saver.setCaption (label);
// Sollte wider Erwarten ein Fehler auftreten, dann merken
errorCount += saver.getErrorCount ();
for (int i=0; i < saver.getErrorCount (); i++)
Error (saver.getErrorText (i));
//debug ("Leave parseLabel");
return label;
}
}
//----------------------------------------------------------------------
// Label-Parser
// ------------
//
// $Log: not supported by cvs2svn $
// Revision 1.4 1999/02/01 11:52:58 swtech20
// - globaler Debug-Schalter
//
// Revision 1.3 1999/01/20 17:32:10 swtech20
// - Status und Doku aktualisiert
// - Fehler, dass Anderungen an Bvarlisten ... nicht nach aussen-
// gegeben werden behoben.
//
// Revision 1.2 1999/01/18 17:08:52 swtech20
// - okDialog -> userMessage
// - Pruefung auf gui==null
// - package visibility fuer Nicht-Schnittstellenklassen
//
// Revision 1.1 1999/01/17 17:16:41 swtech20
// Umstellung der Guard-Syntax auf Statemate-Style, Implementierung des
// LabelParsers fuer den Editor. Anpassung der Schnittstelle.
//
//
//
//
//----------------------------------------------------------------------
| MartinSteffen/pest | src/Pest2/TESC1/TESCLabelParser.java | 1,009 | // gegeben werden behoben. | line_comment | nl | package tesc1;
import java.io.*;
import java.lang.String;
import java.util.Vector;
import absyn.*;
import util.*;
/**
* Label-Parser fuer den Editor.
* <p>
* @author Michael Suelzer, Christoph Schuette.
* @version $Id: TESCLabelParser.java,v 1.5 1999-02-07 11:58:30 swtech20 Exp $
*/
class TESCLabelParser extends TESCParser {
protected Statechart statechart;
// Der Standard-Ktor muss verborgen werden, da
// das Parsen eines Labels ohne Statechart
// keinen Sinn macht.
private TESCLabelParser() {};
/**
* Constructor.
*/
public TESCLabelParser (Statechart sc) {
statechart = sc;
eventlist = sc.events;
bvarlist = sc.bvars;
pathlist = sc.cnames;
}
/**
* Startet den Parsevorgang fuer ein Label.
*/
public TLabel readLabel (BufferedReader br) throws IOException {
warningText = new Vector ();
warningCount = 0 ;
errorText = new Vector ();
errorCount = 0;
lexer = new TESCTokenizer (br);
token = lexer.getNextToken ();
debug ("parseLabel");
TLabel label = parseLabel ();
// Die geaenderten Listen nach aussen geben
statechart.bvars = bvarlist;
statechart.events = eventlist;
statechart.cnames = pathlist;
return label;
}
/**
* LABEL ::= {GUARD} {"/" ACTION}
*/
public TLabel parseLabel () throws IOException {
//debug ("Enter parseLabel");
Guard guard = parseGuardSTMStyle ();
Action action = null;
if (token.getId () == Token.TOK_SLASH) {
matchToken (Token.Slash);
action = parseActions ();
}
else
action = new ActionEmpty (new Dummy ());
// Caption fuer TLabel aufbauen.
TLabel label = new TLabel (guard, action);
TESCSaver saver = new TESCSaver (null);
saver.setCaption (label);
// Sollte wider Erwarten ein Fehler auftreten, dann merken
errorCount += saver.getErrorCount ();
for (int i=0; i < saver.getErrorCount (); i++)
Error (saver.getErrorText (i));
//debug ("Leave parseLabel");
return label;
}
}
//----------------------------------------------------------------------
// Label-Parser
// ------------
//
// $Log: not supported by cvs2svn $
// Revision 1.4 1999/02/01 11:52:58 swtech20
// - globaler Debug-Schalter
//
// Revision 1.3 1999/01/20 17:32:10 swtech20
// - Status und Doku aktualisiert
// - Fehler, dass Anderungen an Bvarlisten ... nicht nach aussen-
// gegeben werden<SUF>
//
// Revision 1.2 1999/01/18 17:08:52 swtech20
// - okDialog -> userMessage
// - Pruefung auf gui==null
// - package visibility fuer Nicht-Schnittstellenklassen
//
// Revision 1.1 1999/01/17 17:16:41 swtech20
// Umstellung der Guard-Syntax auf Statemate-Style, Implementierung des
// LabelParsers fuer den Editor. Anpassung der Schnittstelle.
//
//
//
//
//----------------------------------------------------------------------
| False | 816 | 9 | 938 | 9 | 928 | 8 | 938 | 9 | 1,028 | 9 | false | false | false | false | false | true |
4,382 | 131187_8 | package week2;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class GlobalTransitionSystemTest {
@Test
void hasExecutionTest1() {
String s = "g0 ";
s += "g0--a@p->g1 g1--b@p->g2 g2--e@r->g3 g3--f@r->g4 g4--d@q->g5 ";
s += "g6--b@p->g7 g7--e@r->g8 g8--f@r->g9 g9--d@q->g10 ";
s += "g1--c@q->g6 g2--c@q->g7 g3--c@q->g8 g4--c@q->g9 g5--c@q->g10";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g7 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g6 g7 g8 g9 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g3 g4 g5 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g11 g10", configurations)));
}
@Test
void hasExecutionTest2() {
String s = "g0 ";
s += "g0--c@q->g1 g1--d@q->g2 g2--a@p->g3 g3--b@p->g4 g4--e@q->g5 ";
s += "g6--d@q->g7 g7--a@p->g8 g8--b@p->g9 g9--e@q->g10 ";
s += "g1--f@r->g6 g2--f@r->g7 g3--f@r->g8 g4--f@r->g9 g5--f@r->g10";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g7 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g6 g7 g8 g9 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g3 g4 g5 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g11 g10", configurations)));
}
@Test
void hasExecutionTest3() {
String s = "g0 ";
s += "g0--a@p->g1 g1--c@r->g2 ";
s += "g3--a@p->g4 g4--c@r->g5 ";
s += "g6--a@p->g7 g7--c@r->g8 ";
s += "g0--b@q->g3 g1--b@q->g4 g2--b@q->g5 ";
s += "g3--d@r->g6 g4--d@r->g7 g5--d@r->g8";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g4 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g4 g7 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g4 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g4 g7 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g6 g7 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g5 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5 g9 g8", configurations)));
}
@Test
void hasExecutionTest4() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 3, 4, 12);
for (int i = 0; i < 10; i++) {
assertTrue(system.hasExecution(system.randomExecution(i)));
}
}
@Test
void hasExecutionTest5() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
for (int i = 0; i < 10; i++) {
assertTrue(system.hasExecution(system.randomExecution(i)));
}
}
@Test
void hasExecutionTest6() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 3, 4, 12);
for (int i = 0; i < 10; i++) {
assertFalse(system.hasExecution(system.randomNonExecution(i)));
}
}
@Test
void hasExecutionTest7() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
for (int i = 0; i < 100; i++) {
assertFalse(system.hasExecution(system.randomNonExecution(i)));
}
}
@Test
void hasExecutionTest8() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
assertFalse(system.hasExecution(new ArrayList<>()));
}
// @Test
// void parseTest1() {
// String s = "g0 g0--a@p->g1";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
//
// @Test
// void parseTest2() {
// String s = "g0 g0--s(p,q,1)->g1 g1--r(p,q,1)->g2 g3--a@q->g0";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
//
// @Test
// void parseTest3() {
// String s = "g0 g0--s(p,q,1)->g1 g1--r(p,q,1)->g2 g1--s(p,q,2)->g4 g3--a@q->g0";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
}
| sschivo/ib2302 | Opdrachten/src/week2/GlobalTransitionSystemTest.java | 2,554 | // void parseTest3() { | line_comment | nl | package week2;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class GlobalTransitionSystemTest {
@Test
void hasExecutionTest1() {
String s = "g0 ";
s += "g0--a@p->g1 g1--b@p->g2 g2--e@r->g3 g3--f@r->g4 g4--d@q->g5 ";
s += "g6--b@p->g7 g7--e@r->g8 g8--f@r->g9 g9--d@q->g10 ";
s += "g1--c@q->g6 g2--c@q->g7 g3--c@q->g8 g4--c@q->g9 g5--c@q->g10";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g7 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g6 g7 g8 g9 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g3 g4 g5 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g11 g10", configurations)));
}
@Test
void hasExecutionTest2() {
String s = "g0 ";
s += "g0--c@q->g1 g1--d@q->g2 g2--a@p->g3 g3--b@p->g4 g4--e@q->g5 ";
s += "g6--d@q->g7 g7--a@p->g8 g8--b@p->g9 g9--e@q->g10 ";
s += "g1--f@r->g6 g2--f@r->g7 g3--f@r->g8 g4--f@r->g9 g5--f@r->g10";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g7 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g6 g7 g8 g9 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g3 g4 g5 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g11 g10", configurations)));
}
@Test
void hasExecutionTest3() {
String s = "g0 ";
s += "g0--a@p->g1 g1--c@r->g2 ";
s += "g3--a@p->g4 g4--c@r->g5 ";
s += "g6--a@p->g7 g7--c@r->g8 ";
s += "g0--b@q->g3 g1--b@q->g4 g2--b@q->g5 ";
s += "g3--d@r->g6 g4--d@r->g7 g5--d@r->g8";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g4 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g4 g7 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g4 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g4 g7 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g6 g7 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g5 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5 g9 g8", configurations)));
}
@Test
void hasExecutionTest4() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 3, 4, 12);
for (int i = 0; i < 10; i++) {
assertTrue(system.hasExecution(system.randomExecution(i)));
}
}
@Test
void hasExecutionTest5() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
for (int i = 0; i < 10; i++) {
assertTrue(system.hasExecution(system.randomExecution(i)));
}
}
@Test
void hasExecutionTest6() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 3, 4, 12);
for (int i = 0; i < 10; i++) {
assertFalse(system.hasExecution(system.randomNonExecution(i)));
}
}
@Test
void hasExecutionTest7() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
for (int i = 0; i < 100; i++) {
assertFalse(system.hasExecution(system.randomNonExecution(i)));
}
}
@Test
void hasExecutionTest8() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
assertFalse(system.hasExecution(new ArrayList<>()));
}
// @Test
// void parseTest1() {
// String s = "g0 g0--a@p->g1";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
//
// @Test
// void parseTest2() {
// String s = "g0 g0--s(p,q,1)->g1 g1--r(p,q,1)->g2 g3--a@q->g0";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
//
// @Test
// void parseTest3()<SUF>
// String s = "g0 g0--s(p,q,1)->g1 g1--r(p,q,1)->g2 g1--s(p,q,2)->g4 g3--a@q->g0";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
}
| False | 2,079 | 7 | 2,453 | 8 | 2,453 | 8 | 2,453 | 8 | 2,730 | 8 | false | false | false | false | false | true |
1,433 | 39552_5 | package controller;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import model.Creature;
import view.Main;
import view.SceneManager;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**Deze class is gelinkt met initiativeScene.fxml en geeft een scherm weer waar je creatures kan invoeren voor
* initiative, voordat je naar het echte initiative bijhoudt scherm gaat.
*
* @author R.Groot
*/
public class InitiativeController {
private final SceneManager SCENEMANAGER = Main.getSceneManager();
private ArrayList<Creature> initiative = new ArrayList<>();
//Checkboxxes
@FXML
private CheckBox lairActionCheckBox;
@FXML
private ListView<Creature> initiativeList;
@FXML
private TextField nameTextField;
@FXML
private TextField initiativeTextField;
@FXML
private TextField hpTextField;
@FXML
private TextField maxHPTextField;
@FXML
private TextField legResTextField;
@FXML
private TextField legActTextField;
@FXML
private VBox legendaryControls;
@FXML
private CheckBox legendaryCheckBox;
/**Deze methode wordt gestart wanneer naar dit scherm wordt gegaan. Momenteel doet deze methode niets, maar
* in de toekomst kunnen hier dingen aan toegevoegd worden als nodig.
*/
public void setup() {
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
}
/**Deze methode zet de initiativeList op volgorde van initiative (hoog naar laag).
*
*/
public void orderList() {
initiative.sort((c1, c2) -> Double.compare(c2.getInitiative(), c1.getInitiative()));
initiativeList.getItems().setAll(initiative);
}
public void handleLegendaryCheckBox(){
legendaryControls.setVisible(legendaryCheckBox.isSelected());
if(legendaryCheckBox.isSelected()) {
legendaryControls.setVisible(true);
legResTextField.setText(String.valueOf(0));
} else{
legendaryControls.setVisible(false);
}
}
/**Met deze methode wordt een creature toegevoegd aan de initiativeList.
*
*/
public void doAdd() {
if(validateCreature()) {
try {
double getInitiative = Double.parseDouble(initiativeTextField.getText());
int getHP = Integer.parseInt(hpTextField.getText());
int getMaxHP = Integer.parseInt(maxHPTextField.getText());
int legRes = 0;
int legAct = 0;
if (!legResTextField.getText().isEmpty()) {
legRes = Integer.parseInt(legResTextField.getText());
}
if (!legActTextField.getText().isEmpty()) {
legAct = Integer.parseInt(legActTextField.getText());
}
initiative.add(new Creature(nameTextField.getText(), getInitiative, getHP, getMaxHP, legRes, legAct));
nameTextField.setText("");
initiativeTextField.setText("");
hpTextField.setText("");
maxHPTextField.setText("");
legResTextField.setText("0");
legActTextField.setText("0");
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
orderList();
} catch (NumberFormatException exception) {
showAlert("Initiative and HP must be valid numbers!");
}
}
}
/**Met deze methode wordt de gebruiker naar de initiativeTracker scherm gebracht.
*
*/
public void doTracker() {
if(initiative == null) {
showAlert("Your initiative list is empty!");
}
SCENEMANAGER.showInitiativeTrackerScene(initiative, lairActionCheckBox.isSelected());
}
/**Met deze methode wordt een creature uit de initiativeList gehaald.
*
*/
public void doDelete() {
Creature selectedCreature = initiativeList.getSelectionModel().getSelectedItem();
if (selectedCreature != null) {
initiative.remove(selectedCreature);
initiativeList.getItems().remove(selectedCreature);
}
}
/**Met deze methode wordt een creature die de gebruiker probeert toe te voegen gevallideerd op een aantal
* punten. De creature kan alleen toegevoegd worden als het overal aan voldoet.
*
* @return: true als het overal aan voldoet.
*/
public boolean validateCreature() {
String name = nameTextField.getText();
String initiativeText = initiativeTextField.getText();
String hpText = hpTextField.getText();
String maxHPText = maxHPTextField.getText();
if (name.isEmpty() || initiativeText.isEmpty() || hpText.isEmpty() || maxHPText.isEmpty()) {
showAlert("All fields are required!");
return false;
}
if(initiative != null) {
ArrayList<String> names = initiative.stream().map(Creature::getName).collect(Collectors.toCollection(ArrayList::new));
for (String creatureName : names) {
if(name.equalsIgnoreCase(creatureName)) {
showAlert("This name is already in the initiative list!");
return false;
}
}
}
if (Integer.parseInt(hpText) < 0 || Integer.parseInt(maxHPText) < 0) {
showAlert("You can't add a creature with less then 0 (max) HP.");
return false;
}
if(nameTextField.getText().length() > 20) {
showAlert("The creature's name can't be more then 20 characters long.");
return false;
}
if (Integer.parseInt(hpText) > Integer.parseInt(maxHPText)) {
showAlert("HP can't be higher than max HP!");
return false;
}
return true;
}
public void lowerLegRes(){
int newLegRes = Integer.parseInt(legResTextField.getText()) - 1;
if(newLegRes < 0) {
showAlert("A creature can't have less then 0 legendary resistances!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void addLegRes(){
if(legResTextField.getText().isEmpty()) {
legResTextField.setText("0");
}
int newLegRes = Integer.parseInt(legResTextField.getText()) + 1;
if(newLegRes > 5) {
showAlert("A creature can't have more then 5 legendary resistances in this program!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void lowerLegAct(){
int newLegAct = Integer.parseInt(legActTextField.getText()) - 1;
if(newLegAct < 0) {
showAlert("A creature can't have less then 0 legendary actions!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void addLegAct(){
if(legActTextField.getText().isEmpty()) {
legActTextField.setText("0");
}
int newLegAct = Integer.parseInt(legActTextField.getText()) + 1;
if(newLegAct > 5) {
showAlert("A creature can't have more then 5 legendary actions in this program!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void doMenu(){
SCENEMANAGER.showMenuScene();
}
/**Geeft een error message als deze methode wordt aangeroepen.
*
* @param message: het bericht dat weergegeven wordt in de error message.
*/
public void showAlert(String message) {
Alert errorMessage = new Alert(Alert.AlertType.ERROR);
errorMessage.setContentText(message);
errorMessage.show();
}
} | Rakky88/InitiativeTracker | src/main/java/controller/InitiativeController.java | 2,231 | /**Met deze methode wordt een creature uit de initiativeList gehaald.
*
*/ | block_comment | nl | package controller;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import model.Creature;
import view.Main;
import view.SceneManager;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**Deze class is gelinkt met initiativeScene.fxml en geeft een scherm weer waar je creatures kan invoeren voor
* initiative, voordat je naar het echte initiative bijhoudt scherm gaat.
*
* @author R.Groot
*/
public class InitiativeController {
private final SceneManager SCENEMANAGER = Main.getSceneManager();
private ArrayList<Creature> initiative = new ArrayList<>();
//Checkboxxes
@FXML
private CheckBox lairActionCheckBox;
@FXML
private ListView<Creature> initiativeList;
@FXML
private TextField nameTextField;
@FXML
private TextField initiativeTextField;
@FXML
private TextField hpTextField;
@FXML
private TextField maxHPTextField;
@FXML
private TextField legResTextField;
@FXML
private TextField legActTextField;
@FXML
private VBox legendaryControls;
@FXML
private CheckBox legendaryCheckBox;
/**Deze methode wordt gestart wanneer naar dit scherm wordt gegaan. Momenteel doet deze methode niets, maar
* in de toekomst kunnen hier dingen aan toegevoegd worden als nodig.
*/
public void setup() {
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
}
/**Deze methode zet de initiativeList op volgorde van initiative (hoog naar laag).
*
*/
public void orderList() {
initiative.sort((c1, c2) -> Double.compare(c2.getInitiative(), c1.getInitiative()));
initiativeList.getItems().setAll(initiative);
}
public void handleLegendaryCheckBox(){
legendaryControls.setVisible(legendaryCheckBox.isSelected());
if(legendaryCheckBox.isSelected()) {
legendaryControls.setVisible(true);
legResTextField.setText(String.valueOf(0));
} else{
legendaryControls.setVisible(false);
}
}
/**Met deze methode wordt een creature toegevoegd aan de initiativeList.
*
*/
public void doAdd() {
if(validateCreature()) {
try {
double getInitiative = Double.parseDouble(initiativeTextField.getText());
int getHP = Integer.parseInt(hpTextField.getText());
int getMaxHP = Integer.parseInt(maxHPTextField.getText());
int legRes = 0;
int legAct = 0;
if (!legResTextField.getText().isEmpty()) {
legRes = Integer.parseInt(legResTextField.getText());
}
if (!legActTextField.getText().isEmpty()) {
legAct = Integer.parseInt(legActTextField.getText());
}
initiative.add(new Creature(nameTextField.getText(), getInitiative, getHP, getMaxHP, legRes, legAct));
nameTextField.setText("");
initiativeTextField.setText("");
hpTextField.setText("");
maxHPTextField.setText("");
legResTextField.setText("0");
legActTextField.setText("0");
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
orderList();
} catch (NumberFormatException exception) {
showAlert("Initiative and HP must be valid numbers!");
}
}
}
/**Met deze methode wordt de gebruiker naar de initiativeTracker scherm gebracht.
*
*/
public void doTracker() {
if(initiative == null) {
showAlert("Your initiative list is empty!");
}
SCENEMANAGER.showInitiativeTrackerScene(initiative, lairActionCheckBox.isSelected());
}
/**Met deze methode<SUF>*/
public void doDelete() {
Creature selectedCreature = initiativeList.getSelectionModel().getSelectedItem();
if (selectedCreature != null) {
initiative.remove(selectedCreature);
initiativeList.getItems().remove(selectedCreature);
}
}
/**Met deze methode wordt een creature die de gebruiker probeert toe te voegen gevallideerd op een aantal
* punten. De creature kan alleen toegevoegd worden als het overal aan voldoet.
*
* @return: true als het overal aan voldoet.
*/
public boolean validateCreature() {
String name = nameTextField.getText();
String initiativeText = initiativeTextField.getText();
String hpText = hpTextField.getText();
String maxHPText = maxHPTextField.getText();
if (name.isEmpty() || initiativeText.isEmpty() || hpText.isEmpty() || maxHPText.isEmpty()) {
showAlert("All fields are required!");
return false;
}
if(initiative != null) {
ArrayList<String> names = initiative.stream().map(Creature::getName).collect(Collectors.toCollection(ArrayList::new));
for (String creatureName : names) {
if(name.equalsIgnoreCase(creatureName)) {
showAlert("This name is already in the initiative list!");
return false;
}
}
}
if (Integer.parseInt(hpText) < 0 || Integer.parseInt(maxHPText) < 0) {
showAlert("You can't add a creature with less then 0 (max) HP.");
return false;
}
if(nameTextField.getText().length() > 20) {
showAlert("The creature's name can't be more then 20 characters long.");
return false;
}
if (Integer.parseInt(hpText) > Integer.parseInt(maxHPText)) {
showAlert("HP can't be higher than max HP!");
return false;
}
return true;
}
public void lowerLegRes(){
int newLegRes = Integer.parseInt(legResTextField.getText()) - 1;
if(newLegRes < 0) {
showAlert("A creature can't have less then 0 legendary resistances!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void addLegRes(){
if(legResTextField.getText().isEmpty()) {
legResTextField.setText("0");
}
int newLegRes = Integer.parseInt(legResTextField.getText()) + 1;
if(newLegRes > 5) {
showAlert("A creature can't have more then 5 legendary resistances in this program!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void lowerLegAct(){
int newLegAct = Integer.parseInt(legActTextField.getText()) - 1;
if(newLegAct < 0) {
showAlert("A creature can't have less then 0 legendary actions!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void addLegAct(){
if(legActTextField.getText().isEmpty()) {
legActTextField.setText("0");
}
int newLegAct = Integer.parseInt(legActTextField.getText()) + 1;
if(newLegAct > 5) {
showAlert("A creature can't have more then 5 legendary actions in this program!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void doMenu(){
SCENEMANAGER.showMenuScene();
}
/**Geeft een error message als deze methode wordt aangeroepen.
*
* @param message: het bericht dat weergegeven wordt in de error message.
*/
public void showAlert(String message) {
Alert errorMessage = new Alert(Alert.AlertType.ERROR);
errorMessage.setContentText(message);
errorMessage.show();
}
} | True | 1,624 | 20 | 1,850 | 21 | 1,885 | 20 | 1,850 | 21 | 2,166 | 24 | false | false | false | false | false | true |
3,696 | 27754_20 | /*
This software is OSI Certified Open Source Software.
OSI Certified is a certification mark of the Open Source Initiative.
The license (Mozilla version 1.0) can be read at the MMBase site.
See http://www.MMBase.org/license
*/
package org.mmbase.util;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;
import java.util.regex.*;
import org.mmbase.util.logging.Logger;
import org.mmbase.util.logging.Logging;
/**
* Wrapper around the response. It collects all data that is sent to it, and makes it available
* through a toString() method. It is used by taglib's Include-Tag, but it might find more general
* use, outside taglib.
*
* @author Kees Jongenburger
* @author Johannes Verelst
* @author Michiel Meeuwissen
* @since MMBase-1.7
* @version $Id$
*/
public class GenericResponseWrapper extends HttpServletResponseWrapper {
private static final Logger log = Logging.getLoggerInstance(GenericResponseWrapper.class);
/**
* If this pattern matched the first line of an InputStream then it is a XML. The encoding is in
* matching group 1 (when using " as quote) or 2 (when using ' as quote)
*/
private static final Pattern XMLHEADER = Pattern.compile("<\\?xml.*?(?:\\sencoding=(?:\"([^\"]+?)\"|'([^']+?)'))?\\s*\\?>.*", Pattern.DOTALL);
private static String UNSET_CHARSET = "iso-8859-1";
public static String TEXT_XML_DEFAULT_CHARSET = "US-ASCII";
private static String DEFAULT_CONTENTTYPE = "text/html";
private static String[] IGNORED_HEADERS = new String[]{"Last-Modified", "ETag"};
private PrintWriter writer;
private StringWriter string; // wrapped by writer
private ServletOutputStream outputStream; // wrapped by outputStream
private ByteArrayOutputStream bytes;
private String characterEncoding = UNSET_CHARSET;
private HttpServletResponse wrappedResponse;
protected String redirected = null;
/**
* Public constructor
*/
public GenericResponseWrapper(HttpServletResponse resp) {
super(resp);
wrappedResponse = resp; // I don't understand why this object is not super.getResponse();
}
/**
* Sets also a value for the characterEncoding which must be supposed.
* Normally it would be determined automaticly right, but if for some reason it doesn't you can override it.
*/
public GenericResponseWrapper(HttpServletResponse resp, String encoding) {
this(resp);
characterEncoding = encoding;
wrappedResponse = resp; //
}
/**
* Gets the response object which this wrapper is wrapping. You might need this when giving a
* redirect or so.
* @since MMBase-1.7.1
*/
public HttpServletResponse getHttpServletResponse() {
//return (HttpServletResponse) getResponse(); // should work, I think, but doesn't
HttpServletResponse response = wrappedResponse;
while (response instanceof HttpServletResponseWrapper) {
if (response instanceof GenericResponseWrapper) { // if this happens in an 'mm:included' page.
response = ((GenericResponseWrapper) response).wrappedResponse;
} else {
response = (HttpServletResponse) ((HttpServletResponseWrapper) response).getResponse();
}
}
return response;
}
private boolean mayAddHeader(String header) {
for (String element : IGNORED_HEADERS) {
if (element.equalsIgnoreCase(header)) {
return false;
}
}
return true;
}
@Override
public void sendRedirect(String location) throws IOException {
redirected = location;
getHttpServletResponse().sendRedirect(location);
}
/**
* @since MMBase-1.8.5
*/
public String getRedirected() {
return redirected;
}
@Override
public void setStatus(int s) {
getHttpServletResponse().setStatus(s);
}
@Override
public void addCookie(Cookie c) {
getHttpServletResponse().addCookie(c);
}
@Override
public void setHeader(String header, String value) {
if (mayAddHeader(header)) {
getHttpServletResponse().setHeader(header,value);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addDateHeader(java.lang.String, long)
*/
@Override
public void addDateHeader(String arg0, long arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addDateHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addHeader(java.lang.String, java.lang.String)
*/
@Override
public void addHeader(String arg0, String arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addIntHeader(java.lang.String, int)
*/
@Override
public void addIntHeader(String arg0, int arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addIntHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#containsHeader(java.lang.String)
*/
@Override
public boolean containsHeader(String arg0) {
return getHttpServletResponse().containsHeader(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#encodeRedirectURL(java.lang.String)
*/
@Override
public String encodeRedirectURL(String arg0) {
return getHttpServletResponse().encodeRedirectURL(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#encodeURL(java.lang.String)
*/
@Override
public String encodeURL(String arg0) {
return getHttpServletResponse().encodeURL(arg0);
}
/**
* @see javax.servlet.ServletResponse#getLocale()
*/
@Override
public Locale getLocale() {
return getHttpServletResponse().getLocale();
}
/**
* @see javax.servlet.http.HttpServletResponse#sendError(int, java.lang.String)
*/
@Override
public void sendError(int arg0, String arg1) throws IOException {
getHttpServletResponse().sendError(arg0, arg1);
}
/**
* @see javax.servlet.http.HttpServletResponse#sendError(int)
*/
@Override
public void sendError(int arg0) throws IOException {
getHttpServletResponse().sendError(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#setDateHeader(java.lang.String, long)
*/
@Override
public void setDateHeader(String arg0, long arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().setDateHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#setIntHeader(java.lang.String, int)
*/
@Override
public void setIntHeader(String arg0, int arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().setIntHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.ServletResponse#setLocale(java.util.Locale)
*/
@Override
public void setLocale(Locale arg0) {
getHttpServletResponse().setLocale(arg0);
}
/**
* Return the OutputStream. This is a 'MyServletOutputStream'.
*/
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (outputStream != null) return outputStream;
if (writer != null) {
outputStream = new MyServletOutputStream(new WriterOutputStream(writer, characterEncoding));
return outputStream;
//throw new RuntimeException("Should use getOutputStream _or_ getWriter");
}
bytes = new ByteArrayOutputStream();
outputStream = new MyServletOutputStream(bytes);
return outputStream;
}
/**
* Return the PrintWriter
*/
@Override
public PrintWriter getWriter() throws IOException {
if (writer != null) return writer;
if (outputStream != null) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, characterEncoding)));
return writer;
//throw new RuntimeException("Should use getOutputStream _or_ getWriter");
}
string = new StringWriter();
writer = new PrintWriter(string);
return writer;
}
/**
* Sets the content type of the response being sent to the
* client. The content type may include the type of character
* encoding used, for example, text/html; charset=ISO-8859-4. If
* obtaining a PrintWriter, this method should be called first.
*/
@Override
public void setContentType(String ct) {
String contentType = DEFAULT_CONTENTTYPE;
if (ct == null) {
contentType = DEFAULT_CONTENTTYPE;
} else {
contentType = ct;
characterEncoding = getEncoding(ct); // gets char-encoding from content type
if (characterEncoding == null) {
characterEncoding = getDefaultEncoding(contentType);
}
}
if (log.isDebugEnabled()) {
log.debug("set contenttype of include page to: '" + contentType + "' (and character encoding to '" + characterEncoding + "')");
}
}
/**
* Returns the name of the charset used for the MIME body sent in this response.
* If no charset has been assigned, it is implicitly set to ISO-8859-1 (Latin-1).
* See <a href="http://www.ietf.org/rfc/rfc2047.txt">RFC 2047</a> for more information about character encoding and MIME.
* returns the encoding
*/
@Override
public String getCharacterEncoding() {
log.debug(characterEncoding);
/*
if (characterEncoding == UNSET_CHARSET && outputStream != null) {
determinXMLEncoding();
}
*/
return characterEncoding;
}
protected byte[] determinXMLEncoding() {
byte[] allBytes = bytes.toByteArray();
characterEncoding = getXMLEncoding(allBytes);
if (characterEncoding == null) characterEncoding = "UTF-8"; // missing <?xml header, but we _know_ it is XML.
return allBytes;
}
/**
* Return all data that has been written to the PrintWriter.
*/
@Override
public String toString() {
if (string != null) {
return string.toString();
} else if (outputStream != null) {
try {
byte[] allBytes;
if (TEXT_XML_DEFAULT_CHARSET.equals(characterEncoding)) {
// see comments in getDefaultEncoding
allBytes = determinXMLEncoding();
} else {
allBytes = bytes.toByteArray();
}
return new String(allBytes, getCharacterEncoding());
} catch (Exception e) {
return bytes.toString();
}
} else {
return "";
}
}
/**
* Takes a String, which is considered to be (the first) part of an XML, and returns the
* encoding (the specified one, or the XML default)
* @return The XML Encoding, or <code>null</code> if the String was not recognized as XML (no <?xml> header found)
* @since MMBase-1.7.1
* @see #getXMLEncoding(byte[])
*/
public static String getXMLEncoding(String xmlString) {
Matcher m = XMLHEADER.matcher(xmlString);
if (! m.matches()) {
return null; // No <? xml header found, this file is probably not XML.
} else {
String encoding = m.group(1);
if (encoding == null) encoding = m.group(2);
if (encoding == null) encoding = "UTF-8"; // default encoding for XML.
return encoding;
}
}
/**
* Takes a ByteArrayInputStream, which is considered to be (the first) part of an XML, and returns the encoding.
* @return The XML Encoding, or <code>null</code> if the String was not recognized as XML (not <?xml> header found)
* @since MMBase-1.7.1
* @see #getXMLEncoding(String)
*/
public static String getXMLEncoding(byte[] allBytes) {
byte[] firstBytes = allBytes;
if (allBytes.length > 100) {
firstBytes = new byte[100];
System.arraycopy(allBytes, 0, firstBytes, 0, 100);
}
try {
return getXMLEncoding(new String(firstBytes, "US-ASCII"));
} catch (java.io.UnsupportedEncodingException uee) {
// cannot happen, US-ASCII is known
}
return "UTF-8"; // cannot come here.
}
/**
* Takes the value of a Content-Type header, and tries to find the encoding from it.
* @since MMBase-1.7.1
* @return The found charset if found, otherwise 'null'
*/
public static String getEncoding(String contentType) {
String contentTypeLowerCase = contentType.toLowerCase();
int cs = contentTypeLowerCase.indexOf("charset=");
if (cs > 0) {
return contentType.substring(cs + 8);
} else {
return null;
}
}
/**
* Supposes that no explicit charset is mentioned in a contentType, and returns a default. (UTF-8 or US-ASCII
* for XML types and ISO-8859-1 otherwise).
* @since MMBase-1.7.1
* @return A charset.
*/
public static String getDefaultEncoding(String contentType) {
if ("text/xml".equals(contentType)) {
return TEXT_XML_DEFAULT_CHARSET; // = us-ascii, See
// http://www.rfc-editor.org/rfc/rfc3023.txt. We will
// ignore it, because if not not ascii, it will never
// work, and all known charset are superset of us-ascii
// (so the response _is_ correct it will work).
} else if ("application/xml".equals(contentType) || "application/xhtml+xml".equals(contentType)) {
return "UTF-8";
} else {
return "iso-8859-1";
}
}
}
/**
* Implements ServletOutputStream.
*/
class MyServletOutputStream extends ServletOutputStream {
private OutputStream stream;
public MyServletOutputStream(OutputStream output) {
stream = output;
}
public void write(int b) throws IOException {
stream.write(b);
}
@Override
public void write(byte[] b) throws IOException {
stream.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
stream.write(b, off, len);
}
}
| mmbase/mmbase-utils | src/main/java/org/mmbase/util/GenericResponseWrapper.java | 4,077 | /**
* @see javax.servlet.http.HttpServletResponse#sendError(int)
*/ | block_comment | nl | /*
This software is OSI Certified Open Source Software.
OSI Certified is a certification mark of the Open Source Initiative.
The license (Mozilla version 1.0) can be read at the MMBase site.
See http://www.MMBase.org/license
*/
package org.mmbase.util;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;
import java.util.regex.*;
import org.mmbase.util.logging.Logger;
import org.mmbase.util.logging.Logging;
/**
* Wrapper around the response. It collects all data that is sent to it, and makes it available
* through a toString() method. It is used by taglib's Include-Tag, but it might find more general
* use, outside taglib.
*
* @author Kees Jongenburger
* @author Johannes Verelst
* @author Michiel Meeuwissen
* @since MMBase-1.7
* @version $Id$
*/
public class GenericResponseWrapper extends HttpServletResponseWrapper {
private static final Logger log = Logging.getLoggerInstance(GenericResponseWrapper.class);
/**
* If this pattern matched the first line of an InputStream then it is a XML. The encoding is in
* matching group 1 (when using " as quote) or 2 (when using ' as quote)
*/
private static final Pattern XMLHEADER = Pattern.compile("<\\?xml.*?(?:\\sencoding=(?:\"([^\"]+?)\"|'([^']+?)'))?\\s*\\?>.*", Pattern.DOTALL);
private static String UNSET_CHARSET = "iso-8859-1";
public static String TEXT_XML_DEFAULT_CHARSET = "US-ASCII";
private static String DEFAULT_CONTENTTYPE = "text/html";
private static String[] IGNORED_HEADERS = new String[]{"Last-Modified", "ETag"};
private PrintWriter writer;
private StringWriter string; // wrapped by writer
private ServletOutputStream outputStream; // wrapped by outputStream
private ByteArrayOutputStream bytes;
private String characterEncoding = UNSET_CHARSET;
private HttpServletResponse wrappedResponse;
protected String redirected = null;
/**
* Public constructor
*/
public GenericResponseWrapper(HttpServletResponse resp) {
super(resp);
wrappedResponse = resp; // I don't understand why this object is not super.getResponse();
}
/**
* Sets also a value for the characterEncoding which must be supposed.
* Normally it would be determined automaticly right, but if for some reason it doesn't you can override it.
*/
public GenericResponseWrapper(HttpServletResponse resp, String encoding) {
this(resp);
characterEncoding = encoding;
wrappedResponse = resp; //
}
/**
* Gets the response object which this wrapper is wrapping. You might need this when giving a
* redirect or so.
* @since MMBase-1.7.1
*/
public HttpServletResponse getHttpServletResponse() {
//return (HttpServletResponse) getResponse(); // should work, I think, but doesn't
HttpServletResponse response = wrappedResponse;
while (response instanceof HttpServletResponseWrapper) {
if (response instanceof GenericResponseWrapper) { // if this happens in an 'mm:included' page.
response = ((GenericResponseWrapper) response).wrappedResponse;
} else {
response = (HttpServletResponse) ((HttpServletResponseWrapper) response).getResponse();
}
}
return response;
}
private boolean mayAddHeader(String header) {
for (String element : IGNORED_HEADERS) {
if (element.equalsIgnoreCase(header)) {
return false;
}
}
return true;
}
@Override
public void sendRedirect(String location) throws IOException {
redirected = location;
getHttpServletResponse().sendRedirect(location);
}
/**
* @since MMBase-1.8.5
*/
public String getRedirected() {
return redirected;
}
@Override
public void setStatus(int s) {
getHttpServletResponse().setStatus(s);
}
@Override
public void addCookie(Cookie c) {
getHttpServletResponse().addCookie(c);
}
@Override
public void setHeader(String header, String value) {
if (mayAddHeader(header)) {
getHttpServletResponse().setHeader(header,value);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addDateHeader(java.lang.String, long)
*/
@Override
public void addDateHeader(String arg0, long arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addDateHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addHeader(java.lang.String, java.lang.String)
*/
@Override
public void addHeader(String arg0, String arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addIntHeader(java.lang.String, int)
*/
@Override
public void addIntHeader(String arg0, int arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addIntHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#containsHeader(java.lang.String)
*/
@Override
public boolean containsHeader(String arg0) {
return getHttpServletResponse().containsHeader(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#encodeRedirectURL(java.lang.String)
*/
@Override
public String encodeRedirectURL(String arg0) {
return getHttpServletResponse().encodeRedirectURL(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#encodeURL(java.lang.String)
*/
@Override
public String encodeURL(String arg0) {
return getHttpServletResponse().encodeURL(arg0);
}
/**
* @see javax.servlet.ServletResponse#getLocale()
*/
@Override
public Locale getLocale() {
return getHttpServletResponse().getLocale();
}
/**
* @see javax.servlet.http.HttpServletResponse#sendError(int, java.lang.String)
*/
@Override
public void sendError(int arg0, String arg1) throws IOException {
getHttpServletResponse().sendError(arg0, arg1);
}
/**
* @see javax.servlet.http.HttpServletResponse#sendError(int)
<SUF>*/
@Override
public void sendError(int arg0) throws IOException {
getHttpServletResponse().sendError(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#setDateHeader(java.lang.String, long)
*/
@Override
public void setDateHeader(String arg0, long arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().setDateHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#setIntHeader(java.lang.String, int)
*/
@Override
public void setIntHeader(String arg0, int arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().setIntHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.ServletResponse#setLocale(java.util.Locale)
*/
@Override
public void setLocale(Locale arg0) {
getHttpServletResponse().setLocale(arg0);
}
/**
* Return the OutputStream. This is a 'MyServletOutputStream'.
*/
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (outputStream != null) return outputStream;
if (writer != null) {
outputStream = new MyServletOutputStream(new WriterOutputStream(writer, characterEncoding));
return outputStream;
//throw new RuntimeException("Should use getOutputStream _or_ getWriter");
}
bytes = new ByteArrayOutputStream();
outputStream = new MyServletOutputStream(bytes);
return outputStream;
}
/**
* Return the PrintWriter
*/
@Override
public PrintWriter getWriter() throws IOException {
if (writer != null) return writer;
if (outputStream != null) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, characterEncoding)));
return writer;
//throw new RuntimeException("Should use getOutputStream _or_ getWriter");
}
string = new StringWriter();
writer = new PrintWriter(string);
return writer;
}
/**
* Sets the content type of the response being sent to the
* client. The content type may include the type of character
* encoding used, for example, text/html; charset=ISO-8859-4. If
* obtaining a PrintWriter, this method should be called first.
*/
@Override
public void setContentType(String ct) {
String contentType = DEFAULT_CONTENTTYPE;
if (ct == null) {
contentType = DEFAULT_CONTENTTYPE;
} else {
contentType = ct;
characterEncoding = getEncoding(ct); // gets char-encoding from content type
if (characterEncoding == null) {
characterEncoding = getDefaultEncoding(contentType);
}
}
if (log.isDebugEnabled()) {
log.debug("set contenttype of include page to: '" + contentType + "' (and character encoding to '" + characterEncoding + "')");
}
}
/**
* Returns the name of the charset used for the MIME body sent in this response.
* If no charset has been assigned, it is implicitly set to ISO-8859-1 (Latin-1).
* See <a href="http://www.ietf.org/rfc/rfc2047.txt">RFC 2047</a> for more information about character encoding and MIME.
* returns the encoding
*/
@Override
public String getCharacterEncoding() {
log.debug(characterEncoding);
/*
if (characterEncoding == UNSET_CHARSET && outputStream != null) {
determinXMLEncoding();
}
*/
return characterEncoding;
}
protected byte[] determinXMLEncoding() {
byte[] allBytes = bytes.toByteArray();
characterEncoding = getXMLEncoding(allBytes);
if (characterEncoding == null) characterEncoding = "UTF-8"; // missing <?xml header, but we _know_ it is XML.
return allBytes;
}
/**
* Return all data that has been written to the PrintWriter.
*/
@Override
public String toString() {
if (string != null) {
return string.toString();
} else if (outputStream != null) {
try {
byte[] allBytes;
if (TEXT_XML_DEFAULT_CHARSET.equals(characterEncoding)) {
// see comments in getDefaultEncoding
allBytes = determinXMLEncoding();
} else {
allBytes = bytes.toByteArray();
}
return new String(allBytes, getCharacterEncoding());
} catch (Exception e) {
return bytes.toString();
}
} else {
return "";
}
}
/**
* Takes a String, which is considered to be (the first) part of an XML, and returns the
* encoding (the specified one, or the XML default)
* @return The XML Encoding, or <code>null</code> if the String was not recognized as XML (no <?xml> header found)
* @since MMBase-1.7.1
* @see #getXMLEncoding(byte[])
*/
public static String getXMLEncoding(String xmlString) {
Matcher m = XMLHEADER.matcher(xmlString);
if (! m.matches()) {
return null; // No <? xml header found, this file is probably not XML.
} else {
String encoding = m.group(1);
if (encoding == null) encoding = m.group(2);
if (encoding == null) encoding = "UTF-8"; // default encoding for XML.
return encoding;
}
}
/**
* Takes a ByteArrayInputStream, which is considered to be (the first) part of an XML, and returns the encoding.
* @return The XML Encoding, or <code>null</code> if the String was not recognized as XML (not <?xml> header found)
* @since MMBase-1.7.1
* @see #getXMLEncoding(String)
*/
public static String getXMLEncoding(byte[] allBytes) {
byte[] firstBytes = allBytes;
if (allBytes.length > 100) {
firstBytes = new byte[100];
System.arraycopy(allBytes, 0, firstBytes, 0, 100);
}
try {
return getXMLEncoding(new String(firstBytes, "US-ASCII"));
} catch (java.io.UnsupportedEncodingException uee) {
// cannot happen, US-ASCII is known
}
return "UTF-8"; // cannot come here.
}
/**
* Takes the value of a Content-Type header, and tries to find the encoding from it.
* @since MMBase-1.7.1
* @return The found charset if found, otherwise 'null'
*/
public static String getEncoding(String contentType) {
String contentTypeLowerCase = contentType.toLowerCase();
int cs = contentTypeLowerCase.indexOf("charset=");
if (cs > 0) {
return contentType.substring(cs + 8);
} else {
return null;
}
}
/**
* Supposes that no explicit charset is mentioned in a contentType, and returns a default. (UTF-8 or US-ASCII
* for XML types and ISO-8859-1 otherwise).
* @since MMBase-1.7.1
* @return A charset.
*/
public static String getDefaultEncoding(String contentType) {
if ("text/xml".equals(contentType)) {
return TEXT_XML_DEFAULT_CHARSET; // = us-ascii, See
// http://www.rfc-editor.org/rfc/rfc3023.txt. We will
// ignore it, because if not not ascii, it will never
// work, and all known charset are superset of us-ascii
// (so the response _is_ correct it will work).
} else if ("application/xml".equals(contentType) || "application/xhtml+xml".equals(contentType)) {
return "UTF-8";
} else {
return "iso-8859-1";
}
}
}
/**
* Implements ServletOutputStream.
*/
class MyServletOutputStream extends ServletOutputStream {
private OutputStream stream;
public MyServletOutputStream(OutputStream output) {
stream = output;
}
public void write(int b) throws IOException {
stream.write(b);
}
@Override
public void write(byte[] b) throws IOException {
stream.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
stream.write(b, off, len);
}
}
| False | 3,196 | 16 | 3,382 | 20 | 3,773 | 23 | 3,382 | 20 | 4,067 | 24 | false | false | false | false | false | true |
3,335 | 47139_3 | package src.engine.core.tools;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.sound.sampled.*;
public class MusicPlayer {
// enum for sound effects
public enum SoundEffect {
//Pistol SFX
MORE_BULLETS("src/sound/guns/moreBullets.wav"),
BIGGER_GUN("src/sound/guns/biggerWeapons.wav"),
PICKUP_PISTOL("src/sound/guns/pistol/pickupPistol.wav"),
SHOOT_PISTOL("src/sound/guns/pistol/pistolShot.wav"),
RELOAD_PISTOL("src/sound/guns/pistol/pistolReload.wav"),
//Shotgun SFX
PICKUP_SHOTGUN("src/sound/guns/shotgun/pickupShotgun.wav"),
SHOOT_SHOTGUN("src/sound/guns/shotgun/shotgunShot.wav"),
RELOAD_SHOTGUN("src/sound/guns/shotgun/reloadShotgun.wav"),
//AK SFX
SHOOT_AK("src/sound/guns/AKM/AKM_shoot.wav"),
PICKUP_AK("src/sound/guns/AKM/AKM_rack.wav"),
RELOAD_AK("src/sound/guns/AKM/AKM_reload.wav"),
//Sniper SFX
SHOOT_SNIPER("src/sound/guns/sniper/sniperShot.wav"),
PICKUP_SNIPER("src/sound/guns/sniper/sniperPickup.wav"),
RELOAD_SNIPER("src/sound/guns/sniper/sniperReload.wav"),
SCOPE("src/sound/guns/sniper/scope.wav"),
Knife("src/sound/misc/knife.wav"),
//Round over SFX
LEVEL_FINISHED("src/sound/misc/newRound.wav"),
//player Death SFX
GAME_OVER("src/sound/misc/gameOver.wav"),
//Enemy SFX
GE_DEATH("src/sound/enemies/groundEnemy/groundEnemy_death.wav"),
GUNNER_DEATH("src/sound/enemies/gunTurret/gunTurret_death.wav"),
SIGHSEEKER_ATTACK("src/sound/misc/shoot.wav"),
SIGHTSEEKER_DEATH("src/sound/enemies/sightSeeker/sightSeeker_death.wav"),
MALTESEEKER_RANDOMTALK1("src/sound/enemies/malteSeeker/Alter_marcel.wav"),
MALTESEEKER_RANDOMTALK2("src/sound/enemies/malteSeeker/Alter_marcel_tief_schnell.wav"),
MALTESEEKER_SPAWN_AND_ATTACK("src/sound/enemies/malteSeeker/hallo.wav"),
MALTESEEKER_RANDOMTALK3("src/sound/enemies/malteSeeker/Marcel_ist_immer_schuld.wav");
private final String path;
SoundEffect(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
private static volatile MusicPlayer instance;
private ExecutorService threadPool;
private HashMap<String, Clip> soundClips;
public float volume = 0.8f;
private MusicPlayer() {
threadPool = Executors.newCachedThreadPool();
soundClips = new HashMap<>();
// Initialize resources
}
//adjust volume
public void changeVolume(float volume) {
this.volume = volume;
}
public void setVolume(Clip clip){
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
double gain = volume; // number between 0 and 1 (loudest)
float dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
gainControl.setValue(dB);
}
//singleton
public static MusicPlayer getInstance() {
if (instance == null) {
synchronized (MusicPlayer.class) {
if (instance == null)
instance = new MusicPlayer();
}
}
return instance;
}
public void playSound(String sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound); // Implement loadClip to load and return a Clip
soundClips.put(sound, clip);
setVolume(clip);
clip.start();
});
}
public void playSound(SoundEffect sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound.getPath()); // Implement loadClip to load and return a Clip
soundClips.put(sound.getPath(), clip);
setVolume(clip);
clip.start();
});
}
public void playRandomPlayerSound() {
String[] playerSounds = {"src/sound/player/player_damage_1.wav",
"src/sound/player/player_damage_2.wav",
"src/sound/player/player_damage_3.wav",
"src/sound/player/player_damage_4.wav",
"src/sound/player/player_damage_5.wav",
"src/sound/player/player_damage_6.wav",
"src/sound/player/player_damage_7.wav",
"src/sound/player/player_damage_8.wav"
};
threadPool.execute(() -> {
int random = (int) (Math.random() * playerSounds.length);
Clip clip = loadClip(playerSounds[random]); // Implement loadClip to load and return a Clip
soundClips.put(playerSounds[random], clip);
setVolume(clip);
clip.start();
});
}
private Clip loadClip(String filePath) {
try {
// Open an audio input stream from the file path
File audioFile = new File(filePath);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
// Get a clip resource
Clip clip = AudioSystem.getClip();
// Open the clip and load samples from the audio input stream
clip.open(audioStream);
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace(); // Handle exceptions appropriately
return null;
}
}
public void loopMusic(String sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound); // Implement loadClip to load and return a Clip
soundClips.put(sound, clip);
clip.loop(Clip.LOOP_CONTINUOUSLY);
});
}
public void pauseResume(String sound) {
threadPool.execute(() -> {
Clip clip = soundClips.get(sound);
setVolume(clip);
if (clip.isActive()) {
clip.stop();
} else {
clip.start();
}
});
}
public void stopGameMusic(){
for (Clip clip : soundClips.values()) {
if (clip.isRunning()) {
clip.stop(); // Stop the clip if it is running
}
clip.close(); // Close the clip to release resources
}
soundClips.clear();
}
}
| kastanileel/CPUCrunchEngine | src/engine/core/tools/MusicPlayer.java | 2,123 | // number between 0 and 1 (loudest) | line_comment | nl | package src.engine.core.tools;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.sound.sampled.*;
public class MusicPlayer {
// enum for sound effects
public enum SoundEffect {
//Pistol SFX
MORE_BULLETS("src/sound/guns/moreBullets.wav"),
BIGGER_GUN("src/sound/guns/biggerWeapons.wav"),
PICKUP_PISTOL("src/sound/guns/pistol/pickupPistol.wav"),
SHOOT_PISTOL("src/sound/guns/pistol/pistolShot.wav"),
RELOAD_PISTOL("src/sound/guns/pistol/pistolReload.wav"),
//Shotgun SFX
PICKUP_SHOTGUN("src/sound/guns/shotgun/pickupShotgun.wav"),
SHOOT_SHOTGUN("src/sound/guns/shotgun/shotgunShot.wav"),
RELOAD_SHOTGUN("src/sound/guns/shotgun/reloadShotgun.wav"),
//AK SFX
SHOOT_AK("src/sound/guns/AKM/AKM_shoot.wav"),
PICKUP_AK("src/sound/guns/AKM/AKM_rack.wav"),
RELOAD_AK("src/sound/guns/AKM/AKM_reload.wav"),
//Sniper SFX
SHOOT_SNIPER("src/sound/guns/sniper/sniperShot.wav"),
PICKUP_SNIPER("src/sound/guns/sniper/sniperPickup.wav"),
RELOAD_SNIPER("src/sound/guns/sniper/sniperReload.wav"),
SCOPE("src/sound/guns/sniper/scope.wav"),
Knife("src/sound/misc/knife.wav"),
//Round over SFX
LEVEL_FINISHED("src/sound/misc/newRound.wav"),
//player Death SFX
GAME_OVER("src/sound/misc/gameOver.wav"),
//Enemy SFX
GE_DEATH("src/sound/enemies/groundEnemy/groundEnemy_death.wav"),
GUNNER_DEATH("src/sound/enemies/gunTurret/gunTurret_death.wav"),
SIGHSEEKER_ATTACK("src/sound/misc/shoot.wav"),
SIGHTSEEKER_DEATH("src/sound/enemies/sightSeeker/sightSeeker_death.wav"),
MALTESEEKER_RANDOMTALK1("src/sound/enemies/malteSeeker/Alter_marcel.wav"),
MALTESEEKER_RANDOMTALK2("src/sound/enemies/malteSeeker/Alter_marcel_tief_schnell.wav"),
MALTESEEKER_SPAWN_AND_ATTACK("src/sound/enemies/malteSeeker/hallo.wav"),
MALTESEEKER_RANDOMTALK3("src/sound/enemies/malteSeeker/Marcel_ist_immer_schuld.wav");
private final String path;
SoundEffect(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
private static volatile MusicPlayer instance;
private ExecutorService threadPool;
private HashMap<String, Clip> soundClips;
public float volume = 0.8f;
private MusicPlayer() {
threadPool = Executors.newCachedThreadPool();
soundClips = new HashMap<>();
// Initialize resources
}
//adjust volume
public void changeVolume(float volume) {
this.volume = volume;
}
public void setVolume(Clip clip){
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
double gain = volume; // number between<SUF>
float dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
gainControl.setValue(dB);
}
//singleton
public static MusicPlayer getInstance() {
if (instance == null) {
synchronized (MusicPlayer.class) {
if (instance == null)
instance = new MusicPlayer();
}
}
return instance;
}
public void playSound(String sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound); // Implement loadClip to load and return a Clip
soundClips.put(sound, clip);
setVolume(clip);
clip.start();
});
}
public void playSound(SoundEffect sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound.getPath()); // Implement loadClip to load and return a Clip
soundClips.put(sound.getPath(), clip);
setVolume(clip);
clip.start();
});
}
public void playRandomPlayerSound() {
String[] playerSounds = {"src/sound/player/player_damage_1.wav",
"src/sound/player/player_damage_2.wav",
"src/sound/player/player_damage_3.wav",
"src/sound/player/player_damage_4.wav",
"src/sound/player/player_damage_5.wav",
"src/sound/player/player_damage_6.wav",
"src/sound/player/player_damage_7.wav",
"src/sound/player/player_damage_8.wav"
};
threadPool.execute(() -> {
int random = (int) (Math.random() * playerSounds.length);
Clip clip = loadClip(playerSounds[random]); // Implement loadClip to load and return a Clip
soundClips.put(playerSounds[random], clip);
setVolume(clip);
clip.start();
});
}
private Clip loadClip(String filePath) {
try {
// Open an audio input stream from the file path
File audioFile = new File(filePath);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
// Get a clip resource
Clip clip = AudioSystem.getClip();
// Open the clip and load samples from the audio input stream
clip.open(audioStream);
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace(); // Handle exceptions appropriately
return null;
}
}
public void loopMusic(String sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound); // Implement loadClip to load and return a Clip
soundClips.put(sound, clip);
clip.loop(Clip.LOOP_CONTINUOUSLY);
});
}
public void pauseResume(String sound) {
threadPool.execute(() -> {
Clip clip = soundClips.get(sound);
setVolume(clip);
if (clip.isActive()) {
clip.stop();
} else {
clip.start();
}
});
}
public void stopGameMusic(){
for (Clip clip : soundClips.values()) {
if (clip.isRunning()) {
clip.stop(); // Stop the clip if it is running
}
clip.close(); // Close the clip to release resources
}
soundClips.clear();
}
}
| False | 1,490 | 13 | 1,719 | 13 | 1,758 | 12 | 1,719 | 13 | 2,098 | 13 | false | false | false | false | false | true |
2,114 | 58011_1 | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LinearRing;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import org.geotools.data.dxf.parser.DXFParseException;
import org.geotools.data.dxf.parser.DXFUnivers;
/** @source $URL$ */
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness,
DXFExtendedData extData) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
_extendedData = extData;
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers)
throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
DXFExtendedData _extData = null;
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:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: // "10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: // "2"
name = cvp.getStringValue();
break;
case LAYER_NAME: // "8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: // "6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: // "62"
c = cvp.getShortValue();
break;
case INT_1: // "70"
flag = cvp.getShortValue();
break;
case VISIBILITY: // "60"
visibility = cvp.getShortValue();
break;
case XDATA_APPLICATION_NAME:
String appName = cvp.getStringValue();
_extData = DXFExtendedData.getExtendedData(br);
_extData.setAppName(appName);
break;
default:
break;
}
}
DXFLwPolyline e =
new DXFLwPolyline(
name,
flag,
c,
l,
lv,
visibility,
lineType,
DXFTables.defaultThickness,
_extData);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices)
throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
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:
case X_1: // "10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: // "20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: // "42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[] {}));
}
public String toString(
String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(
getName(),
_flag,
theVertices.size(),
getColor(),
(isVisible() ? 0 : 1),
getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| apollo-mapping/geotools | modules/unsupported/dxf/src/main/java/org/geotools/data/dxf/entities/DXFLwPolyline.java | 3,599 | // geldt voor alle waarden van type | line_comment | nl | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LinearRing;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import org.geotools.data.dxf.parser.DXFParseException;
import org.geotools.data.dxf.parser.DXFUnivers;
/** @source $URL$ */
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness,
DXFExtendedData extData) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
_extendedData = extData;
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers)
throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
DXFExtendedData _extData = null;
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:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor<SUF>
br.reset();
doLoop = false;
break;
case X_1: // "10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: // "2"
name = cvp.getStringValue();
break;
case LAYER_NAME: // "8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: // "6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: // "62"
c = cvp.getShortValue();
break;
case INT_1: // "70"
flag = cvp.getShortValue();
break;
case VISIBILITY: // "60"
visibility = cvp.getShortValue();
break;
case XDATA_APPLICATION_NAME:
String appName = cvp.getStringValue();
_extData = DXFExtendedData.getExtendedData(br);
_extData.setAppName(appName);
break;
default:
break;
}
}
DXFLwPolyline e =
new DXFLwPolyline(
name,
flag,
c,
l,
lv,
visibility,
lineType,
DXFTables.defaultThickness,
_extData);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices)
throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
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:
case X_1: // "10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: // "20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: // "42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[] {}));
}
public String toString(
String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(
getName(),
_flag,
theVertices.size(),
getColor(),
(isVisible() ? 0 : 1),
getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| True | 2,668 | 9 | 2,901 | 10 | 3,156 | 8 | 2,901 | 10 | 3,585 | 9 | false | false | false | false | false | true |
1,802 | 17171_2 | package be.ucll.java.ent;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@WebServlet("/inschrijving")
public class InschrijvingServlet extends HttpServlet {
// private static final String COOKIE_STUDENT = "StudentInfo";
private String stud_name = "";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
/*
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie: cookies){
if (cookie != null && cookie.getName() != null && cookie.getName().trim().equalsIgnoreCase(COOKIE_STUDENT)) {
String tmp = cookie.getValue();
if (tmp != null && tmp.trim().length() > 0) {
stud_name = URLDecoder.decode(tmp.trim(), StandardCharsets.UTF_8.toString());
}
}
}
} else {
this.getServletContext().log("No cookies found");
}
*/
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println("<title>Inschrijving</title>");
pw.println("</head>");
pw.println("<body>");
pw.println(" <p><h3>Schrijf u in voor het opleidingsonderdeel 'Java Enterprise'.</h3>");
pw.println(" <form action='" + request.getContextPath() + request.getServletPath() + "' method='post'>");
pw.println(" Student naam: <input type='text' name='stud_name' size='50' maxlength='50' value='" + stud_name + "' /><br/><br/> ");
pw.println(" <input type='submit' value='Inschrijven'/>");
pw.println(" </form></p>");
pw.println("</body>");
pw.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
stud_name = request.getParameter("stud_name");
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println(" <title>Hello Servlets</title>");
pw.println("</head>");
pw.println("<body>");
if (stud_name != null && stud_name.trim().length() > 0) {
pw.println(" <p><h3>Bedankt " + stud_name + ". U bent ingeschreven</h3>");
/*
// Create a cookie. Een 'cookie' kan zeer weinig info bevatten en de inhoud die je wil opslaan hou je best onder de 4000 bytes.
String encodedStr = URLEncoder.encode(stud_name, StandardCharsets.UTF_8.toString());
Cookie cookie = new Cookie(COOKIE_STUDENT, encodedStr);
cookie.setMaxAge(60 * 60 * 24 * 7); // Seconds, 60 * 60 * 24 * 7 = 1 week
response.addCookie(cookie);
this.getServletContext().log("Added cookie with name: " + COOKIE_STUDENT + ", value: " + encodedStr);
*/
} else {
pw.println(" <p><h3>De naam ontbreekt. U bent niet ingeschreven</h3>");
}
pw.println(" <br/><a href='." + request.getServletPath() + "'>Keer terug naar inschrijving</a>");
pw.println(" <br/><br/>Session Id: " + request.getSession().getId());
pw.println("</body>");
pw.println("</html>");
}
}
} | UcllJavaEnterprise/first-servlet | src/main/java/be/ucll/java/ent/InschrijvingServlet.java | 1,157 | /*
// Create a cookie. Een 'cookie' kan zeer weinig info bevatten en de inhoud die je wil opslaan hou je best onder de 4000 bytes.
String encodedStr = URLEncoder.encode(stud_name, StandardCharsets.UTF_8.toString());
Cookie cookie = new Cookie(COOKIE_STUDENT, encodedStr);
cookie.setMaxAge(60 * 60 * 24 * 7); // Seconds, 60 * 60 * 24 * 7 = 1 week
response.addCookie(cookie);
this.getServletContext().log("Added cookie with name: " + COOKIE_STUDENT + ", value: " + encodedStr);
*/ | block_comment | nl | package be.ucll.java.ent;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@WebServlet("/inschrijving")
public class InschrijvingServlet extends HttpServlet {
// private static final String COOKIE_STUDENT = "StudentInfo";
private String stud_name = "";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
/*
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie: cookies){
if (cookie != null && cookie.getName() != null && cookie.getName().trim().equalsIgnoreCase(COOKIE_STUDENT)) {
String tmp = cookie.getValue();
if (tmp != null && tmp.trim().length() > 0) {
stud_name = URLDecoder.decode(tmp.trim(), StandardCharsets.UTF_8.toString());
}
}
}
} else {
this.getServletContext().log("No cookies found");
}
*/
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println("<title>Inschrijving</title>");
pw.println("</head>");
pw.println("<body>");
pw.println(" <p><h3>Schrijf u in voor het opleidingsonderdeel 'Java Enterprise'.</h3>");
pw.println(" <form action='" + request.getContextPath() + request.getServletPath() + "' method='post'>");
pw.println(" Student naam: <input type='text' name='stud_name' size='50' maxlength='50' value='" + stud_name + "' /><br/><br/> ");
pw.println(" <input type='submit' value='Inschrijven'/>");
pw.println(" </form></p>");
pw.println("</body>");
pw.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
stud_name = request.getParameter("stud_name");
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println(" <title>Hello Servlets</title>");
pw.println("</head>");
pw.println("<body>");
if (stud_name != null && stud_name.trim().length() > 0) {
pw.println(" <p><h3>Bedankt " + stud_name + ". U bent ingeschreven</h3>");
/*
// Create a cookie.<SUF>*/
} else {
pw.println(" <p><h3>De naam ontbreekt. U bent niet ingeschreven</h3>");
}
pw.println(" <br/><a href='." + request.getServletPath() + "'>Keer terug naar inschrijving</a>");
pw.println(" <br/><br/>Session Id: " + request.getSession().getId());
pw.println("</body>");
pw.println("</html>");
}
}
} | True | 848 | 152 | 986 | 167 | 993 | 159 | 986 | 167 | 1,170 | 185 | false | false | false | false | false | true |
636 | 43016_2 | /* Copyright (c) 2018 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator;
import com.qualcomm.hardware.rev.Rev2mDistanceSensor;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.navigation.Acceleration;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.tfod.Recognition;
import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector;
import java.util.List;
/**
* This 2018-2019 OpMode illustrates the basics of using the TensorFlow Object Detection API to
* determine the position of the gold and silver minerals.
*
* Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list.
*
* IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as
* is explained below.
*/
@Disabled
@Autonomous(name = "Crater Side", group = "Concept")
public class CraterSide extends LinearOpMode {
private enum mineralPosEnum {none,left,center,right};
private mineralPosEnum mineralPos;
public int Runstate = 0;
private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite";
private static final String LABEL_GOLD_MINERAL = "Gold Mineral";
private static final String LABEL_SILVER_MINERAL = "Silver Mineral";
private DcMotor MotorFrontLeft;
private DcMotor MotorBackLeft;
private DcMotor MotorFrontRight;
private DcMotor MotorBackRight;
private DcMotor HijsMotor;
private Servo BlockBoxServo;
private Rev2mDistanceSensor frontDistance;
private Rev2mDistanceSensor bottomDistance;
private float LandedDistance = 15.5f; //TODO: meten startwaarde, gemiddelde pakken vnan een aantal metingen
private float heading;
private BNO055IMU imu;
Acceleration gravity;
//private DcMotor HijsMotor;
float startHeading;
float relativeHeading;
/*
* IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which
* 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function.
* A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer
* web site at https://developer.vuforia.com/license-manager.
*
* Vuforia license keys are always 380 characters long, and look as if they contain mostly
* random data. As an example, here is a example of a fragment of a valid key:
* ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
* Once you've obtained a license key, copy the string from the Vuforia web site
* and paste it in to your code on the next line, between the double quotes.
*/
private static final String VUFORIA_KEY = "AfjFORf/////AAABmdp8TdE6Nkuqs+jlHLz05V0LetUXImgc6W92YLIchdsfSuMAtrfYRSeeVYC0dBEgnqdEg16/6KMZcJ8yA55f9h+m01rF5tmJZIe+A//Wv2CcrjRBZ4IbSDFNwzUi23aMJTETtEJ7bpbOul6O1qyhCMVC8T0FLZc7HJJUjkMhZxaCm46Kfpzw2z9yfaU+cbRAO6AIe83UJh5km2Gom3d562hIZekNhaZsbDz3InjVx80/mOhqKOp0FyoZ8SiwBTRftydNo1tkaZhrOpGtgbIURMW+hhyu7TXnM75gOMHBuG5idIUIqZCWZxfSEITmadeGvkWwW7kONeD/VXYLdHh+Dt9zuMnzmGkG1gPhNeQ/JvD+";
/**
* {@link #vuforia} is the variable we will use to store our instance of the Vuforia
* localization engine.
*/
private VuforiaLocalizer vuforia;
/**
* {@link #tfod} is the variable we will use to store our instance of the Tensor Flow Object
* Detection engine.
*/
private TFObjectDetector tfod;
@Override
public void runOpMode() {
//IMU parameter setup
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode
parameters.loggingEnabled = true;
parameters.loggingTag = "IMU";
parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator();
double StartTimeDetection = 0;
//IMU start
imu = hardwareMap.get(BNO055IMU.class, "imu");
imu.initialize(parameters);
startHeading = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.addData("IMU status",imu.isGyroCalibrated());
//starting logging
try {
logUtils.StartLogging(3);
} catch (Exception e){
}
// The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that
// first.
Orientation a = imu.getAngularOrientation();
telemetry.addData("StartHeading", startHeading);
MotorBackLeft = hardwareMap.dcMotor.get("MotorBackLeft");
MotorBackRight = hardwareMap.dcMotor.get("MotorBackRight");
MotorFrontLeft = hardwareMap.dcMotor.get("MotorFrontLeft");
MotorFrontRight = hardwareMap.dcMotor.get("MotorFrontRight");
BlockBoxServo = hardwareMap.servo.get("BlockBoxServo");
Runstate = 0;
HijsMotor = hardwareMap.dcMotor.get("LiftMotor");
HijsMotor.setPower(-.5);
frontDistance = hardwareMap.get(Rev2mDistanceSensor.class, "front");
bottomDistance = hardwareMap.get(Rev2mDistanceSensor.class, "bottom");
/** Wait for the game to begin */
telemetry.addData(">", "Press Play to start tracking");
telemetry.update();
waitForStart();
if (opModeIsActive()) {
while (opModeIsActive()) {
logUtils.Log(logUtils.logType.normal,String.valueOf( Runstate), 3);
relativeHeading = startHeading + imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.update();
switch (Runstate){
case 0:
telemetry.addData("Status", "Hanging");
HijsMotor.setPower(0);
if(bottomDistance.getDistance(DistanceUnit.CM) > 17){
sleep(50);
continue;
}
Runstate = 10;
break;
case 10:
telemetry.addData("Status", "Dropping");
sleep(200);
MoveSideWays(-1);
sleep(150);
MoveSideWays(0);
HijsMotor.setPower(-1);
sleep(600);
HijsMotor.setPower(0);
MoveSideWays(1);
sleep(150);
MoveSideWays(0);
Runstate = 15;
break;
case 15:
MoveForward(1f);
sleep(5000);
MoveForward(0);
logUtils.StopLogging(3);
stop();
}
}
}
}
/**
* Initialize the Vuforia localization engine.
*/
/**
* for driving sideways, also called strafing
* @param direction 1=right, -1=left
*/
public void MoveSideWays(int direction) {
MotorBackLeft.setPower(direction);
MotorFrontLeft.setPower(-direction);
MotorBackRight.setPower(-direction);
MotorFrontRight.setPower(direction);
}
/**
* For moving the robot forwards/backwards
* @param speed the robots speed, on a scale from -1 to 1 (negative for backwards, positive for forwards
*/
public void MoveForward(float speed){
MotorFrontRight.setPower(-speed*.5);
MotorBackRight.setPower(-speed*.5 );
MotorFrontLeft.setPower(speed*.5 );
MotorBackLeft.setPower(speed*.5 );
}
/**
* For turning the robot whilst staying in place
* @param speed the speed the robot turns, 1 for clockwise
*/
public void Turn(float speed) {
MotorFrontRight.setPower(speed * .5);
MotorBackRight.setPower(speed * .5);
MotorFrontLeft.setPower(speed * .5);
MotorBackLeft.setPower(speed * .5);
}
/**
* used for checking the camera view with Tensorflow
*/
}
| Guusje2/FTCUnits-SkyStone | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/CraterSide.java | 3,502 | //TODO: meten startwaarde, gemiddelde pakken vnan een aantal metingen | line_comment | nl | /* Copyright (c) 2018 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator;
import com.qualcomm.hardware.rev.Rev2mDistanceSensor;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.navigation.Acceleration;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.tfod.Recognition;
import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector;
import java.util.List;
/**
* This 2018-2019 OpMode illustrates the basics of using the TensorFlow Object Detection API to
* determine the position of the gold and silver minerals.
*
* Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list.
*
* IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as
* is explained below.
*/
@Disabled
@Autonomous(name = "Crater Side", group = "Concept")
public class CraterSide extends LinearOpMode {
private enum mineralPosEnum {none,left,center,right};
private mineralPosEnum mineralPos;
public int Runstate = 0;
private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite";
private static final String LABEL_GOLD_MINERAL = "Gold Mineral";
private static final String LABEL_SILVER_MINERAL = "Silver Mineral";
private DcMotor MotorFrontLeft;
private DcMotor MotorBackLeft;
private DcMotor MotorFrontRight;
private DcMotor MotorBackRight;
private DcMotor HijsMotor;
private Servo BlockBoxServo;
private Rev2mDistanceSensor frontDistance;
private Rev2mDistanceSensor bottomDistance;
private float LandedDistance = 15.5f; //TODO: meten<SUF>
private float heading;
private BNO055IMU imu;
Acceleration gravity;
//private DcMotor HijsMotor;
float startHeading;
float relativeHeading;
/*
* IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which
* 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function.
* A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer
* web site at https://developer.vuforia.com/license-manager.
*
* Vuforia license keys are always 380 characters long, and look as if they contain mostly
* random data. As an example, here is a example of a fragment of a valid key:
* ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
* Once you've obtained a license key, copy the string from the Vuforia web site
* and paste it in to your code on the next line, between the double quotes.
*/
private static final String VUFORIA_KEY = "AfjFORf/////AAABmdp8TdE6Nkuqs+jlHLz05V0LetUXImgc6W92YLIchdsfSuMAtrfYRSeeVYC0dBEgnqdEg16/6KMZcJ8yA55f9h+m01rF5tmJZIe+A//Wv2CcrjRBZ4IbSDFNwzUi23aMJTETtEJ7bpbOul6O1qyhCMVC8T0FLZc7HJJUjkMhZxaCm46Kfpzw2z9yfaU+cbRAO6AIe83UJh5km2Gom3d562hIZekNhaZsbDz3InjVx80/mOhqKOp0FyoZ8SiwBTRftydNo1tkaZhrOpGtgbIURMW+hhyu7TXnM75gOMHBuG5idIUIqZCWZxfSEITmadeGvkWwW7kONeD/VXYLdHh+Dt9zuMnzmGkG1gPhNeQ/JvD+";
/**
* {@link #vuforia} is the variable we will use to store our instance of the Vuforia
* localization engine.
*/
private VuforiaLocalizer vuforia;
/**
* {@link #tfod} is the variable we will use to store our instance of the Tensor Flow Object
* Detection engine.
*/
private TFObjectDetector tfod;
@Override
public void runOpMode() {
//IMU parameter setup
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode
parameters.loggingEnabled = true;
parameters.loggingTag = "IMU";
parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator();
double StartTimeDetection = 0;
//IMU start
imu = hardwareMap.get(BNO055IMU.class, "imu");
imu.initialize(parameters);
startHeading = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.addData("IMU status",imu.isGyroCalibrated());
//starting logging
try {
logUtils.StartLogging(3);
} catch (Exception e){
}
// The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that
// first.
Orientation a = imu.getAngularOrientation();
telemetry.addData("StartHeading", startHeading);
MotorBackLeft = hardwareMap.dcMotor.get("MotorBackLeft");
MotorBackRight = hardwareMap.dcMotor.get("MotorBackRight");
MotorFrontLeft = hardwareMap.dcMotor.get("MotorFrontLeft");
MotorFrontRight = hardwareMap.dcMotor.get("MotorFrontRight");
BlockBoxServo = hardwareMap.servo.get("BlockBoxServo");
Runstate = 0;
HijsMotor = hardwareMap.dcMotor.get("LiftMotor");
HijsMotor.setPower(-.5);
frontDistance = hardwareMap.get(Rev2mDistanceSensor.class, "front");
bottomDistance = hardwareMap.get(Rev2mDistanceSensor.class, "bottom");
/** Wait for the game to begin */
telemetry.addData(">", "Press Play to start tracking");
telemetry.update();
waitForStart();
if (opModeIsActive()) {
while (opModeIsActive()) {
logUtils.Log(logUtils.logType.normal,String.valueOf( Runstate), 3);
relativeHeading = startHeading + imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.update();
switch (Runstate){
case 0:
telemetry.addData("Status", "Hanging");
HijsMotor.setPower(0);
if(bottomDistance.getDistance(DistanceUnit.CM) > 17){
sleep(50);
continue;
}
Runstate = 10;
break;
case 10:
telemetry.addData("Status", "Dropping");
sleep(200);
MoveSideWays(-1);
sleep(150);
MoveSideWays(0);
HijsMotor.setPower(-1);
sleep(600);
HijsMotor.setPower(0);
MoveSideWays(1);
sleep(150);
MoveSideWays(0);
Runstate = 15;
break;
case 15:
MoveForward(1f);
sleep(5000);
MoveForward(0);
logUtils.StopLogging(3);
stop();
}
}
}
}
/**
* Initialize the Vuforia localization engine.
*/
/**
* for driving sideways, also called strafing
* @param direction 1=right, -1=left
*/
public void MoveSideWays(int direction) {
MotorBackLeft.setPower(direction);
MotorFrontLeft.setPower(-direction);
MotorBackRight.setPower(-direction);
MotorFrontRight.setPower(direction);
}
/**
* For moving the robot forwards/backwards
* @param speed the robots speed, on a scale from -1 to 1 (negative for backwards, positive for forwards
*/
public void MoveForward(float speed){
MotorFrontRight.setPower(-speed*.5);
MotorBackRight.setPower(-speed*.5 );
MotorFrontLeft.setPower(speed*.5 );
MotorBackLeft.setPower(speed*.5 );
}
/**
* For turning the robot whilst staying in place
* @param speed the speed the robot turns, 1 for clockwise
*/
public void Turn(float speed) {
MotorFrontRight.setPower(speed * .5);
MotorBackRight.setPower(speed * .5);
MotorFrontLeft.setPower(speed * .5);
MotorBackLeft.setPower(speed * .5);
}
/**
* used for checking the camera view with Tensorflow
*/
}
| False | 2,637 | 21 | 2,911 | 24 | 2,946 | 19 | 2,911 | 24 | 3,596 | 21 | false | false | false | false | false | true |
1,752 | 10815_0 | package domain;
import java.util.ArrayList;
public class BinaryMinHeap<E extends Comparable<E>> {
private ArrayList<E> values;
private boolean isEmpty() {
return values == null || values.size() == 0;
}
public void print() {
if (this.isEmpty())
System.out.println("De heap is leeg");
else
System.out.println(values);
}
public E getMin() {
if (this.isEmpty())
throw new IllegalStateException("Kan niet zoeken in een lege heap");
//TO DO zie oefening 3
return null;
}
public boolean addValue(E value) {
// geen null toevoegen aan de heap
if (value == null) throw new IllegalArgumentException();
// indien de heap leeg is: eerst initialiseren
if (this.isEmpty())
values = new ArrayList<E>();
values.add(value);//achteraan toevoegen
this.bubbleUp();//bubbleUp vanaf de laatste zie slides theorie
return true;
}
private void bubbleUp() {
//TO DO : oefening 4
}
public E removeSmallest() {
if (this.isEmpty())
throw new IllegalStateException("Kan niets verwijderen uit een lege boom");
E res = this.getMin();// res bevat de kleinste = eerste element van de lijst
this.values.set(0, this.values.get(this.values.size() - 1));// verwissel eerste met de laatste
this.values.remove(this.values.size() - 1); // verwijder de laatste
this.bubbleDown(); // bubble down van eerste naar beneden zie theorie
return res;
}
private void bubbleDown() {
// TODO zie oefening 5
}
public ArrayList<E> getPath(E value) {
// TODO zie oefening 6;
return null;
}
}
| TomEversdijk/Bomen_en_grafen_oefeningen | week05_Heap/src/domain/BinaryMinHeap.java | 498 | //TO DO zie oefening 3 | line_comment | nl | package domain;
import java.util.ArrayList;
public class BinaryMinHeap<E extends Comparable<E>> {
private ArrayList<E> values;
private boolean isEmpty() {
return values == null || values.size() == 0;
}
public void print() {
if (this.isEmpty())
System.out.println("De heap is leeg");
else
System.out.println(values);
}
public E getMin() {
if (this.isEmpty())
throw new IllegalStateException("Kan niet zoeken in een lege heap");
//TO DO<SUF>
return null;
}
public boolean addValue(E value) {
// geen null toevoegen aan de heap
if (value == null) throw new IllegalArgumentException();
// indien de heap leeg is: eerst initialiseren
if (this.isEmpty())
values = new ArrayList<E>();
values.add(value);//achteraan toevoegen
this.bubbleUp();//bubbleUp vanaf de laatste zie slides theorie
return true;
}
private void bubbleUp() {
//TO DO : oefening 4
}
public E removeSmallest() {
if (this.isEmpty())
throw new IllegalStateException("Kan niets verwijderen uit een lege boom");
E res = this.getMin();// res bevat de kleinste = eerste element van de lijst
this.values.set(0, this.values.get(this.values.size() - 1));// verwissel eerste met de laatste
this.values.remove(this.values.size() - 1); // verwijder de laatste
this.bubbleDown(); // bubble down van eerste naar beneden zie theorie
return res;
}
private void bubbleDown() {
// TODO zie oefening 5
}
public ArrayList<E> getPath(E value) {
// TODO zie oefening 6;
return null;
}
}
| True | 414 | 9 | 468 | 10 | 463 | 8 | 468 | 10 | 522 | 9 | false | false | false | false | false | true |
1,596 | 41419_0 | package simonjang.androidmeting;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements Introduction.OnFragmentInteractionListener {
SharedPreferences prefs = null;
@BindView(R.id.collapsingToolbar)
CollapsingToolbarLayout toolbarLayout;
@BindView(R.id.appBar)
AppBarLayout appBar;
android.support.v4.app.FragmentManager fm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences("simonjang.androidmeting", MODE_PRIVATE);
if(prefs.getBoolean("dataInserted", true)) {
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fm = getSupportFragmentManager();
setupWelcome();
}
else {
startOverview();
}
}
private void setupWelcome() {
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
toolbarLayout.setTitle("Meting Applicatie");
toolbarLayout.setCollapsedTitleTextColor(Color.BLACK);
isShow = true;
} else if(isShow) {
toolbarLayout.setTitle("");
isShow = false;
}
}
});
}
private void startOverview() {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
@Override
public void onFragmentInteraction(Uri uri) {
// Moet deze methode implementeren zodat Fragments kunnen gebruikt worden
// Je kan een Activty ook laten ervan van FragmentActivity
}
/*
XML-methode voor fragment toe te voegen werkt hier beter
Fragment in deze activity was eerder een probeersel
private void startIntroduction() {
android.support.v4.app.FragmentTransaction fmt = fm.beginTransaction();
fmt.add(R.id.intro_container, new Introduction());
fmt.commit();
}
*/
}
| SimonJang/MetingAndroid | app/src/main/java/simonjang/androidmeting/MainActivity.java | 781 | // Moet deze methode implementeren zodat Fragments kunnen gebruikt worden | line_comment | nl | package simonjang.androidmeting;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements Introduction.OnFragmentInteractionListener {
SharedPreferences prefs = null;
@BindView(R.id.collapsingToolbar)
CollapsingToolbarLayout toolbarLayout;
@BindView(R.id.appBar)
AppBarLayout appBar;
android.support.v4.app.FragmentManager fm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences("simonjang.androidmeting", MODE_PRIVATE);
if(prefs.getBoolean("dataInserted", true)) {
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fm = getSupportFragmentManager();
setupWelcome();
}
else {
startOverview();
}
}
private void setupWelcome() {
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
toolbarLayout.setTitle("Meting Applicatie");
toolbarLayout.setCollapsedTitleTextColor(Color.BLACK);
isShow = true;
} else if(isShow) {
toolbarLayout.setTitle("");
isShow = false;
}
}
});
}
private void startOverview() {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
@Override
public void onFragmentInteraction(Uri uri) {
// Moet deze<SUF>
// Je kan een Activty ook laten ervan van FragmentActivity
}
/*
XML-methode voor fragment toe te voegen werkt hier beter
Fragment in deze activity was eerder een probeersel
private void startIntroduction() {
android.support.v4.app.FragmentTransaction fmt = fm.beginTransaction();
fmt.add(R.id.intro_container, new Introduction());
fmt.commit();
}
*/
}
| False | 531 | 17 | 648 | 18 | 668 | 12 | 648 | 18 | 779 | 19 | false | false | false | false | false | true |
1,680 | 8380_0 | /*
* CBM interface
* Dit document beschrijft de interface van CBM die ten behoeve van Melvin beschikbaar wordt gesteld. . </br></br> De API moet worden uitgevraagd met een token. De token kan met een gebruikersnaam en wachtwoord verkregen worden. De token is tijdelijk geldig, daarna kan een nieuwe token opgevraagd worden. </br></br> De Geo-inputparameters moeten matchen op de door CBM gebruikte OSM-versie.
*
* OpenAPI spec version: 0.1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client;
import java.io.IOException;
import java.util.Map;
import java.util.List;
/**
* Callback for asynchronous API call.
*
* @param <T> The return type
*/
public interface ApiCallback<T> {
/**
* This is called when the API call fails.
*
* @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null
*/
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API call succeeded.
*
* @param result The result deserialized from response
* @param statusCode Status code of the response
* @param responseHeaders Headers of the response
*/
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API upload processing.
*
* @param bytesWritten bytes Written
* @param contentLength content length of request body
* @param done write end
*/
void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/**
* This is called when the API downlond processing.
*
* @param bytesRead bytes Read
* @param contentLength content lenngth of the response
* @param done Read end
*/
void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}
| TOMP-WG/TOMP-REF | tomp_meta/src/main/java/io/swagger/client/ApiCallback.java | 580 | /*
* CBM interface
* Dit document beschrijft de interface van CBM die ten behoeve van Melvin beschikbaar wordt gesteld. . </br></br> De API moet worden uitgevraagd met een token. De token kan met een gebruikersnaam en wachtwoord verkregen worden. De token is tijdelijk geldig, daarna kan een nieuwe token opgevraagd worden. </br></br> De Geo-inputparameters moeten matchen op de door CBM gebruikte OSM-versie.
*
* OpenAPI spec version: 0.1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/ | block_comment | nl | /*
* CBM interface
<SUF>*/
package io.swagger.client;
import java.io.IOException;
import java.util.Map;
import java.util.List;
/**
* Callback for asynchronous API call.
*
* @param <T> The return type
*/
public interface ApiCallback<T> {
/**
* This is called when the API call fails.
*
* @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null
*/
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API call succeeded.
*
* @param result The result deserialized from response
* @param statusCode Status code of the response
* @param responseHeaders Headers of the response
*/
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API upload processing.
*
* @param bytesWritten bytes Written
* @param contentLength content length of request body
* @param done write end
*/
void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/**
* This is called when the API downlond processing.
*
* @param bytesRead bytes Read
* @param contentLength content lenngth of the response
* @param done Read end
*/
void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}
| True | 499 | 171 | 542 | 192 | 541 | 164 | 542 | 192 | 596 | 195 | false | false | false | false | false | true |
4,689 | 22086_6 | import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String[] args) {
//Initialiseer een nieuwe JFrame en configureer de basics,
//dus size en de ON_CLOSE operation.
JFrame frame = new JFrame("Workshop frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Aanmaak van drie JPanels
JPanel flowLayoutPanel = new JPanel();
JPanel boxLayoutPanel = new JPanel();
JPanel gridLayoutPanel = new JPanel();
//Zet voor iedere panel een aparte layout manager;
//FlowLayout voor links naar rechts, BoxLayout voor x-as of y-as, GridLayout voor raster.
//Let op dat sommige layout managers dus parameters mee moeten krijgen in hun constructors.
flowLayoutPanel.setLayout(new FlowLayout());
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
gridLayoutPanel.setLayout(new GridLayout(3, 2));
//Drie arrays van knoppen, 1 voor iedere panel.
JButton[] buttons1 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons2 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons3 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
//Knoppen toevoegen aan de panels.
for (JButton b : buttons1){
flowLayoutPanel.add(b);
}
for (JButton b : buttons2){
boxLayoutPanel.add(b);
}
for (JButton b : buttons3){
gridLayoutPanel.add(b);
}
//Maak een main panel aan om alle andere panels in onder te brengen, inclusief layout manager.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//Voeg de layout panels toe aan de main panel. Let op, volgorde maakt uit.
mainPanel.add(flowLayoutPanel);
mainPanel.add(boxLayoutPanel);
mainPanel.add(gridLayoutPanel);
//Voeg mainpanel toe aan de JFrame en maak de JFrame visible.
frame.add(mainPanel);
frame.setVisible(true);
}
} | wennhao/project3-4 | guiold_OUTDATED/gui.java | 765 | //Drie arrays van knoppen, 1 voor iedere panel. | line_comment | nl | import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String[] args) {
//Initialiseer een nieuwe JFrame en configureer de basics,
//dus size en de ON_CLOSE operation.
JFrame frame = new JFrame("Workshop frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Aanmaak van drie JPanels
JPanel flowLayoutPanel = new JPanel();
JPanel boxLayoutPanel = new JPanel();
JPanel gridLayoutPanel = new JPanel();
//Zet voor iedere panel een aparte layout manager;
//FlowLayout voor links naar rechts, BoxLayout voor x-as of y-as, GridLayout voor raster.
//Let op dat sommige layout managers dus parameters mee moeten krijgen in hun constructors.
flowLayoutPanel.setLayout(new FlowLayout());
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
gridLayoutPanel.setLayout(new GridLayout(3, 2));
//Drie arrays<SUF>
JButton[] buttons1 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons2 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons3 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
//Knoppen toevoegen aan de panels.
for (JButton b : buttons1){
flowLayoutPanel.add(b);
}
for (JButton b : buttons2){
boxLayoutPanel.add(b);
}
for (JButton b : buttons3){
gridLayoutPanel.add(b);
}
//Maak een main panel aan om alle andere panels in onder te brengen, inclusief layout manager.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//Voeg de layout panels toe aan de main panel. Let op, volgorde maakt uit.
mainPanel.add(flowLayoutPanel);
mainPanel.add(boxLayoutPanel);
mainPanel.add(gridLayoutPanel);
//Voeg mainpanel toe aan de JFrame en maak de JFrame visible.
frame.add(mainPanel);
frame.setVisible(true);
}
} | True | 572 | 16 | 636 | 17 | 666 | 14 | 636 | 17 | 778 | 17 | false | false | false | false | false | true |
1,426 | 128601_0 | public class main{
public static void main(String[] args) {
String halo;
main hewan = new main();
System.out.println(simpel());
hewan.kucing();
halo = "ciko";
hewan.anjing(halo);
}
//method dengan void
//itu maksudnya sebuah method yang bernilai hampa
//dalam pengembaliannya tidak betuh return
void kucing(){
String nama, makanan;
nama = "cerberus";
makanan = "whiskas";
System.out.println("Nama kucing saya "+nama);
System.out.println("Makanan kucing saya adalah "+makanan);
}
void anjing(String name){
System.out.println("Nama anjing saya adalah "+name);
}
//method biasa dengan return
static float simpel(){
return 10.0f;
}
} | RaenaldP/New-Java | Void method/main.java | 271 | //method dengan void | line_comment | nl | public class main{
public static void main(String[] args) {
String halo;
main hewan = new main();
System.out.println(simpel());
hewan.kucing();
halo = "ciko";
hewan.anjing(halo);
}
//method dengan<SUF>
//itu maksudnya sebuah method yang bernilai hampa
//dalam pengembaliannya tidak betuh return
void kucing(){
String nama, makanan;
nama = "cerberus";
makanan = "whiskas";
System.out.println("Nama kucing saya "+nama);
System.out.println("Makanan kucing saya adalah "+makanan);
}
void anjing(String name){
System.out.println("Nama anjing saya adalah "+name);
}
//method biasa dengan return
static float simpel(){
return 10.0f;
}
} | False | 199 | 4 | 255 | 4 | 218 | 4 | 255 | 4 | 295 | 5 | false | false | false | false | false | true |
3,485 | 179629_6 | /*
* Copyright (c) 2018 LingoChamp Inc.
*
* 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.liulishuo.filedownloader.util;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.liulishuo.filedownloader.DownloadTaskAdapter;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.StatusUtil;
import com.liulishuo.okdownload.core.Util;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The utils for FileDownloader.
*/
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public class FileDownloadUtils {
private static String defaultSaveRootPath;
private static final String TAG = "FileDownloadUtils";
private static final String FILEDOWNLOADER_PREFIX = "FileDownloader";
// note on https://tools.ietf.org/html/rfc5987
private static final Pattern CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN =
Pattern.compile("attachment;\\s*filename\\*\\s*=\\s*\"*([^\"]*)'\\S*'([^\"]*)\"*");
// note on http://www.ietf.org/rfc/rfc1806.txt
private static final Pattern CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN =
Pattern.compile("attachment;\\s*filename\\s*=\\s*\"*([^\"\\n]*)\"*");
public static String getDefaultSaveRootPath() {
if (!TextUtils.isEmpty(defaultSaveRootPath)) {
return defaultSaveRootPath;
}
if (FileDownloadHelper.getAppContext().getExternalCacheDir() == null) {
return Environment.getDownloadCacheDirectory().getAbsolutePath();
} else {
//noinspection ConstantConditions
return FileDownloadHelper.getAppContext().getExternalCacheDir().getAbsolutePath();
}
}
/**
* The path is used as the default directory in the case of the task without set path.
*
* @param path default root path for save download file.
* @see com.liulishuo.filedownloader.BaseDownloadTask#setPath(String, boolean)
*/
public static void setDefaultSaveRootPath(final String path) {
defaultSaveRootPath = path;
}
public static String getDefaultSaveFilePath(final String url) {
return generateFilePath(getDefaultSaveRootPath(), generateFileName(url));
}
public static String generateFileName(final String url) {
return md5(url);
}
public static String generateFilePath(String directory, String filename) {
if (filename == null) {
throw new IllegalStateException("can't generate real path, the file name is null");
}
if (directory == null) {
throw new IllegalStateException("can't generate real path, the directory is null");
}
return String.format("%s%s%s", directory, File.separator, filename);
}
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append(0);
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
@Nullable
public static DownloadTaskAdapter findDownloadTaskAdapter(DownloadTask downloadTask) {
if (downloadTask == null) {
Util.w(TAG, "download task is null when find DownloadTaskAdapter");
return null;
}
final Object o = downloadTask.getTag(DownloadTaskAdapter.KEY_TASK_ADAPTER);
if (o == null) {
Util.w(TAG, "no tag with DownloadTaskAdapter.KEY_TASK_ADAPTER");
return null;
}
if (o instanceof DownloadTaskAdapter) {
return (DownloadTaskAdapter) o;
}
Util.w(TAG, "download task's tag is not DownloadTaskAdapter");
return null;
}
public static byte convertDownloadStatus(final StatusUtil.Status status) {
switch (status) {
case COMPLETED:
return FileDownloadStatus.completed;
case IDLE:
return FileDownloadStatus.paused;
case PENDING:
return FileDownloadStatus.pending;
case RUNNING:
return FileDownloadStatus.progress;
default:
return FileDownloadStatus.INVALID_STATUS;
}
}
/**
* Temp file pattern is deprecated in OkDownload.
*/
@Deprecated
public static String getTempPath(final String targetPath) {
return String.format(Locale.ENGLISH, "%s.temp", targetPath);
}
@Deprecated
public static String getThreadPoolName(String name) {
return FILEDOWNLOADER_PREFIX + "-" + name;
}
@Deprecated
public static void setMinProgressStep(int minProgressStep) throws IllegalAccessException {
// do nothing
}
@Deprecated
public static void setMinProgressTime(long minProgressTime) throws IllegalAccessException {
// do nothing
}
@Deprecated
public static int getMinProgressStep() {
return 0;
}
@Deprecated
public static long getMinProgressTime() {
return 0;
}
@Deprecated
public static boolean isFilenameValid(String filename) {
return true;
}
@Deprecated
public static int generateId(final String url, final String path) {
return new DownloadTask.Builder(url, new File(path)).build().getId();
}
@Deprecated
public static int generateId(final String url, final String path,
final boolean pathAsDirectory) {
if (pathAsDirectory) {
return new DownloadTask.Builder(url, path, null).build().getId();
}
return generateId(url, path);
}
public static String getStack() {
return getStack(true);
}
public static String getStack(final boolean printLine) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
return getStack(stackTrace, printLine);
}
public static String getStack(final StackTraceElement[] stackTrace, final boolean printLine) {
if ((stackTrace == null) || (stackTrace.length < 4)) {
return "";
}
StringBuilder t = new StringBuilder();
for (int i = 3; i < stackTrace.length; i++) {
if (!stackTrace[i].getClassName().contains("com.liulishuo.filedownloader")) {
continue;
}
t.append('[');
t.append(stackTrace[i].getClassName()
.substring("com.liulishuo.filedownloader".length()));
t.append(':');
t.append(stackTrace[i].getMethodName());
if (printLine) {
t.append('(').append(stackTrace[i].getLineNumber()).append(")]");
} else {
t.append(']');
}
}
return t.toString();
}
@Deprecated
public static boolean isDownloaderProcess(final Context context) {
return false;
}
public static String[] convertHeaderString(final String nameAndValuesString) {
final String[] lineString = nameAndValuesString.split("\n");
final String[] namesAndValues = new String[lineString.length * 2];
for (int i = 0; i < lineString.length; i++) {
final String[] nameAndValue = lineString[i].split(": ");
/**
* @see Headers#toString()
* @see Headers#name(int)
* @see Headers#value(int)
*/
namesAndValues[i * 2] = nameAndValue[0];
namesAndValues[i * 2 + 1] = nameAndValue[1];
}
return namesAndValues;
}
public static long getFreeSpaceBytes(final String path) {
long freeSpaceBytes;
final StatFs statFs = new StatFs(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
freeSpaceBytes = statFs.getAvailableBytes();
} else {
//noinspection deprecation
freeSpaceBytes = statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
return freeSpaceBytes;
}
public static String formatString(final String msg, Object... args) {
return String.format(Locale.ENGLISH, msg, args);
}
@Deprecated
public static long parseContentRangeFoInstanceLength(String contentRange) {
return -1;
}
/**
* The same to com.android.providers.downloads.Helpers#parseContentDisposition.
* </p>
* Parse the Content-Disposition HTTP Header. The format of the header
* is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
* This header provides a filename for content that is going to be
* downloaded to the file system. We only support the attachment type.
*/
public static String parseContentDisposition(String contentDisposition) {
if (contentDisposition == null) {
return null;
}
try {
Matcher m = CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN.matcher(contentDisposition);
if (m.find()) {
String charset = m.group(1);
String encodeFileName = m.group(2);
return URLDecoder.decode(encodeFileName, charset);
}
m = CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN.matcher(contentDisposition);
if (m.find()) {
return m.group(1);
}
} catch (IllegalStateException | UnsupportedEncodingException ignore) {
// This function is defined as returning null when it can't parse the header
}
return null;
}
/**
* @param path If {@code pathAsDirectory} is true, the {@code path} would be the
* absolute directory to settle down the file;
* If {@code pathAsDirectory} is false, the {@code path} would be the
* absolute file path.
* @param pathAsDirectory whether the {@code path} is a directory.
* @param filename the file's name.
* @return the absolute path of the file. If can't find by params, will return {@code null}.
*/
public static String getTargetFilePath(String path, boolean pathAsDirectory, String filename) {
if (path == null) {
return null;
}
if (pathAsDirectory) {
if (filename == null) {
return null;
}
return FileDownloadUtils.generateFilePath(path, filename);
} else {
return path;
}
}
/**
* The same to {@link File#getParent()}, for non-creating a file object.
*
* @return this file's parent pathname or {@code null}.
*/
public static String getParent(final String path) {
int length = path.length(), firstInPath = 0;
if (File.separatorChar == '\\' && length > 2 && path.charAt(1) == ':') {
firstInPath = 2;
}
int index = path.lastIndexOf(File.separatorChar);
if (index == -1 && firstInPath > 0) {
index = 2;
}
if (index == -1 || path.charAt(length - 1) == File.separatorChar) {
return null;
}
if (path.indexOf(File.separatorChar) == index
&& path.charAt(firstInPath) == File.separatorChar) {
return path.substring(0, index + 1);
}
return path.substring(0, index);
}
@Deprecated
public static boolean isNetworkNotOnWifiType() {
return false;
}
public static boolean checkPermission(String permission) {
final int perm = FileDownloadHelper.getAppContext()
.checkCallingOrSelfPermission(permission);
return perm == PackageManager.PERMISSION_GRANTED;
}
public static void deleteTaskFiles(String targetFilepath, String tempFilePath) {
deleteTempFile(tempFilePath);
deleteTargetFile(targetFilepath);
}
public static void deleteTempFile(String tempFilePath) {
if (tempFilePath != null) {
final File tempFile = new File(tempFilePath);
if (tempFile.exists()) {
//noinspection ResultOfMethodCallIgnored
tempFile.delete();
}
}
}
public static void deleteTargetFile(String targetFilePath) {
if (targetFilePath != null) {
final File targetFile = new File(targetFilePath);
if (targetFile.exists()) {
//noinspection ResultOfMethodCallIgnored
targetFile.delete();
}
}
}
} | lingochamp/okdownload | okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/util/FileDownloadUtils.java | 3,798 | /**
* @see Headers#toString()
* @see Headers#name(int)
* @see Headers#value(int)
*/ | block_comment | nl | /*
* Copyright (c) 2018 LingoChamp Inc.
*
* 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.liulishuo.filedownloader.util;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.liulishuo.filedownloader.DownloadTaskAdapter;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.StatusUtil;
import com.liulishuo.okdownload.core.Util;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The utils for FileDownloader.
*/
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public class FileDownloadUtils {
private static String defaultSaveRootPath;
private static final String TAG = "FileDownloadUtils";
private static final String FILEDOWNLOADER_PREFIX = "FileDownloader";
// note on https://tools.ietf.org/html/rfc5987
private static final Pattern CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN =
Pattern.compile("attachment;\\s*filename\\*\\s*=\\s*\"*([^\"]*)'\\S*'([^\"]*)\"*");
// note on http://www.ietf.org/rfc/rfc1806.txt
private static final Pattern CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN =
Pattern.compile("attachment;\\s*filename\\s*=\\s*\"*([^\"\\n]*)\"*");
public static String getDefaultSaveRootPath() {
if (!TextUtils.isEmpty(defaultSaveRootPath)) {
return defaultSaveRootPath;
}
if (FileDownloadHelper.getAppContext().getExternalCacheDir() == null) {
return Environment.getDownloadCacheDirectory().getAbsolutePath();
} else {
//noinspection ConstantConditions
return FileDownloadHelper.getAppContext().getExternalCacheDir().getAbsolutePath();
}
}
/**
* The path is used as the default directory in the case of the task without set path.
*
* @param path default root path for save download file.
* @see com.liulishuo.filedownloader.BaseDownloadTask#setPath(String, boolean)
*/
public static void setDefaultSaveRootPath(final String path) {
defaultSaveRootPath = path;
}
public static String getDefaultSaveFilePath(final String url) {
return generateFilePath(getDefaultSaveRootPath(), generateFileName(url));
}
public static String generateFileName(final String url) {
return md5(url);
}
public static String generateFilePath(String directory, String filename) {
if (filename == null) {
throw new IllegalStateException("can't generate real path, the file name is null");
}
if (directory == null) {
throw new IllegalStateException("can't generate real path, the directory is null");
}
return String.format("%s%s%s", directory, File.separator, filename);
}
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append(0);
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
@Nullable
public static DownloadTaskAdapter findDownloadTaskAdapter(DownloadTask downloadTask) {
if (downloadTask == null) {
Util.w(TAG, "download task is null when find DownloadTaskAdapter");
return null;
}
final Object o = downloadTask.getTag(DownloadTaskAdapter.KEY_TASK_ADAPTER);
if (o == null) {
Util.w(TAG, "no tag with DownloadTaskAdapter.KEY_TASK_ADAPTER");
return null;
}
if (o instanceof DownloadTaskAdapter) {
return (DownloadTaskAdapter) o;
}
Util.w(TAG, "download task's tag is not DownloadTaskAdapter");
return null;
}
public static byte convertDownloadStatus(final StatusUtil.Status status) {
switch (status) {
case COMPLETED:
return FileDownloadStatus.completed;
case IDLE:
return FileDownloadStatus.paused;
case PENDING:
return FileDownloadStatus.pending;
case RUNNING:
return FileDownloadStatus.progress;
default:
return FileDownloadStatus.INVALID_STATUS;
}
}
/**
* Temp file pattern is deprecated in OkDownload.
*/
@Deprecated
public static String getTempPath(final String targetPath) {
return String.format(Locale.ENGLISH, "%s.temp", targetPath);
}
@Deprecated
public static String getThreadPoolName(String name) {
return FILEDOWNLOADER_PREFIX + "-" + name;
}
@Deprecated
public static void setMinProgressStep(int minProgressStep) throws IllegalAccessException {
// do nothing
}
@Deprecated
public static void setMinProgressTime(long minProgressTime) throws IllegalAccessException {
// do nothing
}
@Deprecated
public static int getMinProgressStep() {
return 0;
}
@Deprecated
public static long getMinProgressTime() {
return 0;
}
@Deprecated
public static boolean isFilenameValid(String filename) {
return true;
}
@Deprecated
public static int generateId(final String url, final String path) {
return new DownloadTask.Builder(url, new File(path)).build().getId();
}
@Deprecated
public static int generateId(final String url, final String path,
final boolean pathAsDirectory) {
if (pathAsDirectory) {
return new DownloadTask.Builder(url, path, null).build().getId();
}
return generateId(url, path);
}
public static String getStack() {
return getStack(true);
}
public static String getStack(final boolean printLine) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
return getStack(stackTrace, printLine);
}
public static String getStack(final StackTraceElement[] stackTrace, final boolean printLine) {
if ((stackTrace == null) || (stackTrace.length < 4)) {
return "";
}
StringBuilder t = new StringBuilder();
for (int i = 3; i < stackTrace.length; i++) {
if (!stackTrace[i].getClassName().contains("com.liulishuo.filedownloader")) {
continue;
}
t.append('[');
t.append(stackTrace[i].getClassName()
.substring("com.liulishuo.filedownloader".length()));
t.append(':');
t.append(stackTrace[i].getMethodName());
if (printLine) {
t.append('(').append(stackTrace[i].getLineNumber()).append(")]");
} else {
t.append(']');
}
}
return t.toString();
}
@Deprecated
public static boolean isDownloaderProcess(final Context context) {
return false;
}
public static String[] convertHeaderString(final String nameAndValuesString) {
final String[] lineString = nameAndValuesString.split("\n");
final String[] namesAndValues = new String[lineString.length * 2];
for (int i = 0; i < lineString.length; i++) {
final String[] nameAndValue = lineString[i].split(": ");
/**
* @see Headers#toString()
<SUF>*/
namesAndValues[i * 2] = nameAndValue[0];
namesAndValues[i * 2 + 1] = nameAndValue[1];
}
return namesAndValues;
}
public static long getFreeSpaceBytes(final String path) {
long freeSpaceBytes;
final StatFs statFs = new StatFs(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
freeSpaceBytes = statFs.getAvailableBytes();
} else {
//noinspection deprecation
freeSpaceBytes = statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
return freeSpaceBytes;
}
public static String formatString(final String msg, Object... args) {
return String.format(Locale.ENGLISH, msg, args);
}
@Deprecated
public static long parseContentRangeFoInstanceLength(String contentRange) {
return -1;
}
/**
* The same to com.android.providers.downloads.Helpers#parseContentDisposition.
* </p>
* Parse the Content-Disposition HTTP Header. The format of the header
* is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
* This header provides a filename for content that is going to be
* downloaded to the file system. We only support the attachment type.
*/
public static String parseContentDisposition(String contentDisposition) {
if (contentDisposition == null) {
return null;
}
try {
Matcher m = CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN.matcher(contentDisposition);
if (m.find()) {
String charset = m.group(1);
String encodeFileName = m.group(2);
return URLDecoder.decode(encodeFileName, charset);
}
m = CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN.matcher(contentDisposition);
if (m.find()) {
return m.group(1);
}
} catch (IllegalStateException | UnsupportedEncodingException ignore) {
// This function is defined as returning null when it can't parse the header
}
return null;
}
/**
* @param path If {@code pathAsDirectory} is true, the {@code path} would be the
* absolute directory to settle down the file;
* If {@code pathAsDirectory} is false, the {@code path} would be the
* absolute file path.
* @param pathAsDirectory whether the {@code path} is a directory.
* @param filename the file's name.
* @return the absolute path of the file. If can't find by params, will return {@code null}.
*/
public static String getTargetFilePath(String path, boolean pathAsDirectory, String filename) {
if (path == null) {
return null;
}
if (pathAsDirectory) {
if (filename == null) {
return null;
}
return FileDownloadUtils.generateFilePath(path, filename);
} else {
return path;
}
}
/**
* The same to {@link File#getParent()}, for non-creating a file object.
*
* @return this file's parent pathname or {@code null}.
*/
public static String getParent(final String path) {
int length = path.length(), firstInPath = 0;
if (File.separatorChar == '\\' && length > 2 && path.charAt(1) == ':') {
firstInPath = 2;
}
int index = path.lastIndexOf(File.separatorChar);
if (index == -1 && firstInPath > 0) {
index = 2;
}
if (index == -1 || path.charAt(length - 1) == File.separatorChar) {
return null;
}
if (path.indexOf(File.separatorChar) == index
&& path.charAt(firstInPath) == File.separatorChar) {
return path.substring(0, index + 1);
}
return path.substring(0, index);
}
@Deprecated
public static boolean isNetworkNotOnWifiType() {
return false;
}
public static boolean checkPermission(String permission) {
final int perm = FileDownloadHelper.getAppContext()
.checkCallingOrSelfPermission(permission);
return perm == PackageManager.PERMISSION_GRANTED;
}
public static void deleteTaskFiles(String targetFilepath, String tempFilePath) {
deleteTempFile(tempFilePath);
deleteTargetFile(targetFilepath);
}
public static void deleteTempFile(String tempFilePath) {
if (tempFilePath != null) {
final File tempFile = new File(tempFilePath);
if (tempFile.exists()) {
//noinspection ResultOfMethodCallIgnored
tempFile.delete();
}
}
}
public static void deleteTargetFile(String targetFilePath) {
if (targetFilePath != null) {
final File targetFile = new File(targetFilePath);
if (targetFile.exists()) {
//noinspection ResultOfMethodCallIgnored
targetFile.delete();
}
}
}
} | False | 2,912 | 29 | 3,169 | 31 | 3,458 | 35 | 3,169 | 31 | 3,843 | 38 | false | false | false | false | false | true |